Skip to content

Commit

Permalink
Add pyupgrade ruff rule
Browse files Browse the repository at this point in the history
  • Loading branch information
larsevj committed Aug 29, 2024
1 parent 825bbb9 commit e8b4f18
Show file tree
Hide file tree
Showing 82 changed files with 314 additions and 406 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ select = [
"NPY", # numpy specific rules
"C4", # flake8-comprehensions
"PD", # pandas-vet
"UP", # pyupgrade
]
ignore = ["PLW2901", # redefined-loop-name
"PLR2004", # magic-value-comparison
Expand Down
6 changes: 3 additions & 3 deletions python/docs/examples/avg_pressure.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ def avg_pressure(p, sw, pv, region, region_id, result):

if __name__ == "__main__":
case = sys.argv[1]
grid = Grid("%s.EGRID" % case)
rst_file = ResdataRestartFile(grid, "%s.UNRST" % case)
init_file = ResdataFile("%s.INIT" % case)
grid = Grid(f"{case}.EGRID")
rst_file = ResdataRestartFile(grid, f"{case}.UNRST")
init_file = ResdataFile(f"{case}.INIT")

# Create PORV keyword where all the inactive cells have been removed.
pv = grid.compressed_kw_copy(init_file["PORV"][0])
Expand Down
4 changes: 1 addition & 3 deletions python/resdata/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,7 @@ class ResdataPrototype(Prototype):
lib = _dlopen_resdata()

def __init__(self, prototype, bind=True):
super(ResdataPrototype, self).__init__(
ResdataPrototype.lib, prototype, bind=bind
)
super().__init__(ResdataPrototype.lib, prototype, bind=bind)


from .rd_type import ResDataType, ResdataTypeEnum
Expand Down
14 changes: 7 additions & 7 deletions python/resdata/geometry/cpolyline.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,14 @@ class CPolyline(BaseCClass):

def __init__(self, name=None, init_points=()):
c_ptr = self._alloc_new(name)
super(CPolyline, self).__init__(c_ptr)
super().__init__(c_ptr)
for xc, yc in init_points:
self.addPoint(xc, yc)

@classmethod
def createFromXYZFile(cls, filename, name=None):
if not os.path.isfile(filename):
raise IOError("No such file:%s" % filename)
raise OSError(f"No such file:{filename}")

polyline = cls._fread_alloc_irap(filename)
if not name is None:
Expand All @@ -56,10 +56,10 @@ def createFromXYZFile(cls, filename, name=None):

def __str__(self):
name = self.getName()
str = "%s [" % name if name else "["
str = f"{name} [" if name else "["

for index, p in enumerate(self):
str += "(%g,%g)" % p
str += "({:g},{:g})".format(*p)
if index < len(self) - 1:
str += ","
str += "]"
Expand All @@ -73,7 +73,7 @@ def __len__(self):

def __getitem__(self, index):
if not isinstance(index, int):
raise TypeError("Index argument must be integer. Index:%s invalid" % index)
raise TypeError(f"Index argument must be integer. Index:{index} invalid")

if index < 0:
index += len(self)
Expand Down Expand Up @@ -119,7 +119,7 @@ def __radd__(self, other):
return copy

def __eq__(self, other):
if super(CPolyline, self).__eq__(other):
if super().__eq__(other):
return True
else:
return self._equal(other)
Expand All @@ -142,7 +142,7 @@ def extendToBBox(self, bbox, start=True):
intersections = GeometryTools.rayPolygonIntersections(p1, ray_dir, bbox)
if intersections:
p2 = intersections[0][1]
name = "Extend:%s" % self.getName() if self.getName() else None
name = f"Extend:{self.getName()}" if self.getName() else None

return CPolyline(name=name, init_points=[(p1[0], p1[1]), p2])
else:
Expand Down
8 changes: 4 additions & 4 deletions python/resdata/geometry/cpolyline_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class CPolylineCollection(BaseCClass):

def __init__(self):
c_ptr = self._alloc_new()
super(CPolylineCollection, self).__init__(c_ptr)
super().__init__(c_ptr)
self.parent_ref = None

def __contains__(self, name):
Expand Down Expand Up @@ -68,7 +68,7 @@ def __getitem__(self, index):
if index in self:
return self._get(index)
else:
raise KeyError("No polyline named:%s" % index)
raise KeyError(f"No polyline named:{index}")
else:
raise TypeError("The index argument must be string or integer")

Expand All @@ -92,7 +92,7 @@ def addPolyline(self, polyline, name=None):

name = polyline.getName()
if name and name in self:
raise KeyError("The polyline collection already has an object:%s" % name)
raise KeyError(f"The polyline collection already has an object:{name}")

if polyline.isReference():
self._add_polyline(polyline, False)
Expand All @@ -102,7 +102,7 @@ def addPolyline(self, polyline, name=None):

def createPolyline(self, name=None):
if name and name in self:
raise KeyError("The polyline collection already has an object:%s" % name)
raise KeyError(f"The polyline collection already has an object:{name}")

polyline = self._create_polyline(name)
polyline.setParent(parent=self)
Expand Down
6 changes: 3 additions & 3 deletions python/resdata/geometry/geo_pointset.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ class GeoPointset(BaseCClass):
def __init__(self, external_z=False):
c_ptr = self._alloc(external_z)
if c_ptr:
super(GeoPointset, self).__init__(c_ptr)
super().__init__(c_ptr)
else:
ext = "external" if external_z else "internal"
raise ValueError("Failed to construct GeoPointset with %s_z." % ext)
raise ValueError(f"Failed to construct GeoPointset with {ext}_z.")

@staticmethod
def fromSurface(surface):
Expand All @@ -42,7 +42,7 @@ def __getitem__(self, key):
)
else:
# TODO implement slicing?
raise ValueError("Index must be int, not %s." % type(key))
raise ValueError(f"Index must be int, not {type(key)}.")

