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

Ruff pyupgrade #1013

Draft
wants to merge 11 commits into
base: main
Choose a base branch
from
Draft
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.

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

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

[tool.ruff.lint]
select = [
"W", # pycodestyle
# "I", # isort ( Issues with circular imports and cwrap)
"B", # flake-8-bugbear
"SIM", # flake-8-simplify
"F", # pyflakes
"PL", # pylint
"NPY", # numpy specific rules
"C4", # flake8-comprehensions
"PD", # pandas-vet
"UP", # pyupgrade
]
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
"PLW1514",
"C419",
]
[tool.ruff.lint.extend-per-file-ignores]
"python/tests/util_tests/test_ctime.py" = ["PLR0124", "B015"]
"python/*tests/*" = ["F841"]
"python/*/__init__.py" = ["F401"]

[tool.ruff.lint.pylint]
max-args = 15
23 changes: 9 additions & 14 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 All @@ -45,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 All @@ -71,9 +66,9 @@ def avg_pressure(p, sw, pv, region, region_id, result):
avg_pressure(p, sw, pv, ResdataRegion(grid, True), "field", result)
sim_days.append(header.get_sim_days())

for key in result.keys():
for key, value in result.items():
plt.figure(1)
for index, p in enumerate(result[key]):
plt.plot(sim_days, p, label="Region:%s P%d" % (key, index + 1))
for index, p in enumerate(value):
plt.plot(sim_days, p, label=f"Region:{key} P{index + 1}")
plt.legend()
plt.show()
4 changes: 2 additions & 2 deletions python/docs/examples/cmp_nnc.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
for g1, g2, T in nnc_list:
# grid_ijk assumes 0-based indexing, g1/g2 are 1-based (FORTRAN)
# Convert them to zero based ones.
g1 = g1 - 1
g2 = g2 - 1
g1 -= 1
g2 -= 1
i1, j1, k1 = grid.get_ijk(global_index=g1)
i2, j2, k2 = grid.get_ijk(global_index=g2)

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)
16 changes: 7 additions & 9 deletions python/resdata/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@


def _dlopen_resdata():
import ctypes
import platform
import ctypes # noqa: PLC0415
import platform # noqa: PLC0415

path = os.path.join(os.path.dirname(__file__), ".libs")
if platform.system() == "Linux":
Expand All @@ -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 @@ -95,18 +95,16 @@ 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
from .rd_util import (
FileType,
FileMode,
FileType,
Phase,
UnitSystem,
ResdataUtil,
UnitSystem,
)
from .util.util import ResdataVersion, updateAbortSignals

Expand Down
32 changes: 13 additions & 19 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 @@ -38,43 +40,40 @@ 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:
polyline._set_name(name)
return polyline

def __str__(self):
def __str__(self) -> str:
name = self.getName()
if name:
str = "%s [" % name
else:
str = "["
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 += "]"
return str

def __repr__(self):
def __repr__(self) -> str:
return str(self)

def __len__(self):
def __len__(self) -> int:
return self._size()

def __getitem__(self, index):
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 All @@ -86,9 +85,7 @@ def __getitem__(self, index):

return (x.value, y.value)
else:
raise IndexError(
"Invalid index:%d valid range: [0,%d)" % (index, len(self))
)
raise IndexError(f"Invalid index:{index} valid range: [0,{len(self)})")

def segmentIntersects(self, p1, p2):
return self._segment_intersects(p1[0], p1[1], p2[0], p2[1])
Expand Down Expand Up @@ -120,7 +117,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 @@ -143,10 +140,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 = f"Extend:{self.getName()}" if self.getName() else None

return CPolyline(name=name, init_points=[(p1[0], p1[1]), p2])
else:
Expand Down
Loading
Loading