From 6eaa3826527707283b383c2004940023baa2825b Mon Sep 17 00:00:00 2001 From: larsevj Date: Thu, 29 Aug 2024 13:18:45 +0200 Subject: [PATCH 01/11] Remove unused helper script 'create_cmakelists.py' --- cmake/create_cmakelists.py | 85 -------------------------------------- 1 file changed, 85 deletions(-) delete mode 100755 cmake/create_cmakelists.py diff --git a/cmake/create_cmakelists.py b/cmake/create_cmakelists.py deleted file mode 100755 index 173331e6b..000000000 --- a/cmake/create_cmakelists.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python - -from os import listdir -from os.path import isfile, join, isdir, islink -import sys - - -def findFilesAndDirectories(directory): - all_files = listdir(directory) - files = [] - directories = [] - for f in all_files: - path = join(directory, f) - if isfile(path) and not f == "CMakeLists.txt" and not islink(path): - files.append(f) - if isdir(path): - directories.append(f) - - return sorted(files), sorted(directories) - - -def findRelativeModulePath(directory): - """@type directory: str""" - index = directory.rfind("python/") - index += len("python/") - return directory[index : len(directory)] - - -def createPythonSources(files, test_sources=False): - result = "" - - if len(files) > 0: - result = "set(%s\n" % ("PYTHON_SOURCES" if not test_sources else "TEST_SOURCES") - - files = [f for f in files if f.endswith(".py")] - - for f in files: - result += " " + str(f) + "\n" - - if len(files) > 0: - result += ")" - - return result - - -def addSubDirectories(directories): - result = "" - - for d in directories: - result += "add_subdirectory(" + str(d) + ")\n" - - return result - - -def addPythonPackage(relative_module_path, test_sources=False): - module_name = ".".join(relative_module_path.split("/")) - source_type = "PYTHON_SOURCES" if not test_sources else "TEST_SOURCES" - template = 'add_python_package("python.%s" ${PYTHON_INSTALL_PREFIX}/%s "${%s}" %s)' - - install = "False" if test_sources else "True" - - return template % (module_name, relative_module_path, source_type, install) - - -def addInclude(filename): - with open(filename, "r") as include_file: - content = include_file.read() - return content - - -files, directories = findFilesAndDirectories(sys.argv[1]) -module_path = findRelativeModulePath(sys.argv[1]) - -output_file = join(sys.argv[1], "CMakeLists.txt") -test_sources = module_path.startswith("tests") -with open(output_file, "w+") as text_file: - text_file.write(createPythonSources(files, test_sources=test_sources)) - text_file.write("\n\n") - text_file.write(addPythonPackage(module_path, test_sources=test_sources)) - text_file.write("\n\n") - text_file.write(addSubDirectories(directories)) - - if "local.cmake" in files: - text_file.write("\n\n") - text_file.write(addInclude(join(sys.argv[1], "local.cmake"))) From 399bb8af551759b530d40fc1ee9a8e427362324b Mon Sep 17 00:00:00 2001 From: larsevj Date: Mon, 26 Aug 2024 12:50:48 +0200 Subject: [PATCH 02/11] Use ruff for linting and formatting --- .github/workflows/style.yml | 13 +- pyproject.toml | 42 +++++ python/docs/examples/avg_pressure.py | 13 +- python/docs/examples/grid_info.py | 5 +- python/resdata/__init__.py | 8 +- python/resdata/geometry/cpolyline.py | 12 +- .../resdata/geometry/cpolyline_collection.py | 9 +- python/resdata/geometry/geo_region.py | 4 +- python/resdata/geometry/geometry_tools.py | 37 ++-- python/resdata/geometry/polyline.py | 12 +- python/resdata/geometry/surface.py | 9 +- python/resdata/gravimetry/__init__.py | 10 +- python/resdata/gravimetry/rd_subsidence.py | 10 +- python/resdata/grid/__init__.py | 14 +- python/resdata/grid/cell.py | 2 +- python/resdata/grid/faults/fault.py | 59 +++---- python/resdata/grid/faults/fault_block.py | 5 +- .../resdata/grid/faults/fault_block_layer.py | 6 +- python/resdata/grid/faults/fault_line.py | 14 +- python/resdata/grid/faults/fault_segments.py | 9 +- python/resdata/grid/faults/layer.py | 4 +- python/resdata/grid/rd_grid.py | 44 ++--- python/resdata/grid/rd_grid_generator.py | 2 +- python/resdata/grid/rd_region.py | 9 +- python/resdata/rd_util.py | 6 +- python/resdata/resfile/rd_3d_file.py | 9 +- python/resdata/resfile/rd_3dkw.py | 24 ++- python/resdata/resfile/rd_file.py | 18 +- python/resdata/resfile/rd_file_view.py | 10 +- python/resdata/resfile/rd_kw.py | 158 ++++++++---------- python/resdata/resfile/rd_restart_file.py | 6 +- python/resdata/rft/__init__.py | 4 +- python/resdata/rft/rd_rft.py | 6 +- python/resdata/rft/well_trajectory.py | 8 +- python/resdata/summary/__init__.py | 6 +- python/resdata/summary/rd_cmp.py | 13 +- python/resdata/summary/rd_npv.py | 11 +- python/resdata/summary/rd_smspec_node.py | 2 +- python/resdata/summary/rd_sum.py | 38 +++-- python/resdata/summary/rd_sum_vector.py | 4 + python/resdata/util/test/extended_testcase.py | 9 +- python/resdata/util/test/mock/rd_sum_mock.py | 3 +- python/resdata/util/test/path_context.py | 5 +- .../resdata/util/test/resdata_test_runner.py | 2 +- python/resdata/util/test/source_enumerator.py | 6 +- python/resdata/util/test/test_run.py | 2 +- python/resdata/util/util/__init__.py | 2 +- python/resdata/util/util/ctime.py | 3 +- python/resdata/util/util/lookup_table.py | 12 +- python/resdata/util/util/thread_pool.py | 14 +- python/resdata/util/util/time_vector.py | 6 +- python/resdata/util/util/vector_template.py | 32 ++-- python/resdata/util/util/version.py | 7 +- python/resdata/well/well_state.py | 5 +- python/tests/__init__.py | 11 +- python/tests/geometry_tests/test_surface.py | 6 +- python/tests/rd_tests/test_fault_blocks.py | 1 - python/tests/rd_tests/test_faults.py | 4 +- python/tests/rd_tests/test_fortio.py | 5 +- python/tests/rd_tests/test_geertsma.py | 28 ---- python/tests/rd_tests/test_grid.py | 2 +- python/tests/rd_tests/test_grid_equinor.py | 17 +- python/tests/rd_tests/test_grid_generator.py | 10 +- python/tests/rd_tests/test_npv.py | 7 +- python/tests/rd_tests/test_rd_cmp.py | 2 +- python/tests/rd_tests/test_rd_kw.py | 26 ++- python/tests/rd_tests/test_rd_sum.py | 6 +- python/tests/rd_tests/test_rd_type.py | 6 +- python/tests/rd_tests/test_rd_util.py | 2 +- python/tests/rd_tests/test_region_equinor.py | 2 +- python/tests/rd_tests/test_sum.py | 28 +--- python/tests/rd_tests/test_sum_equinor.py | 17 +- python/tests/test_bin.py | 2 +- python/tests/util_tests/test_path_context.py | 16 +- python/tests/util_tests/test_string_list.py | 2 +- python/tests/util_tests/test_thread_pool.py | 2 +- python/tests/util_tests/test_vectors.py | 9 +- python/tests/well_tests/test_rd_well.py | 2 +- setup.cfg | 5 - 79 files changed, 434 insertions(+), 567 deletions(-) delete mode 100644 setup.cfg diff --git a/.github/workflows/style.yml b/.github/workflows/style.yml index 0dbb6e269..cf52b2cea 100644 --- a/.github/workflows/style.yml +++ b/.github/workflows/style.yml @@ -13,7 +13,7 @@ jobs: - name: Install dependencies run: | - sudo pip install cmake-format black + sudo pip install cmake-format - name: Clang Format run: ./script/clang-format --check @@ -23,6 +23,13 @@ jobs: find . -name 'CMakeLists.txt' -o -name '*.cmake' > cmake-src xargs cmake-format --check < cmake-src - - name: Black + - name: Setup python + uses: actions/setup-python@v5 + with: + python-version: ["3.12"] + + - name: Run ruff run: | - black --check . + pip install ruff + ruff check + ruff format --check diff --git a/pyproject.toml b/pyproject.toml index 9abf16845..5e2560294 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,2 +1,44 @@ [build-system] requires = ["setuptools", "setuptools_scm", "wheel", "scikit-build", "cmake", "conan<2", "ninja"] + +[tool.ruff] +src = ["python"] +line-length = 88 +target-version = "py38" + +[tool.ruff.lint] +select = [ + "W", # pycodestyle + # "I", # isort ( Issues with circular imports and cwrap) + "B", # flake-8-bugbear + "SIM", # flake-8-simplify + "F", # pyflakes + "PL", # pylint + "NPY", # numpy specific rules + "C4", # flake8-comprehensions + "PD", # pandas-vet +] +ignore = ["PLW2901", # redefined-loop-name + "PLR2004", # magic-value-comparison + "PLR0915", # too-many-statements + "PLR0912", # too-many-branches + "PLR0911", # too-many-return-statements + "PLC2701", # import-private-name + "PLR6201", # literal-membership + "PLR0914", # too-many-locals + "PLR6301", # no-self-use + "PLW1641", # eq-without-hash + "PLR0904", # too-many-public-methods + "PLR1702", # too-many-nested-blocks + "PLW3201", # bad-dunder-method-name + "PD901", # pandas-df-variable-name + "C409", # unnecessary-literal-within-tuple-call + "PLC0414", # useless-import-alias + "F401", # unused-import + "F841", # unused-variable +] +[tool.ruff.lint.extend-per-file-ignores] +"python/tests/util_tests/test_ctime.py" = ["PLR0124", "B015"] + +[tool.ruff.lint.pylint] +max-args = 15 diff --git a/python/docs/examples/avg_pressure.py b/python/docs/examples/avg_pressure.py index 7a0131dff..db97178a7 100755 --- a/python/docs/examples/avg_pressure.py +++ b/python/docs/examples/avg_pressure.py @@ -2,6 +2,7 @@ import sys import matplotlib.pyplot as plt + from resdata.grid import Grid, ResdataRegion from resdata.resfile import ResdataFile, ResdataRestartFile @@ -19,15 +20,9 @@ def avg_pressure(p, sw, pv, region, region_id, result): p1 = p.sum(mask=region) / region.active_size() - if total_pv > 0: - p2 = p_pv.sum(mask=region) / total_pv - else: - p2 = None + p2 = p_pv.sum(mask=region) / total_pv if total_pv > 0 else None - if total_hc_pv > 0: - p3 = p_hc_pv.sum(mask=region) / total_hc_pv - else: - p3 = None + p3 = p_hc_pv.sum(mask=region) / total_hc_pv if total_hc_pv > 0 else None else: p1 = None p2 = None @@ -71,7 +66,7 @@ def avg_pressure(p, sw, pv, region, region_id, result): avg_pressure(p, sw, pv, ResdataRegion(grid, True), "field", result) sim_days.append(header.get_sim_days()) - for key in result.keys(): + for key in result: plt.figure(1) for index, p in enumerate(result[key]): plt.plot(sim_days, p, label="Region:%s P%d" % (key, index + 1)) diff --git a/python/docs/examples/grid_info.py b/python/docs/examples/grid_info.py index 7e442412e..e2aedcaf1 100755 --- a/python/docs/examples/grid_info.py +++ b/python/docs/examples/grid_info.py @@ -1,6 +1,7 @@ #!/usr/bin/env python import sys -from resdata.grid import ResdataRegion, Grid + +from resdata.grid import Grid, ResdataRegion def volume_min_max(grid): @@ -26,7 +27,7 @@ def main(grid): if __name__ == "__main__": if len(sys.argv) < 2: - exit("usage: grid_info.py path/to/file.EGRID") + sys.exit("usage: grid_info.py path/to/file.EGRID") case = sys.argv[1] grid = Grid(case) main(grid) diff --git a/python/resdata/__init__.py b/python/resdata/__init__.py index 5222260f9..a369d228a 100644 --- a/python/resdata/__init__.py +++ b/python/resdata/__init__.py @@ -69,7 +69,7 @@ def _dlopen_resdata(): @ct.CFUNCTYPE(None, ct.c_char_p, ct.c_int, ct.c_char_p, ct.c_char_p, ct.c_char_p) def _c_abort_handler(filename, lineno, function, message, backtrace): - global _abort_handler + global _abort_handler # noqa: PLW0602 if not _abort_handler: return _abort_handler( @@ -85,7 +85,7 @@ def set_abort_handler(function): """ Set callback function for util_abort, which is called prior to std::abort() """ - global _abort_handler + global _abort_handler # noqa: PLW0603 _abort_handler = function ResdataPrototype.lib.util_set_abort_handler(_c_abort_handler) @@ -102,11 +102,11 @@ def __init__(self, prototype, bind=True): from .rd_type import ResDataType, ResdataTypeEnum from .rd_util import ( - FileType, FileMode, + FileType, Phase, - UnitSystem, ResdataUtil, + UnitSystem, ) from .util.util import ResdataVersion, updateAbortSignals diff --git a/python/resdata/geometry/cpolyline.py b/python/resdata/geometry/cpolyline.py index 559fe797a..fcd64949e 100644 --- a/python/resdata/geometry/cpolyline.py +++ b/python/resdata/geometry/cpolyline.py @@ -6,7 +6,9 @@ import os.path from cwrap import BaseCClass + from resdata import ResdataPrototype + from .geometry_tools import GeometryTools @@ -54,10 +56,7 @@ def createFromXYZFile(cls, filename, name=None): def __str__(self): name = self.getName() - if name: - str = "%s [" % name - else: - str = "[" + str = "%s [" % name if name else "[" for index, p in enumerate(self): str += "(%g,%g)" % p @@ -143,10 +142,7 @@ def extendToBBox(self, bbox, start=True): intersections = GeometryTools.rayPolygonIntersections(p1, ray_dir, bbox) if intersections: p2 = intersections[0][1] - if self.getName(): - name = "Extend:%s" % self.getName() - else: - name = None + name = "Extend:%s" % self.getName() if self.getName() else None return CPolyline(name=name, init_points=[(p1[0], p1[1]), p2]) else: diff --git a/python/resdata/geometry/cpolyline_collection.py b/python/resdata/geometry/cpolyline_collection.py index 80608ac31..52d2f44f0 100644 --- a/python/resdata/geometry/cpolyline_collection.py +++ b/python/resdata/geometry/cpolyline_collection.py @@ -85,11 +85,10 @@ def shallowCopy(self): def addPolyline(self, polyline, name=None): if not isinstance(polyline, CPolyline): polyline = CPolyline(init_points=polyline, name=name) - else: - if not name is None: - raise ValueError( - "The name keyword argument can only be supplied when add not CPOlyline object" - ) + elif not name is None: + raise ValueError( + "The name keyword argument can only be supplied when add not CPOlyline object" + ) name = polyline.getName() if name and name in self: diff --git a/python/resdata/geometry/geo_region.py b/python/resdata/geometry/geo_region.py index 33c7cb597..54bb00ba4 100644 --- a/python/resdata/geometry/geo_region.py +++ b/python/resdata/geometry/geo_region.py @@ -42,7 +42,7 @@ class GeoRegion(BaseCClass): ) def __init__(self, pointset, preselect=False): - self._preselect = True if preselect else False + self._preselect = bool(preselect) c_ptr = self._alloc(pointset, self._preselect) if c_ptr: super(GeoRegion, self).__init__(c_ptr) @@ -68,7 +68,7 @@ def _construct_cline(self, line): x2, y2 = map(float, p2) except Exception as err: err_msg = "Select with pair ((x1,y1), (x2,y2)), not %s (%s)." - raise ValueError(err_msg % (line, err)) + raise ValueError(err_msg % (line, err)) from err x1x2_ptr = cpair(x1, x2) y1y2_ptr = cpair(y1, y2) return x1x2_ptr, y1y2_ptr diff --git a/python/resdata/geometry/geometry_tools.py b/python/resdata/geometry/geometry_tools.py index 19d6594c4..1bf0845ee 100644 --- a/python/resdata/geometry/geometry_tools.py +++ b/python/resdata/geometry/geometry_tools.py @@ -1,6 +1,6 @@ -from math import sqrt import functools import sys +from math import sqrt class GeometryTools(object): @@ -135,13 +135,12 @@ def pointInPolygon(p, polygon): for index in range(n + 1): p2x, p2y = polygon[index % n][0:2] - if min(p1y, p2y) < y <= max(p1y, p2y): - if x <= max(p1x, p2x): - if p1y != p2y: - xints = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x + if min(p1y, p2y) < y <= max(p1y, p2y) and x <= max(p1x, p2x): + if p1y != p2y: + xints = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x - if p1x == p2x or x <= xints: - inside = not inside + if p1x == p2x or x <= xints: + inside = not inside p1x, p1y = p2x, p2y @@ -159,9 +158,7 @@ def extendToEdge(bounding_polygon, poly_line): ray1 = GeometryTools.lineToRay(poly_line[1], poly_line[0]) intersection1 = GeometryTools.rayPolygonIntersections( p1, ray1, bounding_polygon - )[ - 0 - ] # assume convex + )[0] # assume convex p2 = poly_line[-1] assert GeometryTools.pointInPolygon(p2, bounding_polygon) @@ -172,9 +169,7 @@ def extendToEdge(bounding_polygon, poly_line): ) intersection2 = GeometryTools.rayPolygonIntersections( p2, ray2, bounding_polygon - )[ - 0 - ] # assume convex + )[0] # assume convex return [intersection1[1]] + poly_line + [intersection2[1]] @@ -196,17 +191,13 @@ def slicePolygon(bounding_polygon, poly_line): tmp = GeometryTools.rayPolygonIntersections(p1, ray1, bounding_polygon) intersection1 = GeometryTools.rayPolygonIntersections( p1, ray1, bounding_polygon - )[ - 0 - ] # assume convex + )[0] # assume convex p2 = poly_line[-1] ray2 = GeometryTools.lineToRay(poly_line[-2], poly_line[-1]) intersection2 = GeometryTools.rayPolygonIntersections( p2, ray2, bounding_polygon - )[ - 0 - ] # assume convex + )[0] # assume convex # Check for intersection between the polyline extensions on the inside of the bounadary internal_intersection = GeometryTools.lineIntersection( @@ -394,13 +385,17 @@ def connectPolylines(polyline, target_polyline): p0 = polyline[-1] p1 = polyline[-2] ray = GeometryTools.lineToRay(p1, p0) - for index, p in GeometryTools.rayPolygonIntersections(p0, ray, target_polyline): + for _index, p in GeometryTools.rayPolygonIntersections( + p0, ray, target_polyline + ): d_list.append((GeometryTools.distance(p0, p), [p0, p])) p0 = polyline[0] p1 = polyline[1] ray = GeometryTools.lineToRay(p1, p0) - for index, p in GeometryTools.rayPolygonIntersections(p0, ray, target_polyline): + for _index, p in GeometryTools.rayPolygonIntersections( + p0, ray, target_polyline + ): d_list.append((GeometryTools.distance(p0, p), [p0, p])) if len(d_list) == 0: diff --git a/python/resdata/geometry/polyline.py b/python/resdata/geometry/polyline.py index 2fff2e0e0..1c7566802 100644 --- a/python/resdata/geometry/polyline.py +++ b/python/resdata/geometry/polyline.py @@ -1,4 +1,5 @@ import collections + from .geometry_tools import GeometryTools @@ -40,20 +41,13 @@ def __eq__(self, other): if len(self) != len(other): return False - for p1, p2 in zip(self, other): - if p1 != p2: - return False - - return True + return all(p1 == p2 for p1, p2 in zip(self, other)) def __len__(self): return len(self.__points) def addPoint(self, x, y, z=None): - if z is None: - p = (x, y) - else: - p = (x, y, z) + p = (x, y) if z is None else (x, y, z) self.__points.append(p) def __getitem__(self, index): diff --git a/python/resdata/geometry/surface.py b/python/resdata/geometry/surface.py index 92150fb50..a361fa2a2 100644 --- a/python/resdata/geometry/surface.py +++ b/python/resdata/geometry/surface.py @@ -255,11 +255,10 @@ def _assert_idx_or_i_and_j(self, idx, i, j): raise ValueError( "idx is None, i and j must be ints, was %s and %s." % (i, j) ) - else: - if i is not None or j is not None: - raise ValueError( - "idx is set, i and j must be None, was %s and %s." % (i, j) - ) + elif i is not None or j is not None: + raise ValueError( + "idx is set, i and j must be None, was %s and %s." % (i, j) + ) def getXYZ(self, idx=None, i=None, j=None): """Returns a tuple of 3 floats, (x,y,z) for given global index, or i and j.""" diff --git a/python/resdata/gravimetry/__init__.py b/python/resdata/gravimetry/__init__.py index 1035865aa..e74a01cd8 100644 --- a/python/resdata/gravimetry/__init__.py +++ b/python/resdata/gravimetry/__init__.py @@ -1,10 +1,10 @@ """ - rd_grav/ResdataGrav: Class used to simplify evaluation of - modelling time-lapse gravitational surveys. +rd_grav/ResdataGrav: Class used to simplify evaluation of + modelling time-lapse gravitational surveys. - rd_subsidence/ResdataSubsidence: Small class used to evaluate simulated - subsidence from simulations; analogous to the EcLGrav - functionality. +rd_subsidence/ResdataSubsidence: Small class used to evaluate simulated + subsidence from simulations; analogous to the EcLGrav + functionality. """ from .rd_grav import ResdataGrav diff --git a/python/resdata/gravimetry/rd_subsidence.py b/python/resdata/gravimetry/rd_subsidence.py index 0ad6b7bb8..4597dbab5 100644 --- a/python/resdata/gravimetry/rd_subsidence.py +++ b/python/resdata/gravimetry/rd_subsidence.py @@ -98,9 +98,8 @@ def eval_geertsma( if not base_survey in self: raise KeyError("No such survey: %s" % base_survey) - if monitor_survey is not None: - if not monitor_survey in self: - raise KeyError("No such survey: %s" % monitor_survey) + if monitor_survey is not None and not monitor_survey in self: + raise KeyError("No such survey: %s" % monitor_survey) return self._eval_geertsma( base_survey, @@ -127,9 +126,8 @@ def eval_geertsma_rporv( if not base_survey in self: raise KeyError("No such survey: %s" % base_survey) - if monitor_survey is not None: - if not monitor_survey in self: - raise KeyError("No such survey: %s" % monitor_survey) + if monitor_survey is not None and not monitor_survey in self: + raise KeyError("No such survey: %s" % monitor_survey) return self._eval_geertsma_rporv( base_survey, diff --git a/python/resdata/grid/__init__.py b/python/resdata/grid/__init__.py index 9e88a4aa2..cbfab5e16 100644 --- a/python/resdata/grid/__init__.py +++ b/python/resdata/grid/__init__.py @@ -1,13 +1,13 @@ """ - rd_grid/Grid: This will load a GRID or EGRID file, and - can then subsequently be used for queries about the grid. +rd_grid/Grid: This will load a GRID or EGRID file, and + can then subsequently be used for queries about the grid. - rd_region/ResdataRegion: Convenience class to support selecting cells - in a grid based on a wide range of criteria. Can be used as a - mask in operations on ResdataKW instances. +rd_region/ResdataRegion: Convenience class to support selecting cells + in a grid based on a wide range of criteria. Can be used as a + mask in operations on ResdataKW instances. - rd_grid_generator/GridGenerator: This can be used to generate various - grids. +rd_grid_generator/GridGenerator: This can be used to generate various + grids. """ import resdata.util.util diff --git a/python/resdata/grid/cell.py b/python/resdata/grid/cell.py index 9b17c10f7..ff0de4df1 100644 --- a/python/resdata/grid/cell.py +++ b/python/resdata/grid/cell.py @@ -81,7 +81,7 @@ def __eq__(self, other): def __neq__(self, other): if isinstance(other, Cell): - return not self == other + return self != other return NotImplemented def hash(self): diff --git a/python/resdata/grid/faults/fault.py b/python/resdata/grid/faults/fault.py index b25a42758..892261947 100644 --- a/python/resdata/grid/faults/fault.py +++ b/python/resdata/grid/faults/fault.py @@ -100,7 +100,7 @@ def __sort_fault_lines(self): perm_list.sort(key=lambda x: x[1]) fault_lines = [] - for index, d in perm_list: + for index, _d in perm_list: fault_lines.append(self.__fault_lines[index]) self.__fault_lines = fault_lines @@ -208,32 +208,29 @@ def add_record(self, I1, I2, J1, J2, K1, K2, face): if K1 > K2: raise ValueError("Invalid K1 K2 indices") - if I1 < 0 or I1 >= self.nx: + if I1 < 0 or self.nx <= I1: raise ValueError("Invalid I1:%d" % I1) - if I2 < 0 or I2 >= self.nx: + if I2 < 0 or self.nx <= I2: raise ValueError("Invalid I2:%d" % I2) - if J1 < 0 or J1 >= self.ny: + if J1 < 0 or self.ny <= J1: raise ValueError("Invalid J1:%d" % J1) - if J2 < 0 or J2 >= self.ny: + if J2 < 0 or self.ny <= J2: raise ValueError("Invalid J2:%d" % J2) - if K1 < 0 or K1 >= self.nz: + if K1 < 0 or self.nz <= K1: raise ValueError("Invalid K1:%d" % K1) - if K2 < 0 or K2 >= self.nz: + if K2 < 0 or self.nz <= K2: raise ValueError("Invalid K2:%d" % K2) - if face in ["X", "I"]: - if I1 != I2: - raise ValueError("For face:%s we must have I1 == I2" % face) + if face in ["X", "I"] and I1 != I2: + raise ValueError("For face:%s we must have I1 == I2" % face) - if face in ["Y", "J"]: - if J1 != J2: - raise ValueError("For face:%s we must have J1 == J2" % face) + if face in ["Y", "J"] and J1 != J2: + raise ValueError("For face:%s we must have J1 == J2" % face) - if face in ["Z", "K"]: - if K1 != K2: - raise ValueError("For face:%s we must have K1 == K2" % face) + if face in ["Z", "K"] and K1 != K2: + raise ValueError("For face:%s we must have K1 == K2" % face) # ----------------------------------------------------------------- @@ -297,10 +294,7 @@ def connect_with_polyline(self, polyline, k): return None def connect(self, target, k): - if isinstance(target, Fault): - polyline = target.getPolyline(k) - else: - polyline = target + polyline = target.getPolyline(k) if isinstance(target, Fault) else target return self.connectWithPolyline(polyline, k) def extend_to_polyline(self, polyline, k): @@ -402,10 +396,7 @@ def extend_to_b_box(self, bbox, k, start=True): intersections = GeometryTools.rayPolygonIntersections(p1, ray_dir, bbox) if intersections: p2 = intersections[0][1] - if self.getName(): - name = "Extend:%s" % self.getName() - else: - name = None + name = "Extend:%s" % self.getName() if self.getName() else None return CPolyline(name=name, init_points=[(p1[0], p1[1]), p2]) else: @@ -414,10 +405,7 @@ def extend_to_b_box(self, bbox, k, start=True): def end_join(self, other, k): fault_polyline = self.getPolyline(k) - if isinstance(other, Fault): - other_polyline = other.getPolyline(k) - else: - other_polyline = other + other_polyline = other.getPolyline(k) if isinstance(other, Fault) else other return GeometryTools.joinPolylines(fault_polyline, other_polyline) @@ -462,13 +450,11 @@ def intersect_fault_rays(ray1, ray2): dx = p2[0] - p1[0] dy = p2[1] - p1[1] - if dx != 0: - if dir1[0] * dx <= 0 and dir2[0] * dx >= 0: - raise ValueError("Rays will never intersect") + if dx != 0 and dir1[0] * dx <= 0 and dir2[0] * dx >= 0: + raise ValueError("Rays will never intersect") - if dy != 0: - if dir1[1] * dy <= 0 and dir2[1] * dy >= 0: - raise ValueError("Rays will never intersect") + if dy != 0 and dir1[1] * dy <= 0 and dir2[1] * dy >= 0: + raise ValueError("Rays will never intersect") if dx * dy != 0: if dir1[0] != 0: @@ -502,10 +488,7 @@ def int_ray(p1, p2): raise Exception("Invalid direction") dy = 0 - if p2[0] > p1[0]: - dx = 1 - else: - dx = -1 + dx = 1 if p2[0] > p1[0] else -1 return [p2, (dx, dy)] diff --git a/python/resdata/grid/faults/fault_block.py b/python/resdata/grid/faults/fault_block.py index a74a4c17d..9ad0f6090 100644 --- a/python/resdata/grid/faults/fault_block.py +++ b/python/resdata/grid/faults/fault_block.py @@ -143,9 +143,8 @@ def contains_polyline(self, polyline): for p in polyline: if GeometryTools.pointInPolygon(p, edge_polyline): return True - else: - edge_polyline.assertClosed() - return GeometryTools.polylinesIntersect(edge_polyline, polyline) + edge_polyline.assertClosed() + return GeometryTools.polylinesIntersect(edge_polyline, polyline) def get_neighbours(self, polylines=None, connected_only=True): """ diff --git a/python/resdata/grid/faults/fault_block_layer.py b/python/resdata/grid/faults/fault_block_layer.py index 3176456a9..cb5d177fa 100644 --- a/python/resdata/grid/faults/fault_block_layer.py +++ b/python/resdata/grid/faults/fault_block_layer.py @@ -126,7 +126,7 @@ def load_keyword(self, fault_block_kw): raise ValueError( "The fault block keyword had wrong type/size: type:%s size:%d grid_size:%d" % ( - fault_block_kw.typeName(), + fault_block_kw.type_name, len(fault_block_kw), self.grid_ref.getGlobalSize(), ) @@ -202,11 +202,11 @@ def join_faults(self, fault1, fault2): layer = self.getGeoLayer() try: layer.addIJBarrier(Fault.joinFaults(fault1, fault2, self.getK())) - except ValueError: + except ValueError as err: err = "Failed to join faults %s and %s" names = (fault1.getName(), fault2.getName()) print(err % names) - raise ValueError(err % names) + raise ValueError(err % names) from err def add_polyline_barrier(self, polyline): layer = self.getGeoLayer() diff --git a/python/resdata/grid/faults/fault_line.py b/python/resdata/grid/faults/fault_line.py index 45697e800..395029128 100644 --- a/python/resdata/grid/faults/fault_line.py +++ b/python/resdata/grid/faults/fault_line.py @@ -29,7 +29,7 @@ def verify(self): if len(self.__segment_list) > 1: current = self.__segment_list[0] for next_segment in self.__segment_list[1:]: - if not current.getC2() == next_segment.getC1(): + if current.getC2() != next_segment.getC1(): sys.stdout.write( "Current: %d ---- %d \n" % (current.getC1(), current.getC2()) ) @@ -54,7 +54,7 @@ def try_append(self, segment): else: segment.swap() - if not tail.getC2() == segment.getC1(): + if tail.getC2() != segment.getC1(): return False self.__segment_list.append(segment) @@ -124,10 +124,7 @@ def __init_neighbor_cells(self): i = i1 for j in range(j1, j2): g2 = i + j * nx + k * nx * ny - if i == 0: - g1 = -1 - else: - g1 = g2 - 1 + g1 = -1 if i == 0 else g2 - 1 if i == nx: g2 = -1 @@ -137,10 +134,7 @@ def __init_neighbor_cells(self): j = j1 for i in range(i1, i2): g2 = i + j * nx + k * nx * ny - if j == 0: - g1 = -1 - else: - g1 = g2 - nx + g1 = -1 if j == 0 else g2 - nx if j == ny: g2 = -1 diff --git a/python/resdata/grid/faults/fault_segments.py b/python/resdata/grid/faults/fault_segments.py index b5ff6e91a..abc620539 100644 --- a/python/resdata/grid/faults/fault_segments.py +++ b/python/resdata/grid/faults/fault_segments.py @@ -13,7 +13,7 @@ def __eq__(self, other): s = self.c1, self.c2 o = other.c1, other.c2 o_flipped = other.c2, other.c1 - return s == o or s == o_flipped + return s in (o, o_flipped) def __hash__(self): return hash(hash(self.__C1) + hash(self.__C2) + hash(self.__next_segment)) @@ -28,10 +28,7 @@ def joins(self, other): return True if self.__C2 == other.__C1: return True - if self.__C2 == other.__C2: - return True - - return False + return self.__C2 == other.__C2 def get_c1(self): return self.__C1 @@ -135,7 +132,7 @@ def pop_next(self, segment): def print_content(self): for d in self.__segment_map.values(): - for C, S in d.iteritems(): + for _C, S in d.iteritems(): print(S) diff --git a/python/resdata/grid/faults/layer.py b/python/resdata/grid/faults/layer.py index eaf263f42..7f5f6f61f 100644 --- a/python/resdata/grid/faults/layer.py +++ b/python/resdata/grid/faults/layer.py @@ -63,10 +63,10 @@ def _assert_ij(self, i, j): def __unpack_index(self, index): try: (i, j) = index - except TypeError: + except TypeError as err: raise ValueError( "Index:%s is invalid - must have two integers" % str(index) - ) + ) from err self._assert_ij(i, j) diff --git a/python/resdata/grid/rd_grid.py b/python/resdata/grid/rd_grid.py index e0c63738b..493a2f042 100644 --- a/python/resdata/grid/rd_grid.py +++ b/python/resdata/grid/rd_grid.py @@ -280,6 +280,7 @@ def create_rectangular(cls, dims, dV, actnum=None): "Grid.createRectangular is deprecated. " + "Please use the similar method: GridGenerator.createRectangular.", DeprecationWarning, + stacklevel=1, ) if actnum is None: @@ -554,12 +555,11 @@ def __global_index(self, active_index=None, global_index=None, ijk=None): raise IndexError("Invalid value k:%d Range: [%d,%d)" % (k, 0, nz)) global_index = self._get_global_index3(i, j, k) - else: - if not 0 <= global_index < self.getGlobalSize(): - raise IndexError( - "Invalid value global_index:%d Range: [%d,%d)" - % (global_index, 0, self.getGlobalSize()) - ) + elif not 0 <= global_index < self.getGlobalSize(): + raise IndexError( + "Invalid value global_index:%d Range: [%d,%d)" + % (global_index, 0, self.getGlobalSize()) + ) return global_index def get_active_index(self, ijk=None, global_index=None): @@ -642,10 +642,7 @@ def active(self, ijk=None, global_index=None): """ gi = self.__global_index(global_index=global_index, ijk=ijk) active_index = self._get_active_index1(gi) - if active_index >= 0: - return True - else: - return False + return active_index >= 0 def get_global_index(self, ijk=None, active_index=None): """ @@ -1045,10 +1042,7 @@ def has_lgr(self, lgr_name): """ Query if the grid has an LGR with name @lgr_name. """ - if self._has_named_lgr(lgr_name): - return True - else: - return False + return self._has_named_lgr(lgr_name) def get_lgr(self, lgr_key): """Get Grid instance with LGR content. @@ -1067,9 +1061,8 @@ def get_lgr(self, lgr_key): if isinstance(lgr_key, int): if self._has_numbered_lgr(lgr_key): lgr = self._get_numbered_lgr(lgr_key) - else: - if self._has_named_lgr(lgr_key): - lgr = self._get_named_lgr(lgr_key) + elif self._has_named_lgr(lgr_key): + lgr = self._get_named_lgr(lgr_key) if lgr is None: raise KeyError("No such LGR: %s" % lgr_key) @@ -1157,10 +1150,7 @@ def create_kw(self, array, kw_name, pack): else: sys.exit("Do not know how to create rd_kw from type:%s" % dtype) - if pack: - size = self.getNumActive() - else: - size = self.getGlobalSize() + size = self.getNumActive() if pack else self.getGlobalSize() if len(kw_name) > 8: # Silently truncate to length 8 @@ -1176,11 +1166,10 @@ def create_kw(self, array, kw_name, pack): if self.active(global_index=global_index): kw[active_index] = array[i, j, k] active_index += 1 + elif dtype == np.int32: + kw[global_index] = int(array[i, j, k]) else: - if dtype == np.int32: - kw[global_index] = int(array[i, j, k]) - else: - kw[global_index] = array[i, j, k] + kw[global_index] = array[i, j, k] global_index += 1 return kw @@ -1379,10 +1368,7 @@ def export_index(self, active_only=False): This index frame should typically be passed to the epxport_data(), export_volume() and export_corners() functions. """ - if active_only: - size = self.get_num_active() - else: - size = self.get_global_size() + size = self.get_num_active() if active_only else self.get_global_size() indx = np.zeros(size, dtype=np.int32) data = np.zeros([size, 4], dtype=np.int32) self._export_index_frame( diff --git a/python/resdata/grid/rd_grid_generator.py b/python/resdata/grid/rd_grid_generator.py index ec8a7f58a..167569111 100644 --- a/python/resdata/grid/rd_grid_generator.py +++ b/python/resdata/grid/rd_grid_generator.py @@ -493,7 +493,7 @@ def assert_actnum(cls, nx, ny, nz, actnum): % (nx * ny * nz, len(actnum)) ) - if set(actnum) - set([0, 1]): + if set(actnum) - {0, 1}: raise AssertionError( "Expected ACTNUM to consist of 0's and 1's, was %s." % ", ".join(map(str, set(actnum))) diff --git a/python/resdata/grid/rd_region.py b/python/resdata/grid/rd_region.py index 69ad6e24b..8955338ea 100644 --- a/python/resdata/grid/rd_region.py +++ b/python/resdata/grid/rd_region.py @@ -552,7 +552,7 @@ def select_equal(self, rd_kw, value, intersect=False): if not rd_kw.data_type.is_int(): raise ValueError( "The select_equal method must have an integer valued keyword - got:%s" - % rd_kw.typeName() + % rd_kw.type_name ) self._select_equal(rd_kw, value) @@ -565,7 +565,7 @@ def deselect_equal(self, rd_kw, value): if not rd_kw.data_type.is_int(): raise ValueError( "The select_equal method must have an integer valued keyword - got:%s" - % rd_kw.typeName() + % rd_kw.type_name ) self._deselect_equal(rd_kw, value) @@ -1067,10 +1067,7 @@ def idiv_kw(self, target_kw, other, force_active=False): else: raise TypeError("Type mismatch") else: - if target_kw.data_type.is_int(): - scale = 1 // other - else: - scale = 1.0 / other + scale = 1 // other if target_kw.data_type.is_int() else 1.0 / other self.scale_kw(target_kw, scale, force_active) def copy_kw(self, target_kw, src_kw, force_active=False): diff --git a/python/resdata/rd_util.py b/python/resdata/rd_util.py index 50932e08f..1454330fd 100644 --- a/python/resdata/rd_util.py +++ b/python/resdata/rd_util.py @@ -15,6 +15,7 @@ import ctypes from cwrap import BaseCEnum + from resdata import ResdataPrototype from resdata.util.util import monkey_the_camel @@ -140,10 +141,7 @@ def inspect_extension(filename): file_type = ResdataUtil._get_file_type( filename, ctypes.byref(fmt_file), ctypes.byref(report_step) ) - if report_step.value == -1: - step = None - else: - step = report_step.value + step = None if report_step.value == -1 else report_step.value return (file_type, fmt_file.value, step) diff --git a/python/resdata/resfile/rd_3d_file.py b/python/resdata/resfile/rd_3d_file.py index 0feed60ff..c5bbc2c64 100644 --- a/python/resdata/resfile/rd_3d_file.py +++ b/python/resdata/resfile/rd_3d_file.py @@ -1,4 +1,4 @@ -from resdata.resfile import ResdataFile, Resdata3DKW +from resdata.resfile import Resdata3DKW, ResdataFile class Resdata3DFile(ResdataFile): @@ -8,14 +8,11 @@ def __init__(self, grid, filename, flags=0): def __getitem__(self, index): return_arg = super(Resdata3DFile, self).__getitem__(index) - if isinstance(return_arg, list): - kw_list = return_arg - else: - kw_list = [return_arg] + kw_list = return_arg if isinstance(return_arg, list) else [return_arg] # Go through all the keywords and try inplace promotion to Resdata3DKW for kw in kw_list: - try: + try: # noqa: SIM105 Resdata3DKW.castFromKW(kw, self.grid) except ValueError: pass diff --git a/python/resdata/resfile/rd_3dkw.py b/python/resdata/resfile/rd_3dkw.py index 791ae8d22..5c0e6e825 100644 --- a/python/resdata/resfile/rd_3dkw.py +++ b/python/resdata/resfile/rd_3dkw.py @@ -1,4 +1,5 @@ from resdata.util.util import monkey_the_camel + from .rd_kw import ResdataKW @@ -51,10 +52,7 @@ class Resdata3DKW(ResdataKW): """ def __init__(self, kw, grid, value_type, default_value=0, global_active=False): - if global_active: - size = grid.getGlobalSize() - else: - size = grid.getNumActive() + size = grid.getGlobalSize() if global_active else grid.getNumActive() super(Resdata3DKW, self).__init__(kw, size, value_type) self.grid = grid self.global_active = global_active @@ -93,11 +91,10 @@ def __getitem__(self, index): global_index = self.grid.get_global_index(ijk=index) if self.global_active: index = global_index + elif not self.grid.active(global_index=global_index): + return self.getDefault() else: - if not self.grid.active(global_index=global_index): - return self.getDefault() - else: - index = self.grid.get_active_index(ijk=index) + index = self.grid.get_active_index(ijk=index) return super(Resdata3DKW, self).__getitem__(index) @@ -116,13 +113,12 @@ def __setitem__(self, index, value): global_index = self.grid.get_global_index(ijk=index) if self.global_active: index = global_index + elif not self.grid.active(global_index=global_index): + raise ValueError( + "Tried to assign value to inactive cell: (%d,%d,%d)" % index + ) else: - if not self.grid.active(global_index=global_index): - raise ValueError( - "Tried to assign value to inactive cell: (%d,%d,%d)" % index - ) - else: - index = self.grid.get_active_index(ijk=index) + index = self.grid.get_active_index(ijk=index) return super(Resdata3DKW, self).__setitem__(index, value) diff --git a/python/resdata/resfile/rd_file.py b/python/resdata/resfile/rd_file.py index 4b4303159..c2e6ac5d0 100644 --- a/python/resdata/resfile/rd_file.py +++ b/python/resdata/resfile/rd_file.py @@ -26,6 +26,7 @@ import re from cwrap import BaseCClass + from resdata import FileMode, FileType, ResdataPrototype from resdata.resfile import ResdataKW from resdata.util.util import CTime, monkey_the_camel @@ -121,19 +122,19 @@ def report_list(self): seqnum_list = self["SEQNUM"] for s in seqnum_list: report_steps.append(s[0]) - except KeyError: + except KeyError as err: # OK - we did not have seqnum; that might be because this # a non-unified restart file; or because this is not a # restart file at all. fname = self.getFilename() - matchObj = re.search("\.[XF](\d{4})$", fname) + matchObj = re.search(r"\.[XF](\d{4})$", fname) if matchObj: report_steps.append(int(matchObj.group(1))) else: raise TypeError( 'Tried get list of report steps from file "%s" - which is not a restart file' % fname - ) + ) from err return report_steps @@ -364,13 +365,12 @@ def restart_get_kw(self, kw_name, dtime, copy=False): return ResdataKW.copy(kw) else: return kw + elif self.has_kw(kw_name): + raise IndexError( + 'Does not have keyword "%s" at time:%s.' % (kw_name, dtime) + ) else: - if self.has_kw(kw_name): - raise IndexError( - 'Does not have keyword "%s" at time:%s.' % (kw_name, dtime) - ) - else: - raise KeyError('Keyword "%s" not recognized.' % kw_name) + raise KeyError('Keyword "%s" not recognized.' % kw_name) else: raise IndexError( 'Does not have keyword "%s" at time:%s.' % (kw_name, dtime) diff --git a/python/resdata/resfile/rd_file_view.py b/python/resdata/resfile/rd_file_view.py index 44bb363cf..e4abc9977 100644 --- a/python/resdata/resfile/rd_file_view.py +++ b/python/resdata/resfile/rd_file_view.py @@ -115,10 +115,7 @@ def __len__(self): return self._get_size() def __contains__(self, kw): - if self.numKeywords(kw) > 0: - return True - else: - return False + return self.numKeywords(kw) > 0 def num_keywords(self, kw): return self._get_num_named_kw(kw) @@ -143,9 +140,8 @@ def block_view2(self, start_kw, stop_kw, start_index): "Index must be in [0, %d), was: %d." % (ls, start_index) ) - if stop_kw: - if not stop_kw in self: - raise KeyError("The keyword:%s is not in file" % stop_kw) + if stop_kw and not stop_kw in self: + raise KeyError("The keyword:%s is not in file" % stop_kw) view = self._create_block_view2(start_kw, stop_kw, idx) view.setParent(parent=self) diff --git a/python/resdata/resfile/rd_kw.py b/python/resdata/resfile/rd_kw.py index d32800747..c4b73d463 100644 --- a/python/resdata/resfile/rd_kw.py +++ b/python/resdata/resfile/rd_kw.py @@ -28,6 +28,7 @@ import numpy as np from cwrap import CFILE, BaseCClass + from resdata import ResdataPrototype, ResDataType, ResdataTypeEnum, ResdataUtil from resdata.util.util import monkey_the_camel @@ -38,6 +39,7 @@ def dump_type_deprecation_warning(): warnings.warn( "ResdataTypeEnum is deprecated. You should instead provide an ResDataType", DeprecationWarning, + stacklevel=1, ) @@ -82,18 +84,16 @@ class ResdataKW(BaseCClass): limit the operation to a part of the ResdataKW. """ - int_kw_set = set( - [ - "PVTNUM", - "FIPNUM", - "EQLNUM", - "FLUXNUM", - "MULTNUM", - "ACTNUM", - "SPECGRID", - "REGIONS", - ] - ) + int_kw_set = { + "PVTNUM", + "FIPNUM", + "EQLNUM", + "FLUXNUM", + "MULTNUM", + "ACTNUM", + "SPECGRID", + "REGIONS", + } TYPE_NAME = "rd_kw" _alloc_new = ResdataPrototype( @@ -312,12 +312,10 @@ def read_grdecl(cls, fileH, kw, strict=True, rd_type=None): """ cfile = CFILE(fileH) - if kw: - if len(kw) > 8: - raise TypeError( - "Sorry keyword:%s is too long, must be eight characters or less." - % kw - ) + if kw and len(kw) > 8: + raise TypeError( + "Sorry keyword:%s is too long, must be eight characters or less." % kw + ) if rd_type is None: if cls.int_kw_set.__contains__(kw): @@ -502,18 +500,16 @@ def __getitem__(self, index): if index < 0 or index >= length: raise IndexError + elif self.data_ptr: + return self.data_ptr[index] + elif self.data_type.is_bool(): + return self._iget_bool(index) + elif self.data_type.is_char(): + return self._iget_char_ptr(index) + elif self.data_type.is_string(): + return self._iget_string_ptr(index) else: - if self.data_ptr: - return self.data_ptr[index] - else: - if self.data_type.is_bool(): - return self._iget_bool(index) - elif self.data_type.is_char(): - return self._iget_char_ptr(index) - elif self.data_type.is_string(): - return self._iget_string_ptr(index) - else: - raise TypeError("Internal implementation error ...") + raise TypeError("Internal implementation error ...") elif isinstance(index, slice): return self.slice_copy(index) else: @@ -531,18 +527,16 @@ def __setitem__(self, index, value): if index < 0 or index >= length: raise IndexError + elif self.data_ptr: + self.data_ptr[index] = value + elif self.data_type.is_bool(): + self._iset_bool(index, value) + elif self.data_type.is_char(): + return self._iset_char_ptr(index, value) + elif self.data_type.is_string(): + return self._iset_string_ptr(index, value) else: - if self.data_ptr: - self.data_ptr[index] = value - else: - if self.data_type.is_bool(): - self._iset_bool(index, value) - elif self.data_type.is_char(): - return self._iset_char_ptr(index, value) - elif self.data_type.is_string(): - return self._iset_string_ptr(index, value) - else: - raise SystemError("Internal implementation error ...") + raise SystemError("Internal implementation error ...") elif isinstance(index, slice): (start, stop, step) = index.indices(len(self)) index = start @@ -573,11 +567,10 @@ def __IMUL__(self, factor, mul=True): self._scale_int(factor) else: raise TypeError("Type mismatch") + elif isinstance(factor, (int, float)): + self._scale_float(factor) else: - if isinstance(factor, int) or isinstance(factor, float): - self._scale_float(factor) - else: - raise TypeError("Only muliplication with scalar supported") + raise TypeError("Only muliplication with scalar supported") else: raise TypeError("Not numeric type") @@ -594,23 +587,19 @@ def __IADD__(self, delta, add=True): else: raise TypeError("Type / size mismatch") else: - if add: - sign = 1 - else: - sign = -1 + sign = 1 if add else -1 if self.data_type.is_int(): if isinstance(delta, int): self._shift_int(delta * sign) else: raise TypeError("Type mismatch") + elif isinstance(delta, (int, float)): + self._shift_float( + delta * sign + ) # Will call the _float() or _double() function in the C layer. else: - if isinstance(delta, int) or isinstance(delta, float): - self._shift_float( - delta * sign - ) # Will call the _float() or _double() function in the C layer. - else: - raise TypeError("Type mismatch") + raise TypeError("Type mismatch") else: raise TypeError("Type / size mismatch") @@ -696,9 +685,7 @@ def sum(self, mask=None, force_active=False): if mask is None: if self.data_type.is_int(): return self._int_sum() - elif self.data_type.is_float(): - return self._float_sum() - elif self.data_type.is_double(): + elif self.data_type.is_float() or self.data_type.is_double(): return self._float_sum() elif self.data_type.is_bool(): sum = 0 @@ -765,25 +752,21 @@ def assign(self, value, mask=None, force_active=False): if type(value) == type(self): if mask is not None: mask.copy_kw(self, value, force_active) + elif self.assert_binary(value): + self._copy_data(value) else: - if self.assert_binary(value): - self._copy_data(value) - else: - raise TypeError("Type / size mismatch") - else: - if mask is not None: - mask.set_kw(self, value, force_active) + raise TypeError("Type / size mismatch") + elif mask is not None: + mask.set_kw(self, value, force_active) + elif self.data_type.is_int(): + if isinstance(value, int): + self._set_int(value) else: - if self.data_type.is_int(): - if isinstance(value, int): - self._set_int(value) - else: - raise TypeError("Type mismatch") - else: - if isinstance(value, int) or isinstance(value, float): - self._set_float(value) - else: - raise TypeError("Only muliplication with scalar supported") + raise TypeError("Type mismatch") + elif isinstance(value, (int, float)): + self._set_float(value) + else: + raise TypeError("Only muliplication with scalar supported") def add(self, other, mask=None, force_active=False): """ @@ -856,13 +839,12 @@ def cutoff(x, limit): else: for index in active_list: self.data_ptr[index] = func(self.data_ptr[index]) + elif arg: + for i in range(len(self)): + self.data_ptr[i] = func(self.data_ptr[i], arg) else: - if arg: - for i in range(len(self)): - self.data_ptr[i] = func(self.data_ptr[i], arg) - else: - for i in range(len(self)): - self.data_ptr[i] = func(self.data_ptr[i]) + for i in range(len(self)): + self.data_ptr[i] = func(self.data_ptr[i]) def equal(self, other): """ @@ -982,7 +964,11 @@ def get_min(self): @property def type(self): - warnings.warn("rd_kw.type is deprecated, use .data_type", DeprecationWarning) + warnings.warn( + "rd_kw.type is deprecated, use .data_type", + DeprecationWarning, + stacklevel=1, + ) return self._get_type() @property @@ -993,26 +979,24 @@ def data_type(self): def type_name(self): return self.data_type.type_name - def type_name(self): - return self.data_type.type_name - def get_rd_type(self): warnings.warn( "ResdataTypeEnum is deprecated. " + "You should instead provide an ResDataType", DeprecationWarning, + stacklevel=1, ) return self._get_type() @property def header(self): - return (self.getName(), len(self), self.typeName()) + return (self.get_name(), len(self), self.type_name) @property def array(self): a = self.data_ptr - if not a == None: + if a != None: a.size = len(self) a.__parent__ = self # Inhibit GC return a @@ -1049,7 +1033,7 @@ def str(self, width=5, max_lines=10, fmt=None): the elements. The implementation of the builtin method __str__() is based on this method. """ - s = "%-8s %8d %-4s\n" % (self.getName(), len(self), self.typeName()) + s = "%-8s %8d %-4s\n" % (self.get_name(), len(self), self.type_name) lines = len(self) // width if not fmt: fmt = self.str_fmt + " " diff --git a/python/resdata/resfile/rd_restart_file.py b/python/resdata/resfile/rd_restart_file.py index 302cdc80d..bc4c86945 100644 --- a/python/resdata/resfile/rd_restart_file.py +++ b/python/resdata/resfile/rd_restart_file.py @@ -1,4 +1,5 @@ from cwrap import BaseCClass + from resdata import FileMode, FileType, ResdataPrototype from resdata.resfile import Resdata3DFile, ResdataFile from resdata.util.util import CTime, monkey_the_camel @@ -104,10 +105,7 @@ def assert_headers(self): else: intehead_kw = self["INTEHEAD"][0] doubhead_kw = self["DOUBHEAD"][0] - if "LOGIHEAD" in self: - logihead_kw = self["LOGIHEAD"][0] - else: - logihead_kw = None + logihead_kw = self["LOGIHEAD"][0] if "LOGIHEAD" in self else None self.rst_headers.append( ResdataRestartHead( diff --git a/python/resdata/rft/__init__.py b/python/resdata/rft/__init__.py index 03686f016..1db117979 100644 --- a/python/resdata/rft/__init__.py +++ b/python/resdata/rft/__init__.py @@ -1,6 +1,6 @@ """ - rd_rft/[ResdataRFTFile , ResdataRFT , ResdataRFTCell]: Loads an RFT/PLT - file, and can afterwords be used to support various queries. +rd_rft/[ResdataRFTFile , ResdataRFT , ResdataRFTCell]: Loads an RFT/PLT + file, and can afterwords be used to support various queries. """ from .well_trajectory import WellTrajectory diff --git a/python/resdata/rft/rd_rft.py b/python/resdata/rft/rd_rft.py index efe6a7568..778ad5539 100644 --- a/python/resdata/rft/rd_rft.py +++ b/python/resdata/rft/rd_rft.py @@ -3,6 +3,7 @@ """ from cwrap import BaseCClass + from resdata import ResdataPrototype from resdata.rft import ResdataPLTCell, ResdataRFTCell from resdata.util.util import CTime, monkey_the_camel @@ -238,10 +239,7 @@ def size(self, well=None, date=None): >>> print "RFTs at 01/01/2010 : %d" % rftFile.size( date = datetime.date( 2010 , 1 , 1 )) """ - if date: - cdate = CTime(date) - else: - cdate = CTime(-1) + cdate = CTime(date) if date else CTime(-1) return self._get_size(well, cdate) diff --git a/python/resdata/rft/well_trajectory.py b/python/resdata/rft/well_trajectory.py index 7af9b9920..20d7722d7 100644 --- a/python/resdata/rft/well_trajectory.py +++ b/python/resdata/rft/well_trajectory.py @@ -1,6 +1,6 @@ import sys -from os.path import isfile from collections import namedtuple +from os.path import isfile TrajectoryPoint = namedtuple( "TrajectoryPoint", @@ -29,8 +29,10 @@ def _parse_point(point): utm_y = float(point[1]) md = float(point[2]) tvd = float(point[3]) - except ValueError: - raise UserWarning("Error: Failed to extract data from line %s\n" % str(point)) + except ValueError as err: + raise UserWarning( + "Error: Failed to extract data from line %s\n" % str(point) + ) from err zone = None if len(point) > 4: zone = point[4] diff --git a/python/resdata/summary/__init__.py b/python/resdata/summary/__init__.py index 44cc63424..f5b03ab2f 100644 --- a/python/resdata/summary/__init__.py +++ b/python/resdata/summary/__init__.py @@ -1,7 +1,7 @@ """ - rd_sum/Summary: This will load summary results; - both data file(s) and the SMSPEC file. The RdSum object can be - used as basis for queries on summary vectors. +rd_sum/Summary: This will load summary results; + both data file(s) and the SMSPEC file. The RdSum object can be + used as basis for queries on summary vectors. """ import resdata.util.util diff --git a/python/resdata/summary/rd_cmp.py b/python/resdata/summary/rd_cmp.py index 9eba124c5..20f41c13c 100644 --- a/python/resdata/summary/rd_cmp.py +++ b/python/resdata/summary/rd_cmp.py @@ -1,4 +1,5 @@ from resdata.util.util import monkey_the_camel + from .rd_sum import Summary @@ -26,16 +27,10 @@ def load_summary(self): self.summary = Summary(self.case) def start_time_equal(self, other): - if self.summary.getDataStartTime() == other.summary.getDataStartTime(): - return True - else: - return False + return self.summary.getDataStartTime() == other.summary.getDataStartTime() def end_time_equal(self, other): - if self.summary.getEndTime() == other.summary.getEndTime(): - return True - else: - return False + return self.summary.getEndTime() == other.summary.getEndTime() def cmp_summary_vector(self, other, key, sample=100): if key in self and key in other: @@ -95,7 +90,7 @@ def end_time_equal(self): return self.test_case.endTimeEqual(self.ref_case) def cmp_summary_vector(self, key, sample=100): - """Will compare the summary vectors according to @key. + r"""Will compare the summary vectors according to @key. The comparison is based on evaluating the integrals: diff --git a/python/resdata/summary/rd_npv.py b/python/resdata/summary/rd_npv.py index f6f0dd8d8..638be8c1c 100644 --- a/python/resdata/summary/rd_npv.py +++ b/python/resdata/summary/rd_npv.py @@ -1,8 +1,9 @@ -import re import datetime import numbers +import re from resdata.util.util import monkey_the_camel + from .rd_sum import Summary @@ -51,8 +52,8 @@ def add_item(self, item): year = int(tmp[2]) date = datetime.date(year, month, day) - except Exception: - raise ValueError("First element was invalid date item") + except Exception as err: + raise ValueError("First element was invalid date item") from err if len(self.dateList): prevItem = self.dateList[-1] @@ -112,14 +113,14 @@ def eval(self, date): class ResdataNPV(object): - sumKeyRE = re.compile("[\[]([\w:,]+)[\]]") + sumKeyRE = re.compile(r"[\[]([\w:,]+)[\]]") def __init__(self, baseCase): sum = Summary(baseCase) if sum: self.baseCase = sum else: - raise Error("Failed to open summary case:%s" % baseCase) + raise OSError("Failed to open summary case:%s" % baseCase) self.expression = None self.keyList = {} self.start = None diff --git a/python/resdata/summary/rd_smspec_node.py b/python/resdata/summary/rd_smspec_node.py index e793b8c03..5460aae7b 100644 --- a/python/resdata/summary/rd_smspec_node.py +++ b/python/resdata/summary/rd_smspec_node.py @@ -52,7 +52,7 @@ def __gt__(self, other): def __eq__(self, other): return self.cmp(other) == 0 - def __hash__(self, other): + def __hash__(self): return hash(self._gen_key1()) @property diff --git a/python/resdata/summary/rd_sum.py b/python/resdata/summary/rd_sum.py index 3cc954c69..e6f489e46 100644 --- a/python/resdata/summary/rd_sum.py +++ b/python/resdata/summary/rd_sum.py @@ -390,8 +390,10 @@ def add_t_step(self, report_step, sim_days): raise TypeError("Parameter report_step should be int, was %r" % report_step) try: float(sim_days) - except TypeError: - raise TypeError("Parameter sim_days should be float, was %r" % sim_days) + except TypeError as err: + raise TypeError( + "Parameter sim_days should be float, was %r" % sim_days + ) from err sim_seconds = sim_days * 24 * 60 * 60 tstep = self._add_tstep(report_step, sim_seconds).setParent(parent=self) @@ -407,6 +409,7 @@ def get_vector(self, key, report_only=False): warnings.warn( "The method get_vector() has been deprecated, use numpy_vector() instead", DeprecationWarning, + stacklevel=1, ) self.assertKeyValid(key) if report_only: @@ -458,6 +461,7 @@ def get_values(self, key, report_only=False): warnings.warn( "The method get_values() has been deprecated - use numpy_vector() instead.", DeprecationWarning, + stacklevel=1, ) if self.has_key(key): key_index = self._get_general_var_index(key) @@ -645,9 +649,10 @@ def _compile_headers_list( pass elif var_type == SummaryVarType.RD_SMSPEC_REGION_VAR: num = int(lst[1]) - elif var_type == SummaryVarType.RD_SMSPEC_GROUP_VAR: - wgname = lst[1] - elif var_type == SummaryVarType.RD_SMSPEC_WELL_VAR: + elif var_type in ( + SummaryVarType.RD_SMSPEC_GROUP_VAR, + SummaryVarType.RD_SMSPEC_WELL_VAR, + ): wgname = lst[1] elif var_type == SummaryVarType.RD_SMSPEC_SEGMENT_VAR: kw, wgname, num = lst @@ -799,6 +804,7 @@ def get_last_value(self, key): warnings.warn( "The function get_last_value() is deprecated, use last_value() instead", DeprecationWarning, + stacklevel=1, ) return self.last_value(key) @@ -852,10 +858,7 @@ def __len__(self): return self._data_length() def __contains__(self, key): - if self._has_key(key): - return True - else: - return False + return self._has_key(key) def assert_key_valid(self, key): if not key in self: @@ -873,6 +876,7 @@ def __getitem__(self, key): warnings.warn( "The method the [] operator will change behaviour in the future. It will then return a plain numpy vector. You are advised to change to use the numpy_vector() method right away", DeprecationWarning, + stacklevel=1, ) return self.get_vector(key) @@ -968,8 +972,7 @@ def time_range( if isinstance(start, datetime.date): start = datetime.datetime(start.year, start.month, start.day, 0, 0, 0) - if start < self.getDataStartTime(): - start = self.getDataStartTime() + start = max(start, self.getDataStartTime()) if end is None: end = self.getEndTime() @@ -977,8 +980,7 @@ def time_range( if isinstance(end, datetime.date): end = datetime.datetime(end.year, end.month, end.day, 0, 0, 0) - if end > self.getEndTime(): - end = self.getEndTime() + end = min(end, self.getEndTime()) if end < start: raise ValueError("Invalid time interval start after end") @@ -988,7 +990,7 @@ def time_range( range_start = start range_end = end - if not timeUnit == "d": + if timeUnit != "d": year1 = start.year year2 = end.year month1 = start.month @@ -1096,13 +1098,11 @@ def get_interp_vector(self, key, days_list=None, date_list=None): vector = np.zeros(len(days_list)) sim_length = self.sim_length sim_start = self.first_day - index = 0 - for days in days_list: + for index, days in enumerate(days_list): if (days >= sim_start) and (days <= sim_length): vector[index] = self._get_general_var_from_sim_days(days, key) else: raise ValueError("Invalid days value") - index += 1 elif date_list: start_time = self.data_start end_time = self.end_date @@ -1265,6 +1265,7 @@ def mpl_dates(self): warnings.warn( "The mpl_dates property has been deprecated - use numpy_dates instead", DeprecationWarning, + stacklevel=1, ) return self.get_mpl_dates(False) @@ -1281,6 +1282,7 @@ def get_mpl_dates(self, report_only=False): warnings.warn( "The get_mpl_dates( ) method has been deprecated - use numpy_dates instead", DeprecationWarning, + stacklevel=1, ) if report_only: return [date2num(dt) for dt in self.report_dates] @@ -1486,7 +1488,7 @@ def solve_dates(self, key, value, rates_clamp_lower=True): return [x.datetime() for x in self._solve_dates(key, value, rates_clamp_lower)] def solve_days(self, key, value, rates_clamp_lower=True): - """Will solve the equation vector[@key] == value. + r"""Will solve the equation vector[@key] == value. This method will solve find tha approximate simulation days where the vector @key is equal @value. The method will return diff --git a/python/resdata/summary/rd_sum_vector.py b/python/resdata/summary/rd_sum_vector.py index 8bdf0ba8b..362ab1217 100644 --- a/python/resdata/summary/rd_sum_vector.py +++ b/python/resdata/summary/rd_sum_vector.py @@ -1,5 +1,7 @@ from __future__ import print_function + import warnings + from .rd_sum_node import SummaryNode @@ -29,6 +31,7 @@ def __init__(self, parent, key, report_only=False): warnings.warn( "The report_only flag to the SummaryVector will be removed", DeprecationWarning, + stacklevel=1, ) self.__dates = parent.get_dates(report_only) @@ -98,6 +101,7 @@ def mpl_dates(self): warnings.warn( "The mpl_dates property has been deprecated - use numpy_dates instead", DeprecationWarning, + stacklevel=1, ) return self.parent.get_mpl_dates(self.report_only) diff --git a/python/resdata/util/test/extended_testcase.py b/python/resdata/util/test/extended_testcase.py index d1c1e1caf..a7656cc9a 100644 --- a/python/resdata/util/test/extended_testcase.py +++ b/python/resdata/util/test/extended_testcase.py @@ -130,8 +130,8 @@ def assertDirectoryDoesNotExist(self, path): self.fail("The directory: %s exists!" % path) def __filesAreEqual(self, first, second): - buffer1 = open(first, "rb").read() - buffer2 = open(second, "rb").read() + buffer1 = open(first, "rb").read() # noqa: SIM115 + buffer2 = open(second, "rb").read() # noqa: SIM115 return buffer1 == buffer2 @@ -198,7 +198,4 @@ def requireVersion(major, minor, micro="git"): required_version = Version(major, minor, micro) current_version = Version.currentVersion() - if required_version < current_version: - return True - else: - return False + return required_version < current_version diff --git a/python/resdata/util/test/mock/rd_sum_mock.py b/python/resdata/util/test/mock/rd_sum_mock.py index 0b9d13ad1..a5ee172d6 100644 --- a/python/resdata/util/test/mock/rd_sum_mock.py +++ b/python/resdata/util/test/mock/rd_sum_mock.py @@ -1,4 +1,5 @@ import datetime + from resdata.summary import Summary @@ -15,7 +16,7 @@ def createSummary( num_report_step=5, num_mini_step=10, dims=(20, 10, 5), - func_table={}, + func_table={}, # noqa: B006 restart_case=None, restart_step=-1, ): diff --git a/python/resdata/util/test/path_context.py b/python/resdata/util/test/path_context.py index d042f1d01..5d622265b 100644 --- a/python/resdata/util/test/path_context.py +++ b/python/resdata/util/test/path_context.py @@ -23,9 +23,8 @@ def __init__(self, path, store=False): break os.makedirs(path) - else: - if not self.store: - raise OSError("Entry %s already exists" % path) + elif not self.store: + raise OSError("Entry %s already exists" % path) os.chdir(path) def __exit__(self, exc_type, exc_val, exc_tb): diff --git a/python/resdata/util/test/resdata_test_runner.py b/python/resdata/util/test/resdata_test_runner.py index d6e0c60e6..6684b9dc9 100644 --- a/python/resdata/util/test/resdata_test_runner.py +++ b/python/resdata/util/test/resdata_test_runner.py @@ -19,7 +19,7 @@ def findTestsInDirectory(path, recursive=True, pattern="test*.py"): loader = TestLoader() test_suite = loader.discover(path, pattern=pattern) - for root, dirnames, filenames in os.walk(path): + for root, dirnames, _filenames in os.walk(path): for directory in dirnames: test_suite.addTests( ResdataTestRunner.findTestsInDirectory( diff --git a/python/resdata/util/test/source_enumerator.py b/python/resdata/util/test/source_enumerator.py index 66087830d..aca52b04a 100644 --- a/python/resdata/util/test/source_enumerator.py +++ b/python/resdata/util/test/source_enumerator.py @@ -6,7 +6,7 @@ class SourceEnumerator(object): @classmethod def removeComments(cls, code_string): code_string = re.sub( - re.compile("/\*.*?\*/", re.DOTALL), "", code_string + re.compile(r"/\*.*?\*/", re.DOTALL), "", code_string ) # remove all occurance streamed comments (/*COMMENT */) from string code_string = re.sub( re.compile("//.*?\n"), "", code_string @@ -20,7 +20,7 @@ def findEnum(cls, enum_name, full_source_file_path): text = SourceEnumerator.removeComments(text) - enum_pattern = re.compile("typedef\s+enum\s+\{(.*?)\}\s*(\w+?);", re.DOTALL) + enum_pattern = re.compile(r"typedef\s+enum\s+\{(.*?)\}\s*(\w+?);", re.DOTALL) for enum in enum_pattern.findall(text): if enum[1] == enum_name: @@ -32,7 +32,7 @@ def findEnum(cls, enum_name, full_source_file_path): def findEnumerators(cls, enum_name, source_file): enum_text = SourceEnumerator.findEnum(enum_name, source_file) - enumerator_pattern = re.compile("(\w+?)\s*?=\s*?(\d+)") + enumerator_pattern = re.compile(r"(\w+?)\s*?=\s*?(\d+)") enumerators = [] for enumerator in enumerator_pattern.findall(enum_text): diff --git a/python/resdata/util/test/test_run.py b/python/resdata/util/test/test_run.py index 59fad8ffe..6b9955e7c 100644 --- a/python/resdata/util/test/test_run.py +++ b/python/resdata/util/test/test_run.py @@ -17,7 +17,7 @@ class TestRun(object): default_ert_version = "stable" default_path_prefix = None - def __init__(self, config_file, args=[], name=None): + def __init__(self, config_file, args=[], name=None): # noqa: B006 if os.path.exists(config_file) and os.path.isfile(config_file): self.parseArgs(args) self.__ert_cmd = TestRun.default_ert_cmd diff --git a/python/resdata/util/util/__init__.py b/python/resdata/util/util/__init__.py index a3b20cb43..0b03cb91c 100644 --- a/python/resdata/util/util/__init__.py +++ b/python/resdata/util/util/__init__.py @@ -72,7 +72,7 @@ def __user_warning(msg): def __dev_warning(msg): - warnings.warn(msg, DeprecationWarning) + warnings.warn(msg, DeprecationWarning, stacklevel=1) def __hard_warning(msg): diff --git a/python/resdata/util/util/ctime.py b/python/resdata/util/util/ctime.py index b22114919..655cd70eb 100644 --- a/python/resdata/util/util/ctime.py +++ b/python/resdata/util/util/ctime.py @@ -3,6 +3,7 @@ import time from cwrap import BaseCValue + from resdata import ResdataPrototype @@ -16,7 +17,7 @@ class CTime(BaseCValue): def __init__(self, value): if isinstance(value, int): - value = value + pass elif isinstance(value, CTime): value = value.value() elif isinstance(value, datetime.datetime): diff --git a/python/resdata/util/util/lookup_table.py b/python/resdata/util/util/lookup_table.py index a1c6a4e2c..45fcb4657 100644 --- a/python/resdata/util/util/lookup_table.py +++ b/python/resdata/util/util/lookup_table.py @@ -1,4 +1,5 @@ from cwrap import BaseCClass + from resdata import ResdataPrototype @@ -101,12 +102,11 @@ def interp(self, x): "Interpolate argument:%g is outside valid interval: [%g,%g]" % (x, self.getMinArg(), self.getMaxArg()) ) - elif x > self.getMaxArg(): - if not self.hasUpperLimit(): - raise ValueError( - "Interpolate argument:%g is outside valid interval: [%g,%g]" - % (x, self.getMinArg(), self.getMaxArg()) - ) + elif x > self.getMaxArg() and not self.hasUpperLimit(): + raise ValueError( + "Interpolate argument:%g is outside valid interval: [%g,%g]" + % (x, self.getMinArg(), self.getMaxArg()) + ) return self._interp(x) diff --git a/python/resdata/util/util/thread_pool.py b/python/resdata/util/util/thread_pool.py index 52b94998c..bbfd3f6bc 100644 --- a/python/resdata/util/util/thread_pool.py +++ b/python/resdata/util/util/thread_pool.py @@ -1,7 +1,7 @@ import multiprocessing -from threading import Thread import time import traceback +from threading import Thread class Task(Thread): @@ -82,11 +82,7 @@ def taskCount(self): return len(self.__task_list) def __allTasksFinished(self): - for task in self.__task_list: - if not task.isDone(): - return False - - return True + return all(task.isDone() for task in self.__task_list) def runningCount(self): count = 0 @@ -143,8 +139,4 @@ def join(self): ) def hasFailedTasks(self): - for task in self.__task_list: - if task.hasFailed(): - return True - - return False + return any(task.hasFailed() for task in self.__task_list) diff --git a/python/resdata/util/util/time_vector.py b/python/resdata/util/util/time_vector.py index fbd49ee2e..0839a7596 100644 --- a/python/resdata/util/util/time_vector.py +++ b/python/resdata/util/util/time_vector.py @@ -120,16 +120,16 @@ def __init__(self, default_value=None, initial_size=0): else: try: default = CTime(default_value) - except: + except Exception as err: raise ValueError( "default value invalid - must be type ctime() or date/datetime" - ) + ) from err super(TimeVector, self).__init__(default, initial_size) @classmethod def parseTimeUnit(cls, deltaString): - deltaRegexp = re.compile("(?P\d*)(?P[dmy])", re.IGNORECASE) + deltaRegexp = re.compile(r"(?P\d*)(?P[dmy])", re.IGNORECASE) matchObj = deltaRegexp.match(deltaString) if matchObj: try: diff --git a/python/resdata/util/util/vector_template.py b/python/resdata/util/util/vector_template.py index 7b2e8a380..d42db20f3 100644 --- a/python/resdata/util/util/vector_template.py +++ b/python/resdata/util/util/vector_template.py @@ -61,10 +61,7 @@ def __bool__(self): """ Will evaluate to False for empty vector. """ - if len(self) == 0: - return False - else: - return True + return len(self) != 0 def __nonzero__(self): return self.__bool__() @@ -266,13 +263,12 @@ def __IADD(self, delta, add): "Incompatible sizes for add self:%d other:%d" % (len(self), len(delta)) ) + elif isinstance(delta, (int, float)): + if not add: + delta *= -1 + self._shift(delta) else: - if isinstance(delta, int) or isinstance(delta, float): - if not add: - delta *= -1 - self._shift(delta) - else: - raise TypeError("delta has wrong type:%s " % type(delta)) + raise TypeError("delta has wrong type:%s " % type(delta)) return self @@ -338,11 +334,10 @@ def __imul__(self, factor): "Incompatible sizes for mul self:%d other:%d" % (len(self), len(factor)) ) + elif isinstance(factor, (int, float)): + self._scale(factor) else: - if isinstance(factor, int) or isinstance(factor, float): - self._scale(factor) - else: - raise TypeError("factor has wrong type:%s " % type(factor)) + raise TypeError("factor has wrong type:%s " % type(factor)) return self @@ -355,7 +350,7 @@ def __rmul__(self, factor): return self.__mul__(factor) def __div__(self, divisor): - if isinstance(divisor, int) or isinstance(divisor, float): + if isinstance(divisor, (int, float)): copy = self._alloc_copy() copy._div(divisor) return copy @@ -396,11 +391,10 @@ def assign(self, value): if type(self) == type(value): # This is a copy operation self._memcpy(value) + elif isinstance(value, (int, float)): + self._assign(value) else: - if isinstance(value, int) or isinstance(value, float): - self._assign(value) - else: - raise TypeError("Value has wrong type") + raise TypeError("Value has wrong type") def __len__(self): """ diff --git a/python/resdata/util/util/version.py b/python/resdata/util/util/version.py index cd32d6e71..5482ee93d 100644 --- a/python/resdata/util/util/version.py +++ b/python/resdata/util/util/version.py @@ -91,11 +91,10 @@ def getBuildTime(self): def getGitCommit(self, short=False): if self.git_commit is None: return "???????" + elif short: + return self.git_commit[0:8] else: - if short: - return self.git_commit[0:8] - else: - return self.git_commit + return self.git_commit class ResdataVersion(Version): diff --git a/python/resdata/well/well_state.py b/python/resdata/well/well_state.py index f0962bd3d..cb10dfffa 100644 --- a/python/resdata/well/well_state.py +++ b/python/resdata/well/well_state.py @@ -163,10 +163,7 @@ def hasSegmentData(self): def __repr__(self): name = self.name() - if name: - name = "%s" % name - else: - name = "[no name]" + name = "%s" % name if name else "[no name]" msw = " (multi segment)" if self.isMultiSegmentWell() else "" wn = str(self.wellNumber()) type_ = self.wellType() diff --git a/python/tests/__init__.py b/python/tests/__init__.py index 709e3de3f..f83881a4e 100644 --- a/python/tests/__init__.py +++ b/python/tests/__init__.py @@ -61,14 +61,13 @@ def equinor_test(): """ def decorator(test_item): - if not isinstance(test_item, type): - if not ResdataTest.EQUINOR_DATA: + if not isinstance(test_item, type) and not ResdataTest.EQUINOR_DATA: - @functools.wraps(test_item) - def skip_wrapper(*args, **kwargs): - raise SkipTest("Missing Equinor testdata") + @wraps(test_item) + def skip_wrapper(*args, **kwargs): + raise SkipTest("Missing Equinor testdata") - test_item = skip_wrapper + test_item = skip_wrapper if not ResdataTest.EQUINOR_DATA: test_item.__unittest_skip__ = True diff --git a/python/tests/geometry_tests/test_surface.py b/python/tests/geometry_tests/test_surface.py index e23691a07..8d6fa0e58 100644 --- a/python/tests/geometry_tests/test_surface.py +++ b/python/tests/geometry_tests/test_surface.py @@ -55,8 +55,8 @@ def test_create_new(self): self.assertNotEqual(s, small) idx = 0 - for i in range(nx): - for j in range(ny): + for _i in range(nx): + for _j in range(ny): s[idx] = small[idx] idx += 1 self.assertEqual(s, small) @@ -164,7 +164,7 @@ def test_ops(self): def test_ops2(self): s0 = Surface(self.surface_small) surface_list = [] - for i in range(10): + for _i in range(10): s = s0.copy() for j in range(len(s)): s[j] = random.random() diff --git a/python/tests/rd_tests/test_fault_blocks.py b/python/tests/rd_tests/test_fault_blocks.py index 0fc5734c9..221a98bd6 100644 --- a/python/tests/rd_tests/test_fault_blocks.py +++ b/python/tests/rd_tests/test_fault_blocks.py @@ -359,7 +359,6 @@ def test_add_polyline_barrier2(self): ((4, 0), (4, 1)), ((6, 0), (6, 1)), ((8, 0), (8, 1)), - # ((8, 1), (9, 1)), ((8, 3), (9, 3)), ((8, 5), (9, 5)), diff --git a/python/tests/rd_tests/test_faults.py b/python/tests/rd_tests/test_faults.py index abf5dab6a..31d1fbc45 100644 --- a/python/tests/rd_tests/test_faults.py +++ b/python/tests/rd_tests/test_faults.py @@ -94,7 +94,7 @@ def test_empty_fault(self): f = Fault(self.grid, "NAME") self.assertEqual("NAME", f.getName()) - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 g = f["Key"] def test_empty_faultLine(self): @@ -409,7 +409,7 @@ def test_iter(self): faults = FaultCollection(self.grid, self.faults1, self.faults2) self.assertEqual(7, len(faults)) c = 0 - for f in faults: + for _f in faults: c += 1 self.assertEqual(c, len(faults)) diff --git a/python/tests/rd_tests/test_fortio.py b/python/tests/rd_tests/test_fortio.py index e2161a0df..8015faf78 100755 --- a/python/tests/rd_tests/test_fortio.py +++ b/python/tests/rd_tests/test_fortio.py @@ -57,9 +57,8 @@ def test_truncate(self): kw2.fwrite(f) # Truncate file in read mode; should fail hard. - with openFortIO("file") as f: - with self.assertRaises(IOError): - f.truncate() + with openFortIO("file") as f, self.assertRaises(IOError): + f.truncate() with openFortIO("file", mode=FortIO.READ_AND_WRITE_MODE) as f: f.seek(pos1) diff --git a/python/tests/rd_tests/test_geertsma.py b/python/tests/rd_tests/test_geertsma.py index 712541a65..de8864998 100644 --- a/python/tests/rd_tests/test_geertsma.py +++ b/python/tests/rd_tests/test_geertsma.py @@ -135,34 +135,6 @@ def test_geertsma_kernel_seabed(): ) np.testing.assert_almost_equal(dz, 5.819790154474284e-08) - @staticmethod - def test_geertsma_kernel_seabed(): - grid = Grid.createRectangular(dims=(1, 1, 1), dV=(50, 50, 50)) - with TestAreaContext("Subsidence"): - p1 = [1] - create_restart(grid, "TEST", p1) - create_init(grid, "TEST") - - init = ResdataFile("TEST.INIT") - restart_file = ResdataFile("TEST.UNRST") - - restart_view1 = restart_file.restartView(sim_time=datetime.date(2000, 1, 1)) - - subsidence = ResdataSubsidence(grid, init) - subsidence.add_survey_PRESSURE("S1", restart_view1) - - youngs_modulus = 5e8 - poisson_ratio = 0.3 - seabed = 300 - above = 100 - topres = 2000 - receiver = (1000, 1000, topres - seabed - above) - - dz = subsidence.evalGeertsma( - "S1", None, receiver, youngs_modulus, poisson_ratio, seabed - ) - np.testing.assert_almost_equal(dz, 5.819790154474284e-08) - def test_geertsma_rporv_kernel_2_source_points_2_vintages(self): grid = Grid.createRectangular(dims=(2, 1, 1), dV=(100, 100, 100)) diff --git a/python/tests/rd_tests/test_grid.py b/python/tests/rd_tests/test_grid.py index 4d8e734c1..09529f5bb 100644 --- a/python/tests/rd_tests/test_grid.py +++ b/python/tests/rd_tests/test_grid.py @@ -306,7 +306,7 @@ def test_all_iters(self): self.assertTrue(c.active) self.assertEqual(cnt, 4160) - cnt = len([c for c in grid.cells()]) + cnt = len(list(grid.cells())) self.assertEqual(cnt, len(grid)) def test_repr_and_name(self): diff --git a/python/tests/rd_tests/test_grid_equinor.py b/python/tests/rd_tests/test_grid_equinor.py index d433fa8a3..a8ecc05c2 100755 --- a/python/tests/rd_tests/test_grid_equinor.py +++ b/python/tests/rd_tests/test_grid_equinor.py @@ -171,16 +171,15 @@ def test_grdecl_load(self): f2.write("SPECGRID\n") f2.write(" 10 10 10 'F' /\n") - with openResdataFile("G.EGRID") as f: - with copen("grid.grdecl", "a") as f2: - coord_kw = f["COORD"][0] - coord_kw.write_grdecl(f2) + with openResdataFile("G.EGRID") as f, copen("grid.grdecl", "a") as f2: + coord_kw = f["COORD"][0] + coord_kw.write_grdecl(f2) - zcorn_kw = f["ZCORN"][0] - zcorn_kw.write_grdecl(f2) + zcorn_kw = f["ZCORN"][0] + zcorn_kw.write_grdecl(f2) - actnum_kw = f["ACTNUM"][0] - actnum_kw.write_grdecl(f2) + actnum_kw = f["ACTNUM"][0] + actnum_kw.write_grdecl(f2) g2 = Grid.loadFromGrdecl("grid.grdecl") self.assertTrue(g1.equal(g2)) @@ -252,7 +251,7 @@ def test_boundingBox(self): def test_num_active_large_memory(self): case = self.createTestPath("Equinor/ECLIPSE/Gurbat/ECLIPSE") vecList = [] - for i in range(12500): + for _i in range(12500): vec = DoubleVector() vec[81920] = 0 vecList.append(vec) diff --git a/python/tests/rd_tests/test_grid_generator.py b/python/tests/rd_tests/test_grid_generator.py index 54343bc2e..0b2adcc32 100644 --- a/python/tests/rd_tests/test_grid_generator.py +++ b/python/tests/rd_tests/test_grid_generator.py @@ -64,15 +64,15 @@ def test_extract_grid_decomposition_change(self): coord = list(GridGen.create_coord(dims, (1, 1, 1))) ijk_bounds = generate_ijk_bounds(dims) - for ijk_bounds in ijk_bounds: - if decomposition_preserving(ijk_bounds): - GridGen.extract_subgrid_data(dims, coord, zcorn, ijk_bounds) + for ijk_bound in ijk_bounds: + if decomposition_preserving(ijk_bound): + GridGen.extract_subgrid_data(dims, coord, zcorn, ijk_bound) else: with self.assertRaises(ValueError): - GridGen.extract_subgrid_data(dims, coord, zcorn, ijk_bounds) + GridGen.extract_subgrid_data(dims, coord, zcorn, ijk_bound) GridGen.extract_subgrid_data( - dims, coord, zcorn, ijk_bounds, decomposition_change=True + dims, coord, zcorn, ijk_bound, decomposition_change=True ) def test_extract_grid_invalid_bounds(self): diff --git a/python/tests/rd_tests/test_npv.py b/python/tests/rd_tests/test_npv.py index d69fd6026..353f988c6 100644 --- a/python/tests/rd_tests/test_npv.py +++ b/python/tests/rd_tests/test_npv.py @@ -3,11 +3,6 @@ import datetime import math -try: - from unittest2 import skipIf, skipUnless, skipIf -except ImportError: - from unittest import skipIf, skipUnless, skipIf - from resdata.summary import Summary from resdata.summary import ResdataNPV, NPVPriceVector @@ -39,7 +34,7 @@ def setUp(self): self.case = self.createTestPath(case) def test_create(self): - with self.assertRaises(Exception): + with self.assertRaises(OSError): npv = ResdataNPV("/does/not/exist") npv = ResdataNPV(self.case) diff --git a/python/tests/rd_tests/test_rd_cmp.py b/python/tests/rd_tests/test_rd_cmp.py index 13f1d2029..152cdb762 100644 --- a/python/tests/rd_tests/test_rd_cmp.py +++ b/python/tests/rd_tests/test_rd_cmp.py @@ -43,7 +43,7 @@ def test_wells(self): rd_cmp = ResdataCmp(self.root1, self.root1) wells = rd_cmp.testWells() - well_set = set(["OP_1", "OP_2", "OP_3", "OP_4", "OP_5", "WI_1", "WI_2", "WI_3"]) + well_set = {"OP_1", "OP_2", "OP_3", "OP_4", "OP_5", "WI_1", "WI_2", "WI_3"} self.assertEqual(len(wells), len(well_set)) for well in wells: self.assertTrue(well in well_set) diff --git a/python/tests/rd_tests/test_rd_kw.py b/python/tests/rd_tests/test_rd_kw.py index 4ff7b17e8..914cfb2e7 100644 --- a/python/tests/rd_tests/test_rd_kw.py +++ b/python/tests/rd_tests/test_rd_kw.py @@ -2,7 +2,6 @@ import random import warnings import cwrap -import random from resdata import ResDataType, ResdataTypeEnum, FileMode from resdata.resfile import ResdataKW, ResdataFile, FortIO, openFortIO @@ -68,10 +67,9 @@ def kw_test(self, data_type, data, fmt): kw.fprintf_data(file1, fmt) file1.close() - file2 = open(name2, "w") - for d in data: - file2.write(fmt % d) - file2.close() + with open(name2, "w") as file2: + for d in data: + file2.write(fmt % d) self.assertFilesAreEqual(name1, name2) self.assertEqual(kw.data_type, data_type) @@ -141,10 +139,8 @@ def test_kw_write(self): data = [random.random() for i in range(10000)] kw = ResdataKW("TEST", len(data), ResDataType.RD_DOUBLE) - i = 0 - for d in data: + for i, d in enumerate(data): kw[i] = d - i += 1 pfx = "ResdataKW(" self.assertEqual(pfx, repr(kw)[: len(pfx)]) @@ -186,12 +182,12 @@ def test_fprintf_data(self): kw.fprintf_data(fileH) fileH.close() - fileH = open("test", "r") - data = [] - for line in fileH.readlines(): - tmp = line.split() - for elm in tmp: - data.append(int(elm)) + with open("test", "r") as fileH: + data = [] + for line in fileH.readlines(): + tmp = line.split() + for elm in tmp: + data.append(int(elm)) for v1, v2 in zip(data, kw): self.assertEqual(v1, v2) @@ -426,7 +422,7 @@ def test_resize(self): def test_typename(self): kw = ResdataKW("KW", 100, ResDataType.RD_INT) - self.assertEqual(kw.typeName(), "INTE") + self.assertEqual(kw.type_name, "INTE") def test_string_alloc(self): kw = ResdataKW("KW", 10, ResDataType.RD_STRING(30)) diff --git a/python/tests/rd_tests/test_rd_sum.py b/python/tests/rd_tests/test_rd_sum.py index e0dac8b7d..26b537e77 100644 --- a/python/tests/rd_tests/test_rd_sum.py +++ b/python/tests/rd_tests/test_rd_sum.py @@ -7,6 +7,7 @@ from cwrap import open as copen from hypothesis import assume, given from pandas.testing import assert_frame_equal + from resdata.resfile import FortIO, ResdataKW, openFortIO, openResdataFile from resdata.summary import Summary, SummaryKeyWordVector from resdata.util.test import TestAreaContext @@ -135,9 +136,8 @@ def test_missing_unsmry_keyword(self): with openFortIO("ECLIPSE.UNSMRY", mode=FortIO.WRITE_MODE) as f: c = 0 for kw in kw_list: - if kw.getName() == "PARAMS": - if c % 5 == 0: - continue + if kw.getName() == "PARAMS" and c % 5 == 0: + continue c += 1 kw.fwrite(f) diff --git a/python/tests/rd_tests/test_rd_type.py b/python/tests/rd_tests/test_rd_type.py index adad89d9a..0ee263999 100644 --- a/python/tests/rd_tests/test_rd_type.py +++ b/python/tests/rd_tests/test_rd_type.py @@ -120,7 +120,7 @@ def test_equals(self): self.assertTrue(a.is_equal(b)) self.assertEqual(a, b) - for otype, osize in set(test_base) - set([(rd_type, elem_size)]): + for otype, osize in set(test_base) - {rd_type, elem_size}: self.assertFalse(a.is_equal(ResDataType(otype, osize))) self.assertNotEqual(a, ResDataType(otype, osize)) @@ -132,10 +132,10 @@ def test_hash(self): all_types.add(ResDataType(rd_type, elem_size)) self.assertEqual(index + 1, len(all_types)) - for index, (rd_type, elem_size) in enumerate(test_base): + for _index, (rd_type, elem_size) in enumerate(test_base): all_types.add(ResDataType(rd_type, elem_size)) - for index, rd_type in enumerate(get_const_size_types()): + for _index, rd_type in enumerate(get_const_size_types()): all_types.add(ResDataType(rd_type)) self.assertEqual(len(test_base), len(all_types)) diff --git a/python/tests/rd_tests/test_rd_util.py b/python/tests/rd_tests/test_rd_util.py index 7343abb10..915624546 100644 --- a/python/tests/rd_tests/test_rd_util.py +++ b/python/tests/rd_tests/test_rd_util.py @@ -41,7 +41,7 @@ def test_get_start_date_reads_from_start_kw_in_data_file(tmp_path): data_file = tmp_path / "dfile" data_file.write_text( dedent( - f"""\ + """\ START 4 Apr 2024 / """ diff --git a/python/tests/rd_tests/test_region_equinor.py b/python/tests/rd_tests/test_region_equinor.py index dc84dd95c..2f58afd38 100755 --- a/python/tests/rd_tests/test_region_equinor.py +++ b/python/tests/rd_tests/test_region_equinor.py @@ -126,7 +126,7 @@ def test_slice(self): OK = False self.assertTrue(OK) - self.assertTrue(2 * 3 * 6 == len(reg.getGlobalList())) + self.assertTrue(len(reg.getGlobalList()) == 2 * 3 * 6) def test_index_list(self): reg = ResdataRegion(self.grid, False) diff --git a/python/tests/rd_tests/test_sum.py b/python/tests/rd_tests/test_sum.py index 198f4627e..ade663f10 100644 --- a/python/tests/rd_tests/test_sum.py +++ b/python/tests/rd_tests/test_sum.py @@ -4,22 +4,10 @@ import os.path import shutil import stat -import datetime +from contextlib import contextmanager import cwrap - - -def assert_frame_equal(a, b): - if not a.equals(b): - raise AssertionError("Expected dataframes to be equal") - - -try: - from pandas.testing import assert_frame_equal -except ImportError: - pass - -from contextlib import contextmanager +from pandas.testing import assert_frame_equal from resdata import ResDataType, UnitSystem from resdata.resfile import FortIO, ResdataFile, ResdataKW, openFortIO @@ -204,7 +192,7 @@ def test_csv_export(self): with TestAreaContext("resdata/csv"): case.exportCSV("file.csv", sep=sep) self.assertTrue(os.path.isfile("file.csv")) - input_file = csv.DictReader(open("file.csv"), delimiter=sep) + input_file = csv.DictReader(open("file.csv"), delimiter=sep) # noqa: SIM115 for row in input_file: self.assertIn("DAYS", row) self.assertIn("DATE", row) @@ -218,7 +206,7 @@ def test_csv_export(self): with TestAreaContext("resdata/csv"): case.exportCSV("file.csv", keys=["FOPT"], sep=sep) self.assertTrue(os.path.isfile("file.csv")) - input_file = csv.DictReader(open("file.csv"), delimiter=sep) + input_file = csv.DictReader(open("file.csv"), delimiter=sep) # noqa: SIM115 for row in input_file: self.assertIn("DAYS", row) self.assertIn("DATE", row) @@ -660,7 +648,7 @@ def test_load_case(self): fopr = case.numpy_vector("FOPR") for time_index, value in enumerate(fopr): - self.assertEqual(fopr[time_index], value) + self.assertEqual(fopr[time_index], value) # noqa: PLR1736 def test_load_case_lazy_and_eager(self): path = os.path.join(self.TESTDATA_ROOT, "local/ECLIPSE/cp_simple3/SHORT.UNSMRY") @@ -718,7 +706,7 @@ def test_resample_extrapolate(self): upper_extrapolation=True, ) - for key in rd_sum.keys(): + for key in rd_sum: self.assertIn(key, resampled) self.assertEqual( @@ -746,9 +734,7 @@ def test_resample_extrapolate(self): key_rate = "FOPR" for time_index, t in enumerate(time_points): - if t < rd_sum.get_data_start_time(): - self.assertFloatEqual(resampled.iget(key_rate, time_index), 0) - elif t > rd_sum.get_end_time(): + if t < rd_sum.get_data_start_time() or t > rd_sum.get_end_time(): self.assertFloatEqual(resampled.iget(key_rate, time_index), 0) else: self.assertFloatEqual( diff --git a/python/tests/rd_tests/test_sum_equinor.py b/python/tests/rd_tests/test_sum_equinor.py index 0f46400dd..fb0f900ff 100755 --- a/python/tests/rd_tests/test_sum_equinor.py +++ b/python/tests/rd_tests/test_sum_equinor.py @@ -1,8 +1,6 @@ import os import datetime -from unittest import skipIf, skipUnless, skipIf - from resdata.resfile import ResdataFile from resdata.summary import Summary from resdata import UnitSystem @@ -109,17 +107,17 @@ def test_wells(self): wells = self.rd_sum.wells() wells.sort() self.assertListEqual( - [well for well in wells], + list(wells), ["OP_1", "OP_2", "OP_3", "OP_4", "OP_5", "WI_1", "WI_2", "WI_3"], ) wells = self.rd_sum.wells(pattern="*_3") wells.sort() - self.assertListEqual([well for well in wells], ["OP_3", "WI_3"]) + self.assertListEqual(list(wells), ["OP_3", "WI_3"]) groups = self.rd_sum.groups() groups.sort() - self.assertListEqual([group for group in groups], ["GMWIN", "OP", "WI"]) + self.assertListEqual(list(groups), ["GMWIN", "OP", "WI"]) def test_last(self): last = self.rd_sum.get_last("FOPT") @@ -283,7 +281,7 @@ def test_stringlist_reference(self): sum = Summary(self.case) wells = sum.wells() self.assertListEqual( - [well for well in wells], + list(wells), ["OP_1", "OP_2", "OP_3", "OP_4", "OP_5", "WI_1", "WI_2", "WI_3"], ) self.assertIsInstance(wells, StringList) @@ -475,10 +473,7 @@ def test_ix_case(self): self.assertTrue( "HWELL_PROD" - in [ - intersect_summary.smspec_node(key).wgname - for key in intersect_summary.keys() - ] + in [intersect_summary.smspec_node(key).wgname for key in intersect_summary] ) eclipse_summary = Summary( @@ -538,7 +533,7 @@ def test_resample(self): time_points.append(CTime(end_time)) resampled = self.rd_sum.resample("OUTPUT_CASE", time_points) - for key in self.rd_sum.keys(): + for key in self.rd_sum: self.assertIn(key, resampled) self.assertEqual( diff --git a/python/tests/test_bin.py b/python/tests/test_bin.py index 40fcf5f29..976b75b20 100644 --- a/python/tests/test_bin.py +++ b/python/tests/test_bin.py @@ -30,6 +30,6 @@ ], ) def test_exec(name: str, returncode: int, stderr: str) -> None: - status = subprocess.run([name], stderr=subprocess.PIPE) + status = subprocess.run([name], stderr=subprocess.PIPE, check=False) assert status.returncode == returncode assert stderr in status.stderr diff --git a/python/tests/util_tests/test_path_context.py b/python/tests/util_tests/test_path_context.py index acd181ddc..0723be0cb 100644 --- a/python/tests/util_tests/test_path_context.py +++ b/python/tests/util_tests/test_path_context.py @@ -1,4 +1,5 @@ import os + from resdata.util.test import PathContext, TestAreaContext from tests import ResdataTest @@ -8,16 +9,14 @@ def test_error(self): with TestAreaContext("pathcontext"): # Test failure on creating PathContext with an existing path os.makedirs("path/1") - with self.assertRaises(OSError): - with PathContext("path/1"): - pass + with self.assertRaises(OSError), PathContext("path/1"): + pass # Test failure on creating PathContext with an existing file with open("path/1/file", "w") as f: f.write("xx") - with self.assertRaises(OSError): - with PathContext("path/1/file"): - pass + with self.assertRaises(OSError), PathContext("path/1/file"): + pass def test_chdir(self): with PathContext("/tmp/pc"): @@ -27,9 +26,8 @@ def test_cleanup(self): with TestAreaContext("pathcontext"): os.makedirs("path/1") - with PathContext("path/1/next/2/level"): - with open("../../file", "w") as f: - f.write("Crap") + with PathContext("path/1/next/2/level"), open("../../file", "w") as f: + f.write("Crap") self.assertTrue(os.path.isdir("path/1")) self.assertTrue(os.path.isdir("path/1/next")) diff --git a/python/tests/util_tests/test_string_list.py b/python/tests/util_tests/test_string_list.py index a2aa344df..2462f1536 100644 --- a/python/tests/util_tests/test_string_list.py +++ b/python/tests/util_tests/test_string_list.py @@ -73,7 +73,7 @@ def test_last(self): s.pop() s.pop() s.pop() - s.last + _ = s.last def test_in_and_not_in(self): s = StringList(["A", "list", "of", "strings"]) diff --git a/python/tests/util_tests/test_thread_pool.py b/python/tests/util_tests/test_thread_pool.py index 8e3b2aa1a..eb99a9bec 100644 --- a/python/tests/util_tests/test_thread_pool.py +++ b/python/tests/util_tests/test_thread_pool.py @@ -61,7 +61,7 @@ def test_pool_unbound_fail(self): def test_fill_pool(self): pool = ThreadPool(4) - for index in range(10): + for _index in range(10): pool.addTask(self.sleepTask, 2) pool.nonBlockingStart() diff --git a/python/tests/util_tests/test_vectors.py b/python/tests/util_tests/test_vectors.py index ea5e73faa..9d1e9d9d2 100755 --- a/python/tests/util_tests/test_vectors.py +++ b/python/tests/util_tests/test_vectors.py @@ -1,6 +1,7 @@ #!/usr/bin/env python import copy import datetime + import six try: @@ -523,16 +524,16 @@ def range_test(self, v, a, b, d): r = range(a, b, d) self.assertEqual(len(v), len(r)) - for a, b in zip(v, r): - self.assertEqual(a, b) + for val1, val2 in zip(v, r): + self.assertEqual(val1, val2) def create_range_test(self, v, a, b, d): v = IntVector.createRange(a, b, d) r = range(a, b, d) self.assertEqual(len(v), len(r)) - for a, b in zip(v, r): - self.assertEqual(a, b) + for val1, val2 in zip(v, r): + self.assertEqual(val1, val2) def test_range(self): v = IntVector() diff --git a/python/tests/well_tests/test_rd_well.py b/python/tests/well_tests/test_rd_well.py index 8bb549e17..e37ba73cd 100644 --- a/python/tests/well_tests/test_rd_well.py +++ b/python/tests/well_tests/test_rd_well.py @@ -376,7 +376,7 @@ def test_well_info(self): self.assertNotEqual(well_info[0], well_info[1]) - well_time_lines = [wtl for wtl in well_info] + well_time_lines = list(well_info) self.assertEqual(len(well_time_lines), len(well_info)) with self.assertRaises(IndexError): diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index c62373ce9..000000000 --- a/setup.cfg +++ /dev/null @@ -1,5 +0,0 @@ -[aliases] -test = pytest - -[flake8] -max-line-length = 88 From 8c11679af2cf4571cf2e8a27aeb7f14766588e1c Mon Sep 17 00:00:00 2001 From: larsevj Date: Thu, 29 Aug 2024 10:08:11 +0200 Subject: [PATCH 03/11] Remove __neq__ from Cell --- python/resdata/grid/cell.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/python/resdata/grid/cell.py b/python/resdata/grid/cell.py index ff0de4df1..cf8c850c4 100644 --- a/python/resdata/grid/cell.py +++ b/python/resdata/grid/cell.py @@ -79,11 +79,6 @@ def __eq__(self, other): return idx_eq and self._grid == other._grid return NotImplemented - def __neq__(self, other): - if isinstance(other, Cell): - return self != other - return NotImplemented - def hash(self): return hash((self._idx, self._aidx, self.ijk)) From 5bf4d3872e0022a0c8511e8b466eee2086265ee1 Mon Sep 17 00:00:00 2001 From: larsevj Date: Thu, 29 Aug 2024 10:08:55 +0200 Subject: [PATCH 04/11] Use _ for unused loop controll index --- python/resdata/geometry/geometry_tools.py | 4 ++-- python/resdata/grid/faults/fault.py | 2 +- python/resdata/grid/faults/fault_segments.py | 2 +- python/resdata/util/test/extended_testcase.py | 5 +---- python/resdata/util/test/resdata_test_runner.py | 7 ++----- python/tests/geometry_tests/test_surface.py | 6 +++--- python/tests/rd_tests/test_equinor_faults.py | 5 +---- python/tests/rd_tests/test_fault_blocks_equinor.py | 5 +---- python/tests/rd_tests/test_faults.py | 2 +- python/tests/rd_tests/test_grid_equinor.py | 7 ++----- python/tests/rd_tests/test_rd_sum_vector.py | 5 +---- python/tests/rd_tests/test_rd_type.py | 4 ++-- python/tests/util_tests/test_ctime.py | 6 +----- python/tests/util_tests/test_lookup_table.py | 5 +---- python/tests/util_tests/test_thread_pool.py | 2 +- python/tests/util_tests/test_vectors.py | 6 +----- python/tests/util_tests/test_work_area.py | 5 +---- 17 files changed, 23 insertions(+), 55 deletions(-) diff --git a/python/resdata/geometry/geometry_tools.py b/python/resdata/geometry/geometry_tools.py index 1bf0845ee..8d15d599d 100644 --- a/python/resdata/geometry/geometry_tools.py +++ b/python/resdata/geometry/geometry_tools.py @@ -385,7 +385,7 @@ def connectPolylines(polyline, target_polyline): p0 = polyline[-1] p1 = polyline[-2] ray = GeometryTools.lineToRay(p1, p0) - for _index, p in GeometryTools.rayPolygonIntersections( + for _, p in GeometryTools.rayPolygonIntersections( p0, ray, target_polyline ): d_list.append((GeometryTools.distance(p0, p), [p0, p])) @@ -393,7 +393,7 @@ def connectPolylines(polyline, target_polyline): p0 = polyline[0] p1 = polyline[1] ray = GeometryTools.lineToRay(p1, p0) - for _index, p in GeometryTools.rayPolygonIntersections( + for _, p in GeometryTools.rayPolygonIntersections( p0, ray, target_polyline ): d_list.append((GeometryTools.distance(p0, p), [p0, p])) diff --git a/python/resdata/grid/faults/fault.py b/python/resdata/grid/faults/fault.py index 892261947..296682a0d 100644 --- a/python/resdata/grid/faults/fault.py +++ b/python/resdata/grid/faults/fault.py @@ -100,7 +100,7 @@ def __sort_fault_lines(self): perm_list.sort(key=lambda x: x[1]) fault_lines = [] - for index, _d in perm_list: + for index, _ in perm_list: fault_lines.append(self.__fault_lines[index]) self.__fault_lines = fault_lines diff --git a/python/resdata/grid/faults/fault_segments.py b/python/resdata/grid/faults/fault_segments.py index abc620539..919662a06 100644 --- a/python/resdata/grid/faults/fault_segments.py +++ b/python/resdata/grid/faults/fault_segments.py @@ -132,7 +132,7 @@ def pop_next(self, segment): def print_content(self): for d in self.__segment_map.values(): - for _C, S in d.iteritems(): + for _, S in d.iteritems(): print(S) diff --git a/python/resdata/util/test/extended_testcase.py b/python/resdata/util/test/extended_testcase.py index a7656cc9a..66c4a5375 100644 --- a/python/resdata/util/test/extended_testcase.py +++ b/python/resdata/util/test/extended_testcase.py @@ -4,10 +4,7 @@ import traceback import sys -try: - from unittest2 import TestCase -except ImportError: - from unittest import TestCase +from unittest import TestCase from .source_enumerator import SourceEnumerator from resdata.util.util import installAbortSignals diff --git a/python/resdata/util/test/resdata_test_runner.py b/python/resdata/util/test/resdata_test_runner.py index 6684b9dc9..6a07eb616 100644 --- a/python/resdata/util/test/resdata_test_runner.py +++ b/python/resdata/util/test/resdata_test_runner.py @@ -1,9 +1,6 @@ import os -try: - from unittest2 import TestLoader, TextTestRunner -except ImportError: - from unittest import TestLoader, TextTestRunner +from unittest import TestLoader, TextTestRunner class ResdataTestRunner(object): @@ -19,7 +16,7 @@ def findTestsInDirectory(path, recursive=True, pattern="test*.py"): loader = TestLoader() test_suite = loader.discover(path, pattern=pattern) - for root, dirnames, _filenames in os.walk(path): + for root, dirnames, _ in os.walk(path): for directory in dirnames: test_suite.addTests( ResdataTestRunner.findTestsInDirectory( diff --git a/python/tests/geometry_tests/test_surface.py b/python/tests/geometry_tests/test_surface.py index 8d6fa0e58..d95d46821 100644 --- a/python/tests/geometry_tests/test_surface.py +++ b/python/tests/geometry_tests/test_surface.py @@ -55,8 +55,8 @@ def test_create_new(self): self.assertNotEqual(s, small) idx = 0 - for _i in range(nx): - for _j in range(ny): + for _ in range(nx): + for _ in range(ny): s[idx] = small[idx] idx += 1 self.assertEqual(s, small) @@ -164,7 +164,7 @@ def test_ops(self): def test_ops2(self): s0 = Surface(self.surface_small) surface_list = [] - for _i in range(10): + for _ in range(10): s = s0.copy() for j in range(len(s)): s[j] = random.random() diff --git a/python/tests/rd_tests/test_equinor_faults.py b/python/tests/rd_tests/test_equinor_faults.py index 15baad8be..c0a1057da 100644 --- a/python/tests/rd_tests/test_equinor_faults.py +++ b/python/tests/rd_tests/test_equinor_faults.py @@ -1,8 +1,5 @@ #!/usr/bin/env python -try: - from unittest2 import skipIf -except ImportError: - from unittest import skipIf +from unittest import skipIf from cwrap import open as copen diff --git a/python/tests/rd_tests/test_fault_blocks_equinor.py b/python/tests/rd_tests/test_fault_blocks_equinor.py index 3ab3b203b..1ee71bd4f 100644 --- a/python/tests/rd_tests/test_fault_blocks_equinor.py +++ b/python/tests/rd_tests/test_fault_blocks_equinor.py @@ -1,8 +1,5 @@ #!/usr/bin/env python -try: - from unittest2 import skipIf -except ImportError: - from unittest import skipIf +from unittest import skipIf from resdata import ResDataType from resdata.resfile import ResdataKW diff --git a/python/tests/rd_tests/test_faults.py b/python/tests/rd_tests/test_faults.py index 31d1fbc45..61434589d 100644 --- a/python/tests/rd_tests/test_faults.py +++ b/python/tests/rd_tests/test_faults.py @@ -409,7 +409,7 @@ def test_iter(self): faults = FaultCollection(self.grid, self.faults1, self.faults2) self.assertEqual(7, len(faults)) c = 0 - for _f in faults: + for _ in faults: c += 1 self.assertEqual(c, len(faults)) diff --git a/python/tests/rd_tests/test_grid_equinor.py b/python/tests/rd_tests/test_grid_equinor.py index a8ecc05c2..873f6e6b9 100755 --- a/python/tests/rd_tests/test_grid_equinor.py +++ b/python/tests/rd_tests/test_grid_equinor.py @@ -1,10 +1,7 @@ #!/usr/bin/env python import math -try: - from unittest2 import skipIf -except ImportError: - from unittest import skipIf +from unittest import skipIf from cwrap import Prototype from cwrap import open as copen @@ -251,7 +248,7 @@ def test_boundingBox(self): def test_num_active_large_memory(self): case = self.createTestPath("Equinor/ECLIPSE/Gurbat/ECLIPSE") vecList = [] - for _i in range(12500): + for _ in range(12500): vec = DoubleVector() vec[81920] = 0 vecList.append(vec) diff --git a/python/tests/rd_tests/test_rd_sum_vector.py b/python/tests/rd_tests/test_rd_sum_vector.py index de9d03016..3b7a1c2dd 100644 --- a/python/tests/rd_tests/test_rd_sum_vector.py +++ b/python/tests/rd_tests/test_rd_sum_vector.py @@ -1,8 +1,5 @@ #!/usr/bin/env python -try: - from unittest2 import skipIf -except ImportError: - from unittest import skipIf +from unittest import skipIf import warnings diff --git a/python/tests/rd_tests/test_rd_type.py b/python/tests/rd_tests/test_rd_type.py index 0ee263999..a6f1f132c 100644 --- a/python/tests/rd_tests/test_rd_type.py +++ b/python/tests/rd_tests/test_rd_type.py @@ -132,10 +132,10 @@ def test_hash(self): all_types.add(ResDataType(rd_type, elem_size)) self.assertEqual(index + 1, len(all_types)) - for _index, (rd_type, elem_size) in enumerate(test_base): + for _, (rd_type, elem_size) in enumerate(test_base): all_types.add(ResDataType(rd_type, elem_size)) - for _index, rd_type in enumerate(get_const_size_types()): + for _, rd_type in enumerate(get_const_size_types()): all_types.add(ResDataType(rd_type)) self.assertEqual(len(test_base), len(all_types)) diff --git a/python/tests/util_tests/test_ctime.py b/python/tests/util_tests/test_ctime.py index 623385b36..2129170ec 100644 --- a/python/tests/util_tests/test_ctime.py +++ b/python/tests/util_tests/test_ctime.py @@ -3,11 +3,7 @@ from resdata.util.util import CTime - -try: - from unittest2 import TestCase -except ImportError: - from unittest import TestCase +from unittest import TestCase class CTimeTest(TestCase): diff --git a/python/tests/util_tests/test_lookup_table.py b/python/tests/util_tests/test_lookup_table.py index e9370dcb2..217def513 100644 --- a/python/tests/util_tests/test_lookup_table.py +++ b/python/tests/util_tests/test_lookup_table.py @@ -1,7 +1,4 @@ -try: - from unittest2 import TestCase -except ImportError: - from unittest import TestCase +from unittest import TestCase from resdata.util.util import LookupTable diff --git a/python/tests/util_tests/test_thread_pool.py b/python/tests/util_tests/test_thread_pool.py index eb99a9bec..5fdd3f67d 100644 --- a/python/tests/util_tests/test_thread_pool.py +++ b/python/tests/util_tests/test_thread_pool.py @@ -61,7 +61,7 @@ def test_pool_unbound_fail(self): def test_fill_pool(self): pool = ThreadPool(4) - for _index in range(10): + for _ in range(10): pool.addTask(self.sleepTask, 2) pool.nonBlockingStart() diff --git a/python/tests/util_tests/test_vectors.py b/python/tests/util_tests/test_vectors.py index 9d1e9d9d2..9898eb853 100755 --- a/python/tests/util_tests/test_vectors.py +++ b/python/tests/util_tests/test_vectors.py @@ -3,11 +3,7 @@ import datetime import six - -try: - from unittest2 import TestCase -except ImportError: - from unittest import TestCase +from unittest import TestCase from resdata.util.util import ( DoubleVector, diff --git a/python/tests/util_tests/test_work_area.py b/python/tests/util_tests/test_work_area.py index a03e8da7c..625853520 100644 --- a/python/tests/util_tests/test_work_area.py +++ b/python/tests/util_tests/test_work_area.py @@ -2,10 +2,7 @@ import os.path import os -try: - from unittest2 import skipIf -except ImportError: - from unittest import skipIf +from unittest import skipIf from resdata.util.test import TestAreaContext from tests import ResdataTest From 825bbb9d956617e712ec5c6952ff895c79c256f8 Mon Sep 17 00:00:00 2001 From: larsevj Date: Thu, 29 Aug 2024 13:26:36 +0200 Subject: [PATCH 05/11] Make type_name a method in rd_kw --- python/resdata/grid/faults/fault_block_layer.py | 4 ++-- python/resdata/grid/rd_region.py | 4 ++-- python/resdata/resfile/rd_kw.py | 5 ++--- python/tests/rd_tests/test_rd_kw.py | 2 +- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/python/resdata/grid/faults/fault_block_layer.py b/python/resdata/grid/faults/fault_block_layer.py index cb5d177fa..aa095b07f 100644 --- a/python/resdata/grid/faults/fault_block_layer.py +++ b/python/resdata/grid/faults/fault_block_layer.py @@ -111,7 +111,7 @@ def scan_keyword(self, fault_block_kw): raise ValueError( "The fault block keyword had wrong type/size: type:%s size:%d grid_size:%d" % ( - fault_block_kw.type_name, + fault_block_kw.type_name(), len(fault_block_kw), self.grid_ref.getGlobalSize(), ) @@ -126,7 +126,7 @@ def load_keyword(self, fault_block_kw): raise ValueError( "The fault block keyword had wrong type/size: type:%s size:%d grid_size:%d" % ( - fault_block_kw.type_name, + fault_block_kw.type_name(), len(fault_block_kw), self.grid_ref.getGlobalSize(), ) diff --git a/python/resdata/grid/rd_region.py b/python/resdata/grid/rd_region.py index 8955338ea..add2e7bec 100644 --- a/python/resdata/grid/rd_region.py +++ b/python/resdata/grid/rd_region.py @@ -552,7 +552,7 @@ def select_equal(self, rd_kw, value, intersect=False): if not rd_kw.data_type.is_int(): raise ValueError( "The select_equal method must have an integer valued keyword - got:%s" - % rd_kw.type_name + % rd_kw.type_name() ) self._select_equal(rd_kw, value) @@ -565,7 +565,7 @@ def deselect_equal(self, rd_kw, value): if not rd_kw.data_type.is_int(): raise ValueError( "The select_equal method must have an integer valued keyword - got:%s" - % rd_kw.type_name + % rd_kw.type_name() ) self._deselect_equal(rd_kw, value) diff --git a/python/resdata/resfile/rd_kw.py b/python/resdata/resfile/rd_kw.py index c4b73d463..c57c1bf57 100644 --- a/python/resdata/resfile/rd_kw.py +++ b/python/resdata/resfile/rd_kw.py @@ -975,7 +975,6 @@ def type(self): def data_type(self): return self._get_data_type() - @property def type_name(self): return self.data_type.type_name @@ -991,7 +990,7 @@ def get_rd_type(self): @property def header(self): - return (self.get_name(), len(self), self.type_name) + return (self.get_name(), len(self), self.type_name()) @property def array(self): @@ -1033,7 +1032,7 @@ def str(self, width=5, max_lines=10, fmt=None): the elements. The implementation of the builtin method __str__() is based on this method. """ - s = "%-8s %8d %-4s\n" % (self.get_name(), len(self), self.type_name) + s = "%-8s %8d %-4s\n" % (self.get_name(), len(self), self.type_name()) lines = len(self) // width if not fmt: fmt = self.str_fmt + " " diff --git a/python/tests/rd_tests/test_rd_kw.py b/python/tests/rd_tests/test_rd_kw.py index 914cfb2e7..58f321a15 100644 --- a/python/tests/rd_tests/test_rd_kw.py +++ b/python/tests/rd_tests/test_rd_kw.py @@ -422,7 +422,7 @@ def test_resize(self): def test_typename(self): kw = ResdataKW("KW", 100, ResDataType.RD_INT) - self.assertEqual(kw.type_name, "INTE") + self.assertEqual(kw.type_name(), "INTE") def test_string_alloc(self): kw = ResdataKW("KW", 10, ResDataType.RD_STRING(30)) From af60c456ae2d7935c409c1af0c69370108ebe229 Mon Sep 17 00:00:00 2001 From: larsevj Date: Thu, 29 Aug 2024 15:16:44 +0200 Subject: [PATCH 06/11] Add pyupgrade ruff rule --- pyproject.toml | 1 + python/docs/examples/avg_pressure.py | 6 +-- python/resdata/__init__.py | 4 +- python/resdata/geometry/cpolyline.py | 14 +++--- .../resdata/geometry/cpolyline_collection.py | 8 ++-- python/resdata/geometry/geo_pointset.py | 6 +-- python/resdata/geometry/geo_region.py | 8 ++-- python/resdata/geometry/geometry_tools.py | 5 +- python/resdata/geometry/polyline.py | 6 +-- python/resdata/geometry/surface.py | 26 ++++------ python/resdata/geometry/xyz_io.py | 12 ++--- python/resdata/gravimetry/rd_grav.py | 2 +- python/resdata/gravimetry/rd_subsidence.py | 14 +++--- python/resdata/grid/cell.py | 8 ++-- python/resdata/grid/faults/fault.py | 21 ++++---- python/resdata/grid/faults/fault_block.py | 2 +- .../resdata/grid/faults/fault_block_layer.py | 5 +- .../resdata/grid/faults/fault_collection.py | 8 ++-- python/resdata/grid/faults/fault_line.py | 2 +- python/resdata/grid/faults/fault_segments.py | 6 +-- python/resdata/grid/faults/layer.py | 4 +- python/resdata/grid/rd_grid.py | 15 +++--- python/resdata/grid/rd_grid_generator.py | 11 +++-- python/resdata/grid/rd_region.py | 8 ++-- python/resdata/rd_type.py | 4 +- python/resdata/rd_util.py | 6 +-- python/resdata/resfile/fortio.py | 10 ++-- python/resdata/resfile/rd_3d_file.py | 4 +- python/resdata/resfile/rd_3dkw.py | 8 ++-- python/resdata/resfile/rd_file.py | 29 +++++------ python/resdata/resfile/rd_file_view.py | 11 ++--- python/resdata/resfile/rd_init_file.py | 2 +- python/resdata/resfile/rd_kw.py | 30 +++++------- python/resdata/resfile/rd_restart_file.py | 7 ++- python/resdata/rft/rd_rft.py | 8 ++-- python/resdata/rft/rd_rft_cell.py | 4 +- python/resdata/rft/well_trajectory.py | 6 +-- python/resdata/summary/rd_cmp.py | 6 +-- python/resdata/summary/rd_npv.py | 28 ++++------- python/resdata/summary/rd_smspec_node.py | 2 +- python/resdata/summary/rd_sum.py | 48 +++++++++---------- .../resdata/summary/rd_sum_keyword_vector.py | 2 +- python/resdata/summary/rd_sum_node.py | 2 +- python/resdata/summary/rd_sum_tstep.py | 6 +-- python/resdata/summary/rd_sum_vector.py | 8 ++-- python/resdata/util/test/debug_msg.py | 2 +- python/resdata/util/test/extended_testcase.py | 40 +++++++--------- python/resdata/util/test/lint_test_case.py | 2 +- python/resdata/util/test/path_context.py | 4 +- .../resdata/util/test/resdata_test_runner.py | 4 +- python/resdata/util/test/source_enumerator.py | 6 +-- python/resdata/util/test/test_area.py | 20 ++++---- python/resdata/util/test/test_run.py | 12 ++--- python/resdata/util/util/__init__.py | 6 +-- python/resdata/util/util/bool_vector.py | 2 +- python/resdata/util/util/ctime.py | 10 ++-- python/resdata/util/util/cwd_context.py | 4 +- python/resdata/util/util/double_vector.py | 2 +- python/resdata/util/util/hash.py | 29 ++++++----- python/resdata/util/util/int_vector.py | 2 +- python/resdata/util/util/lookup_table.py | 8 ++-- python/resdata/util/util/rng.py | 4 +- python/resdata/util/util/stringlist.py | 18 ++++--- python/resdata/util/util/thread_pool.py | 8 ++-- python/resdata/util/util/time_vector.py | 6 +-- python/resdata/util/util/vector_template.py | 10 ++-- python/resdata/util/util/version.py | 6 +-- python/resdata/well/well_connection.py | 15 +----- python/resdata/well/well_info.py | 8 ++-- python/resdata/well/well_segment.py | 2 +- python/resdata/well/well_state.py | 10 +--- python/tests/rd_tests/create_restart.py | 2 +- python/tests/rd_tests/test_fk_user_data.py | 2 +- python/tests/rd_tests/test_geertsma.py | 2 +- python/tests/rd_tests/test_grid.py | 8 ++-- python/tests/rd_tests/test_grid_generator.py | 2 +- python/tests/rd_tests/test_npv.py | 2 +- python/tests/rd_tests/test_rd_kw.py | 2 +- python/tests/rd_tests/test_region_equinor.py | 8 ++-- python/tests/rd_tests/test_rft_equinor.py | 1 - python/tests/rd_tests/test_sum_equinor.py | 2 +- python/tests/util_tests/test_work_area.py | 16 ++----- 82 files changed, 314 insertions(+), 406 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 5e2560294..9640b0665 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,6 +17,7 @@ select = [ "NPY", # numpy specific rules "C4", # flake8-comprehensions "PD", # pandas-vet + "UP", # pyupgrade ] ignore = ["PLW2901", # redefined-loop-name "PLR2004", # magic-value-comparison diff --git a/python/docs/examples/avg_pressure.py b/python/docs/examples/avg_pressure.py index db97178a7..dd37e441e 100755 --- a/python/docs/examples/avg_pressure.py +++ b/python/docs/examples/avg_pressure.py @@ -40,9 +40,9 @@ def avg_pressure(p, sw, pv, region, region_id, result): if __name__ == "__main__": case = sys.argv[1] - grid = Grid("%s.EGRID" % case) - rst_file = ResdataRestartFile(grid, "%s.UNRST" % case) - init_file = ResdataFile("%s.INIT" % case) + grid = Grid(f"{case}.EGRID") + rst_file = ResdataRestartFile(grid, f"{case}.UNRST") + init_file = ResdataFile(f"{case}.INIT") # Create PORV keyword where all the inactive cells have been removed. pv = grid.compressed_kw_copy(init_file["PORV"][0]) diff --git a/python/resdata/__init__.py b/python/resdata/__init__.py index a369d228a..4f57dc4f2 100644 --- a/python/resdata/__init__.py +++ b/python/resdata/__init__.py @@ -95,9 +95,7 @@ class ResdataPrototype(Prototype): lib = _dlopen_resdata() def __init__(self, prototype, bind=True): - super(ResdataPrototype, self).__init__( - ResdataPrototype.lib, prototype, bind=bind - ) + super().__init__(ResdataPrototype.lib, prototype, bind=bind) from .rd_type import ResDataType, ResdataTypeEnum diff --git a/python/resdata/geometry/cpolyline.py b/python/resdata/geometry/cpolyline.py index fcd64949e..8eefbfb14 100644 --- a/python/resdata/geometry/cpolyline.py +++ b/python/resdata/geometry/cpolyline.py @@ -40,14 +40,14 @@ class CPolyline(BaseCClass): def __init__(self, name=None, init_points=()): c_ptr = self._alloc_new(name) - super(CPolyline, self).__init__(c_ptr) + super().__init__(c_ptr) for xc, yc in init_points: self.addPoint(xc, yc) @classmethod def createFromXYZFile(cls, filename, name=None): if not os.path.isfile(filename): - raise IOError("No such file:%s" % filename) + raise OSError(f"No such file:{filename}") polyline = cls._fread_alloc_irap(filename) if not name is None: @@ -56,10 +56,10 @@ def createFromXYZFile(cls, filename, name=None): def __str__(self): name = self.getName() - str = "%s [" % name if name else "[" + str = f"{name} [" if name else "[" for index, p in enumerate(self): - str += "(%g,%g)" % p + str += "({:g},{:g})".format(*p) if index < len(self) - 1: str += "," str += "]" @@ -73,7 +73,7 @@ def __len__(self): def __getitem__(self, index): if not isinstance(index, int): - raise TypeError("Index argument must be integer. Index:%s invalid" % index) + raise TypeError(f"Index argument must be integer. Index:{index} invalid") if index < 0: index += len(self) @@ -119,7 +119,7 @@ def __radd__(self, other): return copy def __eq__(self, other): - if super(CPolyline, self).__eq__(other): + if super().__eq__(other): return True else: return self._equal(other) @@ -142,7 +142,7 @@ def extendToBBox(self, bbox, start=True): intersections = GeometryTools.rayPolygonIntersections(p1, ray_dir, bbox) if intersections: p2 = intersections[0][1] - name = "Extend:%s" % self.getName() if self.getName() else None + name = f"Extend:{self.getName()}" if self.getName() else None return CPolyline(name=name, init_points=[(p1[0], p1[1]), p2]) else: diff --git a/python/resdata/geometry/cpolyline_collection.py b/python/resdata/geometry/cpolyline_collection.py index 52d2f44f0..27c9ad546 100644 --- a/python/resdata/geometry/cpolyline_collection.py +++ b/python/resdata/geometry/cpolyline_collection.py @@ -37,7 +37,7 @@ class CPolylineCollection(BaseCClass): def __init__(self): c_ptr = self._alloc_new() - super(CPolylineCollection, self).__init__(c_ptr) + super().__init__(c_ptr) self.parent_ref = None def __contains__(self, name): @@ -68,7 +68,7 @@ def __getitem__(self, index): if index in self: return self._get(index) else: - raise KeyError("No polyline named:%s" % index) + raise KeyError(f"No polyline named:{index}") else: raise TypeError("The index argument must be string or integer") @@ -92,7 +92,7 @@ def addPolyline(self, polyline, name=None): name = polyline.getName() if name and name in self: - raise KeyError("The polyline collection already has an object:%s" % name) + raise KeyError(f"The polyline collection already has an object:{name}") if polyline.isReference(): self._add_polyline(polyline, False) @@ -102,7 +102,7 @@ def addPolyline(self, polyline, name=None): def createPolyline(self, name=None): if name and name in self: - raise KeyError("The polyline collection already has an object:%s" % name) + raise KeyError(f"The polyline collection already has an object:{name}") polyline = self._create_polyline(name) polyline.setParent(parent=self) diff --git a/python/resdata/geometry/geo_pointset.py b/python/resdata/geometry/geo_pointset.py index c60cb81fb..aa0fe8961 100644 --- a/python/resdata/geometry/geo_pointset.py +++ b/python/resdata/geometry/geo_pointset.py @@ -14,10 +14,10 @@ class GeoPointset(BaseCClass): def __init__(self, external_z=False): c_ptr = self._alloc(external_z) if c_ptr: - super(GeoPointset, self).__init__(c_ptr) + super().__init__(c_ptr) else: ext = "external" if external_z else "internal" - raise ValueError("Failed to construct GeoPointset with %s_z." % ext) + raise ValueError(f"Failed to construct GeoPointset with {ext}_z.") @staticmethod def fromSurface(surface): @@ -42,7 +42,7 @@ def __getitem__(self, key): ) else: # TODO implement slicing? - raise ValueError("Index must be int, not %s." % type(key)) + raise ValueError(f"Index must be int, not {type(key)}.") def __len__(self): return self._get_size() diff --git a/python/resdata/geometry/geo_region.py b/python/resdata/geometry/geo_region.py index 54bb00ba4..15b6f2f5a 100644 --- a/python/resdata/geometry/geo_region.py +++ b/python/resdata/geometry/geo_region.py @@ -45,18 +45,16 @@ def __init__(self, pointset, preselect=False): self._preselect = bool(preselect) c_ptr = self._alloc(pointset, self._preselect) if c_ptr: - super(GeoRegion, self).__init__(c_ptr) + super().__init__(c_ptr) else: - raise ValueError( - "Could not construct GeoRegion from pointset %s." % pointset - ) + raise ValueError(f"Could not construct GeoRegion from pointset {pointset}.") def getActiveList(self): return self._get_index_list() def _assert_polygon(self, polygon): if not isinstance(polygon, CPolyline): - raise ValueError("Need to select with a CPolyline, not %s." % type(polygon)) + raise ValueError(f"Need to select with a CPolyline, not {type(polygon)}.") def _construct_cline(self, line): """Takes a line ((x1,y1), (x2,y2)) and returns two double[2]* but diff --git a/python/resdata/geometry/geometry_tools.py b/python/resdata/geometry/geometry_tools.py index 8d15d599d..eeb34fd2f 100644 --- a/python/resdata/geometry/geometry_tools.py +++ b/python/resdata/geometry/geometry_tools.py @@ -3,7 +3,7 @@ from math import sqrt -class GeometryTools(object): +class GeometryTools: EPSILON = 0.000001 @staticmethod @@ -400,8 +400,7 @@ def connectPolylines(polyline, target_polyline): if len(d_list) == 0: raise ValueError( - "Polyline %s can not be extended to %s" - % (polyline.getName(), target_polyline.getName()) + f"Polyline {polyline.getName()} can not be extended to {target_polyline.getName()}" ) d_list.sort(key=lambda x: x[0]) diff --git a/python/resdata/geometry/polyline.py b/python/resdata/geometry/polyline.py index 1c7566802..a24cc68dd 100644 --- a/python/resdata/geometry/polyline.py +++ b/python/resdata/geometry/polyline.py @@ -3,9 +3,9 @@ from .geometry_tools import GeometryTools -class Polyline(object): +class Polyline: def __init__(self, name=None, init_points=None): - super(Polyline, self).__init__() + super().__init__() self.__name = name self.__points = [] if init_points: @@ -14,7 +14,7 @@ def __init__(self, name=None, init_points=None): def __str__(self): s = "Polyline:[ " for p in self: - s += "(%s,%s) " % (p[0], p[1]) + s += f"({p[0]},{p[1]}) " s += "]" return s diff --git a/python/resdata/geometry/surface.py b/python/resdata/geometry/surface.py index a361fa2a2..d5e9ca846 100644 --- a/python/resdata/geometry/surface.py +++ b/python/resdata/geometry/surface.py @@ -1,8 +1,7 @@ -from __future__ import division - """ Create a polygon """ + import os.path import ctypes @@ -67,18 +66,17 @@ def __init__( filename = str(filename) if os.path.isfile(filename): c_ptr = self._alloc(filename, True) - super(Surface, self).__init__(c_ptr) + super().__init__(c_ptr) else: - raise IOError('No such file "%s".' % filename) + raise OSError(f'No such file "{filename}".') else: s_args = [nx, ny, xinc, yinc, xstart, ystart, angle] if None in s_args: raise ValueError( - "Missing argument for creating surface, all values must be set, was: %s" - % str(s_args) + f"Missing argument for creating surface, all values must be set, was: {str(s_args)}" ) c_ptr = self._new(*s_args) - super(Surface, self).__init__(c_ptr) + super().__init__(c_ptr) def __eq__(self, other): """ @@ -203,7 +201,7 @@ def __setitem__(self, index, value): self._iset_zvalue(index, value) else: - raise TypeError("Invalid index type:%s - must be integer" % index) + raise TypeError(f"Invalid index type:{index} - must be integer") def __getitem__(self, index): if isinstance(index, int): @@ -218,7 +216,7 @@ def __getitem__(self, index): "Invalid index:%d - valid range [0,%d)" % (index, len(self)) ) else: - raise TypeError("Invalid index type:%s - must be integer" % index) + raise TypeError(f"Invalid index type:{index} - must be integer") def getXY(self, index): """Gets the index'th (x,y) coordinate""" @@ -232,7 +230,7 @@ def getXY(self, index): ) index = idx else: - raise TypeError("Invalid index type:%s - must be integer" % index) + raise TypeError(f"Invalid index type:{index} - must be integer") x = ctypes.c_double() y = ctypes.c_double() @@ -252,13 +250,9 @@ def getPointset(self): def _assert_idx_or_i_and_j(self, idx, i, j): if idx is None: if i is None or j is None: - raise ValueError( - "idx is None, i and j must be ints, was %s and %s." % (i, j) - ) + raise ValueError(f"idx is None, i and j must be ints, was {i} and {j}.") elif i is not None or j is not None: - raise ValueError( - "idx is set, i and j must be None, was %s and %s." % (i, j) - ) + raise ValueError(f"idx is set, i and j must be None, was {i} and {j}.") def getXYZ(self, idx=None, i=None, j=None): """Returns a tuple of 3 floats, (x,y,z) for given global index, or i and j.""" diff --git a/python/resdata/geometry/xyz_io.py b/python/resdata/geometry/xyz_io.py index 90e3b09c9..e91084df1 100644 --- a/python/resdata/geometry/xyz_io.py +++ b/python/resdata/geometry/xyz_io.py @@ -2,19 +2,19 @@ from .polyline import Polyline -class XYZIo(object): +class XYZIo: @staticmethod def readXYZFile(path): """@rtype: Polyline""" if not os.path.exists(path): - raise IOError("Path does not exist '%s'!" % path) + raise OSError(f"Path does not exist '{path}'!") name = os.path.basename(path) polyline = Polyline(name=name) - with open(path, "r") as f: + with open(path) as f: for line in f: line = line.strip() if line: @@ -34,13 +34,13 @@ def readXYFile(path): """@rtype: Polyline""" if not os.path.exists(path): - raise IOError("Path does not exist '%s'!" % path) + raise OSError(f"Path does not exist '{path}'!") name = os.path.basename(path) polyline = Polyline(name=name) - with open(path, "r") as f: + with open(path) as f: for line in f: x, y = map(float, line.split()) polyline.addPoint(x, y) @@ -54,4 +54,4 @@ def saveXYFile(polyline, filename): """ with open(filename, "w") as fileH: for p in polyline: - fileH.write("%g %g\n" % (p[0], p[1])) + fileH.write(f"{p[0]:g} {p[1]:g}\n") diff --git a/python/resdata/gravimetry/rd_grav.py b/python/resdata/gravimetry/rd_grav.py index 49aed935a..9cda2c9b9 100644 --- a/python/resdata/gravimetry/rd_grav.py +++ b/python/resdata/gravimetry/rd_grav.py @@ -68,7 +68,7 @@ def __init__(self, grid: Grid, init_file: ResdataFile): self.init_file = init_file # Inhibit premature garbage collection of init_file c_ptr = self._grav_alloc(grid, init_file) - super(ResdataGrav, self).__init__(c_ptr) + super().__init__(c_ptr) self.dispatch = { "FIP": self.add_survey_FIP, diff --git a/python/resdata/gravimetry/rd_subsidence.py b/python/resdata/gravimetry/rd_subsidence.py index 4597dbab5..5198ddd10 100644 --- a/python/resdata/gravimetry/rd_subsidence.py +++ b/python/resdata/gravimetry/rd_subsidence.py @@ -60,7 +60,7 @@ def __init__(self, grid, init_file): """ self.init_file = init_file # Inhibit premature garbage collection of init_file c_ptr = self._alloc(grid, init_file) - super(ResdataSubsidence, self).__init__(c_ptr) + super().__init__(c_ptr) def __contains__(self, survey_name): return self._has_survey(survey_name) @@ -96,10 +96,10 @@ def eval_geertsma( region=None, ): if not base_survey in self: - raise KeyError("No such survey: %s" % base_survey) + raise KeyError(f"No such survey: {base_survey}") if monitor_survey is not None and not monitor_survey in self: - raise KeyError("No such survey: %s" % monitor_survey) + raise KeyError(f"No such survey: {monitor_survey}") return self._eval_geertsma( base_survey, @@ -124,10 +124,10 @@ def eval_geertsma_rporv( region=None, ): if not base_survey in self: - raise KeyError("No such survey: %s" % base_survey) + raise KeyError(f"No such survey: {base_survey}") if monitor_survey is not None and not monitor_survey in self: - raise KeyError("No such survey: %s" % monitor_survey) + raise KeyError(f"No such survey: {monitor_survey}") return self._eval_geertsma_rporv( base_survey, @@ -174,10 +174,10 @@ def eval( The argument @compressibility is the total reservoir compressibility. """ if not base_survey in self: - raise KeyError("No such survey: %s" % base_survey) + raise KeyError(f"No such survey: {base_survey}") if not monitor_survey in self: - raise KeyError("No such survey: %s" % monitor_survey) + raise KeyError(f"No such survey: {monitor_survey}") return self._eval( base_survey, diff --git a/python/resdata/grid/cell.py b/python/resdata/grid/cell.py index cf8c850c4..f4d80c965 100644 --- a/python/resdata/grid/cell.py +++ b/python/resdata/grid/cell.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -class Cell(object): +class Cell: def __init__(self, grid, global_index): self._grid = grid self._idx = global_index @@ -68,7 +68,7 @@ def __contains__(self, coord): """ if len(coord) != 3: raise ValueError( - "Cell contains takes a triple (x,y,z), was given %s." % coord + f"Cell contains takes a triple (x,y,z), was given {coord}." ) x, y, z = coord return self._grid._cell_contains(self._idx, x, y, z) @@ -102,7 +102,7 @@ def corners(self): def __repr__(self): act = "active" if self.active else "inactive" - pos = "(%.3f, %.3f, %.3f)" % self.coordinate + pos = "({:.3f}, {:.3f}, {:.3f})".format(*self.coordinate) cnt = "%d, %d, %d, %s, %s, grid=%s" % ( self.i, self.j, @@ -112,4 +112,4 @@ def __repr__(self): self._grid.get_name(), ) - return "Cell(%s)" % cnt + return f"Cell({cnt})" diff --git a/python/resdata/grid/faults/fault.py b/python/resdata/grid/faults/fault.py index 296682a0d..fdeb8dbbc 100644 --- a/python/resdata/grid/faults/fault.py +++ b/python/resdata/grid/faults/fault.py @@ -7,7 +7,7 @@ from .fault_segments import FaultSegment, SegmentMap -class FaultLayer(object): +class FaultLayer: def __init__(self, grid, K): assert isinstance(K, int) self.__grid = grid @@ -143,7 +143,7 @@ def process_segments(self): ################################################################# -class Fault(object): +class Fault: allowed_faces = ["X", "Y", "Z", "I", "J", "K", "X-", "Y-", "Z-", "I-", "J-", "K-"] def __init__(self, grid, name): @@ -154,7 +154,7 @@ def __init__(self, grid, name): (self.nx, self.ny, self.nz, nactive) = grid.getDims() def __str__(self): - return "Fault:%s" % self.__name + return f"Fault:{self.__name}" def __getitem__(self, K): if not self.hasLayer(K): @@ -166,8 +166,7 @@ def __len__(self): return len(self.__layer_map) def __iter__(self): - for layer in self.__layer_list: - yield layer + yield from self.__layer_list def has_layer(self, K): return K in self.__layer_map @@ -197,7 +196,7 @@ def create_segment(self, I1, I2, J1, J2, face): def add_record(self, I1, I2, J1, J2, K1, K2, face): if not face in Fault.allowed_faces: - raise ValueError("Invalid face:%s" % face) + raise ValueError(f"Invalid face:{face}") if I1 > I2: raise ValueError("Invalid I1 I2 indices") @@ -224,13 +223,13 @@ def add_record(self, I1, I2, J1, J2, K1, K2, face): raise ValueError("Invalid K2:%d" % K2) if face in ["X", "I"] and I1 != I2: - raise ValueError("For face:%s we must have I1 == I2" % face) + raise ValueError(f"For face:{face} we must have I1 == I2") if face in ["Y", "J"] and J1 != J2: - raise ValueError("For face:%s we must have J1 == J2" % face) + raise ValueError(f"For face:{face} we must have J1 == J2") if face in ["Z", "K"] and K1 != K2: - raise ValueError("For face:%s we must have K1 == K2" % face) + raise ValueError(f"For face:{face} we must have K1 == K2") # ----------------------------------------------------------------- @@ -257,7 +256,7 @@ def get_neighbor_cells(self): def get_polyline(self, k): layer = self[k] - return layer.getPolyline(name="Polyline[%s]" % self.getName()) + return layer.getPolyline(name=f"Polyline[{self.getName()}]") def get_ij_polyline(self, k): layer = self[k] @@ -396,7 +395,7 @@ def extend_to_b_box(self, bbox, k, start=True): intersections = GeometryTools.rayPolygonIntersections(p1, ray_dir, bbox) if intersections: p2 = intersections[0][1] - name = "Extend:%s" % self.getName() if self.getName() else None + name = f"Extend:{self.getName()}" if self.getName() else None return CPolyline(name=name, init_points=[(p1[0], p1[1]), p2]) else: diff --git a/python/resdata/grid/faults/fault_block.py b/python/resdata/grid/faults/fault_block.py index 9ad0f6090..e8641bcab 100644 --- a/python/resdata/grid/faults/fault_block.py +++ b/python/resdata/grid/faults/fault_block.py @@ -7,7 +7,7 @@ from resdata.geometry import Polyline, GeometryTools, CPolylineCollection -class FaultBlockCell(object): +class FaultBlockCell: def __init__(self, i, j, k, x, y, z): self.i = i self.j = j diff --git a/python/resdata/grid/faults/fault_block_layer.py b/python/resdata/grid/faults/fault_block_layer.py index aa095b07f..88ca0d014 100644 --- a/python/resdata/grid/faults/fault_block_layer.py +++ b/python/resdata/grid/faults/fault_block_layer.py @@ -1,4 +1,3 @@ -from __future__ import print_function from cwrap import BaseCClass from resdata.util.util import monkey_the_camel @@ -55,7 +54,7 @@ class FaultBlockLayer(BaseCClass): def __init__(self, grid, k): c_ptr = self._alloc(grid, k) if c_ptr: - super(FaultBlockLayer, self).__init__(c_ptr) + super().__init__(c_ptr) else: raise ValueError("Invalid input - failed to create FaultBlockLayer") @@ -152,7 +151,7 @@ def add_block(self, block_id=None): block_id = self.getNextID() if block_id in self: - raise KeyError("Layer already contains block with ID:%s" % block_id) + raise KeyError(f"Layer already contains block with ID:{block_id}") else: return self._add_block(block_id).setParent(self) diff --git a/python/resdata/grid/faults/fault_collection.py b/python/resdata/grid/faults/fault_collection.py index 7930b3f61..a9aa4bacc 100644 --- a/python/resdata/grid/faults/fault_collection.py +++ b/python/resdata/grid/faults/fault_collection.py @@ -12,12 +12,12 @@ def dequote(s): if s[0] == s[-1]: return s[1:-1] else: - raise ValueError("s[0] != s[-1], s[0]={}, s[-1]={}".format(s[0], s[-1])) + raise ValueError(f"s[0] != s[-1], s[0]={s[0]}, s[-1]={s[-1]}") else: return s -class FaultCollection(object): +class FaultCollection: def __init__(self, grid=None, *file_list): self.__fault_list = [] self.__fault_map = {} @@ -64,10 +64,10 @@ def add_fault(self, fault): def split_line(self, line): tmp = line.split() if not tmp[-1] == "/": - raise ValueError("Line:%s does not end with /" % line) + raise ValueError(f"Line:{line} does not end with /") if len(tmp) != 9: - raise ValueError("Line:%s not correct number of items" % line) + raise ValueError(f"Line:{line} not correct number of items") fault_name = dequote(tmp[0]) I1 = int(tmp[1]) - 1 diff --git a/python/resdata/grid/faults/fault_line.py b/python/resdata/grid/faults/fault_line.py index 395029128..5f38e8ec2 100644 --- a/python/resdata/grid/faults/fault_line.py +++ b/python/resdata/grid/faults/fault_line.py @@ -7,7 +7,7 @@ from .fault_segments import FaultSegment -class FaultLine(object): +class FaultLine: def __init__(self, grid, k): self.__grid = grid self.__k = k diff --git a/python/resdata/grid/faults/fault_segments.py b/python/resdata/grid/faults/fault_segments.py index 919662a06..24ca47441 100644 --- a/python/resdata/grid/faults/fault_segments.py +++ b/python/resdata/grid/faults/fault_segments.py @@ -1,9 +1,7 @@ -from __future__ import print_function - from resdata.util.util import monkey_the_camel -class FaultSegment(object): +class FaultSegment: def __init__(self, C1, C2): self.__C1 = C1 self.__C2 = C2 @@ -53,7 +51,7 @@ def __repr__(self): return "%d -> %d" % (self.__C1, self.__C2) -class SegmentMap(object): +class SegmentMap: def __init__(self): self.__segment_map = {} self.__count_map = {} diff --git a/python/resdata/grid/faults/layer.py b/python/resdata/grid/faults/layer.py index 7f5f6f61f..99dc5ef80 100644 --- a/python/resdata/grid/faults/layer.py +++ b/python/resdata/grid/faults/layer.py @@ -49,7 +49,7 @@ class Layer(BaseCClass): def __init__(self, nx, ny): c_ptr = self._alloc(nx, ny) if c_ptr: - super(Layer, self).__init__(c_ptr) + super().__init__(c_ptr) else: raise ValueError("Invalid input - no Layer object created") @@ -65,7 +65,7 @@ def __unpack_index(self, index): (i, j) = index except TypeError as err: raise ValueError( - "Index:%s is invalid - must have two integers" % str(index) + f"Index:{str(index)} is invalid - must have two integers" ) from err self._assert_ij(i, j) diff --git a/python/resdata/grid/rd_grid.py b/python/resdata/grid/rd_grid.py index 493a2f042..ff31311a3 100644 --- a/python/resdata/grid/rd_grid.py +++ b/python/resdata/grid/rd_grid.py @@ -231,7 +231,7 @@ def load_from_grdecl(cls, filename): return Grid.create(specgrid, zcorn, coord, actnum, mapaxes) else: - raise IOError("No such file:%s" % filename) + raise OSError(f"No such file:{filename}") @classmethod def load_from_file(cls, filename): @@ -316,9 +316,9 @@ def __init__(self, filename, apply_mapaxes=True): """ c_ptr = self._fread_alloc(filename, apply_mapaxes) if c_ptr: - super(Grid, self).__init__(c_ptr) + super().__init__(c_ptr) else: - raise IOError("Loading grid from:%s failed" % filename) + raise OSError(f"Loading grid from:{filename} failed") def free(self): self._free() @@ -336,7 +336,7 @@ def __repr__(self): """ name = self._nicename() if name: - name = '"%s", ' % name + name = f'"{name}", ' g_size = self.getGlobalSize() a_size = self.getNumActive() xyz_s = "%dx%dx%d" % (self.getNX(), self.getNY(), self.getNZ()) @@ -496,8 +496,7 @@ def __iter__(self): def cells(self, active=False): """Iterator over all the (active) cells""" if not active: - for c in self: - yield c + yield from self else: for i in range(self.get_num_active()): yield self.cell(active_index=i) @@ -1065,7 +1064,7 @@ def get_lgr(self, lgr_key): lgr = self._get_named_lgr(lgr_key) if lgr is None: - raise KeyError("No such LGR: %s" % lgr_key) + raise KeyError(f"No such LGR: {lgr_key}") lgr.setParent(self) return lgr @@ -1148,7 +1147,7 @@ def create_kw(self, array, kw_name, pack): elif dtype == np.float64: type = ResDataType.RD_DOUBLE else: - sys.exit("Do not know how to create rd_kw from type:%s" % dtype) + sys.exit(f"Do not know how to create rd_kw from type:{dtype}") size = self.getNumActive() if pack else self.getGlobalSize() diff --git a/python/resdata/grid/rd_grid_generator.py b/python/resdata/grid/rd_grid_generator.py index 167569111..88e60ad06 100644 --- a/python/resdata/grid/rd_grid_generator.py +++ b/python/resdata/grid/rd_grid_generator.py @@ -177,7 +177,7 @@ def create_zcorn( zcorn = cls.__create_faults(nx, ny, nz, zcorn, drop) if z != escape_origo_shift[2] + nz * dz: - raise ValueError("%f != %f" % (z, escape_origo_shift[2] + nz * dz)) + raise ValueError(f"{z:f} != {escape_origo_shift[2] + nz * dz:f}") cls.assert_zcorn(nx, ny, nz, zcorn) return construct_floatKW("ZCORN", zcorn) @@ -495,8 +495,9 @@ def assert_actnum(cls, nx, ny, nz, actnum): if set(actnum) - {0, 1}: raise AssertionError( - "Expected ACTNUM to consist of 0's and 1's, was %s." - % ", ".join(map(str, set(actnum))) + "Expected ACTNUM to consist of 0's and 1's, was {}.".format( + ", ".join(map(str, set(actnum))) + ) ) @classmethod @@ -734,7 +735,7 @@ def assert_ijk_bounds(cls, dims, ijk_bounds): if not (isinstance(bound[0], int) and isinstance(bound[1], int)): raise TypeError( "Expected bound to consist of two integers, ", - "was %s (%s)" % (str(bound), str((map(type, bound)))), + f"was {str(bound)} ({str(map(type, bound))})", ) if not (0 <= bound[0] <= bound[1] < n): @@ -750,7 +751,7 @@ def assert_ijk_bounds(cls, dims, ijk_bounds): def assert_decomposition_change(cls, ijk_bounds, decomposition_change): if sum(list(zip(*ijk_bounds))[0]) % 2 == 1 and not decomposition_change: raise ValueError( - "The subgrid defined by %s " % str(ijk_bounds) + f"The subgrid defined by {str(ijk_bounds)} " + "will cause an unintended decomposition change. " + "Either change one of the lower bounds by 1 " + "or activate decomposition_change." diff --git a/python/resdata/grid/rd_region.py b/python/resdata/grid/rd_region.py index add2e7bec..36c8c8bd9 100644 --- a/python/resdata/grid/rd_region.py +++ b/python/resdata/grid/rd_region.py @@ -317,7 +317,7 @@ def __init__(self, grid, preselect): self.grid = grid self.active_index = False c_ptr = self._alloc(grid, preselect) - super(ResdataRegion, self).__init__(c_ptr) + super().__init__(c_ptr) def free(self): self._free() @@ -551,8 +551,7 @@ def select_equal(self, rd_kw, value, intersect=False): """ if not rd_kw.data_type.is_int(): raise ValueError( - "The select_equal method must have an integer valued keyword - got:%s" - % rd_kw.type_name() + f"The select_equal method must have an integer valued keyword - got:{rd_kw.type_name()}" ) self._select_equal(rd_kw, value) @@ -564,8 +563,7 @@ def deselect_equal(self, rd_kw, value): """ if not rd_kw.data_type.is_int(): raise ValueError( - "The select_equal method must have an integer valued keyword - got:%s" - % rd_kw.type_name() + f"The select_equal method must have an integer valued keyword - got:{rd_kw.type_name()}" ) self._deselect_equal(rd_kw, value) diff --git a/python/resdata/rd_type.py b/python/resdata/rd_type.py index 7af86c47e..6b79197e6 100644 --- a/python/resdata/rd_type.py +++ b/python/resdata/rd_type.py @@ -64,7 +64,7 @@ def __init__(self, type_enum=None, element_size=None, type_name=None): else: c_ptr = self._alloc(type_enum, element_size) - super(ResDataType, self).__init__(c_ptr) + super().__init__(c_ptr) def _assert_valid_arguments(self, type_enum, element_size, type_name): if type_name is not None: @@ -148,7 +148,7 @@ def create_from_type_name(cls, name): return ResDataType(type_name=name) # Enables one to fetch a type as ResDataType.RD_XXXX - class classproperty(object): + class classproperty: def __init__(self, fget): self.fget = fget diff --git a/python/resdata/rd_util.py b/python/resdata/rd_util.py index 1454330fd..a4d5b8f87 100644 --- a/python/resdata/rd_util.py +++ b/python/resdata/rd_util.py @@ -10,8 +10,6 @@ functions from rd_util.c which are not bound to any class type. """ -from __future__ import absolute_import - import ctypes from cwrap import BaseCEnum @@ -99,7 +97,7 @@ class FileMode(BaseCEnum): # ----------------------------------------------------------------- -class ResdataUtil(object): +class ResdataUtil: _get_num_cpu = ResdataPrototype("int rd_get_num_cpu(char*)", bind=False) _get_file_type = ResdataPrototype( "rd_file_enum rd_get_file_type(char*, bool*, int*)", bind=False @@ -149,7 +147,7 @@ def inspect_extension(filename): def report_step(filename): report_step = ResdataUtil._get_report_step(filename) if report_step < 0: - raise ValueError("Could not infer report step from: %s" % filename) + raise ValueError(f"Could not infer report step from: {filename}") return report_step diff --git a/python/resdata/resfile/fortio.py b/python/resdata/resfile/fortio.py index e261e15b9..d0a8903fd 100644 --- a/python/resdata/resfile/fortio.py +++ b/python/resdata/resfile/fortio.py @@ -100,7 +100,7 @@ def __init__( """ read_modes = (FortIO.READ_MODE, FortIO.APPEND_MODE, FortIO.READ_AND_WRITE_MODE) if mode in read_modes and not os.path.exists(file_name): - raise IOError('No such file "%s".' % file_name) + raise OSError(f'No such file "{file_name}".') if mode == FortIO.READ_MODE: c_pointer = self._open_reader(file_name, fmt_file, endian_flip_header) elif mode == FortIO.WRITE_MODE: @@ -114,8 +114,8 @@ def __init__( self.__mode = mode if not c_pointer: - raise IOError('Failed to open FortIO file "%s".' % file_name) - super(FortIO, self).__init__(c_pointer) + raise OSError(f'Failed to open FortIO file "{file_name}".') + super().__init__(c_pointer) def close(self): if self: @@ -136,7 +136,7 @@ def truncate(self, size=None): size = self.getPosition() if not self._truncate(size): - raise IOError("Truncate of fortran filehandle:%s failed" % self.filename()) + raise OSError(f"Truncate of fortran filehandle:{self.filename()} failed") def filename(self): return self._filename() @@ -163,7 +163,7 @@ def free(self): self.close() -class FortIOContextManager(object): +class FortIOContextManager: def __init__(self, fortio): self.__fortio = fortio diff --git a/python/resdata/resfile/rd_3d_file.py b/python/resdata/resfile/rd_3d_file.py index c5bbc2c64..c94de1eed 100644 --- a/python/resdata/resfile/rd_3d_file.py +++ b/python/resdata/resfile/rd_3d_file.py @@ -4,10 +4,10 @@ class Resdata3DFile(ResdataFile): def __init__(self, grid, filename, flags=0): self.grid = grid - super(Resdata3DFile, self).__init__(filename, flags) + super().__init__(filename, flags) def __getitem__(self, index): - return_arg = super(Resdata3DFile, self).__getitem__(index) + return_arg = super().__getitem__(index) kw_list = return_arg if isinstance(return_arg, list) else [return_arg] # Go through all the keywords and try inplace promotion to Resdata3DKW diff --git a/python/resdata/resfile/rd_3dkw.py b/python/resdata/resfile/rd_3dkw.py index 5c0e6e825..8f3b1bbf4 100644 --- a/python/resdata/resfile/rd_3dkw.py +++ b/python/resdata/resfile/rd_3dkw.py @@ -53,7 +53,7 @@ class Resdata3DKW(ResdataKW): def __init__(self, kw, grid, value_type, default_value=0, global_active=False): size = grid.getGlobalSize() if global_active else grid.getNumActive() - super(Resdata3DKW, self).__init__(kw, size, value_type) + super().__init__(kw, size, value_type) self.grid = grid self.global_active = global_active self.setDefault(default_value) @@ -70,7 +70,7 @@ def read_grdecl(cls, grid, fileH, kw, strict=True, rd_type=None): See the base class ResdataKW.read_grdecl() for more documentation. """ - kw = super(Resdata3DKW, cls).read_grdecl(fileH, kw, strict, rd_type) + kw = super().read_grdecl(fileH, kw, strict, rd_type) Resdata3DKW.castFromKW(kw, grid) return kw @@ -96,7 +96,7 @@ def __getitem__(self, index): else: index = self.grid.get_active_index(ijk=index) - return super(Resdata3DKW, self).__getitem__(index) + return super().__getitem__(index) def __setitem__(self, index, value): """Set the value of at index [g] or [i,j,k]. @@ -120,7 +120,7 @@ def __setitem__(self, index, value): else: index = self.grid.get_active_index(ijk=index) - return super(Resdata3DKW, self).__setitem__(index, value) + return super().__setitem__(index, value) @classmethod def cast_from_kw(cls, kw, grid, default_value=0): diff --git a/python/resdata/resfile/rd_file.py b/python/resdata/resfile/rd_file.py index c2e6ac5d0..58805fa32 100644 --- a/python/resdata/resfile/rd_file.py +++ b/python/resdata/resfile/rd_file.py @@ -132,8 +132,7 @@ def report_list(self): report_steps.append(int(matchObj.group(1))) else: raise TypeError( - 'Tried get list of report steps from file "%s" - which is not a restart file' - % fname + f'Tried get list of report steps from file "{fname}" - which is not a restart file' ) from err return report_steps @@ -150,7 +149,7 @@ def file_report_list(cls, filename): def __repr__(self): fn = self.getFilename() wr = ", read/write" if self._writable() else "" - return self._create_repr('"%s"%s' % (fn, wr)) + return self._create_repr(f'"{fn}"{wr}') def __init__(self, filename, flags=FileMode.DEFAULT, index_filename=None): """ @@ -182,9 +181,9 @@ def __init__(self, filename, flags=FileMode.DEFAULT, index_filename=None): c_ptr = self._fast_open(filename, index_filename, flags) if c_ptr is None: - raise IOError('Failed to open file "%s"' % filename) + raise OSError(f'Failed to open file "{filename}"') else: - super(ResdataFile, self).__init__(c_ptr) + super().__init__(c_ptr) self.global_view = self._get_global_view() self.global_view.setParent(self) @@ -214,8 +213,8 @@ def save_kw(self, kw): if self._writable(): self._save_kw(kw) else: - raise IOError( - 'save_kw: the file "%s" has been opened read only.' % self.getFilename() + raise OSError( + f'save_kw: the file "{self.getFilename()}" has been opened read only.' ) def __len__(self): @@ -231,7 +230,7 @@ def free(self): def block_view(self, kw, kw_index): if not kw in self: - raise KeyError('No such keyword "%s".' % kw) + raise KeyError(f'No such keyword "{kw}".') ls = self.global_view.numKeywords(kw) idx = kw_index if idx < 0: @@ -366,15 +365,11 @@ def restart_get_kw(self, kw_name, dtime, copy=False): else: return kw elif self.has_kw(kw_name): - raise IndexError( - 'Does not have keyword "%s" at time:%s.' % (kw_name, dtime) - ) + raise IndexError(f'Does not have keyword "{kw_name}" at time:{dtime}.') else: - raise KeyError('Keyword "%s" not recognized.' % kw_name) + raise KeyError(f'Keyword "{kw_name}" not recognized.') else: - raise IndexError( - 'Does not have keyword "%s" at time:%s.' % (kw_name, dtime) - ) + raise IndexError(f'Does not have keyword "{kw_name}" at time:{dtime}.') @property def size(self): @@ -560,10 +555,10 @@ def fwrite(self, fortio): def write_index(self, index_file_name): if not self or not self._write_index(index_file_name): - raise IOError("Failed to write index file:%s" % index_file_name) + raise OSError(f"Failed to write index file:{index_file_name}") -class ResdataFileContextManager(object): +class ResdataFileContextManager: def __init__(self, rd_file): self.__rd_file = rd_file diff --git a/python/resdata/resfile/rd_file_view.py b/python/resdata/resfile/rd_file_view.py index e4abc9977..f7fc47f8f 100644 --- a/python/resdata/resfile/rd_file_view.py +++ b/python/resdata/resfile/rd_file_view.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import, division, print_function, unicode_literals from six import string_types from cwrap import BaseCClass from resdata.util.util import monkey_the_camel @@ -45,7 +44,7 @@ def __repr__(self): def iget_named_kw(self, kw_name, index): if not kw_name in self: - raise KeyError("No such keyword: %s" % kw_name) + raise KeyError(f"No such keyword: {kw_name}") if index >= self.numKeywords(kw_name): raise IndexError("Too large index: %d" % index) @@ -107,7 +106,7 @@ def __getitem__(self, index): kw_list.append(self.iget_named_kw(kw_index, index)) return kw_list else: - raise KeyError("Unrecognized keyword:'%s'" % index) + raise KeyError(f"Unrecognized keyword:'{index}'") else: raise TypeError("Index must be integer or string (keyword)") @@ -130,7 +129,7 @@ def block_view2(self, start_kw, stop_kw, start_index): idx = start_index if start_kw: if not start_kw in self: - raise KeyError("The keyword:%s is not in file" % start_kw) + raise KeyError(f"The keyword:{start_kw} is not in file") ls = self.numKeywords(start_kw) if idx < 0: @@ -141,7 +140,7 @@ def block_view2(self, start_kw, stop_kw, start_index): ) if stop_kw and not stop_kw in self: - raise KeyError("The keyword:%s is not in file" % stop_kw) + raise KeyError(f"The keyword:{stop_kw} is not in file") view = self._create_block_view2(start_kw, stop_kw, idx) view.setParent(parent=self) @@ -151,7 +150,7 @@ def block_view(self, kw, kw_index): num = self.numKeywords(kw) if num == 0: - raise KeyError("Unknown keyword: %s" % kw) + raise KeyError(f"Unknown keyword: {kw}") idx = kw_index if idx < 0: diff --git a/python/resdata/resfile/rd_init_file.py b/python/resdata/resfile/rd_init_file.py index 8771c45f4..90ce37b0a 100644 --- a/python/resdata/resfile/rd_init_file.py +++ b/python/resdata/resfile/rd_init_file.py @@ -6,7 +6,7 @@ class ResdataInitFile(Resdata3DFile): def __init__(self, grid, filename, flags=FileMode.DEFAULT): file_type, report_step, fmt_file = ResdataFile.getFileType(filename) if file_type == FileType.INIT: - super(ResdataInitFile, self).__init__(grid, filename, flags) + super().__init__(grid, filename, flags) else: err = 'The input filename "%s" does not correspond to an init file.' err += " Please follow the Eclipse naming conventions." diff --git a/python/resdata/resfile/rd_kw.py b/python/resdata/resfile/rd_kw.py index c57c1bf57..7fe5a3ee9 100644 --- a/python/resdata/resfile/rd_kw.py +++ b/python/resdata/resfile/rd_kw.py @@ -196,7 +196,7 @@ class ResdataKW(BaseCClass): @classmethod def createCReference(cls, c_ptr, parent=None): - rd_kw = super(ResdataKW, cls).createCReference(c_ptr, parent=parent) + rd_kw = super().createCReference(c_ptr, parent=parent) if rd_kw is None: raise ValueError("Failed to create ResdataKW instance") @@ -205,7 +205,7 @@ def createCReference(cls, c_ptr, parent=None): @classmethod def createPythonObject(cls, c_ptr): - rd_kw = super(ResdataKW, cls).createPythonObject(c_ptr) + rd_kw = super().createPythonObject(c_ptr) if rd_kw is None: raise ValueError("Failed to create ResdataKW instance") @@ -314,7 +314,7 @@ def read_grdecl(cls, fileH, kw, strict=True, rd_type=None): cfile = CFILE(fileH) if kw and len(kw) > 8: raise TypeError( - "Sorry keyword:%s is too long, must be eight characters or less." % kw + f"Sorry keyword:{kw} is too long, must be eight characters or less." ) if rd_type is None: @@ -326,12 +326,11 @@ def read_grdecl(cls, fileH, kw, strict=True, rd_type=None): rd_type = warn_and_cast_data_type(rd_type) if not isinstance(rd_type, ResDataType): - raise TypeError("Expected ResDataType, was: %s" % type(rd_type)) + raise TypeError(f"Expected ResDataType, was: {type(rd_type)}") if not rd_type in [ResDataType.RD_FLOAT, ResDataType.RD_INT]: raise ValueError( - "The type:%s is invalid when loading keyword:%s" - % (rd_type.type_name, kw) + f"The type:{rd_type.type_name} is invalid when loading keyword:{kw}" ) return cls._load_grdecl(cfile, kw, strict, rd_type) @@ -377,10 +376,10 @@ def free(self): def __repr__(self): si = len(self) nm = self.getName() - mm = "type=%s" % str(self.data_type) + mm = f"type={str(self.data_type)}" if self.isNumeric(): mi, ma = self.getMinMax() - mm = "min=%.2f, max=%.2f" % (mi, ma) + mm = f"min={mi:.2f}, max={ma:.2f}" ad = self._ad_str() fmt = 'ResdataKW(size=%d, name="%s", %s) %s' return fmt % (si, nm, mm, ad) @@ -402,10 +401,10 @@ def __init__(self, name, size, data_type): data_type = warn_and_cast_data_type(data_type) if not isinstance(data_type, ResDataType): - raise TypeError("Expected an ResDataType, received: %s" % type(data_type)) + raise TypeError(f"Expected an ResDataType, received: {type(data_type)}") c_ptr = self._alloc_new(name, size, data_type) - super(ResdataKW, self).__init__(c_ptr) + super().__init__(c_ptr) self.__private_init() def __private_init(self): @@ -436,7 +435,7 @@ def __private_init(self): elif self.data_type.is_string(): self.str_fmt = "%" + str(self.data_type.element_size) + "s" else: - raise ValueError("Unknown ResDataType (%s)!" % self.data_type.type_name) + raise ValueError(f"Unknown ResDataType ({self.data_type.type_name})!") def sub_copy(self, offset, count, new_header=None): """ @@ -695,8 +694,7 @@ def sum(self, mask=None, force_active=False): return sum else: raise ValueError( - 'The keyword "%s" is of string type - sum is not implemented' - % self.getName() + f'The keyword "{self.getName()}" is of string type - sum is not implemented' ) return mask.sum_kw(self, force_active) @@ -950,7 +948,7 @@ def get_min_max(self): self._max_min_int(ctypes.byref(max_), ctypes.byref(min_)) else: raise TypeError( - "min_max property not defined for keywords of type: %s" % self.type + f"min_max property not defined for keywords of type: {self.type}" ) return (min_.value, max_.value) @@ -1201,9 +1199,7 @@ def scatter_copy(self, actnum): def safe_div(self, divisor): if not len(self) == len(divisor): - raise ValueError( - "Length mismatch between %s and %s" % (self.name, divisor.name) - ) + raise ValueError(f"Length mismatch between {self.name} and {divisor.name}") if not self.is_numeric(): raise TypeError("The self keyword must be of numeric type") diff --git a/python/resdata/resfile/rd_restart_file.py b/python/resdata/resfile/rd_restart_file.py index bc4c86945..fca970d6e 100644 --- a/python/resdata/resfile/rd_restart_file.py +++ b/python/resdata/resfile/rd_restart_file.py @@ -34,7 +34,7 @@ def __init__(self, kw_arg=None, rst_view=None): else: c_ptr = self._alloc(rst_view, -1) - super(ResdataRestartHead, self).__init__(c_ptr) + super().__init__(c_ptr) def free(self): self._free() @@ -74,11 +74,10 @@ def __init__(self, grid, filename, flags=FileMode.DEFAULT): FileType.UNIFIED_RESTART, ]: raise ValueError( - 'The input filename "%s" does not correspond to a restart file. Please follow the Eclipse naming conventions' - % filename + f'The input filename "{filename}" does not correspond to a restart file. Please follow the Eclipse naming conventions' ) - super(ResdataRestartFile, self).__init__(grid, filename, flags) + super().__init__(grid, filename, flags) self.rst_headers = None if file_type == FileType.RESTART: self.is_unified = False diff --git a/python/resdata/rft/rd_rft.py b/python/resdata/rft/rd_rft.py index 778ad5539..fe33cb138 100644 --- a/python/resdata/rft/rd_rft.py +++ b/python/resdata/rft/rd_rft.py @@ -59,7 +59,7 @@ class ResdataRFT(BaseCClass): def __init__(self, name, type_string, date, days): c_ptr = self._alloc(name, type_string, CTime(date), days) - super(ResdataRFT, self).__init__(c_ptr) + super().__init__(c_ptr) def free(self): self._free() @@ -67,7 +67,7 @@ def free(self): def __repr__(self): rs = [] rs.append("completed_cells = %d" % len(self)) - rs.append("date = %s" % self.getDate()) + rs.append(f"date = {self.getDate()}") if self.is_RFT(): rs.append("RFT") if self.is_PLT(): @@ -205,7 +205,7 @@ class ResdataRFTFile(BaseCClass): def __init__(self, case): c_ptr = self._load(case) - super(ResdataRFTFile, self).__init__(c_ptr) + super().__init__(c_ptr) def __len__(self): return self._get_size(None, CTime(-1)) @@ -272,7 +272,7 @@ def get(self, well_name, date): Raise Exception if not found. """ if self.size(well=well_name, date=date) == 0: - raise KeyError("No RFT for well:%s at %s" % (well_name, date)) + raise KeyError(f"No RFT for well:{well_name} at {date}") rft = self._get_rft(well_name, CTime(date)) rft.setParent(self) diff --git a/python/resdata/rft/rd_rft_cell.py b/python/resdata/rft/rd_rft_cell.py index bcbdcf78d..e6e4c15f5 100644 --- a/python/resdata/rft/rd_rft_cell.py +++ b/python/resdata/rft/rd_rft_cell.py @@ -65,7 +65,7 @@ class ResdataRFTCell(RFTCell): def __init__(self, i, j, k, depth, pressure, swat, sgas): c_ptr = self._alloc_RFT(i, j, k, depth, pressure, swat, sgas) - super(ResdataRFTCell, self).__init__(c_ptr) + super().__init__(c_ptr) @property def swat(self): @@ -144,7 +144,7 @@ def __init__( gas_flowrate, water_flowrate, ) - super(ResdataPLTCell, self).__init__(c_ptr) + super().__init__(c_ptr) @property def orat(self): diff --git a/python/resdata/rft/well_trajectory.py b/python/resdata/rft/well_trajectory.py index 20d7722d7..45b08ddf1 100644 --- a/python/resdata/rft/well_trajectory.py +++ b/python/resdata/rft/well_trajectory.py @@ -31,7 +31,7 @@ def _parse_point(point): tvd = float(point[3]) except ValueError as err: raise UserWarning( - "Error: Failed to extract data from line %s\n" % str(point) + f"Error: Failed to extract data from line {str(point)}\n" ) from err zone = None if len(point) > 4: @@ -43,7 +43,7 @@ class WellTrajectory: def __init__(self, filename): self._points = [] if not isfile(filename): - raise IOError('No such file "%s"' % filename) + raise OSError(f'No such file "{filename}"') with open(filename) as fileH: for line in fileH.readlines(): @@ -66,4 +66,4 @@ def __repr__(self): return "WellTrajectory(len=%d)" % len(self) def __str__(self): - return "WellTrajectory(%s)" % str(self._points) + return f"WellTrajectory({str(self._points)})" diff --git a/python/resdata/summary/rd_cmp.py b/python/resdata/summary/rd_cmp.py index 20f41c13c..77458a99a 100644 --- a/python/resdata/summary/rd_cmp.py +++ b/python/resdata/summary/rd_cmp.py @@ -3,7 +3,7 @@ from .rd_sum import Summary -class ResdataCase(object): +class ResdataCase: def __init__(self, case): self.case = case @@ -48,10 +48,10 @@ def cmp_summary_vector(self, other, key, sample=100): diff_sum = sum(abs(diff_data)) return (diff_sum, ref_sum) else: - raise KeyError("Key:%s was not present in both cases" % key) + raise KeyError(f"Key:{key} was not present in both cases") -class ResdataCmp(object): +class ResdataCmp: def __init__(self, test_case, ref_case): """Class to compare to simulation cases with Eclipse formatted result files. diff --git a/python/resdata/summary/rd_npv.py b/python/resdata/summary/rd_npv.py index 638be8c1c..c048adfc8 100644 --- a/python/resdata/summary/rd_npv.py +++ b/python/resdata/summary/rd_npv.py @@ -7,7 +7,7 @@ from .rd_sum import Summary -class NPVParseKey(object): +class NPVParseKey: def __init__(self, eclNPV): self.baseCase = eclNPV.baseCase self.NPV = eclNPV @@ -20,10 +20,10 @@ def __call__(self, matchObject): self.NPV.addKey(key, var) return var + "[i]" else: - raise ValueError("Sorry - the key: %s is not a total key - aborting" % key) + raise ValueError(f"Sorry - the key: {key} is not a total key - aborting") -class NPVPriceVector(object): +class NPVPriceVector: def __init__(self, argList): self.dateList = [] if isinstance(argList, list): @@ -109,10 +109,10 @@ def eval(self, date): index2 = index return self.evalDate(self.dateList[index], date) else: - raise ValueError("Input date:%s before start of vector" % date) + raise ValueError(f"Input date:{date} before start of vector") -class ResdataNPV(object): +class ResdataNPV: sumKeyRE = re.compile(r"[\[]([\w:,]+)[\]]") def __init__(self, baseCase): @@ -120,7 +120,7 @@ def __init__(self, baseCase): if sum: self.baseCase = sum else: - raise OSError("Failed to open summary case:%s" % baseCase) + raise OSError(f"Failed to open summary case:{baseCase}") self.expression = None self.keyList = {} self.start = None @@ -148,9 +148,7 @@ def add_key(self, key, var): def parse_expression(self, expression): self.keyList = {} if expression.count("[") != expression.count("]"): - raise ValueError( - "Expression:%s invalid - not matching [ and ]" % expression - ) + raise ValueError(f"Expression:{expression} invalid - not matching [ and ]") replaceKey = NPVParseKey(self) parsedExpression = self.sumKeyRE.sub(replaceKey, expression) @@ -162,20 +160,14 @@ def compile(self, expression): "trange = self.baseCase.timeRange(self.start, self.end, self.interval)\n" ) for key, var in self.keyList.items(): - self.code += '%s = self.baseCase.blockedProduction("%s", trange)\n' % ( - var, - key, - ) + self.code += f'{var} = self.baseCase.blockedProduction("{key}", trange)\n' self.code += "npv = 0\n" - self.code += ( - """ + self.code += f""" for i in range(len(trange) - 1): - npv += %s + npv += {parsedExpression} varDict[\"npv\"] = npv """ - % parsedExpression - ) def eval_npv(self): byteCode = compile(self.code, "", "exec") diff --git a/python/resdata/summary/rd_smspec_node.py b/python/resdata/summary/rd_smspec_node.py index 5460aae7b..8a8e908ec 100644 --- a/python/resdata/summary/rd_smspec_node.py +++ b/python/resdata/summary/rd_smspec_node.py @@ -34,7 +34,7 @@ class ResdataSMSPECNode(BaseCClass): _get_default = ResdataPrototype("float smspec_node_get_default(rd_smspec_node)") def __init__(self): - super(ResdataSMSPECNode, self).__init__(0) # null pointer + super().__init__(0) # null pointer raise NotImplementedError("Class can not be instantiated directly!") def cmp(self, other): diff --git a/python/resdata/summary/rd_sum.py b/python/resdata/summary/rd_sum.py index e6f489e46..a62aa3720 100644 --- a/python/resdata/summary/rd_sum.py +++ b/python/resdata/summary/rd_sum.py @@ -253,20 +253,20 @@ def __init__( load_case, join_string, include_restart, lazy_load, file_options ) if c_pointer is None: - raise IOError( - "Failed to create summary instance from argument:%s" % load_case + raise OSError( + f"Failed to create summary instance from argument:{load_case}" ) - super(Summary, self).__init__(c_pointer) + super().__init__(c_pointer) self._load_case = load_case @classmethod def load(cls, smspec_file, unsmry_file, key_join_string=":", include_restart=True): if not os.path.isfile(smspec_file): - raise IOError("No such file: %s" % smspec_file) + raise OSError(f"No such file: {smspec_file}") if not os.path.isfile(unsmry_file): - raise IOError("No such file: %s" % unsmry_file) + raise OSError(f"No such file: {unsmry_file}") data_files = StringList() data_files.append(unsmry_file) @@ -274,7 +274,7 @@ def load(cls, smspec_file, unsmry_file, key_join_string=":", include_restart=Tru smspec_file, data_files, key_join_string, include_restart ) if c_ptr is None: - raise IOError("Failed to create summary instance") + raise OSError("Failed to create summary instance") rd_sum = cls.createPythonObject(c_ptr) rd_sum._load_case = smspec_file @@ -282,12 +282,12 @@ def load(cls, smspec_file, unsmry_file, key_join_string=":", include_restart=Tru @classmethod def createCReference(cls, c_pointer, parent=None): - result = super(Summary, cls).createCReference(c_pointer, parent) + result = super().createCReference(c_pointer, parent) return result @classmethod def createPythonObject(cls, c_pointer): - result = super(Summary, cls).createPythonObject(c_pointer) + result = super().createPythonObject(c_pointer) return result @staticmethod @@ -387,12 +387,12 @@ def add_t_step(self, report_step, sim_days): """@rtype: SummaryTStep""" # report_step int if not isinstance(report_step, int): - raise TypeError("Parameter report_step should be int, was %r" % report_step) + raise TypeError(f"Parameter report_step should be int, was {report_step!r}") try: float(sim_days) except TypeError as err: raise TypeError( - "Parameter sim_days should be float, was %r" % sim_days + f"Parameter sim_days should be float, was {sim_days!r}" ) from err sim_seconds = sim_days * 24 * 60 * 60 @@ -479,7 +479,7 @@ def get_values(self, key, report_only=False): return values else: - raise KeyError("Summary object does not have key:%s" % key) + raise KeyError(f"Summary object does not have key:{key}") def _make_time_vector(self, time_index): time_points = TimeVector() @@ -511,7 +511,7 @@ def numpy_vector(self, key, time_index=None, report_only=False): """ if key not in self: - raise KeyError("No such key:%s" % key) + raise KeyError(f"No such key:{key}") if report_only: if time_index is None: @@ -701,8 +701,7 @@ def _compile_headers_list( k = int(nums[2]) - 1 if dims is None: raise ValueError( - "For key %s When using indexing i,j,k you must supply a valid value for the dims argument" - % key + f"For key {key} When using indexing i,j,k you must supply a valid value for the dims argument" ) num = i + j * dims[0] + k * dims[0] * dims[1] + 1 @@ -787,7 +786,7 @@ def last_value(self, key): instance with some extra time related information. """ if not key in self: - raise KeyError("No such key:%s" % key) + raise KeyError(f"No such key:{key}") return self._get_last_value(key) @@ -796,7 +795,7 @@ def first_value(self, key): Will return first value corresponding to @key. """ if not key in self: - raise KeyError("No such key:%s" % key) + raise KeyError(f"No such key:{key}") return self._get_first_value(key) @@ -862,7 +861,7 @@ def __contains__(self, key): def assert_key_valid(self, key): if not key in self: - raise KeyError("The summary key:%s was not recognized" % key) + raise KeyError(f"The summary key:{key} was not recognized") def __iter__(self): return iter(self.keys()) @@ -936,14 +935,13 @@ def get_interp(self, key, days=None, date=None): if self.check_sim_time(t): return self._get_general_var_from_sim_time(t, key) else: - raise ValueError("date:%s is outside range of simulation data" % date) + raise ValueError(f"date:{date} is outside range of simulation data") elif date is None: if self._check_sim_days(days): return self._get_general_var_from_sim_days(days, key) else: raise ValueError( - "days:%s is outside range of simulation: [%g,%g]" - % (days, self.first_day, self.sim_length) + f"days:{days} is outside range of simulation: [{self.first_day:g},{self.sim_length:g}]" ) else: raise ValueError("Must supply either days or date") @@ -1146,7 +1144,7 @@ def smspec_node(self, key): node = self._get_var_node(key).setParent(self) return node else: - raise KeyError("Summary case does not have key:%s" % key) + raise KeyError(f"Summary case does not have key:{key}") def unit(self, key): """ @@ -1480,7 +1478,7 @@ def solve_dates(self, key, value, rates_clamp_lower=True): See solveDays() for further details. """ if not key in self: - raise KeyError("Unrecognized key:%s" % key) + raise KeyError(f"Unrecognized key:{key}") if len(self) < 2: raise ValueError("Must have at least two elements to start solving") @@ -1571,7 +1569,7 @@ def solve_days(self, key, value, rates_clamp_lower=True): """ if not key in self: - raise KeyError("Unrecognized key:%s" % key) + raise KeyError(f"Unrecognized key:{key}") if len(self) < 2: raise ValueError("Must have at least two elements to start solving") @@ -1682,9 +1680,7 @@ def resample( new_case_name, time_points, lower_extrapolation, upper_extrapolation ) if new_case is None: - raise ValueError( - "Failed to create new resampled case:{}".format(new_case_name) - ) + raise ValueError(f"Failed to create new resampled case:{new_case_name}") return new_case diff --git a/python/resdata/summary/rd_sum_keyword_vector.py b/python/resdata/summary/rd_sum_keyword_vector.py index ce4c324d0..e249ac383 100644 --- a/python/resdata/summary/rd_sum_keyword_vector.py +++ b/python/resdata/summary/rd_sum_keyword_vector.py @@ -24,7 +24,7 @@ class SummaryKeyWordVector(BaseCClass): def __init__(self, rd_sum, add_keywords=False): c_pointer = self._alloc(rd_sum, add_keywords) - super(SummaryKeyWordVector, self).__init__(c_pointer) + super().__init__(c_pointer) def __getitem__(self, index): if index < 0: diff --git a/python/resdata/summary/rd_sum_node.py b/python/resdata/summary/rd_sum_node.py index 024bb661f..c4a0417d0 100644 --- a/python/resdata/summary/rd_sum_node.py +++ b/python/resdata/summary/rd_sum_node.py @@ -1,4 +1,4 @@ -class SummaryNode(object): +class SummaryNode: def __init__(self, report_step, days, date, mpl_date, value): """ SummaryNode is a 'struct' with a summary value and time. diff --git a/python/resdata/summary/rd_sum_tstep.py b/python/resdata/summary/rd_sum_tstep.py index 68699c078..54ac197f4 100644 --- a/python/resdata/summary/rd_sum_tstep.py +++ b/python/resdata/summary/rd_sum_tstep.py @@ -28,7 +28,7 @@ class SummaryTStep(BaseCClass): def __init__(self, report_step, mini_step, sim_days, smspec): sim_seconds = sim_days * 24 * 60 * 60 c_pointer = self._alloc(report_step, mini_step, sim_seconds, smspec) - super(SummaryTStep, self).__init__(c_pointer) + super().__init__(c_pointer) def get_sim_days(self): """@rtype: double""" @@ -49,13 +49,13 @@ def get_sim_time(self): def __getitem__(self, key): """@rtype: double""" if not key in self: - raise KeyError("Key '%s' is not available." % key) + raise KeyError(f"Key '{key}' is not available.") return self._get_from_key(key) def __setitem__(self, key, value): if not key in self: - raise KeyError("Key '%s' is not available." % key) + raise KeyError(f"Key '{key}' is not available.") self._set_from_key(key, value) diff --git a/python/resdata/summary/rd_sum_vector.py b/python/resdata/summary/rd_sum_vector.py index 362ab1217..5560668e9 100644 --- a/python/resdata/summary/rd_sum_vector.py +++ b/python/resdata/summary/rd_sum_vector.py @@ -1,11 +1,9 @@ -from __future__ import print_function - import warnings from .rd_sum_node import SummaryNode -class SummaryVector(object): +class SummaryVector: def __init__(self, parent, key, report_only=False): """ A summary vector with a vector of values and time. @@ -41,7 +39,7 @@ def __init__(self, parent, key, report_only=False): self.__values = None def __str__(self): - return "" % self.key + return f"" def __repr__(self): return "SummaryVector(key = %s, size = %d, unit = %s)" % ( @@ -174,7 +172,7 @@ def __getitem__(self, index): index += step return sub_vector - raise KeyError("Invalid index:%s - must have integer or slice." % index) + raise KeyError(f"Invalid index:{index} - must have integer or slice.") @property def first(self): diff --git a/python/resdata/util/test/debug_msg.py b/python/resdata/util/test/debug_msg.py index 9faac85ec..2fff34e07 100644 --- a/python/resdata/util/test/debug_msg.py +++ b/python/resdata/util/test/debug_msg.py @@ -5,4 +5,4 @@ def debug_msg(msg): record = inspect.stack()[1] frame = record[0] info = inspect.getframeinfo(frame) - return "FILE: %s LINE: %s Msg: %s" % (info.filename, info.lineno, msg) + return f"FILE: {info.filename} LINE: {info.lineno} Msg: {msg}" diff --git a/python/resdata/util/test/extended_testcase.py b/python/resdata/util/test/extended_testcase.py index 66c4a5375..5311386ba 100644 --- a/python/resdata/util/test/extended_testcase.py +++ b/python/resdata/util/test/extended_testcase.py @@ -20,16 +20,16 @@ def log_test(test): def wrapper(*args): - sys.stderr.write("starting: %s \n" % test.__name__) + sys.stderr.write(f"starting: {test.__name__} \n") test(*args) - sys.stderr.write("complete: %s \n" % test.__name__) + sys.stderr.write(f"complete: {test.__name__} \n") return wrapper -class _AssertNotRaisesContext(object): +class _AssertNotRaisesContext: def __init__(self, test_class): - super(_AssertNotRaisesContext, self).__init__() + super().__init__() self._test_class = test_class def __enter__(self): @@ -42,8 +42,7 @@ def __exit__(self, exc_type, exc_value, tb): except AttributeError: exc_name = str(exc_type) self._test_class.fail( - "Exception: %s raised\n%s" - % (exc_name, traceback.print_exception(exc_type, exc_value, tb)) + f"Exception: {exc_name} raised\n{traceback.print_exception(exc_type, exc_value, tb)}" ) return True @@ -60,7 +59,7 @@ class ExtendedTestCase(TestCase): def __init__(self, *args, **kwargs): installAbortSignals() - super(ExtendedTestCase, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def assertFloatEqual(self, first, second, msg=None, tolerance=1e-6): try: @@ -68,16 +67,11 @@ def assertFloatEqual(self, first, second, msg=None, tolerance=1e-6): diff = abs(f_first - f_second) scale = max(1, abs(first) + abs(second)) if msg is None: - msg = "Floats not equal: |%f - %f| > %g" % ( - f_first, - f_second, - tolerance, - ) + msg = f"Floats not equal: |{f_first:f} - {f_second:f}| > {tolerance:g}" self.assertTrue(diff < tolerance * scale, msg=msg) except TypeError: self.fail( - "Cannot compare as floats: %s (%s) and %s (%s)" - % (first, type(first), second, type(second)) + f"Cannot compare as floats: {first} ({type(first)}) and {second} ({type(second)})" ) def assertAlmostEqualList(self, first, second, msg=None, tolerance=1e-6): @@ -94,12 +88,11 @@ def assertImportable(self, module_name): __import__(module_name) except ImportError: tb = traceback.format_exc() - self.fail("Module %s not found!\n\nTrace:\n%s" % (module_name, str(tb))) + self.fail(f"Module {module_name} not found!\n\nTrace:\n{str(tb)}") except Exception: tb = traceback.format_exc() self.fail( - "Import of module %s caused errors!\n\nTrace:\n%s" - % (module_name, str(tb)) + f"Import of module {module_name} caused errors!\n\nTrace:\n{str(tb)}" ) def assertFilesAreEqual(self, first, second): @@ -112,19 +105,19 @@ def assertFilesAreNotEqual(self, first, second): def assertFileExists(self, path): if not os.path.exists(path) or not os.path.isfile(path): - self.fail("The file: %s does not exist!" % path) + self.fail(f"The file: {path} does not exist!") def assertDirectoryExists(self, path): if not os.path.exists(path) or not os.path.isdir(path): - self.fail("The directory: %s does not exist!" % path) + self.fail(f"The directory: {path} does not exist!") def assertFileDoesNotExist(self, path): if os.path.exists(path) and os.path.isfile(path): - self.fail("The file: %s exists!" % path) + self.fail(f"The file: {path} exists!") def assertDirectoryDoesNotExist(self, path): if os.path.exists(path) and os.path.isdir(path): - self.fail("The directory: %s exists!" % path) + self.fail(f"The directory: {path} exists!") def __filesAreEqual(self, first, second): buffer1 = open(first, "rb").read() # noqa: SIM115 @@ -148,14 +141,13 @@ def assertEnumIsFullyDefined( self.assertTrue( identifier in enum_class.__dict__, - "Enum does not have identifier: %s" % identifier, + f"Enum does not have identifier: {identifier}", ) class_value = enum_class.__dict__[identifier] self.assertEqual( class_value, value, - "Enum value for identifier: %s does not match: %s != %s" - % (identifier, class_value, value), + f"Enum value for identifier: {identifier} does not match: {class_value} != {value}", ) @classmethod diff --git a/python/resdata/util/test/lint_test_case.py b/python/resdata/util/test/lint_test_case.py index f743fcde1..6092465fd 100644 --- a/python/resdata/util/test/lint_test_case.py +++ b/python/resdata/util/test/lint_test_case.py @@ -43,5 +43,5 @@ def assertLinted(self, paths, whitelist=()): # noqa files = self._get_lintable_files(paths, whitelist=whitelist) for f in files: self.assertEqual( - 0, lint.lint(f, self.LINT_ARGS), "Linting required for %s" % f + 0, lint.lint(f, self.LINT_ARGS), f"Linting required for {f}" ) diff --git a/python/resdata/util/test/path_context.py b/python/resdata/util/test/path_context.py index 5d622265b..2775ace2f 100644 --- a/python/resdata/util/test/path_context.py +++ b/python/resdata/util/test/path_context.py @@ -2,7 +2,7 @@ import shutil -class PathContext(object): +class PathContext: def __init__(self, path, store=False): self.path = path self.cwd = os.getcwd() @@ -24,7 +24,7 @@ def __init__(self, path, store=False): os.makedirs(path) elif not self.store: - raise OSError("Entry %s already exists" % path) + raise OSError(f"Entry {path} already exists") os.chdir(path) def __exit__(self, exc_type, exc_val, exc_tb): diff --git a/python/resdata/util/test/resdata_test_runner.py b/python/resdata/util/test/resdata_test_runner.py index 6a07eb616..bc47bd212 100644 --- a/python/resdata/util/test/resdata_test_runner.py +++ b/python/resdata/util/test/resdata_test_runner.py @@ -3,7 +3,7 @@ from unittest import TestLoader, TextTestRunner -class ResdataTestRunner(object): +class ResdataTestRunner: @staticmethod def runTestSuite(tests, test_verbosity=3): test_runner = TextTestRunner(verbosity=test_verbosity) @@ -47,7 +47,7 @@ def importClass(classpath): m = __import__(classpath[0:dot], globals(), locals(), [class_name]) return getattr(m, class_name) except ImportError: - print("Failed to import: %s" % classpath) + print(f"Failed to import: {classpath}") raise @staticmethod diff --git a/python/resdata/util/test/source_enumerator.py b/python/resdata/util/test/source_enumerator.py index aca52b04a..5953a769a 100644 --- a/python/resdata/util/test/source_enumerator.py +++ b/python/resdata/util/test/source_enumerator.py @@ -2,7 +2,7 @@ import re -class SourceEnumerator(object): +class SourceEnumerator: @classmethod def removeComments(cls, code_string): code_string = re.sub( @@ -15,7 +15,7 @@ def removeComments(cls, code_string): @classmethod def findEnum(cls, enum_name, full_source_file_path): - with open(full_source_file_path, "r") as f: + with open(full_source_file_path) as f: text = f.read() text = SourceEnumerator.removeComments(text) @@ -26,7 +26,7 @@ def findEnum(cls, enum_name, full_source_file_path): if enum[1] == enum_name: return enum[0] - raise ValueError("Enum with name: '%s' not found!" % enum_name) + raise ValueError(f"Enum with name: '{enum_name}' not found!") @classmethod def findEnumerators(cls, enum_name, source_file): diff --git a/python/resdata/util/test/test_area.py b/python/resdata/util/test/test_area.py index 29c75c0c2..9865dccfe 100644 --- a/python/resdata/util/test/test_area.py +++ b/python/resdata/util/test/test_area.py @@ -36,7 +36,7 @@ def __init__(self, test_name, store_area=False, c_ptr=None): if c_ptr is None: c_ptr = self._test_area_alloc(test_name, store_area) - super(TestArea, self).__init__(c_ptr) + super().__init__(c_ptr) def get_original_cwd(self): return self._get_original_cwd() @@ -59,52 +59,52 @@ def install_file(self, filename): if os.path.isfile(self.orgPath(filename)): self._install_file(filename) else: - raise IOError("No such file:%s" % filename) + raise OSError(f"No such file:{filename}") def copy_directory(self, directory): if os.path.isdir(self.orgPath(directory)): self._copy_directory(directory) else: - raise IOError("No such directory: %s" % directory) + raise OSError(f"No such directory: {directory}") def copy_parent_directory(self, path): if os.path.exists(self.orgPath(path)): self._copy_parent_directory(path) else: - raise IOError("No such file or directory: %s" % path) + raise OSError(f"No such file or directory: {path}") def copy_parent_content(self, path): if os.path.exists(self.orgPath(path)): self._copy_parent_content(path) else: - raise IOError("No such file or directory: %s" % path) + raise OSError(f"No such file or directory: {path}") def copy_directory_content(self, directory): if os.path.isdir(self.orgPath(directory)): self._copy_directory_content(directory) else: - raise IOError("No such directory: %s" % directory) + raise OSError(f"No such directory: {directory}") def copy_file(self, filename): if os.path.isfile(self.orgPath(filename)): self._copy_file(filename) else: - raise IOError("No such file:%s" % filename) + raise OSError(f"No such file:{filename}") def free(self): self._free() def getFullPath(self, path): if not os.path.exists(path): - raise IOError("Path not found:%s" % path) + raise OSError(f"Path not found:{path}") if os.path.isabs(path): - raise IOError("Path:%s is already absolute" % path) + raise OSError(f"Path:{path} is already absolute") return os.path.join(self.get_cwd(), path) -class TestAreaContext(object): +class TestAreaContext: __test__ = False def __init__(self, test_name, store_area=False): diff --git a/python/resdata/util/test/test_run.py b/python/resdata/util/test/test_run.py index 6b9955e7c..c5a299926 100644 --- a/python/resdata/util/test/test_run.py +++ b/python/resdata/util/test/test_run.py @@ -7,12 +7,12 @@ def path_exists(path): if os.path.exists(path): - return (True, "Path:%s exists" % path) + return (True, f"Path:{path} exists") else: - return (False, "ERROR: Path:%s does not exist" % path) + return (False, f"ERROR: Path:{path} does not exist") -class TestRun(object): +class TestRun: default_ert_cmd = "ert" default_ert_version = "stable" default_path_prefix = None @@ -37,7 +37,7 @@ def __init__(self, config_file, args=[], name=None): # noqa: B006 break self.name += "/%08d" % random.randint(0, 100000000) else: - raise IOError("No such config file: %s" % config_file) + raise OSError(f"No such config file: {config_file}") def parseArgs(self, args): parser = argparse.ArgumentParser() @@ -95,7 +95,7 @@ def add_check(self, check_func, arg): if callable(check_func): self.check_list.append((check_func, arg)) else: - raise Exception("The checker:%s is not callable" % check_func) + raise Exception(f"The checker:{check_func} is not callable") # ----------------------------------------------------------------- @@ -112,7 +112,7 @@ def __run(self, work_area): if status == 0: return (True, "ert has run successfully") else: - return (False, "ERROR:: ert exited with status code:%s" % status) + return (False, f"ERROR:: ert exited with status code:{status}") def run(self): if len(self.workflows): diff --git a/python/resdata/util/util/__init__.py b/python/resdata/util/util/__init__.py index 0b03cb91c..753cbd851 100644 --- a/python/resdata/util/util/__init__.py +++ b/python/resdata/util/util/__init__.py @@ -21,8 +21,6 @@ """ -from __future__ import absolute_import, division, print_function, unicode_literals - import resdata from cwrap import Prototype @@ -98,9 +96,7 @@ def shift(*args): return args if (method_type != classmethod) else args[1:] def warned_method(*args, **kwargs): - __rd_camel_case_warning( - "Warning, %s is deprecated, use %s" % (camel, str(method_)) - ) + __rd_camel_case_warning(f"Warning, {camel} is deprecated, use {str(method_)}") return method_(*shift(*args), **kwargs) if method_type == staticmethod: diff --git a/python/resdata/util/util/bool_vector.py b/python/resdata/util/util/bool_vector.py index 161ad4a4b..de8fdd270 100644 --- a/python/resdata/util/util/bool_vector.py +++ b/python/resdata/util/util/bool_vector.py @@ -99,7 +99,7 @@ class BoolVector(VectorTemplate): ) def __init__(self, default_value=False, initial_size=0): - super(BoolVector, self).__init__(default_value, initial_size) + super().__init__(default_value, initial_size) def count(self, value=True): """@rtype: int""" diff --git a/python/resdata/util/util/ctime.py b/python/resdata/util/util/ctime.py index 655cd70eb..10116f87d 100644 --- a/python/resdata/util/util/ctime.py +++ b/python/resdata/util/util/ctime.py @@ -33,10 +33,10 @@ def __init__(self, value): value = CTime._timegm(0, 0, 0, value.day, value.month, value.year) else: raise NotImplementedError( - "Can not convert class %s to CTime" % value.__class__ + f"Can not convert class {value.__class__} to CTime" ) - super(CTime, self).__init__(value) + super().__init__(value) def ctime(self): """@rtype: int""" @@ -68,7 +68,7 @@ def __gt__(self, other): elif isinstance(other, (int, datetime.datetime, datetime.date)): return self > CTime(other) else: - raise TypeError("CTime does not support type: %s" % other.__class__) + raise TypeError(f"CTime does not support type: {other.__class__}") def __lt__(self, other): if isinstance(other, CTime): @@ -76,7 +76,7 @@ def __lt__(self, other): elif isinstance(other, (int, datetime.datetime, datetime.date)): return self < CTime(other) else: - raise TypeError("CTime does not support type: %s" % other.__class__) + raise TypeError(f"CTime does not support type: {other.__class__}") def __ne__(self, other): return not self == other @@ -89,7 +89,7 @@ def __eq__(self, other): elif isinstance(other, type(None)): return False else: - raise TypeError("CTime does not support type: %s" % other.__class__) + raise TypeError(f"CTime does not support type: {other.__class__}") def __imul__(self, other): value = int(self.value() * other) diff --git a/python/resdata/util/util/cwd_context.py b/python/resdata/util/util/cwd_context.py index 358f488c9..bc8925bd1 100644 --- a/python/resdata/util/util/cwd_context.py +++ b/python/resdata/util/util/cwd_context.py @@ -1,13 +1,13 @@ import os -class CWDContext(object): +class CWDContext: def __init__(self, path): self.cwd = os.getcwd() if os.path.isdir(path): os.chdir(path) else: - raise IOError("Path:%s does not exist" % path) + raise OSError(f"Path:{path} does not exist") def __exit__(self, exc_type, exc_val, exc_tb): os.chdir(self.cwd) diff --git a/python/resdata/util/util/double_vector.py b/python/resdata/util/util/double_vector.py index f1499fb48..66266c64e 100644 --- a/python/resdata/util/util/double_vector.py +++ b/python/resdata/util/util/double_vector.py @@ -109,4 +109,4 @@ class DoubleVector(VectorTemplate): ) def __init__(self, default_value=0, initial_size=0): - super(DoubleVector, self).__init__(default_value, initial_size) + super().__init__(default_value, initial_size) diff --git a/python/resdata/util/util/hash.py b/python/resdata/util/util/hash.py index 18e8dc13e..153387f9c 100644 --- a/python/resdata/util/util/hash.py +++ b/python/resdata/util/util/hash.py @@ -21,7 +21,7 @@ class Hash(BaseCClass): def __init__(self): c_ptr = self._alloc() - super(Hash, self).__init__(c_ptr) + super().__init__(c_ptr) def __len__(self): return self._size() @@ -30,21 +30,20 @@ def __getitem__(self, key): if self._has_key(key): return self._get(key) else: - raise KeyError("Hash does not have key: %s" % key) + raise KeyError(f"Hash does not have key: {key}") def __setitem__(self, key, value): if isinstance(value, c_void_p): self._insert_ref(key, value) else: - raise ValueError("Hash does not support type: %s" % value.__class__) + raise ValueError(f"Hash does not support type: {value.__class__}") def __contains__(self, key): """@rtype: bool""" return self._has_key(key) def __iter__(self): - for key in self.keys(): - yield key + yield from self.keys() def keys(self): """@rtype: StringList""" @@ -54,7 +53,7 @@ def free(self): self._free() def __str__(self): - return str(["%s: %s" % (key, self[key]) for key in self.keys()]) + return str([f"{key}: {self[key]}" for key in self.keys()]) class StringHash(Hash): @@ -63,19 +62,19 @@ class StringHash(Hash): _insert_string = ResdataPrototype("void hash_insert_string(rd_hash, char*, char*)") def __init__(self): - super(StringHash, self).__init__() + super().__init__() def __setitem__(self, key, value): if isinstance(value, str): self._insert_string(key, value) else: - raise ValueError("StringHash does not support type: %s" % value.__class__) + raise ValueError(f"StringHash does not support type: {value.__class__}") def __getitem__(self, key): if key in self: return self._get_string(key) else: - raise KeyError("Hash does not have key: %s" % key) + raise KeyError(f"Hash does not have key: {key}") class IntegerHash(Hash): @@ -84,19 +83,19 @@ class IntegerHash(Hash): _insert_int = ResdataPrototype("void hash_insert_int(rd_hash, char*, int)") def __init__(self): - super(IntegerHash, self).__init__() + super().__init__() def __setitem__(self, key, value): if isinstance(value, int): self._insert_int(key, value) else: - raise ValueError("IntegerHash does not support type: %s" % value.__class__) + raise ValueError(f"IntegerHash does not support type: {value.__class__}") def __getitem__(self, key): if key in self: return self._get_int(key) else: - raise KeyError("Hash does not have key: %s" % key) + raise KeyError(f"Hash does not have key: {key}") class DoubleHash(Hash): @@ -105,7 +104,7 @@ class DoubleHash(Hash): _insert_double = ResdataPrototype("void hash_insert_double(rd_hash, char*, double)") def __init__(self): - super(DoubleHash, self).__init__() + super().__init__() def __setitem__(self, key, value): if isinstance(value, int): @@ -114,10 +113,10 @@ def __setitem__(self, key, value): if isinstance(value, float): self._insert_double(key, value) else: - raise ValueError("DoubleHash does not support type: %s" % value.__class__) + raise ValueError(f"DoubleHash does not support type: {value.__class__}") def __getitem__(self, key): if key in self: return self._get_double(key) else: - raise KeyError("Hash does not have key: %s" % key) + raise KeyError(f"Hash does not have key: {key}") diff --git a/python/resdata/util/util/int_vector.py b/python/resdata/util/util/int_vector.py index 09208614c..fd0931d37 100644 --- a/python/resdata/util/util/int_vector.py +++ b/python/resdata/util/util/int_vector.py @@ -95,7 +95,7 @@ class IntVector(VectorTemplate): ) def __init__(self, default_value=0, initial_size=0): - super(IntVector, self).__init__(default_value, initial_size) + super().__init__(default_value, initial_size) @classmethod def active_list(cls, range_string): diff --git a/python/resdata/util/util/lookup_table.py b/python/resdata/util/util/lookup_table.py index 45fcb4657..178ac5197 100644 --- a/python/resdata/util/util/lookup_table.py +++ b/python/resdata/util/util/lookup_table.py @@ -30,7 +30,7 @@ class LookupTable(BaseCClass): ) def __init__(self, lower_limit=None, upper_limit=None): - super(LookupTable, self).__init__(self._alloc()) + super().__init__(self._alloc()) if not lower_limit is None: self.setLowerLimit(lower_limit) @@ -99,13 +99,11 @@ def interp(self, x): if x < self.getMinArg(): if not self.hasLowerLimit(): raise ValueError( - "Interpolate argument:%g is outside valid interval: [%g,%g]" - % (x, self.getMinArg(), self.getMaxArg()) + f"Interpolate argument:{x:g} is outside valid interval: [{self.getMinArg():g},{self.getMaxArg():g}]" ) elif x > self.getMaxArg() and not self.hasUpperLimit(): raise ValueError( - "Interpolate argument:%g is outside valid interval: [%g,%g]" - % (x, self.getMinArg(), self.getMaxArg()) + f"Interpolate argument:{x:g} is outside valid interval: [{self.getMinArg():g},{self.getMaxArg():g}]" ) return self._interp(x) diff --git a/python/resdata/util/util/rng.py b/python/resdata/util/util/rng.py index 17274159a..635c54597 100644 --- a/python/resdata/util/util/rng.py +++ b/python/resdata/util/util/rng.py @@ -28,7 +28,7 @@ def __init__( assert isinstance(init_mode, RngInitModeEnum) c_ptr = self._rng_alloc(alg_type, init_mode) - super(RandomNumberGenerator, self).__init__(c_ptr) + super().__init__(c_ptr) def stateSize(self): return self._state_size() @@ -65,7 +65,7 @@ def loadState(self, seed_file): if os.path.isfile(seed_file): self._load_state(seed_file) else: - raise IOError("No such file: %s" % seed_file) + raise OSError(f"No such file: {seed_file}") def saveState(self, seed_file): """ diff --git a/python/resdata/util/util/stringlist.py b/python/resdata/util/util/stringlist.py index 8cd6b2f55..38cf8810e 100644 --- a/python/resdata/util/util/stringlist.py +++ b/python/resdata/util/util/stringlist.py @@ -61,16 +61,14 @@ def __init__(self, initial=None): """ c_ptr = self._alloc() - super(StringList, self).__init__(c_ptr) + super().__init__(c_ptr) if not initial: return if isinstance(initial, str): raise TypeError( - ( - 'Cannot initialize a StringList from "{initial}".\n' - 'Did you mean "[{initial}]"?' - ).format(initial=initial) + f'Cannot initialize a StringList from "{initial}".\n' + f'Did you mean "[{initial}]"?' ) for s in initial: if isinstance(s, bytes): @@ -78,7 +76,7 @@ def __init__(self, initial=None): if isinstance(s, str): self.append(s) else: - raise TypeError('Item is not a string: "%s".' % s) + raise TypeError(f'Item is not a string: "{s}".') def __eq__(self, other): if len(self) == len(other): @@ -110,7 +108,7 @@ def __setitem__(self, index, value): if isinstance(value, str): self._iset(index, value) else: - raise TypeError("Item: %s not string type" % value) + raise TypeError(f"Item: {value} not string type") def __getitem__(self, index): """ @@ -192,9 +190,9 @@ def __str__(self): length = len(self) for i in range(length): if i == length - 1: - buffer += "'%s'" % self[i] + buffer += f"'{self[i]}'" else: - buffer += "'%s'," % self[i] + buffer += f"'{self[i]}'," buffer += "]" return buffer @@ -272,7 +270,7 @@ def index(self, value): if isinstance(value, str): return self._find_first(value) raise KeyError( - 'Cannot index by "%s", lst.index() needs a string.' % str(type(value)) + f'Cannot index by "{str(type(value))}", lst.index() needs a string.' ) def free(self): diff --git a/python/resdata/util/util/thread_pool.py b/python/resdata/util/util/thread_pool.py index bbfd3f6bc..7c45ad548 100644 --- a/python/resdata/util/util/thread_pool.py +++ b/python/resdata/util/util/thread_pool.py @@ -6,7 +6,7 @@ class Task(Thread): def __init__(self, func, *args, **kwargs): - super(Task, self).__init__() + super().__init__() self.__func = func self.__args = args self.__kwargs = kwargs @@ -34,7 +34,7 @@ def run(self): if self.__verbose: running_time = time.time() - self.__start_time - print("Running time of task: %f" % running_time) + print(f"Running time of task: {running_time:f}") def isDone(self): return self.__done @@ -53,9 +53,9 @@ def join(self, timeout=None): time.sleep(0.01) -class ThreadPool(object): +class ThreadPool: def __init__(self, size=None, verbose=False): - super(ThreadPool, self).__init__() + super().__init__() if size is None: size = multiprocessing.cpu_count() diff --git a/python/resdata/util/util/time_vector.py b/python/resdata/util/util/time_vector.py index 0839a7596..effa480e8 100644 --- a/python/resdata/util/util/time_vector.py +++ b/python/resdata/util/util/time_vector.py @@ -116,7 +116,7 @@ class TimeVector(VectorTemplate): def __init__(self, default_value=None, initial_size=0): if default_value is None: - super(TimeVector, self).__init__(CTime(0), initial_size) + super().__init__(CTime(0), initial_size) else: try: default = CTime(default_value) @@ -125,7 +125,7 @@ def __init__(self, default_value=None, initial_size=0): "default value invalid - must be type ctime() or date/datetime" ) from err - super(TimeVector, self).__init__(default, initial_size) + super().__init__(default, initial_size) @classmethod def parseTimeUnit(cls, deltaString): @@ -150,7 +150,7 @@ def __str__(self): """ string_list = [] for d in self: - string_list.append("%s" % d) + string_list.append(f"{d}") return str(string_list) diff --git a/python/resdata/util/util/vector_template.py b/python/resdata/util/util/vector_template.py index d42db20f3..07e1e2a29 100644 --- a/python/resdata/util/util/vector_template.py +++ b/python/resdata/util/util/vector_template.py @@ -25,8 +25,6 @@ float and size_t not currently implemented in the Python version. """ -from __future__ import absolute_import, division, print_function, unicode_literals - import sys from cwrap import CFILE, BaseCClass @@ -126,7 +124,7 @@ def __init__(self, default_value=0, initial_size=0): Creates a new TVector instance. """ c_pointer = self._alloc(initial_size, default_value) - super(VectorTemplate, self).__init__(c_pointer) + super().__init__(c_pointer) self.element_size = self._element_size() def __contains__(self, value): @@ -268,7 +266,7 @@ def __IADD(self, delta, add): delta *= -1 self._shift(delta) else: - raise TypeError("delta has wrong type:%s " % type(delta)) + raise TypeError(f"delta has wrong type:{type(delta)} ") return self @@ -337,7 +335,7 @@ def __imul__(self, factor): elif isinstance(factor, (int, float)): self._scale(factor) else: - raise TypeError("factor has wrong type:%s " % type(factor)) + raise TypeError(f"factor has wrong type:{type(factor)} ") return self @@ -355,7 +353,7 @@ def __div__(self, divisor): copy._div(divisor) return copy else: - raise TypeError("Divisor has wrong type:%s" % type(divisor)) + raise TypeError(f"Divisor has wrong type:{type(divisor)}") def __truediv__(self, divisor): return self.__div__(divisor) diff --git a/python/resdata/util/util/version.py b/python/resdata/util/util/version.py index 5482ee93d..523370c69 100644 --- a/python/resdata/util/util/version.py +++ b/python/resdata/util/util/version.py @@ -14,7 +14,7 @@ def cmp_wrapper(self, other): return cmp_wrapper -class Version(object): +class Version: def __init__(self, major, minor, micro, git_commit=None, build_time=None): self.major = major self.minor = minor @@ -113,6 +113,4 @@ def __init__(self): micro = self._micro_version() git_commit = self._git_commit() build_time = self._build_time() - super(ResdataVersion, self).__init__( - major, minor, micro, git_commit, build_time - ) + super().__init__(major, minor, micro, git_commit, build_time) diff --git a/python/resdata/well/well_connection.py b/python/resdata/well/well_connection.py index 005f07ea5..1f7953325 100644 --- a/python/resdata/well/well_connection.py +++ b/python/resdata/well/well_connection.py @@ -96,20 +96,7 @@ def __repr__(self): msw = " (multi segment)" if self.isMultiSegmentWell() else "" dir = WellConnectionDirection(self.direction()) addr = self._address() - return ( - "WellConnection(%s %s%s%s, rates = (O:%s,G:%s,W:%s), direction = %s) at 0x%x" - % ( - ijk, - frac, - open_, - msw, - self.oilRate(), - self.gasRate(), - self.waterRate(), - dir, - addr, - ) - ) + return f"WellConnection({ijk} {frac}{open_}{msw}, rates = (O:{self.oilRate()},G:{self.gasRate()},W:{self.waterRate()}), direction = {dir}) at 0x{addr:x}" def gasRate(self): return self._gas_rate() diff --git a/python/resdata/well/well_info.py b/python/resdata/well/well_info.py index d86e9e4f3..fa3b14999 100644 --- a/python/resdata/well/well_info.py +++ b/python/resdata/well/well_info.py @@ -32,9 +32,9 @@ def __init__(self, grid, rst_file=None, load_segment_information=True): @type rst_file: str or ResdataFile or list of str or list of ResdataFile """ c_ptr = self._alloc(grid) - super(WellInfo, self).__init__(c_ptr) + super().__init__(c_ptr) if not c_ptr: - raise ValueError("Unable to construct WellInfo from grid %s." % str(grid)) + raise ValueError(f"Unable to construct WellInfo from grid {str(grid)}.") if rst_file is not None: if isinstance(rst_file, list): @@ -58,7 +58,7 @@ def __getitem__(self, item): if isinstance(item, str): if not item in self: - raise KeyError("The well '%s' is not in this set." % item) + raise KeyError(f"The well '{item}' is not in this set.") well_name = item elif isinstance(item, int): @@ -91,7 +91,7 @@ def __contains__(self, item): def _assert_file_exists(self, rst_file): if not isfile(rst_file): - raise IOError("No such file %s" % rst_file) + raise OSError(f"No such file {rst_file}") def addWellFile(self, rst_file, load_segment_information): """@type rstfile: str or ResdataFile""" diff --git a/python/resdata/well/well_segment.py b/python/resdata/well/well_segment.py index 7c4b7e684..ac406f0d3 100644 --- a/python/resdata/well/well_segment.py +++ b/python/resdata/well/well_segment.py @@ -28,7 +28,7 @@ def free(self): pass def __repr__(self): - return "WellSegment(%s) at 0x%x" % (str(self), self._address()) + return f"WellSegment({str(self)}) at 0x{self._address():x}" def __str__(self): return "{Segment ID:%d BranchID:%d Length:%g}" % ( diff --git a/python/resdata/well/well_state.py b/python/resdata/well/well_state.py index cb10dfffa..5cd9d5489 100644 --- a/python/resdata/well/well_state.py +++ b/python/resdata/well/well_state.py @@ -163,18 +163,12 @@ def hasSegmentData(self): def __repr__(self): name = self.name() - name = "%s" % name if name else "[no name]" + name = f"{name}" if name else "[no name]" msw = " (multi segment)" if self.isMultiSegmentWell() else "" wn = str(self.wellNumber()) type_ = self.wellType() open_ = "open" if self.isOpen() else "shut" - cnt = '%s%s, number = %s, type = "%s", state = %s' % ( - name, - msw, - wn, - type_, - open_, - ) + cnt = f'{name}{msw}, number = {wn}, type = "{type_}", state = {open_}' return self._create_repr(cnt) def gasRate(self): diff --git a/python/tests/rd_tests/create_restart.py b/python/tests/rd_tests/create_restart.py index a01ddcdd5..f43121936 100644 --- a/python/tests/rd_tests/create_restart.py +++ b/python/tests/rd_tests/create_restart.py @@ -3,7 +3,7 @@ def create_restart(grid, case, p1, p2=None, rporv1=None, rporv2=None): - with openFortIO("%s.UNRST" % case, mode=FortIO.WRITE_MODE) as f: + with openFortIO(f"{case}.UNRST", mode=FortIO.WRITE_MODE) as f: seq_hdr = ResdataKW("SEQNUM", 1, ResDataType.RD_INT) seq_hdr[0] = 10 p = ResdataKW("PRESSURE", grid.getNumActive(), ResDataType.RD_FLOAT) diff --git a/python/tests/rd_tests/test_fk_user_data.py b/python/tests/rd_tests/test_fk_user_data.py index f468cc71d..90075845f 100644 --- a/python/tests/rd_tests/test_fk_user_data.py +++ b/python/tests/rd_tests/test_fk_user_data.py @@ -16,7 +16,7 @@ def test_cell_containment(self): grid = Grid(grid_file) # Load well data - with open(well_file, "r") as f: + with open(well_file) as f: lines = [line.split() for line in f.readlines()] points = [map(float, line[:3:]) for line in lines] diff --git a/python/tests/rd_tests/test_geertsma.py b/python/tests/rd_tests/test_geertsma.py index de8864998..6a8091625 100644 --- a/python/tests/rd_tests/test_geertsma.py +++ b/python/tests/rd_tests/test_geertsma.py @@ -19,7 +19,7 @@ def create_init(grid, case): for g in range(grid.getGlobalSize()): porv[g] *= grid.cell_volume(global_index=g) - with openFortIO("%s.INIT" % case, mode=FortIO.WRITE_MODE) as f: + with openFortIO(f"{case}.INIT", mode=FortIO.WRITE_MODE) as f: poro.fwrite(f) porv.fwrite(f) diff --git a/python/tests/rd_tests/test_grid.py b/python/tests/rd_tests/test_grid.py index 09529f5bb..4401169c6 100644 --- a/python/tests/rd_tests/test_grid.py +++ b/python/tests/rd_tests/test_grid.py @@ -316,15 +316,15 @@ def test_repr_and_name(self): pfx = "Grid(" rep = repr(grid) self.assertEqual(pfx, rep[: len(pfx)]) - self.assertEqual(type(rep), type("")) - self.assertEqual(type(grid.getName()), type("")) + self.assertEqual(type(rep), str) + self.assertEqual(type(grid.getName()), str) with TestAreaContext("python/rd_grid/repr"): grid.save_EGRID("CASE.EGRID") g2 = Grid("CASE.EGRID") r2 = repr(g2) self.assertEqual(pfx, r2[: len(pfx)]) - self.assertEqual(type(r2), type("")) - self.assertEqual(type(g2.getName()), type("")) + self.assertEqual(type(r2), str) + self.assertEqual(type(g2.getName()), str) def test_node_pos(self): grid = GridGen.createRectangular((10, 20, 30), (1, 1, 1)) diff --git a/python/tests/rd_tests/test_grid_generator.py b/python/tests/rd_tests/test_grid_generator.py index 0b2adcc32..64a1f8262 100644 --- a/python/tests/rd_tests/test_grid_generator.py +++ b/python/tests/rd_tests/test_grid_generator.py @@ -253,6 +253,6 @@ def test_subgrid_translation(self): gc, sc, msg="Failed to translate corners correctly." - + "Expected %s, was %s." % (gc, sc), + + f"Expected {gc}, was {sc}.", tolerance=10e-10, ) diff --git a/python/tests/rd_tests/test_npv.py b/python/tests/rd_tests/test_npv.py index 353f988c6..fcec50641 100644 --- a/python/tests/rd_tests/test_npv.py +++ b/python/tests/rd_tests/test_npv.py @@ -13,7 +13,7 @@ base = "ECLIPSE" path = "Equinor/ECLIPSE/Gurbat" -case = "%s/%s" % (path, base) +case = f"{path}/{base}" def callable(x): diff --git a/python/tests/rd_tests/test_rd_kw.py b/python/tests/rd_tests/test_rd_kw.py index 58f321a15..1338d3bfc 100644 --- a/python/tests/rd_tests/test_rd_kw.py +++ b/python/tests/rd_tests/test_rd_kw.py @@ -182,7 +182,7 @@ def test_fprintf_data(self): kw.fprintf_data(fileH) fileH.close() - with open("test", "r") as fileH: + with open("test") as fileH: data = [] for line in fileH.readlines(): tmp = line.split() diff --git a/python/tests/rd_tests/test_region_equinor.py b/python/tests/rd_tests/test_region_equinor.py index 2f58afd38..b4d03f371 100755 --- a/python/tests/rd_tests/test_region_equinor.py +++ b/python/tests/rd_tests/test_region_equinor.py @@ -10,8 +10,8 @@ class RegionTest(ResdataTest): def setUp(self): case = self.createTestPath("Equinor/ECLIPSE/Gurbat/ECLIPSE") self.grid = Grid(case) - self.rst_file = ResdataFile("%s.UNRST" % case) - self.init_file = ResdataFile("%s.INIT" % case) + self.rst_file = ResdataFile(f"{case}.UNRST") + self.init_file = ResdataFile(f"{case}.INIT") def test_kw_imul(self): P = self.rst_file["PRESSURE"][5] @@ -146,10 +146,10 @@ def test_polygon(self): def test_heidrun(self): root = self.createTestPath("Equinor/ECLIPSE/Heidrun") - grid = Grid("%s/FF12_2013B2_AMAP_AOP-J15_NO62_MOVEX.EGRID" % root) + grid = Grid(f"{root}/FF12_2013B2_AMAP_AOP-J15_NO62_MOVEX.EGRID") polygon = [] - with open("%s/polygon.ply" % root) as fileH: + with open(f"{root}/polygon.ply") as fileH: for line in fileH.readlines(): tmp = line.split() polygon.append((float(tmp[0]), float(tmp[1]))) diff --git a/python/tests/rd_tests/test_rft_equinor.py b/python/tests/rd_tests/test_rft_equinor.py index ef76a3738..af3f7e865 100644 --- a/python/tests/rd_tests/test_rft_equinor.py +++ b/python/tests/rd_tests/test_rft_equinor.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -from __future__ import print_function import datetime from resdata.rft import ResdataRFTFile, ResdataRFTCell, ResdataPLTCell, WellTrajectory from tests import ResdataTest, equinor_test diff --git a/python/tests/rd_tests/test_sum_equinor.py b/python/tests/rd_tests/test_sum_equinor.py index fb0f900ff..9c6422482 100755 --- a/python/tests/rd_tests/test_sum_equinor.py +++ b/python/tests/rd_tests/test_sum_equinor.py @@ -13,7 +13,7 @@ base = "ECLIPSE" path = "Equinor/ECLIPSE/Gurbat" -case = "%s/%s" % (path, base) +case = f"{path}/{base}" def sum_get(*args): diff --git a/python/tests/util_tests/test_work_area.py b/python/tests/util_tests/test_work_area.py index 625853520..151435aa5 100644 --- a/python/tests/util_tests/test_work_area.py +++ b/python/tests/util_tests/test_work_area.py @@ -55,9 +55,7 @@ def test_multiple_areas(self): self.assertEqual( loop_dir, original_dir, - "Wrong folder before creating TestAreaContext. Loop: {} -- CWD: {} ".format( - i, loop_dir - ), + f"Wrong folder before creating TestAreaContext. Loop: {i} -- CWD: {loop_dir} ", ) with TestAreaContext("test_multiple_areas") as t: @@ -66,9 +64,7 @@ def test_multiple_areas(self): self.assertNotIn( t_dir, context_dirs, - "Multiple TestAreaContext objects in the same folder. Loop {} -- CWD: {}".format( - i, loop_dir - ), + f"Multiple TestAreaContext objects in the same folder. Loop {i} -- CWD: {loop_dir}", ) context_dirs.append(t_dir) @@ -77,18 +73,14 @@ def test_multiple_areas(self): self.assertNotEqual( t_dir, original_dir, - "TestAreaContext in the current working directory. Loop: {} -- CWD: {}".format( - i, loop_dir - ), + f"TestAreaContext in the current working directory. Loop: {i} -- CWD: {loop_dir}", ) loop_dir = os.getcwd() self.assertEqual( loop_dir, original_dir, - "Wrong folder after creating TestAreaContext. Loop: {} -- CWD: {} ".format( - i, loop_dir - ), + f"Wrong folder after creating TestAreaContext. Loop: {i} -- CWD: {loop_dir} ", ) From 722c894ad06423a224a8583a3e0ddbed85f7b068 Mon Sep 17 00:00:00 2001 From: larsevj Date: Thu, 29 Aug 2024 15:33:40 +0200 Subject: [PATCH 07/11] Remove unused variabled from source --- pyproject.toml | 6 +++--- python/resdata/geometry/geometry_tools.py | 9 ++------- python/resdata/grid/faults/fault_block_layer.py | 6 ++---- python/resdata/grid/faults/fault_line.py | 1 - python/resdata/grid/rd_grid_generator.py | 4 ---- python/resdata/resfile/rd_file.py | 1 - 6 files changed, 7 insertions(+), 20 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 9640b0665..7f38ab0b5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools", "setuptools_scm", "wheel", "scikit-build", "cmake", "conan<2", "ninja"] +requires = ["setuptools", "setuptools_scm", "scikit-build", "cmake", "conan<2", "ninja"] [tool.ruff] src = ["python"] @@ -35,11 +35,11 @@ ignore = ["PLW2901", # redefined-loop-name "PD901", # pandas-df-variable-name "C409", # unnecessary-literal-within-tuple-call "PLC0414", # useless-import-alias - "F401", # unused-import - "F841", # unused-variable ] [tool.ruff.lint.extend-per-file-ignores] "python/tests/util_tests/test_ctime.py" = ["PLR0124", "B015"] +"python/*tests/*" = ["F841"] +"python/*/__init__.py" = ["F401"] [tool.ruff.lint.pylint] max-args = 15 diff --git a/python/resdata/geometry/geometry_tools.py b/python/resdata/geometry/geometry_tools.py index eeb34fd2f..9500b5e77 100644 --- a/python/resdata/geometry/geometry_tools.py +++ b/python/resdata/geometry/geometry_tools.py @@ -188,7 +188,6 @@ def slicePolygon(bounding_polygon, poly_line): p1 = poly_line[0] ray1 = GeometryTools.lineToRay(poly_line[1], poly_line[0]) - tmp = GeometryTools.rayPolygonIntersections(p1, ray1, bounding_polygon) intersection1 = GeometryTools.rayPolygonIntersections( p1, ray1, bounding_polygon )[0] # assume convex @@ -385,17 +384,13 @@ def connectPolylines(polyline, target_polyline): p0 = polyline[-1] p1 = polyline[-2] ray = GeometryTools.lineToRay(p1, p0) - for _, p in GeometryTools.rayPolygonIntersections( - p0, ray, target_polyline - ): + for _, p in GeometryTools.rayPolygonIntersections(p0, ray, target_polyline): d_list.append((GeometryTools.distance(p0, p), [p0, p])) p0 = polyline[0] p1 = polyline[1] ray = GeometryTools.lineToRay(p1, p0) - for _, p in GeometryTools.rayPolygonIntersections( - p0, ray, target_polyline - ): + for _, p in GeometryTools.rayPolygonIntersections(p0, ray, target_polyline): d_list.append((GeometryTools.distance(p0, p), [p0, p])) if len(d_list) == 0: diff --git a/python/resdata/grid/faults/fault_block_layer.py b/python/resdata/grid/faults/fault_block_layer.py index 88ca0d014..173b742e8 100644 --- a/python/resdata/grid/faults/fault_block_layer.py +++ b/python/resdata/grid/faults/fault_block_layer.py @@ -202,10 +202,8 @@ def join_faults(self, fault1, fault2): try: layer.addIJBarrier(Fault.joinFaults(fault1, fault2, self.getK())) except ValueError as err: - err = "Failed to join faults %s and %s" - names = (fault1.getName(), fault2.getName()) - print(err % names) - raise ValueError(err % names) from err + msg = f"Failed to join faults {fault1.getName()} and {fault2.getName()}" + raise ValueError(msg) from err def add_polyline_barrier(self, polyline): layer = self.getGeoLayer() diff --git a/python/resdata/grid/faults/fault_line.py b/python/resdata/grid/faults/fault_line.py index 5f38e8ec2..88b6bd28a 100644 --- a/python/resdata/grid/faults/fault_line.py +++ b/python/resdata/grid/faults/fault_line.py @@ -72,7 +72,6 @@ def k(self): def __init_ij_polyline(self): pl = [] nx = self.__grid.getNX() - ny = self.__grid.getNY() for segment in self: corner = segment.getC1() i = corner % (nx + 1) diff --git a/python/resdata/grid/rd_grid_generator.py b/python/resdata/grid/rd_grid_generator.py index 88e60ad06..6547fcc7c 100644 --- a/python/resdata/grid/rd_grid_generator.py +++ b/python/resdata/grid/rd_grid_generator.py @@ -693,10 +693,6 @@ def extract_subgrid_data( ijk_bounds = cls.assert_ijk_bounds(dims, ijk_bounds) cls.assert_decomposition_change(ijk_bounds, decomposition_change) - nx, ny, nz = dims - (lx, ux), (ly, uy), (lz, uz) = ijk_bounds - new_nx, new_ny, new_nz = ux - lx + 1, uy - ly + 1, uz - lz + 1 - new_coord = cls.extract_coord(dims, coord, ijk_bounds) new_zcorn = cls.extract_zcorn(dims, zcorn, ijk_bounds) new_actnum = cls.extract_actnum(dims, actnum, ijk_bounds) diff --git a/python/resdata/resfile/rd_file.py b/python/resdata/resfile/rd_file.py index 58805fa32..1090509f8 100644 --- a/python/resdata/resfile/rd_file.py +++ b/python/resdata/resfile/rd_file.py @@ -417,7 +417,6 @@ def report_steps(self): keywords and the method will simply return an empty list. """ steps = [] - seqnum_list = self["SEQNUM"] for kw in self["SEQNUM"]: steps.append(kw[0]) return steps From 9d3db0b1ad72d2527039d11de0f98478bd6b933b Mon Sep 17 00:00:00 2001 From: larsevj Date: Thu, 29 Aug 2024 15:34:25 +0200 Subject: [PATCH 08/11] Remove unused imports --- python/resdata/geometry/cpolyline_collection.py | 1 - python/resdata/geometry/geo_region.py | 1 - python/resdata/geometry/polyline.py | 1 - python/resdata/geometry/surface.py | 1 - python/resdata/gravimetry/rd_subsidence.py | 1 - python/resdata/grid/faults/fault.py | 2 +- python/resdata/grid/faults/fault_block_layer.py | 1 - python/resdata/grid/faults/layer.py | 2 -- python/resdata/grid/rd_grid.py | 3 +-- python/resdata/grid/rd_region.py | 2 -- python/resdata/resfile/fortio.py | 1 - python/resdata/resfile/rd_kw.py | 3 +-- python/resdata/rft/well_trajectory.py | 1 - python/resdata/summary/rd_sum.py | 5 +---- python/resdata/summary/rd_sum_tstep.py | 1 - python/resdata/util/test/extended_testcase.py | 1 - python/resdata/util/test/source_enumerator.py | 1 - python/resdata/util/util/hash.py | 1 - python/resdata/well/well_info.py | 2 -- python/resdata/well/well_state.py | 2 -- python/resdata/well/well_time_line.py | 1 - python/tests/bin_tests/test_summary_resample.py | 1 - python/tests/geometry_tests/test_cpolyline.py | 2 -- python/tests/geometry_tests/test_cpolyline_collection.py | 3 --- python/tests/geometry_tests/test_geo_pointset.py | 1 - python/tests/geometry_tests/test_geo_region.py | 1 - python/tests/geometry_tests/test_geometry_tools.py | 2 -- python/tests/rd_tests/test_cell.py | 3 +-- python/tests/rd_tests/test_deprecation.py | 7 +------ python/tests/rd_tests/test_equinor_faults.py | 4 +--- python/tests/rd_tests/test_fault_blocks.py | 1 - python/tests/rd_tests/test_fault_blocks_equinor.py | 3 +-- python/tests/rd_tests/test_faults.py | 3 --- python/tests/rd_tests/test_fk_user_data.py | 1 - python/tests/rd_tests/test_grav.py | 1 - python/tests/rd_tests/test_grid_equinor.py | 5 ++--- python/tests/rd_tests/test_grid_equinor_dual.py | 1 - python/tests/rd_tests/test_grid_generator.py | 1 - python/tests/rd_tests/test_grid_large_case.py | 1 - python/tests/rd_tests/test_grid_pandas.py | 1 - python/tests/rd_tests/test_kw_function.py | 2 -- python/tests/rd_tests/test_layer.py | 2 -- python/tests/rd_tests/test_npv.py | 5 +---- python/tests/rd_tests/test_rd_3dkw.py | 7 ++----- python/tests/rd_tests/test_rd_cmp.py | 2 -- python/tests/rd_tests/test_rd_file_equinor.py | 5 ++--- python/tests/rd_tests/test_rd_init_file.py | 3 +-- python/tests/rd_tests/test_rd_kw_equinor.py | 6 ++---- python/tests/rd_tests/test_rd_restart_file.py | 3 --- python/tests/rd_tests/test_rd_sum_vector.py | 1 - python/tests/rd_tests/test_rd_type.py | 1 - python/tests/rd_tests/test_rd_util.py | 1 - python/tests/rd_tests/test_restart.py | 1 - python/tests/rd_tests/test_restart_head.py | 5 +---- python/tests/rd_tests/test_rft.py | 5 ----- python/tests/rd_tests/test_sum_equinor.py | 2 -- python/tests/util_tests/test_vectors.py | 2 -- python/tests/util_tests/test_work_area.py | 1 - python/tests/well_tests/test_rd_well2.py | 8 -------- python/tests/well_tests/test_rd_well3.py | 8 -------- python/tests/well_tests/test_well_missing_ICON.py | 2 -- 61 files changed, 19 insertions(+), 129 deletions(-) diff --git a/python/resdata/geometry/cpolyline_collection.py b/python/resdata/geometry/cpolyline_collection.py index 27c9ad546..a2310a5ca 100644 --- a/python/resdata/geometry/cpolyline_collection.py +++ b/python/resdata/geometry/cpolyline_collection.py @@ -2,7 +2,6 @@ Create a polygon """ -import ctypes from cwrap import BaseCClass from resdata import ResdataPrototype diff --git a/python/resdata/geometry/geo_region.py b/python/resdata/geometry/geo_region.py index 15b6f2f5a..d041545fc 100644 --- a/python/resdata/geometry/geo_region.py +++ b/python/resdata/geometry/geo_region.py @@ -1,5 +1,4 @@ from cwrap import BaseCClass -from resdata.util.util import IntVector from resdata import ResdataPrototype from .cpolyline import CPolyline from ctypes import c_double diff --git a/python/resdata/geometry/polyline.py b/python/resdata/geometry/polyline.py index a24cc68dd..4c7a5eeab 100644 --- a/python/resdata/geometry/polyline.py +++ b/python/resdata/geometry/polyline.py @@ -1,4 +1,3 @@ -import collections from .geometry_tools import GeometryTools diff --git a/python/resdata/geometry/surface.py b/python/resdata/geometry/surface.py index d5e9ca846..14d90bbc3 100644 --- a/python/resdata/geometry/surface.py +++ b/python/resdata/geometry/surface.py @@ -7,7 +7,6 @@ from cwrap import BaseCClass from resdata import ResdataPrototype -from resdata.geometry import GeoPointset class Surface(BaseCClass): diff --git a/python/resdata/gravimetry/rd_subsidence.py b/python/resdata/gravimetry/rd_subsidence.py index 5198ddd10..8e2894cc1 100644 --- a/python/resdata/gravimetry/rd_subsidence.py +++ b/python/resdata/gravimetry/rd_subsidence.py @@ -10,7 +10,6 @@ from cwrap import BaseCClass from resdata import ResdataPrototype from resdata.util.util import monkey_the_camel -import resdata.grid class ResdataSubsidence(BaseCClass): diff --git a/python/resdata/grid/faults/fault.py b/python/resdata/grid/faults/fault.py index fdeb8dbbc..15f0459a7 100644 --- a/python/resdata/grid/faults/fault.py +++ b/python/resdata/grid/faults/fault.py @@ -1,7 +1,7 @@ import numpy as np from resdata.util.util import monkey_the_camel -from resdata.geometry import Polyline, CPolyline, GeometryTools +from resdata.geometry import CPolyline, GeometryTools from .fault_line import FaultLine from .fault_segments import FaultSegment, SegmentMap diff --git a/python/resdata/grid/faults/fault_block_layer.py b/python/resdata/grid/faults/fault_block_layer.py index 173b742e8..77f7e319d 100644 --- a/python/resdata/grid/faults/fault_block_layer.py +++ b/python/resdata/grid/faults/fault_block_layer.py @@ -1,7 +1,6 @@ from cwrap import BaseCClass from resdata.util.util import monkey_the_camel -from resdata import ResDataType from resdata import ResdataPrototype from resdata.grid.faults import Fault diff --git a/python/resdata/grid/faults/layer.py b/python/resdata/grid/faults/layer.py index 99dc5ef80..9b691c2af 100644 --- a/python/resdata/grid/faults/layer.py +++ b/python/resdata/grid/faults/layer.py @@ -1,6 +1,4 @@ -import ctypes -from resdata.grid import Grid from cwrap import BaseCClass from resdata.util.util import monkey_the_camel from resdata.util.util import IntVector diff --git a/python/resdata/grid/rd_grid.py b/python/resdata/grid/rd_grid.py index ff31311a3..3a0e55ad3 100644 --- a/python/resdata/grid/rd_grid.py +++ b/python/resdata/grid/rd_grid.py @@ -16,8 +16,7 @@ import sys import os.path import math -import itertools -from cwrap import CFILE, BaseCClass, load, open as copen +from cwrap import CFILE, BaseCClass, open as copen from resdata import ResdataPrototype from resdata.util.util import monkey_the_camel diff --git a/python/resdata/grid/rd_region.py b/python/resdata/grid/rd_region.py index 36c8c8bd9..381b06cb9 100644 --- a/python/resdata/grid/rd_region.py +++ b/python/resdata/grid/rd_region.py @@ -16,12 +16,10 @@ from cwrap import BaseCClass -import resdata from resdata.util.util import monkey_the_camel from resdata.util.util import IntVector from resdata import ResdataPrototype -from resdata.grid.faults import Layer from resdata import ResDataType from resdata.resfile import ResdataKW from resdata.geometry import CPolyline diff --git a/python/resdata/resfile/fortio.py b/python/resdata/resfile/fortio.py index d0a8903fd..5fcfebbf6 100644 --- a/python/resdata/resfile/fortio.py +++ b/python/resdata/resfile/fortio.py @@ -22,7 +22,6 @@ more extensive wrapping of the fortio implementation would be easy. """ -import ctypes import os from cwrap import BaseCClass diff --git a/python/resdata/resfile/rd_kw.py b/python/resdata/resfile/rd_kw.py index 7fe5a3ee9..28c608cb0 100644 --- a/python/resdata/resfile/rd_kw.py +++ b/python/resdata/resfile/rd_kw.py @@ -29,10 +29,9 @@ import numpy as np from cwrap import CFILE, BaseCClass -from resdata import ResdataPrototype, ResDataType, ResdataTypeEnum, ResdataUtil +from resdata import ResdataPrototype, ResDataType, ResdataTypeEnum from resdata.util.util import monkey_the_camel -from .fortio import FortIO def dump_type_deprecation_warning(): diff --git a/python/resdata/rft/well_trajectory.py b/python/resdata/rft/well_trajectory.py index 45b08ddf1..9eb0dae48 100644 --- a/python/resdata/rft/well_trajectory.py +++ b/python/resdata/rft/well_trajectory.py @@ -1,4 +1,3 @@ -import sys from collections import namedtuple from os.path import isfile diff --git a/python/resdata/summary/rd_sum.py b/python/resdata/summary/rd_sum.py index a62aa3720..02eb3a49e 100644 --- a/python/resdata/summary/rd_sum.py +++ b/python/resdata/summary/rd_sum.py @@ -24,11 +24,9 @@ from resdata.util.util import monkey_the_camel from resdata.util.util import StringList, CTime, DoubleVector, TimeVector, IntVector -from .rd_sum_tstep import SummaryTStep from .rd_sum_var_type import SummaryVarType from .rd_sum_vector import SummaryVector -from .rd_smspec_node import ResdataSMSPECNode -from resdata import ResdataPrototype, UnitSystem +from resdata import ResdataPrototype # , SummaryKeyWordVector @@ -1685,7 +1683,6 @@ def resample( return new_case -import resdata.summary.rd_sum_keyword_vector Summary._dump_csv_line = ResdataPrototype( "void rd_sum_fwrite_interp_csv_line(rd_sum, rd_time_t, rd_sum_vector, FILE)", diff --git a/python/resdata/summary/rd_sum_tstep.py b/python/resdata/summary/rd_sum_tstep.py index 54ac197f4..0262ee36b 100644 --- a/python/resdata/summary/rd_sum_tstep.py +++ b/python/resdata/summary/rd_sum_tstep.py @@ -1,7 +1,6 @@ from cwrap import BaseCClass from resdata.util.util import monkey_the_camel -from resdata.util.util import CTime from resdata import ResdataPrototype diff --git a/python/resdata/util/test/extended_testcase.py b/python/resdata/util/test/extended_testcase.py index 5311386ba..f18ba21d4 100644 --- a/python/resdata/util/test/extended_testcase.py +++ b/python/resdata/util/test/extended_testcase.py @@ -1,4 +1,3 @@ -import numbers import os import os.path import traceback diff --git a/python/resdata/util/test/source_enumerator.py b/python/resdata/util/test/source_enumerator.py index 5953a769a..ac1f37b9e 100644 --- a/python/resdata/util/test/source_enumerator.py +++ b/python/resdata/util/test/source_enumerator.py @@ -1,4 +1,3 @@ -import os import re diff --git a/python/resdata/util/util/hash.py b/python/resdata/util/util/hash.py index 153387f9c..4391f1e11 100644 --- a/python/resdata/util/util/hash.py +++ b/python/resdata/util/util/hash.py @@ -2,7 +2,6 @@ from cwrap import BaseCClass from resdata import ResdataPrototype -from resdata.util.util import StringList class Hash(BaseCClass): diff --git a/python/resdata/well/well_info.py b/python/resdata/well/well_info.py index fa3b14999..69813cfb0 100644 --- a/python/resdata/well/well_info.py +++ b/python/resdata/well/well_info.py @@ -1,8 +1,6 @@ from os.path import isfile from cwrap import BaseCClass -from resdata.grid import Grid from resdata.resfile.rd_file import ResdataFile -from resdata.well import WellTimeLine from resdata import ResdataPrototype diff --git a/python/resdata/well/well_state.py b/python/resdata/well/well_state.py index 5cd9d5489..05a82e4cb 100644 --- a/python/resdata/well/well_state.py +++ b/python/resdata/well/well_state.py @@ -1,8 +1,6 @@ from cwrap import BaseCClass from resdata import ResdataPrototype -from resdata.well import WellType, WellConnection -from resdata.util.util import CTime class WellState(BaseCClass): diff --git a/python/resdata/well/well_time_line.py b/python/resdata/well/well_time_line.py index f77f2b741..d1a9cb304 100644 --- a/python/resdata/well/well_time_line.py +++ b/python/resdata/well/well_time_line.py @@ -1,6 +1,5 @@ from cwrap import BaseCClass from resdata import ResdataPrototype -from resdata.well import WellState class WellTimeLine(BaseCClass): diff --git a/python/tests/bin_tests/test_summary_resample.py b/python/tests/bin_tests/test_summary_resample.py index 307ef0cf8..22d86b637 100644 --- a/python/tests/bin_tests/test_summary_resample.py +++ b/python/tests/bin_tests/test_summary_resample.py @@ -2,7 +2,6 @@ import subprocess from subprocess import CalledProcessError as CallError -from resdata.grid import Cell, Grid from resdata.summary import Summary from resdata.util.test import TestAreaContext from resdata.util.test.mock import createSummary diff --git a/python/tests/geometry_tests/test_cpolyline.py b/python/tests/geometry_tests/test_cpolyline.py index cdf737f71..56645f3ed 100644 --- a/python/tests/geometry_tests/test_cpolyline.py +++ b/python/tests/geometry_tests/test_cpolyline.py @@ -1,8 +1,6 @@ import math from resdata.geometry import CPolyline, Polyline -from resdata.geometry.xyz_io import XYZIo -from resdata.util.test import TestAreaContext from tests import ResdataTest diff --git a/python/tests/geometry_tests/test_cpolyline_collection.py b/python/tests/geometry_tests/test_cpolyline_collection.py index 037ddc229..265113e10 100644 --- a/python/tests/geometry_tests/test_cpolyline_collection.py +++ b/python/tests/geometry_tests/test_cpolyline_collection.py @@ -1,8 +1,5 @@ -import gc from resdata.geometry import CPolylineCollection, CPolyline -from resdata.geometry.xyz_io import XYZIo -from resdata.util.test import TestAreaContext from tests import ResdataTest from resdata.util.util import DoubleVector diff --git a/python/tests/geometry_tests/test_geo_pointset.py b/python/tests/geometry_tests/test_geo_pointset.py index 49da25663..53b5a8e6a 100644 --- a/python/tests/geometry_tests/test_geo_pointset.py +++ b/python/tests/geometry_tests/test_geo_pointset.py @@ -1,5 +1,4 @@ from resdata.geometry import GeoPointset, Surface -from resdata.util.test import TestAreaContext from tests import ResdataTest diff --git a/python/tests/geometry_tests/test_geo_region.py b/python/tests/geometry_tests/test_geo_region.py index cfcc12ee2..f01d14730 100644 --- a/python/tests/geometry_tests/test_geo_region.py +++ b/python/tests/geometry_tests/test_geo_region.py @@ -1,5 +1,4 @@ from resdata.geometry import GeoRegion, GeoPointset, CPolyline, Surface -from resdata.util.test import TestAreaContext from tests import ResdataTest diff --git a/python/tests/geometry_tests/test_geometry_tools.py b/python/tests/geometry_tests/test_geometry_tools.py index 7c72edad7..cd6674e68 100644 --- a/python/tests/geometry_tests/test_geometry_tools.py +++ b/python/tests/geometry_tests/test_geometry_tools.py @@ -1,8 +1,6 @@ import math from resdata.geometry import Polyline, GeometryTools, CPolyline -from resdata.geometry.xyz_io import XYZIo -from resdata.util.test import TestAreaContext from tests import ResdataTest diff --git a/python/tests/rd_tests/test_cell.py b/python/tests/rd_tests/test_cell.py index 4bea8a6a6..a10db28c1 100644 --- a/python/tests/rd_tests/test_cell.py +++ b/python/tests/rd_tests/test_cell.py @@ -1,7 +1,6 @@ #!/usr/bin/env python -from resdata.grid import Cell, Grid +from resdata.grid import Grid from tests import ResdataTest -from unittest import skipUnless class CellTest(ResdataTest): diff --git a/python/tests/rd_tests/test_deprecation.py b/python/tests/rd_tests/test_deprecation.py index d754f1b5f..3e209056a 100644 --- a/python/tests/rd_tests/test_deprecation.py +++ b/python/tests/rd_tests/test_deprecation.py @@ -1,15 +1,10 @@ #!/usr/bin/env python -import datetime -import time import warnings from resdata import ResDataType -from resdata.grid import Grid, GridGenerator, ResdataRegion +from resdata.grid import GridGenerator, ResdataRegion from resdata.resfile import FortIO, ResdataFile, ResdataKW, openFortIO -from resdata.rft import ResdataRFT from resdata.util.test import TestAreaContext -from resdata.util.test.mock import createSummary -from resdata.util.util import BoolVector from tests import ResdataTest # The class Deprecation_1_9_Test contains methods which will be marked diff --git a/python/tests/rd_tests/test_equinor_faults.py b/python/tests/rd_tests/test_equinor_faults.py index c0a1057da..213343b04 100644 --- a/python/tests/rd_tests/test_equinor_faults.py +++ b/python/tests/rd_tests/test_equinor_faults.py @@ -1,13 +1,11 @@ #!/usr/bin/env python -from unittest import skipIf from cwrap import open as copen -import time from resdata import ResDataType from resdata.resfile import ResdataKW from resdata.grid import Grid -from resdata.grid.faults import FaultCollection, Fault, FaultLine, FaultSegment +from resdata.grid.faults import FaultCollection, Fault from tests import ResdataTest, equinor_test diff --git a/python/tests/rd_tests/test_fault_blocks.py b/python/tests/rd_tests/test_fault_blocks.py index 221a98bd6..6d27c7d90 100644 --- a/python/tests/rd_tests/test_fault_blocks.py +++ b/python/tests/rd_tests/test_fault_blocks.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -from unittest import skipIf import cwrap from resdata import ResDataType diff --git a/python/tests/rd_tests/test_fault_blocks_equinor.py b/python/tests/rd_tests/test_fault_blocks_equinor.py index 1ee71bd4f..a63d7eb4b 100644 --- a/python/tests/rd_tests/test_fault_blocks_equinor.py +++ b/python/tests/rd_tests/test_fault_blocks_equinor.py @@ -1,11 +1,10 @@ #!/usr/bin/env python -from unittest import skipIf from resdata import ResDataType from resdata.resfile import ResdataKW from resdata.grid import Grid from tests import ResdataTest, equinor_test -from resdata.grid.faults import FaultBlock, FaultBlockLayer +from resdata.grid.faults import FaultBlockLayer from cwrap import open as copen diff --git a/python/tests/rd_tests/test_faults.py b/python/tests/rd_tests/test_faults.py index 61434589d..efcd7200b 100644 --- a/python/tests/rd_tests/test_faults.py +++ b/python/tests/rd_tests/test_faults.py @@ -1,7 +1,4 @@ #!/usr/bin/env python -from unittest import skipIf -import time -from resdata import util from resdata import ResDataType from resdata.resfile import ResdataKW diff --git a/python/tests/rd_tests/test_fk_user_data.py b/python/tests/rd_tests/test_fk_user_data.py index 90075845f..8deb77fa4 100644 --- a/python/tests/rd_tests/test_fk_user_data.py +++ b/python/tests/rd_tests/test_fk_user_data.py @@ -1,6 +1,5 @@ #!/usr/bin/env python from resdata.grid import Grid -from resdata.util.test import TestAreaContext from tests import ResdataTest diff --git a/python/tests/rd_tests/test_grav.py b/python/tests/rd_tests/test_grav.py index ff7a15725..190328e81 100644 --- a/python/tests/rd_tests/test_grav.py +++ b/python/tests/rd_tests/test_grav.py @@ -5,7 +5,6 @@ from resdata.gravimetry import ResdataGrav from resdata.util.test import TestAreaContext from tests import ResdataTest -from resdata.rd_util import Phase class ResdataGravTest(ResdataTest): diff --git a/python/tests/rd_tests/test_grid_equinor.py b/python/tests/rd_tests/test_grid_equinor.py index 873f6e6b9..22527e5c3 100755 --- a/python/tests/rd_tests/test_grid_equinor.py +++ b/python/tests/rd_tests/test_grid_equinor.py @@ -3,12 +3,11 @@ from unittest import skipIf -from cwrap import Prototype from cwrap import open as copen import time -from resdata import ResDataType, UnitSystem -from resdata.resfile import ResdataKW, ResdataFile, openResdataFile +from resdata import ResDataType +from resdata.resfile import ResdataKW, openResdataFile from resdata.grid import Grid from resdata.util.util import DoubleVector, IntVector from resdata.util.test import TestAreaContext diff --git a/python/tests/rd_tests/test_grid_equinor_dual.py b/python/tests/rd_tests/test_grid_equinor_dual.py index 731abd31f..73d1b067e 100644 --- a/python/tests/rd_tests/test_grid_equinor_dual.py +++ b/python/tests/rd_tests/test_grid_equinor_dual.py @@ -1,4 +1,3 @@ -import math from resdata.util.test import TestAreaContext from resdata.grid import Grid diff --git a/python/tests/rd_tests/test_grid_generator.py b/python/tests/rd_tests/test_grid_generator.py index 64a1f8262..5d7a54a3a 100644 --- a/python/tests/rd_tests/test_grid_generator.py +++ b/python/tests/rd_tests/test_grid_generator.py @@ -9,7 +9,6 @@ from resdata.resfile import ResdataKW from resdata.grid import Grid from resdata.grid import GridGenerator as GridGen -from resdata.util.test import TestAreaContext from tests import ResdataTest diff --git a/python/tests/rd_tests/test_grid_large_case.py b/python/tests/rd_tests/test_grid_large_case.py index b08ed8d6f..ca07859be 100644 --- a/python/tests/rd_tests/test_grid_large_case.py +++ b/python/tests/rd_tests/test_grid_large_case.py @@ -1,4 +1,3 @@ -import itertools import pytest from resdata.grid import Grid diff --git a/python/tests/rd_tests/test_grid_pandas.py b/python/tests/rd_tests/test_grid_pandas.py index 15158d08e..23fe0fb95 100644 --- a/python/tests/rd_tests/test_grid_pandas.py +++ b/python/tests/rd_tests/test_grid_pandas.py @@ -1,6 +1,5 @@ #!/usr/bin/env python import numpy as np -import pandas as pd from resdata import ResdataTypeEnum diff --git a/python/tests/rd_tests/test_kw_function.py b/python/tests/rd_tests/test_kw_function.py index dc1158b19..44def55ca 100644 --- a/python/tests/rd_tests/test_kw_function.py +++ b/python/tests/rd_tests/test_kw_function.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -import os -import random from resdata import ResDataType from resdata.resfile import ResdataKW, Resdata3DKW from resdata.grid import Grid diff --git a/python/tests/rd_tests/test_layer.py b/python/tests/rd_tests/test_layer.py index 62e790c9d..10add9f38 100644 --- a/python/tests/rd_tests/test_layer.py +++ b/python/tests/rd_tests/test_layer.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -from unittest import skipIf -import time from resdata.util.util import IntVector from resdata.grid import Grid diff --git a/python/tests/rd_tests/test_npv.py b/python/tests/rd_tests/test_npv.py index fcec50641..4a7ca8b30 100644 --- a/python/tests/rd_tests/test_npv.py +++ b/python/tests/rd_tests/test_npv.py @@ -1,13 +1,10 @@ #!/usr/bin/env python -import os import datetime -import math from resdata.summary import Summary from resdata.summary import ResdataNPV, NPVPriceVector -from resdata.util.util import StringList, TimeVector, DoubleVector, CTime -from resdata.util.test import TestAreaContext +from resdata.util.util import CTime from tests import ResdataTest, equinor_test diff --git a/python/tests/rd_tests/test_rd_3dkw.py b/python/tests/rd_tests/test_rd_3dkw.py index 1ae1f8b9d..bae4d7eac 100644 --- a/python/tests/rd_tests/test_rd_3dkw.py +++ b/python/tests/rd_tests/test_rd_3dkw.py @@ -1,12 +1,9 @@ #!/usr/bin/env python -import os -import random from resdata.util.util import IntVector -from resdata import ResDataType, FileMode -from resdata.resfile import Resdata3DKW, ResdataKW, ResdataFile, FortIO +from resdata import ResDataType +from resdata.resfile import Resdata3DKW, ResdataKW from resdata.grid import Grid -from resdata.util.test import TestAreaContext from tests import ResdataTest diff --git a/python/tests/rd_tests/test_rd_cmp.py b/python/tests/rd_tests/test_rd_cmp.py index 152cdb762..7ac2e18a0 100644 --- a/python/tests/rd_tests/test_rd_cmp.py +++ b/python/tests/rd_tests/test_rd_cmp.py @@ -1,6 +1,4 @@ from resdata.summary import ResdataCmp -from resdata.util.test import TestAreaContext -from resdata.util.test.mock import createSummary from tests import ResdataTest, equinor_test diff --git a/python/tests/rd_tests/test_rd_file_equinor.py b/python/tests/rd_tests/test_rd_file_equinor.py index a374b5149..051d2613a 100755 --- a/python/tests/rd_tests/test_rd_file_equinor.py +++ b/python/tests/rd_tests/test_rd_file_equinor.py @@ -1,10 +1,9 @@ #!/usr/bin/env python import datetime -import os.path from unittest import skipIf -from resdata import FileMode, FileType -from resdata.resfile import ResdataFile, FortIO, ResdataKW, openFortIO, openResdataFile +from resdata import FileMode +from resdata.resfile import ResdataFile, FortIO from resdata.util.test import TestAreaContext from tests import ResdataTest, equinor_test diff --git a/python/tests/rd_tests/test_rd_init_file.py b/python/tests/rd_tests/test_rd_init_file.py index bf1404961..7e622889a 100644 --- a/python/tests/rd_tests/test_rd_init_file.py +++ b/python/tests/rd_tests/test_rd_init_file.py @@ -1,6 +1,5 @@ from tests import ResdataTest, equinor_test -from resdata import FileMode -from resdata.resfile import Resdata3DKW, ResdataKW, ResdataInitFile, ResdataFile, FortIO +from resdata.resfile import Resdata3DKW, ResdataKW, ResdataInitFile from resdata.grid import Grid diff --git a/python/tests/rd_tests/test_rd_kw_equinor.py b/python/tests/rd_tests/test_rd_kw_equinor.py index 12afd83cb..24f2c13ba 100755 --- a/python/tests/rd_tests/test_rd_kw_equinor.py +++ b/python/tests/rd_tests/test_rd_kw_equinor.py @@ -1,10 +1,8 @@ #!/usr/bin/env python import os -import random -from resdata import ResDataType, FileMode -from resdata.resfile import ResdataKW, ResdataFile, FortIO +from resdata import ResDataType +from resdata.resfile import ResdataKW, ResdataFile -from resdata.util.test import TestAreaContext from tests import ResdataTest, equinor_test diff --git a/python/tests/rd_tests/test_rd_restart_file.py b/python/tests/rd_tests/test_rd_restart_file.py index 3b60c4e86..925045dea 100644 --- a/python/tests/rd_tests/test_rd_restart_file.py +++ b/python/tests/rd_tests/test_rd_restart_file.py @@ -1,13 +1,10 @@ import datetime from tests import ResdataTest, equinor_test -from resdata import FileMode from resdata.resfile import ( Resdata3DKW, ResdataKW, ResdataRestartFile, - ResdataFile, - FortIO, ) from resdata.grid import Grid diff --git a/python/tests/rd_tests/test_rd_sum_vector.py b/python/tests/rd_tests/test_rd_sum_vector.py index 3b7a1c2dd..5d5b785bc 100644 --- a/python/tests/rd_tests/test_rd_sum_vector.py +++ b/python/tests/rd_tests/test_rd_sum_vector.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -from unittest import skipIf import warnings diff --git a/python/tests/rd_tests/test_rd_type.py b/python/tests/rd_tests/test_rd_type.py index a6f1f132c..7bc792575 100644 --- a/python/tests/rd_tests/test_rd_type.py +++ b/python/tests/rd_tests/test_rd_type.py @@ -1,4 +1,3 @@ -from resdata.util.test import TestAreaContext from tests import ResdataTest from resdata import ResDataType, ResdataTypeEnum diff --git a/python/tests/rd_tests/test_rd_util.py b/python/tests/rd_tests/test_rd_util.py index 915624546..8dfa0d33b 100644 --- a/python/tests/rd_tests/test_rd_util.py +++ b/python/tests/rd_tests/test_rd_util.py @@ -1,4 +1,3 @@ -import pytest import datetime from textwrap import dedent diff --git a/python/tests/rd_tests/test_restart.py b/python/tests/rd_tests/test_restart.py index a327536c7..cc4ab4b54 100755 --- a/python/tests/rd_tests/test_restart.py +++ b/python/tests/rd_tests/test_restart.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -from _ctypes import ArgumentError import os import datetime from resdata.resfile import ResdataFile diff --git a/python/tests/rd_tests/test_restart_head.py b/python/tests/rd_tests/test_restart_head.py index 2c7caae2c..e43b9cbf2 100644 --- a/python/tests/rd_tests/test_restart_head.py +++ b/python/tests/rd_tests/test_restart_head.py @@ -2,13 +2,10 @@ import os.path from tests import ResdataTest, equinor_test, source_root -from resdata import FileMode, ResDataType +from resdata import ResDataType from resdata.resfile import ( - Resdata3DKW, ResdataKW, ResdataRestartFile, - ResdataFile, - FortIO, ) from resdata.resfile.rd_restart_file import ResdataRestartHead from resdata.grid import Grid diff --git a/python/tests/rd_tests/test_rft.py b/python/tests/rd_tests/test_rft.py index 0aa92b022..5cad6c5a1 100644 --- a/python/tests/rd_tests/test_rft.py +++ b/python/tests/rd_tests/test_rft.py @@ -1,12 +1,7 @@ #!/usr/bin/env python import datetime -from resdata.util.util import CTime from resdata.rft import ( - ResdataRFTFile, - ResdataRFTCell, - ResdataPLTCell, ResdataRFT, - WellTrajectory, ) from tests import ResdataTest diff --git a/python/tests/rd_tests/test_sum_equinor.py b/python/tests/rd_tests/test_sum_equinor.py index 9c6422482..fdf61c626 100755 --- a/python/tests/rd_tests/test_sum_equinor.py +++ b/python/tests/rd_tests/test_sum_equinor.py @@ -1,7 +1,6 @@ import os import datetime -from resdata.resfile import ResdataFile from resdata.summary import Summary from resdata import UnitSystem @@ -9,7 +8,6 @@ from resdata.util.test import TestAreaContext from tests import ResdataTest, equinor_test -import csv base = "ECLIPSE" path = "Equinor/ECLIPSE/Gurbat" diff --git a/python/tests/util_tests/test_vectors.py b/python/tests/util_tests/test_vectors.py index 9898eb853..c3687eccf 100755 --- a/python/tests/util_tests/test_vectors.py +++ b/python/tests/util_tests/test_vectors.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import copy import datetime import six @@ -11,7 +10,6 @@ BoolVector, TimeVector, CTime, - PermutationVector, ) diff --git a/python/tests/util_tests/test_work_area.py b/python/tests/util_tests/test_work_area.py index 151435aa5..6e6476d19 100644 --- a/python/tests/util_tests/test_work_area.py +++ b/python/tests/util_tests/test_work_area.py @@ -2,7 +2,6 @@ import os.path import os -from unittest import skipIf from resdata.util.test import TestAreaContext from tests import ResdataTest diff --git a/python/tests/well_tests/test_rd_well2.py b/python/tests/well_tests/test_rd_well2.py index 842cc4ecc..1de05c9f8 100644 --- a/python/tests/well_tests/test_rd_well2.py +++ b/python/tests/well_tests/test_rd_well2.py @@ -1,17 +1,9 @@ -import datetime import os.path -from resdata import FileMode -from resdata.resfile import ResdataFile from resdata.grid import Grid from tests import ResdataTest, equinor_test -from resdata.util.util.ctime import CTime from resdata.well import ( WellInfo, - WellConnection, - WellType, - WellConnectionDirection, - WellSegment, ) diff --git a/python/tests/well_tests/test_rd_well3.py b/python/tests/well_tests/test_rd_well3.py index 3e46df2b6..cfbc84ea2 100644 --- a/python/tests/well_tests/test_rd_well3.py +++ b/python/tests/well_tests/test_rd_well3.py @@ -1,17 +1,9 @@ -import datetime -import os.path -from resdata.resfile import ResdataFile from resdata.grid import Grid from resdata.summary import Summary from tests import ResdataTest, equinor_test -from resdata.util.util.ctime import CTime from resdata.well import ( WellInfo, - WellConnection, - WellType, - WellConnectionDirection, - WellSegment, ) diff --git a/python/tests/well_tests/test_well_missing_ICON.py b/python/tests/well_tests/test_well_missing_ICON.py index 7ca828194..b06d57251 100644 --- a/python/tests/well_tests/test_well_missing_ICON.py +++ b/python/tests/well_tests/test_well_missing_ICON.py @@ -4,10 +4,8 @@ from resdata.resfile import ResdataFile from resdata.well import ( WellInfo, - WellConnection, WellType, WellConnectionDirection, - WellSegment, ) From d0380ee1cba3ddb73e866bb0534ae2ac085a6f46 Mon Sep 17 00:00:00 2001 From: larsevj Date: Thu, 29 Aug 2024 17:30:10 +0200 Subject: [PATCH 09/11] Various fixes --- pyproject.toml | 2 ++ python/docs/examples/avg_pressure.py | 4 +-- python/docs/examples/cmp_nnc.py | 4 +-- python/resdata/grid/faults/fault.py | 2 +- python/resdata/grid/faults/fault_line.py | 14 ++++----- python/resdata/grid/faults/layer.py | 15 +++++----- python/resdata/grid/rd_grid.py | 36 +++++++++++------------ python/resdata/grid/rd_grid_generator.py | 23 +++++++-------- python/resdata/grid/rd_region.py | 6 ++-- python/resdata/rd_util.py | 2 +- python/resdata/resfile/rd_init_file.py | 2 +- python/resdata/resfile/rd_kw.py | 12 ++++---- python/resdata/resfile/rd_restart_file.py | 2 +- python/resdata/rft/rd_rft.py | 2 +- python/resdata/summary/rd_sum.py | 3 +- python/resdata/util/test/path_context.py | 2 +- python/tests/rd_tests/test_grid.py | 2 +- python/tests/rd_tests/test_sum.py | 2 +- 18 files changed, 69 insertions(+), 66 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 7f38ab0b5..2a974e17c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,8 @@ ignore = ["PLW2901", # redefined-loop-name "PD901", # pandas-df-variable-name "C409", # unnecessary-literal-within-tuple-call "PLC0414", # useless-import-alias + "PLW1514", + "C419", ] [tool.ruff.lint.extend-per-file-ignores] "python/tests/util_tests/test_ctime.py" = ["PLR0124", "B015"] diff --git a/python/docs/examples/avg_pressure.py b/python/docs/examples/avg_pressure.py index dd37e441e..c23ee4595 100755 --- a/python/docs/examples/avg_pressure.py +++ b/python/docs/examples/avg_pressure.py @@ -66,9 +66,9 @@ def avg_pressure(p, sw, pv, region, region_id, result): avg_pressure(p, sw, pv, ResdataRegion(grid, True), "field", result) sim_days.append(header.get_sim_days()) - for key in result: + for key, value in result.items(): plt.figure(1) - for index, p in enumerate(result[key]): + for index, p in enumerate(value): plt.plot(sim_days, p, label="Region:%s P%d" % (key, index + 1)) plt.legend() plt.show() diff --git a/python/docs/examples/cmp_nnc.py b/python/docs/examples/cmp_nnc.py index 4ca50e36f..1a4f2e528 100755 --- a/python/docs/examples/cmp_nnc.py +++ b/python/docs/examples/cmp_nnc.py @@ -23,8 +23,8 @@ for g1, g2, T in nnc_list: # grid_ijk assumes 0-based indexing, g1/g2 are 1-based (FORTRAN) # Convert them to zero based ones. - g1 = g1 - 1 - g2 = g2 - 1 + g1 -= 1 + g2 -= 1 i1, j1, k1 = grid.get_ijk(global_index=g1) i2, j2, k2 = grid.get_ijk(global_index=g2) diff --git a/python/resdata/grid/faults/fault.py b/python/resdata/grid/faults/fault.py index 15f0459a7..eb2f3e9a0 100644 --- a/python/resdata/grid/faults/fault.py +++ b/python/resdata/grid/faults/fault.py @@ -151,7 +151,7 @@ def __init__(self, grid, name): self.__name = name self.__layer_map = {} self.__layer_list = [] - (self.nx, self.ny, self.nz, nactive) = grid.getDims() + (self.nx, self.ny, self.nz, _) = grid.getDims() def __str__(self): return f"Fault:{self.__name}" diff --git a/python/resdata/grid/faults/fault_line.py b/python/resdata/grid/faults/fault_line.py index 88b6bd28a..80f468285 100644 --- a/python/resdata/grid/faults/fault_line.py +++ b/python/resdata/grid/faults/fault_line.py @@ -71,7 +71,7 @@ def k(self): def __init_ij_polyline(self): pl = [] - nx = self.__grid.getNX() + nx = self.__grid.get_nx() for segment in self: corner = segment.getC1() i = corner % (nx + 1) @@ -88,8 +88,8 @@ def __init_ij_polyline(self): def __init_polyline(self): pl = CPolyline() - for i, j in self.getIJPolyline(): - x, y, z = self.__grid.getNodeXYZ(i, j, self.__k) + for i, j in self.get_ij_polyline(): + x, y, _ = self.__grid.getNodeXYZ(i, j, self.__k) pl.addPoint(x, y) self.__polyline = pl @@ -162,8 +162,8 @@ def center(self): (J1, I1) = divmod(C1, self.__grid.getNX() + 1) (J2, I2) = divmod(C2, self.__grid.getNX() + 1) - (x1, y1, z) = self.__grid.getNodePos(I1, J1, self.__k) - (x2, y2, z) = self.__grid.getNodePos(I2, J2, self.__k) + (x1, y1, _) = self.__grid.getNodePos(I1, J1, self.__k) + (x2, y2, _) = self.__grid.getNodePos(I2, J2, self.__k) xlist.append(x1) xlist.append(x2) @@ -197,8 +197,8 @@ def dump(self): for segment in self: C1 = segment.getC1() C2 = segment.getC2() - (J1, I1) = divmod(C1, self.__grid.getNX() + 1) - (J2, I2) = divmod(C2, self.__grid.getNX() + 1) + (J1, I1) = divmod(C1, self.__grid.get_nx() + 1) + (J2, I2) = divmod(C2, self.__grid.get_nx() + 1) print( "[Corner:%5d IJ:(%3d,%d)] -> [Corner:%5d IJ:(%3d,%d)]" % (C1, I1, J1, C2, I2, J2) diff --git a/python/resdata/grid/faults/layer.py b/python/resdata/grid/faults/layer.py index 9b691c2af..0313258f3 100644 --- a/python/resdata/grid/faults/layer.py +++ b/python/resdata/grid/faults/layer.py @@ -1,4 +1,3 @@ - from cwrap import BaseCClass from resdata.util.util import monkey_the_camel from resdata.util.util import IntVector @@ -52,11 +51,11 @@ def __init__(self, nx, ny): raise ValueError("Invalid input - no Layer object created") def _assert_ij(self, i, j): - if i < 0 or i >= self.getNX(): - raise ValueError("Invalid layer i:%d" % i) + if i < 0 or i >= self.get_nx(): + raise ValueError(f"Invalid layer i:{i}") - if j < 0 or j >= self.getNY(): - raise ValueError("Invalid layer j:%d" % j) + if j < 0 or j >= self.get_ny(): + raise ValueError(f"Invalid layer j:{j}") def __unpack_index(self, index): try: @@ -168,7 +167,7 @@ def add_fault_barrier(self, fault, K, link_segments=True): if index < num_lines - 1: next_line = fault_layer[index + 1] next_segment = next_line[0] - next_c1, next_c2 = next_segment.getCorners() + next_c1, _ = next_segment.getCorners() if link_segments: self.addInterpBarrier(c2, next_c1) @@ -177,8 +176,8 @@ def add_ij_barrier(self, ij_list): if len(ij_list) < 2: raise ValueError("Must have at least two (i,j) points") - nx = self.getNX() - ny = self.getNY() + nx = self.get_nx() + ny = self.get_ny() p1 = ij_list[0] i1, j1 = p1 for p2 in ij_list[1:]: diff --git a/python/resdata/grid/rd_grid.py b/python/resdata/grid/rd_grid.py index 3a0e55ad3..5c9112942 100644 --- a/python/resdata/grid/rd_grid.py +++ b/python/resdata/grid/rd_grid.py @@ -402,7 +402,7 @@ def get_num_active_fracture(self): return self._get_active_fracture() def get_bounding_box_2d(self, layer=0, lower_left=None, upper_right=None): - if 0 <= layer <= self.getNZ(): + if 0 <= layer <= self.get_nz(): x = ctypes.c_double() y = ctypes.c_double() z = ctypes.c_double() @@ -412,22 +412,22 @@ def get_bounding_box_2d(self, layer=0, lower_left=None, upper_right=None): j1 = 0 else: i1, j1 = lower_left - if not 0 < i1 < self.getNX(): + if not 0 < i1 < self.get_nx(): raise ValueError("lower_left i coordinate invalid") - if not 0 < j1 < self.getNY(): + if not 0 < j1 < self.get_ny(): raise ValueError("lower_left j coordinate invalid") if upper_right is None: - i2 = self.getNX() - j2 = self.getNY() + i2 = self.get_nx() + j2 = self.get_ny() else: i2, j2 = upper_right - if not 1 < i2 <= self.getNX(): + if not 1 < i2 <= self.get_nx(): raise ValueError("upper_right i coordinate invalid") - if not 1 < j2 <= self.getNY(): + if not 1 < j2 <= self.get_ny(): raise ValueError("upper_right j coordinate invalid") if not i1 < i2: @@ -537,9 +537,9 @@ def __global_index(self, active_index=None, global_index=None, ijk=None): if not active_index is None: global_index = self._get_global_index1A(active_index) elif ijk: - nx = self.getNX() - ny = self.getNY() - nz = self.getNZ() + nx = self.get_nx() + ny = self.get_ny() + nz = self.get_nz() i, j, k = ijk @@ -553,7 +553,7 @@ def __global_index(self, active_index=None, global_index=None, ijk=None): raise IndexError("Invalid value k:%d Range: [%d,%d)" % (k, 0, nz)) global_index = self._get_global_index3(i, j, k) - elif not 0 <= global_index < self.getGlobalSize(): + elif not 0 <= global_index < self.get_global_size(): raise IndexError( "Invalid value global_index:%d Range: [%d,%d)" % (global_index, 0, self.getGlobalSize()) @@ -717,9 +717,9 @@ def get_node_pos(self, i, j, k): bounding points of the lower layer of the grid: p0 = grid.getNodePos(0, 0, 0) - p1 = grid.getNodePos(grid.getNX(), 0, 0) - p2 = grid.getNodePos(0, grid.getNY(), 0) - p3 = grid.getNodePos(grid.getNX(), grid.getNY(), 0) + p1 = grid.getNodePos(grid.get_nx(), 0, 0) + p2 = grid.getNodePos(0, grid.get_ny(), 0) + p3 = grid.getNodePos(grid.get_nx(), grid.get_ny(), 0) """ if not 0 <= i <= self.getNX(): @@ -946,19 +946,19 @@ def find_cell_corner_xy(self, x, y, k): corner_shift = 0 nx = self.getNX() - x0, y0, z0 = self.getCellCorner(corner_shift, ijk=(i, j, k)) + x0, y0, _ = self.getCellCorner(corner_shift, ijk=(i, j, k)) d0 = math.sqrt((x0 - x) * (x0 - x) + (y0 - y) * (y0 - y)) c0 = i + j * (nx + 1) - x1, y1, z1 = self.getCellCorner(1 + corner_shift, ijk=(i, j, k)) + x1, y1, _ = self.getCellCorner(1 + corner_shift, ijk=(i, j, k)) d1 = math.sqrt((x1 - x) * (x1 - x) + (y1 - y) * (y1 - y)) c1 = i + 1 + j * (nx + 1) - x2, y2, z2 = self.getCellCorner(2 + corner_shift, ijk=(i, j, k)) + x2, y2, _ = self.getCellCorner(2 + corner_shift, ijk=(i, j, k)) d2 = math.sqrt((x2 - x) * (x2 - x) + (y2 - y) * (y2 - y)) c2 = i + (j + 1) * (nx + 1) - x3, y3, z3 = self.getCellCorner(3 + corner_shift, ijk=(i, j, k)) + x3, y3, _ = self.getCellCorner(3 + corner_shift, ijk=(i, j, k)) d3 = math.sqrt((x3 - x) * (x3 - x) + (y3 - y) * (y3 - y)) c3 = i + 1 + (j + 1) * (nx + 1) diff --git a/python/resdata/grid/rd_grid_generator.py b/python/resdata/grid/rd_grid_generator.py index 6547fcc7c..a46126aa2 100644 --- a/python/resdata/grid/rd_grid_generator.py +++ b/python/resdata/grid/rd_grid_generator.py @@ -149,13 +149,13 @@ def create_zcorn( ) nx, ny, nz = dims - dx, dy, dz = dV + _, _, dz = dV # Compute zcorn z = escape_origo_shift[2] zcorn = [z] * (4 * nx * ny) for k in range(nz - 1): - z = z + dz + z += dz local_offset = offset + (dz / 2.0 if irregular_offset and k % 2 == 0 else 0) layer = [] @@ -166,10 +166,10 @@ def create_zcorn( ] layer.append(duplicate_inner(path)) - zcorn = zcorn + (2 * flatten(duplicate_inner(layer))) + zcorn += 2 * flatten(duplicate_inner(layer)) - z = z + dz - zcorn = zcorn + ([z] * (4 * nx * ny)) + z += dz + zcorn += [z] * (4 * nx * ny) if faults: # Ensure that drop does not align with grid structure @@ -201,7 +201,7 @@ def create_coord( coord = [] for j, i in itertools.product(range(ny + 1), range(nx + 1)): x, y = i * dx + escape_origo_shift[0], j * dy + escape_origo_shift[1] - coord = coord + [x, y, escape_origo_shift[2], x, y, z] + coord += [x, y, escape_origo_shift[2], x, y, z] # Apply transformations lower_center = ( @@ -234,8 +234,7 @@ def __assert_zcorn_parameters( concave, faults, ): - nx, ny, nz = dims - dx, dy, dz = dV + _, _, dz = dV # Validate arguments if min(dims + dV) <= 0: @@ -354,7 +353,7 @@ def __create_faults(cls, nx, ny, nz, zcorn, drop): corner[i] = corner[i - 4] + plane_size for c in corner: - zcorn[c] = zcorn[c] + drop + zcorn[c] += drop return zcorn @@ -395,7 +394,7 @@ def __scale_coord(cls, coord, scale, lower_center): @classmethod def __misalign_coord(cls, coord, dims, dV): - nx, ny, nz = dims + nx, _, _ = dims coord = np.array( [list(map(float, coord[i : i + 6 :])) for i in range(0, len(coord), 6)] @@ -442,7 +441,7 @@ def __translate_lower_coord(cls, coord, translation): ) translation = np.array(3 * [0.0] + list(translation)) - coord = coord + translation + coord += translation return coord.flatten().tolist() @classmethod @@ -579,7 +578,7 @@ def __translate_coord(cls, coord, translation): ) translation = np.array(list(translation) + list(translation)) - coord = coord + translation + coord += translation return construct_floatKW("COORD", coord.flatten().tolist()) @classmethod diff --git a/python/resdata/grid/rd_region.py b/python/resdata/grid/rd_region.py index 381b06cb9..e4b826748 100644 --- a/python/resdata/grid/rd_region.py +++ b/python/resdata/grid/rd_region.py @@ -453,7 +453,8 @@ def union_with(self, other): See doscumentation of __ior__(). """ - return self.__ior__(other) + self |= other + return self def intersect_with(self, other): """ @@ -461,7 +462,8 @@ def intersect_with(self, other): See doscumentation of __iand__(). """ - return self.__iand__(other) + self &= other + return self def copy(self): return self.__deep_copy__({}) diff --git a/python/resdata/rd_util.py b/python/resdata/rd_util.py index a4d5b8f87..c2a7f5c97 100644 --- a/python/resdata/rd_util.py +++ b/python/resdata/rd_util.py @@ -121,7 +121,7 @@ def get_file_type(filename): """ Will inspect an ECLIPSE filename and return an integer type flag. """ - file_type, fmt, step = ResdataUtil.inspectExtension(filename) + file_type, _, _ = ResdataUtil.inspectExtension(filename) return file_type @staticmethod diff --git a/python/resdata/resfile/rd_init_file.py b/python/resdata/resfile/rd_init_file.py index 90ce37b0a..a8c1dd840 100644 --- a/python/resdata/resfile/rd_init_file.py +++ b/python/resdata/resfile/rd_init_file.py @@ -4,7 +4,7 @@ class ResdataInitFile(Resdata3DFile): def __init__(self, grid, filename, flags=FileMode.DEFAULT): - file_type, report_step, fmt_file = ResdataFile.getFileType(filename) + file_type, _, _ = ResdataFile.getFileType(filename) if file_type == FileType.INIT: super().__init__(grid, filename, flags) else: diff --git a/python/resdata/resfile/rd_kw.py b/python/resdata/resfile/rd_kw.py index 28c608cb0..796a17908 100644 --- a/python/resdata/resfile/rd_kw.py +++ b/python/resdata/resfile/rd_kw.py @@ -33,7 +33,6 @@ from resdata.util.util import monkey_the_camel - def dump_type_deprecation_warning(): warnings.warn( "ResdataTypeEnum is deprecated. You should instead provide an ResDataType", @@ -317,7 +316,7 @@ def read_grdecl(cls, fileH, kw, strict=True, rd_type=None): ) if rd_type is None: - if cls.int_kw_set.__contains__(kw): + if kw in cls.int_kw_set: rd_type = ResDataType.RD_INT else: rd_type = ResDataType.RD_FLOAT @@ -773,7 +772,8 @@ def add(self, other, mask=None, force_active=False): if mask is not None: mask.iadd_kw(self, other, force_active) else: - return self.__iadd__(other) + self += other + return self def sub(self, other, mask=None, force_active=False): """ @@ -783,7 +783,8 @@ def sub(self, other, mask=None, force_active=False): if mask is not None: mask.isub_kw(self, other, force_active) else: - return self.__isub__(other) + self -= other + return self def mul(self, other, mask=None, force_active=False): """ @@ -793,7 +794,8 @@ def mul(self, other, mask=None, force_active=False): if mask is not None: mask.imul_kw(self, other, force_active) else: - return self.__imul__(other) + self *= other + return self def div(self, other, mask=None, force_active=False): """ diff --git a/python/resdata/resfile/rd_restart_file.py b/python/resdata/resfile/rd_restart_file.py index fca970d6e..bc3fd60d8 100644 --- a/python/resdata/resfile/rd_restart_file.py +++ b/python/resdata/resfile/rd_restart_file.py @@ -68,7 +68,7 @@ def __init__(self, grid, filename, flags=FileMode.DEFAULT): 'nactive' or 'nx*ny*nz' elements. """ - file_type, report_step, fmt_file = ResdataFile.getFileType(filename) + file_type, report_step, _ = ResdataFile.getFileType(filename) if not file_type in [ FileType.RESTART, FileType.UNIFIED_RESTART, diff --git a/python/resdata/rft/rd_rft.py b/python/resdata/rft/rd_rft.py index fe33cb138..1372bc447 100644 --- a/python/resdata/rft/rd_rft.py +++ b/python/resdata/rft/rd_rft.py @@ -132,7 +132,7 @@ def __cell_ref(self, cell_ptr): def assert_cell_index(self, index): if isinstance(index, int): - length = self.__len__() + length = len(self) if index < 0 or index >= length: raise IndexError else: diff --git a/python/resdata/summary/rd_sum.py b/python/resdata/summary/rd_sum.py index 02eb3a49e..5a1e22991 100644 --- a/python/resdata/summary/rd_sum.py +++ b/python/resdata/summary/rd_sum.py @@ -592,7 +592,7 @@ def pandas_frame(self, time_index=None, column_keys=None): 2010-04-01 672.7 620.4 78.7 .... """ - from resdata.summary import SummaryKeyWordVector + from resdata.summary import SummaryKeyWordVector # noqa: PLC0415 if column_keys is None: keywords = SummaryKeyWordVector(self, add_keywords=True) @@ -1683,7 +1683,6 @@ def resample( return new_case - Summary._dump_csv_line = ResdataPrototype( "void rd_sum_fwrite_interp_csv_line(rd_sum, rd_time_t, rd_sum_vector, FILE)", bind=False, diff --git a/python/resdata/util/test/path_context.py b/python/resdata/util/test/path_context.py index 2775ace2f..3c5f54880 100644 --- a/python/resdata/util/test/path_context.py +++ b/python/resdata/util/test/path_context.py @@ -13,7 +13,7 @@ def __init__(self, path, store=False): work_path = path while True: - work_path, base = os.path.split(work_path) + work_path, _ = os.path.split(work_path) if work_path: if os.path.isdir(work_path): break diff --git a/python/tests/rd_tests/test_grid.py b/python/tests/rd_tests/test_grid.py index 4401169c6..68cdf7d02 100644 --- a/python/tests/rd_tests/test_grid.py +++ b/python/tests/rd_tests/test_grid.py @@ -595,7 +595,7 @@ def test_cell_face_containment(self): for x, y, z in itertools.product(range(d // 2, n * d, d), repeat=3): for axis, direction in itertools.product(range(3), [-1, 1]): p = [x, y, z] - p[axis] = p[axis] + direction * d / 2 + p[axis] += direction * d / 2 self.assertEqual( 1, [ diff --git a/python/tests/rd_tests/test_sum.py b/python/tests/rd_tests/test_sum.py index ade663f10..4c93a129a 100644 --- a/python/tests/rd_tests/test_sum.py +++ b/python/tests/rd_tests/test_sum.py @@ -679,7 +679,7 @@ def test_resample_extrapolate(self): """ Test resampling of summary with extrapolate option of lower and upper boundaries enabled """ - from resdata.util.util import CTime, TimeVector + from resdata.util.util import CTime, TimeVector # noqa: PLC0415 time_points = TimeVector() From daa260a4ee649d22f81fb89f710c4954ee4537a6 Mon Sep 17 00:00:00 2001 From: larsevj Date: Thu, 29 Aug 2024 18:37:01 +0200 Subject: [PATCH 10/11] Use f-string --- python/docs/examples/avg_pressure.py | 2 +- python/resdata/__init__.py | 4 +- python/resdata/geometry/cpolyline.py | 4 +- .../resdata/geometry/cpolyline_collection.py | 3 +- python/resdata/geometry/geo_pointset.py | 6 +- python/resdata/geometry/geo_region.py | 3 +- python/resdata/geometry/polyline.py | 3 +- python/resdata/geometry/surface.py | 14 ++-- python/resdata/grid/cell.py | 9 +-- python/resdata/grid/faults/fault.py | 16 ++--- python/resdata/grid/faults/fault_block.py | 8 +-- .../resdata/grid/faults/fault_block_layer.py | 42 ++++++------ python/resdata/grid/faults/fault_line.py | 8 +-- python/resdata/grid/faults/fault_segments.py | 7 +- python/resdata/grid/faults/layer.py | 40 +++++------- python/resdata/grid/rd_grid.py | 64 +++++++------------ python/resdata/grid/rd_grid_generator.py | 16 ++--- python/resdata/grid/rd_region.py | 14 ++-- python/resdata/rd_type.py | 2 +- python/resdata/resfile/fortio.py | 2 +- python/resdata/resfile/rd_3dkw.py | 4 +- python/resdata/resfile/rd_file.py | 6 +- python/resdata/resfile/rd_file_view.py | 12 ++-- python/resdata/resfile/rd_init_file.py | 6 +- python/resdata/resfile/rd_kw.py | 10 ++- python/resdata/rft/rd_rft.py | 7 +- python/resdata/rft/well_trajectory.py | 2 +- python/resdata/summary/rd_sum.py | 2 +- .../resdata/summary/rd_sum_keyword_vector.py | 2 +- python/resdata/summary/rd_sum_node.py | 2 +- python/resdata/summary/rd_sum_vector.py | 8 +-- python/resdata/util/test/extended_testcase.py | 2 +- python/resdata/util/test/test_run.py | 2 +- python/resdata/util/util/bool_vector.py | 2 +- python/resdata/util/util/ctime.py | 2 +- .../resdata/util/util/permutation_vector.py | 4 +- python/resdata/util/util/rng.py | 2 +- python/resdata/util/util/stringlist.py | 10 +-- python/resdata/util/util/thread_pool.py | 3 +- python/resdata/util/util/vector_template.py | 14 ++-- python/resdata/util/util/version.py | 2 +- python/resdata/well/well_info.py | 6 +- python/resdata/well/well_segment.py | 6 +- python/resdata/well/well_state.py | 4 +- python/resdata/well/well_time_line.py | 6 +- python/tests/rd_tests/test_fault_blocks.py | 2 +- python/tests/rd_tests/test_grid.py | 2 +- python/tests/rd_tests/test_rd_kw.py | 4 +- 48 files changed, 159 insertions(+), 242 deletions(-) diff --git a/python/docs/examples/avg_pressure.py b/python/docs/examples/avg_pressure.py index c23ee4595..773bd347c 100755 --- a/python/docs/examples/avg_pressure.py +++ b/python/docs/examples/avg_pressure.py @@ -69,6 +69,6 @@ def avg_pressure(p, sw, pv, region, region_id, result): for key, value in result.items(): plt.figure(1) for index, p in enumerate(value): - plt.plot(sim_days, p, label="Region:%s P%d" % (key, index + 1)) + plt.plot(sim_days, p, label=f"Region:{key} P{index + 1}") plt.legend() plt.show() diff --git a/python/resdata/__init__.py b/python/resdata/__init__.py index 4f57dc4f2..e5cc0b518 100644 --- a/python/resdata/__init__.py +++ b/python/resdata/__init__.py @@ -46,8 +46,8 @@ def _dlopen_resdata(): - import ctypes - import platform + import ctypes # noqa: PLC0415 + import platform # noqa: PLC0415 path = os.path.join(os.path.dirname(__file__), ".libs") if platform.system() == "Linux": diff --git a/python/resdata/geometry/cpolyline.py b/python/resdata/geometry/cpolyline.py index 8eefbfb14..271044bad 100644 --- a/python/resdata/geometry/cpolyline.py +++ b/python/resdata/geometry/cpolyline.py @@ -85,9 +85,7 @@ def __getitem__(self, index): return (x.value, y.value) else: - raise IndexError( - "Invalid index:%d valid range: [0,%d)" % (index, len(self)) - ) + raise IndexError(f"Invalid index:{index} valid range: [0,{len(self)})") def segmentIntersects(self, p1, p2): return self._segment_intersects(p1[0], p1[1], p2[0], p2[1]) diff --git a/python/resdata/geometry/cpolyline_collection.py b/python/resdata/geometry/cpolyline_collection.py index a2310a5ca..9c0462b0f 100644 --- a/python/resdata/geometry/cpolyline_collection.py +++ b/python/resdata/geometry/cpolyline_collection.py @@ -2,7 +2,6 @@ Create a polygon """ - from cwrap import BaseCClass from resdata import ResdataPrototype from resdata.geometry import CPolyline @@ -61,7 +60,7 @@ def __getitem__(self, index): return self._iget(index).setParent(self) else: raise IndexError( - "Invalid index:%d - valid range: [0,%d)" % (index, len(self)) + f"Invalid index:{index} - valid range: [0,{len(self)})" ) elif isinstance(index, str): if index in self: diff --git a/python/resdata/geometry/geo_pointset.py b/python/resdata/geometry/geo_pointset.py index aa0fe8961..06d0b3152 100644 --- a/python/resdata/geometry/geo_pointset.py +++ b/python/resdata/geometry/geo_pointset.py @@ -37,9 +37,7 @@ def __getitem__(self, key): if 0 <= idx < size: return self._iget_z(idx) else: - raise IndexError( - "Invalid index, must be in [0, %d), was: %d." % (size, key) - ) + raise IndexError(f"Invalid index, must be in [0, {size}), was: {key}.") else: # TODO implement slicing? raise ValueError(f"Index must be int, not {type(key)}.") @@ -48,7 +46,7 @@ def __len__(self): return self._get_size() def __repr__(self): - return self._create_repr("len=%d" % len(self)) + return self._create_repr(f"len={len(self)}") def free(self): self._free() diff --git a/python/resdata/geometry/geo_region.py b/python/resdata/geometry/geo_region.py index d041545fc..d22003563 100644 --- a/python/resdata/geometry/geo_region.py +++ b/python/resdata/geometry/geo_region.py @@ -108,10 +108,9 @@ def __len__(self): return len(self._get_index_list()) def __repr__(self): - ls = len(self) il = repr(self.getActiveList()) pres = "preselected" if self._preselect else "not preselected" - return self._create_repr("size=%d, active_list=<%s>, %s" % (ls, il, pres)) + return self._create_repr(f"size={len(self)}, active_list=<{il}>, {pres}") def free(self): self._free() diff --git a/python/resdata/geometry/polyline.py b/python/resdata/geometry/polyline.py index 4c7a5eeab..94104ebfd 100644 --- a/python/resdata/geometry/polyline.py +++ b/python/resdata/geometry/polyline.py @@ -1,4 +1,3 @@ - from .geometry_tools import GeometryTools @@ -56,7 +55,7 @@ def __getitem__(self, index): if not 0 <= index < len(self): raise IndexError( - "Index:%d invalid must be in range: [0, %d]" % (index, (len(self) - 1)) + f"Index:{index} invalid must be in range: [0, {len(self) - 1}]" ) return self.__points[index] diff --git a/python/resdata/geometry/surface.py b/python/resdata/geometry/surface.py index 14d90bbc3..b62a2409e 100644 --- a/python/resdata/geometry/surface.py +++ b/python/resdata/geometry/surface.py @@ -192,9 +192,7 @@ def assign(self, value): def __setitem__(self, index, value): if isinstance(index, int): if index >= len(self): - raise IndexError( - "Invalid index:%d - valid range [0,%d)" % (index, len(self)) - ) + raise IndexError(f"Invalid index:{index} - valid range [0,{len(self)})") if index < 0: index += len(self) @@ -211,9 +209,7 @@ def __getitem__(self, index): if 0 <= idx < ls: return self._iget_zvalue(idx) else: - raise IndexError( - "Invalid index:%d - valid range [0,%d)" % (index, len(self)) - ) + raise IndexError(f"Invalid index:{index} - valid range [0,{len(self)})") else: raise TypeError(f"Invalid index type:{index} - must be integer") @@ -224,9 +220,7 @@ def getXY(self, index): if idx < 0: idx += len(self) if not 0 <= idx < len(self): - raise IndexError( - "Invalid index:%d - valid range [0,%d)" % (index, len(self)) - ) + raise IndexError(f"Invalid index:{index} - valid range [0,{len(self)})") index = idx else: raise TypeError(f"Invalid index type:{index} - must be integer") @@ -276,5 +270,5 @@ def free(self): self._free() def __repr__(self): - cnt = "nx=%d, ny=%d" % (self.getNX(), self.getNY()) + cnt = f"nx={self.getNX()}, ny={self.getNY()}" return self._create_repr(cnt) diff --git a/python/resdata/grid/cell.py b/python/resdata/grid/cell.py index f4d80c965..f1070c459 100644 --- a/python/resdata/grid/cell.py +++ b/python/resdata/grid/cell.py @@ -103,13 +103,8 @@ def corners(self): def __repr__(self): act = "active" if self.active else "inactive" pos = "({:.3f}, {:.3f}, {:.3f})".format(*self.coordinate) - cnt = "%d, %d, %d, %s, %s, grid=%s" % ( - self.i, - self.j, - self.k, - act, - pos, - self._grid.get_name(), + cnt = ( + f"{self.i}, {self.j}, {self.k}, {act}, {pos}, grid={self._grid.get_name()}" ) return f"Cell({cnt})" diff --git a/python/resdata/grid/faults/fault.py b/python/resdata/grid/faults/fault.py index eb2f3e9a0..b8b4cc466 100644 --- a/python/resdata/grid/faults/fault.py +++ b/python/resdata/grid/faults/fault.py @@ -208,19 +208,19 @@ def add_record(self, I1, I2, J1, J2, K1, K2, face): raise ValueError("Invalid K1 K2 indices") if I1 < 0 or self.nx <= I1: - raise ValueError("Invalid I1:%d" % I1) + raise ValueError(f"Invalid I1:{I1}") if I2 < 0 or self.nx <= I2: - raise ValueError("Invalid I2:%d" % I2) + raise ValueError(f"Invalid I2:{I2}") if J1 < 0 or self.ny <= J1: - raise ValueError("Invalid J1:%d" % J1) + raise ValueError(f"Invalid J1:{J1}") if J2 < 0 or self.ny <= J2: - raise ValueError("Invalid J2:%d" % J2) + raise ValueError(f"Invalid J2:{J2}") if K1 < 0 or self.nz <= K1: - raise ValueError("Invalid K1:%d" % K1) + raise ValueError(f"Invalid K1:{K1}") if K2 < 0 or self.nz <= K2: - raise ValueError("Invalid K2:%d" % K2) + raise ValueError(f"Invalid K2:{K2}") if face in ["X", "I"] and I1 != I2: raise ValueError(f"For face:{face} we must have I1 == I2") @@ -360,8 +360,8 @@ def extend_to_polyline(self, polyline, k): return extension raise ValueError( - "The fault %s can not be extended to intersect with polyline:%s in layer:%d" - % (self.getName(), polyline.getName(), k + 1) + f"The fault {self.get_name()} can not be extended to intersect with " + f"polyline:{polyline.get_name()} in layer:{k+1}" ) def intersects_polyline(self, polyline, k): diff --git a/python/resdata/grid/faults/fault_block.py b/python/resdata/grid/faults/fault_block.py index e8641bcab..9028a334a 100644 --- a/python/resdata/grid/faults/fault_block.py +++ b/python/resdata/grid/faults/fault_block.py @@ -18,7 +18,7 @@ def __init__(self, i, j, k, x, y, z): self.z = z def __str__(self): - return "(%d,%d)" % (self.i, self.j) + return f"({self.i}, {self.j})" class FaultBlock(BaseCClass): @@ -79,12 +79,12 @@ def __getitem__(self, index): i.value, j.value, k.value, x.value, y.value, z.value ) else: - raise IndexError("Index:%d out of range: [0,%d)" % (index, len(self))) + raise IndexError(f"Index:{index} out of range: [0,{len(self)})") else: - raise TypeError("Index:%s wrong type - integer expected") + raise TypeError(f"Index:{index !s} wrong type - integer expected") def __str__(self): - return "Block ID: %d" % self.getBlockID() + return f"Block ID: {self.get_block_id()}" def __len__(self): return self._get_size() diff --git a/python/resdata/grid/faults/fault_block_layer.py b/python/resdata/grid/faults/fault_block_layer.py index 77f7e319d..1701caff4 100644 --- a/python/resdata/grid/faults/fault_block_layer.py +++ b/python/resdata/grid/faults/fault_block_layer.py @@ -67,7 +67,7 @@ def __len__(self): return self._size() def __repr__(self): - return self._create_repr("size=%d, k=%d" % (len(self), self.get_k())) + return self._create_repr(f"size={len(self)}, k={self.get_k()}") def __getitem__(self, index): """ @@ -80,20 +80,18 @@ def __getitem__(self, index): if 0 <= index < len(self): return self._iget_block(index).setParent(self) else: - raise IndexError("Index:%d out of range: [0,%d)" % (index, len(self))) + raise IndexError(f"Index:{index} out of range: [0,{len(self)})") elif isinstance(index, tuple): i, j = index - if 0 <= i < self.grid_ref.getNX() and 0 <= j < self.grid_ref.getNY(): + if 0 <= i < self.grid_ref.get_nx() and 0 <= j < self.grid_ref.get_ny(): geo_layer = self.getGeoLayer() block_id = geo_layer[i, j] if block_id == 0: - raise ValueError( - "No fault block defined for location (%d,%d)" % (i, j) - ) + raise ValueError(f"No fault block defined for location ({i},{j})") else: return self.getBlock(block_id) else: - raise IndexError("Invalid i,j : (%d,%d)" % (i, j)) + raise IndexError(f"Invalid i,j : ({i},{j})") else: raise TypeError("Index should be integer type") @@ -107,12 +105,10 @@ def scan_keyword(self, fault_block_kw): ok = self._scan_keyword(fault_block_kw) if not ok: raise ValueError( - "The fault block keyword had wrong type/size: type:%s size:%d grid_size:%d" - % ( - fault_block_kw.type_name(), - len(fault_block_kw), - self.grid_ref.getGlobalSize(), - ) + "The fault block keyword had wrong type/size:" + f" type:{fault_block_kw.type_name()}" + f" size:{len(fault_block_kw)}" + f" grid_size:{self.grid_ref.get_global_size()}" ) def load_keyword(self, fault_block_kw): @@ -122,12 +118,10 @@ def load_keyword(self, fault_block_kw): ok = self._load_keyword(fault_block_kw) if not ok: raise ValueError( - "The fault block keyword had wrong type/size: type:%s size:%d grid_size:%d" - % ( - fault_block_kw.type_name(), - len(fault_block_kw), - self.grid_ref.getGlobalSize(), - ) + "The fault block keyword had wrong type/size:" + f" type:{fault_block_kw.type_name()}" + f" size:{len(fault_block_kw)}" + f" grid_size:{self.grid_ref.get_global_size()}" ) def get_block(self, block_id): @@ -137,13 +131,13 @@ def get_block(self, block_id): if block_id in self: return self._get_block(block_id).setParent(self) else: - raise KeyError("No blocks with ID:%d in this layer" % block_id) + raise KeyError(f"No blocks with ID:{block_id} in this layer") def delete_block(self, block_id): if block_id in self: self._del_block(block_id) else: - raise KeyError("No blocks with ID:%d in this layer" % block_id) + raise KeyError(f"No blocks with ID:{block_id} in this layer") def add_block(self, block_id=None): if block_id is None: @@ -209,14 +203,14 @@ def add_polyline_barrier(self, polyline): p0 = polyline[0] c0 = self.grid_ref.findCellCornerXY(p0[0], p0[1], self.getK()) i, j = self.grid_ref.findCellXY(p0[0], p0[1], self.getK()) - print("%g,%g -> %d,%d %d" % (p0[0], p0[1], i, j, c0)) + print(f"{p0[0]:g},{p0[1]:g} -> {i},{j} {c0}") for index in range(1, len(polyline)): p1 = polyline[index] c1 = self.grid_ref.findCellCornerXY(p1[0], p1[1], self.getK()) i, j = self.grid_ref.findCellXY(p1[0], p1[1], self.getK()) layer.addInterpBarrier(c0, c1) - print("%g,%g -> %d,%d %d" % (p1[0], p1[1], i, j, c1)) - print("Adding barrier %d -> %d" % (c0, c1)) + print(f"{p1[0]:g},{p1[1]:g} -> {i},{j} {c1}") + print(f"Adding barrier {c0} -> {c1}") c0 = c1 def get_geo_layer(self): diff --git a/python/resdata/grid/faults/fault_line.py b/python/resdata/grid/faults/fault_line.py index 80f468285..adafed951 100644 --- a/python/resdata/grid/faults/fault_line.py +++ b/python/resdata/grid/faults/fault_line.py @@ -31,11 +31,10 @@ def verify(self): for next_segment in self.__segment_list[1:]: if current.getC2() != next_segment.getC1(): sys.stdout.write( - "Current: %d ---- %d \n" % (current.getC1(), current.getC2()) + f"Current: {current.getC1()} ---- {current.getC2()} \n" ) sys.stdout.write( - "Next : %d ---- %d \n" - % (next_segment.getC1(), next_segment.getC2()) + f"Next : {next_segment.getC1()} ---- {next_segment.getC2()} \n" ) assert current.getC2() == next_segment.getC1() current = next_segment @@ -200,8 +199,7 @@ def dump(self): (J1, I1) = divmod(C1, self.__grid.get_nx() + 1) (J2, I2) = divmod(C2, self.__grid.get_nx() + 1) print( - "[Corner:%5d IJ:(%3d,%d)] -> [Corner:%5d IJ:(%3d,%d)]" - % (C1, I1, J1, C2, I2, J2) + f"[Corner:{C1:5d} IJ:({I1:3d},{J1:d})] -> [Corner:{C2:5d} IJ:({I2:3d},{J2:d})]" ) diff --git a/python/resdata/grid/faults/fault_segments.py b/python/resdata/grid/faults/fault_segments.py index 24ca47441..16eda80db 100644 --- a/python/resdata/grid/faults/fault_segments.py +++ b/python/resdata/grid/faults/fault_segments.py @@ -48,7 +48,7 @@ def swap(self): self.__C2 = C1 def __repr__(self): - return "%d -> %d" % (self.__C1, self.__C2) + return f"{self.__C1} -> {self.__C2}" class SegmentMap: @@ -67,10 +67,7 @@ def verify(self): if count > 0: d = self.__segment_map[C] if len(d) != count: - print( - "CornerPoint:%d count:%d len(d):%d map:%s" - % (C, count, len(d), d) - ) + print(f"CornerPoint:{C} count:{count} len(d):{len(d)} map:{d}") assert len(d) == count else: assert self.__segment_map.get(C) is None diff --git a/python/resdata/grid/faults/layer.py b/python/resdata/grid/faults/layer.py index 0313258f3..2f28696cb 100644 --- a/python/resdata/grid/faults/layer.py +++ b/python/resdata/grid/faults/layer.py @@ -78,20 +78,18 @@ def active_cell(self, i, j): return self._active_cell(i, j) def update_active(self, grid, k): - if grid.getNX() != self.getNX(): + if grid.get_nx() != self.get_nx(): raise ValueError( - "NX dimension mismatch. Grid:%d layer:%d" - % (grid.getNX(), self.getNX()) + f"NX dimension mismatch. Grid:{grid.get_nx()} layer:{self.get_nx()}" ) - if grid.getNY() != self.getNY(): + if grid.get_ny() != self.get_ny(): raise ValueError( - "NY dimension mismatch. Grid:%d layer:%d" - % (grid.getNY(), self.getNY()) + f"NY dimension mismatch. Grid:{grid.get_ny()} layer:{self.get_ny()}" ) - if k >= grid.getNZ(): - raise ValueError("K value invalid: Grid range [0,%d)" % grid.getNZ()) + if k >= grid.get_nz(): + raise ValueError(f"K value invalid: Grid range [0,{grid.get_nz()})") self._update_active(grid, k) @@ -128,17 +126,17 @@ def cell_contact(self, p1, p2): i1, j1 = p1 i2, j2 = p2 - if not 0 <= i1 < self.getNX(): - raise IndexError("Invalid i1:%d" % i1) + if not 0 <= i1 < self.get_nx(): + raise IndexError(f"Invalid i1:{i1}") - if not 0 <= i2 < self.getNX(): - raise IndexError("Invalid i2:%d" % i2) + if not 0 <= i2 < self.get_nx(): + raise IndexError(f"Invalid i2:{i2}") - if not 0 <= j1 < self.getNY(): - raise IndexError("Invalid i1:%d" % j1) + if not 0 <= j1 < self.get_ny(): + raise IndexError(f"Invalid j1:{j1}") - if not 0 <= j2 < self.getNY(): - raise IndexError("Invalid i2:%d" % j2) + if not 0 <= j2 < self.get_ny(): + raise IndexError(f"Invalid j2:{j2}") return self._cell_contact(i1, j1, i2, j2) @@ -184,14 +182,10 @@ def add_ij_barrier(self, ij_list): i2, j2 = p2 if i1 == i2 or j1 == j2: if not 0 <= i2 <= nx: - raise ValueError( - "i value:%d invalid. Valid range: [0,%d] " % (i1, i2) - ) + raise ValueError(f"i value:{i1} invalid. Valid range: [0,{i2}] ") if not 0 <= j2 <= ny: - raise ValueError( - "i value:%d invalid. Valid range: [0,%d] " % (j1, j2) - ) + raise ValueError(f"i value:{j1} invalid. Valid range: [0,{j2}] ") self._add_ijbarrier(i1, j1, i2, j2) p1 = p2 @@ -227,7 +221,7 @@ def update_connected(self, ij, new_value, org_value=None): if self[ij] == org_value: self._update_connected(ij[0], ij[1], org_value, new_value) else: - raise ValueError("Cell %s is not equal to %d \n" % (ij, org_value)) + raise ValueError(f"Cell {ij} is not equal to {org_value} \n") def cells_equal(self, value): """ diff --git a/python/resdata/grid/rd_grid.py b/python/resdata/grid/rd_grid.py index 5c9112942..d4b55f6ad 100644 --- a/python/resdata/grid/rd_grid.py +++ b/python/resdata/grid/rd_grid.py @@ -295,8 +295,7 @@ def create_rectangular(cls, dims, dV, actnum=None): if not len(actnum) == dims[0] * dims[1] * dims[2]: raise ValueError( - "ACTNUM size mismatch: len(ACTNUM):%d Expected:%d" - % (len(actnum), dims[0] * dims[1] * dims[2]) + f"ACTNUM size mismatch: len(ACTNUM):{len(actnum)} Expected:{dims[0] * dims[1] * dims[2]}" ) rd_grid = cls._alloc_rectangular( dims[0], dims[1], dims[2], dV[0], dV[1], dV[2], actnum.getDataPtr() @@ -336,11 +335,11 @@ def __repr__(self): name = self._nicename() if name: name = f'"{name}", ' - g_size = self.getGlobalSize() - a_size = self.getNumActive() - xyz_s = "%dx%dx%d" % (self.getNX(), self.getNY(), self.getNZ()) + g_size = self.get_global_size() + a_size = self.get_num_active() + xyz_s = f"{self.get_nx()}x{self.get_ny()}x{self.get_nz()}" return self._create_repr( - "%s%s, global_size=%d, active_size=%d" % (name, xyz_s, g_size, a_size) + f"{name}{xyz_s}, global_size={g_size}, active_size={a_size}" ) def __len__(self): @@ -459,7 +458,7 @@ def get_bounding_box_2d(self, layer=0, lower_left=None, upper_right=None): return (p0, p1, p2, p3) else: raise ValueError( - "Invalid layer value:%d Valid range: [0,%d]" % (layer, self.getNZ()) + f"Invalid layer value:{layer} Valid range: [0,{self.get_nz()}]" ) def get_name(self): @@ -544,19 +543,18 @@ def __global_index(self, active_index=None, global_index=None, ijk=None): i, j, k = ijk if not 0 <= i < nx: - raise IndexError("Invalid value i:%d Range: [%d,%d)" % (i, 0, nx)) + raise IndexError(f"Invalid value i:{i} Range: [0,{nx})") if not 0 <= j < ny: - raise IndexError("Invalid value j:%d Range: [%d,%d)" % (j, 0, ny)) + raise IndexError(f"Invalid value j:{j} Range: [0,{ny})") if not 0 <= k < nz: - raise IndexError("Invalid value k:%d Range: [%d,%d)" % (k, 0, nz)) + raise IndexError(f"Invalid value k:{k} Range: [0,{nz})") global_index = self._get_global_index3(i, j, k) elif not 0 <= global_index < self.get_global_size(): raise IndexError( - "Invalid value global_index:%d Range: [%d,%d)" - % (global_index, 0, self.getGlobalSize()) + f"Invalid value global_index:{global_index} Range: [0,{self.get_global_size()})" ) return global_index @@ -722,20 +720,14 @@ def get_node_pos(self, i, j, k): p3 = grid.getNodePos(grid.get_nx(), grid.get_ny(), 0) """ - if not 0 <= i <= self.getNX(): - raise IndexError( - "Invalid I value:%d - valid range: [0,%d]" % (i, self.getNX()) - ) + if not 0 <= i <= self.get_nx(): + raise IndexError(f"Invalid I value:{i} - valid range: [0,{self.get_nx()}]") - if not 0 <= j <= self.getNY(): - raise IndexError( - "Invalid J value:%d - valid range: [0,%d]" % (j, self.getNY()) - ) + if not 0 <= j <= self.get_ny(): + raise IndexError(f"Invalid J value:{j} - valid range: [0,{self.get_ny()}]") - if not 0 <= k <= self.getNZ(): - raise IndexError( - "Invalid K value:%d - valid range: [0,%d]" % (k, self.getNZ()) - ) + if not 0 <= k <= self.get_nz(): + raise IndexError(f"Invalid K value:{k} - valid range: [0,{self.get_nz()}]") x = ctypes.c_double() y = ctypes.c_double() @@ -793,9 +785,9 @@ def get_node_xyz(self, i, j, k): corner += 4 if self._ijk_valid(i, j, k): - return self.getCellCorner(corner, global_index=i + j * nx + k * nx * ny) + return self.get_cell_corner(corner, global_index=i + j * nx + k * nx * ny) else: - raise IndexError("Invalid coordinates: (%d,%d,%d) " % (i, j, k)) + raise IndexError(f"Invalid coordinates: ({i}, {j}, {k}) ") def get_layer_xyz(self, xy_corner, layer): nx = self.getNX() @@ -846,7 +838,7 @@ def top_active(self, i, j): a_idx = self.get_active_index(ijk=(i, j, k)) if a_idx >= 0: return self._get_top1A(a_idx) - raise ValueError("No active cell in column (%d,%d)" % (i, j)) + raise ValueError(f"No active cell in column ({i}, {j})") def bottom(self, i, j): """ @@ -926,10 +918,10 @@ def find_cell_xy(self, x, y, k): return (i.value, j.value) else: raise ValueError( - "Could not find the point:(%g,%g) in layer:%d" % (x, y, k) + f"Could not find the point:({x :g}, {y :g}) in layer:{k}" ) else: - raise IndexError("Invalid layer value:%d" % k) + raise IndexError(f"Invalid layer value:{k}") def find_cell_corner_xy(self, x, y, k): """Will find the corner nr of corner closest to utm coordinates x,y. @@ -1278,13 +1270,7 @@ def write_grdecl(self, rd_kw, pyfile, special_header=None, default_value=0): self._fwrite_grdecl(rd_kw, special_header, cfile, default_value) else: raise ValueError( - "Keyword: %s has invalid size(%d), must be either nactive:%d or nx*ny*nz:%d" - % ( - rd_kw.getName(), - len(rd_kw), - self.getNumActive(), - self.getGlobalSize(), - ) + f"Keyword: {rd_kw.get_name()} has invalid size({len(rd_kw)}), must be either nactive:{self.get_num_active()} or nx*ny*nz:{self.get_global_size()}" ) def exportACTNUM(self): @@ -1301,8 +1287,7 @@ def compressed_kw_copy(self, kw): return kw_copy else: raise ValueError( - "The input keyword must have nx*n*nz or nactive elements. Size:%d invalid" - % len(kw) + f"The input keyword must have nx*n*nz or nactive elements. Size:{len(kw)} invalid" ) def global_kw_copy(self, kw, default_value): @@ -1315,8 +1300,7 @@ def global_kw_copy(self, kw, default_value): return kw_copy else: raise ValueError( - "The input keyword must have nx*n*nz or nactive elements. Size:%d invalid" - % len(kw) + f"The input keyword must have nx*n*nz or nactive elements. Size:{len(kw)} invalid" ) def export_ACTNUM_kw(self): diff --git a/python/resdata/grid/rd_grid_generator.py b/python/resdata/grid/rd_grid_generator.py index a46126aa2..b83525408 100644 --- a/python/resdata/grid/rd_grid_generator.py +++ b/python/resdata/grid/rd_grid_generator.py @@ -76,8 +76,7 @@ def create_rectangular(cls, dims, dV, actnum=None): if not len(actnum) == dims[0] * dims[1] * dims[2]: raise ValueError( - "ACTNUM size mismatch: len(ACTNUM):%d Expected:%d" - % (len(actnum), dims[0] * dims[1] * dims[2]) + f"ACTNUM size mismatch: len(ACTNUM):{len(actnum)} Expected:{dims[0] * dims[1] * dims[2]}" ) rd_grid = cls._alloc_rectangular( @@ -371,7 +370,7 @@ def assert_zcorn(cls, nx, ny, nz, zcorn, twisted_check=True): if len(zcorn) != 8 * nx * ny * nz: raise AssertionError( - "Expected len(zcorn) to be %d, was %d" % (8 * nx * ny * nz, len(zcorn)) + f"Expected len(zcorn) to be {8 * nx * ny * nz}, was {len(zcorn)}" ) plane_size = 4 * nx * ny @@ -459,8 +458,7 @@ def assert_coord(cls, nx, ny, nz, coord, negative_values=False): if len(coord) != 6 * (nx + 1) * (ny + 1): raise AssertionError( - "Expected len(coord) to be %d, was %d" - % (6 * (nx + 1) * (ny + 1), len(coord)) + f"Expected len(coord) to be {6 * (nx + 1) * (ny + 1)}, was {len(coord)}" ) if not negative_values and min(coord) < 0: @@ -488,8 +486,7 @@ def assert_actnum(cls, nx, ny, nz, actnum): if len(actnum) != nx * ny * nz: raise AssertionError( - "Expected the length of ACTNUM to be %d, was %s." - % (nx * ny * nz, len(actnum)) + f"Expected the length of ACTNUM to be {nx * ny* nz}, was {len(actnum)}." ) if set(actnum) - {0, 1}: @@ -718,7 +715,7 @@ def assert_ijk_bounds(cls, dims, ijk_bounds): if len(ijk_bounds) != 3: raise ValueError( "Expected ijk_bounds to contain three intervals, " - + "contained only %d" % len(ijk_bounds) + + f"contained only {len(ijk_bounds)}" ) for n, bound in zip(dims, ijk_bounds): @@ -737,7 +734,8 @@ def assert_ijk_bounds(cls, dims, ijk_bounds): raise ValueError( "Expected bounds to have the following format: " + "0 <= lower bound <= upper_bound < ni, " - + "was %d <=? %d <=? %d = grid.getNZ(): + if k < 0 or k >= grid.get_nz(): raise ValueError( - "Invalid k value:%d - must be in range [0,%d)" % (k, grid.getNZ()) + f"Invalid k value:{k} - must be in range [0,{grid.get_nz()})" ) - if grid.getNX() != layer.getNX(): + if grid.get_nx() != layer.get_nx(): raise ValueError( - "NX dimension mismatch. Grid:%d layer:%d" - % (grid.getNX(), layer.getNX()) + f"NX dimension mismatch. Grid:{grid.get_nx()} layer:{layer.get_nx()}" ) - if grid.getNY() != layer.getNY(): + if grid.get_ny() != layer.get_ny(): raise ValueError( - "NY dimension mismatch. Grid:%d layer:%d" - % (grid.getNY(), layer.getNY()) + f"NY dimension mismatch. Grid:{grid.get_ny()} layer:{layer.get_ny()}" ) self._select_from_layer(layer, k, value) diff --git a/python/resdata/rd_type.py b/python/resdata/rd_type.py index 6b79197e6..87f264d96 100644 --- a/python/resdata/rd_type.py +++ b/python/resdata/rd_type.py @@ -87,7 +87,7 @@ def _assert_valid_arguments(self, type_enum, element_size, type_name): if not (0 <= element_size <= 999): raise ValueError( "Expected element_size to be in the range " - + "[0, 999], was: %d" % element_size + + f"[0, 999], was: {element_size}" ) @property diff --git a/python/resdata/resfile/fortio.py b/python/resdata/resfile/fortio.py index 5fcfebbf6..eb41eb2ca 100644 --- a/python/resdata/resfile/fortio.py +++ b/python/resdata/resfile/fortio.py @@ -109,7 +109,7 @@ def __init__( elif mode == FortIO.APPEND_MODE: c_pointer = self._open_append(file_name, fmt_file, endian_flip_header) else: - raise UserWarning("Unknown mode: %d" % mode) + raise UserWarning(f"Unknown mode: {mode}") self.__mode = mode if not c_pointer: diff --git a/python/resdata/resfile/rd_3dkw.py b/python/resdata/resfile/rd_3dkw.py index 8f3b1bbf4..d622aa482 100644 --- a/python/resdata/resfile/rd_3dkw.py +++ b/python/resdata/resfile/rd_3dkw.py @@ -114,9 +114,7 @@ def __setitem__(self, index, value): if self.global_active: index = global_index elif not self.grid.active(global_index=global_index): - raise ValueError( - "Tried to assign value to inactive cell: (%d,%d,%d)" % index - ) + raise ValueError(f"Tried to assign value to inactive cell: {index}") else: index = self.grid.get_active_index(ijk=index) diff --git a/python/resdata/resfile/rd_file.py b/python/resdata/resfile/rd_file.py index 1090509f8..414274bb0 100644 --- a/python/resdata/resfile/rd_file.py +++ b/python/resdata/resfile/rd_file.py @@ -237,9 +237,7 @@ def block_view(self, kw, kw_index): idx += ls if 0 <= idx < ls: return self.global_view.blockView(kw, idx) - raise IndexError( - "Index out of range, must be in [0, %d), was %d." % (ls, kw_index) - ) + raise IndexError(f"Index out of range, must be in [0, {ls}), was {kw_index}.") def block_view2(self, start_kw, stop_kw, start_index): return self.global_view.blockView2(start_kw, stop_kw, start_index) @@ -286,7 +284,7 @@ def __getitem__(self, index): if 0 <= idx < ls: return self.global_view[idx] else: - raise IndexError("Index must be in [0, %d), was: %d." % (ls, index)) + raise IndexError(f"Index must be in [0, {ls}), was: {index}.") return self.global_view[index] def iget_kw(self, index, copy=False): diff --git a/python/resdata/resfile/rd_file_view.py b/python/resdata/resfile/rd_file_view.py index f7fc47f8f..d32d18484 100644 --- a/python/resdata/resfile/rd_file_view.py +++ b/python/resdata/resfile/rd_file_view.py @@ -40,14 +40,14 @@ def __iget(self, index): return self._iget_kw(index).setParent(parent=self) def __repr__(self): - return "ResdataFileView(size=%d) %s" % (len(self), self._ad_str()) + return f"ResdataFileView(size={len(self)}) {self._ad_str()}" def iget_named_kw(self, kw_name, index): if not kw_name in self: raise KeyError(f"No such keyword: {kw_name}") if index >= self.numKeywords(kw_name): - raise IndexError("Too large index: %d" % index) + raise IndexError(f"Too large index: {index}") return self._iget_named_kw(kw_name, index).setParent(parent=self) @@ -87,7 +87,7 @@ def __getitem__(self, index): if 0 <= idx < ls: return self.__iget(idx) else: - raise IndexError("Index must be in [0, %d), was: %d." % (ls, index)) + raise IndexError(f"Index must be in [0, {ls}), was: {index}.") if isinstance(index, slice): indices = index.indices(len(self)) @@ -135,9 +135,7 @@ def block_view2(self, start_kw, stop_kw, start_index): if idx < 0: idx += ls if not (0 <= idx < ls): - raise IndexError( - "Index must be in [0, %d), was: %d." % (ls, start_index) - ) + raise IndexError(f"Index must be in [0, {ls}), was: {start_index}.") if stop_kw and not stop_kw in self: raise KeyError(f"The keyword:{stop_kw} is not in file") @@ -157,7 +155,7 @@ def block_view(self, kw, kw_index): idx += num if not (0 <= idx < num): - raise IndexError("Index must be in [0, %d), was: %d." % (num, kw_index)) + raise IndexError(f"Index must be in [0, {num}), was: {kw_index}.") view = self._create_block_view(kw, kw_index) view.setParent(parent=self) diff --git a/python/resdata/resfile/rd_init_file.py b/python/resdata/resfile/rd_init_file.py index a8c1dd840..601a5ee3c 100644 --- a/python/resdata/resfile/rd_init_file.py +++ b/python/resdata/resfile/rd_init_file.py @@ -8,6 +8,8 @@ def __init__(self, grid, filename, flags=FileMode.DEFAULT): if file_type == FileType.INIT: super().__init__(grid, filename, flags) else: - err = 'The input filename "%s" does not correspond to an init file.' + err = ( + f'The input filename "{filename}" does not correspond to an init file.' + ) err += " Please follow the Eclipse naming conventions." - raise ValueError(err % filename) + raise ValueError(err) diff --git a/python/resdata/resfile/rd_kw.py b/python/resdata/resfile/rd_kw.py index 796a17908..2fa54369f 100644 --- a/python/resdata/resfile/rd_kw.py +++ b/python/resdata/resfile/rd_kw.py @@ -454,12 +454,10 @@ def sub_copy(self, offset, count, new_header=None): method will raise IndexError. """ if offset < 0 or offset >= len(self): - raise IndexError( - "Offset:%d invalid - valid range:[0,%d)" % (offset, len(self)) - ) + raise IndexError(f"Offset:{offset} invalid - valid range:[0,{len(self)})") if offset + count > len(self): - raise IndexError("Invalid value of (offset + count):%d" % (offset + count)) + raise IndexError(f"Invalid value of (offset + count):{offset + count}") return self._sub_copy(new_header, offset, count) @@ -1031,7 +1029,7 @@ def str(self, width=5, max_lines=10, fmt=None): the elements. The implementation of the builtin method __str__() is based on this method. """ - s = "%-8s %8d %-4s\n" % (self.get_name(), len(self), self.type_name()) + s = f"{self.get_name():-8s} {len(self):8d} {self.type_name():-4s}\n" lines = len(self) // width if not fmt: fmt = self.str_fmt + " " @@ -1179,7 +1177,7 @@ def first_different( raise ValueError("Keywords must have equal size") if offset >= len(self): - raise IndexError("Offset:%d invalid - size:%d" % (offset, len(self))) + raise IndexError(f"Offset:{offset} invalid - size:{len(self)}") if self.data_type != other.data_type: raise TypeError("The two keywords have different type") diff --git a/python/resdata/rft/rd_rft.py b/python/resdata/rft/rd_rft.py index 1372bc447..349bb0ce0 100644 --- a/python/resdata/rft/rd_rft.py +++ b/python/resdata/rft/rd_rft.py @@ -66,7 +66,7 @@ def free(self): def __repr__(self): rs = [] - rs.append("completed_cells = %d" % len(self)) + rs.append(f"completed_cells = {len(self)}") rs.append(f"date = {self.getDate()}") if self.is_RFT(): rs.append("RFT") @@ -218,7 +218,7 @@ def __getitem__(self, index): return rft else: raise IndexError( - "Index '%d' must be in range: [0, %d]" % (index, len(self) - 1) + f"Index '{index}' must be in range: [0, {len(self) - 1}]" ) else: raise TypeError("Index must be integer type") @@ -282,8 +282,7 @@ def free(self): self._free() def __repr__(self): - w = len(self) - return self._create_repr("wells = %d" % w) + return self._create_repr(f"wells = {len(self)}") monkey_the_camel(ResdataRFT, "getWellName", ResdataRFT.get_well_name) diff --git a/python/resdata/rft/well_trajectory.py b/python/resdata/rft/well_trajectory.py index 9eb0dae48..eda04d63c 100644 --- a/python/resdata/rft/well_trajectory.py +++ b/python/resdata/rft/well_trajectory.py @@ -62,7 +62,7 @@ def __getitem__(self, index): return self._points[index] def __repr__(self): - return "WellTrajectory(len=%d)" % len(self) + return f"WellTrajectory(len={len(self)})" def __str__(self): return f"WellTrajectory({str(self._points)})" diff --git a/python/resdata/summary/rd_sum.py b/python/resdata/summary/rd_sum.py index 5a1e22991..a75ebaf64 100644 --- a/python/resdata/summary/rd_sum.py +++ b/python/resdata/summary/rd_sum.py @@ -1633,7 +1633,7 @@ def __repr__(self): s_time = self.getStartTime() e_time = self.getEndTime() num_keys = len(self.keys()) - content = 'name="%s", time=[%s, %s], keys=%d' % (name, s_time, e_time, num_keys) + content = f'name="{name}", time=[{s_time}, {e_time}], keys={num_keys}' return self._create_repr(content) def dump_csv_line(self, time, keywords, pfile): diff --git a/python/resdata/summary/rd_sum_keyword_vector.py b/python/resdata/summary/rd_sum_keyword_vector.py index e249ac383..e936b3a12 100644 --- a/python/resdata/summary/rd_sum_keyword_vector.py +++ b/python/resdata/summary/rd_sum_keyword_vector.py @@ -50,7 +50,7 @@ def add_keywords(self, keyword_pattern): self._add_multiple(keyword_pattern) def __repr__(self): - return self._create_repr("len=%d" % len(self)) + return self._create_repr(f"len={len(self)}") def copy(self, rd_sum): return self._alloc_copy(rd_sum) diff --git a/python/resdata/summary/rd_sum_node.py b/python/resdata/summary/rd_sum_node.py index c4a0417d0..6e74b9db9 100644 --- a/python/resdata/summary/rd_sum_node.py +++ b/python/resdata/summary/rd_sum_node.py @@ -22,4 +22,4 @@ def __init__(self, report_step, days, date, mpl_date, value): self.mpl_date = mpl_date def __repr__(self): - return "SummaryNode(days=%d, value=%g)" % (self.days, self.value) + return f"SummaryNode(days={self.days}, value={self.value :g})" diff --git a/python/resdata/summary/rd_sum_vector.py b/python/resdata/summary/rd_sum_vector.py index 5560668e9..89317b22c 100644 --- a/python/resdata/summary/rd_sum_vector.py +++ b/python/resdata/summary/rd_sum_vector.py @@ -42,10 +42,8 @@ def __str__(self): return f"" def __repr__(self): - return "SummaryVector(key = %s, size = %d, unit = %s)" % ( - self.key, - len(self), - self.unit, + return ( + f"SummaryVector(key = {self.key}, size = {len(self)}, unit = {self.unit})" ) @property @@ -157,7 +155,7 @@ def __getitem__(self, index): if index < 0: index += len(vals) if index < 0 or index > length: - raise KeyError("Invalid index:%d out of range [0:%d)" % (index, length)) + raise KeyError(f"Invalid index:{index} out of range [0:{length})") else: return self.__iget(index) elif isinstance(index, slice): diff --git a/python/resdata/util/test/extended_testcase.py b/python/resdata/util/test/extended_testcase.py index f18ba21d4..041f45676 100644 --- a/python/resdata/util/test/extended_testcase.py +++ b/python/resdata/util/test/extended_testcase.py @@ -136,7 +136,7 @@ def assertEnumIsFullyDefined( for identifier, value in enum_values: if verbose: - print("%s = %d" % (identifier, value)) + print(f"{identifier} = {value}") self.assertTrue( identifier in enum_class.__dict__, diff --git a/python/resdata/util/test/test_run.py b/python/resdata/util/test/test_run.py index c5a299926..dbcced743 100644 --- a/python/resdata/util/test/test_run.py +++ b/python/resdata/util/test/test_run.py @@ -35,7 +35,7 @@ def __init__(self, config_file, args=[], name=None): # noqa: B006 self.name = self.name[1:] else: break - self.name += "/%08d" % random.randint(0, 100000000) + self.name += f"/{random.randint(0, 100000000):08d}" else: raise OSError(f"No such config file: {config_file}") diff --git a/python/resdata/util/util/bool_vector.py b/python/resdata/util/util/bool_vector.py index de8fdd270..fff67cec8 100644 --- a/python/resdata/util/util/bool_vector.py +++ b/python/resdata/util/util/bool_vector.py @@ -168,7 +168,7 @@ def __repr__(self): cnt = self._tostr(a) cnt += "..." cnt += self._tostr(b) - return 'BoolVector(size = %d, content = "%s") %s' % (ls, cnt, self._ad_str()) + return f'BoolVector(size = {ls}, content = "{cnt}") {self._ad_str()}' @classmethod def create_linear(cls, start_value, end_value, num_values): diff --git a/python/resdata/util/util/ctime.py b/python/resdata/util/util/ctime.py index 10116f87d..8c3546cce 100644 --- a/python/resdata/util/util/ctime.py +++ b/python/resdata/util/util/ctime.py @@ -128,7 +128,7 @@ def timetuple(self): pass def __repr__(self): - return "time_t value: %d [%s]" % (self.value(), str(self)) + return f"time_t value: {self.value()} [{self}]" @property def stripped(self): diff --git a/python/resdata/util/util/permutation_vector.py b/python/resdata/util/util/permutation_vector.py index 0a5bea8b5..fc54b1f4b 100644 --- a/python/resdata/util/util/permutation_vector.py +++ b/python/resdata/util/util/permutation_vector.py @@ -17,7 +17,7 @@ def __len__(self): def __str__(self): s = "(" for index in self: - s += " %d" % index + s += f" {index}" return s + ")" def __getitem__(self, index): @@ -27,7 +27,7 @@ def __getitem__(self, index): if 0 <= index < len(self): return self._iget(index) else: - raise IndexError("Invalid index:%d" % index) + raise IndexError(f"Invalid index:{index}") def free(self): self._free() diff --git a/python/resdata/util/util/rng.py b/python/resdata/util/util/rng.py index 635c54597..0e1d89680 100644 --- a/python/resdata/util/util/rng.py +++ b/python/resdata/util/util/rng.py @@ -37,7 +37,7 @@ def setState(self, seed_string): state_size = self.stateSize() if len(seed_string) < state_size: raise ValueError( - "The seed string must be at least %d characters long" % self.stateSize() + f"The seed string must be at least {self.stateSize()} characters long" ) self._set_state(seed_string) diff --git a/python/resdata/util/util/stringlist.py b/python/resdata/util/util/stringlist.py index 38cf8810e..17cd1c396 100644 --- a/python/resdata/util/util/stringlist.py +++ b/python/resdata/util/util/stringlist.py @@ -100,9 +100,7 @@ def __setitem__(self, index, value): index = len(self) + index if index < 0 or index >= length: - raise IndexError( - "index must be in range %d <= %d < %d" % (0, index, len(self)) - ) + raise IndexError(f"index must be in range 0 <= {index} < {len(self)}") if isinstance(value, bytes): value = value.decode("ascii") if isinstance(value, str): @@ -122,9 +120,7 @@ def __getitem__(self, index): if index < 0: index += length if index < 0 or index >= length: - raise IndexError( - "index must be in range %d <= %d < %d" % (0, index, len(self)) - ) + raise IndexError(f"index must be in range 0 <= {index} < {len(self)}") else: return self._iget(index) else: @@ -197,7 +193,7 @@ def __str__(self): return buffer def __repr__(self): - return "StringList(size = %d) %s" % (len(self), self._ad_str()) + return f"StringList(size = {len(self)}) {self._ad_str()}" def empty(self): """Returns true if and only if list is empty.""" diff --git a/python/resdata/util/util/thread_pool.py b/python/resdata/util/util/thread_pool.py index 7c45ad548..e2b3c42e5 100644 --- a/python/resdata/util/util/thread_pool.py +++ b/python/resdata/util/util/thread_pool.py @@ -134,8 +134,7 @@ def join(self): if self.__verbose: running_time = time.time() - self.__start_time print( - "Running time: %f using a pool size of: %d" - % (running_time, self.poolSize()) + f"Running time: {running_time :f} using a pool size of: {self.poolSize()}" ) def hasFailedTasks(self): diff --git a/python/resdata/util/util/vector_template.py b/python/resdata/util/util/vector_template.py index 07e1e2a29..40cdcfa3e 100644 --- a/python/resdata/util/util/vector_template.py +++ b/python/resdata/util/util/vector_template.py @@ -101,7 +101,7 @@ def __ilshift__(self, shift): if shift < 0: raise ValueError("The shift must be positive") if shift > len(self): - raise ValueError("The shift is too large %d > %d" % (shift, len(self))) + raise ValueError(f"The shift is too large {len(self)} < {shift}") self._lshift(shift) return self @@ -205,9 +205,7 @@ def __getitem__(self, index): if 0 <= idx < length: return self._iget(idx) else: - raise IndexError( - "Index must be in range %d <= %d < %d." % (0, index, length) - ) + raise IndexError(f"Index must be in range 0 <= {index} < {length}.") elif isinstance(index, slice): return self.strided_copy(index) else: @@ -258,8 +256,7 @@ def __IADD(self, delta, add): self._inplace_add(delta) else: raise ValueError( - "Incompatible sizes for add self:%d other:%d" - % (len(self), len(delta)) + f"Incompatible sizes for add self:{len(self)} other:{len(delta)}" ) elif isinstance(delta, (int, float)): if not add: @@ -329,8 +326,7 @@ def __imul__(self, factor): self._inplace_mul(factor) else: raise ValueError( - "Incompatible sizes for mul self:%d other:%d" - % (len(self), len(factor)) + f"Incompatible sizes for mul self:{len(self)} other:{len(factor)}" ) elif isinstance(factor, (int, float)): self._scale(factor) @@ -485,7 +481,7 @@ def free(self): self._free() def __repr__(self): - return self._create_repr("size = %d" % len(self)) + return self._create_repr(f"size = {len(self)}") def permute(self, permutation_vector): """ diff --git a/python/resdata/util/util/version.py b/python/resdata/util/util/version.py index 523370c69..018cc0125 100644 --- a/python/resdata/util/util/version.py +++ b/python/resdata/util/util/version.py @@ -32,7 +32,7 @@ def isDevelVersion(self): return self.is_devel def versionString(self): - return "%d.%d.%s" % (self.major, self.minor, self.micro) + return f"{self.major}.{self.minor}.{self.micro}" def versionTuple(self): return self.major, self.minor, self.micro diff --git a/python/resdata/well/well_info.py b/python/resdata/well/well_info.py index 69813cfb0..c0ab3dac2 100644 --- a/python/resdata/well/well_info.py +++ b/python/resdata/well/well_info.py @@ -42,7 +42,7 @@ def __init__(self, grid, rst_file=None, load_segment_information=True): self.addWellFile(rst_file, load_segment_information) def __repr__(self): - return "WellInfo(well_count = %d) at 0x%x" % (len(self), self._address()) + return f"WellInfo(well_count = {len(self)}) at 0x{self._address() :x}" def __len__(self): """@rtype: int""" @@ -61,9 +61,7 @@ def __getitem__(self, item): elif isinstance(item, int): if not 0 <= item < len(self): - raise IndexError( - "Index must be in range 0 <= %d < %d" % (item, len(self)) - ) + raise IndexError(f"Index must be in range 0 <= {item} < {len(self)}") well_name = self._iget_well_name(item) return self._get_ts(well_name).setParent(self) diff --git a/python/resdata/well/well_segment.py b/python/resdata/well/well_segment.py index ac406f0d3..3db50636d 100644 --- a/python/resdata/well/well_segment.py +++ b/python/resdata/well/well_segment.py @@ -31,11 +31,7 @@ def __repr__(self): return f"WellSegment({str(self)}) at 0x{self._address():x}" def __str__(self): - return "{Segment ID:%d BranchID:%d Length:%g}" % ( - self.id(), - self.branchId(), - self.length(), - ) + return f"Segment ID:{self.id()} BranchID:{self.branchId()} Length:{self.length() :g}" def id(self): """@rtype: int""" diff --git a/python/resdata/well/well_state.py b/python/resdata/well/well_state.py index 05a82e4cb..797039b14 100644 --- a/python/resdata/well/well_state.py +++ b/python/resdata/well/well_state.py @@ -142,9 +142,7 @@ def igetSegment(self, seg_idx): seg_idx += len(self) if not 0 <= seg_idx < self.numSegments(): - raise IndexError( - "Invalid index:%d - valid range [0,%d)" % (seg_idx, len(self)) - ) + raise IndexError(f"Invalid index:{seg_idx} - valid range [0,{len(self)})") segment_collection = self._get_segment_collection() return self._segment_collection_iget(segment_collection, seg_idx).setParent( diff --git a/python/resdata/well/well_time_line.py b/python/resdata/well/well_time_line.py index d1a9cb304..248ac8627 100644 --- a/python/resdata/well/well_time_line.py +++ b/python/resdata/well/well_time_line.py @@ -30,7 +30,7 @@ def __getitem__(self, index): index += len(self) if not 0 <= index < len(self): - raise IndexError("Index must be in range 0 <= %d < %d" % (index, len(self))) + raise IndexError(f"Index must be in range 0 <= {index} < {len(self)}") return self._iget(index).setParent(self) @@ -38,7 +38,5 @@ def free(self): pass def __repr__(self): - n = self.getName() - l = len(self) - cnt = "name = %s, size = %d" % (n, l) + cnt = f"name = {self.getName()}, size = {len(self)}" return self._create_repr(cnt) diff --git a/python/tests/rd_tests/test_fault_blocks.py b/python/tests/rd_tests/test_fault_blocks.py index 6d27c7d90..7811f9fd0 100644 --- a/python/tests/rd_tests/test_fault_blocks.py +++ b/python/tests/rd_tests/test_fault_blocks.py @@ -424,7 +424,7 @@ def test_internal_blocks(self): nb = b1.getNeighbours() for b in nb: - print("Block:%d" % b.getBlockID()) + print(f"Block:{b.getBlockID()}") self.assertTrue(len(nb) == 2) self.assertTrue(b3 in nb) diff --git a/python/tests/rd_tests/test_grid.py b/python/tests/rd_tests/test_grid.py index 68cdf7d02..44a1a0f1a 100644 --- a/python/tests/rd_tests/test_grid.py +++ b/python/tests/rd_tests/test_grid.py @@ -566,7 +566,7 @@ def test_unique_containment(self): self.assertEqual( expected, hits, - "Expected %d for (%g,%g,%g), got %d" % (expected, x, y, z, hits), + f"Expected {expected} for ({x :g},{y :g},{z :g}), got {hits}", ) def test_cell_corner_containment(self): diff --git a/python/tests/rd_tests/test_rd_kw.py b/python/tests/rd_tests/test_rd_kw.py index 1338d3bfc..38ced1cc6 100644 --- a/python/tests/rd_tests/test_rd_kw.py +++ b/python/tests/rd_tests/test_rd_kw.py @@ -565,7 +565,7 @@ def test_fmu_stat_workflow(self): permx.assign(random.random()) poro.assign(random.random()) - with openFortIO("TEST%d.INIT" % i, FortIO.WRITE_MODE) as f: + with openFortIO(f"TEST{i}.INIT", FortIO.WRITE_MODE) as f: permx.fwrite(f) poro.fwrite(f) porv.fwrite(f) @@ -577,7 +577,7 @@ def test_fmu_stat_workflow(self): count = ResdataKW("COUNT", global_size, ResDataType.RD_INT) for i in range(N): - f = ResdataFile("TEST%d.INIT" % i) + f = ResdataFile(f"TEST{i}.INIT") porv = f["PORV"][0] permx = f["PERMX"][0] From 1aac2411acc34afac2fd81378cb9b3661b22dd5e Mon Sep 17 00:00:00 2001 From: larsevj Date: Thu, 29 Aug 2024 18:37:17 +0200 Subject: [PATCH 11/11] Some initial typing and misc --- python/resdata/geometry/cpolyline.py | 6 +- .../resdata/geometry/cpolyline_collection.py | 2 +- python/resdata/geometry/geo_pointset.py | 2 +- python/resdata/grid/rd_grid.py | 157 ++++++++++-------- .../test_cpolyline_collection.py | 1 - .../tests/rd_tests/test_grid_equinor_dual.py | 1 - python/tests/rd_tests/test_grid_large_case.py | 1 - python/tests/well_tests/test_rd_well3.py | 1 - 8 files changed, 91 insertions(+), 80 deletions(-) diff --git a/python/resdata/geometry/cpolyline.py b/python/resdata/geometry/cpolyline.py index 271044bad..85f946f62 100644 --- a/python/resdata/geometry/cpolyline.py +++ b/python/resdata/geometry/cpolyline.py @@ -54,7 +54,7 @@ def createFromXYZFile(cls, filename, name=None): polyline._set_name(name) return polyline - def __str__(self): + def __str__(self) -> str: name = self.getName() str = f"{name} [" if name else "[" @@ -65,10 +65,10 @@ def __str__(self): str += "]" return str - def __repr__(self): + def __repr__(self) -> str: return str(self) - def __len__(self): + def __len__(self) -> int: return self._size() def __getitem__(self, index): diff --git a/python/resdata/geometry/cpolyline_collection.py b/python/resdata/geometry/cpolyline_collection.py index 9c0462b0f..f69601bf3 100644 --- a/python/resdata/geometry/cpolyline_collection.py +++ b/python/resdata/geometry/cpolyline_collection.py @@ -41,7 +41,7 @@ def __init__(self): def __contains__(self, name): return self._has_polyline(name) - def __len__(self): + def __len__(self) -> int: return self._size() def __iter__(self): diff --git a/python/resdata/geometry/geo_pointset.py b/python/resdata/geometry/geo_pointset.py index 06d0b3152..48d59f6b3 100644 --- a/python/resdata/geometry/geo_pointset.py +++ b/python/resdata/geometry/geo_pointset.py @@ -42,7 +42,7 @@ def __getitem__(self, key): # TODO implement slicing? raise ValueError(f"Index must be int, not {type(key)}.") - def __len__(self): + def __len__(self) -> int: return self._get_size() def __repr__(self): diff --git a/python/resdata/grid/rd_grid.py b/python/resdata/grid/rd_grid.py index d4b55f6ad..a5dfbe4c0 100644 --- a/python/resdata/grid/rd_grid.py +++ b/python/resdata/grid/rd_grid.py @@ -25,6 +25,11 @@ from resdata.resfile import ResdataKW, FortIO from resdata.grid import Cell +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from resdata.util.util import DoubleVector + class Grid(BaseCClass): """ @@ -342,7 +347,7 @@ def __repr__(self): f"{name}{xyz_s}, global_size={g_size}, active_size={a_size}" ) - def __len__(self): + def __len__(self) -> int: """ len(grid) wil return the total number of cells. """ @@ -356,47 +361,47 @@ def equal(self, other, include_lgr=True, include_nnc=False, verbose=False): raise TypeError("The other argument must be an Grid instance") return self._equal(other, include_lgr, include_nnc, verbose) - def dual_grid(self): + def dual_grid(self) -> bool: """Is this grid dual porosity model?""" return self._dual_grid() def get_dims(self): """A tuple of four elements: (nx, ny, nz, nactive).""" - return (self.getNX(), self.getNY(), self.getNZ(), self.getNumActive()) + return (self.get_nx(), self.get_ny(), self.get_nz(), self.get_num_active()) @property - def nx(self): + def nx(self) -> int: return self._get_nx() - def get_nx(self): + def get_nx(self) -> int: """The number of elements in the x direction""" return self._get_nx() @property - def ny(self): + def ny(self) -> int: return self._get_ny() - def get_ny(self): + def get_ny(self) -> int: """The number of elements in the y direction""" return self._get_ny() @property - def nz(self): + def nz(self) -> int: return self._get_nz() - def get_nz(self): + def get_nz(self) -> int: """The number of elements in the z direction""" return self._get_nz() - def get_global_size(self): + def get_global_size(self) -> int: """Returns the total number of cells in this grid""" return self._get_global_size() - def get_num_active(self): + def get_num_active(self) -> int: """The number of active cells in the grid.""" return self._get_active() - def get_num_active_fracture(self): + def get_num_active_fracture(self) -> int: """The number of active cells in the grid.""" return self._get_active_fracture() @@ -461,7 +466,7 @@ def get_bounding_box_2d(self, layer=0, lower_left=None, upper_right=None): f"Invalid layer value:{layer} Valid range: [0,{self.get_nz()}]" ) - def get_name(self): + def get_name(self) -> str: """ Name of the current grid, returns a string. @@ -473,7 +478,9 @@ def get_name(self): n = self._get_name() return str(n) if n else "" - def cell(self, global_index=None, active_index=None, i=None, j=None, k=None): + def cell( + self, global_index=None, active_index=None, i=None, j=None, k=None + ) -> Cell: if global_index is not None: return Cell(self, global_index) if active_index is not None: @@ -481,7 +488,7 @@ def cell(self, global_index=None, active_index=None, i=None, j=None, k=None): if i is not None: return Cell(self, self.global_index(ijk=(i, j, k))) - def __getitem__(self, global_index): + def __getitem__(self, global_index) -> Cell: if isinstance(global_index, tuple): i, j, k = global_index return self.cell(i=i, j=j, k=k) @@ -505,7 +512,7 @@ def global_index(self, active_index=None, ijk=None): """ return self.__global_index(active_index=active_index, ijk=ijk) - def __global_index(self, active_index=None, global_index=None, ijk=None): + def __global_index(self, active_index=None, global_index=None, ijk=None) -> int: """ Will convert @active_index or @ijk to global_index. @@ -576,7 +583,7 @@ def get_active_fracture_index(self, ijk=None, global_index=None): gi = self.__global_index(global_index=global_index, ijk=ijk) return self._get_active_fracture_index1(gi) - def get_global_index1F(self, active_fracture_index): + def get_global_index1F(self, active_fracture_index) -> int: """ Will return the global index corresponding to active fracture index. @@ -587,7 +594,7 @@ def get_global_index1F(self, active_fracture_index): return None return result - def cell_invalid(self, ijk=None, global_index=None, active_index=None): + def cell_invalid(self, ijk=None, global_index=None, active_index=None) -> bool: """ Tries to check if a cell is invalid. @@ -604,7 +611,9 @@ def cell_invalid(self, ijk=None, global_index=None, active_index=None): ) return self._invalid_cell(gi) - def valid_cell_geometry(self, ijk=None, global_index=None, active_index=None): + def valid_cell_geometry( + self, ijk=None, global_index=None, active_index=None + ) -> bool: """Checks if the cell has valid geometry. There are at least two reasons why a cell might have invalid @@ -629,7 +638,7 @@ def valid_cell_geometry(self, ijk=None, global_index=None, active_index=None): ) return self._valid_cell(gi) - def active(self, ijk=None, global_index=None): + def active(self, ijk=None, global_index=None) -> bool: """ Is the cell active? @@ -822,31 +831,31 @@ def depth(self, active_index=None, global_index=None, ijk=None): ) return self._get_depth(gi) - def top(self, i, j): + def top(self, i, j) -> float: """ Top of the reservoir; in the column (@i, @j). Returns average depth of the four top corners. """ return self._get_top(i, j) - def top_active(self, i, j): + def top_active(self, i, j) -> float: """ Top of the active part of the reservoir; in the column (@i, @j). Raises ValueError if (i,j) column is inactive. """ - for k in range(self.getNZ()): + for k in range(self.get_nz()): a_idx = self.get_active_index(ijk=(i, j, k)) if a_idx >= 0: return self._get_top1A(a_idx) raise ValueError(f"No active cell in column ({i}, {j})") - def bottom(self, i, j): + def bottom(self, i: int, j: int) -> float: """ Bottom of the reservoir; in the column (@i, @j). """ return self._get_bottom(i, j) - def locate_depth(self, depth, i, j): + def locate_depth(self, depth: float, i: int, j: int) -> int: """ Will locate the k value of cell containing specified depth. @@ -910,7 +919,7 @@ def find_cell_xy(self, x, y, k): values for k are [0,nz]. If the coordinates (x,y) are found to be outside the grid a ValueError exception is raised. """ - if 0 <= k <= self.getNZ(): + if 0 <= k <= self.get_nz(): i = ctypes.c_int() j = ctypes.c_int() ok = self._get_ij_xy(x, y, k, ctypes.byref(i), ctypes.byref(j)) @@ -931,26 +940,26 @@ def find_cell_corner_xy(self, x, y, k): be outside the grid a ValueError exception is raised. """ i, j = self.findCellXY(x, y, k) - if k == self.getNZ(): + if k == self.get_nz(): k -= 1 corner_shift = 4 else: corner_shift = 0 - nx = self.getNX() - x0, y0, _ = self.getCellCorner(corner_shift, ijk=(i, j, k)) + nx = self.get_nx() + x0, y0, _ = self.get_cell_corner(corner_shift, ijk=(i, j, k)) d0 = math.sqrt((x0 - x) * (x0 - x) + (y0 - y) * (y0 - y)) c0 = i + j * (nx + 1) - x1, y1, _ = self.getCellCorner(1 + corner_shift, ijk=(i, j, k)) + x1, y1, _ = self.get_cell_corner(1 + corner_shift, ijk=(i, j, k)) d1 = math.sqrt((x1 - x) * (x1 - x) + (y1 - y) * (y1 - y)) c1 = i + 1 + j * (nx + 1) - x2, y2, _ = self.getCellCorner(2 + corner_shift, ijk=(i, j, k)) + x2, y2, _ = self.get_cell_corner(2 + corner_shift, ijk=(i, j, k)) d2 = math.sqrt((x2 - x) * (x2 - x) + (y2 - y) * (y2 - y)) c2 = i + (j + 1) * (nx + 1) - x3, y3, _ = self.getCellCorner(3 + corner_shift, ijk=(i, j, k)) + x3, y3, _ = self.get_cell_corner(3 + corner_shift, ijk=(i, j, k)) d3 = math.sqrt((x3 - x) * (x3 - x) + (y3 - y) * (y3 - y)) c3 = i + 1 + (j + 1) * (nx + 1) @@ -958,7 +967,7 @@ def find_cell_corner_xy(self, x, y, k): l.sort(key=lambda k: k[0]) return l[0][1] - def cell_regular(self, active_index=None, global_index=None, ijk=None): + def cell_regular(self, active_index=None, global_index=None, ijk=None) -> bool: """ The grid models often contain various degenerate cells, which are twisted, have overlapping corners or what not. This @@ -972,7 +981,7 @@ def cell_regular(self, active_index=None, global_index=None, ijk=None): ) return self._cell_regular(gi) - def cell_volume(self, active_index=None, global_index=None, ijk=None): + def cell_volume(self, active_index=None, global_index=None, ijk=None) -> float: """ Calculate the volume of a cell. @@ -985,7 +994,7 @@ def cell_volume(self, active_index=None, global_index=None, ijk=None): ) return self._get_cell_volume(gi) - def cell_dz(self, active_index=None, global_index=None, ijk=None): + def cell_dz(self, active_index=None, global_index=None, ijk=None) -> float: """ The thickness of a cell. @@ -1019,7 +1028,7 @@ def get_cell_dims(self, active_index=None, global_index=None, ijk=None): dz = self._get_cell_thickness(gi) return (dx, dy, dz) - def get_num_lgr(self): + def get_num_lgr(self) -> int: """ How many LGRs are attached to this main grid? @@ -1028,7 +1037,7 @@ def get_num_lgr(self): """ return self._num_lgr() - def has_lgr(self, lgr_name): + def has_lgr(self, lgr_name: str) -> bool: """ Query if the grid has an LGR with name @lgr_name. """ @@ -1081,7 +1090,7 @@ def get_cell_lgr(self, active_index=None, global_index=None, ijk=None): else: raise IndexError("No LGR defined for this cell") - def grid_value(self, kw, i, j, k): + def grid_value(self, kw: ResdataKW, i: int, j: int, k: int) -> float: """ Will evalute @kw in location (@i,@j,@k). @@ -1098,7 +1107,9 @@ def grid_value(self, kw, i, j, k): """ return self._grid_value(kw, i, j, k) - def load_column(self, kw, i, j, column): + def load_column( + self, kw: ResdataKW, i: int, j: int, column: "DoubleVector" + ) -> None: """ Load the values of @kw from the column specified by (@i,@j). @@ -1114,7 +1125,7 @@ def load_column(self, kw, i, j, column): """ self._load_column(kw, i, j, column) - def create_kw(self, array, kw_name, pack): + def create_kw(self, array, kw_name, pack) -> ResdataKW: """ Creates an ResdataKW instance based on existing 3D numpy object. @@ -1126,9 +1137,9 @@ def create_kw(self, array, kw_name, pack): if array.ndim == 3: dims = array.shape if ( - dims[0] == self.getNX() - and dims[1] == self.getNY() - and dims[2] == self.getNZ() + dims[0] == self.get_nx() + and dims[1] == self.get_ny() + and dims[2] == self.get_nz() ): dtype = array.dtype if dtype == np.int32: @@ -1140,7 +1151,7 @@ def create_kw(self, array, kw_name, pack): else: sys.exit(f"Do not know how to create rd_kw from type:{dtype}") - size = self.getNumActive() if pack else self.getGlobalSize() + size = self.get_num_active() if pack else self.get_global_size() if len(kw_name) > 8: # Silently truncate to length 8 @@ -1165,13 +1176,13 @@ def create_kw(self, array, kw_name, pack): return kw raise ValueError("Wrong size / dimension on array") - def coarse_groups(self): + def coarse_groups(self) -> int: """ Will return the number of coarse groups in this grid. """ return self._num_coarse_groups() - def in_coarse_group(self, global_index=None, ijk=None, active_index=None): + def in_coarse_group(self, global_index=None, ijk=None, active_index=None) -> bool: """ Will return True or False if the cell is part of coarse group. """ @@ -1180,7 +1191,7 @@ def in_coarse_group(self, global_index=None, ijk=None, active_index=None): ) return self._in_coarse_group1(global_index) - def create_3d(self, rd_kw, default=0): + def create_3d(self, rd_kw: ResdataKW, default=0): """ Creates a 3D numpy array object with the data from @rd_kw. @@ -1199,30 +1210,32 @@ def create_3d(self, rd_kw, default=0): value = grid.grid_value(rd_kw, i, j, k) """ - if len(rd_kw) == self.getNumActive() or len(rd_kw) == self.getGlobalSize(): - array = np.ones([self.getGlobalSize()], dtype=rd_kw.dtype) * default + if len(rd_kw) == self.get_num_active() or len(rd_kw) == self.get_global_size(): + array = np.ones([self.get_global_size()], dtype=rd_kw.dtype) * default kwa = rd_kw.array - if len(rd_kw) == self.getGlobalSize(): + if len(rd_kw) == self.get_global_size(): for i in range(kwa.size): array[i] = kwa[i] else: - for global_index in range(self.getGlobalSize()): + for global_index in range(self.get_global_size()): active_index = self._get_active_index1(global_index) array[global_index] = kwa[active_index] - array = array.reshape([self.getNX(), self.getNY(), self.getNZ()], order="F") + array = array.reshape( + [self.get_nx(), self.get_ny(), self.get_nz()], order="F" + ) return array else: err_msg_fmt = 'Keyword "%s" has invalid size %d; must be either nactive=%d or nx*ny*nz=%d' err_msg = err_msg_fmt % ( rd_kw, len(rd_kw), - self.getNumActive(), - self.getGlobalSize(), + self.get_num_active(), + self.get_global_size(), ) raise ValueError(err_msg) - def save_grdecl(self, pyfile, output_unit=UnitSystem.METRIC): + def save_grdecl(self, pyfile, output_unit=UnitSystem.METRIC) -> None: """ Will write the the grid content as grdecl formatted keywords. @@ -1242,7 +1255,9 @@ def save_GRID(self, filename, output_unit=UnitSystem.METRIC): """ self._fwrite_GRID2(filename, output_unit) - def write_grdecl(self, rd_kw, pyfile, special_header=None, default_value=0): + def write_grdecl( + self, rd_kw: ResdataKW, pyfile, special_header=None, default_value=0 + ): """ Writes an ResdataKW instance as an ECLIPSE grdecl formatted file. @@ -1265,7 +1280,7 @@ def write_grdecl(self, rd_kw, pyfile, special_header=None, default_value=0): """ - if len(rd_kw) == self.getNumActive() or len(rd_kw) == self.getGlobalSize(): + if len(rd_kw) == self.get_num_active() or len(rd_kw) == self.get_global_size(): cfile = CFILE(pyfile) self._fwrite_grdecl(rd_kw, special_header, cfile, default_value) else: @@ -1278,11 +1293,11 @@ def exportACTNUM(self): self._init_actnum(actnum.getDataPtr()) return actnum - def compressed_kw_copy(self, kw): - if len(kw) == self.getNumActive(): + def compressed_kw_copy(self, kw: ResdataKW) -> ResdataKW: + if len(kw) == self.get_num_active(): return kw.copy() - elif len(kw) == self.getGlobalSize(): - kw_copy = ResdataKW(kw.getName(), self.getNumActive(), kw.data_type) + elif len(kw) == self.get_global_size(): + kw_copy = ResdataKW(kw.get_name(), self.get_num_active(), kw.data_type) self._compressed_kw_copy(kw_copy, kw) return kw_copy else: @@ -1290,11 +1305,11 @@ def compressed_kw_copy(self, kw): f"The input keyword must have nx*n*nz or nactive elements. Size:{len(kw)} invalid" ) - def global_kw_copy(self, kw, default_value): - if len(kw) == self.getGlobalSize(): + def global_kw_copy(self, kw, default_value) -> ResdataKW: + if len(kw) == self.get_global_size(): return kw.copy() - elif len(kw) == self.getNumActive(): - kw_copy = ResdataKW(kw.getName(), self.getGlobalSize(), kw.data_type) + elif len(kw) == self.get_num_active(): + kw_copy = ResdataKW(kw.get_name(), self.get_global_size(), kw.data_type) kw_copy.assign(default_value) self._global_kw_copy(kw_copy, kw) return kw_copy @@ -1303,12 +1318,12 @@ def global_kw_copy(self, kw, default_value): f"The input keyword must have nx*n*nz or nactive elements. Size:{len(kw)} invalid" ) - def export_ACTNUM_kw(self): - actnum = ResdataKW("ACTNUM", self.getGlobalSize(), ResDataType.RD_INT) - self._init_actnum(actnum.getDataPtr()) + def export_ACTNUM_kw(self) -> ResdataKW: + actnum = ResdataKW("ACTNUM", self.get_global_size(), ResDataType.RD_INT) + self._init_actnum(actnum.get_data_ptr()) return actnum - def create_volume_keyword(self, active_size=True): + def create_volume_keyword(self, active_size: bool = True) -> ResdataKW: """Will create a ResdataKW initialized with cell volumes. The purpose of this method is to create a ResdataKW instance which @@ -1338,7 +1353,7 @@ def create_volume_keyword(self, active_size=True): return self._create_volume_keyword(active_size) - def export_index(self, active_only=False): + def export_index(self, active_only=False) -> pd.DataFrame: """ Exports a pandas dataframe containing index data of grid cells. @@ -1361,7 +1376,7 @@ def export_index(self, active_only=False): df = pd.DataFrame(data=data, index=indx, columns=["i", "j", "k", "active"]) return df - def export_data(self, index_frame, kw, default=0): + def export_data(self, index_frame: pd.DataFrame, kw: ResdataKW, default=0): """ Exports keywoard data to a numpy vector. diff --git a/python/tests/geometry_tests/test_cpolyline_collection.py b/python/tests/geometry_tests/test_cpolyline_collection.py index 265113e10..d1490fc5b 100644 --- a/python/tests/geometry_tests/test_cpolyline_collection.py +++ b/python/tests/geometry_tests/test_cpolyline_collection.py @@ -1,4 +1,3 @@ - from resdata.geometry import CPolylineCollection, CPolyline from tests import ResdataTest from resdata.util.util import DoubleVector diff --git a/python/tests/rd_tests/test_grid_equinor_dual.py b/python/tests/rd_tests/test_grid_equinor_dual.py index 73d1b067e..04196da24 100644 --- a/python/tests/rd_tests/test_grid_equinor_dual.py +++ b/python/tests/rd_tests/test_grid_equinor_dual.py @@ -1,4 +1,3 @@ - from resdata.util.test import TestAreaContext from resdata.grid import Grid diff --git a/python/tests/rd_tests/test_grid_large_case.py b/python/tests/rd_tests/test_grid_large_case.py index ca07859be..2df447d52 100644 --- a/python/tests/rd_tests/test_grid_large_case.py +++ b/python/tests/rd_tests/test_grid_large_case.py @@ -1,4 +1,3 @@ - import pytest from resdata.grid import Grid diff --git a/python/tests/well_tests/test_rd_well3.py b/python/tests/well_tests/test_rd_well3.py index cfbc84ea2..c3a0a662c 100644 --- a/python/tests/well_tests/test_rd_well3.py +++ b/python/tests/well_tests/test_rd_well3.py @@ -1,4 +1,3 @@ - from resdata.grid import Grid from resdata.summary import Summary from tests import ResdataTest, equinor_test