Skip to content

Commit

Permalink
Use ruff as linter and formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
larsevj committed Aug 25, 2024
1 parent 4d70d65 commit c9b9dc3
Show file tree
Hide file tree
Showing 76 changed files with 412 additions and 538 deletions.
13 changes: 10 additions & 3 deletions .github/workflows/style.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
2 changes: 1 addition & 1 deletion cmake/create_cmakelists.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
41 changes: 41 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,43 @@
[build-system]
requires = ["setuptools", "setuptools_scm", "wheel", "scikit-build", "cmake", "conan<2", "ninja"]

[tool.ruff]
src = ["python"]
line-length = 88

[tool.ruff.lint]
select = [
"W", # pycodestyle
# "I", # isort ( Issues with circular imports and cwrap)
"B", # flake-8-bugbear
"SIM", # flake-8-simplify
"F", # pyflakes
"PL", # pylint
"NPY", # numpy specific rules
"C4", # flake8-comprehensions
"PD", # pandas-vet
]
ignore = ["PLW2901", # redefined-loop-name
"PLR2004", # magic-value-comparison
"PLR0915", # too-many-statements
"PLR0912", # too-many-branches
"PLR0911", # too-many-return-statements
"PLC2701", # import-private-name
"PLR6201", # literal-membership
"PLR0914", # too-many-locals
"PLR6301", # no-self-use
"PLW1641", # eq-without-hash
"PLR0904", # too-many-public-methods
"PLR1702", # too-many-nested-blocks
"PLW3201", # bad-dunder-method-name
"PD901",
"C409",
"PLC0414",
"F401",
"F841",
]
[tool.ruff.lint.extend-per-file-ignores]
"python/tests/util_tests/test_ctime.py" = ["PLR0124", "B015"]

[tool.ruff.lint.pylint]
max-args = 15
13 changes: 4 additions & 9 deletions python/docs/examples/avg_pressure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import sys

import matplotlib.pyplot as plt

from resdata.grid import Grid, ResdataRegion
from resdata.resfile import ResdataFile, ResdataRestartFile

Expand All @@ -19,15 +20,9 @@ def avg_pressure(p, sw, pv, region, region_id, result):

p1 = p.sum(mask=region) / region.active_size()

if total_pv > 0:
p2 = p_pv.sum(mask=region) / total_pv
else:
p2 = None
p2 = p_pv.sum(mask=region) / total_pv if total_pv > 0 else None

if total_hc_pv > 0:
p3 = p_hc_pv.sum(mask=region) / total_hc_pv
else:
p3 = None
p3 = p_hc_pv.sum(mask=region) / total_hc_pv if total_hc_pv > 0 else None
else:
p1 = None
p2 = None
Expand Down Expand Up @@ -71,7 +66,7 @@ def avg_pressure(p, sw, pv, region, region_id, result):
avg_pressure(p, sw, pv, ResdataRegion(grid, True), "field", result)
sim_days.append(header.get_sim_days())

for key in result.keys():
for key in result:
plt.figure(1)
for index, p in enumerate(result[key]):
plt.plot(sim_days, p, label="Region:%s P%d" % (key, index + 1))
Expand Down
5 changes: 3 additions & 2 deletions python/docs/examples/grid_info.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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)
8 changes: 4 additions & 4 deletions python/resdata/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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)
Expand All @@ -102,11 +102,11 @@ def __init__(self, prototype, bind=True):

from .rd_type import ResDataType, ResdataTypeEnum
from .rd_util import (
FileType,
FileMode,
FileType,
Phase,
UnitSystem,
ResdataUtil,
UnitSystem,
)
from .util.util import ResdataVersion, updateAbortSignals

Expand Down
12 changes: 4 additions & 8 deletions python/resdata/geometry/cpolyline.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
import os.path

from cwrap import BaseCClass

from resdata import ResdataPrototype