def __len__(self):
return self._get_size()
Expand Down
8 changes: 3 additions & 5 deletions python/resdata/geometry/geo_region.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,16 @@ def __init__(self, pointset, preselect=False):
self._preselect = bool(preselect)
c_ptr = self._alloc(pointset, self._preselect)
if c_ptr:
super(GeoRegion, self).__init__(c_ptr)
super().__init__(c_ptr)
else:
raise ValueError(
"Could not construct GeoRegion from pointset %s." % pointset
)
raise ValueError(f"Could not construct GeoRegion from pointset {pointset}.")

def getActiveList(self):
return self._get_index_list()

def _assert_polygon(self, polygon):
if not isinstance(polygon, CPolyline):
raise ValueError("Need to select with a CPolyline, not %s." % type(polygon))
raise ValueError(f"Need to select with a CPolyline, not {type(polygon)}.")

def _construct_cline(self, line):
"""Takes a line ((x1,y1), (x2,y2)) and returns two double[2]* but
Expand Down
5 changes: 2 additions & 3 deletions python/resdata/geometry/geometry_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from math import sqrt


class GeometryTools(object):
class GeometryTools:
EPSILON = 0.000001

@staticmethod
Expand Down Expand Up @@ -400,8 +400,7 @@ def connectPolylines(polyline, target_polyline):

if len(d_list) == 0:
raise ValueError(
"Polyline %s can not be extended to %s"
% (polyline.getName(), target_polyline.getName())
f"Polyline {polyline.getName()} can not be extended to {target_polyline.getName()}"
)

d_list.sort(key=lambda x: x[0])
Expand Down
6 changes: 3 additions & 3 deletions python/resdata/geometry/polyline.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
from .geometry_tools import GeometryTools


class Polyline(object):
class Polyline:
def __init__(self, name=None, init_points=None):
super(Polyline, self).__init__()
super().__init__()
self.__name = name
self.__points = []
if init_points:
Expand All @@ -14,7 +14,7 @@ def __init__(self, name=None, init_points=None):
def __str__(self):
s = "Polyline:[ "
for p in self:
s += "(%s,%s) " % (p[0], p[1])
s += f"({p[0]},{p[1]}) "
s += "]"
return s

Expand Down
26 changes: 10 additions & 16 deletions python/resdata/geometry/surface.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from __future__ import division

"""
Create a polygon
"""

import os.path
import ctypes

Expand Down Expand Up @@ -67,18 +66,17 @@ def __init__(
filename = str(filename)
if os.path.isfile(filename):
c_ptr = self._alloc(filename, True)
super(Surface, self).__init__(c_ptr)
super().__init__(c_ptr)
else:
raise IOError('No such file "%s".' % filename)
raise OSError(f'No such file "{filename}".')
else:
s_args = [nx, ny, xinc, yinc, xstart, ystart, angle]
if None in s_args:
raise ValueError(
"Missing argument for creating surface, all values must be set, was: %s"
% str(s_args)
f"Missing argument for creating surface, all values must be set, was: {str(s_args)}"
)
c_ptr = self._new(*s_args)
super(Surface, self).__init__(c_ptr)
super().__init__(c_ptr)

def __eq__(self, other):
"""
Expand Down Expand Up @@ -203,7 +201,7 @@ def __setitem__(self, index, value):

self._iset_zvalue(index, value)
else:
raise TypeError("Invalid index type:%s - must be integer" % index)
raise TypeError(f"Invalid index type:{index} - must be integer")

def __getitem__(self, index):
if isinstance(index, int):
Expand All @@ -218,7 +216,7 @@ def __getitem__(self, index):
"Invalid index:%d - valid range [0,%d)" % (index, len(self))
)
else:
raise TypeError("Invalid index type:%s - must be integer" % index)
raise TypeError(f"Invalid index type:{index} - must be integer")

