Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use ruff as linter and formatter #1012

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
85 changes: 0 additions & 85 deletions cmake/create_cmakelists.py

This file was deleted.

43 changes: 43 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,45 @@
[build-system]
requires = ["setuptools", "setuptools_scm", "wheel", "scikit-build", "cmake", "conan<2", "ninja"]

[tool.ruff]
src = ["python"]
line-length = 88
target-version = "py38"
extend-exclude = ["python/resdata/util/util/version.py"]

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

[tool.ruff.lint.pylint]
max-args = 15
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 _, 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 _, p in GeometryTools.rayPolygonIntersections(
p0, ray, target_polyline
):
d_list.append((GeometryTools.distance(p0, p), [p0, p]))

if len(d_list) == 0:
Expand Down
Loading