from .geometry_tools import GeometryTools


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
9 changes: 4 additions & 5 deletions python/resdata/geometry/cpolyline_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,10 @@ def shallowCopy(self):
def addPolyline(self, polyline, name=None):
if not isinstance(polyline, CPolyline):
polyline = CPolyline(init_points=polyline, name=name)
else:
if not name is None:
raise ValueError(
"The name keyword argument can only be supplied when add not CPOlyline object"
)
elif not name is None:
raise ValueError(
"The name keyword argument can only be supplied when add not CPOlyline object"
)

name = polyline.getName()
if name and name in self:
Expand Down
4 changes: 2 additions & 2 deletions python/resdata/geometry/geo_region.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class GeoRegion(BaseCClass):
)

def __init__(self, pointset, preselect=False):
self._preselect = True if preselect else False
self._preselect = bool(preselect)
c_ptr = self._alloc(pointset, self._preselect)
if c_ptr:
super(GeoRegion, self).__init__(c_ptr)
Expand All @@ -68,7 +68,7 @@ def _construct_cline(self, line):
x2, y2 = map(float, p2)
except Exception as err:
err_msg = "Select with pair ((x1,y1), (x2,y2)), not %s (%s)."
raise ValueError(err_msg % (line, err))
raise ValueError(err_msg % (line, err)) from err
x1x2_ptr = cpair(x1, x2)
y1y2_ptr = cpair(y1, y2)
return x1x2_ptr, y1y2_ptr
Expand Down
37 changes: 16 additions & 21 deletions python/resdata/geometry/geometry_tools.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from math import sqrt
import functools
import sys
from math import sqrt


class GeometryTools(object):
Expand Down Expand Up @@ -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

Expand All @@ -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)
Expand All @@ -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]]

Expand All @@ -196,17 +191,13 @@ def slicePolygon(bounding_polygon, poly_line):
tmp = GeometryTools.rayPolygonIntersections(p1, ray1, bounding_polygon)
intersection1 = GeometryTools.rayPolygonIntersections(
p1, ray1, bounding_polygon
)[
0
] # assume convex
)[0] # assume convex

p2 = poly_line[-1]
ray2 = GeometryTools.lineToRay(poly_line[-2], poly_line[-1])
intersection2 = GeometryTools.rayPolygonIntersections(
p2, ray2, bounding_polygon
)[
0
] # assume convex
)[0] # assume convex

# Check for intersection between the polyline extensions on the inside of the bounadary
internal_intersection = GeometryTools.lineIntersection(
Expand Down Expand Up @@ -394,13 +385,17 @@ def connectPolylines(polyline, target_polyline):
p0 = polyline[-1]
p1 = polyline[-2]
ray = GeometryTools.lineToRay(p1, p0)
for index, p in GeometryTools.rayPolygonIntersections(p0, ray, target_polyline):
for _index, p in GeometryTools.rayPolygonIntersections(
p0, ray, target_polyline
):
d_list.append((GeometryTools.distance(p0, p), [p0, p]))

p0 = polyline[0]
p1 = polyline[1]
ray = GeometryTools.lineToRay(p1, p0)
for index, p in GeometryTools.rayPolygonIntersections(p0, ray, target_polyline):
for _index, p in GeometryTools.rayPolygonIntersections(
p0, ray, target_polyline
):
d_list.append((GeometryTools.distance(p0, p), [p0, p]))

if len(d_list) == 0:
Expand Down
12 changes: 3 additions & 9 deletions python/resdata/geometry/polyline.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import collections

from .geometry_tools import GeometryTools


Expand Down Expand Up @@ -40,20 +41,13 @@ def __eq__(self, other):
if len(self) != len(other):
return False

for p1, p2 in zip(self, other):
if p1 != p2:
return False

return True
return all(p1 == p2 for p1, p2 in zip(self, other))

def __len__(self):
return len(self.__points)

def addPoint(self, x, y, z=None):
if z is None:
p = (x, y)
else:
p = (x, y, z)
p = (x, y) if z is None else (x, y, z)
self.__points.append(p)

def __getitem__(self, index):
Expand Down
9 changes: 4 additions & 5 deletions python/resdata/geometry/surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
10 changes: 4 additions & 6 deletions python/resdata/gravimetry/rd_subsidence.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion python/resdata/grid/cell.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading

0 comments on commit c9b9dc3

Please sign in to comment.