def getXY(self, index):
"""Gets the index'th (x,y) coordinate"""
Expand All @@ -232,7 +230,7 @@ def getXY(self, index):
)
index = idx
else:
raise TypeError("Invalid index type:%s - must be integer" % index)
raise TypeError(f"Invalid index type:{index} - must be integer")

x = ctypes.c_double()
y = ctypes.c_double()
Expand All @@ -252,13 +250,9 @@ def getPointset(self):
def _assert_idx_or_i_and_j(self, idx, i, j):
if idx is None:
if i is None or j is None:
raise ValueError(
"idx is None, i and j must be ints, was %s and %s." % (i, j)
)
raise ValueError(f"idx is None, i and j must be ints, was {i} and {j}.")
elif i is not None or j is not None:
raise ValueError(
"idx is set, i and j must be None, was %s and %s." % (i, j)
)
raise ValueError(f"idx is set, i and j must be None, was {i} and {j}.")

def getXYZ(self, idx=None, i=None, j=None):
"""Returns a tuple of 3 floats, (x,y,z) for given global index, or i and j."""
Expand Down
12 changes: 6 additions & 6 deletions python/resdata/geometry/xyz_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@
from .polyline import Polyline


class XYZIo(object):
class XYZIo:
@staticmethod
def readXYZFile(path):
"""@rtype: Polyline"""

if not os.path.exists(path):
raise IOError("Path does not exist '%s'!" % path)
raise OSError(f"Path does not exist '{path}'!")

name = os.path.basename(path)

polyline = Polyline(name=name)

with open(path, "r") as f:
with open(path) as f:
for line in f:
line = line.strip()
if line:
Expand All @@ -34,13 +34,13 @@ def readXYFile(path):
"""@rtype: Polyline"""

if not os.path.exists(path):
raise IOError("Path does not exist '%s'!" % path)
raise OSError(f"Path does not exist '{path}'!")

name = os.path.basename(path)

polyline = Polyline(name=name)

with open(path, "r") as f:
with open(path) as f:
for line in f:
x, y = map(float, line.split())
polyline.addPoint(x, y)
Expand All @@ -54,4 +54,4 @@ def saveXYFile(polyline, filename):
"""
with open(filename, "w") as fileH:
for p in polyline:
fileH.write("%g %g\n" % (p[0], p[1]))
fileH.write(f"{p[0]:g} {p[1]:g}\n")
2 changes: 1 addition & 1 deletion python/resdata/gravimetry/rd_grav.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def __init__(self, grid: Grid, init_file: ResdataFile):
self.init_file = init_file # Inhibit premature garbage collection of init_file

c_ptr = self._grav_alloc(grid, init_file)
super(ResdataGrav, self).__init__(c_ptr)
super().__init__(c_ptr)

self.dispatch = {
"FIP": self.add_survey_FIP,
Expand Down
14 changes: 7 additions & 7 deletions python/resdata/gravimetry/rd_subsidence.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __init__(self, grid, init_file):
"""
self.init_file = init_file # Inhibit premature garbage collection of init_file
c_ptr = self._alloc(grid, init_file)
super(ResdataSubsidence, self).__init__(c_ptr)
super().__init__(c_ptr)

def __contains__(self, survey_name):
return self._has_survey(survey_name)
Expand Down Expand Up @@ -96,10 +96,10 @@ def eval_geertsma(
region=None,
):
if not base_survey in self:
raise KeyError("No such survey: %s" % base_survey)
raise KeyError(f"No such survey: {base_survey}")

if monitor_survey is not None and not monitor_survey in self:
raise KeyError("No such survey: %s" % monitor_survey)
raise KeyError(f"No such survey: {monitor_survey}")

return self._eval_geertsma(
base_survey,
Expand All @@ -124,10 +124,10 @@ def eval_geertsma_rporv(
region=None,
):
if not base_survey in self:
raise KeyError("No such survey: %s" % base_survey)
raise KeyError(f"No such survey: {base_survey}")

if monitor_survey is not None and not monitor_survey in self:
raise KeyError("No such survey: %s" % monitor_survey)
raise KeyError(f"No such survey: {monitor_survey}")

return self._eval_geertsma_rporv(
base_survey,
Expand Down Expand Up @@ -174,10 +174,10 @@ def eval(
The argument @compressibility is the total reservoir compressibility.
"""
if not base_survey in self:
raise KeyError("No such survey: %s" % base_survey)
raise KeyError(f"No such survey: {base_survey}")

if not monitor_survey in self:
raise KeyError("No such survey: %s" % monitor_survey)
raise KeyError(f"No such survey: {monitor_survey}")

return self._eval(
base_survey,
Expand Down
Loading

0 comments on commit e8b4f18

Please sign in to comment.