Skip to content

Commit

Permalink
Merge pull request #162 from tataratat/update-pre-commit
Browse files Browse the repository at this point in the history
Update pre commit
  • Loading branch information
j042 authored Oct 4, 2023
2 parents 644115f + b5ddfef commit fc5b9e6
Show file tree
Hide file tree
Showing 26 changed files with 178 additions and 162 deletions.
36 changes: 20 additions & 16 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

# use default options for ci
ci:
autoupdate_schedule: "monthly"
autoupdate_schedule: "weekly"
submodules: false

repos:
Expand All @@ -26,25 +26,29 @@ repos:
- id: requirements-txt-fixer
- id: trailing-whitespace

- repo: https://github.com/asottile/pyupgrade
rev: "v3.14.0"
hooks:
- id: pyupgrade
args: [--py36-plus]

- repo: https://github.com/PyCQA/isort
rev: "5.12.0"
hooks:
- id: isort

- repo: https://github.com/psf/black
rev: "23.9.1"
hooks:
- id: black
args: [--line-length=79]

- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.291
hooks:
- id: ruff
args: [
--fix,
--exit-non-zero-on-fix,
]

- repo: https://github.com/codespell-project/codespell
rev: v2.2.5
hooks:
- id: codespell
args: [-w]

- repo: https://github.com/keewis/blackdoc
rev: v0.3.8
hooks:
- id: flake8
args: [--extend-ignore=E203]
- id: blackdoc
args: [--line-length=75]
4 changes: 1 addition & 3 deletions docs/source/handle_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,7 @@ def process_file(
links = get_markdown_links(content)

for item in links:
if item[1].startswith(
tuple(["http", "#"])
): # skip http links and anchors
if item[1].startswith(("http", "#")): # skip http links and anchors
content = content.replace(
f"[{item[0]}]({item[1]})",
f"<a href='{item[1]}'>{item[0]}</a>",
Expand Down
2 changes: 1 addition & 1 deletion examples/load_sample_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ def load_sample_file(filename: str, force_reload: bool = False) -> bool:
f.write(response.content)
return True
else:
print(f"Cant load {url}, status code: {response.status_code}.")
print(f"Can't load {url}, status code: {response.status_code}.")
return False
10 changes: 7 additions & 3 deletions examples/run_all_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@
files_not_completed = []

for file in glob.glob(str(pathlib.Path(__file__).parent) + "/*.py"):
if file.split("/")[-1] == "run_all_examples.py":
if file.split("/")[-1] in [
"run_all_examples.py",
"load_sample_file.py",
]:
continue
print(f"Calling {file}")
proc_return = subprocess.run([sys.executable, file])
if proc_return.returncode != 0:
try:
proc_return = subprocess.run([sys.executable, file], check=True)
except subprocess.CalledProcessError:
files_not_completed.append(file)
if len(files_not_completed) > 0:
print(
Expand Down
8 changes: 3 additions & 5 deletions gustaf/create/edges.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,10 @@ def from_data(gus_obj, data, scale=None, data_norm=None):
if scale is None:
if isinstance(data, str):
norm = gus_obj.vertex_data.as_scalar(data, None, True)
elif data_norm is None:
norm = np.linalg.norm(increment, axis=1)
else:
# compute
if data_norm is None:
norm = np.linalg.norm(increment, axis=1)
else:
norm = np.asanyarray(data_norm)
norm = np.asanyarray(data_norm)

max_data_norm = norm.max()
aabb_diagonal_norm = gus_obj.bounds_diagonal_norm()
Expand Down
15 changes: 9 additions & 6 deletions gustaf/create/faces.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
from gustaf.faces import Faces


def box(
bounds=[[0, 0], [1, 1]], resolutions=[2, 2], simplex=False, backslash=False
):
def box(bounds=None, resolutions=None, simplex=False, backslash=False):
"""Create structured quadrangle or triangle block mesh.
Parameters
Expand All @@ -27,6 +25,10 @@ def box(
face_mesh: Volumes
"""

if resolutions is None:
resolutions = [2, 2]
if bounds is None:
bounds = [[0, 0], [1, 1]]
if np.array(bounds).shape != (2, 2):
raise ValueError("Bounds must have a dimension of (2, 2).")
if len(resolutions) != 2:
Expand Down Expand Up @@ -56,7 +58,7 @@ def to_simplex(quad, alternate=False):
vice versa. Will return a tri-mesh, if input is triangular.
Default diagonalization looks like this:
.. code-block::
.. code-block:: text
(3) *---* (2)
| /|
Expand All @@ -66,7 +68,7 @@ def to_simplex(quad, alternate=False):
resembling 'slash'.
.. code-block::
.. code-block:: text
(3) *---* (2)
|\\ |
Expand Down Expand Up @@ -136,7 +138,8 @@ def to_quad(tri):
each triangle face. Warning: mesh quality could be bad!
``(new) Quad Face``
.. code-block::
.. code-block:: text
Ref: (node_ind), face_ind
Expand Down
2 changes: 1 addition & 1 deletion gustaf/create/vertices.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def raster(
if len(resolutions) != len(bounds[0]) == len(bounds[1]):
raise ValueError("Length of resolutions and bounds should match.")

slices = list()
slices = []
for b0, b1, r in zip(bounds[0], bounds[1], resolutions):
slices.append(slice(b0, b1, int(r) * 1j))

Expand Down
6 changes: 5 additions & 1 deletion gustaf/create/volumes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from gustaf.volumes import Volumes


def box(bounds=[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]], resolutions=[2, 2, 2]):
def box(bounds=None, resolutions=None):
"""Create structured hexahedron block mesh.
Parameters
Expand All @@ -23,6 +23,10 @@ def box(bounds=[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]], resolutions=[2, 2, 2]):
volume_mesh: Volumes
"""

if resolutions is None:
resolutions = [2, 2, 2]
if bounds is None:
bounds = [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]
if np.array(bounds).shape != (2, 3):
raise ValueError("Bounds must have a dimension of (2, 3).")
if len(resolutions) != 3:
Expand Down
2 changes: 1 addition & 1 deletion gustaf/edges.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ def dashed(self, spacing=None):
``dashed edges``
.. code-block::
.. code-block:: text
o--------o o--------o o--------o
|<------>| |<-->|
Expand Down
2 changes: 1 addition & 1 deletion gustaf/faces.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def __init__(
elif elements is not None:
self.faces = elements

self.BC = dict()
self.BC = {}

@helpers.data.ComputedMeshData.depends_on(["elements"])
def edges(self):
Expand Down
35 changes: 18 additions & 17 deletions gustaf/helpers/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __array_finalize__(self, obj):
"""Sets default flags for any arrays that maybe generated based on
tracked array."""
self._modified = True
self._source = int(0)
self._source = 0

if isinstance(obj, type(self)):
if isinstance(obj._source, int):
Expand All @@ -53,7 +53,7 @@ def _set_modified(self):
if isinstance(self._source, type(self)):
self._source._modified = True

def copy(self, *args, **kwargs):
def copy(self, *_args, **_kwargs):
"""copy gives np.ndarray.
no more tracking.
Expand Down Expand Up @@ -170,10 +170,11 @@ def make_tracked_array(array, dtype=None, copy=True):
array = []
# make sure it is contiguous then view it as our subclass
tracked = np.ascontiguousarray(array, dtype=dtype)
if copy:
tracked = tracked.copy().view(TrackedArray)
else:
tracked = tracked.view(TrackedArray)
tracked = (
tracked.copy().view(TrackedArray)
if copy
else tracked.view(TrackedArray)
)

# should always be contiguous here
assert tracked.flags["C_CONTIGUOUS"]
Expand All @@ -196,7 +197,7 @@ def __init__(self, helpee):
GustafBase objects would probably make the most sense here.
"""
self._helpee = helpee
self._saved = dict()
self._saved = {}

def __setitem__(self, key, value):
"""Raise Error to disable direct value setting.
Expand All @@ -222,7 +223,7 @@ def __getitem__(self, key):
--------
value: object
"""
if key in self._saved.keys():
if key in self._saved:
return self._saved[key]

else:
Expand All @@ -247,7 +248,7 @@ def clear(self):
"""
Clears saved data by reassigning new dict
"""
self._saved = dict()
self._saved = {}

def get(self, key, default_values=None):
"""Returns stored item if the key exists. Else, given default value. If
Expand All @@ -263,7 +264,7 @@ def get(self, key, default_values=None):
--------
value: object
"""
if key in self._saved.keys():
if key in self._saved:
return self._saved[key]
else:
return default_values
Expand Down Expand Up @@ -302,7 +303,7 @@ class ComputedData(DataHolder):

__slots__ = ()

def __init__(self, helpee, **kwargs):
def __init__(self, helpee, **_kwargs):
"""Stores last computed values.
Keys are expected to be the same as helpee's function that computes the
Expand Down Expand Up @@ -334,26 +335,26 @@ def depends_on(cls, var_names, make_property=False):
"""

def inner(func):
# followings are done once while modules are loaded
# following are done once while modules are loaded
# just subclass this class to make a special helper
# for each helpee class.
assert isinstance(var_names, list), "var_names should be a list"
# initialize property
# _depends is dict(str: list)
if cls._depends is None:
cls._depends = dict()
cls._depends = {}
if cls._depends.get(func.__name__, None) is None:
cls._depends[func.__name__] = list()
cls._depends[func.__name__] = []
# add dependency info
cls._depends[func.__name__].extend(var_names)

# _inv_depends is dict(str: list)
if cls._inv_depends is None:
cls._inv_depends = dict()
cls._inv_depends = {}
# add inverse dependency
for vn in var_names:
if cls._inv_depends.get(vn, None) is None:
cls._inv_depends[vn] = list()
cls._inv_depends[vn] = []

cls._inv_depends[vn].append(func.__name__)

Expand All @@ -373,7 +374,7 @@ def compute_or_return_saved(*args, **kwargs):
recompute = kwargs.get("recompute", True)

# computed arrays are called _computed.
# loop over dependees and check if they are modified
# loop over dependencies and check if they are modified
for dependee_str in cls._depends[func.__name__]:
dependee = getattr(self, dependee_str)
# is modified?
Expand Down
Loading

0 comments on commit fc5b9e6

Please sign in to comment.