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

formatting python via black #792

Merged
merged 2 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
22 changes: 9 additions & 13 deletions pyphare/pyphare/core/box.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@
from .phare_utilities import np_array_ify, is_scalar, is_nd_array





class Box:
"""represents a box in AMR index cell
lower, upper : lower and upper cell AMR indexes
Expand All @@ -14,11 +11,10 @@ def __init__(self, lower, upper):
lower, upper = [np_array_ify(arr) for arr in [lower, upper]]
assert lower.shape == upper.shape
assert (lower <= upper).all()
self.lower = lower.astype(int) # can't slice with floats
self.lower = lower.astype(int) # can't slice with floats
self.upper = upper.astype(int)
self.ndim = len(self.lower)


def __mul__(self, box2):
"""
return the box resulting from the intersection
Expand All @@ -32,25 +28,21 @@ def __mul__(self, box2):
if (lower <= upper).all():
return Box(lower, upper)


@property
def shape(self):
"""returns the length per dimension"""
return (self.upper - self.lower) + 1


def nCells(self):
"""returns the number of cells in the box"""
return self.shape.prod()


def __str__(self):
return "Box({},{})".format(self.lower.tolist(), self.upper.tolist())

def __repr__(self):
return self.__str__()


def __contains__(self, item):
"""true if item is completely within self"""
if not isinstance(item, Box):
Expand All @@ -62,9 +54,12 @@ def __contains__(self, item):

return (item.lower >= self.lower).all() and (item.upper <= self.upper).all()


def __eq__(self, other):
return isinstance(other, Box) and (self.lower == other.lower).all() and (self.upper == other.upper).all()
return (
isinstance(other, Box)
and (self.lower == other.lower).all()
and (self.upper == other.upper).all()
)

def __sub__(self, other):
assert isinstance(other, Box)
Expand All @@ -82,7 +77,6 @@ def _get(self, p):
super().__init__(_get(dim, l), _get(dim, u))



class Box1D(nDBox):
def __init__(self, l, u):
super().__init__(1, l, u)
Expand Down Expand Up @@ -121,6 +115,7 @@ def grow(box, size):
raise ValueError("size must be >=0")
return Box(box.lower - size, box.upper + size)


