From 4536bfff62ae6d37cb561192b6860d5be29fefca Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Thu, 26 Nov 2026 20:30:57 +1030 Subject: [PATCH 1/3] fix(fault): restore a cutting fault before the fault it cuts A fault created with faults=[A] is faulted by the younger fault A, so A must be restored first. Features keep their faults newest first, and A must exist before the fault it cuts, so A came after it in every list: restore_through applied the cut fault first, its frame restored every point through A again inside each step, and the result near the intersection differed. In a chain of cutting faults the work multiplied at each level (a 5-fault test model: 3460 fault calls and 14.2 s for 2000 points; restored cutters first: 5 calls and 0.034 s). restore_through now orders the faults so that a cutting fault comes before every fault of the list that it cuts (cutters_first); faults with no such relation keep the order of the list, so models without faulted faults do not change. Moving points forward (reverse) puts the cutting fault last. The builder rotates data vectors in the same order. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XADRvHhG72666JkYNHtzUx --- .../builders/_geological_feature_builder.py | 5 +- LoopStructural/utils/_fault_block.py | 55 ++++++++++++- .../modelling/test_cut_fault_restore_order.py | 82 +++++++++++++++++++ 3 files changed, 137 insertions(+), 5 deletions(-) create mode 100644 tests/unit/modelling/test_cut_fault_restore_order.py diff --git a/LoopStructural/modelling/features/builders/_geological_feature_builder.py b/LoopStructural/modelling/features/builders/_geological_feature_builder.py index 24b41665..36619edb 100644 --- a/LoopStructural/modelling/features/builders/_geological_feature_builder.py +++ b/LoopStructural/modelling/features/builders/_geological_feature_builder.py @@ -9,7 +9,7 @@ from ....modelling.features import GeologicalFeature from ....utils import getLogger from ....utils._api_registry import public_api -from ....utils._fault_block import restore_through +from ....utils._fault_block import cutters_first, restore_through from ....utils.helper import ( get_data_bounding_box_map as get_data_bounding_box, ) @@ -204,7 +204,8 @@ def add_data_to_interpolator(self, constrained=False, force_constrained=False, * mask_tangent = np.all(~np.isnan(data.loc[:, tangent_vec_names()].to_numpy(float)), axis=1) mask_vector = mask_gradient | mask_normal | mask_tangent if np.sum(mask_vector) > 0: - for f in self.faults: + # the same order as restore_through below: a cutting fault first + for f in cutters_first(self.faults): if np.sum(mask_normal) > 0: data.loc[mask_normal, normal_vec_names()] = f.apply_to_vectors( data.loc[mask_normal, xyz_names() + normal_vec_names()].to_numpy(float) diff --git a/LoopStructural/utils/_fault_block.py b/LoopStructural/utils/_fault_block.py index 626f9d01..5eee79c9 100644 --- a/LoopStructural/utils/_fault_block.py +++ b/LoopStructural/utils/_fault_block.py @@ -24,7 +24,7 @@ from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Iterable, Mapping import numpy as np @@ -148,11 +148,54 @@ def is_in(fault, faults) -> bool: return any(fault is f for f in faults) +def _cutters(fault: object) -> list: + """Return the faults that displace the frame of ``fault`` (its ``faults=[...]``). + + Before the frame is built only its builders know them; after the build the + frame members do. + """ + found = [] + builder = getattr(fault, "builder", None) + sources = [getattr(b, "faults", None) or [] for b in getattr(builder, "builders", None) or []] + try: + sources += [getattr(fault[i], "faults", None) or [] for i in range(3)] + except (IndexError, KeyError, TypeError): + pass + for source in sources: + for cutter in source: + if not is_in(cutter, found): + found.append(cutter) + return found + + +def cutters_first(faults: Iterable) -> list: + """Order ``faults`` so that a fault comes after every fault of the list that cuts it. + + A fault created with ``faults=[A]`` is faulted by the younger fault ``A``, so + ``A`` must be restored first. Faults without such a relation keep the order + of the list. A cycle of relations keeps the order of the list for the faults + in it. + """ + faults = list(faults) + pending, ordered = list(faults), [] + while pending: + for fault in pending: + if not any(is_in(c, pending) and c is not fault for c in _cutters(fault)): + break + else: + fault = pending[0] # a cycle: keep the order of the list + ordered.append(fault) + pending = [f for f in pending if f is not fault] + return ordered + + def restore_through(points, faults, *, reverse=False, block=None, restored_through=()): """Restore points through a list of faults, each fault once. The faults are applied in the order of the list (a feature keeps its - faults youngest first). Each fault is told which faults the points have + faults youngest first), except that a fault faulted by another fault of the + list (``faults=[...]``) comes after it; when the points move forward + (``reverse``) the cutting fault comes last. Each fault is told which faults the points have already been restored through, so that its frame, which was built in the space restored by the younger faults that displace it, is evaluated at the points as they are and does not apply those younger faults a second time. @@ -176,7 +219,13 @@ def restore_through(points, faults, *, reverse=False, block=None, restored_throu the restored points """ done = list(restored_through) - for fault in faults: + if reverse: + # Forward movement: a cutting fault moves after the faults it cuts. Without + # such relations the order of the list does not change. + ordered = cutters_first(list(faults)[::-1])[::-1] + else: + ordered = cutters_first(faults) + for fault in ordered: if is_in(fault, done): continue # Pass only the keywords that are needed, so a fault-like object with diff --git a/tests/unit/modelling/test_cut_fault_restore_order.py b/tests/unit/modelling/test_cut_fault_restore_order.py new file mode 100644 index 00000000..06778065 --- /dev/null +++ b/tests/unit/modelling/test_cut_fault_restore_order.py @@ -0,0 +1,82 @@ +"""A fault faulted by a younger fault (``faults=[A]``) is restored after ``A``. + +Features keep their faults newest first. A fault created with ``faults=[A]`` +needs ``A`` to exist, so ``A`` comes later in that list, and was restored after +the fault it cuts: the frame then restored every point through ``A`` inside each +step (a cost that multiplies along chains of cutting faults) and gave a +different result near the intersection. +""" + +import numpy as np +import pandas as pd + +from LoopStructural import GeologicalModel +from LoopStructural.modelling.features.fault._fault_segment import FaultSegment +from LoopStructural.utils._fault_block import cutters_first, restore_through +from tests.fixtures.fault_models import COLUMNS, OLD, YOUNG, add_fault, interior_points + + +class _Fault: + """A stand-in with the frame builders that hold the cutting faults.""" + + def __init__(self, name, cut_by=()): + self.name = name + self.builder = type("B", (), {"builders": [type("S", (), {"faults": list(cut_by)})()]})() + + def __getitem__(self, key): + raise IndexError(key) + + +def test_cutting_fault_comes_first_and_other_faults_keep_their_order(): + a = _Fault("a") + i = _Fault("i") + b = _Fault("b", cut_by=[a]) + c = _Fault("c", cut_by=[b]) + assert [f.name for f in cutters_first([c, i, b, a])] == ["i", "a", "b", "c"] + assert [f.name for f in cutters_first([i, a, b])] == ["i", "a", "b"] + unrelated = [_Fault("x"), _Fault("y"), _Fault("z")] + assert cutters_first(unrelated) == unrelated + + +def _model_with_cut_pair(): + model = GeologicalModel(np.zeros(3), np.ones(3)) + young = add_fault(model, "young", **YOUNG, steps=3) + old = add_fault(model, "old", **OLD, steps=3, faults=[young]) + rng = np.random.default_rng(1) + pts = rng.uniform(0, 1, (200, 3)) + data = pd.DataFrame({"X": pts[:, 0], "Y": pts[:, 1], "Z": pts[:, 2], "val": pts[:, 2], + "nx": np.nan, "ny": np.nan, "nz": np.nan, "coord": np.nan, + "feature_name": "strat"})[COLUMNS] + strat = model.create_and_add_foliation("strat", data=data, nelements=2000, buffer=0.3) + model.update() + return strat, young, old + + +def test_feature_restores_the_cutting_fault_first(monkeypatch): + strat, young, old = _model_with_cut_pair() + # The feature keeps the faults newest first: the cut fault comes before its cutter. + assert [f.name for f in strat.faults] == ["old", "young"] + points = interior_points(n=300) + expected = old.apply_to_points(young.apply_to_points(points.copy()), restored_through=(young,)) + + calls = [] + original = FaultSegment.apply_to_points + + def counted(self, pts, *args, **kwargs): + calls.append(self.name) + return original(self, pts, *args, **kwargs) + + monkeypatch.setattr(FaultSegment, "apply_to_points", counted) + restored = restore_through(points.copy(), strat.faults) + np.testing.assert_allclose(restored, expected, rtol=0.0, atol=1e-12) + # One application of each fault: the frame of old does not restore through young again. + assert calls == ["young", "old"] + + +def test_forward_movement_keeps_the_list_order_without_relations(): + a, b = _Fault("a"), _Fault("b") + seen = [] + for f in (a, b): + f.apply_to_points = lambda pts, f=f, **kw: seen.append(f.name) or pts + restore_through(np.zeros((1, 3)), [a, b], reverse=True) + assert seen == ["a", "b"] From eb8396db1f25c35d629566e0132229a8fa6b1d33 Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Thu, 26 Nov 2026 20:36:25 +1030 Subject: [PATCH 2/3] fix(fault): read the frame members from StructuralFrame.features _cutters read the members by index, which calls __getitem__ of any fault-like object in a list (a test double asserts its key). The members are in StructuralFrame.features. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XADRvHhG72666JkYNHtzUx --- LoopStructural/utils/_fault_block.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/LoopStructural/utils/_fault_block.py b/LoopStructural/utils/_fault_block.py index 5eee79c9..2bccfda0 100644 --- a/LoopStructural/utils/_fault_block.py +++ b/LoopStructural/utils/_fault_block.py @@ -157,10 +157,8 @@ def _cutters(fault: object) -> list: found = [] builder = getattr(fault, "builder", None) sources = [getattr(b, "faults", None) or [] for b in getattr(builder, "builders", None) or []] - try: - sources += [getattr(fault[i], "faults", None) or [] for i in range(3)] - except (IndexError, KeyError, TypeError): - pass + # The frame members (a StructuralFrame keeps them in ``features``). + sources += [getattr(m, "faults", None) or [] for m in getattr(fault, "features", None) or []] for source in sources: for cutter in source: if not is_in(cutter, found): From 79f66bf1f222fdcfcad46cd6c66b015ab38e1d6e Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Thu, 26 Nov 2026 22:08:46 +1030 Subject: [PATCH 3/3] fix(fault): restore the whole chain of cutting faults in one pass A fault applied through a list that names only its direct cutters (a fault frame builder, or a feature with faults=[C]) restored through C alone. The frame of C was built in the space restored through its own cutter B, so C restored every point through B again at each step, and B through A: the nesting gained one level for each link of a chain, and the cost multiplied (build of a 5-fault chain: 272.7 s and 44850 fault calls). restore_through now adds, transitively, the faults that cut a fault of the list (with_cutters) and restores them in one pass, youngest first, each told what is already restored. A fault frame cut by B is then also moved by the younger faults that cut B, where their displacement reaches it. The same 5-fault chain builds in 7.0 s (1923 fault calls); a 6-fault chain in 15 s. The builder rotates data vectors through the same faults. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XADRvHhG72666JkYNHtzUx --- .../builders/_geological_feature_builder.py | 6 ++-- LoopStructural/utils/_fault_block.py | 31 +++++++++++++++--- .../modelling/test_cut_fault_restore_order.py | 32 +++++++++++++++++++ 3 files changed, 62 insertions(+), 7 deletions(-) diff --git a/LoopStructural/modelling/features/builders/_geological_feature_builder.py b/LoopStructural/modelling/features/builders/_geological_feature_builder.py index 36619edb..39056676 100644 --- a/LoopStructural/modelling/features/builders/_geological_feature_builder.py +++ b/LoopStructural/modelling/features/builders/_geological_feature_builder.py @@ -9,7 +9,7 @@ from ....modelling.features import GeologicalFeature from ....utils import getLogger from ....utils._api_registry import public_api -from ....utils._fault_block import cutters_first, restore_through +from ....utils._fault_block import cutters_first, restore_through, with_cutters from ....utils.helper import ( get_data_bounding_box_map as get_data_bounding_box, ) @@ -204,8 +204,8 @@ def add_data_to_interpolator(self, constrained=False, force_constrained=False, * mask_tangent = np.all(~np.isnan(data.loc[:, tangent_vec_names()].to_numpy(float)), axis=1) mask_vector = mask_gradient | mask_normal | mask_tangent if np.sum(mask_vector) > 0: - # the same order as restore_through below: a cutting fault first - for f in cutters_first(self.faults): + # the same faults and order as restore_through below + for f in cutters_first(with_cutters(self.faults)): if np.sum(mask_normal) > 0: data.loc[mask_normal, normal_vec_names()] = f.apply_to_vectors( data.loc[mask_normal, xyz_names() + normal_vec_names()].to_numpy(float) diff --git a/LoopStructural/utils/_fault_block.py b/LoopStructural/utils/_fault_block.py index 2bccfda0..b3b4e711 100644 --- a/LoopStructural/utils/_fault_block.py +++ b/LoopStructural/utils/_fault_block.py @@ -166,6 +166,26 @@ def _cutters(fault: object) -> list: return found +def with_cutters(faults: Iterable) -> list: + """Return ``faults`` and, transitively, every fault that cuts one of them. + + A fault frame cut by ``B`` was built in the space restored through ``B``, and + ``B`` was built in the space restored through its own cutters. Restoring the + whole chain in one pass (each fault told what was already restored) keeps the + cost linear in the depth of the chain; restoring through ``B`` alone makes the + frame of ``B`` restore every point through its cutters again at each step. + Each fault appears once, in the order found. + """ + result = list(faults) + index = 0 + while index < len(result): + for cutter in _cutters(result[index]): + if not is_in(cutter, result): + result.append(cutter) + index += 1 + return result + + def cutters_first(faults: Iterable) -> list: """Order ``faults`` so that a fault comes after every fault of the list that cuts it. @@ -191,9 +211,10 @@ def restore_through(points, faults, *, reverse=False, block=None, restored_throu """Restore points through a list of faults, each fault once. The faults are applied in the order of the list (a feature keeps its - faults youngest first), except that a fault faulted by another fault of the - list (``faults=[...]``) comes after it; when the points move forward - (``reverse``) the cutting fault comes last. Each fault is told which faults the points have + faults youngest first), except that a fault faulted by another fault + (``faults=[...]``) comes after it; when the points move forward + (``reverse``) the cutting fault comes last. The faults that cut a fault of + the list, and the faults that cut those, are restored too. Each fault is told which faults the points have already been restored through, so that its frame, which was built in the space restored by the younger faults that displace it, is evaluated at the points as they are and does not apply those younger faults a second time. @@ -217,10 +238,12 @@ def restore_through(points, faults, *, reverse=False, block=None, restored_throu the restored points """ done = list(restored_through) + # The chain of cutting faults is restored too (see with_cutters). + faults = with_cutters(faults) if reverse: # Forward movement: a cutting fault moves after the faults it cuts. Without # such relations the order of the list does not change. - ordered = cutters_first(list(faults)[::-1])[::-1] + ordered = cutters_first(faults[::-1])[::-1] else: ordered = cutters_first(faults) for fault in ordered: diff --git a/tests/unit/modelling/test_cut_fault_restore_order.py b/tests/unit/modelling/test_cut_fault_restore_order.py index 06778065..4ad716e1 100644 --- a/tests/unit/modelling/test_cut_fault_restore_order.py +++ b/tests/unit/modelling/test_cut_fault_restore_order.py @@ -80,3 +80,35 @@ def test_forward_movement_keeps_the_list_order_without_relations(): f.apply_to_points = lambda pts, f=f, **kw: seen.append(f.name) or pts restore_through(np.zeros((1, 3)), [a, b], reverse=True) assert seen == ["a", "b"] + + +def test_a_chain_of_cuts_is_restored_in_one_pass(monkeypatch): + """oldest is cut by old, old by young: no fault restores through its cutters alone. + + Restoring the frame of oldest through old alone made the frame of old restore + every point through young again at each step (one more level of nesting for + each link of the chain, so the cost multiplied). The chain is now restored in + one pass, youngest first, so nesting never goes deeper than 2. + """ + model = GeologicalModel(np.zeros(3), np.ones(3)) + young = add_fault(model, "young", **YOUNG, steps=3) + old = add_fault(model, "old", **OLD, steps=3, faults=[young]) + oldest = add_fault(model, "oldest", center=(0.5, 0.5, 0.7), dip=70, dip_azimuth=0, + displacement=0.08, steps=3, faults=[old]) + model.update() + + depth, deepest = [0], [0] + original = FaultSegment.apply_to_points + + def tracked(self, pts, *args, **kwargs): + depth[0] += 1 + deepest[0] = max(deepest[0], depth[0]) + try: + return original(self, pts, *args, **kwargs) + finally: + depth[0] -= 1 + + monkeypatch.setattr(FaultSegment, "apply_to_points", tracked) + restored = oldest.apply_to_points(interior_points(n=200)) + assert not np.isnan(restored).any() + assert deepest[0] == 2