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/ci/github/setup.py b/ci/github/setup.py index 298b40b6b..081cca16e 100644 --- a/ci/github/setup.py +++ b/ci/github/setup.py @@ -1,7 +1,6 @@ from setuptools import setup from setuptools_scm import get_version - version = get_version() diff --git a/cmake/create_cmakelists.py b/cmake/create_cmakelists.py index 173331e6b..5eeb2ad75 100755 --- a/cmake/create_cmakelists.py +++ b/cmake/create_cmakelists.py @@ -1,8 +1,8 @@ #!/usr/bin/env python -from os import listdir -from os.path import isfile, join, isdir, islink import sys +from os import listdir +from os.path import isdir, isfile, islink, join def findFilesAndDirectories(directory): @@ -11,7 +11,7 @@ def findFilesAndDirectories(directory): directories = [] for f in all_files: path = join(directory, f) - if isfile(path) and not f == "CMakeLists.txt" and not islink(path): + if isfile(path) and f != "CMakeLists.txt" and not islink(path): files.append(f) if isdir(path): directories.append(f) diff --git a/pyproject.toml b/pyproject.toml index 9abf16845..c0630a755 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,2 +1,39 @@ [build-system] requires = ["setuptools", "setuptools_scm", "wheel", "scikit-build", "cmake", "conan<2", "ninja"] + +[tool.ruff] +src = ["python/resdata"] +line-length = 88 + +[tool.ruff.lint] +select = [ + "W", # pycodestyle + "I", # isort + "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", + "C409", + "PLC0414", +] + +[tool.ruff.lint.pylint] +max-args = 15 \ No newline at end of file diff --git a/python/docs/examples/avg_pressure.py b/python/docs/examples/avg_pressure.py index 7a0131dff..59a4e4efb 100755 --- a/python/docs/examples/avg_pressure.py +++ b/python/docs/examples/avg_pressure.py @@ -19,15 +19,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 - - if total_hc_pv > 0: - p3 = p_hc_pv.sum(mask=region) / total_hc_pv - else: - p3 = None + p2 = p_pv.sum(mask=region) / total_pv if total_pv > 0 else 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 +65,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/cmp_nnc.py b/python/docs/examples/cmp_nnc.py index 4ca50e36f..b38ca2034 100755 --- a/python/docs/examples/cmp_nnc.py +++ b/python/docs/examples/cmp_nnc.py @@ -1,9 +1,9 @@ #!/usr/bin/env python import sys from operator import itemgetter -from resdata.resfile import ResdataFile -from resdata.grid import Grid +from resdata.grid import Grid +from resdata.resfile import ResdataFile if __name__ == "__main__": case = sys.argv[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..748919f0e 100644 --- a/python/resdata/__init__.py +++ b/python/resdata/__init__.py @@ -42,7 +42,7 @@ from cwrap import Prototype -from .version import version as __version__ +from .version import version as __version__ # noqa: F401 def _dlopen_resdata(): @@ -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) @@ -100,15 +100,25 @@ def __init__(self, prototype, bind=True): ) -from .rd_type import ResDataType, ResdataTypeEnum +from .rd_type import ResDataType as ResDataType +from .rd_type import ResdataTypeEnum as ResdataTypeEnum from .rd_util import ( - FileType, - FileMode, - Phase, - UnitSystem, - ResdataUtil, + FileMode as FileMode, ) -from .util.util import ResdataVersion, updateAbortSignals +from .rd_util import ( + FileType as FileType, +) +from .rd_util import ( + Phase as Phase, +) +from .rd_util import ( + ResdataUtil as ResdataUtil, +) +from .rd_util import ( + UnitSystem as UnitSystem, +) +from .util.util import ResdataVersion as ResdataVersion +from .util.util import updateAbortSignals updateAbortSignals() diff --git a/python/resdata/geometry/__init__.py b/python/resdata/geometry/__init__.py index 50e558a21..e5c78c156 100644 --- a/python/resdata/geometry/__init__.py +++ b/python/resdata/geometry/__init__.py @@ -3,14 +3,13 @@ """ -import resdata -from cwrap import Prototype +import resdata as resdata -from .geo_pointset import GeoPointset -from .geo_region import GeoRegion -from .cpolyline import CPolyline -from .cpolyline_collection import CPolylineCollection -from .polyline import Polyline -from .xyz_io import XYZIo -from .geometry_tools import GeometryTools -from .surface import Surface +from .cpolyline import CPolyline as CPolyline +from .cpolyline_collection import CPolylineCollection as CPolylineCollection +from .geo_pointset import GeoPointset as GeoPointset +from .geo_region import GeoRegion as GeoRegion +from .geometry_tools import GeometryTools as GeometryTools +from .polyline import Polyline as Polyline +from .surface import Surface as Surface +from .xyz_io import XYZIo as XYZIo 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..720eb31f3 100644 --- a/python/resdata/geometry/cpolyline_collection.py +++ b/python/resdata/geometry/cpolyline_collection.py @@ -2,9 +2,8 @@ Create a polygon """ -import ctypes - from cwrap import BaseCClass + from resdata import ResdataPrototype from resdata.geometry import CPolyline @@ -85,11 +84,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_pointset.py b/python/resdata/geometry/geo_pointset.py index c60cb81fb..8a708fa81 100644 --- a/python/resdata/geometry/geo_pointset.py +++ b/python/resdata/geometry/geo_pointset.py @@ -1,4 +1,5 @@ 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 33c7cb597..f4901b625 100644 --- a/python/resdata/geometry/geo_region.py +++ b/python/resdata/geometry/geo_region.py @@ -1,8 +1,10 @@ +from ctypes import c_double + from cwrap import BaseCClass -from resdata.util.util import IntVector + from resdata import ResdataPrototype + from .cpolyline import CPolyline -from ctypes import c_double cpair = c_double * 2 # this is a function that maps two doubles to a double* @@ -42,7 +44,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 +70,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..36928af22 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]] @@ -193,20 +188,15 @@ 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 + )[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 +384,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..7d4e73385 100644 --- a/python/resdata/geometry/polyline.py +++ b/python/resdata/geometry/polyline.py @@ -1,4 +1,3 @@ -import collections from .geometry_tools import GeometryTools @@ -40,20 +39,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..be07deae3 100644 --- a/python/resdata/geometry/surface.py +++ b/python/resdata/geometry/surface.py @@ -3,12 +3,12 @@ """ Create a polygon """ -import os.path import ctypes +import os.path from cwrap import BaseCClass + from resdata import ResdataPrototype -from resdata.geometry import GeoPointset class Surface(BaseCClass): @@ -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/geometry/xyz_io.py b/python/resdata/geometry/xyz_io.py index 90e3b09c9..ff2dee821 100644 --- a/python/resdata/geometry/xyz_io.py +++ b/python/resdata/geometry/xyz_io.py @@ -1,4 +1,5 @@ import os + from .polyline import Polyline diff --git a/python/resdata/gravimetry/__init__.py b/python/resdata/gravimetry/__init__.py index 1035865aa..e4c4e7ccb 100644 --- a/python/resdata/gravimetry/__init__.py +++ b/python/resdata/gravimetry/__init__.py @@ -1,11 +1,11 @@ """ - 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 -from .rd_subsidence import ResdataSubsidence +from .rd_grav import ResdataGrav as ResdataGrav +from .rd_subsidence import ResdataSubsidence as ResdataSubsidence diff --git a/python/resdata/gravimetry/rd_grav.py b/python/resdata/gravimetry/rd_grav.py index 49aed935a..9ebe5a5e6 100644 --- a/python/resdata/gravimetry/rd_grav.py +++ b/python/resdata/gravimetry/rd_grav.py @@ -10,6 +10,7 @@ from typing import Optional from cwrap import BaseCClass + from resdata import Phase, ResdataPrototype from resdata.grid import Grid, ResdataRegion from resdata.resfile import ResdataFile, ResdataFileView diff --git a/python/resdata/gravimetry/rd_subsidence.py b/python/resdata/gravimetry/rd_subsidence.py index 0ad6b7bb8..47da77729 100644 --- a/python/resdata/gravimetry/rd_subsidence.py +++ b/python/resdata/gravimetry/rd_subsidence.py @@ -8,9 +8,9 @@ """ from cwrap import BaseCClass + from resdata import ResdataPrototype from resdata.util.util import monkey_the_camel -import resdata.grid class ResdataSubsidence(BaseCClass): @@ -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..9a0296de0 100644 --- a/python/resdata/grid/__init__.py +++ b/python/resdata/grid/__init__.py @@ -1,19 +1,19 @@ """ - 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 -import resdata.geometry +import resdata.geometry # noqa: F401 +import resdata.util.util # noqa: F401 -from .cell import Cell -from .rd_grid import Grid -from .rd_grid_generator import GridGenerator -from .rd_region import ResdataRegion +from .cell import Cell as Cell +from .rd_grid import Grid as Grid +from .rd_grid_generator import GridGenerator as GridGenerator +from .rd_region import ResdataRegion as ResdataRegion 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/__init__.py b/python/resdata/grid/faults/__init__.py index 179c5e577..6fd34dcb6 100644 --- a/python/resdata/grid/faults/__init__.py +++ b/python/resdata/grid/faults/__init__.py @@ -1,7 +1,9 @@ -from .layer import Layer -from .fault_collection import FaultCollection -from .fault import Fault -from .fault_line import FaultLine -from .fault_segments import FaultSegment, SegmentMap -from .fault_block import FaultBlock, FaultBlockCell -from .fault_block_layer import FaultBlockLayer +from .fault import Fault as Fault +from .fault_block import FaultBlock as FaultBlock +from .fault_block import FaultBlockCell as FaultBlockCell +from .fault_block_layer import FaultBlockLayer as FaultBlockLayer +from .fault_collection import FaultCollection as FaultCollection +from .fault_line import FaultLine as FaultLine +from .fault_segments import FaultSegment as FaultSegment +from .fault_segments import SegmentMap as SegmentMap +from .layer import Layer as Layer diff --git a/python/resdata/grid/faults/fault.py b/python/resdata/grid/faults/fault.py index b25a42758..a9128e2e4 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.geometry import CPolyline, GeometryTools from resdata.util.util import monkey_the_camel -from resdata.geometry import Polyline, CPolyline, GeometryTools from .fault_line import FaultLine from .fault_segments import FaultSegment, SegmentMap @@ -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..f9a8ba778 100644 --- a/python/resdata/grid/faults/fault_block.py +++ b/python/resdata/grid/faults/fault_block.py @@ -1,10 +1,10 @@ import ctypes + from cwrap import BaseCClass -from resdata.util.util import monkey_the_camel -from resdata.util.util import DoubleVector, IntVector from resdata import ResdataPrototype -from resdata.geometry import Polyline, GeometryTools, CPolylineCollection +from resdata.geometry import CPolylineCollection, GeometryTools, Polyline +from resdata.util.util import DoubleVector, IntVector, monkey_the_camel class FaultBlockCell(object): @@ -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..eea629ab1 100644 --- a/python/resdata/grid/faults/fault_block_layer.py +++ b/python/resdata/grid/faults/fault_block_layer.py @@ -1,10 +1,10 @@ from __future__ import print_function + 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 +from resdata.util.util import monkey_the_camel class FaultBlockLayer(BaseCClass): @@ -206,7 +206,7 @@ def join_faults(self, fault1, fault2): 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_collection.py b/python/resdata/grid/faults/fault_collection.py index 7930b3f61..072f225eb 100644 --- a/python/resdata/grid/faults/fault_collection.py +++ b/python/resdata/grid/faults/fault_collection.py @@ -1,7 +1,8 @@ import re -from resdata.util.util import monkey_the_camel from resdata.grid import Grid +from resdata.util.util import monkey_the_camel + from .fault import Fault comment_regexp = re.compile("--.*") diff --git a/python/resdata/grid/faults/fault_line.py b/python/resdata/grid/faults/fault_line.py index 45697e800..4310261f4 100644 --- a/python/resdata/grid/faults/fault_line.py +++ b/python/resdata/grid/faults/fault_line.py @@ -1,8 +1,7 @@ import sys -from resdata.util.util import monkey_the_camel -from resdata.util.util import DoubleVector from resdata.geometry import CPolyline +from resdata.util.util import DoubleVector, monkey_the_camel from .fault_segments import FaultSegment @@ -29,7 +28,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 +53,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) @@ -72,7 +71,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) @@ -124,10 +122,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 +132,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..42974f2ec 100644 --- a/python/resdata/grid/faults/layer.py +++ b/python/resdata/grid/faults/layer.py @@ -1,10 +1,7 @@ -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 + from resdata import ResdataPrototype +from resdata.util.util import IntVector, monkey_the_camel class Layer(BaseCClass): @@ -63,10 +60,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 d20c236a6..49beb6950 100644 --- a/python/resdata/grid/rd_grid.py +++ b/python/resdata/grid/rd_grid.py @@ -9,22 +9,20 @@ """ import ctypes - +import math +import os.path +import sys import warnings + import numpy import pandas -import sys -import os.path -import math -import itertools -from cwrap import CFILE, BaseCClass, load, open as copen - -from resdata import ResdataPrototype -from resdata.util.util import monkey_the_camel -from resdata.util.util import IntVector -from resdata import ResDataType, UnitSystem, ResdataTypeEnum -from resdata.resfile import ResdataKW, FortIO +from cwrap import CFILE, BaseCClass +from cwrap import open as copen + +from resdata import ResdataPrototype, ResDataType, ResdataTypeEnum, UnitSystem from resdata.grid import Cell +from resdata.resfile import FortIO, ResdataKW +from resdata.util.util import IntVector, monkey_the_camel class Grid(BaseCClass): @@ -280,6 +278,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 +553,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 +640,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 +1040,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 +1059,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 +1148,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 +1164,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 == numpy.int32: + kw[global_index] = int(array[i, j, k]) else: - if dtype == numpy.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 +1366,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 = numpy.zeros(size, dtype=numpy.int32) data = numpy.zeros([size, 4], dtype=numpy.int32) self._export_index_frame( diff --git a/python/resdata/grid/rd_grid_generator.py b/python/resdata/grid/rd_grid_generator.py index 44f9a958f..09a4557a2 100644 --- a/python/resdata/grid/rd_grid_generator.py +++ b/python/resdata/grid/rd_grid_generator.py @@ -1,12 +1,12 @@ -import itertools, numpy +import itertools from math import sqrt -from resdata import ResdataPrototype -from resdata.util.util import monkey_the_camel -from resdata.util.util import IntVector -from resdata import ResDataType -from resdata.resfile import ResdataKW +import numpy + +from resdata import ResdataPrototype, ResDataType from resdata.grid import Grid +from resdata.resfile import ResdataKW +from resdata.util.util import IntVector, monkey_the_camel def flatten(l): @@ -492,7 +492,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))) @@ -691,10 +691,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/grid/rd_region.py b/python/resdata/grid/rd_region.py index 69ad6e24b..262dd5b1f 100644 --- a/python/resdata/grid/rd_region.py +++ b/python/resdata/grid/rd_region.py @@ -11,20 +11,15 @@ queried for the corresponding list of indices. """ -from functools import wraps import ctypes +from functools import wraps 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 import ResdataPrototype, ResDataType from resdata.geometry import CPolyline +from resdata.resfile import ResdataKW +from resdata.util.util import IntVector, monkey_the_camel def select_method(select): @@ -1067,10 +1062,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_type.py b/python/resdata/rd_type.py index 7af86c47e..ff1e597dc 100644 --- a/python/resdata/rd_type.py +++ b/python/resdata/rd_type.py @@ -1,4 +1,5 @@ from cwrap import BaseCClass, BaseCEnum + from resdata import ResdataPrototype 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/__init__.py b/python/resdata/resfile/__init__.py index 6b1093e20..16a5a0036 100644 --- a/python/resdata/resfile/__init__.py +++ b/python/resdata/resfile/__init__.py @@ -17,13 +17,15 @@ instances. """ -import resdata.util.util +import resdata.util.util # noqa: F401 -from .fortio import FortIO, openFortIO -from .rd_kw import ResdataKW -from .rd_file_view import ResdataFileView -from .rd_file import ResdataFile, openResdataFile -from .rd_3dkw import Resdata3DKW -from .rd_3d_file import Resdata3DFile -from .rd_init_file import ResdataInitFile -from .rd_restart_file import ResdataRestartFile +from .fortio import FortIO as FortIO +from .fortio import openFortIO as openFortIO +from .rd_3d_file import Resdata3DFile as Resdata3DFile +from .rd_3dkw import Resdata3DKW as Resdata3DKW +from .rd_file import ResdataFile as ResdataFile +from .rd_file import openResdataFile as openResdataFile +from .rd_file_view import ResdataFileView as ResdataFileView +from .rd_init_file import ResdataInitFile as ResdataInitFile +from .rd_kw import ResdataKW as ResdataKW +from .rd_restart_file import ResdataRestartFile as ResdataRestartFile diff --git a/python/resdata/resfile/fortio.py b/python/resdata/resfile/fortio.py index e261e15b9..0cbc4afa7 100644 --- a/python/resdata/resfile/fortio.py +++ b/python/resdata/resfile/fortio.py @@ -22,12 +22,12 @@ more extensive wrapping of the fortio implementation would be easy. """ -import ctypes import os from cwrap import BaseCClass -from resdata.util.util import monkey_the_camel + from resdata import ResdataPrototype +from resdata.util.util import monkey_the_camel class FortIO(BaseCClass): 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..e5a60dac1 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 @@ -126,11 +127,11 @@ def report_list(self): # 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( + raise TypeError( # noqa: B904 'Tried get list of report steps from file "%s" - which is not a restart file' % fname ) @@ -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) @@ -422,7 +422,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 diff --git a/python/resdata/resfile/rd_file_view.py b/python/resdata/resfile/rd_file_view.py index 44bb363cf..07b6fcced 100644 --- a/python/resdata/resfile/rd_file_view.py +++ b/python/resdata/resfile/rd_file_view.py @@ -1,9 +1,10 @@ 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 -from resdata.util.util import CTime +from six import string_types + from resdata import ResdataPrototype +from resdata.util.util import CTime, monkey_the_camel class ResdataFileView(BaseCClass): @@ -115,10 +116,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 +141,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 256c90e30..c68831fb4 100644 --- a/python/resdata/resfile/rd_kw.py +++ b/python/resdata/resfile/rd_kw.py @@ -28,16 +28,16 @@ import numpy from cwrap import CFILE, BaseCClass -from resdata import ResdataPrototype, ResDataType, ResdataTypeEnum, ResdataUtil -from resdata.util.util import monkey_the_camel -from .fortio import FortIO +from resdata import ResdataPrototype, ResDataType, ResdataTypeEnum +from resdata.util.util import monkey_the_camel def dump_type_deprecation_warning(): warnings.warn( "ResdataTypeEnum is deprecated. You should instead provide an ResDataType", DeprecationWarning, + stacklevel=1, ) @@ -82,18 +82,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 +310,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 +498,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 +525,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 +565,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 +585,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 +683,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 +750,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 +837,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 +962,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,14 +977,12 @@ 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() @@ -1012,7 +994,7 @@ def header(self): @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 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..661882be5 100644 --- a/python/resdata/rft/__init__.py +++ b/python/resdata/rft/__init__.py @@ -1,8 +1,10 @@ """ - 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 -from .rd_rft_cell import ResdataPLTCell, ResdataRFTCell -from .rd_rft import ResdataRFT, ResdataRFTFile +from .rd_rft import ResdataRFT as ResdataRFT +from .rd_rft import ResdataRFTFile as ResdataRFTFile +from .rd_rft_cell import ResdataPLTCell as ResdataPLTCell +from .rd_rft_cell import ResdataRFTCell as ResdataRFTCell +from .well_trajectory import WellTrajectory as 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/rd_rft_cell.py b/python/resdata/rft/rd_rft_cell.py index bcbdcf78d..c15aea5f7 100644 --- a/python/resdata/rft/rd_rft_cell.py +++ b/python/resdata/rft/rd_rft_cell.py @@ -1,4 +1,5 @@ from cwrap import BaseCClass + from resdata import ResdataPrototype diff --git a/python/resdata/rft/well_trajectory.py b/python/resdata/rft/well_trajectory.py index 7af9b9920..eb2392175 100644 --- a/python/resdata/rft/well_trajectory.py +++ b/python/resdata/rft/well_trajectory.py @@ -1,6 +1,5 @@ -import sys -from os.path import isfile from collections import namedtuple +from os.path import isfile TrajectoryPoint = namedtuple( "TrajectoryPoint", @@ -29,8 +28,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..63eb572f3 100644 --- a/python/resdata/summary/__init__.py +++ b/python/resdata/summary/__init__.py @@ -1,17 +1,20 @@ """ - 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 -import resdata.geometry +import resdata.geometry # noqa: F401 +import resdata.util.util # noqa: F401 -from .rd_cmp import ResdataCmp -from .rd_npv import NPVPriceVector, ResdataNPV -from .rd_sum import Summary # , SummaryVector, SummaryNode, ResdataSMSPECNode -from .rd_sum_keyword_vector import SummaryKeyWordVector -from .rd_sum_node import SummaryNode -from .rd_sum_tstep import SummaryTStep -from .rd_sum_var_type import SummaryVarType -from .rd_sum_vector import SummaryVector +from .rd_cmp import ResdataCmp as ResdataCmp +from .rd_npv import NPVPriceVector as NPVPriceVector +from .rd_npv import ResdataNPV as ResdataNPV +from .rd_sum import ( + Summary as Summary, # , SummaryVector, SummaryNode, ResdataSMSPECNode +) +from .rd_sum_keyword_vector import SummaryKeyWordVector as SummaryKeyWordVector +from .rd_sum_node import SummaryNode as SummaryNode +from .rd_sum_tstep import SummaryTStep as SummaryTStep +from .rd_sum_var_type import SummaryVarType as SummaryVarType +from .rd_sum_vector import SummaryVector as SummaryVector 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..ef2dd932f 100644 --- a/python/resdata/summary/rd_smspec_node.py +++ b/python/resdata/summary/rd_smspec_node.py @@ -1,6 +1,7 @@ from cwrap import BaseCClass -from resdata.util.util import monkey_the_camel + from resdata import ResdataPrototype +from resdata.util.util import monkey_the_camel class ResdataSMSPECNode(BaseCClass): @@ -52,7 +53,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 ae10c0e66..afe21e519 100644 --- a/python/resdata/summary/rd_sum.py +++ b/python/resdata/summary/rd_sum.py @@ -6,29 +6,34 @@ resdata/src directory. """ -import warnings -import numpy +import ctypes import datetime import os.path -import ctypes -import pandas import re -from typing import Sequence, List, Tuple, Optional +import warnings +from typing import List, Optional, Sequence, Tuple + +import numpy +import pandas # Observe that there is some convention conflict with the C code # regarding order of arguments: The C code generally takes the time # index as the first argument and the key/key_index as second # argument. In the python code this order has been reversed. -from cwrap import BaseCClass, CFILE - -from resdata.util.util import monkey_the_camel -from resdata.util.util import StringList, CTime, DoubleVector, TimeVector, IntVector +from cwrap import CFILE, BaseCClass + +from resdata import ResdataPrototype +from resdata.util.util import ( + CTime, + DoubleVector, + IntVector, + StringList, + TimeVector, + monkey_the_camel, +) -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 # , SummaryKeyWordVector @@ -390,8 +395,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 +414,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 +466,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 +654,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 +809,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 +863,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 +881,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 +977,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 +985,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 +995,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 +1103,11 @@ def get_interp_vector(self, key, days_list=None, date_list=None): vector = numpy.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 +1270,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 +1287,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 +1493,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 @@ -1687,8 +1694,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)", bind=False, diff --git a/python/resdata/summary/rd_sum_keyword_vector.py b/python/resdata/summary/rd_sum_keyword_vector.py index fa2ca308e..9374bf535 100644 --- a/python/resdata/summary/rd_sum_keyword_vector.py +++ b/python/resdata/summary/rd_sum_keyword_vector.py @@ -1,14 +1,12 @@ -import numpy -import datetime - # Observe that there is some convention conflict with the C code # regarding order of arguments: The C code generally takes the time # index as the first argument and the key/key_index as second # argument. In the python code this order has been reversed. from cwrap import BaseCClass -from resdata.util.util import monkey_the_camel + from resdata import ResdataPrototype +from resdata.util.util import monkey_the_camel class SummaryKeyWordVector(BaseCClass): diff --git a/python/resdata/summary/rd_sum_tstep.py b/python/resdata/summary/rd_sum_tstep.py index 68699c078..331e373bd 100644 --- a/python/resdata/summary/rd_sum_tstep.py +++ b/python/resdata/summary/rd_sum_tstep.py @@ -1,8 +1,7 @@ from cwrap import BaseCClass -from resdata.util.util import monkey_the_camel -from resdata.util.util import CTime from resdata import ResdataPrototype +from resdata.util.util import monkey_the_camel class SummaryTStep(BaseCClass): 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/enums/__init__.py b/python/resdata/util/enums/__init__.py index ced8c2008..8e426cbd9 100644 --- a/python/resdata/util/enums/__init__.py +++ b/python/resdata/util/enums/__init__.py @@ -1,2 +1,2 @@ -from .rng_init_mode_enum import RngInitModeEnum -from .rng_alg_type_enum import RngAlgTypeEnum +from .rng_alg_type_enum import RngAlgTypeEnum as RngAlgTypeEnum +from .rng_init_mode_enum import RngInitModeEnum as RngInitModeEnum diff --git a/python/resdata/util/test/__init__.py b/python/resdata/util/test/__init__.py index d42c8527b..c9fd52fb1 100644 --- a/python/resdata/util/test/__init__.py +++ b/python/resdata/util/test/__init__.py @@ -1,10 +1,11 @@ -from .test_run import TestRun -from .test_run import path_exists -from .extended_testcase import ExtendedTestCase -from .source_enumerator import SourceEnumerator -from .test_area import TestArea, TestAreaContext -from .resdata_test_runner import ResdataTestRunner -from .path_context import PathContext -from .lint_test_case import LintTestCase -from .import_test_case import ImportTestCase -from .debug_msg import debug_msg +from .debug_msg import debug_msg as debug_msg +from .extended_testcase import ExtendedTestCase as ExtendedTestCase +from .import_test_case import ImportTestCase as ImportTestCase +from .lint_test_case import LintTestCase as LintTestCase +from .path_context import PathContext as PathContext +from .resdata_test_runner import ResdataTestRunner as ResdataTestRunner +from .source_enumerator import SourceEnumerator as SourceEnumerator +from .test_area import TestArea as TestArea +from .test_area import TestAreaContext as TestAreaContext +from .test_run import TestRun as TestRun +from .test_run import path_exists as path_exists diff --git a/python/resdata/util/test/extended_testcase.py b/python/resdata/util/test/extended_testcase.py index d1c1e1caf..c130bd7f9 100644 --- a/python/resdata/util/test/extended_testcase.py +++ b/python/resdata/util/test/extended_testcase.py @@ -1,18 +1,16 @@ -import numbers import os import os.path -import traceback import sys +import traceback try: from unittest2 import TestCase except ImportError: from unittest import TestCase -from .source_enumerator import SourceEnumerator -from resdata.util.util import installAbortSignals -from resdata.util.util import Version +from resdata.util.util import Version, installAbortSignals +from .source_enumerator import SourceEnumerator # Function wrapper which can be used to add decorator @log_test to test # methods. When a test has been decorated with @log_test it will print @@ -130,8 +128,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 +196,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/lint_test_case.py b/python/resdata/util/test/lint_test_case.py index f743fcde1..6bcc83081 100644 --- a/python/resdata/util/test/lint_test_case.py +++ b/python/resdata/util/test/lint_test_case.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -import sys import fnmatch import os +import sys import unittest try: diff --git a/python/resdata/util/test/mock/__init__.py b/python/resdata/util/test/mock/__init__.py index 01d5fc1ea..73a89c289 100644 --- a/python/resdata/util/test/mock/__init__.py +++ b/python/resdata/util/test/mock/__init__.py @@ -1 +1 @@ -from .rd_sum_mock import createSummary +from .rd_sum_mock import createSummary as createSummary 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..68159e464 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 @@ -6,7 +5,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 +19,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 +31,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_area.py b/python/resdata/util/test/test_area.py index 29c75c0c2..ecac0fa0b 100644 --- a/python/resdata/util/test/test_area.py +++ b/python/resdata/util/test/test_area.py @@ -1,6 +1,7 @@ import os.path from cwrap import BaseCClass + from resdata import ResdataPrototype diff --git a/python/resdata/util/test/test_run.py b/python/resdata/util/test/test_run.py index 59fad8ffe..c01289a7b 100644 --- a/python/resdata/util/test/test_run.py +++ b/python/resdata/util/test/test_run.py @@ -1,7 +1,8 @@ -import random +import argparse import os.path +import random import subprocess -import argparse + from .test_area import TestAreaContext @@ -17,7 +18,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..3a2064c12 100644 --- a/python/resdata/util/util/__init__.py +++ b/python/resdata/util/util/__init__.py @@ -23,31 +23,6 @@ from __future__ import absolute_import, division, print_function, unicode_literals -import resdata -from cwrap import Prototype - - -from .version import Version, ResdataVersion - -from resdata.util.enums import RngAlgTypeEnum, RngInitModeEnum - -from .ctime import CTime - -from .permutation_vector import PermutationVector -from .vector_template import VectorTemplate -from .double_vector import DoubleVector -from .int_vector import IntVector -from .bool_vector import BoolVector -from .time_vector import TimeVector -from .stringlist import StringList -from .rng import RandomNumberGenerator -from .lookup_table import LookupTable -from .hash import Hash, StringHash, DoubleHash, IntegerHash -from .thread_pool import ThreadPool -from .install_abort_signals import installAbortSignals, updateAbortSignals -from .cwd_context import CWDContext - - ### ### monkey_the_camel is a function temporarily added to resdata while we are in ### the process of changing camelCase function names to snake_case function @@ -56,10 +31,36 @@ ### See https://github.com/Equinor/resdata/issues/142 for a discussion and for ### usage. ### - import os import warnings +from cwrap import Prototype as Prototype + +import resdata as resdata +from resdata.util.enums import RngAlgTypeEnum as RngAlgTypeEnum +from resdata.util.enums import RngInitModeEnum as RngInitModeEnum + +from .bool_vector import BoolVector as BoolVector +from .ctime import CTime as CTime +from .cwd_context import CWDContext as CWDContext +from .double_vector import DoubleVector as DoubleVector +from .hash import DoubleHash as DoubleHash +from .hash import Hash as Hash +from .hash import IntegerHash as IntegerHash +from .hash import StringHash as StringHash +from .install_abort_signals import installAbortSignals as installAbortSignals +from .install_abort_signals import updateAbortSignals as updateAbortSignals +from .int_vector import IntVector as IntVector +from .lookup_table import LookupTable as LookupTable +from .permutation_vector import PermutationVector as PermutationVector +from .rng import RandomNumberGenerator as RandomNumberGenerator +from .stringlist import StringList as StringList +from .thread_pool import ThreadPool as ThreadPool +from .time_vector import TimeVector as TimeVector +from .vector_template import VectorTemplate as VectorTemplate +from .version import ResdataVersion as ResdataVersion +from .version import Version as Version + __cc = os.environ.get("RDWARNING", None) # __cc in (None, 'user', 'dev', 'hard') @@ -72,7 +73,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/hash.py b/python/resdata/util/util/hash.py index 18e8dc13e..5cbb6a07b 100644 --- a/python/resdata/util/util/hash.py +++ b/python/resdata/util/util/hash.py @@ -1,8 +1,8 @@ from ctypes import c_void_p from cwrap import BaseCClass + from resdata import ResdataPrototype -from resdata.util.util import StringList class Hash(BaseCClass): diff --git a/python/resdata/util/util/install_abort_signals.py b/python/resdata/util/util/install_abort_signals.py index 56439e870..bb95f2bd7 100644 --- a/python/resdata/util/util/install_abort_signals.py +++ b/python/resdata/util/util/install_abort_signals.py @@ -1,6 +1,7 @@ -from resdata import ResdataPrototype -import sys import os +import sys + +from resdata import ResdataPrototype def installAbortSignals(): 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/permutation_vector.py b/python/resdata/util/util/permutation_vector.py index 0a5bea8b5..a6f2e62e3 100644 --- a/python/resdata/util/util/permutation_vector.py +++ b/python/resdata/util/util/permutation_vector.py @@ -1,4 +1,5 @@ from cwrap import BaseCClass + from resdata import ResdataPrototype diff --git a/python/resdata/util/util/rng.py b/python/resdata/util/util/rng.py index 17274159a..f8bf461b2 100644 --- a/python/resdata/util/util/rng.py +++ b/python/resdata/util/util/rng.py @@ -1,8 +1,9 @@ import os.path from cwrap import BaseCClass + from resdata import ResdataPrototype -from resdata.util.enums import RngInitModeEnum, RngAlgTypeEnum +from resdata.util.enums import RngAlgTypeEnum, RngInitModeEnum class RandomNumberGenerator(BaseCClass): diff --git a/python/resdata/util/util/stringlist.py b/python/resdata/util/util/stringlist.py index 8cd6b2f55..3919760b9 100644 --- a/python/resdata/util/util/stringlist.py +++ b/python/resdata/util/util/stringlist.py @@ -16,9 +16,10 @@ hardly need to notice that the StringList class is at play. """ -from resdata import ResdataPrototype from cwrap import BaseCClass +from resdata import ResdataPrototype + class StringList(BaseCClass): TYPE_NAME = "rd_stringlist" 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..14442628e 100644 --- a/python/resdata/util/util/time_vector.py +++ b/python/resdata/util/util/time_vector.py @@ -2,7 +2,7 @@ import re from resdata import ResdataPrototype -from resdata.util.util import VectorTemplate, CTime +from resdata.util.util import CTime, VectorTemplate class TimeVector(VectorTemplate): @@ -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..c950d25cd 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/__init__.py b/python/resdata/well/__init__.py index 6a3710037..d40b8bb02 100644 --- a/python/resdata/well/__init__.py +++ b/python/resdata/well/__init__.py @@ -1,13 +1,14 @@ -import resdata -import resdata.util.util -import resdata.geometry +import redata.geometry # noqa: F401 -from cwrap import Prototype +import resdata +import resdata.util.util # noqa: F401 -from .well_type_enum import WellType -from .well_connection_direction_enum import WellConnectionDirection -from .well_connection import WellConnection -from .well_segment import WellSegment -from .well_state import WellState -from .well_time_line import WellTimeLine -from .well_info import WellInfo +from .well_connection import WellConnection as WellConnection +from .well_connection_direction_enum import ( + WellConnectionDirection as WellConnectionDirection, +) +from .well_info import WellInfo as WellInfo +from .well_segment import WellSegment as WellSegment +from .well_state import WellState as WellState +from .well_time_line import WellTimeLine as WellTimeLine +from .well_type_enum import WellType as WellType diff --git a/python/resdata/well/well_connection.py b/python/resdata/well/well_connection.py index 005f07ea5..f20d7f059 100644 --- a/python/resdata/well/well_connection.py +++ b/python/resdata/well/well_connection.py @@ -1,4 +1,5 @@ from cwrap import BaseCClass + from resdata import ResdataPrototype from resdata.well import WellConnectionDirection diff --git a/python/resdata/well/well_info.py b/python/resdata/well/well_info.py index d86e9e4f3..a3d50f568 100644 --- a/python/resdata/well/well_info.py +++ b/python/resdata/well/well_info.py @@ -1,9 +1,9 @@ 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 +from resdata.resfile.rd_file import ResdataFile class WellInfo(BaseCClass): diff --git a/python/resdata/well/well_segment.py b/python/resdata/well/well_segment.py index 7c4b7e684..13ad21e98 100644 --- a/python/resdata/well/well_segment.py +++ b/python/resdata/well/well_segment.py @@ -1,4 +1,5 @@ from cwrap import BaseCClass + from resdata import ResdataPrototype diff --git a/python/resdata/well/well_state.py b/python/resdata/well/well_state.py index f0962bd3d..6856c177e 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): @@ -163,10 +161,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/resdata/well/well_time_line.py b/python/resdata/well/well_time_line.py index f77f2b741..3d46c2d8e 100644 --- a/python/resdata/well/well_time_line.py +++ b/python/resdata/well/well_time_line.py @@ -1,6 +1,6 @@ from cwrap import BaseCClass + from resdata import ResdataPrototype -from resdata.well import WellState class WellTimeLine(BaseCClass): diff --git a/python/tests/__init__.py b/python/tests/__init__.py index 709e3de3f..50022f582 100644 --- a/python/tests/__init__.py +++ b/python/tests/__init__.py @@ -1,11 +1,9 @@ import os.path -import types -from resdata.util.test import ExtendedTestCase from functools import wraps -from functools import partial -import unittest from unittest import SkipTest +from resdata.util.test import ExtendedTestCase + def source_root(): src = "@CMAKE_CURRENT_SOURCE_DIR@/../.." @@ -61,14 +59,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/bin_tests/test_summary_resample.py b/python/tests/bin_tests/test_summary_resample.py index 307ef0cf8..cdca5bd94 100644 --- a/python/tests/bin_tests/test_summary_resample.py +++ b/python/tests/bin_tests/test_summary_resample.py @@ -2,10 +2,10 @@ 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 + from tests import ResdataTest @@ -83,7 +83,7 @@ def test_run_default(self): output_case.get_data_start_time(), refcase.get_data_start_time() ) self.assertEqual(output_case.get_end_time(), refcase.get_end_time()) - time_points = output_case.alloc_time_vector(False) + _time_points = output_case.alloc_time_vector(False) t1 = output_case.alloc_time_vector(False) t2 = refcase.alloc_time_vector(False) self.assertEqual(t1, t2) diff --git a/python/tests/geometry_tests/test_convex_hull.py b/python/tests/geometry_tests/test_convex_hull.py index e58d6ca91..f68e2cb1d 100644 --- a/python/tests/geometry_tests/test_convex_hull.py +++ b/python/tests/geometry_tests/test_convex_hull.py @@ -1,4 +1,5 @@ from resdata.geometry.geometry_tools import GeometryTools + from tests import ResdataTest diff --git a/python/tests/geometry_tests/test_cpolyline.py b/python/tests/geometry_tests/test_cpolyline.py index cdf737f71..90aae41e8 100644 --- a/python/tests/geometry_tests/test_cpolyline.py +++ b/python/tests/geometry_tests/test_cpolyline.py @@ -1,8 +1,7 @@ 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..73180263f 100644 --- a/python/tests/geometry_tests/test_cpolyline_collection.py +++ b/python/tests/geometry_tests/test_cpolyline_collection.py @@ -1,10 +1,7 @@ -import gc +from resdata.geometry import CPolyline, CPolylineCollection +from resdata.util.util import DoubleVector -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 class CPolylineCollectionTest(ResdataTest): @@ -73,7 +70,7 @@ def test_gc_polyline(self): # safely accessed, even after the polyline objects p1 and p2 # from create_collection() have gone out of scope. c = self.create_collection() - v = DoubleVector(initial_size=10000) + _v = DoubleVector(initial_size=10000) p1 = c[0] tail = p1[-1] diff --git a/python/tests/geometry_tests/test_geo_pointset.py b/python/tests/geometry_tests/test_geo_pointset.py index 49da25663..af0aebd9e 100644 --- a/python/tests/geometry_tests/test_geo_pointset.py +++ b/python/tests/geometry_tests/test_geo_pointset.py @@ -1,5 +1,5 @@ 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..53bf9d616 100644 --- a/python/tests/geometry_tests/test_geo_region.py +++ b/python/tests/geometry_tests/test_geo_region.py @@ -1,5 +1,5 @@ -from resdata.geometry import GeoRegion, GeoPointset, CPolyline, Surface -from resdata.util.test import TestAreaContext +from resdata.geometry import CPolyline, GeoPointset, GeoRegion, Surface + 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..46b1ad1e0 100644 --- a/python/tests/geometry_tests/test_geometry_tools.py +++ b/python/tests/geometry_tests/test_geometry_tools.py @@ -1,8 +1,7 @@ import math -from resdata.geometry import Polyline, GeometryTools, CPolyline -from resdata.geometry.xyz_io import XYZIo -from resdata.util.test import TestAreaContext +from resdata.geometry import CPolyline, GeometryTools, Polyline + from tests import ResdataTest @@ -26,7 +25,7 @@ def test_distance(self): def test_join__polylines(self): l1 = Polyline(init_points=[(0, 1), (1, 1)]) l2 = CPolyline(init_points=[(2, -1), (2, 0)]) - l3 = CPolyline(init_points=[(2, 2), (2, 3)]) + _l3 = CPolyline(init_points=[(2, 2), (2, 3)]) l4 = Polyline() l5 = CPolyline(init_points=[(0.5, 0), (0.5, 2)]) diff --git a/python/tests/geometry_tests/test_intersection.py b/python/tests/geometry_tests/test_intersection.py index 04398d198..c72749e27 100644 --- a/python/tests/geometry_tests/test_intersection.py +++ b/python/tests/geometry_tests/test_intersection.py @@ -1,4 +1,5 @@ from resdata.geometry import GeometryTools + from tests import ResdataTest diff --git a/python/tests/geometry_tests/test_point_in_polygon.py b/python/tests/geometry_tests/test_point_in_polygon.py index a2e22863a..bdd34dce6 100644 --- a/python/tests/geometry_tests/test_point_in_polygon.py +++ b/python/tests/geometry_tests/test_point_in_polygon.py @@ -1,5 +1,6 @@ from resdata.geometry.geometry_tools import GeometryTools from resdata.geometry.polyline import Polyline + from tests import ResdataTest diff --git a/python/tests/geometry_tests/test_polygon_slicing.py b/python/tests/geometry_tests/test_polygon_slicing.py index 30af14f25..393ffcca0 100644 --- a/python/tests/geometry_tests/test_polygon_slicing.py +++ b/python/tests/geometry_tests/test_polygon_slicing.py @@ -1,5 +1,7 @@ from math import sqrt + from resdata.geometry.geometry_tools import GeometryTools + from tests import ResdataTest diff --git a/python/tests/geometry_tests/test_polyline.py b/python/tests/geometry_tests/test_polyline.py index df39ccb4e..776d521e4 100644 --- a/python/tests/geometry_tests/test_polyline.py +++ b/python/tests/geometry_tests/test_polyline.py @@ -1,6 +1,7 @@ -from resdata.geometry import Polyline, GeometryTools +from resdata.geometry import GeometryTools, Polyline from resdata.geometry.xyz_io import XYZIo from resdata.util.test import TestAreaContext + from tests import ResdataTest @@ -101,7 +102,7 @@ def test_closed(self): self.assertTrue(pl.isClosed()) def test_save(self): - with TestAreaContext("polyline/fwrite") as work_area: + with TestAreaContext("polyline/fwrite"): p1 = Polyline(init_points=[(1, 0), (1, 1), (1, 2)]) p2 = Polyline(init_points=[(1, 0), (1, 1), (1, 2)]) self.assertTrue(p1 == p2) diff --git a/python/tests/geometry_tests/test_surface.py b/python/tests/geometry_tests/test_surface.py index e23691a07..fdff9c125 100644 --- a/python/tests/geometry_tests/test_surface.py +++ b/python/tests/geometry_tests/test_surface.py @@ -1,6 +1,8 @@ import random + from resdata.geometry import Surface from resdata.util.test import TestAreaContext + from tests import ResdataTest @@ -55,8 +57,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) @@ -78,10 +80,10 @@ def test_create(self): self.assertEqual(len(s), 49 * 79) with self.assertRaises(IndexError): - v = s[49 * 79] + _v = s[49 * 79] with self.assertRaises(TypeError): - v = s["KEY"] + _v = s["KEY"] self.assertEqual(s[0], 0.0051) self.assertEqual(s[-1], -0.0014) @@ -151,7 +153,7 @@ def test_ops(self): s2 = Surface(self.surface_valid2) with self.assertRaises(ValueError): - s3 = s1 + s2 + _s3 = s1 + s2 s4 = s1 + s0 for v in s4: @@ -164,7 +166,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/create_restart.py b/python/tests/rd_tests/create_restart.py index a01ddcdd5..9bfe7bd0f 100644 --- a/python/tests/rd_tests/create_restart.py +++ b/python/tests/rd_tests/create_restart.py @@ -1,5 +1,5 @@ from resdata import ResDataType -from resdata.resfile import ResdataKW, openFortIO, FortIO +from resdata.resfile import FortIO, ResdataKW, openFortIO def create_restart(grid, case, p1, p2=None, rporv1=None, rporv2=None): diff --git a/python/tests/rd_tests/test_cell.py b/python/tests/rd_tests/test_cell.py index 4bea8a6a6..6c73362d0 100644 --- a/python/tests/rd_tests/test_cell.py +++ b/python/tests/rd_tests/test_cell.py @@ -1,7 +1,7 @@ #!/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_debug.py b/python/tests/rd_tests/test_debug.py index d836cf296..130efe48d 100644 --- a/python/tests/rd_tests/test_debug.py +++ b/python/tests/rd_tests/test_debug.py @@ -1,4 +1,5 @@ from resdata.util.test import debug_msg + from tests import ResdataTest diff --git a/python/tests/rd_tests/test_deprecation.py b/python/tests/rd_tests/test_deprecation.py index d754f1b5f..f9992173f 100644 --- a/python/tests/rd_tests/test_deprecation.py +++ b/python/tests/rd_tests/test_deprecation.py @@ -1,15 +1,11 @@ #!/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 @@ -24,7 +20,7 @@ class Deprecation_2_1_Test(ResdataTest): class Deprecation_2_0_Test(ResdataTest): def test_ResdataFile_name_property(self): - with TestAreaContext("name") as t: + with TestAreaContext("name"): kw = ResdataKW("TEST", 3, ResDataType.RD_INT) with openFortIO("TEST", mode=FortIO.WRITE_MODE) as f: kw.fwrite(f) @@ -35,4 +31,4 @@ def test_ResdataFile_name_property(self): class Deprecation_1_9_Test(ResdataTest): def test_ResdataRegion_properties(self): grid = GridGenerator.createRectangular((10, 10, 10), (1, 1, 1)) - region = ResdataRegion(grid, False) + _region = ResdataRegion(grid, False) diff --git a/python/tests/rd_tests/test_equinor_faults.py b/python/tests/rd_tests/test_equinor_faults.py index 15baad8be..a55d30919 100644 --- a/python/tests/rd_tests/test_equinor_faults.py +++ b/python/tests/rd_tests/test_equinor_faults.py @@ -1,16 +1,12 @@ #!/usr/bin/env python -try: - from unittest2 import skipIf -except ImportError: - from unittest import skipIf -from cwrap import open as copen -import time +from cwrap import open as copen 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 Fault, FaultCollection +from resdata.resfile import ResdataKW + 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 0fc5734c9..03376a053 100644 --- a/python/tests/rd_tests/test_fault_blocks.py +++ b/python/tests/rd_tests/test_fault_blocks.py @@ -1,13 +1,12 @@ #!/usr/bin/env python -from unittest import skipIf import cwrap - from resdata import ResDataType -from resdata.resfile import ResdataKW +from resdata.geometry import CPolylineCollection, Polyline from resdata.grid import Grid, ResdataRegion from resdata.grid.faults import FaultBlock, FaultBlockLayer, FaultCollection -from resdata.geometry import Polyline, CPolylineCollection +from resdata.resfile import ResdataKW from resdata.util.test import TestAreaContext + from tests import ResdataTest @@ -43,7 +42,7 @@ def test_fault_block(self): self.assertEqual(layer, block.getParentLayer()) def test_get_ijk(self): - with TestAreaContext("python/fault_block_layer/neighbour") as work_area: + with TestAreaContext("python/fault_block_layer/neighbour"): with open("kw.grdecl", "w") as fileH: fileH.write("FAULTBLK \n") fileH.write("1 1 1 0 0\n") @@ -72,7 +71,7 @@ def test_get_ijk(self): layer[5, 5] def test_neighbours(self): - with TestAreaContext("python/fault_block_layer/neighbour") as work_area: + with TestAreaContext("python/fault_block_layer/neighbour"): with open("kw.grdecl", "w") as fileH: fileH.write("FAULTBLK \n") fileH.write("1 1 1 0 0\n") @@ -233,7 +232,7 @@ def test_fault_block_edge(self): g = i + j * grid.getNX() kw[g] = 1 - layer = FaultBlockLayer(grid, 0) + _layer = FaultBlockLayer(grid, 0) # with self.assertRaises: # layer.getEdgePolygon( ) @@ -255,7 +254,7 @@ def test_fault_block_layer(self): self.assertEqual(2, len(layer)) with self.assertRaises(TypeError): - ls = layer["JJ"] + _ls = layer["JJ"] l = [] for blk in layer: @@ -272,7 +271,7 @@ def test_fault_block_layer(self): assert list(l1.get_region_list()) == [] with self.assertRaises(IndexError): - l2 = layer[2] + _l2 = layer[2] self.assertEqual(True, 1 in layer) self.assertEqual(True, 2 in layer) @@ -303,7 +302,7 @@ def test_fault_block_layer(self): blk2 = layer.addBlock(2) self.assertEqual(len(layer), 2) - blk3 = layer.addBlock() + _blk3 = layer.addBlock() self.assertEqual(len(layer), 3) layer.addBlock(100) @@ -333,7 +332,7 @@ def test_fault_block_layer(self): self.assertEqual([1, 2, 3], list(fault_block.getRegionList())) def test_add_polyline_barrier1(self): - grid = Grid.createRectangular((4, 1, 1), (1, 1, 1)) + _grid = Grid.createRectangular((4, 1, 1), (1, 1, 1)) layer = FaultBlockLayer(self.grid, 0) polyline = Polyline(init_points=[(1.99, 0.001), (2.01, 0.99)]) @@ -349,7 +348,7 @@ def test_add_polyline_barrier1(self): self.assertFalse(geo_layer.cellContact(p1, p2)) def test_add_polyline_barrier2(self): - grid = Grid.createRectangular((10, 10, 1), (1, 1, 1)) + _grid = Grid.createRectangular((10, 10, 1), (1, 1, 1)) layer = FaultBlockLayer(self.grid, 0) polyline = Polyline(init_points=[(0.1, 0.9), (8.9, 0.9), (8.9, 8.9)]) @@ -359,7 +358,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_fault_blocks_equinor.py b/python/tests/rd_tests/test_fault_blocks_equinor.py index 3ab3b203b..fb6e27aa8 100644 --- a/python/tests/rd_tests/test_fault_blocks_equinor.py +++ b/python/tests/rd_tests/test_fault_blocks_equinor.py @@ -1,16 +1,12 @@ #!/usr/bin/env python -try: - from unittest2 import skipIf -except ImportError: - from unittest import skipIf +from cwrap import open as copen 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 resdata.resfile import ResdataKW -from cwrap import open as copen +from tests import ResdataTest, equinor_test @equinor_test() @@ -25,4 +21,4 @@ def test_load(self): faultBlocks = FaultBlockLayer(self.grid, k) faultBlocks.scanKeyword(self.kw) for block in faultBlocks: - centroid = block.getCentroid() + _centroid = block.getCentroid() diff --git a/python/tests/rd_tests/test_faults.py b/python/tests/rd_tests/test_faults.py index abf5dab6a..e1cf17441 100644 --- a/python/tests/rd_tests/test_faults.py +++ b/python/tests/rd_tests/test_faults.py @@ -1,20 +1,18 @@ #!/usr/bin/env python -from unittest import skipIf -import time -from resdata import util from resdata import ResDataType -from resdata.resfile import ResdataKW +from resdata.geometry import CPolyline, Polyline from resdata.grid import Grid from resdata.grid.faults import ( - FaultCollection, Fault, + FaultBlockLayer, + FaultCollection, FaultLine, FaultSegment, - FaultBlockLayer, ) +from resdata.resfile import ResdataKW from resdata.util.test import TestAreaContext -from resdata.geometry import Polyline, CPolyline + from tests import ResdataTest @@ -47,46 +45,46 @@ def test_empty_collection(self): self.assertFalse(faults.hasFault("FX")) with self.assertRaises(TypeError): - f = faults[[]] + _f = faults[[]] with self.assertRaises(KeyError): - f = faults["FX"] + _f = faults["FX"] with self.assertRaises(IndexError): - f = faults[0] + _f = faults[0] self.assertFalse("NAME" in faults) def test_collection_invalid_arg(self): with self.assertRaises(ValueError): - faults = FaultCollection(self.faults1) + _faults = FaultCollection(self.faults1) with self.assertRaises(ValueError): - faults = FaultCollection(self.faults1, self.faults2) + _faults = FaultCollection(self.faults1, self.faults2) def test_splitLine(self): faults = FaultCollection(self.grid) with self.assertRaises(ValueError): # Not slash terminated - t = faults.splitLine( + _t = faults.splitLine( "'F1' 149 149 29 29 1 43 'Y'" ) with self.assertRaises(ValueError): # Not integer - t = faults.splitLine( + _t = faults.splitLine( "'F1' 149 149 29 29 1 43X 'Y' /" ) with self.assertRaises(ValueError): # Missing item - t = faults.splitLine( + _t = faults.splitLine( "'F1' 149 29 29 1 43 'Y' /" ) with self.assertRaises(ValueError): # Quote problem - t = faults.splitLine( + _t = faults.splitLine( "'F1 149 149 29 29 1 43 'X' /" ) @@ -94,8 +92,8 @@ def test_empty_fault(self): f = Fault(self.grid, "NAME") self.assertEqual("NAME", f.getName()) - with self.assertRaises(Exception): - g = f["Key"] + with self.assertRaises(Exception): # noqa: B017 + _g = f["Key"] def test_empty_faultLine(self): fl = FaultLine(self.grid, 10) @@ -103,10 +101,10 @@ def test_empty_faultLine(self): self.assertEqual(0, len(fl)) with self.assertRaises(TypeError): - f = fl["Test"] + _f = fl["Test"] with self.assertRaises(IndexError): - f = fl[0] + _f = fl[0] def test_faultLine_center(self): nx = 10 @@ -409,7 +407,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_fk_user_data.py b/python/tests/rd_tests/test_fk_user_data.py index f468cc71d..83870d200 100644 --- a/python/tests/rd_tests/test_fk_user_data.py +++ b/python/tests/rd_tests/test_fk_user_data.py @@ -1,6 +1,6 @@ #!/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_fortio.py b/python/tests/rd_tests/test_fortio.py index e2161a0df..9a9f8830d 100755 --- a/python/tests/rd_tests/test_fortio.py +++ b/python/tests/rd_tests/test_fortio.py @@ -1,22 +1,24 @@ #!/usr/bin/env python import os -import cwrap from random import randint + +import cwrap from resdata import ResDataType -from resdata.resfile import FortIO, ResdataKW, openFortIO, ResdataFile +from resdata.resfile import FortIO, ResdataFile, ResdataKW, openFortIO from resdata.util.test import TestAreaContext + from tests import ResdataTest class FortIOTest(ResdataTest): def test_open_write(self): with TestAreaContext("python/fortio/write"): - f = FortIO("newfile", FortIO.WRITE_MODE) + _f = FortIO("newfile", FortIO.WRITE_MODE) self.assertTrue(os.path.exists("newfile")) def test_noex(self): with self.assertRaises(IOError): - f = FortIO("odes_not_exist", FortIO.READ_MODE) + _f = FortIO("odes_not_exist", FortIO.READ_MODE) def test_kw(self): kw1 = ResdataKW("KW1", 2, ResDataType.RD_INT) @@ -50,16 +52,15 @@ def test_truncate(self): kw2[0] = 113 kw2[1] = 335 - with TestAreaContext("python/fortio/ftruncate") as t: + with TestAreaContext("python/fortio/ftruncate"): with openFortIO("file", mode=FortIO.WRITE_MODE) as f: kw1.fwrite(f) pos1 = f.getPosition() 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) @@ -73,15 +74,15 @@ def test_truncate(self): def test_fortio_creation(self): with TestAreaContext("python/fortio/create"): w = FortIO("test", FortIO.WRITE_MODE) - rw = FortIO("test", FortIO.READ_AND_WRITE_MODE) - r = FortIO("test", FortIO.READ_MODE) - a = FortIO("test", FortIO.APPEND_MODE) + _rw = FortIO("test", FortIO.READ_AND_WRITE_MODE) + _r = FortIO("test", FortIO.READ_MODE) + _a = FortIO("test", FortIO.APPEND_MODE) w.close() w.close() # should not fail def test_context(self): - with TestAreaContext("python/fortio/context") as t: + with TestAreaContext("python/fortio/context"): kw1 = ResdataKW("KW", 2456, ResDataType.RD_FLOAT) for i in range(len(kw1)): kw1[i] = randint(0, 1000) diff --git a/python/tests/rd_tests/test_geertsma.py b/python/tests/rd_tests/test_geertsma.py index 712541a65..6cd03062b 100644 --- a/python/tests/rd_tests/test_geertsma.py +++ b/python/tests/rd_tests/test_geertsma.py @@ -1,16 +1,16 @@ import datetime + +import numpy as np import pytest from resdata import ResDataType -from resdata.resfile import ResdataKW, openFortIO, FortIO, ResdataFile -from resdata.grid import Grid from resdata.gravimetry import ResdataSubsidence - +from resdata.grid import Grid +from resdata.resfile import FortIO, ResdataFile, ResdataKW, openFortIO from resdata.util.test import TestAreaContext + from tests import ResdataTest from tests.rd_tests.create_restart import create_restart -import numpy as np - def create_init(grid, case): poro = ResdataKW("PORO", grid.getNumActive(), ResDataType.RD_FLOAT) @@ -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_grav.py b/python/tests/rd_tests/test_grav.py index ff7a15725..fc477a809 100644 --- a/python/tests/rd_tests/test_grav.py +++ b/python/tests/rd_tests/test_grav.py @@ -1,11 +1,12 @@ import datetime + from resdata import ResDataType -from resdata.resfile import ResdataKW, ResdataFile, openFortIO, FortIO -from resdata.grid import Grid from resdata.gravimetry import ResdataGrav +from resdata.grid import Grid +from resdata.resfile import FortIO, ResdataFile, ResdataKW, openFortIO 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_grdecl.py b/python/tests/rd_tests/test_grdecl.py index f9e7c733a..b82f1e458 100644 --- a/python/tests/rd_tests/test_grdecl.py +++ b/python/tests/rd_tests/test_grdecl.py @@ -1,6 +1,5 @@ -from numpy import allclose - import cwrap +from numpy import allclose from resdata.resfile import ResdataKW diff --git a/python/tests/rd_tests/test_grdrd_equinor.py b/python/tests/rd_tests/test_grdrd_equinor.py index 05113ad4c..8c46dbafc 100755 --- a/python/tests/rd_tests/test_grdrd_equinor.py +++ b/python/tests/rd_tests/test_grdrd_equinor.py @@ -1,10 +1,11 @@ #!/usr/bin/env python import os -from resdata.resfile import ResdataKW, Resdata3DKW -from resdata.grid import Grid -from tests import ResdataTest, equinor_test from cwrap import open as copen +from resdata.grid import Grid +from resdata.resfile import Resdata3DKW, ResdataKW + +from tests import ResdataTest, equinor_test @equinor_test() @@ -57,7 +58,7 @@ def test_fseek(self): file.close() file = copen(self.src_file, "r") - kw1 = ResdataKW.read_grdecl(file, "PERMX") + _kw1 = ResdataKW.read_grdecl(file, "PERMX") self.assertFalse(ResdataKW.fseek_grdecl(file, "PERMX")) self.assertTrue(ResdataKW.fseek_grdecl(file, "PERMX", rewind=True)) file.close() diff --git a/python/tests/rd_tests/test_grid.py b/python/tests/rd_tests/test_grid.py index 4d8e734c1..9e495d287 100644 --- a/python/tests/rd_tests/test_grid.py +++ b/python/tests/rd_tests/test_grid.py @@ -1,18 +1,18 @@ #!/usr/bin/env python +import functools +import itertools import os.path from unittest import skip -import itertools -import functools -from numpy import linspace, allclose import cwrap - -from resdata.util.util import IntVector, DoubleVector +from numpy import allclose, linspace from resdata import ResDataType, UnitSystem -from resdata.resfile import ResdataKW, ResdataFile from resdata.grid import Grid from resdata.grid import GridGenerator as GridGen +from resdata.resfile import ResdataFile, ResdataKW from resdata.util.test import TestAreaContext +from resdata.util.util import DoubleVector, IntVector + from tests import ResdataTest # This dict is used to verify that corners are mapped to the correct @@ -192,7 +192,7 @@ def test_oom_grid(self): nz = 2000 with self.assertRaises(MemoryError): - grid = GridGen.createRectangular((nx, ny, nz), (1, 1, 1)) + _grid = GridGen.createRectangular((nx, ny, nz), (1, 1, 1)) def test_posXYEdge(self): nx = 10 @@ -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): @@ -431,7 +431,7 @@ def test_compressed_copy(self): grid = GridGen.createRectangular((nx, ny, nz), (1, 1, 1)) kw1 = ResdataKW("KW", 1001, ResDataType.RD_INT) with self.assertRaises(ValueError): - cp = grid.compressedKWCopy(kw1) + _cp = grid.compressedKWCopy(kw1) def test_dxdydz(self): nx = 10 diff --git a/python/tests/rd_tests/test_grid_equinor.py b/python/tests/rd_tests/test_grid_equinor.py index d433fa8a3..ae4422441 100755 --- a/python/tests/rd_tests/test_grid_equinor.py +++ b/python/tests/rd_tests/test_grid_equinor.py @@ -6,15 +6,15 @@ except ImportError: 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 cwrap import open as copen +from resdata import ResDataType from resdata.grid import Grid -from resdata.util.util import DoubleVector, IntVector +from resdata.resfile import ResdataKW, openResdataFile from resdata.util.test import TestAreaContext +from resdata.util.util import DoubleVector, IntVector + from tests import ResdataTest, equinor_test @@ -152,14 +152,14 @@ def test_create(self): def test_grdecl_load(self): with self.assertRaises(IOError): - grid = Grid.loadFromGrdecl("/file/does/not/exists") + _grid = Grid.loadFromGrdecl("/file/does/not/exists") with TestAreaContext("python/grid-test/grdeclLoad"): with open("grid.grdecl", "w") as f: f.write("Hei ...") with self.assertRaises(ValueError): - grid = Grid.loadFromGrdecl("grid.grdecl") + _grid = Grid.loadFromGrdecl("grid.grdecl") actnum = IntVector(default_value=1, initial_size=1000) actnum[0] = 0 @@ -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)) @@ -192,7 +191,7 @@ def test_ACTNUM(self): def test_time(self): t0 = time.perf_counter() - g1 = Grid(self.egrid_file()) + _g1 = Grid(self.egrid_file()) t1 = time.perf_counter() t = t1 - t0 self.assertTrue(t < 1.0) @@ -217,7 +216,7 @@ def test_save(self): def test_raise_IO_error(self): with self.assertRaises(IOError): - g = Grid("/does/not/exist.EGRID") + _g = Grid("/does/not/exist.EGRID") def test_boundingBox(self): grid = Grid.createRectangular((10, 10, 10), (1, 1, 1)) @@ -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_equinor_coarse.py b/python/tests/rd_tests/test_grid_equinor_coarse.py index 7c6373105..4c1e0612d 100644 --- a/python/tests/rd_tests/test_grid_equinor_coarse.py +++ b/python/tests/rd_tests/test_grid_equinor_coarse.py @@ -1,8 +1,9 @@ import itertools -from resdata.resfile import ResdataRestartFile from resdata.grid import Grid +from resdata.resfile import ResdataRestartFile from resdata.util.test import TestAreaContext + from tests import ResdataTest, equinor_test diff --git a/python/tests/rd_tests/test_grid_equinor_dual.py b/python/tests/rd_tests/test_grid_equinor_dual.py index 731abd31f..585206566 100644 --- a/python/tests/rd_tests/test_grid_equinor_dual.py +++ b/python/tests/rd_tests/test_grid_equinor_dual.py @@ -1,7 +1,5 @@ -import math - -from resdata.util.test import TestAreaContext from resdata.grid import Grid +from resdata.util.test import TestAreaContext from tests import ResdataTest, equinor_test @@ -20,7 +18,7 @@ def test_dual(self): self.assertFalse(grid.dualGrid()) self.assertTrue(grid.getNumActiveFracture() == 0) - grid2 = Grid(self.grid_file()) + _grid2 = Grid(self.grid_file()) self.assertFalse(grid.dualGrid()) self.assertTrue(grid.getNumActiveFracture() == 0) diff --git a/python/tests/rd_tests/test_grid_generator.py b/python/tests/rd_tests/test_grid_generator.py index 4c261b643..07a5274bb 100644 --- a/python/tests/rd_tests/test_grid_generator.py +++ b/python/tests/rd_tests/test_grid_generator.py @@ -1,15 +1,15 @@ #!/usr/bin/env python -from itertools import product as prod +import functools import operator import random -import numpy -import functools +from itertools import product as prod +import numpy from resdata import ResDataType -from resdata.resfile import ResdataKW from resdata.grid import Grid from resdata.grid import GridGenerator as GridGen -from resdata.util.test import TestAreaContext +from resdata.resfile import ResdataKW + from tests import ResdataTest @@ -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_grid_large_case.py b/python/tests/rd_tests/test_grid_large_case.py index b08ed8d6f..2df447d52 100644 --- a/python/tests/rd_tests/test_grid_large_case.py +++ b/python/tests/rd_tests/test_grid_large_case.py @@ -1,5 +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..5eb852173 100644 --- a/python/tests/rd_tests/test_grid_pandas.py +++ b/python/tests/rd_tests/test_grid_pandas.py @@ -1,12 +1,8 @@ #!/usr/bin/env python import numpy as np -import pandas as pd - from resdata import ResdataTypeEnum - -from resdata.resfile import ResdataKW - from resdata.grid import Grid +from resdata.resfile import ResdataKW from tests import ResdataTest diff --git a/python/tests/rd_tests/test_kw_function.py b/python/tests/rd_tests/test_kw_function.py index dc1158b19..118e37f00 100644 --- a/python/tests/rd_tests/test_kw_function.py +++ b/python/tests/rd_tests/test_kw_function.py @@ -1,10 +1,9 @@ #!/usr/bin/env python -import os -import random from resdata import ResDataType -from resdata.resfile import ResdataKW, Resdata3DKW from resdata.grid import Grid +from resdata.resfile import Resdata3DKW, ResdataKW from resdata.util.util import IntVector + from tests import ResdataTest diff --git a/python/tests/rd_tests/test_layer.py b/python/tests/rd_tests/test_layer.py index 62e790c9d..2a458decd 100644 --- a/python/tests/rd_tests/test_layer.py +++ b/python/tests/rd_tests/test_layer.py @@ -1,12 +1,11 @@ #!/usr/bin/env python -from unittest import skipIf -import time -from resdata.util.util import IntVector -from resdata.grid import Grid from resdata.geometry import CPolyline -from resdata.grid.faults import Layer, FaultCollection +from resdata.grid import Grid +from resdata.grid.faults import FaultCollection, Layer from resdata.util.test import TestAreaContext +from resdata.util.util import IntVector + from tests import ResdataTest @@ -60,7 +59,7 @@ def test_contact(self): self.assertTrue(layer.cellContact((0, 4), (0, 5))) with TestAreaContext("Layer/barrier"): - with open("faults.grdecl", "w") as f: + with open("faults.grdecl", "w", encoding="utf-8") as f: f.write("FAULTS\n") f.write("'FX' 5 5 1 10 1 1 'X' /\n") f.write("'FY' 1 10 5 5 1 1 'Y' /\n") @@ -92,7 +91,7 @@ def test_fault_barrier(self): nz = 43 grid = Grid.createRectangular((nx, ny, nz), (1, 1, 1)) with TestAreaContext("python/faults/line_order"): - with open("faults.grdecl", "w") as f: + with open("faults.grdecl", "w", encoding="utf-8") as f: f.write( """FAULTS \'F\' 105 107 50 50 1 43 \'Y\' / @@ -104,7 +103,7 @@ def test_fault_barrier(self): / """ ) - with open("faults.grdecl") as f: + with open("faults.grdecl", encoding="utf-8") as f: faults = FaultCollection(grid, "faults.grdecl") # Fault layout: @@ -149,7 +148,7 @@ def test_contact2(self): nx = 10 ny = 10 layer = Layer(nx, ny) - grid = Grid.createRectangular((nx, ny, 1), (1, 1, 1)) + _grid = Grid.createRectangular((nx, ny, 1), (1, 1, 1)) # Too short with self.assertRaises(ValueError): diff --git a/python/tests/rd_tests/test_npv.py b/python/tests/rd_tests/test_npv.py index d69fd6026..b2f11a5f7 100644 --- a/python/tests/rd_tests/test_npv.py +++ b/python/tests/rd_tests/test_npv.py @@ -1,21 +1,11 @@ #!/usr/bin/env python -import os import datetime -import math -try: - from unittest2 import skipIf, skipUnless, skipIf -except ImportError: - from unittest import skipIf, skipUnless, skipIf +from resdata.summary import NPVPriceVector, ResdataNPV, Summary +from resdata.util.util import CTime -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 tests import ResdataTest, equinor_test - base = "ECLIPSE" path = "Equinor/ECLIPSE/Gurbat" case = "%s/%s" % (path, base) @@ -39,10 +29,10 @@ def setUp(self): self.case = self.createTestPath(case) def test_create(self): - with self.assertRaises(Exception): - npv = ResdataNPV("/does/not/exist") + with self.assertRaises(Exception): # noqa: B017 + _npv = ResdataNPV("/does/not/exist") - npv = ResdataNPV(self.case) + _npv = ResdataNPV(self.case) def test_eval_npv(self): npv = ResdataNPV(self.case) diff --git a/python/tests/rd_tests/test_rd_3dkw.py b/python/tests/rd_tests/test_rd_3dkw.py index 1ae1f8b9d..212750026 100644 --- a/python/tests/rd_tests/test_rd_3dkw.py +++ b/python/tests/rd_tests/test_rd_3dkw.py @@ -1,12 +1,10 @@ #!/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.grid import Grid -from resdata.util.test import TestAreaContext +from resdata.resfile import Resdata3DKW, ResdataKW +from resdata.util.util import IntVector + 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 13f1d2029..23224a6df 100644 --- a/python/tests/rd_tests/test_rd_cmp.py +++ b/python/tests/rd_tests/test_rd_cmp.py @@ -1,6 +1,5 @@ from resdata.summary import ResdataCmp -from resdata.util.test import TestAreaContext -from resdata.util.test.mock import createSummary + from tests import ResdataTest, equinor_test @@ -12,20 +11,20 @@ def setUp(self): def test_not_existing(self): with self.assertRaises(IOError): - rd_cmp = ResdataCmp("missing/case1", "missing/case2") + _rd_cmp = ResdataCmp("missing/case1", "missing/case2") with self.assertRaises(IOError): - rd_cmp = ResdataCmp("missing/case1", self.root1) + _rd_cmp = ResdataCmp("missing/case1", self.root1) with self.assertRaises(IOError): - rd_cmp = ResdataCmp(self.root1, "missing/case1") + _rd_cmp = ResdataCmp(self.root1, "missing/case1") - rd_cmp = ResdataCmp(self.root1, self.root1) - rd_cmp = ResdataCmp(self.root2, self.root2) + _rd_cmp = ResdataCmp(self.root1, self.root1) + _rd_cmp = ResdataCmp(self.root2, self.root2) def test_different_start(self): with self.assertRaises(ValueError): - rd_cmp = ResdataCmp(self.root1, self.root2) + _rd_cmp = ResdataCmp(self.root1, self.root2) def test_summary_cmp(self): rd_cmp = ResdataCmp(self.root1, self.root1) @@ -33,9 +32,9 @@ def test_summary_cmp(self): self.assertEqual((True, True), rd_cmp.hasSummaryVector("FOPT")) with self.assertRaises(KeyError): - diff = rd_cmp.cmpSummaryVector("MISSING") + _diff = rd_cmp.cmpSummaryVector("MISSING") - diff_sum, ref_sum = rd_cmp.cmpSummaryVector("FOPT") + diff_sum, _ref_sum = rd_cmp.cmpSummaryVector("FOPT") self.assertEqual(diff_sum, 0.0) self.assertTrue(rd_cmp.endTimeEqual()) @@ -43,7 +42,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_file.py b/python/tests/rd_tests/test_rd_file.py index c4f08d270..f7bfe59e3 100644 --- a/python/tests/rd_tests/test_rd_file.py +++ b/python/tests/rd_tests/test_rd_file.py @@ -1,14 +1,15 @@ -import shutil -import pytest import datetime -import os.path import gc +import os.path +import shutil -from resdata import FileMode, ResDataType, FileType -from resdata.resfile import ResdataFile, FortIO, ResdataKW, openFortIO, openResdataFile -from resdata.util.util import CWDContext -from resdata.util.test import TestAreaContext +import pytest +from resdata import FileMode, FileType, ResDataType from resdata.grid import Grid +from resdata.resfile import FortIO, ResdataFile, ResdataKW, openFortIO, openResdataFile +from resdata.util.test import TestAreaContext +from resdata.util.util import CWDContext + from tests import ResdataTest from tests.rd_tests.create_restart import create_restart @@ -148,7 +149,7 @@ def test_gc(self): kw_list = [kw1, kw2, kw2] - with TestAreaContext("context") as ta: + with TestAreaContext("context"): createFile("TEST", kw_list) gc.collect() kw_list2 = loadKeywords("TEST") @@ -158,7 +159,7 @@ def test_gc(self): def test_broken_file(self): with TestAreaContext("test_broken_file"): - with open("CASE.FINIT", "w") as f: + with open("CASE.FINIT", "w", encoding="utf-8") as f: f.write( "This - is not a RDISPE file\nsdlcblhcdbjlwhc\naschscbasjhcasc\nascasck c s s aiasic asc" ) @@ -170,7 +171,7 @@ def test_broken_file(self): kw.fwrite(f) kw.fwrite(f) - with open("FILE", "a+") as f: + with open("FILE", "a+", encoding="utf-8") as f: f.write("Seom random gibberish") f = ResdataFile("FILE") @@ -181,7 +182,7 @@ def test_broken_file(self): kw.fwrite(f) file_size = os.path.getsize("FILE") - with open("FILE", "a+") as f: + with open("FILE", "a+", encoding="utf-8") as f: f.truncate(int(file_size * 0.75)) f = ResdataFile("FILE") @@ -216,7 +217,7 @@ def test_block_view(self): with self.assertRaises(IndexError): rd_file.blockView("HEADER", 1000) - bv = rd_file.blockView("HEADER", -1) + _bv = rd_file.blockView("HEADER", -1) for i in range(5): view = rd_file.blockView("HEADER", i) diff --git a/python/tests/rd_tests/test_rd_file_equinor.py b/python/tests/rd_tests/test_rd_file_equinor.py index a374b5149..5b10c3852 100755 --- a/python/tests/rd_tests/test_rd_file_equinor.py +++ b/python/tests/rd_tests/test_rd_file_equinor.py @@ -1,12 +1,11 @@ #!/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 FortIO, ResdataFile from resdata.util.test import TestAreaContext + from tests import ResdataTest, equinor_test @@ -48,7 +47,7 @@ def test_iget_named(self): f = ResdataFile(self.test_file) N = f.num_named_kw("SWAT") with self.assertRaises(IndexError): - s = f.iget_named_kw("SWAT", N + 1) + _s = f.iget_named_kw("SWAT", N + 1) def test_fwrite(self): # work_area = TestArea("python/rd_file/fwrite") @@ -117,12 +116,12 @@ def test_save_fmt(self): def test_restart_view(self): f = ResdataFile(self.test_file) with self.assertRaises(ValueError): - v = f.restartView() + _v = f.restartView() - v = f.restartView(sim_days=274) - v = f.restartView(sim_time=datetime.date(2004, 1, 1)) - v = f.restartView(report_step=30) - v = f.restartView(seqnum_index=30) + _v = f.restartView(sim_days=274) + _v = f.restartView(sim_time=datetime.date(2004, 1, 1)) + _v = f.restartView(report_step=30) + _v = f.restartView(seqnum_index=30) def test_index(self): with TestAreaContext("python/rd_file/truncated"): diff --git a/python/tests/rd_tests/test_rd_init_file.py b/python/tests/rd_tests/test_rd_init_file.py index bf1404961..e555bd939 100644 --- a/python/tests/rd_tests/test_rd_init_file.py +++ b/python/tests/rd_tests/test_rd_init_file.py @@ -1,7 +1,7 @@ -from tests import ResdataTest, equinor_test -from resdata import FileMode -from resdata.resfile import Resdata3DKW, ResdataKW, ResdataInitFile, ResdataFile, FortIO from resdata.grid import Grid +from resdata.resfile import Resdata3DKW, ResdataInitFile, ResdataKW + +from tests import ResdataTest, equinor_test @equinor_test() @@ -13,7 +13,7 @@ def setUp(self): def test_wrong_type(self): g = Grid(self.grid_file) with self.assertRaises(ValueError): - f = ResdataInitFile(g, self.grid_file) + _f = ResdataInitFile(g, self.grid_file) def test_load(self): g = Grid(self.grid_file) diff --git a/python/tests/rd_tests/test_rd_kw.py b/python/tests/rd_tests/test_rd_kw.py index 4ff7b17e8..66ecb3a6d 100644 --- a/python/tests/rd_tests/test_rd_kw.py +++ b/python/tests/rd_tests/test_rd_kw.py @@ -1,25 +1,23 @@ #!/usr/bin/env python import random import warnings -import cwrap -import random - -from resdata import ResDataType, ResdataTypeEnum, FileMode -from resdata.resfile import ResdataKW, ResdataFile, FortIO, openFortIO - +import cwrap +from resdata import FileMode, ResDataType, ResdataTypeEnum +from resdata.resfile import FortIO, ResdataFile, ResdataKW, openFortIO from resdata.util.test import TestAreaContext + from tests import ResdataTest def copy_long(): src = ResdataKW("NAME", 100, ResDataType.RD_FLOAT) - copy = src.sub_copy(0, 2000) + _copy = src.sub_copy(0, 2000) def copy_offset(): src = ResdataKW("NAME", 100, ResDataType.RD_FLOAT) - copy = src.sub_copy(200, 100) + _copy = src.sub_copy(200, 100) class KWTest(ResdataTest): @@ -68,10 +66,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", encoding="utf-8") as file2: + for d in data: + file2.write(fmt % d) self.assertFilesAreEqual(name1, name2) self.assertEqual(kw.data_type, data_type) @@ -141,10 +138,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 +181,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", encoding="utf-8") 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) @@ -239,7 +234,7 @@ def test_fmt(self): kw1[i] = i + 1 kw2[i] = len(kw1) - kw1[i] - with TestAreaContext("rd_kw/fmt") as ta: + with TestAreaContext("rd_kw/fmt"): with openFortIO("TEST.FINIT", FortIO.WRITE_MODE, fmt_file=True) as f: kw1.fwrite(f) kw2.fwrite(f) diff --git a/python/tests/rd_tests/test_rd_kw_equinor.py b/python/tests/rd_tests/test_rd_kw_equinor.py index 12afd83cb..927b759b5 100755 --- a/python/tests/rd_tests/test_rd_kw_equinor.py +++ b/python/tests/rd_tests/test_rd_kw_equinor.py @@ -1,21 +1,20 @@ #!/usr/bin/env python import os -import random -from resdata import ResDataType, FileMode -from resdata.resfile import ResdataKW, ResdataFile, FortIO -from resdata.util.test import TestAreaContext +from resdata import ResDataType +from resdata.resfile import ResdataFile, ResdataKW + from tests import ResdataTest, equinor_test def copy_long(): src = ResdataKW("NAME", 100, ResDataType.RD_FLOAT) - copy = src.sub_copy(0, 2000) + _copy = src.sub_copy(0, 2000) def copy_offset(): src = ResdataKW("NAME", 100, ResDataType.RD_FLOAT) - copy = src.sub_copy(200, 100) + _copy = src.sub_copy(200, 100) @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..e854c8e81 100644 --- a/python/tests/rd_tests/test_rd_restart_file.py +++ b/python/tests/rd_tests/test_rd_restart_file.py @@ -1,15 +1,13 @@ import datetime -from tests import ResdataTest, equinor_test -from resdata import FileMode +from resdata.grid import Grid from resdata.resfile import ( Resdata3DKW, ResdataKW, ResdataRestartFile, - ResdataFile, - FortIO, ) -from resdata.grid import Grid + +from tests import ResdataTest, equinor_test @equinor_test() @@ -37,7 +35,7 @@ def test_load(self): def test_type(self): g = Grid(self.grid_file) with self.assertRaises(ValueError): - f = ResdataRestartFile(g, "NOT_A_RESTART_FILE") + _f = ResdataRestartFile(g, "NOT_A_RESTART_FILE") def test_unified(self): g = Grid(self.grid_file) diff --git a/python/tests/rd_tests/test_rd_sum.py b/python/tests/rd_tests/test_rd_sum.py index e0dac8b7d..492042831 100644 --- a/python/tests/rd_tests/test_rd_sum.py +++ b/python/tests/rd_tests/test_rd_sum.py @@ -10,6 +10,7 @@ from resdata.resfile import FortIO, ResdataKW, openFortIO, openResdataFile from resdata.summary import Summary, SummaryKeyWordVector from resdata.util.test import TestAreaContext + from tests import ResdataTest, equinor_test from tests.summary_generator import summaries @@ -85,7 +86,7 @@ def test_truncated_smspec(self): ta.copy_file(self.createTestPath("Equinor/ECLIPSE/Gurbat/ECLIPSE.UNSMRY")) file_size = os.path.getsize("ECLIPSE.SMSPEC") - with open("ECLIPSE.SMSPEC", "r+") as f: + with open("ECLIPSE.SMSPEC", "r+", encoding="utf-8") as f: f.truncate(file_size // 2) with self.assertRaises(IOError): @@ -97,7 +98,7 @@ def test_truncated_data(self): ta.copy_file(self.createTestPath("Equinor/ECLIPSE/Gurbat/ECLIPSE.UNSMRY")) file_size = os.path.getsize("ECLIPSE.UNSMRY") - with open("ECLIPSE.UNSMRY", "r+") as f: + with open("ECLIPSE.UNSMRY", "r+", encoding="utf-8") as f: f.truncate(file_size // 2) with self.assertRaises(IOError): @@ -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_sum_vector.py b/python/tests/rd_tests/test_rd_sum_vector.py index de9d03016..2a18f2def 100644 --- a/python/tests/rd_tests/test_rd_sum_vector.py +++ b/python/tests/rd_tests/test_rd_sum_vector.py @@ -1,12 +1,9 @@ #!/usr/bin/env python -try: - from unittest2 import skipIf -except ImportError: - from unittest import skipIf import warnings -from resdata.summary import SummaryVector, Summary +from resdata.summary import Summary, SummaryVector + from tests import ResdataTest, equinor_test @@ -20,7 +17,7 @@ def test_reportOnly_warns(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") - vector = SummaryVector(self.rd_sum, "FOPT", True) + _vector = SummaryVector(self.rd_sum, "FOPT", True) self.assertEqual(len(w), 1) assert issubclass(w[-1].category, DeprecationWarning) diff --git a/python/tests/rd_tests/test_rd_type.py b/python/tests/rd_tests/test_rd_type.py index adad89d9a..6a5d96d3d 100644 --- a/python/tests/rd_tests/test_rd_type.py +++ b/python/tests/rd_tests/test_rd_type.py @@ -1,8 +1,7 @@ -from resdata.util.test import TestAreaContext -from tests import ResdataTest - from resdata import ResDataType, ResdataTypeEnum +from tests import ResdataTest + def get_const_size_types(): return ResdataTypeEnum.enums()[:-1:] @@ -47,13 +46,13 @@ def test_alloc_from_type(self): def test_invalid_string_alloc(self): with self.assertRaises(ValueError): - data_type = ResDataType(ResdataTypeEnum.RD_STRING_TYPE) + _data_type = ResDataType(ResdataTypeEnum.RD_STRING_TYPE) with self.assertRaises(ValueError): - data_type = ResDataType(ResdataTypeEnum.RD_STRING_TYPE, -1) + _data_type = ResDataType(ResdataTypeEnum.RD_STRING_TYPE, -1) with self.assertRaises(ValueError): - data_type = ResDataType(ResdataTypeEnum.RD_STRING_TYPE, 1000) + _data_type = ResDataType(ResdataTypeEnum.RD_STRING_TYPE, 1000) def test_alloc(self): for rd_type, element_size in zip(self.TYPES, self.SIZES): @@ -120,7 +119,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) - set(rd_type, elem_size): self.assertFalse(a.is_equal(ResDataType(otype, osize))) self.assertNotEqual(a, ResDataType(otype, osize)) @@ -132,10 +131,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..51c098ba5 100644 --- a/python/tests/rd_tests/test_rd_util.py +++ b/python/tests/rd_tests/test_rd_util.py @@ -1,8 +1,8 @@ -import pytest import datetime from textwrap import dedent from resdata import FileType, ResdataTypeEnum, ResdataUtil + from tests import ResdataTest @@ -12,7 +12,7 @@ def test_enums(self): self.assertEnumIsFullyDefined(ResdataTypeEnum, "rd_type_enum", source_file_path) def test_file_type(self): - file_type, fmt, report = ResdataUtil.inspectExtension("CASE.X0078") + file_type, _fmt, _report = ResdataUtil.inspectExtension("CASE.X0078") self.assertEqual(file_type, FileType.RESTART) def test_file_report_nr(self): @@ -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.py b/python/tests/rd_tests/test_region.py index efd7f0a38..ff98111d9 100644 --- a/python/tests/rd_tests/test_region.py +++ b/python/tests/rd_tests/test_region.py @@ -1,11 +1,12 @@ -from resdata import ResDataType import numpy as np import pytest -from resdata.resfile import ResdataKW +from resdata import ResDataType from resdata.grid import Grid, ResdataRegion +from resdata.grid.faults import Layer +from resdata.resfile import ResdataKW from resdata.util.util import IntVector + from tests import ResdataTest -from resdata.grid.faults import Layer class RegionTest(ResdataTest): diff --git a/python/tests/rd_tests/test_region_equinor.py b/python/tests/rd_tests/test_region_equinor.py index dc84dd95c..3608ac3aa 100755 --- a/python/tests/rd_tests/test_region_equinor.py +++ b/python/tests/rd_tests/test_region_equinor.py @@ -1,7 +1,8 @@ #!/usr/bin/env python -from resdata.resfile import ResdataFile from resdata.grid import Grid, ResdataRegion from resdata.grid.faults import Layer +from resdata.resfile import ResdataFile + from tests import ResdataTest, equinor_test @@ -126,17 +127,17 @@ 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) reg.select_islice(0, 5) - active_list = reg.getActiveList() - global_list = reg.getGlobalList() + _active_list = reg.getActiveList() + _global_list = reg.getGlobalList() def test_polygon(self): reg = ResdataRegion(self.grid, False) - (x, y, z) = self.grid.get_xyz(ijk=(10, 10, 0)) + (x, y, _z) = self.grid.get_xyz(ijk=(10, 10, 0)) dx = 0.1 dy = 0.1 reg.select_inside_polygon( @@ -149,7 +150,7 @@ def test_heidrun(self): grid = Grid("%s/FF12_2013B2_AMAP_AOP-J15_NO62_MOVEX.EGRID" % root) polygon = [] - with open("%s/polygon.ply" % root) as fileH: + with open("%s/polygon.ply" % root, encoding="utf-8") 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_restart.py b/python/tests/rd_tests/test_restart.py index a327536c7..a51a2ff55 100755 --- a/python/tests/rd_tests/test_restart.py +++ b/python/tests/rd_tests/test_restart.py @@ -1,8 +1,9 @@ #!/usr/bin/env python -from _ctypes import ArgumentError -import os import datetime +import os + from resdata.resfile import ResdataFile + from tests import ResdataTest, equinor_test @@ -103,4 +104,4 @@ def test_kw(self): self.assertTrue(kw1.equal(kw3)) with self.assertRaises(IndexError): - kw4 = f.restart_get_kw("SWAT", datetime.datetime(2009, 3, 17)) + _kw4 = f.restart_get_kw("SWAT", datetime.datetime(2009, 3, 17)) diff --git a/python/tests/rd_tests/test_restart_head.py b/python/tests/rd_tests/test_restart_head.py index 2c7caae2c..fe52a0938 100644 --- a/python/tests/rd_tests/test_restart_head.py +++ b/python/tests/rd_tests/test_restart_head.py @@ -1,17 +1,15 @@ import datetime import os.path -from tests import ResdataTest, equinor_test, source_root -from resdata import FileMode, ResDataType +from resdata import ResDataType +from resdata.grid import Grid from resdata.resfile import ( - Resdata3DKW, ResdataKW, ResdataRestartFile, - ResdataFile, - FortIO, ) from resdata.resfile.rd_restart_file import ResdataRestartHead -from resdata.grid import Grid + +from tests import ResdataTest, equinor_test, source_root @equinor_test() diff --git a/python/tests/rd_tests/test_rft.py b/python/tests/rd_tests/test_rft.py index 0aa92b022..b6d633009 100644 --- a/python/tests/rd_tests/test_rft.py +++ b/python/tests/rd_tests/test_rft.py @@ -1,13 +1,10 @@ #!/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 @@ -18,7 +15,7 @@ def test_create(self): self.assertEqual(rft.get_well_name(), "WELL") with self.assertRaises(IndexError): - cell = rft[5] + _cell = rft[5] def test_repr(self): rft = ResdataRFT("WELL", "RFT", datetime.date(2015, 10, 1), 100) diff --git a/python/tests/rd_tests/test_rft_cell.py b/python/tests/rd_tests/test_rft_cell.py index 1dff5931a..3e42873da 100644 --- a/python/tests/rd_tests/test_rft_cell.py +++ b/python/tests/rd_tests/test_rft_cell.py @@ -1,5 +1,6 @@ #!/usr/bin/env python from resdata.rft import ResdataPLTCell, ResdataRFTCell + from tests import ResdataTest diff --git a/python/tests/rd_tests/test_rft_equinor.py b/python/tests/rd_tests/test_rft_equinor.py index ef76a3738..7dbee37b9 100644 --- a/python/tests/rd_tests/test_rft_equinor.py +++ b/python/tests/rd_tests/test_rft_equinor.py @@ -1,7 +1,10 @@ #!/usr/bin/env python from __future__ import print_function + import datetime -from resdata.rft import ResdataRFTFile, ResdataRFTCell, ResdataPLTCell, WellTrajectory + +from resdata.rft import ResdataPLTCell, ResdataRFTCell, ResdataRFTFile, WellTrajectory + from tests import ResdataTest, equinor_test @@ -54,7 +57,7 @@ def test_PLT_load(self): def test_exceptions(self): with self.assertRaises(IndexError): rftFile = ResdataRFTFile(self.RFT_file) - rft = rftFile[100] + _rft = rftFile[100] def test_basics(self): wt = WellTrajectory( @@ -89,7 +92,7 @@ def test_trajectory(self): self.assertEqual(len(wt), 38) with self.assertRaises(IndexError): - p = wt[38] + _p = wt[38] p0 = wt[0] self.assertEqual(p0.utm_x, 458920.671) diff --git a/python/tests/rd_tests/test_sum.py b/python/tests/rd_tests/test_sum.py index 198f4627e..e13d65554 100644 --- a/python/tests/rd_tests/test_sum.py +++ b/python/tests/rd_tests/test_sum.py @@ -4,7 +4,6 @@ import os.path import shutil import stat -import datetime import cwrap @@ -14,20 +13,19 @@ def assert_frame_equal(a, b): raise AssertionError("Expected dataframes to be equal") -try: - from pandas.testing import assert_frame_equal -except ImportError: - pass - -from contextlib import contextmanager +from contextlib import contextmanager, suppress from resdata import ResDataType, UnitSystem from resdata.resfile import FortIO, ResdataFile, ResdataKW, openFortIO from resdata.summary import Summary, SummaryKeyWordVector, SummaryVarType from resdata.util.test import TestAreaContext from resdata.util.test.mock import createSummary + from tests import ResdataTest +with suppress(ImportError): + from pandas.testing import assert_frame_equal + @contextmanager def pushd(path): @@ -194,7 +192,7 @@ def test_identify_var_type(self): self.assertNotEqual(node1, node2) with self.assertRaises(TypeError): - a = node1 < 1 + _a = node1 < 1 def test_csv_export(self): case = createSummary( @@ -204,7 +202,10 @@ 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", encoding="utf-8"), # noqa: SIM115 + delimiter=sep, + ) for row in input_file: self.assertIn("DAYS", row) self.assertIn("DATE", row) @@ -218,7 +219,10 @@ 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", encoding="utf-8"), # noqa: SIM115 + delimiter=sep, + ) for row in input_file: self.assertIn("DAYS", row) self.assertIn("DATE", row) @@ -231,7 +235,7 @@ def test_csv_export(self): sep = "," case.exportCSV("file.csv", keys=["F*"], sep=sep, date_format=date_format) self.assertTrue(os.path.isfile("file.csv")) - with open("file.csv") as f: + with open("file.csv", encoding="utf-8") as f: time_index = -1 for line in f.readlines(): tmp = line.split(sep) @@ -244,7 +248,6 @@ def test_csv_export(self): time_index += 1 def test_solve(self): - length = 100 case = create_case() self.assert_solve(case) @@ -314,14 +317,14 @@ def test_invalid(self): case = create_case() with TestAreaContext("sum_invalid"): case.fwrite() - with open("CASE.txt", "w") as f: + with open("CASE.txt", "w", encoding="utf-8") as f: f.write("No - this is not ResdataKW file ....") with self.assertRaises(IOError): - case2 = Summary.load("CSV.SMSPEC", "CASE.txt") + _case2 = Summary.load("CSV.SMSPEC", "CASE.txt") with self.assertRaises(IOError): - case2 = Summary.load("CASE.txt", "CSV.UNSMRY") + _case2 = Summary.load("CASE.txt", "CSV.UNSMRY") kw1 = ResdataKW("TEST1", 30, ResDataType.RD_INT) kw2 = ResdataKW("TEST2", 30, ResDataType.RD_INT) @@ -331,10 +334,10 @@ def test_invalid(self): kw2.fwrite(f) with self.assertRaises(IOError): - case2 = Summary.load("CSV.SMSPEC", "CASE.KW") + _case2 = Summary.load("CSV.SMSPEC", "CASE.KW") with self.assertRaises(IOError): - case2 = Summary.load("CASE.KW", "CSV.UNSMRY") + _case2 = Summary.load("CASE.KW", "CSV.UNSMRY") def test_kw_vector(self): case1 = create_case() @@ -393,10 +396,10 @@ def test_kw_vector(self): with cwrap.open("f2.txt", "w") as f: case2.dumpCSVLine(t, kw_list2, f) - with open("f1.txt") as f: + with open("f1.txt", encoding="utf-8") as f: d1 = f.readline().split(",") - with open("f2.txt") as f: + with open("f2.txt", encoding="utf-8") as f: d2 = f.readline().split(",") self.assertEqual(d1[0], d2[0]) @@ -440,7 +443,7 @@ def test_resample(self): time_vector = case.alloc_time_vector(False) case2 = case.resample("RS", time_vector) time_vector_resample = case2.alloc_time_vector(False) - first_diff = time_vector_resample.first_neq(time_vector) + _first_diff = time_vector_resample.first_neq(time_vector) self.assertEqual(time_vector_resample, time_vector) # The purpose of this test is to reproduce a slightly contrived error situation. @@ -476,7 +479,7 @@ def test_restart_abs_path(self): ) self.assertEqual(pred.restart_step, history.last_report) - length = pred.sim_length + _length = pred.sim_length pred_times = pred.alloc_time_vector(False) hist_times = history.alloc_time_vector(False) @@ -513,7 +516,7 @@ def test_restart_perm_denied(self): # This just tests that we can create a summary instance even if we do not # have access to load the history case. - pred = Summary("PREDICTION") + _pred = Summary("PREDICTION") os.chmod("history", stat.S_IRWXU) @@ -527,7 +530,7 @@ def test_units(self): with TestAreaContext("unit_test"): case = create_case("UNITS") case.fwrite() - case2 = Summary("UNITS") + _case2 = Summary("UNITS") kw_list = [] f = ResdataFile("UNITS.SMSPEC") @@ -588,8 +591,8 @@ def test_vector(self): # The get_vector method is extremely deprecated. v1 = case.get_vector("FOPT") v2 = case.get_vector("FOPT", report_only=True) - s1 = sum([x.value for x in v1]) - s2 = sum([x.value for x in v2]) + _s1 = sum(x.value for x in v1) + _s2 = sum(x.value for x in v2) def test_wells_and_groups(self): case = create_case() @@ -659,8 +662,8 @@ def test_load_case(self): self.assertFloatEqual(case.sim_length, 545.0) fopr = case.numpy_vector("FOPR") - for time_index, value in enumerate(fopr): - self.assertEqual(fopr[time_index], value) + for _time_index, value in enumerate(fopr): + self.assertEqual(value, value) def test_load_case_lazy_and_eager(self): path = os.path.join(self.TESTDATA_ROOT, "local/ECLIPSE/cp_simple3/SHORT.UNSMRY") @@ -685,13 +688,13 @@ def test_directory_conflict(self): case = create_case("UNITS") case.fwrite() os.mkdir("UNITS") - case2 = Summary("./UNITS") + _case2 = Summary("./UNITS") 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() @@ -718,7 +721,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 +749,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..dc4a85085 100755 --- a/python/tests/rd_tests/test_sum_equinor.py +++ b/python/tests/rd_tests/test_sum_equinor.py @@ -1,17 +1,12 @@ -import os import datetime +import os -from unittest import skipIf, skipUnless, skipIf - -from resdata.resfile import ResdataFile -from resdata.summary import Summary from resdata import UnitSystem - -from resdata.util.util import StringList, TimeVector, DoubleVector, CTime - +from resdata.summary import Summary from resdata.util.test import TestAreaContext +from resdata.util.util import CTime, DoubleVector, StringList, TimeVector + from tests import ResdataTest, equinor_test -import csv base = "ECLIPSE" path = "Equinor/ECLIPSE/Gurbat" @@ -21,7 +16,7 @@ def sum_get(*args): sum = args[0] key = args[1] - vec = sum[key] + _vec = sum[key] @equinor_test() @@ -37,18 +32,18 @@ def test_load(self): def test_invalid(self): with self.assertRaises(IOError): - sum = Summary("Does/not/exist") + _sum = Summary("Does/not/exist") def test_KeyError(self): sum = self.rd_sum with self.assertRaises(KeyError): - v = sum.numpy_vector("KeyMissing") + _v = sum.numpy_vector("KeyMissing") with self.assertRaises(KeyError): - v = sum.get_interp("Missing", days=750) + _v = sum.get_interp("Missing", days=750) with self.assertRaises(KeyError): - v = sum.get_interp_vector("Missing", days_list=[750]) + _v = sum.get_interp_vector("Missing", days_list=[750]) def test_contains(self): self.assertTrue("FOPT" in self.rd_sum) @@ -109,17 +104,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") @@ -188,7 +183,7 @@ def test_report(self): def test_fwrite(self): rd_sum = Summary(self.case, lazy_load=False) - with TestAreaContext("python/sum-test/fwrite") as work_area: + with TestAreaContext("python/sum-test/fwrite"): rd_sum.fwrite(rd_case="CASE") self.assertTrue(True) @@ -283,7 +278,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) @@ -328,8 +323,6 @@ def test_timeRange(self): start=datetime.datetime(2000, 1, 1), end=datetime.datetime(1999, 1, 1) ) - sim_start = datetime.datetime(2000, 1, 1, 0, 0, 0) - sim_end = datetime.datetime(2004, 12, 31, 0, 0, 0) trange = sum.timeRange(interval="1Y") self.assertTrue(trange[0] == datetime.date(2000, 1, 1)) self.assertTrue(trange[1] == datetime.date(2001, 1, 1)) @@ -379,11 +372,11 @@ def test_regularProduction(self): sum = Summary(self.case) with self.assertRaises(TypeError): trange = TimeVector.createRegular(sum.start_time, sum.end_time, "1M") - prod = sum.blockedProduction("FOPR", trange) + _prod = sum.blockedProduction("FOPR", trange) with self.assertRaises(KeyError): trange = TimeVector.createRegular(sum.start_time, sum.end_time, "1M") - prod = sum.blockedProduction("NoNotThis", trange) + _prod = sum.blockedProduction("NoNotThis", trange) trange = sum.timeRange(interval="2Y") self.assertTrue(trange[0] == datetime.date(2000, 1, 1)) @@ -452,7 +445,7 @@ def test_restart_mapping(self): self.assertEqual(total.iget("WGPR:NOT_21_D", 5), node.default) def test_write(self): - with TestAreaContext("my_space") as area: + with TestAreaContext("my_space"): intersect_summary = Summary( self.createTestPath( "Equinor/ECLIPSE/SummaryRestart/iter-1/NOR-2013A_R007-0" @@ -475,10 +468,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( @@ -501,7 +491,7 @@ def test_ix_write(self): "Equinor/ECLIPSE/ix/summary/CREATE_REGION_AROUND_WELL", "Equinor/ECLIPSE/ix/troll/IX_NOPH3_R04_75X75X1_GRID2.SMSPEC", ]: - with TestAreaContext("my_space" + data_set.split("/")[-1]) as area: + with TestAreaContext("my_space" + data_set.split("/")[-1]): intersect_summary = Summary( self.createTestPath(data_set), lazy_load=False ) @@ -538,7 +528,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( @@ -562,7 +552,7 @@ def test_summary_units(self): # which was shut down brutally. This test verifies that we # can create a valid rd_sum instance from what we find. def test_broken_case(self): - rd_sum = Summary( + _rd_sum = Summary( self.createTestPath( "Equinor/ECLIPSE/SummaryFail3/COMBINED-AUTUMN2018_CARBSENS-0" ) diff --git a/python/tests/test_bin.py b/python/tests/test_bin.py index 40fcf5f29..643306bf7 100644 --- a/python/tests/test_bin.py +++ b/python/tests/test_bin.py @@ -1,7 +1,8 @@ +import signal +import subprocess import sys + import pytest -import subprocess -import signal @pytest.mark.skipif( @@ -30,6 +31,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_ctime.py b/python/tests/util_tests/test_ctime.py index 623385b36..310ce24d3 100644 --- a/python/tests/util_tests/test_ctime.py +++ b/python/tests/util_tests/test_ctime.py @@ -1,9 +1,8 @@ import time -from datetime import datetime, date +from datetime import date, datetime from resdata.util.util import CTime - try: from unittest2 import TestCase except ImportError: @@ -24,7 +23,6 @@ def test_creation(self): CTime("string") def test_c_time(self): - delta = 0 c_time = CTime(0) py_time = datetime(1970, 1, 1) @@ -59,27 +57,27 @@ def test_comparison(self): self.assertTrue(t0 == t1) self.assertFalse(t0 != t1) with self.assertRaises(TypeError): - t0 != 0.5 + t0 != 0.5 # noqa: B015 self.assertFalse(t0 < t1) self.assertTrue(t0 < t2) with self.assertRaises(TypeError): - t0 < 0.5 + t0 < 0.5 # noqa: B015 self.assertTrue(t0 <= t1) self.assertTrue(t0 <= t2) with self.assertRaises(TypeError): - t0 <= 0.5 + t0 <= 0.5 # noqa: B015 self.assertFalse(t0 > t1) self.assertFalse(t0 > t2) with self.assertRaises(TypeError): - t0 > 0.5 + t0 > 0.5 # noqa: B015 self.assertTrue(t0 >= t1) self.assertFalse(t0 >= t2) with self.assertRaises(TypeError): - t0 >= 0.5 + t0 >= 0.5 # noqa: B015 t3 = CTime(date(2050, 1, 1)) t4 = CTime(date(2060, 1, 1)) @@ -112,16 +110,16 @@ def test_range(self): self.assertFalse(dt1 <= c0 < c2) self.assertTrue(d0 <= c0 < dt2) - self.assertTrue(c0 <= c0 < d2) + self.assertTrue(c0 <= c0 < d2) # noqa: PLR0124 self.assertTrue(dt0 <= c0 < c2) self.assertFalse(d0 <= c2 < dt2) self.assertFalse(c0 <= c2 < d2) - self.assertFalse(dt0 <= c2 < c2) + self.assertFalse(dt0 <= c2 < c2) # noqa: PLR0124 self.assertTrue(d0 <= c2 <= dt2) self.assertTrue(c0 <= c2 <= d2) - self.assertTrue(dt0 <= c2 <= c2) + self.assertTrue(dt0 <= c2 <= c2) # noqa: PLR0124 def test_conversion(self): t = CTime(0) diff --git a/python/tests/util_tests/test_hash.py b/python/tests/util_tests/test_hash.py index 285432efe..f5e8835bf 100644 --- a/python/tests/util_tests/test_hash.py +++ b/python/tests/util_tests/test_hash.py @@ -1,7 +1,8 @@ from ctypes import c_void_p +from resdata.util.util import DoubleHash, Hash, IntegerHash, StringHash + from tests import ResdataTest -from resdata.util.util import Hash, StringHash, DoubleHash, IntegerHash class HashTest(ResdataTest): @@ -18,7 +19,7 @@ def test_string_hash(self): hash["hopp"] = 55 with self.assertRaises(KeyError): - hopp = hash["hopp"] + _hopp = hash["hopp"] self.assertTrue("hipp" in hash) diff --git a/python/tests/util_tests/test_path_context.py b/python/tests/util_tests/test_path_context.py index acd181ddc..dcc289a64 100644 --- a/python/tests/util_tests/test_path_context.py +++ b/python/tests/util_tests/test_path_context.py @@ -1,5 +1,7 @@ import os + from resdata.util.test import PathContext, TestAreaContext + from tests import ResdataTest @@ -8,16 +10,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: + with open("path/1/file", "w", encoding="utf-8") 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 +27,10 @@ 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", encoding="utf-8" + ) 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_rng.py b/python/tests/util_tests/test_rng.py index ec3c3a1c8..f77ea16a8 100644 --- a/python/tests/util_tests/test_rng.py +++ b/python/tests/util_tests/test_rng.py @@ -1,6 +1,7 @@ from resdata.util.enums import RngAlgTypeEnum, RngInitModeEnum -from resdata.util.util import RandomNumberGenerator from resdata.util.test import TestAreaContext +from resdata.util.util import RandomNumberGenerator + from tests import ResdataTest @@ -38,7 +39,7 @@ def test_load_save(self): with self.assertRaises(IOError): rng.loadState("does/not/exist") - with TestAreaContext("rng_state") as t: + with TestAreaContext("rng_state"): rng.saveState("rng.txt") val1 = rng.getInt() val2 = rng.getInt() diff --git a/python/tests/util_tests/test_string_list.py b/python/tests/util_tests/test_string_list.py index a2aa344df..661e42379 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 # noqa: B018 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..65938aa43 100644 --- a/python/tests/util_tests/test_thread_pool.py +++ b/python/tests/util_tests/test_thread_pool.py @@ -1,6 +1,8 @@ import time + from resdata.util.util import ThreadPool from resdata.util.util.thread_pool import Task + from tests import ResdataTest @@ -61,7 +63,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..c3fe6ff9d 100755 --- a/python/tests/util_tests/test_vectors.py +++ b/python/tests/util_tests/test_vectors.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -import copy import datetime + import six try: @@ -9,12 +9,11 @@ from unittest import TestCase from resdata.util.util import ( + BoolVector, + CTime, DoubleVector, IntVector, - BoolVector, TimeVector, - CTime, - PermutationVector, ) @@ -118,11 +117,11 @@ def test_vector_operations_with_exceptions(self): # Size mismatch with self.assertRaises(ValueError): - iv3 = iv1 + iv2 + _iv3 = iv1 + iv2 # Size mismatch with self.assertRaises(ValueError): - iv3 = iv1 * iv2 + _iv3 = iv1 * iv2 # Type mismatch with self.assertRaises(TypeError): @@ -317,7 +316,7 @@ def test_int_vector(self): self.assertEqual(list(sliced), [5, 4, 3]) with self.assertRaises(IndexError): - item = a[6] + _item = a[6] copy_of_a = a.copy() self.assertEqual(list(a), list(copy_of_a)) @@ -523,16 +522,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) + vec = IntVector.createRange(a, b, d) + ran = range(a, b, d) - self.assertEqual(len(v), len(r)) - for a, b in zip(v, r): - self.assertEqual(a, b) + self.assertEqual(len(vec), len(ran)) + for val1, val2 in zip(vec, ran): + self.assertEqual(val1, val2) def test_range(self): v = IntVector() diff --git a/python/tests/util_tests/test_version.py b/python/tests/util_tests/test_version.py index 33e2142fa..ed67a5dbb 100644 --- a/python/tests/util_tests/test_version.py +++ b/python/tests/util_tests/test_version.py @@ -1,5 +1,6 @@ import resdata from resdata.util.util import ResdataVersion, Version + from tests import ResdataTest diff --git a/python/tests/util_tests/test_work_area.py b/python/tests/util_tests/test_work_area.py index a03e8da7c..295bb162a 100644 --- a/python/tests/util_tests/test_work_area.py +++ b/python/tests/util_tests/test_work_area.py @@ -1,20 +1,16 @@ #!/usr/bin/env python -import os.path import os - -try: - from unittest2 import skipIf -except ImportError: - from unittest import skipIf +import os.path from resdata.util.test import TestAreaContext + from tests import ResdataTest class WorkAreaTest(ResdataTest): def test_full_path(self): with TestAreaContext("TestArea") as test_area: - with open("test_file", "w") as fileH: + with open("test_file", "w", encoding="utf-8") as fileH: fileH.write("Something") self.assertTrue(os.path.isfile("test_file")) @@ -44,7 +40,7 @@ def test_IOError(self): test_area.copy_parent_directory("Does/not/exist") os.makedirs("path1/path2") - with open("path1/file.txt", "w") as f: + with open("path1/file.txt", "w", encoding="utf-8") as f: f.write("File ...") with self.assertRaises(IOError): diff --git a/python/tests/well_tests/test_rd_well.py b/python/tests/well_tests/test_rd_well.py index 8bb549e17..d36c2a806 100644 --- a/python/tests/well_tests/test_rd_well.py +++ b/python/tests/well_tests/test_rd_well.py @@ -1,17 +1,19 @@ import datetime + from resdata import FileMode -from resdata.resfile import ResdataFile from resdata.grid import Grid -from tests import ResdataTest, equinor_test +from resdata.resfile import ResdataFile from resdata.util.util.ctime import CTime from resdata.well import ( - WellInfo, WellConnection, WellConnectionDirection, + WellInfo, WellSegment, WellType, ) +from tests import ResdataTest, equinor_test + @equinor_test() class ResdataWellTest(ResdataTest): @@ -376,14 +378,14 @@ 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): - err = well_info[222] + _err = well_info[222] with self.assertRaises(KeyError): - err = well_info["Well"] + _err = well_info["Well"] def test_well_time_line(self): well_info = self.getWellInfo() @@ -397,7 +399,7 @@ def test_well_time_line(self): well_states.add(well_time_line[0]) with self.assertRaises(IndexError): - err = well_time_line[1] + _err = well_time_line[1] self.assertEqual(len(well_states), len(ResdataWellTest.ALL_WELLS)) @@ -432,8 +434,6 @@ def test_well_state(self): WellType.WATER_INJECTOR: 0, } - segments = set() - branches = set() connections = set() connections_count = 0 @@ -458,9 +458,6 @@ def test_well_state(self): connections_count += len(global_connections) connections.update(global_connections) - # branches.add(well_state.branches()) - # segments.add(well_state.segments()) - self.assertEqual(open_states[True], 53) self.assertEqual(open_states[False], 169) @@ -1365,4 +1362,4 @@ def test_load_broken_direction(self): "Equinor/ECLIPSE/icon-invalid-value/R6_HM2016B_FFP_BASE.UNRST" ) grid = Grid(grid_path) - well_info = WellInfo(grid, rst_path) + _well_info = WellInfo(grid, rst_path) diff --git a/python/tests/well_tests/test_rd_well2.py b/python/tests/well_tests/test_rd_well2.py index 842cc4ecc..0b4d81253 100644 --- a/python/tests/well_tests/test_rd_well2.py +++ b/python/tests/well_tests/test_rd_well2.py @@ -1,19 +1,12 @@ -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, ) +from tests import ResdataTest, equinor_test + @equinor_test() class ResdataWellTest2(ResdataTest): diff --git a/python/tests/well_tests/test_rd_well3.py b/python/tests/well_tests/test_rd_well3.py index 3e46df2b6..530c0d7d2 100644 --- a/python/tests/well_tests/test_rd_well3.py +++ b/python/tests/well_tests/test_rd_well3.py @@ -1,19 +1,11 @@ -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, ) +from tests import ResdataTest, equinor_test + @equinor_test() class ResdataWellTest3(ResdataTest): @@ -26,7 +18,7 @@ def test_rates(self): grid = Grid(grid_path) well_info = WellInfo(grid, rst_path) - sum = Summary(sum_path) + _sum = Summary(sum_path) for wtl in well_info: for well_state in wtl: diff --git a/python/tests/well_tests/test_well_missing_ICON.py b/python/tests/well_tests/test_well_missing_ICON.py index 7ca828194..6ffa881dc 100644 --- a/python/tests/well_tests/test_well_missing_ICON.py +++ b/python/tests/well_tests/test_well_missing_ICON.py @@ -1,15 +1,15 @@ import datetime -from tests import ResdataTest + from resdata.grid import GridGenerator from resdata.resfile import ResdataFile from resdata.well import ( + WellConnectionDirection, WellInfo, - WellConnection, WellType, - WellConnectionDirection, - WellSegment, ) +from tests import ResdataTest + class ResdataWellICONTest(ResdataTest): def setUp(self): 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 diff --git a/setup.py b/setup.py index f973d9abc..ca74cf130 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ break -with open("README.md") as f: +with open("README.md", encoding="utf-8") as f: long_description = f.read()