def shrink(box, size):
if is_scalar(size) and box.ndim > 1:
raise ValueError("box.py: shrink must use a list for dimension > 1")
Expand Down Expand Up @@ -171,7 +166,8 @@ def copy(arr, replace):
miny = intersection.lower[1] if "down" in boxes else box.lower[1]
maxy = intersection.upper[1] if "up" in boxes else box.upper[1]
if intersection.lower[2] > box.lower[2]:
boxes["back"] = Box(copy(box.lower, {0: minx, 1: miny}),
boxes["back"] = Box(
copy(box.lower, {0: minx, 1: miny}),
copy(intersection.lower - 1, {0: maxx, 1: maxy}),
)
if intersection.upper[2] < box.upper[2]:
Expand Down
3 changes: 0 additions & 3 deletions pyphare/pyphare/core/gridlayout.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ def __init__(self):
def yeeCoordsFor(
origin, nbrGhosts, dl, nbrCells, qty, direction, withGhosts=False, **kwargs
):

assert direction in direction_to_dim, f"direction ({direction} not supported)"
if qty in yee_centering_lower[direction] and qty not in yee_centering[direction]:
qty = qty[0].upper() + qty[1:]
Expand Down Expand Up @@ -391,7 +390,6 @@ def fieldCoords(self, knode, iStart, qty, direction, ds, origin, derivOrder):
# changeCentering( qtyCentering(qty, direct), 1 )
#
def changeCentering(self, centering, derivOrder=0):

newCentering = centering

# if derivOrder is odd the centering is changed
Expand All @@ -402,7 +400,6 @@ def changeCentering(self, centering, derivOrder=0):

# -------------------------------------------------------
def swapCentering(self, centering):

newCentering = "primal"

if centering == "primal":
Expand Down
31 changes: 21 additions & 10 deletions pyphare/pyphare/core/phare_utilities.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import math
import numpy as np


def all_iterables(*args):
"""
return true if all arguments are either lists or tuples
Comment on lines 5 to 7
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docstring for all_iterables should be inside the function body for proper association with the function.

-  6:
-    """
-  7:
-    return true if all arguments are either lists or tuples
+  6:    """
+  7:    return true if all arguments are either lists or tuples
+  8:    """

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
def all_iterables(*args):
"""
return true if all arguments are either lists or tuples
def all_iterables(*args):
"""
return true if all arguments are either lists or tuples
"""

Expand All @@ -12,7 +13,9 @@ def none_iterable(*args):
"""
return true if none of the arguments are either lists or tuples
"""
Comment on lines 13 to 15
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docstring for none_iterable should also be inside the function body.

-  14:
-    """
-  15:
-    return true if none of the arguments are either lists or tuples
+  14:    """
+  15:    return true if none of the arguments are either lists or tuples
+  16:    """

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"""
return true if none of the arguments are either lists or tuples
"""
"""
return true if none of the arguments are either lists or tuples
"""

return all([not isinstance(arg, list) and not isinstance(arg, tuple) for arg in args])
return all(
[not isinstance(arg, list) and not isinstance(arg, tuple) for arg in args]
)


def equal_size(*args):
Expand Down Expand Up @@ -51,7 +54,7 @@ def is_nd_array(arg):
return isinstance(arg, np.ndarray)


def np_array_ify(arg, size = 1):
def np_array_ify(arg, size=1):
if is_scalar(arg):
return np.asarray([arg] * size)
if not is_nd_array(arg):
Expand All @@ -62,7 +65,7 @@ def np_array_ify(arg, size = 1):
refinement_ratio = 2


def not_in_keywords_list(kwd_list,**kwargs):
def not_in_keywords_list(kwd_list, **kwargs):
"""
return the list of kwargs keys that are not in 'kwd_list'
"""
Comment on lines +68 to 71
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docstring for not_in_keywords_list should be inside the function body.

-  69:
-    """
-  70:
-    return the list of kwargs keys that are not in 'kwd_list'
+  69:    """
+  70:    return the list of kwargs keys that are not in 'kwd_list'
+  71:    """

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
def not_in_keywords_list(kwd_list, **kwargs):
"""
return the list of kwargs keys that are not in 'kwd_list'
"""
def not_in_keywords_list(kwd_list, **kwargs):
"""
return the list of kwargs keys that are not in 'kwd_list'
"""

Expand All @@ -76,23 +79,26 @@ def check_mandatory_keywords(mandatory_kwd_list, **kwargs):
"""
return those of mandatory_kwd_list not found in the kwargs keys
"""
Comment on lines 79 to 81
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docstring for check_mandatory_keywords should be inside the function body.

-  80:
-    """
-  81:
-    return those of mandatory_kwd_list not found in the kwargs keys
+  80:    """
+  81:    return those of mandatory_kwd_list not found in the kwargs keys
+  82:    """

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"""
return those of mandatory_kwd_list not found in the kwargs keys
"""
"""
return those of mandatory_kwd_list not found in the kwargs keys
"""

keys = [k for k in kwargs.keys()]
keys = [k for k in kwargs.keys()]
check = [(mk, mk in keys) for mk in mandatory_kwd_list]
return [mk[0] for mk in check if mk[1] is False]


def fp_equal(a, b, atol=1e-6):
return math.isclose(a, b, abs_tol=atol)


def fp_less_equal(a, b, atol=1e-6):
return fp_equal(a, b, atol=atol) or a < b


def fp_gtr_equal(a, b, atol=1e-6):
return fp_equal(a, b, atol=atol) or a > b


class FloatingPoint_comparator:
def __init__(self, fp, atol=1e-6):
self.fp = fp
self.fp = fp
self.atol = atol

def __eq__(self, other):
Expand Down Expand Up @@ -120,27 +126,33 @@ def run_cli_cmd(cmd, shell=True, capture_output=True, check=False, print_cmd=Fal
https://docs.python.org/3/library/subprocess.html
"""
import subprocess

if print_cmd:
print(f"running: {cmd}")
try:
return subprocess.run(cmd, shell=shell, capture_output=capture_output, check=check)
except subprocess.CalledProcessError as e: # only triggers on failure if check=True
return subprocess.run(
cmd, shell=shell, capture_output=capture_output, check=check
)
except subprocess.CalledProcessError as e: # only triggers on failure if check=True
raise RuntimeError(decode_bytes(e.stderr))


def git_hashes(N=1):
return decode_bytes(run_cli_cmd(f"git log -{N} --pretty=format:%h").stdout).splitlines()
return decode_bytes(
run_cli_cmd(f"git log -{N} --pretty=format:%h").stdout
).splitlines()


def top_git_hash():
hashes = git_hashes(1)
if len(hashes) > 0:
return hashes[0]
return "master" # github actions fails?
return "master" # github actions fails?


def print_trace():
import sys, traceback

_, _, tb = sys.exc_info()
traceback.print_tb(tb)

Expand All @@ -158,4 +170,3 @@ def deep_copy(item, memo, excludes=[]):
else:
setattr(that, key, deepcopy(value, memo))
return that

4 changes: 3 additions & 1 deletion pyphare/pyphare/cpp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

# continue to use override if set
_cpp_lib_override = None


def cpp_lib(override=None):
import importlib

Expand All @@ -21,12 +21,14 @@ def cpp_lib(override=None):

def cpp_etc_lib():
import importlib

return importlib.import_module("pybindlibs.cpp_etc")
Comment on lines 22 to +24
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The importlib import statement is inside the cpp_etc_lib function body. If this is intentional to avoid import side-effects or circular dependencies, it's acceptable; otherwise, consider moving it to the top for consistency and clarity.



def splitter_type(dim, interp, n_particles):
return getattr(cpp_lib(), f"Splitter_{dim}_{interp}_{n_particles}")


def create_splitter(dim, interp, n_particles):
return splitter_type(dim, interp, n_particles)()

Expand Down
18 changes: 10 additions & 8 deletions pyphare/pyphare/data/wrangler.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@


from pyphare.core import gridlayout

class DataWrangler:

class DataWrangler:
def __init__(self, simulator):
from .. import pharein as ph
from pyphare.cpp import cpp_lib

self.dim = ph.global_vars.sim.ndim
self.interp = ph.global_vars.sim.interp_order
self.refined_particle_nbr = ph.global_vars.sim.refined_particle_nbr
self.cpp = getattr(cpp_lib(), f"DataWrangler_{self.dim}_{self.interp}_{self.refined_particle_nbr}")\
(simulator.cpp_sim, simulator.cpp_hier)
self.cpp = getattr(
cpp_lib(),
f"DataWrangler_{self.dim}_{self.interp}_{self.refined_particle_nbr}",
)(simulator.cpp_sim, simulator.cpp_hier)

def kill(self):
del self.cpp


def getNumberOfLevels(self):
return self.cpp.getNumberOfLevels()

Expand Down Expand Up @@ -49,14 +48,17 @@ def lvl0PopFluxes(self):
}

def extract_is_primal_key_from(self, em_xyz):
""" extract "Ex" from "EM_E_x" """
"""extract "Ex" from "EM_E_x" """
return "".join(em_xyz.split("_"))[2:]

def lvl0EM(self):
return {
em: {
em_xyz: self.cpp.sync_merge(
data, gridlayout.yee_element_is_primal(self.extract_is_primal_key_from(em_xyz))
data,
gridlayout.yee_element_is_primal(
self.extract_is_primal_key_from(em_xyz)
),
)
for em_xyz, data in xyz_map.items()
}
Expand Down
Loading
Loading