Skip to content

Commit 03a6e58

Browse files
authored
fix: coordinate and fault-frame correctness, stage S1 (spec 005) (#392)
* chore(lint): fix baseline Python checks * docs(spec): add plan and S1 tasks for 005-coordinate-frame-correctness * test(geometry): add S1 analytic fixtures and transform checks * feat(geometry): add rigid rotation validation and S1 regressions * fix(geometry): correct review finding of wave 2 * feat(geometry): validate rigid transforms and repair fault frame setup (wave 3) T005: validate the local transform and add BoundingBox.local_enclosure. T006: repair the support resize node count and validate rotation_xy. Regenerate the structured support golden file (27 resize values). T008: add the public world/local conversion methods. T012: keep the requested buffer, the 3D inferred centre, the in-plane slip and one extent row at the centre. Correct two test setups (T003 dimensions, T011 slip row scale). * feat(modelling): sample reference features at world points (wave 4) T009: sample add_inequality_feature at world nodes. T010: sample orthogonal and equality references at world points, install target-local rows, count excluded rows, use the local enclosure for the support, and expand the support for restored points in world space. Correct the T007 affine residual test: compute the exact field without cancellation at large world coordinates. The tolerance is not changed. * fix(modelling): keep the fault centre and buffer in the fault factory (wave 5) T013: do not project an explicit fault centre, because it is a world point (FR-010). Do not replace the requested fault buffer with the default 0.2 buffer. Correct the T011 test setup: give the SC-003 CG settings through solver_kwargs. The builder ignored the top-level values. * docs(compat): record S1 golden review and migration notice (wave 6) T015: record the golden review. test__fault_builder.py encodes no S1 defect. Record the 27 changed values of the structured support golden file. T016: add the S1 migration notice to COMPAT.md. * docs(spec): record S1 pre-fix evidence, results, rollback and run time (wave 7) T017: fill verification.md with the pre-fix failures at ebc7c69, the post-fix results, the backend matrix, the rollback check and the S1 test time. * fix(modelling): correct spec review findings Copy the fault normal and slip so the array of the caller does not change (T012). Use the world fault centre in FaultSegment.fault_ellipsoid with no second conversion (T013). Add regression tests for both (T011 file). Keep only the 27 FR-014 changes in the structured support golden file (T006). Correct the FR ranges in the verification.md titles (T017). * docs(spec): mark 005 stage S1 as implemented Record the final checks and the open minor review findings in run-state.json. * docs(spec): record decisions after stage S1 of 005 Put the anisotropy reset (#394) and the ignored solver settings (#393) out of scope. Close OP2: the R2 and R5 matrix stays in the default pytest run. * test(interp): loosen golden gradient tolerance for macOS arm64 The gradient amplifies solver noise by about 1/h, so it needs a looser limit than the value. Report max |dgrad| in the failure message.
1 parent a0e8209 commit 03a6e58

24 files changed

Lines changed: 2928 additions & 129 deletions

‎COMPAT.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ unchanged, but the new path is preferred going forward.
4747
| `FaultBuilder.__init__`/`FoldedFeatureBuilder.__init__`/`StructuralFrameBuilder.__init__` `bounding_box` param annotated as `LoopStructural.geometry._bounding_box.BoundingBox` | annotated as `loop_common.geometry._bounding_box.BoundingBox` — `LoopStructural.geometry.BoundingBox` now re-exports `loop_common.geometry.BoundingBox` (ROADMAP 2c-3 closed); accepted argument type is unchanged, only the class's canonical module path | 2026-07-30 |
4848
| `BoundingBox(global_origin=..., global_maximum=...)` (local/global split, `origin`/`maximum` pre-shifted to be near-zero) | `BoundingBox(origin=..., maximum=...)` with `origin`/`maximum` always in world coordinates, plus `set_local_transform(local_origin=...)` for the interpolation frame and `project()`/`reproject()` as a proper affine transform. `global_origin`/`global_maximum` constructor args and properties are removed; `GeologicalModel`'s `scale()`/`rescale()` public methods keep their existing signature and behavior. | 2026-07-30 |
4949
| `GeologicalModel.from_file(file)` (always loads via `dill`/`pickle`, no opt-out) | `GeologicalModel.from_file(file, allow_pickle=True)` — same default behavior (still unpickles trusted files with no code change required), but `allow_pickle=False` now refuses to unpickle and raises `LoopValueError` instead, since deserialising an untrusted pickle/dill file can execute arbitrary code. A runtime warning is also now logged whenever pickle-based loading is used. For untrusted/JSON-based input, use `GeologicalModel.from_recipe_dict`/`to_recipe_dict` instead. | 2026-07-30 |
50+
| `create_and_add_fault(fault_center=...)` projected the centre into local coordinates; `fault_buffer`/`force_mesh_geometry` were replaced by a default 0.2 buffer; an inferred centre had z = 0; any 3x3 matrix was accepted as a rotation | `fault_center` is a world point; the requested buffer and forced geometry are kept; an inferred centre keeps its elevation; `set_local_transform` and `rotation_xy` raise `RigidRotationError` for a non-rigid matrix. Extra observations added to work around these defects are no longer necessary (spec 005) | 2026-11-04 |
5051

5152
The following stable methods remain part of the documented public API surface after the package extraction work and are covered by the snapshot-based contract test: add_onlap_unconformity, add_unconformity, create_and_add_domain_fault, create_and_add_fault, create_and_add_fold_frame, create_and_add_folded_fold_frame, create_and_add_folded_foliation, create_and_add_foliation, evaluate_model, evaluate_model_gradient, from_file, get_fault_surfaces, get_feature_by_name, get_stratigraphic_surfaces, rescale, save, scale.
5253

‎LoopStructural/modelling/core/_model_feature_factory.py‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -748,8 +748,6 @@ def build_fault(
748748
model._add_faults(fault_frame_builder, features=faults)
749749
# add data
750750

751-
if fault_center is not None and ~np.isnan(fault_center).any():
752-
fault_center = model.scale(fault_center, inplace=False)
753751
# Keep the supplied fault-axis values unchanged; the previous self-assignment
754752
# was only present to satisfy a linter and did not affect behavior.
755753
fault_frame_builder.create_data_from_geometry(
@@ -768,8 +766,6 @@ def build_fault(
768766
fault_dip_anisotropy=fault_dip_anisotropy,
769767
fault_pitch=fault_pitch,
770768
)
771-
if "force_mesh_geometry" not in kwargs:
772-
fault_frame_builder.set_mesh_geometry(kwargs.get("fault_buffer", 0.2), 0)
773769
if "splay" in kwargs and "splayregion" in kwargs:
774770
fault_frame_builder.add_splay(kwargs["splay"], kwargs["splayregion"])
775771

‎LoopStructural/modelling/features/builders/_fault_builder.py‎

Lines changed: 122 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ def __init__(
7373
self._fault_major_axis = None
7474
self._fault_intermediate_axis = None
7575
self._fault_centre = None
76+
self._fault_buffer: float = 0.2
77+
self._force_mesh_geometry: bool = False
7678
self._suspend_rebuild = False
7779

7880
def update_geometry(self, points):
@@ -102,7 +104,7 @@ def update_geometry(self, points):
102104

103105
def _on_geometry_change(
104106
self,
105-
force_mesh_geometry: bool = False,
107+
force_mesh_geometry: bool | None = None,
106108
fault_buffer: float | None = None,
107109
fault_trace_anisotropy: float = 1.0,
108110
fault_dip_anisotropy: float = 1.0,
@@ -116,6 +118,10 @@ def _on_geometry_change(
116118
"""
117119
if getattr(self, "raw_data", None) is None or self.raw_data.empty:
118120
return
121+
if force_mesh_geometry is None:
122+
force_mesh_geometry = self._force_mesh_geometry
123+
if fault_buffer is None:
124+
fault_buffer = self._fault_buffer
119125

120126
# Use a copy of the DataFrame so callers don't observe mutations
121127
self.create_data_from_geometry(
@@ -129,7 +135,7 @@ def _on_geometry_change(
129135
w=1.0,
130136
points=False,
131137
force_mesh_geometry=force_mesh_geometry,
132-
fault_buffer=fault_buffer if fault_buffer is not None else 0.2,
138+
fault_buffer=fault_buffer,
133139
fault_trace_anisotropy=fault_trace_anisotropy,
134140
fault_dip=fault_dip if fault_dip is not None else getattr(self, "fault_dip", 90),
135141
fault_dip_anisotropy=fault_dip_anisotropy,
@@ -148,7 +154,7 @@ def fault_normal_vector(self, v):
148154
if len(v.shape) != 1 or v.shape[0] != 3:
149155
raise ValueError("fault_normal_vector must be a 3 element array")
150156
if v.ndim != 1:
151-
v = v[0,:]
157+
v = v[0, :]
152158
if v.shape[0] != 3:
153159
raise ValueError("fault_normal_vector must be a 3 element array")
154160
arr = np.array(v, dtype=float)
@@ -289,6 +295,8 @@ def create_data_from_geometry(
289295
Pitch angle of the fault.
290296
"""
291297
# Suspend automatic rebuilds while we populate internal attributes to avoid recursion
298+
self._fault_buffer = fault_buffer
299+
self._force_mesh_geometry = force_mesh_geometry
292300
prev_suspend = getattr(self, "_suspend_rebuild", False)
293301
self._suspend_rebuild = True
294302
try:
@@ -299,37 +307,52 @@ def create_data_from_geometry(
299307
].to_numpy()
300308
self.fault_dip = fault_dip
301309
if fault_normal_vector is None:
302-
gx_mask = np.logical_and(fault_frame_data["coord"] == 0, fault_frame_data["gx"].notna())
303-
nx_mask = np.logical_and(fault_frame_data["coord"] == 0, fault_frame_data["nx"].notna())
304-
value_mask = np.logical_and(fault_frame_data["coord"] == 0, fault_frame_data["val"] == 0)
310+
gx_mask = np.logical_and(
311+
fault_frame_data["coord"] == 0, fault_frame_data["gx"].notna()
312+
)
313+
nx_mask = np.logical_and(
314+
fault_frame_data["coord"] == 0, fault_frame_data["nx"].notna()
315+
)
316+
value_mask = np.logical_and(
317+
fault_frame_data["coord"] == 0, fault_frame_data["val"] == 0
318+
)
305319
if not fault_frame_data.loc[gx_mask].empty:
306-
fault_normal_vector = fault_frame_data.loc[
307-
gx_mask,
308-
["gx", "gy", "gz"],
309-
].to_numpy().mean(axis=0)
320+
fault_normal_vector = (
321+
fault_frame_data.loc[
322+
gx_mask,
323+
["gx", "gy", "gz"],
324+
]
325+
.to_numpy()
326+
.mean(axis=0)
327+
)
310328
elif not fault_frame_data.loc[nx_mask].empty:
311-
fault_normal_vector = fault_frame_data.loc[
312-
nx_mask,
313-
["nx", "ny", "nz"],
314-
].to_numpy().mean(axis=0)
329+
fault_normal_vector = (
330+
fault_frame_data.loc[
331+
nx_mask,
332+
["nx", "ny", "nz"],
333+
]
334+
.to_numpy()
335+
.mean(axis=0)
336+
)
315337

316338
else:
317339
fault_surface_pts = fault_frame_data.loc[
318340
value_mask,
319341
["X", "Y", "Z"],
320342
].to_numpy()
321-
fault_surface_pts = fault_surface_pts[
322-
~np.isnan(fault_surface_pts).any(axis=1)
323-
]
343+
fault_surface_pts = fault_surface_pts[~np.isnan(fault_surface_pts).any(axis=1)]
324344

325345
if fault_surface_pts.shape[0] >= 3:
326346
pts_3d = fault_surface_pts - fault_surface_pts.mean(axis=0)
327347
cov_matrix = pts_3d.T @ pts_3d
328348
eigenvalues, eigenvectors = np.linalg.eigh(cov_matrix)
329349
# If points span a surface, use the smallest eigenvector as plane normal
330-
if eigenvalues[-1] > 0 and (eigenvalues[1] / eigenvalues[-1]) > plane_line_threshold:
350+
if (
351+
eigenvalues[-1] > 0
352+
and (eigenvalues[1] / eigenvalues[-1]) > plane_line_threshold
353+
):
331354
fault_normal_vector = eigenvectors[:, 0]
332-
355+
333356
if fault_normal_vector is None:
334357
# Fall back to line-on-map strike logic
335358
pts = fault_trace - fault_trace.mean(axis=0)
@@ -340,9 +363,7 @@ def create_data_from_geometry(
340363
strike_vector /= np.linalg.norm(strike_vector)
341364

342365
fault_normal_vector = np.cross(strike_vector, [0, 0, 1])
343-
rotation_matrix = rotation(
344-
strike_vector[None, :], np.array([90 - fault_dip])
345-
)
366+
rotation_matrix = rotation(strike_vector[None, :], np.array([90 - fault_dip]))
346367
fault_normal_vector = np.einsum(
347368
"ijk,ik->ij", rotation_matrix, fault_normal_vector[None, :]
348369
)[0]
@@ -352,35 +373,66 @@ def create_data_from_geometry(
352373

353374
if fault_pitch is not None:
354375
rotation_matrix = rotation(fault_normal_vector[None, :], np.array([fault_pitch]))
355-
fault_slip_vector = np.einsum("ijk,ik->ij", rotation_matrix, fault_normal_vector[None, :])[0]
376+
fault_slip_vector = np.einsum(
377+
"ijk,ik->ij", rotation_matrix, fault_normal_vector[None, :]
378+
)[0]
356379

357380
if fault_slip_vector is None:
358-
if fault_frame_data.loc[
359-
np.logical_and(fault_frame_data["coord"] == 1, fault_frame_data["nx"].notna())].shape[0]>0:
360-
fault_slip_vector = fault_frame_data.loc[
361-
np.logical_and(fault_frame_data["coord"] == 1, fault_frame_data["nx"].notna()),
362-
["nx", "ny", "nz"],
363-
].to_numpy().mean(axis=0)
381+
if (
382+
fault_frame_data.loc[
383+
np.logical_and(
384+
fault_frame_data["coord"] == 1, fault_frame_data["nx"].notna()
385+
)
386+
].shape[0]
387+
> 0
388+
):
389+
fault_slip_vector = (
390+
fault_frame_data.loc[
391+
np.logical_and(
392+
fault_frame_data["coord"] == 1, fault_frame_data["nx"].notna()
393+
),
394+
["nx", "ny", "nz"],
395+
]
396+
.to_numpy()
397+
.mean(axis=0)
398+
)
364399

365400
else:
366-
fault_slip_vector = np.cross(fault_normal_vector, [1., 0., 0.])
401+
fault_slip_vector = np.cross(fault_normal_vector, [1.0, 0.0, 0.0])
367402
if np.linalg.norm(fault_slip_vector) == 0:
368-
fault_slip_vector = np.cross(fault_normal_vector, [0., 1., 0.])
403+
fault_slip_vector = np.cross(fault_normal_vector, [0.0, 1.0, 0.0])
369404
fault_slip_vector /= np.linalg.norm(fault_slip_vector)
370405
if fault_center is None:
371-
fault_trace = fault_frame_data.loc[
372-
np.logical_and(fault_frame_data["coord"] == 0, fault_frame_data["val"] == 0),
373-
["X", "Y"],
374-
].to_numpy()
375-
fault_center = fault_trace.mean(axis=0)
376-
fault_center = np.array([fault_center[0], fault_center[1], 0.0])
406+
centre_rows = fault_frame_data.loc[
407+
np.logical_and(fault_frame_data["coord"] == 0, fault_frame_data["val"] == 0),
408+
["X", "Y", "Z"],
409+
].to_numpy(dtype=float)
410+
fault_center = np.nanmean(centre_rows, axis=0)
411+
for axis, axis_name in enumerate(("X", "Y", "Z")):
412+
if not np.isfinite(fault_center[axis]):
413+
logger.warning(
414+
"Inferred fault centre has no finite %s coordinate; using 0.0",
415+
axis_name,
416+
)
417+
fault_center[axis] = 0.0
377418
if not isinstance(fault_center, np.ndarray):
378419
fault_center = np.array(fault_center)
379420
if fault_center.shape[0] != 3:
380421
raise ValueError("fault_center must be a 3 element array")
381422
# Assign to properties (these won't trigger _on_geometry_change because suspend flag is True)
382-
self.fault_normal_vector = fault_normal_vector / np.linalg.norm(fault_normal_vector)
383-
self.fault_slip_vector = fault_slip_vector / np.linalg.norm(fault_slip_vector)
423+
# Copy the input so the array of the caller does not change.
424+
normal = np.array(fault_normal_vector, dtype=float)
425+
normal /= np.linalg.norm(normal)
426+
slip = np.array(fault_slip_vector, dtype=float)
427+
slip_perp = slip - np.dot(slip, normal) * normal
428+
slip_norm = np.linalg.norm(slip_perp)
429+
if slip_norm < 1e-12:
430+
raise ValueError(
431+
"fault slip vector is parallel to the fault normal; supply a slip direction in the fault plane"
432+
)
433+
fault_slip_vector = slip_perp / slip_norm
434+
self.fault_normal_vector = normal
435+
self.fault_slip_vector = fault_slip_vector
384436

385437
self.fault_centre = fault_center
386438
if major_axis is None:
@@ -395,6 +447,7 @@ def create_data_from_geometry(
395447
self.add_data_from_data_frame(fault_frame_data)
396448
self.origin = self.model.bounding_box.origin
397449
self.maximum = self.model.bounding_box.maximum
450+
self.set_mesh_geometry(fault_buffer, None)
398451
return
399452
major_axis = np.max(distance)
400453
logger.info(f"Fault major axis using map length: {major_axis}")
@@ -404,15 +457,18 @@ def create_data_from_geometry(
404457
minor_axis = major_axis / 2.0
405458
if intermediate_axis is None:
406459
intermediate_axis = major_axis
407-
logger.info(f"Fault intermediate axis not set, using major axis: {intermediate_axis}")
460+
logger.info(
461+
f"Fault intermediate axis not set, using major axis: {intermediate_axis}"
462+
)
408463
self.fault_minor_axis = minor_axis
409464
self.fault_major_axis = major_axis
410465
self.fault_intermediate_axis = intermediate_axis
411466
self.fault_normal_vector /= np.linalg.norm(self.fault_normal_vector)
412-
fault_slip_vector /= np.linalg.norm(fault_slip_vector)
467+
fault_slip_vector = self.fault_slip_vector.copy()
413468
# check if slip vector is inside fault plane, if not project onto fault plane
414469
# if not np.isclose(normal_vector @ slip_vector, 0):
415470
strike_vector = np.cross(self.fault_normal_vector, fault_slip_vector)
471+
strike_vector /= np.linalg.norm(strike_vector)
416472
self.fault_strike_vector = strike_vector
417473

418474
fault_edges = np.zeros((2, 3))
@@ -538,6 +594,21 @@ def create_data_from_geometry(
538594
]
539595

540596
if major_axis is not None:
597+
fault_frame_data.loc[
598+
len(fault_frame_data),
599+
["X", "Y", "Z", "feature_name", "nx", "ny", "nz", "val", "coord", "w"],
600+
] = [
601+
fault_center[0],
602+
fault_center[1],
603+
fault_center[2],
604+
self.name,
605+
strike_vector[0] / major_axis,
606+
strike_vector[1] / major_axis,
607+
strike_vector[2] / major_axis,
608+
np.nan,
609+
2,
610+
w,
611+
]
541612
fault_tips[0, :] = fault_center[:3] + strike_vector * 0.5 * major_axis
542613
fault_tips[1, :] = fault_center[:3] - strike_vector * 0.5 * major_axis
543614
self.update_geometry(fault_tips)
@@ -596,8 +667,10 @@ def create_data_from_geometry(
596667
]
597668

598669
self.update_geometry(fault_depth)
599-
# TODO need to add data here
600-
fault_slip_vector /= intermediate_axis
670+
# The depth points above use the unit slip vector.
671+
# The gradient row uses the slip vector divided by intermediate_axis.
672+
# This is a local copy, so self.fault_slip_vector stays a unit vector.
673+
fault_slip_vector = fault_slip_vector / intermediate_axis
601674
fault_frame_data.loc[
602675
len(fault_frame_data),
603676
[
@@ -704,7 +777,9 @@ def add_fault_trace_anisotropy(self, w: float = 1.0):
704777
"""
705778
if w > 0:
706779
if self.fault_normal_vector is None:
707-
raise ValueError("fault_normal_vector must be initialized before adding anisotropy.")
780+
raise ValueError(
781+
"fault_normal_vector must be initialized before adding anisotropy."
782+
)
708783

709784
plane = np.array([0, 0, 1])
710785
strike_vector = (
@@ -731,7 +806,9 @@ def add_fault_dip_anisotropy(self, w: float = 1.0):
731806
"""
732807
if w > 0:
733808
if self.fault_normal_vector is None:
734-
raise ValueError("fault_normal_vector must be initialized before adding anisotropy.")
809+
raise ValueError(
810+
"fault_normal_vector must be initialized before adding anisotropy."
811+
)
735812

736813
plane = np.array([0, 0, 1])
737814
strike_vector = (

0 commit comments

Comments
 (0)