diff --git a/LoopStructural/modelling/features/builders/_geological_feature_builder.py b/LoopStructural/modelling/features/builders/_geological_feature_builder.py index 24b41665..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 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,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 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 626f9d01..b3b4e711 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,73 @@ 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 []] + # 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): + found.append(cutter) + 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. + + 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 + (``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. @@ -176,7 +238,15 @@ def restore_through(points, faults, *, reverse=False, block=None, restored_throu the restored points """ done = list(restored_through) - for fault in faults: + # 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(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..4ad716e1 --- /dev/null +++ b/tests/unit/modelling/test_cut_fault_restore_order.py @@ -0,0 +1,114 @@ +"""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"] + + +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