Skip to content

Commit 0d84e51

Browse files
black
1 parent cc75556 commit 0d84e51

5 files changed

Lines changed: 64 additions & 82 deletions

File tree

energyml-utils/src/energyml/utils/data/crs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -889,7 +889,7 @@ def extract_crs_info(
889889
"""
890890
if crs_obj is None:
891891
return CrsInfo()
892-
892+
893893
if isinstance(crs_obj, CrsInfo):
894894
return crs_obj
895895

energyml-utils/src/energyml/utils/data/helper.py

Lines changed: 31 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -514,9 +514,9 @@ def hermite_interpolation(md_target, md_start, md_end, p_start, p_end, v_start,
514514

515515
def _interp1d_vectorized(
516516
ctrl_params: np.ndarray, # (K,)
517-
ctrl_pts: np.ndarray, # (K, d)
518-
query: np.ndarray, # (Q,)
519-
) -> np.ndarray: # (Q, d)
517+
ctrl_pts: np.ndarray, # (K, d)
518+
query: np.ndarray, # (Q,)
519+
) -> np.ndarray: # (Q, d)
520520
"""Vectorised piecewise-linear interpolation of a 1-D parametric curve."""
521521
result = np.empty((len(query), ctrl_pts.shape[1]), dtype=np.float64)
522522
for dim in range(ctrl_pts.shape[1]):
@@ -526,9 +526,9 @@ def _interp1d_vectorized(
526526

527527
def _natural_cubic_spline_eval(
528528
ctrl_params: np.ndarray, # (K,)
529-
ctrl_pts: np.ndarray, # (K, d)
530-
query: np.ndarray, # (Q,)
531-
) -> np.ndarray: # (Q, d)
529+
ctrl_pts: np.ndarray, # (K, d)
530+
query: np.ndarray, # (Q,)
531+
) -> np.ndarray: # (Q, d)
532532
"""
533533
Evaluate a natural cubic spline (second derivatives = 0 at endpoints) via
534534
``scipy.interpolate.CubicSpline``.
@@ -552,10 +552,10 @@ def _natural_cubic_spline_eval(
552552

553553
def _minimum_curvature_eval(
554554
ctrl_params: np.ndarray, # (K,) P-values (e.g. depth) at knots
555-
ctrl_pts: np.ndarray, # (K, 3) XYZ at knots
556-
tangents: np.ndarray, # (K, 3) unit tangent vectors at knots
557-
query: np.ndarray, # (Q,) query P-values
558-
) -> np.ndarray: # (Q, 3)
555+
ctrl_pts: np.ndarray, # (K, 3) XYZ at knots
556+
tangents: np.ndarray, # (K, 3) unit tangent vectors at knots
557+
query: np.ndarray, # (Q,) query P-values
558+
) -> np.ndarray: # (Q, 3)
559559
"""
560560
Minimum-curvature interpolation (RESQML line kind 5).
561561
@@ -612,10 +612,10 @@ def _minimum_curvature_eval(
612612
def _evaluate_one_pillar(
613613
kind: int,
614614
ctrl_params: Optional[np.ndarray], # (K,) — may be None for kind=0
615-
ctrl_pts: np.ndarray, # (K, d) — d=2 for kind=0, d=3 otherwise
616-
tangents: Optional[np.ndarray], # (K, 3) — only for kinds 3, 5
617-
query_params: np.ndarray, # (Q,) query P-values for this pillar
618-
) -> np.ndarray: # (Q, 3)
615+
ctrl_pts: np.ndarray, # (K, d) — d=2 for kind=0, d=3 otherwise
616+
tangents: Optional[np.ndarray], # (K, 3) — only for kinds 3, 5
617+
query_params: np.ndarray, # (Q,) query P-values for this pillar
618+
) -> np.ndarray: # (Q, 3)
619619
"""
620620
Evaluate a single parametric pillar at *query_params*, returning `(Q, 3)` XYZ.
621621
@@ -728,14 +728,10 @@ def resolve_parametric_line_array(
728728
# ParametricLineFromRepresentationLatticeArray path (RESQML v2.0.1).
729729
supporting_rep_dor = getattr(parametric_lines_obj, "supporting_representation", None)
730730
if supporting_rep_dor is None:
731-
raise ValueError(
732-
"ParametricLineFromRepresentationLatticeArray has no supporting_representation reference."
733-
)
731+
raise ValueError("ParametricLineFromRepresentationLatticeArray has no supporting_representation reference.")
734732

735733
if workspace is None:
736-
raise ValueError(
737-
"A workspace is required to resolve ParametricLineFromRepresentationLatticeArray."
738-
)
734+
raise ValueError("A workspace is required to resolve ParametricLineFromRepresentationLatticeArray.")
739735

740736
sup_uri = get_obj_uri(supporting_rep_dor)
741737
sup_obj = workspace.get_object(sup_uri)
@@ -747,9 +743,7 @@ def resolve_parametric_line_array(
747743
if not pla_results:
748744
pla_results = search_attribute_matching_name_with_path(sup_obj, "parametric_lines")
749745
if not pla_results:
750-
raise ValueError(
751-
f"Cannot find a ParametricLineArray in supporting representation {sup_uri}."
752-
)
746+
raise ValueError(f"Cannot find a ParametricLineArray in supporting representation {sup_uri}.")
753747
_, sup_pla = pla_results[0]
754748

755749
# Read the pillar index selection (IntegerLatticeArray).
@@ -760,9 +754,7 @@ def resolve_parametric_line_array(
760754

761755
from energyml.utils.data.helper import read_array as _read_array_helper # for local use
762756

763-
raw_indices = _read_array_helper(
764-
energyml_array=idx_obj, root_obj=root_obj, workspace=workspace
765-
)
757+
raw_indices = _read_array_helper(energyml_array=idx_obj, root_obj=root_obj, workspace=workspace)
766758
if not isinstance(raw_indices, np.ndarray):
767759
raw_indices = np.array(raw_indices, dtype=np.int64)
768760
raw_indices = raw_indices.flatten().astype(np.int64)
@@ -791,7 +783,7 @@ def evaluate_parametric_line_array(
791783
query_parameters: np.ndarray, # shape (NKL, n_pillars)
792784
ni: int,
793785
nj: int,
794-
) -> np.ndarray: # shape (NKL, n_pillars, 3) float64
786+
) -> np.ndarray: # shape (NKL, n_pillars, 3) float64
795787
"""
796788
Evaluate a ``ParametricLineArray`` at the given query P-values and return
797789
3-D Cartesian coordinates for every grid node.
@@ -906,7 +898,7 @@ def evaluate_parametric_line_array(
906898
for p_idx in range(n_pillars):
907899
kind = int(kinds[p_idx])
908900
q_p = query_parameters[:, p_idx] # (NKL,) P-values for this pillar
909-
cp_p = ctrl_pts[:, p_idx, :] # (K, d)
901+
cp_p = ctrl_pts[:, p_idx, :] # (K, d)
910902

911903
# ctrl_params_p: (K,) — derived from global or pillar-specific params.
912904
# For kind=0, ctrl_params is None (vertical) and we pass None.
@@ -1970,7 +1962,7 @@ def from_hsv(hsv_obj: Any) -> "RgbaColor":
19701962
a = hsv_obj.alpha if hsv_obj.alpha is not None else 1.0
19711963
r, g, b = colorsys.hsv_to_rgb(h, s, v)
19721964
return RgbaColor(r, g, b, a)
1973-
1965+
19741966
@staticmethod
19751967
def random() -> "RgbaColor":
19761968
"""Generate a random RGBA color (for testing)."""
@@ -1982,7 +1974,7 @@ def random() -> "RgbaColor":
19821974
b=random.random(),
19831975
a=1.0,
19841976
)
1985-
1977+
19861978
@staticmethod
19871979
def random_from_uuid(uuid_str: str) -> "RgbaColor":
19881980
"""Generate a random RGBA color based on a UUID string (for consistent testing)."""
@@ -1991,7 +1983,7 @@ def random_from_uuid(uuid_str: str) -> "RgbaColor":
19911983

19921984
# Create a hash of the UUID string to seed the random generator
19931985
hash_bytes = hashlib.sha256(uuid_str.encode()).digest()
1994-
seed = int.from_bytes(hash_bytes, 'big')
1986+
seed = int.from_bytes(hash_bytes, "big")
19951987
random.seed(seed)
19961988

19971989
return RgbaColor(
@@ -2051,9 +2043,7 @@ def to_vtk_lut(self, n_colors: int = 256) -> np.ndarray:
20512043

20522044
if not self.is_continuous:
20532045
# One exact row per integer entry - no interpolation needed.
2054-
return np.array(
2055-
[e.color.to_uint8() for e in sorted_entries], dtype=np.uint8
2056-
)
2046+
return np.array([e.color.to_uint8() for e in sorted_entries], dtype=np.uint8)
20572047

20582048
# Continuous: sample n_colors levels with linear interpolation in RGBA.
20592049
indices = np.array([e.index for e in sorted_entries], dtype=np.float64)
@@ -2064,9 +2054,7 @@ def to_vtk_lut(self, n_colors: int = 256) -> np.ndarray:
20642054
t = np.linspace(indices[0], indices[-1], n_colors)
20652055
result = np.zeros((n_colors, 4), dtype=np.uint8)
20662056
for ch in range(4):
2067-
result[:, ch] = np.clip(
2068-
np.interp(t, indices, float_colors[:, ch]) * 255, 0, 255
2069-
).round().astype(np.uint8)
2057+
result[:, ch] = np.clip(np.interp(t, indices, float_colors[:, ch]) * 255, 0, 255).round().astype(np.uint8)
20702058
return result
20712059

20722060
def scalar_range(self) -> Tuple[float, float]:
@@ -2271,7 +2259,9 @@ def read_graphical_rendering_info(
22712259
result = ScalarRenderingInfo(target_obj_uuid=target_uuid)
22722260
found = False
22732261

2274-
gis_infos: List[Any] = getattr(graphical_information_set, "graphical_information", []) or ([graphical_information_set] if not isinstance(graphical_information_set, list) else graphical_information_set)
2262+
gis_infos: List[Any] = getattr(graphical_information_set, "graphical_information", []) or (
2263+
[graphical_information_set] if not isinstance(graphical_information_set, list) else graphical_information_set
2264+
)
22752265

22762266
for info in gis_infos:
22772267
# Each AbstractGraphicalInformation targets ≥1 objects via target_object[].
@@ -2308,10 +2298,7 @@ def read_graphical_rendering_info(
23082298
raw_alphas = getattr(info, "alpha", []) or []
23092299
if raw_indices and raw_alphas:
23102300
try:
2311-
result.alpha_control_points = [
2312-
(float(idx), float(a))
2313-
for idx, a in zip(raw_indices, raw_alphas)
2314-
]
2301+
result.alpha_control_points = [(float(idx), float(a)) for idx, a in zip(raw_indices, raw_alphas)]
23152302
except (TypeError, ValueError) as exc:
23162303
logging.warning(f"read_graphical_rendering_info: cannot parse AlphaInformation indices: {exc}")
23172304

@@ -2323,7 +2310,7 @@ def read_graphical_rendering_info(
23232310
result.size_min_max = (mm.minimum, mm.maximum)
23242311

23252312
elif "DefaultGraphicalInformation" in type_name:
2326-
for elem_info in (getattr(info, "indexable_element_info", []) or []):
2313+
for elem_info in getattr(info, "indexable_element_info", []) or []:
23272314
if (getattr(elem_info, "is_visible", None)) is False:
23282315
result.is_visible = False
23292316
const_col = getattr(elem_info, "constant_color", None)
@@ -2340,4 +2327,4 @@ def read_graphical_rendering_info(
23402327
# AnnotationInformation is intentionally not mapped to ScalarRenderingInfo
23412328
# because it drives label text, not colour/size - handle separately if needed.
23422329

2343-
return result if found else None
2330+
return result if found else None

energyml-utils/src/energyml/utils/data/mesh.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1133,10 +1133,7 @@ def read_property_interpreted_with_cbt(
11331133
# empty while another is not). Pad all columns with None up to
11341134
# the maximum column length so that np.array() can build a
11351135
# rectangular (n_columns, max_rows) matrix before transposing.
1136-
col_values = [
1137-
list(v) if not isinstance(v, list) else v
1138-
for v in category_lookup_data.values()
1139-
]
1136+
col_values = [list(v) if not isinstance(v, list) else v for v in category_lookup_data.values()]
11401137
max_len = max((len(c) for c in col_values), default=0)
11411138
if max_len == 0:
11421139
# All columns empty — nothing to look up.

energyml-utils/src/energyml/utils/data/mesh_numpy.py

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def flat_patches(self) -> List["NumpyMesh"]:
242242
for child in self.children:
243243
result.extend(child.flat_patches())
244244
return result
245-
245+
246246
def flat_children(self) -> List["NumpyMultiMesh"]:
247247
"""Return all child containers in depth-first order."""
248248
result: List[NumpyMultiMesh] = list(self.children)
@@ -639,10 +639,7 @@ def read_numpy_polyline_representation(
639639
pt_offsets = np.concatenate([[0], np.cumsum(nc_arr)])
640640

641641
# Gather contiguous point ranges for the selected polylines.
642-
keep_ranges = [
643-
np.arange(int(pt_offsets[i]), int(pt_offsets[i + 1]), dtype=np.int64)
644-
for i in _valid
645-
]
642+
keep_ranges = [np.arange(int(pt_offsets[i]), int(pt_offsets[i + 1]), dtype=np.int64) for i in _valid]
646643
keep_pts = np.concatenate(keep_ranges) if keep_ranges else np.empty(0, dtype=np.int64)
647644

648645
# Build a full remapping: old_pt_idx → new_pt_idx (-1 = not kept).
@@ -1363,9 +1360,7 @@ def read_numpy_seismic_wellbore_frame_representation(
13631360
for patch in result.flat_patches():
13641361
patch.extra_arrays["node_time_values"] = node_time_values
13651362
except (IndexError, Exception) as exc:
1366-
logging.warning(
1367-
f"SeismicWellboreFrameRepresentation: could not read NodeTimeValues: {exc}"
1368-
)
1363+
logging.warning(f"SeismicWellboreFrameRepresentation: could not read NodeTimeValues: {exc}")
13691364
result.source_type = type(energyml_object).__name__
13701365
return result
13711366

@@ -1464,9 +1459,9 @@ def _build_split_pillar_map(
14641459
pillar_map = np.zeros((nj, ni, 4), dtype=np.int64)
14651460
for j in range(nj):
14661461
for i in range(ni):
1467-
pillar_map[j, i, 0] = j * (ni + 1) + i # TL
1468-
pillar_map[j, i, 1] = j * (ni + 1) + (i + 1) # TR
1469-
pillar_map[j, i, 2] = (j + 1) * (ni + 1) + i # BL
1462+
pillar_map[j, i, 0] = j * (ni + 1) + i # TL
1463+
pillar_map[j, i, 1] = j * (ni + 1) + (i + 1) # TR
1464+
pillar_map[j, i, 2] = (j + 1) * (ni + 1) + i # BL
14701465
pillar_map[j, i, 3] = (j + 1) * (ni + 1) + (i + 1) # BR
14711466

14721467
for split_idx in range(n_splits):
@@ -1483,13 +1478,13 @@ def _build_split_pillar_map(
14831478
continue
14841479
# Identify which corner of this column corresponds to (orig_j, orig_i)
14851480
if orig_j == col_j and orig_i == col_i:
1486-
pillar_map[col_j, col_i, 0] = new_pillar_idx # TL
1481+
pillar_map[col_j, col_i, 0] = new_pillar_idx # TL
14871482
elif orig_j == col_j and orig_i == col_i + 1:
1488-
pillar_map[col_j, col_i, 1] = new_pillar_idx # TR
1483+
pillar_map[col_j, col_i, 1] = new_pillar_idx # TR
14891484
elif orig_j == col_j + 1 and orig_i == col_i:
1490-
pillar_map[col_j, col_i, 2] = new_pillar_idx # BL
1485+
pillar_map[col_j, col_i, 2] = new_pillar_idx # BL
14911486
elif orig_j == col_j + 1 and orig_i == col_i + 1:
1492-
pillar_map[col_j, col_i, 3] = new_pillar_idx # BR
1487+
pillar_map[col_j, col_i, 3] = new_pillar_idx # BR
14931488

14941489
return pillar_map
14951490

@@ -1642,9 +1637,7 @@ def _read_point3d_parametric_array(
16421637
# --- 4. Resolve ParametricLineArray ---
16431638
pla_raw = getattr(pts_obj, "parametric_lines", None)
16441639
if pla_raw is None:
1645-
raise ValueError(
1646-
"Point3dParametricArray.parametric_lines is required but absent."
1647-
)
1640+
raise ValueError("Point3dParametricArray.parametric_lines is required but absent.")
16481641
pla = resolve_parametric_line_array(pla_raw, energyml_object, ws, n_pillars_total)
16491642

16501643
# --- 5. Evaluate pillar splines ---
@@ -1755,13 +1748,16 @@ def read_numpy_ijk_grid_representation(
17551748
if pi_list:
17561749
pi_path, pi_obj = pi_list[0]
17571750
pillar_indices_arr = _read_array_np(
1758-
pi_obj, energyml_object,
1759-
f"geometry.column_layer_split_coordinate_lines.{pi_path}", ws,
1751+
pi_obj,
1752+
energyml_object,
1753+
f"geometry.column_layer_split_coordinate_lines.{pi_path}",
1754+
ws,
17601755
)
17611756
cps_obj = getattr(split_cl, "columns_per_split_coordinate_line", None)
17621757
if cps_obj is not None:
17631758
columns_per_split = _decode_jagged_array(
1764-
cps_obj, energyml_object,
1759+
cps_obj,
1760+
energyml_object,
17651761
"geometry.column_layer_split_coordinate_lines.columns_per_split_coordinate_line",
17661762
ws,
17671763
)
@@ -1835,9 +1831,9 @@ def read_numpy_ijk_grid_representation(
18351831

18361832
kl_b = kl_bottom[ik_arr] # (ni, nj, nk)
18371833
kl_t = kl_top[ik_arr]
1838-
p_tl = ij_arr * (ni + 1) + ii_arr # pillar TL
1839-
p_tr = ij_arr * (ni + 1) + (ii_arr + 1) # pillar TR
1840-
p_bl = (ij_arr + 1) * (ni + 1) + ii_arr # pillar BL
1834+
p_tl = ij_arr * (ni + 1) + ii_arr # pillar TL
1835+
p_tr = ij_arr * (ni + 1) + (ii_arr + 1) # pillar TR
1836+
p_bl = (ij_arr + 1) * (ni + 1) + ii_arr # pillar BL
18411837
p_br = (ij_arr + 1) * (ni + 1) + (ii_arr + 1) # pillar BR
18421838

18431839
def _nidx(kl, pl):
@@ -1979,8 +1975,7 @@ def read_numpy_unstructured_grid_representation(
19791975
fpc_obj = getattr(geom, "faces_per_cell", None)
19801976
if npf_obj is None or fpc_obj is None:
19811977
logging.warning(
1982-
"UnstructuredGridRepresentation: missing nodes_per_face or faces_per_cell "
1983-
"— returning point-set mesh"
1978+
"UnstructuredGridRepresentation: missing nodes_per_face or faces_per_cell " "— returning point-set mesh"
19841979
)
19851980
label = f"{src_type}_patch_0"
19861981
multi = NumpyMultiMesh(
@@ -2180,9 +2175,7 @@ def _import_pyvista() -> Any:
21802175
try:
21812176
import pyvista as pv # type: ignore[import]
21822177
except ImportError as exc:
2183-
raise ImportError(
2184-
"pyvista is not installed. Install it with: pip install pyvista"
2185-
) from exc
2178+
raise ImportError("pyvista is not installed. Install it with: pip install pyvista") from exc
21862179
# Enable strict n_faces mode: makes n_faces return n_faces_strict (polygon
21872180
# count) instead of raising AttributeError in PyVista >= 0.46.
21882181
if hasattr(pv.PolyData, "use_strict_n_faces"):

energyml-utils/src/energyml/utils/data/representation_context.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@ def collect_graphical_info(obj: Any, workspace: EnergymlStorageInterface) -> dic
2020
obj_uuid = get_obj_uuid(obj)
2121
return collect_graphical_info_from_rels(rels, obj_uuid, workspace)
2222

23-
def collect_graphical_info_from_rels(rels: List[Relationship], obj_uuid: str, workspace: EnergymlStorageInterface) -> dict:
23+
24+
def collect_graphical_info_from_rels(
25+
rels: List[Relationship], obj_uuid: str, workspace: EnergymlStorageInterface
26+
) -> dict:
2427
graphical_info_result = {}
2528
# Collect graphical information entries whose target matches this representation
2629
for r in rels:
@@ -44,7 +47,7 @@ def collect_graphical_info_from_rels(rels: List[Relationship], obj_uuid: str, wo
4447
graphical_info_result[graphical_info_set_uri].append(graphical_info)
4548
break
4649
return graphical_info_result
47-
50+
4851

4952
class RepresentationContext(BaseModel):
5053

@@ -116,7 +119,7 @@ def _collect_crs(self):
116119
def _collect_graphical_info(self, rels: List[Relationship]):
117120
# Collect graphical information entries whose target matches this representation
118121
self.graphical_info = collect_graphical_info_from_rels(rels, self.uri.uuid, self.workspace)
119-
122+
120123
def get_default_color(self) -> ScalarRenderingInfo:
121124
"""Search for a default color (first found) for the representation, and return it as an RGBA tuple. Returns a random color (generated from uuid) if no color information is found."""
122125
for gis_uri, entries in self.graphical_info.items():
@@ -128,7 +131,9 @@ def get_default_color(self) -> ScalarRenderingInfo:
128131
except Exception as exc:
129132
logging.debug(f"Error reading graphical rendering info for entry {entry}: {exc}")
130133
# No color information found, generate a random color from uuid
131-
return ScalarRenderingInfo(target_obj_uuid=self.uri.uuid, constant_color=RgbaColor.random_from_uuid(self.uri.uuid))
134+
return ScalarRenderingInfo(
135+
target_obj_uuid=self.uri.uuid, constant_color=RgbaColor.random_from_uuid(self.uri.uuid)
136+
)
132137

133138
def get_property(self, property_uuid: str) -> Optional[Any]:
134139
"""Return the property object with the given uuid, or None."""

0 commit comments

Comments
 (0)