diff --git a/API.md b/API.md index c9230ed5c..53d235374 100644 --- a/API.md +++ b/API.md @@ -195,6 +195,48 @@ exposed: - `getLogger` itself is promoted to enforced-**stable** (see below) as part of this work — its signature/behavior are unchanged, only tracked by the registry now. +- Fault blocks: evaluation of a feature as it is in one fault block. A block + maps fault names to `+1` (hanging wall), `-1` (footwall) or `0` (absent); + each fault it names restores every point as if the point were on that side, + so the result has no jump across those faults. The block is an argument + only: no state changes, so calls with different blocks can run in parallel. + On the other side of its fault a block takes the smooth continuation of the + displacement profile of its side (C2 at the fault; exact up to 0.25 in gx, + constant beyond 0.5), not the mirror image; the module setting + `LoopStructural.utils._fault_block.BLOCK_EXTENSION = "mirror"` gives the + mirror image for comparisons. See + `tests/unit/modelling/test_fault_block_extension.py`. + - `GeologicalModel.evaluate_feature_block_value(feature_name, xyz, block, *, ignore_regions=True)` / + `GeologicalModel.evaluate_feature_block_gradient(...)`. + - `FaultSegment.evaluate_frame_value(points, coordinate=0, *, block=None)` / + `FaultSegment.evaluate_frame_gradient(...)` — one fault frame coordinate + without the fault regions, optionally in a block of the younger faults. + - `FaultSegment.evaluate_tip_value(points, *, block=None)` / + `FaultSegment.evaluate_tip_gradient(...)` — `min(1 - |g|)` over the + frame coordinates whose displacement profile is zero at `|g| = 1`. + - The keyword `block` on `GeologicalFeature.evaluate_value` / + `evaluate_gradient` and on `FaultSegment.apply_to_points` / + `evaluate_value` / `evaluate_displacement` (both unregistered; the + keyword is new and optional, so existing calls are unchanged). + - See `tests/unit/modelling/test_fault_block_fields.py`. +- `GeologicalModel.get_feature_relations()` — the relations of a model as a + plain dict (event order, displaced-by, abutment with side, truncation by + unconformities); reads the builders, same before and after `update()`. +- `FaultDisplacement.tip_ends` (property) and the `tip_ends` attribute of + the profiles — which frame coordinates carry a tip (unregistered). +- The keyword `restored_through` on `FaultSegment.apply_to_points` / + `apply_to_vectors` and `GeologicalFeature.evaluate_value` / + `evaluate_gradient` — faults the points have already been restored + through (a displaced fault is applied once; unregistered). +- `GeologicalModel.add_unconformity` truncates the faults that are older + than the unconformity (signature unchanged; the rule for "older" is in its + doc string and the changed results are in `COMPAT.md`). The keyword + `restored_through` is also on `UnconformityFeature.evaluate` / `__call__`. +- `GeologicalModel.position_tolerance` (attribute, default None), the keyword + `position_tolerance` of the `create_and_add_*` methods and of + `DiscreteInterpolator.solve_system` — a cg stop on an estimate of the + position error of the isosurfaces, in model length units (an estimate, not + a guarantee; unregistered). ## Known internal-path consumers diff --git a/COMPAT.md b/COMPAT.md index da8588d70..448444a76 100644 --- a/COMPAT.md +++ b/COMPAT.md @@ -70,6 +70,10 @@ unchanged, but the new path is preferred going forward. | Known issue, not fixed in S6: the gradient of a model outside the support | Outside the support the FDI gradient is 0 and the PLI gradient is NaN. S6 test T095 pins this behavior (spec 005, stage S6) | 2026-11-06 | | Known issue, not fixed in S6: `P2Interpolator.add_gradient_constraints` for a P2 foliation with gradient rows | It raises `ValueError`. This is a library defect. S6 does not change it (spec 005, stage S6) | 2026-11-06 | | Known issue, not fixed in S6: `set_nelements` | It passes a cell count to the node setter. For example, `nelements=1000` gives 729 cells. This is old behavior, not a regression. S6 does not change it (spec 005, stage S6, S5 finding 3) | 2026-11-06 | +| **Changes model results.** `add_unconformity` did not truncate a fault that was already in the model: the fault kept its frame and its surface above the unconformity and moved points there. Only a fault created after the call took the region of the unconformity | `add_unconformity` truncates every fault that is older than the unconformity: the fault takes the region of the unconformity, so its frame and surface exist only below it and it moves no point above it. A fault is younger (not changed) if it displaces the series of the unconformity, or a series above an earlier unconformity. Models change where a fault is added before the call and is left out of the `faults` list of the series of the unconformity, or is added between that series and the call. Models without an unconformity, models whose faults all displace the series of the unconformity, and onlap unconformities do not change (kiridashi requirement LS-D2) | 2026-11-16 | +| **Changes model results.** A fault created after two or more unconformities took the region of the last one only | It takes the region of each erosional unconformity that is before it in the model (LS-D2) | 2026-11-16 | +| **Changes model results.** The unconformity region of a fault that a younger fault displaces was read at a point restored twice through the younger fault (the same error as the double restoration of a displaced fault) | The region is read at the point restored once, so the older fault ends on the unconformity in the space in which its frame is built. Models change where a fault is truncated by an unconformity, is displaced by a younger fault, and both faults displace a series. `UnconformityFeature.evaluate` and `__call__` have a new keyword `restored_through` (LS-D2) | 2026-11-16 | +| **Bug fix that changes model results.** A feature that a fault displaces was restored twice through a younger fault when the younger fault also displaces that fault: the frame of the older fault is built in the space restored by the younger fault, and its evaluation restored the point through the younger fault a second time. The side and the slip of the older fault were read at the wrong point (all versions up to 1.11.0) | Each point is restored once through each fault. There is no flag for the old behaviour. **Models change** where a fault displaces a feature and is itself displaced by a younger fault that also displaces that feature: the restored data and the evaluated field of that feature both change (in the test model by up to 0.059, for an offset of the older fault of 0.082). **Models without displaced faults do not change.** New keyword `restored_through` on `FaultSegment.apply_to_points` / `apply_to_vectors` and `GeologicalFeature.evaluate_value` / `evaluate_gradient`. `LambdaGeologicalFeature` and `AnalyticalGeologicalFeature` keep their own fault loops and are not changed (kiridashi requirement LS-E1) | 2026-11-16 | 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. diff --git a/LoopStructural/modelling/core/_model_feature_factory.py b/LoopStructural/modelling/core/_model_feature_factory.py index 13be2d5dd..165861822 100644 --- a/LoopStructural/modelling/core/_model_feature_factory.py +++ b/LoopStructural/modelling/core/_model_feature_factory.py @@ -31,6 +31,7 @@ from ...modelling.features.fold import FoldEvent, FoldFrame from ...modelling.intrusions import IntrusionBuilder, IntrusionFeature, IntrusionFrameBuilder from ...utils import getLogger +from ._model_relationships import FeatureRelationshipManager if TYPE_CHECKING: from numpy.typing import ArrayLike @@ -775,10 +776,7 @@ def build_fault( fault.displacement = displacement_scaled fault.faultfunction = faultfunction - for f in reversed(model.features): - if f.type == FeatureType.UNCONFORMITY: - fault.add_region(f) - break + FeatureRelationshipManager.add_unconformities_above_fault(model, fault, index=index) if displacement == 0: fault.type = FeatureType.INACTIVEFAULT model._add_feature(fault, index=index) diff --git a/LoopStructural/modelling/core/_model_relationships.py b/LoopStructural/modelling/core/_model_relationships.py index 03ba1e6b3..9236b092a 100644 --- a/LoopStructural/modelling/core/_model_relationships.py +++ b/LoopStructural/modelling/core/_model_relationships.py @@ -174,10 +174,135 @@ def add_unconformity( continue else: f.add_region(uc_feature) + # the faults that are older than the unconformity end on it + for f in list(model.features): + if f.type not in (FeatureType.FAULT, FeatureType.INACTIVEFAULT): + continue + if FeatureRelationshipManager.fault_is_older_than(model, f, feature): + FeatureRelationshipManager.truncate_fault(model, f, uc_feature) # now add the unconformity to the feature list model._add_feature(uc_feature, index=index) return uc_feature + @staticmethod + def _displaced_by(feature: GeologicalFeature) -> list: + """The faults that displace a feature (read from its builder).""" + builder = getattr(feature, "builder", None) + builders = getattr(builder, "builders", None) + if builders is not None: + # a structural frame: the three coordinates have the same faults + builder = builders[0] + faults = getattr(builder, "faults", None) + if faults is None: + faults = getattr(feature, "faults", []) + return list(faults) + + @staticmethod + def fault_is_older_than( + model: GeologicalModel, fault: GeologicalFeature, feature: GeologicalFeature + ) -> bool: + """Whether a fault is older than the unconformity at the base of a feature. + + Call it before the unconformity is added to the model. + + The features of a model are in the order in which they were added, + and a new feature is displaced by every fault that the model has at + that moment, unless its ``faults`` argument gives another list. An + unconformity truncates the features that the model has back to the + last unconformity or domain fault; the features before that one lie + above an earlier unconformity and are younger. So the rule is: + + A fault is **younger** than the unconformity if it displaces + ``feature`` (the series whose isovalue is the unconformity), or a + feature that lies above an earlier unconformity. Every other fault + is **older**: a fault added after ``feature``, and a fault added + before it that the ``faults`` argument of ``feature`` leaves out. + + Parameters + ---------- + model : GeologicalModel + fault : FaultSegment + feature : GeologicalFeature + the series that defines the unconformity + + Returns + ------- + bool + """ + displaced_by = FeatureRelationshipManager._displaced_by + if any(d is fault for d in displaced_by(feature)): + return False + # the features that this unconformity does not truncate: all that + # are before the last unconformity or domain fault + boundary = None + for i in reversed(range(len(model.features))): + if model.features[i].type in (FeatureType.UNCONFORMITY, FeatureType.DOMAINFAULT): + boundary = i + break + if boundary is None: + return True + skip = ( + FeatureType.FAULT, + FeatureType.INACTIVEFAULT, + FeatureType.UNCONFORMITY, + FeatureType.ONLAPUNCONFORMITY, + ) + for f in model.features[:boundary]: + if f.type not in skip and any(d is fault for d in displaced_by(f)): + return False + return True + + @staticmethod + def truncate_fault( + model: GeologicalModel, fault: GeologicalFeature, unconformity: UnconformityFeature + ) -> bool: + """Limit a fault to the region below an unconformity. + + The fault frame gets the region of the unconformity: the frame, the + fault surface and the displacement exist only where the series of + the unconformity is below its value. A point above the unconformity + is not moved by the fault, so the fault does not displace the + features above it. The features that the fault displaces are marked + to be built again. + + Returns + ------- + bool + False if the fault already has this region. + """ + for r in fault.regions: + if ( + isinstance(r, UnconformityFeature) + and r.parent is unconformity.parent + and r.value == unconformity.value + and r.sign == unconformity.sign + ): + return False + logger.info(f"Adding {unconformity.name} as unconformity to fault {fault.name}") + fault.add_region(unconformity) + for f in model.features: + if any(d is fault for d in FeatureRelationshipManager._displaced_by(f)): + builder = getattr(f, "builder", None) + if builder is not None: + builder.set_not_up_to_date(fault) + return True + + @staticmethod + def add_unconformities_above_fault( + model: GeologicalModel, fault: GeologicalFeature, index: int | None = None + ) -> None: + """Truncate a new fault by the unconformities that are younger than it. + + A fault that is added after an unconformity is older than it. The + fault takes the region of every erosional unconformity that is + before its place in the model (``index``, or the end of the list). + Onlap unconformities are not used. + """ + features = model.features if index is None else model.features[:index] + for f in reversed(features): + if f.type == FeatureType.UNCONFORMITY: + FeatureRelationshipManager.truncate_fault(model, fault, f) + @staticmethod def add_onlap_unconformity( model: GeologicalModel, feature: GeologicalFeature, value: float, index: int | None = None @@ -216,3 +341,108 @@ def add_onlap_unconformity( model._add_feature(uc_feature.inverse(), index=index) return uc_feature + + @staticmethod + def relations(model: GeologicalModel) -> dict: + """Read the relations between the features of a model. + + The relations are read from the builders, which hold them from the + moment a feature is created, so the result does not depend on whether + the model has been built. Nothing is changed. + + Parameters + ---------- + model : GeologicalModel + + Returns + ------- + dict + ``events``: the features in the order they were added + (``{"name", "type"}``, ``type`` a :class:`FeatureType` name). A + feature added later is older; an unconformity entry follows the + series that defines it. + + ``faults``: for each fault, ``displaced_by`` (the faults that + displace its frame, youngest first), ``abuts`` (``{"fault", "side"}``: + side +1 if the fault exists where the host gx > 0, -1 where it is + < 0), ``truncated_by`` (see below) and ``displacement``. + + ``features``: for each other feature that is not an unconformity, + ``type``, ``faults`` (the faults that displace it, in restore + order: youngest first) and ``truncated_by``. + + ``unconformities``: for each unconformity, ``feature`` (the series + whose isovalue it is), ``value``, ``onlap`` and ``truncates`` (the + features and faults whose ``truncated_by`` names it). + + A ``truncated_by`` entry is ``{"unconformity", "feature", "value", + "keep"}``: the feature exists only where ``feature`` is ``<= value`` + (``keep == "below"``) or ``>= value`` (``"above"``). + """ + from ...modelling.features.fault import FaultSegment + from ...utils.regions import NegativeRegion, PositiveRegion + + def faults_of(feature): + builder = getattr(feature, "builder", None) + faults = getattr(builder, "faults", None) + if faults is None: + faults = feature.faults + return [f.name for f in faults] + + def truncations(regions): + out = [] + for r in regions: + if isinstance(r, UnconformityFeature): + out.append( + { + "unconformity": r.name, + "feature": r.parent.name, + "value": float(r.value), + "keep": "below" if r.sign else "above", + } + ) + return out + + events, faults, features, unconformities = [], {}, {}, {} + for feature in model.features: + events.append({"name": feature.name, "type": FeatureType(feature.type).name}) + if isinstance(feature, FaultSegment): + abuts = [] + for host, region in feature.abut.items(): + if isinstance(region, PositiveRegion): + side = 1 + elif isinstance(region, NegativeRegion): + side = -1 + else: + side = 0 + abuts.append({"fault": host, "side": side}) + faults[feature.name] = { + "displaced_by": faults_of(feature[0]), + "abuts": abuts, + "truncated_by": truncations(feature[0].regions), + "displacement": float(feature.displacement), + } + elif isinstance(feature, UnconformityFeature): + unconformities[feature.name] = { + "feature": feature.parent.name, + "value": float(feature.value), + "onlap": feature.type == FeatureType.ONLAPUNCONFORMITY, + "truncates": [], + } + else: + features[feature.name] = { + "type": FeatureType(feature.type).name, + "faults": faults_of(feature), + "truncated_by": truncations(feature.regions), + } + for name, entry in list(faults.items()) + list(features.items()): + for t in entry["truncated_by"]: + for u in unconformities.values(): + if u["feature"] == t["feature"] and u["value"] == t["value"]: + u["truncates"].append(name) + return { + "events": events, + "faults": faults, + "features": features, + "unconformities": unconformities, + } diff --git a/LoopStructural/modelling/core/geological_model.py b/LoopStructural/modelling/core/geological_model.py index cec10d228..c67b5bdb0 100644 --- a/LoopStructural/modelling/core/geological_model.py +++ b/LoopStructural/modelling/core/geological_model.py @@ -21,6 +21,7 @@ from ...modelling.features.fault import FaultSegment from ...modelling.features.fold import FoldFrame from ...utils import LoopValueError, getLogger, public_api, strikedip2vector, timed_stage +from ...utils._fault_block import check_block from ...utils.helper import ( all_heading, gradient_vec_names, @@ -60,6 +61,17 @@ class GeologicalModel: the origin of the model box parameters : dict a dictionary tracking the parameters used to build the model + tol : float + absolute tolerance of the residual of the solver, 1e-10 of the + longest side of the model. It has no length meaning. + position_tolerance : float or None + how far the isosurfaces of a cg-solved feature may be from the + isosurfaces of the fully converged field, as a length in the units + of the model (for example 1.0 for 1 m). It is an estimate, not a + bound: see ``DiscreteInterpolator.solve_system``. None (default) + keeps the stop on the solver residual. Set it before the features + are built; a feature can have its own value with the keyword + ``position_tolerance`` of the ``create_and_add_*`` methods. """ @@ -134,6 +146,7 @@ def __init__(self, *args): self._stratigraphic_column = StratigraphicColumn() self.tol = 1e-10 * np.max(self.bounding_box.maximum - self.bounding_box.origin) + self.position_tolerance = None self._dtm = None @public_api(tier="stable") @@ -920,6 +933,32 @@ def add_unconformity( """ Use an existing feature to add an unconformity to the model. + The unconformity is erosional. ``feature`` exists only above it. The + other features of the model back to the last unconformity, and the + features that are added later, exist only below it. + + The unconformity also truncates the faults that are older than it: + such a fault takes the region of the unconformity, so its frame and + its surface exist only below the unconformity and it moves no point + above it (it does not displace ``feature``). + + **Which faults are older.** The features of a model are in the order + in which they were added, and a new feature is displaced by every + fault that the model has at that moment, unless its ``faults`` + argument gives another list. A fault is *younger* than the + unconformity if it displaces ``feature``, or a feature that lies + above an earlier unconformity (a feature that this unconformity does + not truncate); it then cuts the unconformity and is not changed. + Every other fault is *older*: + + * a fault that is added after ``feature`` (before or after this + call), + * a fault that was added before ``feature`` and that the ``faults`` + argument of ``feature`` leaves out. + + A fault that is added after several unconformities is truncated by + each of them. + Parameters ---------- feature : GeologicalFeature @@ -942,6 +981,10 @@ def add_onlap_unconformity( """ Use an existing feature to add an unconformity to the model. + An onlap unconformity does not truncate faults: no fault takes its + region, whether the fault is added before or after this call. Only + :meth:`add_unconformity` (erosional) truncates the older faults. + Parameters ---------- feature : GeologicalFeature @@ -1405,6 +1448,116 @@ def evaluate_feature_gradient(self, feature_name, xyz, scale=True): else: return np.zeros(xyz.shape[0]) + @public_api(tier="provisional") + def evaluate_feature_block_value( + self, feature_name: str, xyz: np.ndarray, block: dict, *, ignore_regions: bool = True + ) -> np.ndarray: + """Evaluate a feature as it is in one fault block. + + A fault block gives, for faults that displace the feature, the side of + the fault that every point is taken to be on: ``+1`` the hanging wall + (fault frame coordinate gx > 0), ``-1`` the footwall, ``0`` the fault + is absent (it moves no point). The result is the field of that block, + extended smoothly over the whole model: it has no jump across the + faults that the block names, and it equals + :meth:`evaluate_feature_value` wherever the points are in that block. + A fault that the block does not name keeps the side of each point. + + The block is also used for the faults that displace the faults of the + feature, and for the regions of the faults (for example, a fault that + abuts on the hanging wall of another fault is absent in a block that + puts the points on the footwall of that fault). + + The call changes no state, so calls with different blocks can run at + the same time. + + Parameters + ---------- + feature_name : str + name of the feature + xyz : np.ndarray + Nx3 locations, world coordinates + block : dict + maps fault names (or faults) to +1, -1 or 0 + ignore_regions : bool, optional + do not apply the regions of the feature itself (for example a + younger unconformity), by default True: the block field covers the + whole support of the feature + + Returns + ------- + np.ndarray + N values, NaN where the feature has no support + + Examples + -------- + >>> hanging_wall = model.evaluate_feature_block_value("strat", xyz, {"fault": 1}) + >>> footwall = model.evaluate_feature_block_value("strat", xyz, {"fault": -1}) + """ + feature = self.get_feature_by_name(feature_name) + return feature.evaluate_value( + np.asarray(xyz, dtype=float), + ignore_regions=ignore_regions, + block=self._check_fault_block(block), + ) + + @public_api(tier="provisional") + def evaluate_feature_block_gradient( + self, feature_name: str, xyz: np.ndarray, block: dict, *, ignore_regions: bool = True + ) -> np.ndarray: + """Evaluate the gradient of a feature as it is in one fault block. + + See :meth:`evaluate_feature_block_value` for the block and the + parameters. + + Returns + ------- + np.ndarray + Nx3 gradients, NaN where the feature has no support + """ + feature = self.get_feature_by_name(feature_name) + return feature.evaluate_gradient( + np.asarray(xyz, dtype=float), + ignore_regions=ignore_regions, + block=self._check_fault_block(block), + ) + + @public_api(tier="provisional") + def get_feature_relations(self) -> dict: + """Return the relations between the features of the model. + + For each fault: the faults that displace it, the faults it abuts on + and on which side, the unconformities that truncate it. For each + other feature: the faults that displace it (restore order) and the + unconformities that truncate it. For each unconformity: its series, + value and what it truncates. And the order in which the features were + added (the event order). The result is a plain dictionary, valid + before and after :meth:`update`; nothing is changed. See + :meth:`FeatureRelationshipManager.relations` for the keys. + + Returns + ------- + dict + keys ``events``, ``faults``, ``features``, ``unconformities`` + + Examples + -------- + >>> rel = model.get_feature_relations() + >>> rel["faults"]["f_pre"]["displaced_by"] + ['f_post'] + """ + return FeatureRelationshipManager.relations(self) + + def _check_fault_block(self, block) -> dict: + """Check that a fault block names only faults of this model.""" + block = check_block(block) + if block is None: + raise ValueError("block must map fault names to +1, -1 or 0") + unknown = sorted(set(block) - set(self.fault_names())) + if unknown: + raise ValueError(f"block names faults that are not in the model: {unknown}") + return block + @public_api(tier="stable") def update(self, verbose=False, progressbar=True): total_dof = 0 diff --git a/LoopStructural/modelling/features/_base_geological_feature.py b/LoopStructural/modelling/features/_base_geological_feature.py index cddd98da9..dcbe7a527 100644 --- a/LoopStructural/modelling/features/_base_geological_feature.py +++ b/LoopStructural/modelling/features/_base_geological_feature.py @@ -7,6 +7,8 @@ from LoopStructural.geometry import VectorPoints from LoopStructural.modelling.features import FeatureType from LoopStructural.utils import LoopIsosurfacer, LoopValueError, getLogger, surface_list +from LoopStructural.utils._fault_block import block_kwargs, is_in, restore_through +from LoopStructural.utils.regions import BaseRegion from LoopStructural.utils.typing import NumericInput logger = getLogger(__name__) @@ -193,20 +195,22 @@ def add_region(self, region): """ self.regions.append(region) - def __call__(self, xyz): + def __call__(self, xyz, *, block=None): """Calls evaluate_value method Parameters ---------- xyz : np.ndarray location to evaluate feature + block : dict, optional + fault block, passed to evaluate_value if given Returns ------- np.ndarray the value of the feature at the locations """ - return self.evaluate_value(xyz) + return self.evaluate_value(xyz, **block_kwargs(block)) @abstractmethod def evaluate_value(self, pos, ignore_regions=False): @@ -226,13 +230,24 @@ def evaluate_normalised_value(self, pos: NumericInput): value = self.evaluate_value(pos) return (value - self.min()) / (self.max() - self.min()) - def _calculate_mask(self, evaluation_points: np.ndarray, ignore_regions=False) -> np.ndarray: + def _calculate_mask( + self, evaluation_points: np.ndarray, ignore_regions=False, block=None, + restored_through=(), + ) -> np.ndarray: """Calculate the mask for which evaluation points need to be calculated Parameters ---------- evaluation_points : np.ndarray location to be evaluated, Nx3 array + block : dict, optional + fault block, passed on to the regions that are features or + region objects (a plain function region is called without it) + restored_through : sequence of FaultSegment + faults whose restoration the points already have. A region that + is an unconformity is read without applying them again: the + frame of a fault that younger faults displace is built in the + restored space, and it ends on the unconformity in that space. Returns ------- @@ -245,17 +260,26 @@ def _calculate_mask(self, evaluation_points: np.ndarray, ignore_regions=False) - if not ignore_regions: # check regions for r in self.regions: - # try: - mask = np.logical_and(mask, r(evaluation_points)) + kwargs = block_kwargs(block) if isinstance(r, (BaseRegion, BaseFeature)) else {} + if restored_through and getattr(r, "takes_restored_through", False): + kwargs["restored_through"] = tuple(restored_through) + mask = np.logical_and(mask, r(evaluation_points, **kwargs)) return mask - def _apply_faults(self, evaluation_points: np.ndarray, reverse: bool = False) -> np.ndarray: + def _apply_faults( + self, evaluation_points: np.ndarray, reverse: bool = False, block=None, + restored_through=(), + ) -> np.ndarray: """Calculate the restored location of the points given any faults if faults are enabled Parameters ---------- evaluation_points : np.ndarray location to be evaluated, Nx3 array + block : dict, optional + fault block, see :meth:`FaultSegment.apply_to_points` + restored_through : sequence of FaultSegment + faults whose restoration the points already have (skipped) Returns ------- @@ -264,11 +288,21 @@ def _apply_faults(self, evaluation_points: np.ndarray, reverse: bool = False) -> """ if self.faults_enabled: - # check faults - for f in self.faults: - evaluation_points = f.apply_to_points(evaluation_points, reverse=reverse) + evaluation_points = restore_through( + evaluation_points, + self.faults, + reverse=reverse, + block=block, + restored_through=restored_through, + ) return evaluation_points + def _unrestored_faults(self, restored_through=()) -> list: + """The faults of the feature that the points have not been restored through.""" + if not self.faults_enabled: + return [] + return [f for f in self.faults if not is_in(f, restored_through)] + @abstractmethod def evaluate_gradient(self, pos, ignore_regions=False): """ diff --git a/LoopStructural/modelling/features/_geological_feature.py b/LoopStructural/modelling/features/_geological_feature.py index 8273477b3..518b09fdf 100644 --- a/LoopStructural/modelling/features/_geological_feature.py +++ b/LoopStructural/modelling/features/_geological_feature.py @@ -23,6 +23,7 @@ from ...geometry import ValuePoints, VectorPoints from ...utils import LoopValueError, getLogger +from ...utils._fault_block import block_kwargs, check_block from . import FeatureType from ._base_geological_feature import BaseFeature @@ -125,7 +126,10 @@ def __setitem__(self, key, item): def set_model(self, model): self.model = model - def evaluate_value(self, pos: np.ndarray, ignore_regions=False, fillnan=None) -> np.ndarray: + def evaluate_value( + self, pos: np.ndarray, ignore_regions=False, fillnan=None, *, block=None, + restored_through=(), + ) -> np.ndarray: """ Evaluate the scalar field value of the geological feature at the locations specified @@ -134,6 +138,19 @@ def evaluate_value(self, pos: np.ndarray, ignore_regions=False, fillnan=None) -> ---------- pos : np.ndarray location to evaluate the scalar value + block : dict, optional + fault block: maps fault names to +1 (hanging wall), -1 (footwall) or + 0 (absent). Each fault that the block names restores every point + as if the point were on that side, so the result is the smooth + extension of that fault block over the whole support, with no jump + across those faults. Faults that the block does not name keep the + side of each point. The call changes no state. See + :meth:`GeologicalModel.evaluate_feature_block_value`. + restored_through : sequence of FaultSegment, optional + faults whose restoration the points already have: they are not + applied again. A fault uses this to evaluate its frame at points + that a feature has already restored through the younger faults + that displace the fault. Returns ------- @@ -143,6 +160,7 @@ def evaluate_value(self, pos: np.ndarray, ignore_regions=False, fillnan=None) -> """ if pos.shape[1] != 3: raise LoopValueError("Need Nx3 array of xyz points to evaluate value") + block = check_block(block) # TODO need to add a generic type checker for all methods # if evaluation_points is not a numpy array try and convert # otherwise error @@ -153,8 +171,12 @@ def evaluate_value(self, pos: np.ndarray, ignore_regions=False, fillnan=None) -> # check if the points are within the display region v = np.zeros(evaluation_points.shape[0]) v[:] = np.nan - mask = self._calculate_mask(pos, ignore_regions=ignore_regions) - evaluation_points = self._apply_faults(evaluation_points) + mask = self._calculate_mask( + pos, ignore_regions=ignore_regions, block=block, restored_through=restored_through + ) + evaluation_points = self._apply_faults( + evaluation_points, block=block, restored_through=restored_through + ) if mask.dtype not in [int, bool]: logger.error(f"Unable to evaluate value for {self.name}") else: @@ -169,7 +191,8 @@ def evaluate_value(self, pos: np.ndarray, ignore_regions=False, fillnan=None) -> return v def evaluate_gradient( - self, pos: np.ndarray, ignore_regions=False, element_scale_parameter=None + self, pos: np.ndarray, ignore_regions=False, element_scale_parameter=None, *, block=None, + restored_through=(), ) -> np.ndarray: """ @@ -177,6 +200,11 @@ def evaluate_gradient( ---------- locations : numpy array location where the gradient is being evaluated + block : dict, optional + fault block, see :meth:`evaluate_value`. The gradient is the + gradient of the block field. + restored_through : sequence of FaultSegment, optional + see :meth:`evaluate_value` Returns ------- @@ -185,6 +213,7 @@ def evaluate_gradient( """ if pos.shape[1] != 3: raise LoopValueError("Need Nx3 array of xyz points to evaluate gradient") + block = check_block(block) logger.info(f'Calculating gradient for {self.name}') if element_scale_parameter is None: if self.model is not None: @@ -203,22 +232,29 @@ def evaluate_gradient( v = np.zeros(pos.shape) v[:] = np.nan - mask = self._calculate_mask(pos, ignore_regions=ignore_regions) + mask = self._calculate_mask( + pos, ignore_regions=ignore_regions, block=block, restored_through=restored_through + ) # evaluate the faults on the nodes of the faulted feature support # then evaluate the gradient at these points - if len(self.faults) > 0: + faults = self._unrestored_faults(restored_through) + if len(faults) > 0: # generate a regular tetrahedron for each point # we will then move these points by the fault and then recalculate the gradient. # this should work... resolved = False tetrahedron = regular_tetraherdron_for_points(pos, element_scale_parameter) + # A fault that the block names has no jump, so a tetrahedron may cross it. + jumping = [f for f in faults if not block or f.name not in block] while not resolved: resolved = True - for f in self.faults: + for f in jumping: side = ( f[0] - .evaluate_value(tetrahedron.reshape(-1, 3), fillnan='nearest') + .evaluate_value( + tetrahedron.reshape(-1, 3), fillnan='nearest', **block_kwargs(block) + ) .reshape(tetrahedron.shape[0], 4) ) flag = np.logical_or(np.all(side > 0, axis=1), np.all(side < 0, axis=1)) @@ -230,9 +266,9 @@ def evaluate_gradient( tetrahedron = regular_tetraherdron_for_points(pos, element_scale_parameter) resolved = False - tetrahedron_faulted = self._apply_faults(np.array(tetrahedron.reshape(-1, 3))).reshape( - tetrahedron.shape - ) + tetrahedron_faulted = self._apply_faults( + np.array(tetrahedron.reshape(-1, 3)), block=block, restored_through=restored_through + ).reshape(tetrahedron.shape) values = self.interpolator.evaluate_value(tetrahedron_faulted.reshape(-1, 3)).reshape( (-1, 4) @@ -240,7 +276,7 @@ def evaluate_gradient( v[mask, :] = gradient_from_tetrahedron(tetrahedron[mask, :, :], values[mask]) return v - pos = self._apply_faults(pos) + pos = self._apply_faults(pos, block=block, restored_through=restored_through) if mask.dtype not in [int, bool]: logger.error(f"Unable to evaluate gradient for {self.name}") else: diff --git a/LoopStructural/modelling/features/_unconformity_feature.py b/LoopStructural/modelling/features/_unconformity_feature.py index c2986123a..8387f44d1 100644 --- a/LoopStructural/modelling/features/_unconformity_feature.py +++ b/LoopStructural/modelling/features/_unconformity_feature.py @@ -59,23 +59,32 @@ def inverse(self): uc.name = self.name + "_inverse" return uc - def evaluate(self, pos: np.ndarray) -> np.ndarray: + # _calculate_mask passes restored_through to a region with this flag + takes_restored_through = True + + def evaluate(self, pos: np.ndarray, *, block=None, restored_through=()) -> np.ndarray: """ Parameters ---------- pos : numpy array locations to evaluate whether below or above unconformity + block : dict, optional + fault block in which the unconformity is evaluated + restored_through : sequence of FaultSegment, optional + faults whose restoration the points already have: the series of + the unconformity does not apply them again Returns ------- np.ndarray.dtype(bool) true if above the unconformity, false if below """ + kwargs = {"restored_through": tuple(restored_through)} if restored_through else {} if self.sign: - return self.evaluate_value(pos) <= self.value + return self.evaluate_value(pos, block=block, **kwargs) <= self.value if not self.sign: - return self.evaluate_value(pos) >= self.value + return self.evaluate_value(pos, block=block, **kwargs) >= self.value - def __call__(self, pos) -> np.ndarray: - return self.evaluate(pos) + def __call__(self, pos, *, block=None, restored_through=()) -> np.ndarray: + return self.evaluate(pos, block=block, restored_through=restored_through) diff --git a/LoopStructural/modelling/features/builders/_geological_feature_builder.py b/LoopStructural/modelling/features/builders/_geological_feature_builder.py index ebd6fe527..24b416654 100644 --- a/LoopStructural/modelling/features/builders/_geological_feature_builder.py +++ b/LoopStructural/modelling/features/builders/_geological_feature_builder.py @@ -9,6 +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.helper import ( get_data_bounding_box_map as get_data_bounding_box, ) @@ -217,8 +218,11 @@ def add_data_to_interpolator(self, constrained=False, force_constrained=False, * data.loc[mask_tangent, xyz_names() + tangent_vec_names()].to_numpy(float) ) - for f in self.faults: - data.loc[:, xyz_names()] = f.apply_to_points(data.loc[:, xyz_names()]) + # Each fault once: a fault displaced by a younger fault of this list + # evaluates its frame at the points already restored by that fault. + data.loc[:, xyz_names()] = restore_through( + data.loc[:, xyz_names()].to_numpy(float), self.faults + ) # self.check_interpolation_geometry(data.loc[:,xyz_names()].to_numpy()) # Now check whether there are enough constraints for the @@ -534,8 +538,7 @@ def check_interpolation_geometry(self, data, buffer=0.3): logger.info(f"Checking interpolation geometry for {self.name}") # The grid and the fault restoration are in world coordinates. pts = self.model.bounding_box.with_buffer(buffer).regular_grid(local=False) - for f in self.faults: - pts = f.apply_to_points(pts) + pts = restore_through(pts, self.faults) pts = self.interpolator.world_to_local_points(pts) # Use copies. Do not change the support arrays in place. origin = np.minimum(self.interpolator.support.origin.copy(), np.min(pts, axis=0)) @@ -615,10 +618,29 @@ def build(self, data_region=None, **kwargs): self.install_equality_constraints() logger.info(f'running interpolation for {self.name}') + solve_kwargs = {} + # A position tolerance of the feature, else the one of the model. + # It is passed only when set: other interpolators do not take it. + position_tolerance = kwargs.get( + 'position_tolerance', getattr(self.model, 'position_tolerance', None) + ) + if position_tolerance is not None: + import inspect + + if 'position_tolerance' in inspect.signature( + self.interpolator.solve_system + ).parameters: + solve_kwargs['position_tolerance'] = position_tolerance + else: + logger.warning( + f'{type(self.interpolator).__name__} has no position_tolerance; ' + f'{self.name} is solved with tol' + ) self.interpolator.solve_system( solver=kwargs.get('solver', 'cg'), tol=kwargs.get('tol', None), solver_kwargs=kwargs.get('solver_kwargs', {}), + **solve_kwargs, ) logger.info(f'Finished building {self.name}') self._up_to_date = True diff --git a/LoopStructural/modelling/features/fault/_fault_function.py b/LoopStructural/modelling/features/fault/_fault_function.py index 752608a72..41895bb6e 100644 --- a/LoopStructural/modelling/features/fault/_fault_function.py +++ b/LoopStructural/modelling/features/fault/_fault_function.py @@ -16,6 +16,10 @@ def smooth_peak(x): return v +# smooth_peak is zero for |x| >= 1: a tip at both ends (see FaultDisplacement.tip_ends). +smooth_peak.tip_ends = (1, -1) + + class FaultProfileFunction(metaclass=ABCMeta): def __init__(self): self.lim = [-1, 1] @@ -28,6 +32,16 @@ def to_dict(self) -> dict: def __call__(self, v: np.ndarray) -> np.ndarray: pass + @property + def tip_ends(self) -> tuple | None: + """The ends (+1, -1) of the coordinate beyond which the profile is zero. + + A tip at +1 means the profile is exactly zero for v >= 1. The default + is None: not declared (``FaultDisplacement.tip_ends`` then tests the + profile numerically). + """ + return None + def plot(self, ax=None): if ax is None: import matplotlib.pyplot as plt @@ -128,21 +142,33 @@ def solve(self): self.w = np.linalg.lstsq(ATA, ATB, rcond=None)[0] self.up_to_date = True + @property + def tip_ends(self) -> tuple: + """The limits at +-1 where the cubic is zero; it is clamped beyond them.""" + self.solve() + ends = [] + for end, lim in ((1, self.lim[1]), (-1, self.lim[0])): + value = self._limit_value(lim) + if lim == end and min(max(value, self.min_v), self.max_v) == 0.0: + ends.append(end) + return tuple(ends) + + def _limit_value(self, x: float) -> float: + """Value at a limit: the value constraint there if there is one, else the cubic. + + The least squares fit leaves about 1e-14 where a constraint asks for 0; + using the constraint makes a profile that ends at 0 exactly 0 beyond it. + """ + for cx, cy in self.value_points: + if cx == x: + return float(cy) + return self.w[0] * x**3 + self.w[1] * x**2 + self.w[2] * x + self.w[3] + def __call__(self, v): self.solve() eva = self.w[0] * v**3 + self.w[1] * v**2 + self.w[2] * v + self.w[3] - eva[v > self.lim[1]] = ( - self.w[0] * self.lim[1] ** 3 - + self.w[1] * self.lim[1] ** 2 - + self.w[2] * self.lim[1] - + self.w[3] - ) - eva[v < self.lim[0]] = ( - self.w[0] * self.lim[0] ** 3 - + self.w[1] * self.lim[0] ** 2 - + self.w[2] * self.lim[0] - + self.w[3] - ) + eva[v >= self.lim[1]] = self._limit_value(self.lim[1]) + eva[v <= self.lim[0]] = self._limit_value(self.lim[0]) eva[eva > self.max_v] = self.max_v eva[eva < self.min_v] = self.min_v @@ -204,6 +230,8 @@ def __init__(self, positive: FaultProfileFunction, negative: FaultProfileFunctio self.positive = positive self.negative = negative + tip_ends = () + def __call__(self, v: np.ndarray) -> np.ndarray: """calculate the displacement for the input coordinate @@ -270,6 +298,8 @@ def __call__(self, v: np.ndarray) -> np.ndarray: v = np.array(v) return np.ones(v.shape) + tip_ends = () + def to_dict(self) -> dict: return {} @@ -299,6 +329,8 @@ def __call__(self, v: np.ndarray) -> np.ndarray: v = np.array(v) return np.zeros(v.shape) + tip_ends = () + def to_dict(self) -> dict: return {} @@ -361,6 +393,24 @@ def __call__(self, gx, gy, gz): return self.scale * self.gx(gx) * self.gy(gy) * self.gz(gz) + @property + def tip_ends(self) -> dict: + """The tip of the fault: for gy (1) and gz (2), the ends where the profile is zero. + + A tip at end e of coordinate c means the displacement is exactly zero + where ``e * g_c >= 1``; ``FaultSegment.evaluate_tip_value`` is built + from it. A profile declares its ends with an attribute ``tip_ends`` + (the library profiles and ``smooth_peak`` do). For a profile that does + not, the ends are found by testing that the profile is zero at + ``|g| = 1, 1.5, 2, 10``. + + Returns + ------- + dict of int to tuple of int + ``{1: ends of gy, 2: ends of gz}``; an empty tuple: no tip + """ + return {1: _profile_tip_ends(self.gy), 2: _profile_tip_ends(self.gz)} + def to_dict(self) -> dict: return { "gx": self.gx.to_dict(), @@ -394,6 +444,172 @@ def plot(self, range=(-1, 1), axs: list | None = None): return +def _saturate(distance: np.ndarray) -> np.ndarray: + """Limit a distance from the fault: the identity up to BLOCK_EXTENSION_EXACT, + constant beyond BLOCK_EXTENSION_LIMIT, and C2 in between.""" + from ....utils import _fault_block + + exact, limit = _fault_block.BLOCK_EXTENSION_EXACT, _fault_block.BLOCK_EXTENSION_LIMIT + length = limit - exact + t = np.clip((distance - exact) / length, 0.0, 1.0) + # q(0) = 0, q'(0) = 1, q''(0) = 0, q'(1) = 0, q''(1) = 0 + return np.minimum(distance, exact) + length * (t - t**3 + 0.5 * t**4) + + +def _taylor(function, x: np.ndarray, side: int) -> np.ndarray: + """Second-order expansion of ``function`` at the fault, from the side ``side``. + + ``d(x0) + d'(x0) (x - x0) + 0.5 d''(x0) (x - x0)**2`` about + ``x0 = side * BLOCK_SIDE_EPSILON``, the place of a point on the fault in + the block, with one-sided finite differences of fourth order on six + points with the step ``BLOCK_EXTENSION_STEP`` (their error is of the + order of the step to the fourth power times the fifth and sixth + derivative of the profile; the rounding error of the curvature is about + 1e-9 for a profile of size 1). + """ + from ....utils import _fault_block + + h = _fault_block.BLOCK_EXTENSION_STEP + x0 = side * _fault_block.BLOCK_SIDE_EPSILON + f0, f1, f2, f3, f4, f5 = (function(x0 + side * k * h) for k in range(6)) + slope = side * (-25.0 * f0 + 48.0 * f1 - 36.0 * f2 + 16.0 * f3 - 3.0 * f4) / (12.0 * h) + curvature = ( + 45.0 * f0 - 154.0 * f1 + 214.0 * f2 - 156.0 * f3 + 61.0 * f4 - 10.0 * f5 + ) / (12.0 * h**2) + return f0 + slope * (x - x0) + 0.5 * curvature * (x - x0) ** 2 + + +def continue_profile(profile, x: np.ndarray, side: int) -> np.ndarray: + """A gx profile of the side ``side`` continued to the other side of the fault. + + Parameters + ---------- + profile : callable + the profile of the block's side: the positive or negative part of a + :class:`Composite`, or the whole gx profile + x : np.ndarray + fault frame coordinate gx of points on the other side + (``side * x < 0``) + side : int + +1 or -1 + + Returns + ------- + np.ndarray + * :class:`Ones`, :class:`Zeros`: the constant. + * :class:`CubicFunction`: its own cubic at the signed coordinate + (without its limits and its floor and ceiling). This is the + natural continuation, smooth to all orders at the fault. + * any other callable: the second-order expansion at the fault + (:func:`_taylor`), so the value, the slope and the curvature are + continuous (C2) and the third derivative is not. + + Beyond ``BLOCK_EXTENSION_EXACT`` from the fault the coordinate is + limited (:func:`_saturate`), so the continuation is constant beyond + ``BLOCK_EXTENSION_LIMIT``. + """ + from ....utils import _fault_block + + x = np.asarray(x, dtype=float) + if isinstance(profile, (Ones, Zeros)): + return np.asarray(profile(x), dtype=float) + x = -side * _saturate(np.abs(x)) + if isinstance(profile, CubicFunction): + profile.solve() + w = profile.w + + def cubic(v): + return w[0] * v**3 + w[1] * v**2 + w[2] * v + w[3] + + # the cubic is the profile at the fault unless a limit, a floor or a + # ceiling acts there + near = side * np.array([_fault_block.BLOCK_SIDE_EPSILON, _fault_block.BLOCK_EXTENSION_STEP]) + if np.allclose(profile(near), cubic(near), rtol=0.0, atol=1e-12): + return cubic(x) + + def scalar(v): + return float(np.asarray(profile(np.array([v], dtype=float)), dtype=float)[0]) + + return _taylor(scalar, x, side) + + +def block_displacement(faultfunction, gx, forced_gx, gy, gz, side) -> np.ndarray: + """The displacement profile of a fault in the block that has the side ``side``. + + On the block's own side (``side * gx >= 0``) this is the profile itself. + On the other side it is the smooth continuation of the profile of the + block's side across gx = 0 (``_fault_block.BLOCK_EXTENSION == "smooth"``): + + * a :class:`FaultDisplacement`: its gx profile is continued + (:func:`continue_profile`); the gy and gz profiles are not changed. + * any other ``faultfunction(gx, gy, gz)``: the second-order expansion + in gx at the fault, at the gy and gz of each point. + + The value, the slope and the curvature in gx are continuous at the fault + (C2), so a field restored with this displacement has a continuous + gradient across the fault surface. With ``BLOCK_EXTENSION == "mirror"`` + the other side takes the mirror image (the profile at ``side * |gx|``), + which has a kink where the profile has a slope at the fault. + + Parameters + ---------- + faultfunction : callable + ``faultfunction(gx, gy, gz)`` + gx : np.ndarray + fault frame coordinate of the points + forced_gx : np.ndarray + ``force_side(gx, side)``: gx on the block's side + gy, gz : np.ndarray + side : int or None + +1, -1, or None (no block side: the profile at gx) + + Returns + ------- + np.ndarray + """ + from ....utils import _fault_block + + out = faultfunction(forced_gx, gy, gz) + if side not in (-1, 1) or _fault_block.BLOCK_EXTENSION != "smooth": + return out + other = side * gx < 0 + if not np.any(other): + return out + out = np.array(out, dtype=float, copy=True) + x, y, z = gx[other], gy[other], gz[other] + if isinstance(faultfunction, FaultDisplacement): + profile = faultfunction.gx + if isinstance(profile, Composite): + profile = profile.positive if side > 0 else profile.negative + out[other] = ( + faultfunction.scale + * continue_profile(profile, x, side) + * faultfunction.gy(y) + * faultfunction.gz(z) + ) + else: + x = -side * _saturate(np.abs(x)) + + def at(v): + return np.asarray(faultfunction(np.full(x.shape, v), y, z), dtype=float) + + out[other] = _taylor(at, x, side) + return out + + +def _profile_tip_ends(profile) -> tuple: + """The declared tip ends of a profile, or ends found by testing it.""" + ends = getattr(profile, "tip_ends", None) + if ends is not None: + return tuple(ends) + found = [] + for end in (1, -1): + beyond = end * np.array([1.0, 1.5, 2.0, 10.0]) + if np.all(np.asarray(profile(beyond), dtype=float) == 0.0): + found.append(end) + return tuple(found) + + class BaseFault: """ """ diff --git a/LoopStructural/modelling/features/fault/_fault_segment.py b/LoopStructural/modelling/features/fault/_fault_segment.py index 944675d59..e3b1453ca 100644 --- a/LoopStructural/modelling/features/fault/_fault_segment.py +++ b/LoopStructural/modelling/features/fault/_fault_segment.py @@ -5,11 +5,17 @@ from LoopStructural.utils.maths import gradient_from_tetrahedron, regular_tetraherdron_for_points from ....modelling.features import FeatureType, StructuralFrame -from ....modelling.features.fault._fault_function import BaseFault, BaseFault3D, FaultDisplacement +from ....modelling.features.fault._fault_function import ( + BaseFault, + BaseFault3D, + FaultDisplacement, + block_displacement, +) from ....modelling.features.fault._fault_function_feature import ( FaultDisplacementFeature, ) -from ....utils import NegativeRegion, PositiveRegion, getLogger +from ....utils import NegativeRegion, PositiveRegion, getLogger, public_api +from ....utils._fault_block import block_kwargs, block_side, check_block, force_side logger = getLogger(__name__) @@ -205,7 +211,7 @@ def inside_volume(self, locations, threshold=0.001): return np.abs(v) > threshold # return np.all(np.logical_and(v > -1,v<1),axis=1) - def evaluate_value(self, locations, ignore_regions=False): + def evaluate_value(self, locations, ignore_regions=False, *, block=None): """ Return the value of the fault surface scalar field @@ -213,6 +219,14 @@ def evaluate_value(self, locations, ignore_regions=False): ---------- locations - numpy array location to evaluate scalar field + ignore_regions : bool + do not apply the regions of the fault (for example an abutting fault) + block : dict, optional + fault block, maps fault names to +1 (hanging wall), -1 (footwall) or + 0 (absent); see :meth:`GeologicalModel.evaluate_feature_block_value`. + If the block names this fault with +1 or -1, the value is put on that + side (``side * |gx|``), so a region defined by this fault gives the + same answer at every point. Returns ------- @@ -230,7 +244,11 @@ def evaluate_value(self, locations, ignore_regions=False): # except: # logger.error("nan slicing") # v[mask] = self.__getitem__(0).evaluate_value(locations[mask, :]) - return self.__getitem__(0).evaluate_value(locations, ignore_regions=ignore_regions) + block = check_block(block) + v = self.__getitem__(0).evaluate_value( + locations, ignore_regions=ignore_regions, **block_kwargs(block) + ) + return force_side(v, block_side(block, self.name)) def ellipsoid(self): pass @@ -274,39 +292,241 @@ def evaluate_gradient(self, locations): v[mask, :] *= scale[:, None] * self.displacement return v - def evaluate_displacement(self, points): - newp = np.copy(points).astype(float) - # evaluate fault function for all - # points then define mask for only points affected by fault - gx = None - gy = None - gz = None - if use_threads: + def _evaluate_frame(self, points, block=None, precomputed_gx=None, restored_through=()): + """Evaluate the three fault frame coordinates at the points. + + Parameters + ---------- + points : np.ndarray + Nx3 locations + block : dict, optional + checked fault block; gx is put on the side that the block gives + for this fault, and the frame is evaluated in the block of the + faults that displace this fault + precomputed_gx : np.ndarray, optional + gx already evaluated at the same points + restored_through : sequence of FaultSegment + faults whose restoration the points already have; the frame does + not apply them again + + Returns + ------- + tuple of np.ndarray + gx, gy, gz + """ + kwargs = block_kwargs(block) + if restored_through: + kwargs["restored_through"] = tuple(restored_through) + if precomputed_gx is not None: + gx = precomputed_gx + gy = self.__getitem__(1).evaluate_value(points, **kwargs) + gz = self.__getitem__(2).evaluate_value(points, **kwargs) + elif use_threads: with ThreadPoolExecutor(max_workers=8) as executor: # all of these operations should be independent so # just run as different threads - gx_future = executor.submit(self.__getitem__(0).evaluate_value, newp) - gy_future = executor.submit(self.__getitem__(1).evaluate_value, newp) - gz_future = executor.submit(self.__getitem__(2).evaluate_value, newp) + gx_future = executor.submit(self.__getitem__(0).evaluate_value, points, **kwargs) + gy_future = executor.submit(self.__getitem__(1).evaluate_value, points, **kwargs) + gz_future = executor.submit(self.__getitem__(2).evaluate_value, points, **kwargs) gx = gx_future.result() gy = gy_future.result() gz = gz_future.result() else: - gx = self.__getitem__(0).evaluate_value(newp) - gy = self.__getitem__(1).evaluate_value(newp) - gz = self.__getitem__(2).evaluate_value(newp) + gx = self.__getitem__(0).evaluate_value(points, **kwargs) + gy = self.__getitem__(1).evaluate_value(points, **kwargs) + gz = self.__getitem__(2).evaluate_value(points, **kwargs) + return gx, gy, gz + + def _displacement_fraction(self, gx, gy, gz, block=None, offset=0.0): + """The displacement at the frame coordinates, as a fraction of the displacement. + + Parameters + ---------- + gx, gy, gz : np.ndarray + fault frame coordinates (:meth:`_evaluate_frame`), NaN where the + fault has no frame + block : dict, optional + checked fault block. If it gives a side for this fault, every + point takes the displacement of that side: the profile itself on + that side and its smooth continuation across the fault on the + other side (see ``_fault_function.block_displacement``). + offset : float + added to gx in the profile + + Returns + ------- + np.ndarray + zero where a frame coordinate is NaN + """ + side = block_side(block, self.name) + forced = force_side(gx, side) if side in (-1, 1) else gx d = np.zeros(gx.shape) - mask = np.logical_and(~np.isnan(gx), ~np.isnan(gy)) + mask = np.logical_and(~np.isnan(forced), ~np.isnan(gy)) mask = np.logical_and(mask, ~np.isnan(gz)) d[~mask] = 0 gx_mask = np.zeros_like(mask, dtype=bool) - gx_mask[mask] = gx[mask] > 0 + gx_mask[mask] = forced[mask] > 0 d[gx_mask] = 1.0 if self.faultfunction is not None: - d[mask] = self.faultfunction(gx[mask] + self.fault_offset, gy[mask], gz[mask]) + d[mask] = block_displacement( + self.faultfunction, gx[mask] + offset, forced[mask] + offset, gy[mask], gz[mask], + side, + ) + return d + + def evaluate_displacement(self, points, *, block=None): + """Evaluate the displacement magnitude of the fault at the points. + + Parameters + ---------- + points : np.ndarray + Nx3 locations + block : dict, optional + fault block (see :meth:`apply_to_points`) + + Returns + ------- + np.ndarray + displacement magnitude, zero where the fault does not move points + """ + block = check_block(block) + if block_side(block, self.name) == 0: + return np.zeros(np.shape(points)[0]) + newp = np.copy(points).astype(float) + # evaluate fault function for all + # points then define mask for only points affected by fault + gx, gy, gz = self._evaluate_frame(newp, block) + d = self._displacement_fraction(gx, gy, gz, block, offset=self.fault_offset) return d * self.displacement - def apply_to_points(self, points, reverse=False, precomputed_gx=None): + @public_api(tier="provisional") + def evaluate_frame_value(self, points, coordinate: int = 0, *, block=None) -> np.ndarray: + """Evaluate one coordinate of the fault frame, without the fault regions. + + Coordinate 0 (gx) is zero on the fault surface and positive in the + hanging wall, so ``gx / |grad gx|`` is a signed distance to the fault + near the fault. Coordinate 1 (gy) follows the slip direction and + coordinate 2 (gz) the fault extent. The regions of the fault (for + example the side of an abutting fault where the fault exists) are not + applied: the fault surface is extended over the whole support. + + Parameters + ---------- + points : np.ndarray + Nx3 locations, world coordinates + coordinate : int + 0, 1 or 2 + block : dict, optional + fault block of the younger faults that displace this fault (see + :meth:`GeologicalModel.evaluate_feature_block_value`). The frame + is then the smooth frame of that block, with no jump across the + younger faults. A side given for this fault itself has no effect. + + Returns + ------- + np.ndarray + N values, NaN where the frame has no support + """ + block = check_block(block) + points = np.asarray(points, dtype=float) + return self.__getitem__(coordinate).evaluate_value( + points, ignore_regions=True, **block_kwargs(block) + ) + + @public_api(tier="provisional") + def evaluate_frame_gradient(self, points, coordinate: int = 0, *, block=None) -> np.ndarray: + """Evaluate the gradient of one coordinate of the fault frame. + + See :meth:`evaluate_frame_value` for the parameters. + + Returns + ------- + np.ndarray + Nx3 gradients, NaN where the frame has no support + """ + block = check_block(block) + points = np.asarray(points, dtype=float) + return self.__getitem__(coordinate).evaluate_gradient( + points, ignore_regions=True, **block_kwargs(block) + ) + + def _tip_ends(self) -> dict: + """Find the ends of gy and gz where the displacement profile is zero. + + Returns + ------- + dict of int to list of int + For coordinate 1 and 2, the ends (+1 and/or -1) where the profile + is zero at |g| >= 1. An empty list means no tip on that coordinate. + """ + if isinstance(self.faultfunction, FaultDisplacement): + return {c: list(e) for c, e in self.faultfunction.tip_ends.items()} + # A plain function of (gx, gy, gz): its tip is not known. + return {1: [], 2: []} + + def _evaluate_tip(self, points, block, gradient: bool): + """Evaluate the tip function and, if asked, its gradient.""" + points = np.asarray(points, dtype=float) + value = np.full(points.shape[0], np.inf) + grad = np.zeros(points.shape) + for coordinate, ends in self._tip_ends().items(): + if not ends: + continue + g = self.evaluate_frame_value(points, coordinate, block=block) + if len(ends) == 2: + part, sign = 1.0 - np.abs(g), -np.sign(g) + else: + part, sign = 1.0 - ends[0] * g, -ends[0] * np.ones_like(g) + if gradient: + dg = self.evaluate_frame_gradient(points, coordinate, block=block) + lower = (part < value) | np.isnan(part) + grad[lower] = sign[lower, None] * dg[lower] + value = np.where(np.isnan(part) | (part < value), part, value) + return value, grad + + @public_api(tier="provisional") + def evaluate_tip_value(self, points, *, block=None) -> np.ndarray: + """Evaluate the tip function of a finite fault. + + The function is ``min(1 - |gy|, 1 - |gz|)`` over the frame coordinates + whose displacement profile goes to zero at ``|g| = 1`` (``1 - g`` or + ``1 + g`` if the profile is zero at one end only). It is positive where + the fault displaces points, zero on the tip line and negative beyond. + Beyond the tip the displacement is exactly zero, so the fields of the + two fault blocks are equal there. + + Parameters + ---------- + points : np.ndarray + Nx3 locations, world coordinates + block : dict, optional + fault block of the faults that displace this fault (see + :meth:`evaluate_frame_value`) + + Returns + ------- + np.ndarray + N values; ``inf`` everywhere if the fault has no tip (its profile + is not zero at ``|g| = 1``, or the fault function is not a + :class:`FaultDisplacement`); NaN where the frame has no support + """ + return self._evaluate_tip(points, check_block(block), gradient=False)[0] + + @public_api(tier="provisional") + def evaluate_tip_gradient(self, points, *, block=None) -> np.ndarray: + """Evaluate the gradient of :meth:`evaluate_tip_value`. + + Returns + ------- + np.ndarray + Nx3 gradients of the frame coordinate that gives the minimum; + zero if the fault has no tip + """ + return self._evaluate_tip(points, check_block(block), gradient=True)[1] + + def apply_to_points( + self, points, reverse=False, precomputed_gx=None, *, block=None, restored_through=() + ): """ Unfault the array of points @@ -314,44 +534,43 @@ def apply_to_points(self, points, reverse=False, precomputed_gx=None): ---------- points - numpy array Nx3 precomputed_gx - optional pre-evaluated gx values (same points, avoids duplicate evaluation) + block : dict, optional + fault block: maps fault names to +1 (hanging wall), -1 (footwall) + or 0 (absent). If it names this fault, every point is restored as + if it were on that side (0: the points are not moved). A point on + the other side takes the smooth continuation of the displacement + profile of that side across the fault, so the restored field is + C2 across the fault surface (see + ``_fault_function.block_displacement``). The block + is also used to evaluate the frame of this fault, so a fault that + younger faults displace is evaluated in the block of those faults. + The call changes no state. + restored_through : sequence of FaultSegment, optional + faults whose restoration the points already have. The frame of + this fault was built in the space restored by the younger faults + that displace it, so it is evaluated at the points as they are, + without applying those faults a second time. Returns ------- """ logger.info(f'Applying fault {self.name} to points {points.shape}') + block = check_block(block) + if block_side(block, self.name) == 0: + return np.copy(points).astype(float) + kwargs = block_kwargs(block) + if restored_through: + kwargs["restored_through"] = tuple(restored_through) steps = self.steps newp = np.copy(points).astype(float) # evaluate fault function for all points # then define mask for only points affected by fault # gx may be supplied by caller to avoid re-evaluation (precomputed from region check) - if precomputed_gx is not None: - gx = precomputed_gx - gy = self.__getitem__(1).evaluate_value(newp) - gz = self.__getitem__(2).evaluate_value(newp) - elif use_threads: - with ThreadPoolExecutor(max_workers=8) as executor: - # all of these operations should be - # independent so just run as different threads - gx_future = executor.submit(self.__getitem__(0).evaluate_value, newp) - gy_future = executor.submit(self.__getitem__(1).evaluate_value, newp) - gz_future = executor.submit(self.__getitem__(2).evaluate_value, newp) - gx = gx_future.result() - gy = gy_future.result() - gz = gz_future.result() - else: - gx = self.__getitem__(0).evaluate_value(newp) - gy = self.__getitem__(1).evaluate_value(newp) - gz = self.__getitem__(2).evaluate_value(newp) - d = np.zeros(gx.shape) - mask = np.logical_and(~np.isnan(gx), ~np.isnan(gy)) - mask = np.logical_and(mask, ~np.isnan(gz)) - d[~mask] = 0 - gx_mask = np.zeros_like(mask, dtype=bool) - gx_mask[mask] = gx[mask] > 0 - d[gx_mask] = 1.0 - if self.faultfunction is not None: - d[mask] = self.faultfunction(gx[mask], gy[mask], gz[mask]) + gx, gy, gz = self._evaluate_frame( + newp, block, precomputed_gx=precomputed_gx, restored_through=restored_through + ) + d = self._displacement_fraction(gx, gy, gz, block) mask = np.abs(d) > 0.0 d *= self.displacement @@ -366,41 +585,22 @@ def apply_to_points(self, points, reverse=False, precomputed_gx=None): gx_m = gx[mask] gy_m = gy[mask] gz_m = gz[mask] - g = self.__getitem__(1).evaluate_gradient(newp[mask, :], ignore_regions=True) - elif use_threads: - with ThreadPoolExecutor(max_workers=8) as executor: - # all of these operations should be - # independent so just run as different threads - gx_future = executor.submit(self.__getitem__(0).evaluate_value, newp[mask, :]) - g_future = executor.submit(self.__getitem__(1).evaluate_gradient, newp[mask, :]) - gy_future = executor.submit(self.__getitem__(1).evaluate_value, newp[mask, :]) - gz_future = executor.submit(self.__getitem__(2).evaluate_value, newp[mask, :]) - gx_m = gx_future.result() - g = g_future.result() - gy_m = gy_future.result() - gz_m = gz_future.result() else: - gx_m = self.__getitem__(0).evaluate_value(newp[mask, :]) - gy_m = self.__getitem__(1).evaluate_value(newp[mask, :]) - gz_m = self.__getitem__(2).evaluate_value(newp[mask, :]) - g = self.__getitem__(1).evaluate_gradient(newp[mask, :], ignore_regions=True) + gx_m, gy_m, gz_m = self._evaluate_frame( + newp[mask, :], block, restored_through=restored_through + ) + g = self.__getitem__(1).evaluate_gradient(newp[mask, :], ignore_regions=True, **kwargs) gx, gy, gz = gx_m, gy_m, gz_m # alias for block below # # get the fault frame val/grad for the points # determine displacement magnitude, for constant displacement # hanging wall should be > 0 - d = np.zeros(gx.shape) mask2 = np.logical_and(~np.isnan(gx), ~np.isnan(gy)) mask2 = np.logical_and(mask2, ~np.isnan(gz)) - d[~mask2] = 0 - gx_mask2 = np.zeros_like(mask2, dtype=bool) - gx_mask2[mask2] = gx[mask2] > 0 - # d[~np.isnan(gx)][gx[~np.isnan(gx)]>0] = 1 - d[gx_mask2] = 1.0 - # d[mask2][gx[mask2] < 0] = 0. - # d[gx < 0] = 0. - if self.faultfunction is not None: - d[mask2] = self.faultfunction(gx[mask2], gy[mask2], gz[mask2]) + d = self._displacement_fraction(gx, gy, gz, block) d *= self.displacement + if reverse: + # forward (geological) movement: the opposite of the restoration + d *= -1.0 # normalise when length is >0 g_mag = np.zeros(g.shape[0]) g_mag[mask2] = np.linalg.norm(g[mask2], axis=1) @@ -416,7 +616,9 @@ def apply_to_points(self, points, reverse=False, precomputed_gx=None): return newp - def apply_to_vectors(self, vector: np.ndarray, scale_parameter: float = 1.0) -> np.ndarray: + def apply_to_vectors( + self, vector: np.ndarray, scale_parameter: float = 1.0, *, restored_through=() + ) -> np.ndarray: """Rotates the vector through the fault displacement field Parameters @@ -437,7 +639,8 @@ def apply_to_vectors(self, vector: np.ndarray, scale_parameter: float = 1.0) -> tetrahedron = regular_tetraherdron_for_points(vector[:, :3], scale_parameter) corners = np.einsum('ikj,ij->ik', tetrahedron - vector[:, None, :3], vector[:, 3:]) - tetrahedron = self.apply_to_points(tetrahedron.reshape(-1, 3)).reshape(-1, 4, 3) + kwargs = {"restored_through": tuple(restored_through)} if restored_through else {} + tetrahedron = self.apply_to_points(tetrahedron.reshape(-1, 3), **kwargs).reshape(-1, 4, 3) v = gradient_from_tetrahedron(tetrahedron, corners) return v diff --git a/LoopStructural/utils/_fault_block.py b/LoopStructural/utils/_fault_block.py new file mode 100644 index 000000000..626f9d013 --- /dev/null +++ b/LoopStructural/utils/_fault_block.py @@ -0,0 +1,191 @@ +"""Helpers for evaluating a field in one fault block. + +A fault block gives, for some faults, the side of the fault that every point +is taken to be on: + +* ``+1``: the hanging wall (the side where the fault frame coordinate gx > 0), +* ``-1``: the footwall (gx < 0), +* ``0``: the fault is absent: it moves no point. + +A fault that the block does not name keeps the side of each point. The block +is passed down the evaluation as an argument. No object is changed, so two +evaluations with different blocks can run at the same time. + +**The block on the other side of its fault.** A block field is also evaluated +at points on the other side of the fault. There the displacement of the fault +is the smooth continuation of the displacement profile of the block's own +side across gx = 0 (``BLOCK_EXTENSION = "smooth"``, see +``LoopStructural.modelling.features.fault._fault_function.block_displacement``): +the value, the slope and the curvature of the profile at the fault are kept, +so the block field is C2 across the fault surface and has no sharp change of +gradient there. The continuation has no geological meaning; a mesher needs +it only within a few cells of the fault. +""" + +from __future__ import annotations + +from collections.abc import Mapping + +import numpy as np + +BLOCK_SIDE_EPSILON = 1e-9 +"""Smallest absolute value of a forced fault frame coordinate. + +A point exactly on the fault (gx = 0) is moved to this distance on the +forced side, so that the displacement profile takes the value of that side. +""" + + +BLOCK_EXTENSION = "smooth" +"""How the displacement of a block continues on the other side of its fault. + +``"smooth"`` (default): the continuation of the profile of the block's side. +``"mirror"``: the mirror image, gx becomes ``side * |gx|`` (the first draft +and the fault benchmark study data). The mirror image has a kink where the +profile has a slope at the fault. It is kept only to compare with data made +with it. This is a module setting, read at each evaluation: do not change it +while other threads evaluate. +""" + +BLOCK_EXTENSION_EXACT = 0.25 +"""Distance from the fault, in units of gx, up to which the continuation is +the exact continuation of the profile.""" + +BLOCK_EXTENSION_LIMIT = 0.5 +"""Distance from the fault, in units of gx, beyond which the continuation is +constant. Between the two distances it is blended (C2), so the continuation +cannot grow without limit. The library profiles decay over |gx| = 1.""" + +BLOCK_EXTENSION_STEP = 1e-3 +"""Step in gx of the one-sided finite differences that give the slope and +the curvature at the fault of a profile that is not a polynomial.""" + + +def check_block(block) -> dict[str, int] | None: + """Check a fault block and return it as a dictionary of fault names. + + Parameters + ---------- + block : Mapping or None + Maps a fault (its name or the fault object) to +1, -1 or 0. + + Returns + ------- + dict of str to int, or None + The block with fault names as keys, or None if ``block`` is None. + + Raises + ------ + TypeError + If ``block`` is not a mapping. + ValueError + If a side is not +1, -1 or 0. + """ + if block is None: + return None + if not isinstance(block, Mapping): + raise TypeError("block must map fault names to +1, -1 or 0") + out = {} + for fault, side in block.items(): + name = fault if isinstance(fault, str) else getattr(fault, "name", None) + if not isinstance(name, str): + raise TypeError(f"block key {fault!r} is not a fault or a fault name") + if isinstance(side, bool) or side not in (-1, 0, 1): + raise ValueError(f"side of fault {name} must be +1, -1 or 0, not {side!r}") + out[name] = int(side) + return out + + +def block_side(block: Mapping[str, int] | None, name: str) -> int | None: + """Return the side of one fault in a block, or None if the block does not name it.""" + if not block: + return None + return block.get(name) + + +def force_side(values: np.ndarray, side: int | None) -> np.ndarray: + """Put fault frame values on one side of the fault. + + The value v becomes ``side * max(|v|, BLOCK_SIDE_EPSILON)``: the mirror + image of the field on the other side. The result is continuous across the + fault. NaN values (no support, or outside a region of the fault) stay NaN. + + This decides the side of a point (regions, abutting faults). The + displacement of a block on the other side of its fault does not use the + mirror image, see ``BLOCK_EXTENSION``. + + Parameters + ---------- + values : np.ndarray + Fault frame coordinate gx. + side : int or None + +1 or -1. Any other value returns the values unchanged. + + Returns + ------- + np.ndarray + A new array. + """ + out = np.array(values, dtype=float, copy=True) + if side not in (-1, 1): + return out + known = ~np.isnan(out) + out[known] = side * np.maximum(np.abs(out[known]), BLOCK_SIDE_EPSILON) + return out + + +def block_kwargs(block: Mapping[str, int] | None) -> dict: + """Keyword arguments that pass a block on, or none if there is no block. + + Callers use this so that an evaluation without a block calls the same + signatures as before. + """ + return {} if block is None else {"block": block} + + +def is_in(fault, faults) -> bool: + """True if ``fault`` is one of ``faults`` (by identity).""" + return any(fault is f for f in faults) + + +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 + 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. + + Parameters + ---------- + points : np.ndarray + Nx3 locations + faults : list of FaultSegment + faults in the order to apply them + reverse : bool + move the points forward instead of restoring them + block : dict, optional + checked fault block + restored_through : sequence of FaultSegment + faults whose restoration the points already have; they are skipped + + Returns + ------- + np.ndarray + the restored points + """ + done = list(restored_through) + for fault in faults: + if is_in(fault, done): + continue + # Pass only the keywords that are needed, so a fault-like object with + # the plain apply_to_points(points) signature still works. + kwargs = block_kwargs(block) + if reverse: + kwargs["reverse"] = True + if done: + kwargs["restored_through"] = tuple(done) + points = fault.apply_to_points(points, **kwargs) + done.append(fault) + return points diff --git a/LoopStructural/utils/regions.py b/LoopStructural/utils/regions.py index 7933fd011..44af193cb 100644 --- a/LoopStructural/utils/regions.py +++ b/LoopStructural/utils/regions.py @@ -2,6 +2,8 @@ import numpy as np +from ._fault_block import block_kwargs, block_side, force_side + class BaseRegion(ABC): @abstractmethod @@ -13,8 +15,12 @@ def __init__(self, feature, vector=None, point=None): self.parent = None @abstractmethod - def __call__(self, xyz) -> np.ndarray: - """Evaluate the region based on the input coordinates.""" + def __call__(self, xyz, *, block=None) -> np.ndarray: + """Evaluate the region based on the input coordinates. + + ``block`` is a fault block (see ``LoopStructural.utils._fault_block``); + a region that depends on a faulted feature evaluates it in that block. + """ class RegionEverywhere(BaseRegion): @@ -22,7 +28,7 @@ def __init__(self): super().__init__() self.type = "RegionEverywhere" - def __call__(self, xyz): + def __call__(self, xyz, *, block=None): return np.ones(xyz.shape[0], dtype="bool") @@ -31,7 +37,7 @@ def __init__(self, function): super().__init__() self.function = function - def __call__(self, xyz): + def __call__(self, xyz, *, block=None): return self.function(xyz) class BaseSignRegion(BaseRegion): @@ -45,8 +51,13 @@ def __init__(self, feature, vector=None, point=None): self.name = 'PositiveRegion' self.parent = feature - def _calculate_value_and_distance(self, xyz, precomputed_val=None)-> tuple[np.ndarray, np.ndarray]: - val = precomputed_val if precomputed_val is not None else self.feature.evaluate_value(xyz) + def _calculate_value_and_distance( + self, xyz, precomputed_val=None, block=None + ) -> tuple[np.ndarray, np.ndarray]: + if precomputed_val is not None: + val = precomputed_val + else: + val = self.feature.evaluate_value(xyz, **block_kwargs(block)) # find a point on/near 0 isosurface — compute once and cache on self if self.point is None: mask = np.zeros(xyz.shape[0], dtype="bool") @@ -65,6 +76,9 @@ def _calculate_value_and_distance(self, xyz, precomputed_val=None)-> tuple[np.nd distance = np.einsum( "ij,j->i", centre[None, :] - xyz, average_gradient.reshape(-1, 3)[0, :] ) + # Where the feature has no support the distance decides the side, so a + # fault block that fixes the side of this fault fixes it here too. + distance = force_side(distance, block_side(block, getattr(self.feature, "name", None))) return val, distance @@ -79,8 +93,10 @@ def __init__(self, feature, vector=None, point=None): self.name = 'PositiveRegion' self.parent = feature - def __call__(self, xyz, precomputed_val=None) -> np.ndarray: - val, distance = self._calculate_value_and_distance(xyz, precomputed_val=precomputed_val) + def __call__(self, xyz, precomputed_val=None, *, block=None) -> np.ndarray: + val, distance = self._calculate_value_and_distance( + xyz, precomputed_val=precomputed_val, block=block + ) return np.logical_or( np.logical_and(~np.isnan(val), val > 0), np.logical_and(np.isnan(val), distance > 0), @@ -98,8 +114,10 @@ def __init__(self, feature, vector=None, point=None): self.name = 'NegativeRegion' self.parent = feature - def __call__(self, xyz, precomputed_val=None) -> np.ndarray: - val, distance = self._calculate_value_and_distance(xyz, precomputed_val=precomputed_val) + def __call__(self, xyz, precomputed_val=None, *, block=None) -> np.ndarray: + val, distance = self._calculate_value_and_distance( + xyz, precomputed_val=precomputed_val, block=block + ) return np.logical_or( np.logical_and(~np.isnan(val), val < 0), np.logical_and(np.isnan(val), distance < 0), diff --git a/packages/loop_common/src/loop_common/geometry/_structured_grid_3d.py b/packages/loop_common/src/loop_common/geometry/_structured_grid_3d.py index 90576e4cd..ab5ea4301 100644 --- a/packages/loop_common/src/loop_common/geometry/_structured_grid_3d.py +++ b/packages/loop_common/src/loop_common/geometry/_structured_grid_3d.py @@ -235,19 +235,25 @@ def position_to_cell_index(self, pos: np.ndarray) -> tuple[np.ndarray, np.ndarra outside the grid is (0, 0, 0): use the mask, not the index, to detect them. """ pos = self.check_position(pos) + # Read the geometry once: each property is computed on access. + origin = self.origin + ncells = self.nsteps_cells inside = self.inside(pos) cell_indexes = np.zeros((pos.shape[0], 3), dtype=int) - for axis in range(3): - cell = np.floor((pos[inside, axis] - self.origin[axis]) / self.step_vector[axis]) - cell_indexes[inside, axis] = np.clip(cell.astype(int), 0, self.nsteps_cells[axis] - 1) + cell = np.floor((pos[inside] - origin) / self.step_vector) + cell_indexes[inside] = np.clip(cell.astype(int), 0, ncells - 1) return cell_indexes, inside def inside(self, pos: np.ndarray) -> np.ndarray: """Boolean mask of the points inside the grid, boundary included (to a small tolerance).""" pos = self.check_position(pos) - extent = np.maximum(np.abs(self.maximum - self.origin), 1.0) + return self._inside(pos, self.origin, self.maximum) + + @staticmethod + def _inside(pos: np.ndarray, origin: np.ndarray, maximum: np.ndarray) -> np.ndarray: + extent = np.maximum(np.abs(maximum - origin), 1.0) tol = np.finfo(float).eps * 32.0 * extent - return np.all((pos >= (self.origin - tol)) & (pos <= (self.maximum + tol)), axis=1) + return np.all((pos >= (origin - tol)) & (pos <= (maximum + tol)), axis=1) def check_position(self, pos: np.ndarray) -> np.ndarray: if len(pos.shape) == 1: diff --git a/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py b/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py index b0c4edf50..76235d22b 100644 --- a/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py +++ b/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py @@ -1104,12 +1104,51 @@ def _solve_with_cg( solver_kwargs: dict, timing: dict, x0: np.ndarray | None = None, + position_stop=None, ) -> bool: + # position_stop is passed only when it is set, so that the call is + # unchanged without a position tolerance + extra = {} if position_stop is None else {"position_stop": position_stop} self.c, ok = _solver_strategy.solve_with_cg( - A, b, tol, solver_kwargs, timing, logger, x0=x0 + A, b, tol, solver_kwargs, timing, logger, x0=x0, **extra ) return ok + def _position_error_function(self, scaling_matrix=None): + """The position error that a change of the solver unknowns means. + + Returns ``position_error(x, dx)`` for + ``_solver_strategy.cg_to_position_tolerance``: the largest change of + the field at a degree of freedom, divided by the median norm of the + gradient of the field at the support nodes. ``x`` and ``dx`` are in + the unknowns of the solver (``c = scaling_matrix @ x``). The support + works in the local frame, which is the world frame moved and rotated + but not scaled, so the result is in the length units of the model. + + The gradient at the nodes costs more than a cg iteration. It is + evaluated at the first call and then at every fifth call (every 50 + iterations); the solver calls this only when the residual has + dropped by 1e-6, where the gradient hardly changes any more. + """ + scale = None if scaling_matrix is None else np.asarray(scaling_matrix.diagonal()) + nodes = self.support.nodes + state = {"calls": 0, "gradient": float("nan")} + + def position_error(x: np.ndarray, dx: np.ndarray) -> float: + if state["calls"] % 5 == 0: + c = x if scale is None else scale * x + gradient = np.asarray(self.support.evaluate_gradient(nodes, c)) + norm = np.linalg.norm(gradient, axis=1) + norm = norm[np.isfinite(norm) & (norm > 0)] + state["gradient"] = float(np.median(norm)) if norm.size else float("nan") + state["calls"] += 1 + if not state["gradient"] > 0: + return float("inf") + dc = dx if scale is None else scale * dx + return float(np.max(np.abs(dc)) / state["gradient"]) + + return position_error + def _use_fused_cg_regularisation(self, solver_choice) -> bool: """Whether the fused-kernel matrix-free-regularisation CG fast path (``_solve_with_cg_fused_regularisation``) should be used for this @@ -1141,6 +1180,7 @@ def _solve_with_cg_fused_regularisation( add_ridge_regularisation: bool | None = None, ridge_factor: float | None = None, x0: np.ndarray | None = None, + position_stop=None, ) -> bool: """CG fast path for ``regularisation_matrix_free=True``: assemble the normal-equations system ``(A_data^T A_data + R_reg^T R_reg) x = @@ -1213,8 +1253,9 @@ def matvec(x): ) timing["preprocess_seconds"] = perf_counter() - preprocess_started + extra = {} if position_stop is None else {"position_stop": position_stop} self.c, ok = _solver_strategy.solve_with_cg_normal_equations( - normal_operator, rhs, tol, solver_kwargs, timing, logger, x0=x0 + normal_operator, rhs, tol, solver_kwargs, timing, logger, x0=x0, **extra ) return ok @@ -1294,6 +1335,7 @@ def solve_system( solver: Callable[[sparse.csr_matrix, np.ndarray], np.ndarray] | str | None = None, tol: float | None = None, solver_kwargs: dict | None = None, + position_tolerance: float | None = None, ) -> bool: """ Main entry point to run the solver and update the node value @@ -1304,6 +1346,52 @@ def solve_system( ---------- solver : string/callable solver 'cg' conjugate gradient, 'lsmr' or callable function + tol : float, optional + Absolute tolerance of the residual of the solver (``atol`` of cg, + ``btol`` of lsmr). It has no length meaning. Not used by cg when + ``position_tolerance`` is given. + position_tolerance : float, optional + Only for ``solver="cg"``. How far the isosurfaces of the solved + field may be from the isosurfaces of the fully converged field, + as a length in the units of the model (the support is not + rescaled). For example 1.0 for 1 m in a model in metres. None, + the default, keeps the stop on the residual (``tol``, ``rtol``). + + The solve stops when the estimated position error is below the + tolerance. The position error is the error of the field value + divided by the gradient norm of the field. The estimate takes + the size of the error from the residual and the smallest Ritz + value of the cg steps (``|r| / theta``, a bound of the 2-norm of + the error once the Ritz value has converged), its distribution + over the degrees of freedom from the change of the field over + the last 50 iterations, and the median gradient norm at the + support nodes. See + ``_solver_strategy.cg_to_position_tolerance``. + + **What is guaranteed:** nothing in the strict sense; it is an + estimate. Measured on five models (foliations, fault frames and + fold frames; FDI, PLI and DFI; boxes of 1 unit to 10 km), for + tolerances of 1e-3 to 1e-5 of the box: the largest position + error at a node, with the gradient at that node, was between + 0.00006 and 0.19 times the tolerance. So the solve is usually + more exact than asked, by 5 to 1000 times. On three synthetic + systems where cg stagnates it was at most 0.13 times the + tolerance, where a stop on the change of the solution alone was + up to 1000 times over the tolerance. + + **What it does not cover:** the error of the converged field + against the geology (the discretisation and the data); places + where the gradient is much lower than the median, where the + position of an isosurface is not well defined; an error that is + concentrated at a few nodes while the recent change is spread + out. The stop is not tested before the residual has dropped by + 1e-6. With this option the cg stop ignores ``tol`` and the + ``rtol`` and ``atol`` of ``solver_kwargs``, and a + preconditioner ``M`` is refused. A warning is logged if the + solve reaches a relative residual of 1e-13 or ``maxiter`` + first. The timing of the solve (``get_last_solve_timing``) has + ``cg_iterations``, ``cg_stop``, ``position_error_estimate`` and + ``position_error_change``. solver_kwargs kwargs for solver check scipy documentation for more information. These keys are used by the interpolator and not sent to the solver: @@ -1326,6 +1414,15 @@ def solve_system( """ solver_choice = self._normalise_solver_choice(solver) + if position_tolerance is not None: + position_tolerance = float(position_tolerance) + if not position_tolerance > 0: + raise ValueError("position_tolerance must be a positive length") + if solver_choice != "cg": + logger.warning( + "position_tolerance is used only by solver='cg'; it is ignored here" + ) + position_tolerance = None # A native setup builds no sparse rows. A matrix solver needs them. # Check this before _pre_solve, so that the old field stays. if getattr(self, "_native_setup", False) and solver_choice != "native": @@ -1412,8 +1509,14 @@ def solve_system( # every other solver/case below). See # `_solve_with_cg_fused_regularisation` / `FiniteDifferenceInterpolator. # _build_fused_cg_regularisation_operator`. + position_kwargs = {} + if position_tolerance is not None: + position_kwargs["position_stop"] = ( + position_tolerance, + self._position_error_function(), + ) self.up_to_date = self._solve_with_cg_fused_regularisation( - tol, solver_kwargs, timing, x0=x0, **ridge_kwargs + tol, solver_kwargs, timing, x0=x0, **ridge_kwargs, **position_kwargs ) else: A, b = self._assemble_main_system(timing) @@ -1425,7 +1528,15 @@ def solve_system( if callable(solver_choice): self.up_to_date = self._solve_with_callable(solver_choice, A, b, timing) elif solver_choice == "cg": - self.up_to_date = self._solve_with_cg(A, b, tol, solver_kwargs, timing, x0=x0) + position_kwargs = {} + if position_tolerance is not None: + position_kwargs["position_stop"] = ( + position_tolerance, + self._position_error_function(scaling_matrix), + ) + self.up_to_date = self._solve_with_cg( + A, b, tol, solver_kwargs, timing, x0=x0, **position_kwargs + ) elif solver_choice == "lsmr": self.up_to_date = self._solve_with_lsmr( A, b, tol, solver_kwargs, timing, x0=x0 diff --git a/packages/loop_interpolation/src/loop_interpolation/_solver_strategy.py b/packages/loop_interpolation/src/loop_interpolation/_solver_strategy.py index a9f447f17..46df6365d 100644 --- a/packages/loop_interpolation/src/loop_interpolation/_solver_strategy.py +++ b/packages/loop_interpolation/src/loop_interpolation/_solver_strategy.py @@ -14,6 +14,19 @@ # scipy's default rtol (1e-5) stops P2 solves up to 0.6 from the converged field DEFAULT_CG_RTOL = 1e-8 +# The stop rule of a CG solve with a position tolerance (cg_to_position_tolerance). +# The stop is tested every CG_POSITION_CHECK iterations, with the change of the +# solution over the last CG_POSITION_DELAY iterations. +CG_POSITION_DELAY = 50 +CG_POSITION_CHECK = 10 +# CG on these systems often starts with a plateau: the solution hardly moves +# for hundreds of iterations and the smallest Ritz value is still far above +# the smallest eigenvalue. The stop is not tested before the residual has +# dropped by this factor. +CG_POSITION_GUARD_RTOL = 1e-6 +# Nothing more can be gained below this relative residual. +CG_POSITION_FLOOR_RTOL = 1e-13 + def resolve_solver_choice( solver: Callable[[sparse.csr_matrix, np.ndarray], np.ndarray] | str | None, logger @@ -48,6 +61,226 @@ def solve_with_callable( return np.asarray(c), True +def _set_cg_tolerances(solver_kwargs: dict, tol: float | None) -> None: + """Fill in the CG stopping tolerances that the caller did not give. + + scipy's cg stops at ``max(rtol * |b|, atol)``. A ``tol`` sets ``atol``; + without an ``rtol`` scipy would use its own default 1e-5, which then + decides the stop and makes ``tol`` meaningless. So ``rtol`` defaults to + ``DEFAULT_CG_RTOL`` in both cases. + """ + if tol is not None and "atol" not in solver_kwargs: + solver_kwargs["atol"] = tol + if "rtol" not in solver_kwargs and (tol is not None or "atol" not in solver_kwargs): + solver_kwargs["rtol"] = DEFAULT_CG_RTOL + + +def _smallest_ritz_value(diagonal: list, off_diagonal: list) -> float: + """Smallest eigenvalue of the Lanczos matrix of the CG steps so far.""" + from scipy.linalg import eigvalsh_tridiagonal + + if len(diagonal) == 1: + return float(diagonal[0]) + return float( + eigvalsh_tridiagonal( + np.asarray(diagonal), np.asarray(off_diagonal), select="i", select_range=(0, 0) + )[0] + ) + + +def cg_to_position_tolerance( + N, + rhs: np.ndarray, + position_tolerance: float, + position_error: Callable[[np.ndarray, np.ndarray], float], + x0: np.ndarray | None = None, + maxiter: int | None = None, + callback: Callable[[np.ndarray], None] | None = None, +) -> tuple[np.ndarray, int, dict]: + """Conjugate gradients on ``N x = rhs`` that stop on an estimate of the + position error of the isosurfaces. + + The iteration is the one of ``scipy.sparse.linalg.cg`` without a + preconditioner (the same operations in the same order), so the iterates + are the iterates of scipy. Only the stop differs. Every + ``CG_POSITION_CHECK`` iterations, once the residual is below + ``CG_POSITION_GUARD_RTOL * |rhs|``, the solve stops if:: + + max(1, bound / |change|) * position_error(x_k, change) <= position_tolerance + + change = x_k - x_(k - CG_POSITION_DELAY) + bound = |r_k| / theta_k + + Two estimates of the error ``x - x_k`` are combined: + + * ``change`` is the delay estimate of the error: the vector form of the + estimate of Strakos and Tichy (2002) for the A-norm of the error, from + the same CG steps. It is a **lower** estimate and it is far too small + while CG stagnates (measured: up to 1000 times). + * ``bound`` is the classical bound ``|x - x_k| <= |r_k| / lambda_min`` + of the 2-norm of the error, with the smallest eigenvalue replaced by + ``theta_k``, the smallest Ritz value of the Lanczos matrix that the CG + coefficients define (Golub and Meurant; Meurant and Tichy 2019). + ``theta_k`` comes down to ``lambda_min`` from above, so ``bound`` is + an upper bound only once ``theta_k`` has converged; before that it is + too small by the factor ``theta_k / lambda_min``. + + The bound gives a size but no place. The rule assumes that the error is + spread over the unknowns like the recent change, and scales the change + up to the size of the bound. This assumption has no proof. So the result + is an **estimate, not a guarantee** (the measured cases are given in + ``DiscreteInterpolator.solve_system``). + + Parameters + ---------- + N + Symmetric positive definite matrix or ``LinearOperator``. + rhs + Right-hand side. + position_tolerance + Requested position error, in the length units of ``position_error``. + position_error + ``position_error(x, dx)``: the position error, as a length, that a + change ``dx`` of the solution ``x`` means. It must be a norm of + ``dx`` (it is scaled linearly). ``inf`` if it has no meaning (for + example a field without a gradient). + x0, maxiter, callback + As in ``scipy.sparse.linalg.cg``. + + Returns + ------- + x, info, report + ``info`` is 0 when a stop rule was met and ``maxiter`` otherwise, as + in scipy. ``report`` has ``iterations``, ``relative_residual``, + ``position_error_estimate`` (the last tested estimate; NaN if none + was tested), ``position_error_change`` (the lower estimate in it), + ``smallest_ritz_value`` and ``stop``: ``"position"``, ``"residual"`` + (the floor ``CG_POSITION_FLOOR_RTOL`` was reached first), + ``"zero_rhs"`` or ``"maxiter"``. + """ + rhs = np.asarray(rhs, dtype=float).reshape(-1) + n = rhs.shape[0] + matvec = N.matvec if hasattr(N, "matvec") else (lambda v: N @ v) + x = np.zeros(n) if x0 is None else np.array(x0, dtype=float).reshape(-1) + report = { + "iterations": 0, + "relative_residual": 0.0, + "position_error_estimate": float("nan"), + "position_error_change": float("nan"), + "smallest_ritz_value": float("nan"), + "stop": "zero_rhs", + } + bnrm2 = np.linalg.norm(rhs) + if bnrm2 == 0: + return rhs.copy(), 0, report + if maxiter is None: + maxiter = n * 10 + r = rhs - np.asarray(matvec(x)).reshape(-1) if x.any() else rhs.copy() + guard = CG_POSITION_GUARD_RTOL * bnrm2 + floor = CG_POSITION_FLOOR_RTOL * bnrm2 + lag = CG_POSITION_DELAY // CG_POSITION_CHECK + # x at the last checks: history[0] is CG_POSITION_DELAY iterations old + # when it holds lag entries + history: list[np.ndarray] = [x.copy()] + # the Lanczos matrix of the CG steps (Golub and Van Loan, section 11.3) + diagonal: list[float] = [] + off_diagonal: list[float] = [] + rho_prev, p, alpha_prev = None, None, None + info, stop = maxiter, "maxiter" + iteration = 0 + for iteration in range(maxiter): + rnorm = np.linalg.norm(r) + if rnorm < floor: + info, stop = 0, "residual" + break + if iteration > 0 and iteration % CG_POSITION_CHECK == 0: + if len(history) == lag and rnorm < guard: + change = x - history[0] + lower = float(position_error(x, change)) + theta = _smallest_ritz_value(diagonal, off_diagonal) + change_norm = float(np.linalg.norm(change)) + report["position_error_change"] = lower + report["smallest_ritz_value"] = theta + if theta > 0 and change_norm > 0: + estimate = max(1.0, float(rnorm) / theta / change_norm) * lower + report["position_error_estimate"] = estimate + if estimate <= position_tolerance: + info, stop = 0, "position" + break + history.append(x.copy()) + del history[:-lag] + rho_cur = np.dot(r, r) + if iteration > 0: + beta = rho_cur / rho_prev + off_diagonal.append(float(np.sqrt(beta) / alpha_prev)) + p *= beta + p += r + else: + beta = 0.0 + p = r.copy() + q = np.asarray(matvec(p)).reshape(-1) + alpha = rho_cur / np.dot(p, q) + diagonal.append(float(1.0 / alpha + (beta / alpha_prev if iteration > 0 else 0.0))) + x += alpha * p + r -= alpha * q + rho_prev, alpha_prev = rho_cur, alpha + if callback: + callback(x) + else: + iteration = maxiter + report["iterations"] = iteration + report["relative_residual"] = float(np.linalg.norm(r) / bnrm2) + report["stop"] = stop + return x, info, report + + +def _solve_cg_position(N, rhs, position_stop, solver_kwargs, timing, logger, x0): + """Run cg_to_position_tolerance for solve_with_cg(_normal_equations).""" + from time import perf_counter + + position_tolerance, position_error = position_stop + if solver_kwargs.get("M") is not None: + raise ValueError("position_tolerance does not support a cg preconditioner (M)") + ignored = sorted(k for k in solver_kwargs if k not in ("maxiter", "callback", "M")) + if ignored: + logger.warning( + "position_tolerance sets the cg stop rule; these solver_kwargs are ignored: %s", + ignored, + ) + logger.info(f"cg position tolerance: {position_tolerance}") + solve_step_started = perf_counter() + x, info, report = cg_to_position_tolerance( + N, + rhs, + position_tolerance, + position_error, + x0=x0, + maxiter=solver_kwargs.get("maxiter"), + callback=solver_kwargs.get("callback"), + ) + timing["solve_seconds"] = perf_counter() - solve_step_started + timing["cg_iterations"] = report["iterations"] + timing["cg_stop"] = report["stop"] + timing["cg_relative_residual"] = report["relative_residual"] + timing["position_tolerance"] = float(position_tolerance) + timing["position_error_estimate"] = report["position_error_estimate"] + timing["position_error_change"] = report["position_error_change"] + if info > 0: + logger.warning( + "CG reached iteration limit (%s) and did not converge; using last iteration", + info, + ) + elif report["stop"] == "residual": + logger.warning( + "CG reached the relative residual %s before the position tolerance %s " + "(last estimate %s); using last iteration", + CG_POSITION_FLOOR_RTOL, + position_tolerance, + report["position_error_estimate"], + ) + return np.asarray(x), info == 0 + + def solve_with_cg( A: sparse.spmatrix, b: np.ndarray, @@ -56,14 +289,17 @@ def solve_with_cg( timing: dict, logger, x0: np.ndarray | None = None, + position_stop: tuple[float, Callable[[np.ndarray, np.ndarray], float]] | None = None, ) -> tuple[np.ndarray, bool]: from time import perf_counter logger.info("Solving using cg") - if ("atol" not in solver_kwargs or "rtol" not in solver_kwargs) and tol is not None: - solver_kwargs["atol"] = tol - elif tol is None and "rtol" not in solver_kwargs and "atol" not in solver_kwargs: - solver_kwargs["rtol"] = DEFAULT_CG_RTOL + if position_stop is not None: + # tol is not used: the position tolerance sets the stop + return _solve_cg_position( + A.T @ A, A.T @ b, position_stop, solver_kwargs, timing, logger, x0 + ) + _set_cg_tolerances(solver_kwargs, tol) logger.info(f"Solver kwargs: {solver_kwargs}") solve_step_started = perf_counter() @@ -85,6 +321,7 @@ def solve_with_cg_normal_equations( timing: dict, logger, x0: np.ndarray | None = None, + position_stop: tuple[float, Callable[[np.ndarray, np.ndarray], float]] | None = None, ) -> tuple[np.ndarray, bool]: """Solve an already-assembled normal-equations system ``N x = rhs`` with CG. @@ -97,10 +334,9 @@ def solve_with_cg_normal_equations( from time import perf_counter logger.info("Solving using cg (matrix-free fused regularisation normal equations)") - if ("atol" not in solver_kwargs or "rtol" not in solver_kwargs) and tol is not None: - solver_kwargs["atol"] = tol - elif tol is None and "rtol" not in solver_kwargs and "atol" not in solver_kwargs: - solver_kwargs["rtol"] = DEFAULT_CG_RTOL + if position_stop is not None: + return _solve_cg_position(N, rhs, position_stop, solver_kwargs, timing, logger, x0) + _set_cg_tolerances(solver_kwargs, tol) logger.info(f"Solver kwargs: {solver_kwargs}") solve_step_started = perf_counter() diff --git a/packages/loop_interpolation/tests/test_cg_position_tolerance.py b/packages/loop_interpolation/tests/test_cg_position_tolerance.py new file mode 100644 index 000000000..97be3b156 --- /dev/null +++ b/packages/loop_interpolation/tests/test_cg_position_tolerance.py @@ -0,0 +1,208 @@ +"""The cg stop on an estimate of the position error (position_tolerance).""" + +import logging + +import numpy as np +import pytest +from loop_interpolation import FiniteDifferenceInterpolator, StructuredGrid, _solver_strategy +from loop_interpolation._solver_strategy import ( + CG_POSITION_CHECK, + CG_POSITION_DELAY, + cg_to_position_tolerance, +) +from scipy import sparse +from scipy.sparse.linalg import cg + + +def _spd(n=400, seed=0, ridge=1e-6): + """A 1D bi-Laplacian plus a small ridge: cg stagnates, the solution is known. + + The change of the solution over 50 iterations is here up to 500 times + smaller than the error, so a stop on the change alone fails on it. + """ + lap = sparse.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(n, n), format="csr") + N = (lap.T @ lap + ridge * sparse.eye(n)).tocsr() + x = np.sin(np.linspace(0.0, 3.0, n)) + np.random.default_rng(seed).normal(0.0, 0.01, n) + return N, N @ x, x + + +def _never(x, dx): + return float("inf") + + +def test_iterates_are_those_of_scipy(): + N, rhs, _ = _spd() + for maxiter in (1, 7, 60, 135): + ours, info, report = cg_to_position_tolerance(N, rhs, 1.0, _never, maxiter=maxiter) + theirs, _ = cg(N, rhs, rtol=0.0, atol=0.0, maxiter=maxiter) + assert info == maxiter and report["stop"] == "maxiter" + assert report["iterations"] == maxiter + np.testing.assert_array_equal(ours, theirs) + + +def test_zero_right_hand_side(): + N, rhs, _ = _spd(50) + x, info, report = cg_to_position_tolerance(N, np.zeros_like(rhs), 1.0, _never) + assert info == 0 and report["stop"] == "zero_rhs" + assert np.all(x == 0.0) + + +def test_stops_on_the_position_estimate(): + N, rhs, exact = _spd() + gradient = 2.0 + calls = [] + + def position_error(x, dx): + calls.append(len(calls)) + return float(np.max(np.abs(dx)) / gradient) + + tolerance = 1e-4 + x, info, report = cg_to_position_tolerance(N, rhs, tolerance, position_error) + assert info == 0 and report["stop"] == "position" + assert report["position_error_estimate"] <= tolerance + # the estimate is the change scaled up, never less than the change + assert report["position_error_change"] <= report["position_error_estimate"] + assert report["smallest_ritz_value"] == pytest.approx(1e-6, rel=0.05) + assert report["iterations"] % CG_POSITION_CHECK == 0 + assert report["iterations"] >= CG_POSITION_DELAY + # the true position error is within the tolerance + assert np.max(np.abs(x - exact)) / gradient <= tolerance + # a tighter tolerance takes more iterations and is more accurate + x2, _, report2 = cg_to_position_tolerance(N, rhs, 1e-6, position_error) + assert report2["iterations"] > report["iterations"] + assert np.max(np.abs(x2 - exact)) < np.max(np.abs(x - exact)) + assert np.max(np.abs(x2 - exact)) / gradient <= 1e-6 + + +@pytest.mark.parametrize("ridge", [1e-6, 1e-9]) +@pytest.mark.parametrize("tolerance", [1e-2, 1e-4]) +def test_the_stop_holds_on_a_stagnating_system(ridge, tolerance): + """Where the change of the solution alone is 10 to 500 times too small.""" + N, rhs, exact = _spd(ridge=ridge) + fn = lambda x, dx: float(np.max(np.abs(dx))) # noqa: E731 + x, info, report = cg_to_position_tolerance(N, rhs, tolerance, fn, maxiter=40 * len(rhs)) + assert info == 0 and report["stop"] == "position" + assert np.max(np.abs(x - exact)) <= tolerance + + +def test_the_estimate_is_not_tested_before_the_residual_guard(): + N, rhs, _ = _spd() + seen = [] + + def position_error(x, dx): + seen.append(np.linalg.norm(rhs - N @ x) / np.linalg.norm(rhs)) + return 1e-30 # would stop at once + + _, info, report = cg_to_position_tolerance(N, rhs, 1e30, position_error) + assert info == 0 and report["stop"] == "position" + assert len(seen) == 1 + assert seen[0] < _solver_strategy.CG_POSITION_GUARD_RTOL * (1 + 1e-6) + + +def test_stops_at_the_residual_floor_without_an_estimate(): + N, rhs, exact = _spd(60) + x, info, report = cg_to_position_tolerance(N, rhs, 1e-30, _never) + assert info == 0 and report["stop"] == "residual" + assert report["relative_residual"] < 1e-12 + np.testing.assert_allclose(x, exact, atol=1e-6) + + +def test_repeatable(): + N, rhs, _ = _spd() + fn = lambda x, dx: float(np.max(np.abs(dx))) # noqa: E731 + a, _, _ = cg_to_position_tolerance(N, rhs, 1e-5, fn) + b, _, _ = cg_to_position_tolerance(N, rhs, 1e-5, fn) + np.testing.assert_array_equal(a, b) + + +def _interpolator(scale=1.0, matrix_free=False): + """A dipping plane with noise in a box of side 20 * scale.""" + grid = StructuredGrid( + origin=np.zeros(3), nsteps=np.array([21, 21, 21]), step_vector=np.full(3, scale) + ) + interp = FiniteDifferenceInterpolator(grid) + rng = np.random.default_rng(3) + xyz = rng.uniform(2.0, 18.0, size=(60, 3)) * scale + values = xyz[:, 2] + 0.3 * xyz[:, 0] + scale * np.sin(xyz[:, 1] / scale) + interp.set_value_constraints(np.column_stack([xyz, values, np.ones(len(xyz))])) + if matrix_free: + interp.apply_scaling_matrix = False + interp.setup_interpolator(regularisation_matrix_free=matrix_free) + return interp + + +def _position_error(interp, reference): + nodes = interp.support.nodes + gradient = np.linalg.norm(interp.support.evaluate_gradient(nodes, reference), axis=1) + return np.max(np.abs(interp.c - reference) / gradient) + + +@pytest.mark.parametrize("scale", [1.0, 500.0]) +@pytest.mark.parametrize("matrix_free", [False, True]) +def test_interpolator_position_tolerance(scale, matrix_free): + """The position error is within the tolerance, in the units of the support.""" + reference = _interpolator(scale, matrix_free) + assert reference.solve_system(solver="cg", solver_kwargs={"rtol": 1e-13, "atol": 0.0}) + extent = 20.0 * scale + errors = [] + for fraction in (1e-3, 1e-5): + tolerance = fraction * extent + interp = _interpolator(scale, matrix_free) + assert interp.solve_system(solver="cg", position_tolerance=tolerance) + timing = interp.get_last_solve_timing() + assert timing["cg_stop"] == "position" + assert timing["position_tolerance"] == tolerance + assert timing["position_error_estimate"] <= tolerance + error = _position_error(interp, reference.c) + assert error <= tolerance + errors.append(error / extent) + assert errors[1] < errors[0] + + +def test_position_tolerance_does_not_depend_on_the_length_unit(): + """The same model in metres and in kilometres stops at the same iteration.""" + iterations = [] + for scale in (1.0, 1000.0): + interp = _interpolator(scale) + interp.solve_system(solver="cg", position_tolerance=1e-4 * 20.0 * scale) + iterations.append(interp.get_last_solve_timing()["cg_iterations"]) + assert abs(iterations[0] - iterations[1]) <= CG_POSITION_CHECK + + +def test_without_a_position_tolerance_nothing_changes(): + a = _interpolator() + a.solve_system(solver="cg", tol=1e-9) + b = _interpolator() + b.solve_system(solver="cg", tol=1e-9, position_tolerance=None) + np.testing.assert_array_equal(a.c, b.c) + assert "cg_stop" not in a.get_last_solve_timing() + assert "cg_stop" not in b.get_last_solve_timing() + + +def test_tol_and_rtol_do_not_stop_a_position_solve(caplog): + reference = _interpolator() + reference.solve_system(solver="cg", position_tolerance=1e-3) + interp = _interpolator() + with caplog.at_level(logging.WARNING): + # this tol and rtol alone would stop cg after a few iterations + interp.solve_system( + solver="cg", tol=1e3, solver_kwargs={"rtol": 0.5}, position_tolerance=1e-3 + ) + np.testing.assert_array_equal(interp.c, reference.c) + assert "ignored" in caplog.text + + +def test_position_tolerance_must_be_positive(): + interp = _interpolator() + with pytest.raises(ValueError, match="position_tolerance"): + interp.solve_system(solver="cg", position_tolerance=0.0) + + +def test_other_solvers_ignore_the_position_tolerance(caplog): + a = _interpolator() + a.solve_system(solver="lsmr", tol=1e-10) + b = _interpolator() + with caplog.at_level(logging.WARNING): + b.solve_system(solver="lsmr", tol=1e-10, position_tolerance=1e-3) + np.testing.assert_array_equal(a.c, b.c) + assert "position_tolerance is used only by solver='cg'" in caplog.text diff --git a/packages/loop_interpolation/tests/test_cg_tolerances.py b/packages/loop_interpolation/tests/test_cg_tolerances.py new file mode 100644 index 000000000..c38b3f1df --- /dev/null +++ b/packages/loop_interpolation/tests/test_cg_tolerances.py @@ -0,0 +1,28 @@ +"""The CG stopping tolerances that solve_with_cg fills in.""" + +import pytest + +from loop_interpolation import _solver_strategy +from loop_interpolation._solver_strategy import DEFAULT_CG_RTOL, _set_cg_tolerances + + +@pytest.mark.parametrize( + "given, tol, expected", + [ + # A tol without an rtol: scipy's own rtol (1e-5) must not decide the stop. + ({}, 1e-10, {"atol": 1e-10, "rtol": DEFAULT_CG_RTOL}), + ({}, None, {"rtol": DEFAULT_CG_RTOL}), + ({"rtol": 1e-3}, 1e-10, {"atol": 1e-10, "rtol": 1e-3}), + ({"atol": 1e-6}, 1e-10, {"atol": 1e-6, "rtol": DEFAULT_CG_RTOL}), + ({"atol": 1e-6}, None, {"atol": 1e-6}), + ({"atol": 1e-6, "rtol": 1e-4}, 1e-10, {"atol": 1e-6, "rtol": 1e-4}), + ], +) +def test_cg_tolerances(given, tol, expected): + kwargs = dict(given) + _set_cg_tolerances(kwargs, tol) + assert kwargs == expected + + +def test_solve_with_cg_uses_them(): + assert _solver_strategy.solve_with_cg.__code__.co_names.count("_set_cg_tolerances") == 1 diff --git a/tests/fixtures/fault_models.py b/tests/fixtures/fault_models.py new file mode 100644 index 000000000..91db3fe7a --- /dev/null +++ b/tests/fixtures/fault_models.py @@ -0,0 +1,115 @@ +"""Small faulted models in the unit cube, for the fault block and kinematics tests. + +The stratigraphic data are made the way LoopStructural evaluates a faulted +feature: each random present-day point is restored through the faults, and +the analytic field (z) of the restored point is its value. +""" + +import numpy as np +import pandas as pd + +from LoopStructural.modelling.features.fault._fault_function import ( + Composite, + FaultDisplacement, + Ones, + Zeros, +) + +COLUMNS = ["X", "Y", "Z", "val", "nx", "ny", "nz", "coord", "feature_name"] + + +def dip_vectors(dip_deg, dip_azimuth_deg): + """Unit normal (up), down-dip and strike vectors of a plane.""" + d, a = np.radians(dip_deg), np.radians(dip_azimuth_deg) + horizontal = np.array([np.sin(a), np.cos(a), 0.0]) + down_dip = np.cos(d) * horizontal + np.array([0.0, 0.0, -np.sin(d)]) + normal = np.sin(d) * horizontal + np.array([0.0, 0.0, np.cos(d)]) + return normal, down_dip, np.cross(normal, down_dip) + + +def constant_profile(): + """The hanging wall moves rigidly, the footwall does not move.""" + return FaultDisplacement(gx=Composite(Ones(), Zeros()), gy=Ones(), gz=Ones(), scale=1.0) + + +def plane_points(center, dip, dip_azimuth, n=11, half=0.9): + normal, down_dip, strike = dip_vectors(dip, dip_azimuth) + u, v = np.meshgrid(np.linspace(-1, 1, n), np.linspace(-1, 1, n), indexing="ij") + pts = ( + np.asarray(center) + + u.ravel()[:, None] * half * strike + + v.ravel()[:, None] * half * down_dip + ) + return pts, normal, down_dip + + +def add_fault(model, name, center, dip, dip_azimuth, displacement, *, points=None, + profile=None, axes=(4.0, 4.0, 4.0), faults=None, steps=1, nelements=4000): + plane, normal, down_dip = plane_points(center, dip, dip_azimuth) + if points is None: + points = plane + inside = np.all((points > -0.1) & (points < 1.1), axis=1) + points = points[inside] + df = pd.DataFrame( + { + "X": points[:, 0], "Y": points[:, 1], "Z": points[:, 2], "val": 0.0, + "nx": normal[0], "ny": normal[1], "nz": normal[2], "coord": 0, + "feature_name": name, + } + )[COLUMNS] + fault = model.create_and_add_fault( + name, + displacement, + data=df, + fault_slip_vector=-down_dip, # restoration direction: normal fault + fault_normal_vector=normal, + fault_center=np.asarray(center, dtype=float), + major_axis=axes[0], + intermediate_axis=axes[1], + minor_axis=axes[2], + faultfunction=profile if profile is not None else constant_profile(), + faults=faults or [], + nelements=nelements, + fault_buffer=0.5, + ) + fault.steps = steps + return fault + + +def add_layers(model, faults_oldest_first, n=800, seed=7, nelements=8000): + rng = np.random.default_rng(seed) + pts = rng.uniform(0.0, 1.0, size=(n, 3)) + restored = pts.copy() + for f in reversed(faults_oldest_first): + restored = f.apply_to_points(restored) + df = pd.DataFrame( + { + "X": pts[:, 0], "Y": pts[:, 1], "Z": pts[:, 2], "val": restored[:, 2], + "nx": np.nan, "ny": np.nan, "nz": np.nan, "coord": np.nan, "feature_name": "strat", + } + )[COLUMNS] + return model.create_and_add_foliation( + "strat", data=df, faults=faults_oldest_first, nelements=nelements, buffer=0.3 + ) + + +def interior_points(n=400, seed=3, lo=0.15, hi=0.85): + return np.random.default_rng(seed).uniform(lo, hi, size=(n, 3)) + + +YOUNG = dict(center=(0.65, 0.5, 0.5), dip=65, dip_azimuth=270, displacement=0.12) +OLD = dict(center=(0.3, 0.5, 0.4), dip=55, dip_azimuth=90, displacement=0.1) + + +def young_side(points): + normal, _, _ = dip_vectors(YOUNG["dip"], YOUNG["dip_azimuth"]) + return (np.asarray(points) - np.asarray(YOUNG["center"])) @ normal + + +def young_forward(points): + """Move restored points forward through the young fault (exact: a translation).""" + _, down_dip, _ = dip_vectors(YOUNG["dip"], YOUNG["dip_azimuth"]) + points = np.array(points, dtype=float) + hanging = young_side(points) > 0 + points[hanging] += YOUNG["displacement"] * down_dip + return points diff --git a/tests/unit/modelling/test_fault_block_extension.py b/tests/unit/modelling/test_fault_block_extension.py new file mode 100644 index 000000000..6656f30be --- /dev/null +++ b/tests/unit/modelling/test_fault_block_extension.py @@ -0,0 +1,296 @@ +"""The displacement of a block on the other side of its fault (LS-A2, decision D1). + +A block field is evaluated on both sides of the fault. On the other side the +displacement is the smooth continuation of the profile of the block's side +across gx = 0, so the block field is C2 across the fault surface. +""" + +import numpy as np +import pytest + +from LoopStructural import GeologicalModel +from LoopStructural.modelling.features.fault._fault_function import ( + BaseFault, + BaseFault3D, + Composite, + CubicFunction, + FaultDisplacement, + Ones, + block_displacement, +) +from LoopStructural.utils import _fault_block +from LoopStructural.utils._fault_block import ( + BLOCK_EXTENSION_EXACT, + BLOCK_EXTENSION_LIMIT, + force_side, +) +from tests.fixtures.fault_models import add_fault, add_layers, constant_profile + +GY, GZ = 0.3, -0.2 + + +def cubic(value, slope, end): + """A cubic with a value and a slope at the fault that is flat and zero at ``end``.""" + f = CubicFunction() + f.add_cstr(0, value) + f.add_grad(0, slope) + f.add_cstr(end, 0) + f.add_grad(end, 0) + f.set_lim(min(0, end), max(0, end)) + return f + + +def sloped_cubic_profile(): + """A user profile with a slope at the fault on both sides.""" + return FaultDisplacement(hw=cubic(1.0, -1.5, 1), fw=cubic(-0.6, -0.8, -1), scale=1.0) + + +def sloped_callable_profile(): + """A user gx profile that is not a polynomial: the second-order expansion is used.""" + + def gx(v): + v = np.asarray(v, dtype=float) + return np.where(v > 0, np.exp(-2.0 * v), -0.5 * np.exp(3.0 * v)) + + return FaultDisplacement(gx=gx, gy=Ones(), gz=Ones(), scale=1.0) + + +def plain_function(gx, gy, gz): + """A fault function that is not a FaultDisplacement.""" + return np.where(gx > 0, 1.0 / (1.0 + 2.0 * gx), 0.2 * np.cos(gx) - 0.3 * gx) * ( + 1.0 - 0.1 * gy**2 + ) + + +PROFILES = { + "constant": constant_profile, + "BaseFault": lambda: BaseFault().fault_displacement, + "BaseFault3D": lambda: BaseFault3D().fault_displacement, + "user cubic with a slope": sloped_cubic_profile, + "user callable with a slope": sloped_callable_profile, + "plain function": lambda: plain_function, +} +SLOPED = ("user cubic with a slope", "user callable with a slope", "plain function") + + +def displacement(profile, x, side): + x = np.asarray(x, dtype=float) + return block_displacement( + profile, x, force_side(x, side), np.full(x.shape, GY), np.full(x.shape, GZ), side + ) + + +def one_sided(profile, side, direction, h=5e-4): + """Value, slope and curvature of the block displacement at the fault, from one side.""" + x = direction * (1e-9 + h * np.arange(4)) + f = displacement(profile, x, side) + slope = direction * (-3 * f[0] + 4 * f[1] - f[2]) / (2 * h) + curvature = (2 * f[0] - 5 * f[1] + 4 * f[2] - f[3]) / h**2 + return f[0], slope, curvature + + +def test_library_cubics_at_the_fault(): + """Value, slope, curvature and third derivative of the library gx profiles.""" + for fault in (BaseFault, BaseFault3D): + for piece, expected in ((fault.hw, [2, -3, 0, 1]), (fault.fw, [2, 3, 0, -1])): + piece.solve() + np.testing.assert_allclose(piece.w, expected, atol=1e-12) + value, slope, curvature, third = piece.w[3], piece.w[2], 2 * piece.w[1], 6 * piece.w[0] + assert slope == pytest.approx(0.0, abs=1e-12) + assert abs(curvature) == pytest.approx(6.0) + assert third == pytest.approx(12.0) + assert abs(value) == pytest.approx(1.0) + + +@pytest.mark.parametrize("name", PROFILES) +@pytest.mark.parametrize("side", [1, -1]) +def test_block_displacement_is_c2_at_the_fault(name, side): + """Value (1e-8), slope (1e-5) and curvature (1e-3) agree from both sides. + + The two values are taken 1e-9 from the fault on each side. + """ + profile = PROFILES[name]() + own = one_sided(profile, side, side) + other = one_sided(profile, side, -side) + assert other[0] == pytest.approx(own[0], abs=1e-8) + assert other[1] == pytest.approx(own[1], abs=1e-5) + assert other[2] == pytest.approx(own[2], abs=1e-3) + + +@pytest.mark.parametrize("name", SLOPED) +def test_the_mirror_image_has_a_kink_where_the_profile_has_a_slope(name, monkeypatch): + profile = PROFILES[name]() + own = one_sided(profile, 1, 1) + assert abs(own[1]) > 0.5 + monkeypatch.setattr(_fault_block, "BLOCK_EXTENSION", "mirror") + mirrored = one_sided(profile, 1, -1) + # an even extension: the slope changes sign at the fault + assert mirrored[1] == pytest.approx(-own[1], abs=1e-5) + + +@pytest.mark.parametrize("name", PROFILES) +@pytest.mark.parametrize("side", [1, -1]) +def test_the_block_side_is_not_changed(name, side, monkeypatch): + """On the block's own side the displacement is the profile, bit for bit.""" + profile = PROFILES[name]() + x = side * np.concatenate([[0.0, 1e-12], np.linspace(1e-6, 1.5, 400)]) + y, z = np.full(x.shape, GY), np.full(x.shape, GZ) + expected = profile(force_side(x, side), y, z) + np.testing.assert_array_equal(displacement(profile, x, side), expected) + monkeypatch.setattr(_fault_block, "BLOCK_EXTENSION", "mirror") + np.testing.assert_array_equal(displacement(profile, x, side), expected) + + +@pytest.mark.parametrize("side", [1, -1]) +def test_cubic_continuation_is_the_cubic_itself(side, monkeypatch): + """The library cubic at the signed coordinate; the mirror image differs by 4|x|^3.""" + profile = BaseFault().fault_displacement + x = -side * np.linspace(1e-6, BLOCK_EXTENSION_EXACT, 50) + y, z = np.full(x.shape, GY), np.full(x.shape, GZ) + w = (profile.gx.positive if side > 0 else profile.gx.negative).w + cubic_value = w[0] * x**3 + w[1] * x**2 + w[2] * x + w[3] + rest = profile.scale * profile.gy(y) * profile.gz(z) + smooth = displacement(profile, x, side) + np.testing.assert_allclose(smooth, rest * cubic_value, atol=1e-14) + monkeypatch.setattr(_fault_block, "BLOCK_EXTENSION", "mirror") + mirror = displacement(profile, x, side) + np.testing.assert_allclose(smooth - mirror, rest * 4 * x**3, atol=1e-13) + + +@pytest.mark.parametrize("name", PROFILES) +@pytest.mark.parametrize("side", [1, -1]) +def test_the_continuation_is_constant_beyond_the_limit(name, side): + profile = PROFILES[name]() + far = -side * np.array([BLOCK_EXTENSION_LIMIT, 0.7, 1.0, 5.0, 100.0]) + values = displacement(profile, far, side) + np.testing.assert_allclose(values, values[0], rtol=0, atol=1e-12) + # it stays between the values that the exact part can take: no growth without limit + near = displacement(profile, -side * np.linspace(1e-6, BLOCK_EXTENSION_LIMIT, 200), side) + assert np.all(np.isfinite(near)) + assert abs(values[0]) <= np.max(np.abs(near)) + 1e-12 + + +@pytest.mark.parametrize("name", PROFILES) +def test_the_blend_is_c2(name): + """No jump of the value, the slope or the curvature at the two ends of the blend.""" + profile = PROFILES[name]() + h = 1e-4 + for joint in (BLOCK_EXTENSION_EXACT, BLOCK_EXTENSION_LIMIT): + x = -(joint + h * np.arange(-3, 4)) + f = displacement(profile, x, 1) + left = (2 * f[3] - 5 * f[2] + 4 * f[1] - f[0]) / h**2 + right = (2 * f[3] - 5 * f[4] + 4 * f[5] - f[6]) / h**2 + assert right == pytest.approx(left, abs=5e-2) + assert (f[4] - f[3]) / h == pytest.approx((f[3] - f[2]) / h, abs=1e-2) + + +# --------------------------------------------------------------------------- +# a model: the block field across the fault surface + + +@pytest.fixture(scope="module") +def sloped_model(): + """Planar normal fault (dip 60) whose profile has a slope at the fault.""" + model = GeologicalModel(np.zeros(3), np.ones(3)) + fault = add_fault(model, "f1", (0.5, 0.5, 0.5), 60, 90, 0.15, + profile=sloped_cubic_profile(), axes=(4.0, 4.0, 1.0)) + add_layers(model, [fault]) + model.update() + return model + + +def crossing(model, y=0.5, z=0.5): + """The x at which the line (x, y, z) crosses the fault.""" + lo, hi = 0.2, 0.8 + fault = model["f1"] + + def gx(x): + return fault.evaluate_frame_value(np.array([[x, y, z]]))[0] + + assert gx(lo) * gx(hi) < 0 + for _ in range(60): + mid = 0.5 * (lo + hi) + if gx(lo) * gx(mid) <= 0: + hi = mid + else: + lo = mid + return 0.5 * (lo + hi) + + +def line(x, y=0.5, z=0.5): + x = np.atleast_1d(x) + return np.column_stack([x, np.full(x.shape, y), np.full(x.shape, z)]) + + +def slope_jump(model, block, x0, d=1e-3): + """Jump of the slope of the block field along the line, across the fault.""" + v = model.evaluate_feature_block_value( + "strat", line(x0 + d * np.array([-2.0, -1.0, 1.0, 2.0])), block + ) + return abs((v[3] - v[2]) / d - (v[1] - v[0]) / d) + + +@pytest.mark.parametrize("side", [1, -1]) +def test_block_field_has_a_continuous_gradient_across_the_fault(sloped_model, side, monkeypatch): + x0 = crossing(sloped_model) + block = {"f1": side} + assert slope_jump(sloped_model, block, x0) < 5e-3 + # the test sees a kink: the mirror image gives one + monkeypatch.setattr(_fault_block, "BLOCK_EXTENSION", "mirror") + assert slope_jump(sloped_model, block, x0) > 5e-2 + + +@pytest.mark.parametrize("side", [1, -1]) +def test_block_gradient_uses_the_same_continuation(sloped_model, side, monkeypatch): + """evaluate_feature_block_gradient is the gradient of the block value on both sides.""" + x0 = crossing(sloped_model) + block = {"f1": side} + d = 0.01 + points = line(x0 + d * np.array([-3.0, -2.0, -1.0, 1.0, 2.0, 3.0])) + gradient = sloped_model.evaluate_feature_block_gradient("strat", points, block) + h = 1e-4 + finite_difference = np.empty(points.shape) + for axis in range(3): + step = np.zeros(3) + step[axis] = h + finite_difference[:, axis] = ( + sloped_model.evaluate_feature_block_value("strat", points + step, block) + - sloped_model.evaluate_feature_block_value("strat", points - step, block) + ) / (2 * h) + np.testing.assert_allclose(gradient, finite_difference, atol=2e-2) + # continuous across the fault surface, and not with the mirror image + near = line(x0 + 1e-3 * np.array([-1.0, 1.0])) + smooth = sloped_model.evaluate_feature_block_gradient("strat", near, block) + assert np.max(np.abs(smooth[1] - smooth[0])) < 1e-2 + monkeypatch.setattr(_fault_block, "BLOCK_EXTENSION", "mirror") + mirror = sloped_model.evaluate_feature_block_gradient("strat", near, block) + assert np.max(np.abs(mirror[1] - mirror[0])) > 5e-2 + + +@pytest.mark.parametrize("side", [1, -1]) +def test_block_field_inside_its_block_is_not_changed(sloped_model, side, monkeypatch): + """Bit-equal to the mirror image (the first draft) and to the plain field.""" + points = np.random.default_rng(2).uniform(0.1, 0.9, size=(3000, 3)) + gx = sloped_model["f1"].evaluate_frame_value(points) + inside = side * gx > 0 + block = {"f1": side} + smooth = sloped_model.evaluate_feature_block_value("strat", points, block) + plain = sloped_model.evaluate_feature_value("strat", points) + np.testing.assert_array_equal(smooth[inside], plain[inside]) + monkeypatch.setattr(_fault_block, "BLOCK_EXTENSION", "mirror") + mirror = sloped_model.evaluate_feature_block_value("strat", points, block) + np.testing.assert_array_equal(smooth[inside], mirror[inside]) + assert np.max(np.abs(smooth[~inside] - mirror[~inside])) > 1e-3 + + +def test_constant_profile_is_the_same_with_both_extensions(monkeypatch): + """A constant-slip block: the continuation and the mirror image are equal.""" + model = GeologicalModel(np.zeros(3), np.ones(3)) + fault = add_fault(model, "f1", (0.5, 0.5, 0.5), 60, 90, 0.15) + add_layers(model, [fault]) + points = np.random.default_rng(2).uniform(0.1, 0.9, size=(2000, 3)) + smooth = [model.evaluate_feature_block_value("strat", points, {"f1": s}) for s in (1, -1)] + monkeypatch.setattr(_fault_block, "BLOCK_EXTENSION", "mirror") + mirror = [model.evaluate_feature_block_value("strat", points, {"f1": s}) for s in (1, -1)] + for a, b in zip(smooth, mirror): + np.testing.assert_array_equal(a, b) diff --git a/tests/unit/modelling/test_fault_block_fields.py b/tests/unit/modelling/test_fault_block_fields.py new file mode 100644 index 000000000..b450e948a --- /dev/null +++ b/tests/unit/modelling/test_fault_block_fields.py @@ -0,0 +1,255 @@ +"""Block fields: a feature evaluated as it is in one fault block. + +The models are built in the unit cube. The stratigraphic data are made the +way LoopStructural evaluates a faulted feature: each random present-day point +is restored through the faults, and the analytic field (z) of the restored +point is its value. The interpolated field is then z in restored space, and +the faults are the only source of a jump. +""" + +from concurrent.futures import ThreadPoolExecutor + +import numpy as np +import pytest + +from LoopStructural import GeologicalModel +from tests.fixtures.fault_models import ( + OLD, + YOUNG, + add_fault, + add_layers, + dip_vectors, + interior_points, + plane_points, + young_forward, + young_side, +) + + +@pytest.fixture(scope="module") +def planar(): + """Planar normal fault, dip 60 toward +x, constant slip 0.15 down dip.""" + model = GeologicalModel(np.zeros(3), np.ones(3)) + fault = add_fault(model, "f1", (0.5, 0.5, 0.5), 60, 90, 0.15) + add_layers(model, [fault]) + return model + + +@pytest.fixture(scope="module") +def finite(): + """Finite fault (BaseFault3D) with a tip loop inside the model.""" + model = GeologicalModel(np.zeros(3), np.ones(3)) + fault = add_fault( + model, "f1", (0.5, 0.5, 0.5), 70, 90, 0.2, + profile="BaseFault3D", axes=(0.35, 0.3, 0.5), steps=10, + ) + add_layers(model, [fault]) + return model + + +@pytest.fixture(scope="module") +def displaced(): + """An old fault displaced by a young fault (both constant slip).""" + model = GeologicalModel(np.zeros(3), np.ones(3)) + young = add_fault(model, "young", YOUNG["center"], YOUNG["dip"], YOUNG["dip_azimuth"], + YOUNG["displacement"]) + plane, _, _ = plane_points(OLD["center"], OLD["dip"], OLD["dip_azimuth"], n=15) + present = young_forward(plane) + keep = np.abs(young_side(plane)) > 0.04 + center = young_forward(np.asarray([OLD["center"]]))[0] + add_fault(model, "old", center, OLD["dip"], OLD["dip_azimuth"], OLD["displacement"], + points=present[keep], faults=[young]) + return model + + +def test_planar_block_values_differ_by_the_analytic_offset(planar): + pts = interior_points() + hanging = planar.evaluate_feature_block_value("strat", pts, {"f1": 1}) + footwall = planar.evaluate_feature_block_value("strat", pts, {"f1": -1}) + # Restoring the hanging wall moves a point 0.15 up dip: z grows by 0.15 sin(60). + offset = 0.15 * np.sin(np.radians(60)) + np.testing.assert_allclose(hanging - footwall, offset, atol=2e-3) + + +def test_planar_block_value_equals_the_field_inside_its_block(planar): + pts = interior_points() + fault = planar["f1"] + gx = fault.evaluate_frame_value(pts) + value = planar.evaluate_feature_value("strat", pts) + for side in (1, -1): + inside = side * gx > 1e-6 + block = planar.evaluate_feature_block_value("strat", pts, {"f1": side}) + np.testing.assert_array_equal(block[inside], value[inside]) + + +def test_planar_block_gradient_is_smooth_across_the_fault(planar): + pts = interior_points(n=100) + for side in (1, -1): + grad = planar.evaluate_feature_block_gradient("strat", pts, {"f1": side}) + np.testing.assert_allclose(grad, np.tile([0.0, 0.0, 1.0], (len(pts), 1)), atol=2e-2) + + +def test_block_absent_fault_does_not_move_points(planar): + pts = interior_points() + absent = planar.evaluate_feature_block_value("strat", pts, {"f1": 0}) + np.testing.assert_allclose(absent, pts[:, 2], atol=2e-3) + + +def test_block_calls_leave_no_state(planar): + pts = interior_points() + before = planar.evaluate_feature_value("strat", pts) + first = planar.evaluate_feature_block_value("strat", pts, {"f1": 1}) + planar.evaluate_feature_block_value("strat", pts, {"f1": -1}) + again = planar.evaluate_feature_block_value("strat", pts, {"f1": 1}) + np.testing.assert_array_equal(first, again) + np.testing.assert_array_equal(before, planar.evaluate_feature_value("strat", pts)) + + +def test_block_calls_in_threads_match_sequential_calls(planar): + pts = interior_points(n=2000) + blocks = [{"f1": 1}, {"f1": -1}] * 4 + expected = [planar.evaluate_feature_block_value("strat", pts, b) for b in blocks] + with ThreadPoolExecutor(max_workers=4) as pool: + got = list(pool.map(lambda b: planar.evaluate_feature_block_value("strat", pts, b), blocks)) + for e, g in zip(expected, got): + np.testing.assert_array_equal(e, g) + + +def test_block_is_checked(planar): + pts = interior_points(n=5) + with pytest.raises(ValueError, match="not in the model"): + planar.evaluate_feature_block_value("strat", pts, {"nofault": 1}) + with pytest.raises(ValueError, match="must be"): + planar.evaluate_feature_block_value("strat", pts, {"f1": 2}) + with pytest.raises(TypeError): + planar.evaluate_feature_block_value("strat", pts, [("f1", 1)]) + + +def test_fault_object_can_be_a_block_key(planar): + pts = interior_points(n=50) + by_name = planar.evaluate_feature_block_value("strat", pts, {"f1": 1}) + by_fault = planar.evaluate_feature_block_value("strat", pts, {planar["f1"]: 1}) + np.testing.assert_array_equal(by_name, by_fault) + + +def test_frame_value_is_a_signed_distance_near_the_fault(planar): + fault = planar["f1"] + normal, _, _ = dip_vectors(60, 90) + pts = interior_points(n=200, lo=0.3, hi=0.7) + distance = (pts - 0.5) @ normal + gx = fault.evaluate_frame_value(pts) + grad = fault.evaluate_frame_gradient(pts) + signed = gx / np.linalg.norm(grad, axis=1) + near = np.abs(distance) < 0.1 + np.testing.assert_allclose(signed[near], distance[near], atol=5e-3) + + +def test_constant_fault_has_no_tip(planar): + pts = interior_points(n=10) + assert np.all(np.isinf(planar["f1"].evaluate_tip_value(pts))) + np.testing.assert_array_equal(planar["f1"].evaluate_tip_gradient(pts), 0.0) + + +def test_finite_fault_block_fields_are_equal_beyond_the_tip(finite): + pts = np.random.default_rng(11).uniform(0.0, 1.0, size=(4000, 3)) + fault = finite["f1"] + tip = fault.evaluate_tip_value(pts) + hanging = finite.evaluate_feature_block_value("strat", pts, {"f1": 1}) + footwall = finite.evaluate_feature_block_value("strat", pts, {"f1": -1}) + beyond = tip < 0 + assert beyond.sum() > 100 + np.testing.assert_array_equal(hanging[beyond], footwall[beyond]) + # Inside the tip loop and near the fault the blocks differ. + gx = fault.evaluate_frame_value(pts) + active = (tip > 0.5) & (np.abs(gx) < 0.1) + assert active.sum() > 10 + assert np.all(np.abs(hanging[active] - footwall[active]) > 1e-2) + + +def test_finite_fault_displacement_goes_to_zero_at_the_tip(finite): + fault = finite["f1"] + normal, down_dip, strike = dip_vectors(70, 90) + # A line on the fault along strike, from the centre past the tip. + s = np.linspace(0.0, 0.48, 241) + line = np.asarray([0.5, 0.5, 0.5]) + s[:, None] * strike + tip = fault.evaluate_tip_value(line) + displacement = np.abs(fault.evaluate_displacement(line, block={"f1": 1})) + assert tip[0] > 0.5 and tip[-1] < 0 + np.testing.assert_array_equal(displacement[tip < 0], 0.0) + # Continuous: small just inside the tip. + near = (tip > 0) & (tip < 0.02) + assert near.any() + assert np.all(displacement[near] < 0.01 * displacement.max()) + + +def test_finite_fault_tip_gradient_matches_finite_differences(finite): + fault = finite["f1"] + pts = np.random.default_rng(5).uniform(0.3, 0.7, size=(50, 3)) + grad = fault.evaluate_tip_gradient(pts) + h = 1e-4 + fd = np.zeros_like(pts) + for axis in range(3): + step = np.zeros(3) + step[axis] = h + fd[:, axis] = ( + fault.evaluate_tip_value(pts + step) - fault.evaluate_tip_value(pts - step) + ) / (2 * h) + # Skip points near a kink of min(1 - |gy|, 1 - |gz|): |gy| = |gz|, gy = 0 or gz = 0. + gy = np.abs(fault.evaluate_frame_value(pts, 1)) + gz = np.abs(fault.evaluate_frame_value(pts, 2)) + smooth = (np.abs(gy - gz) > 1e-2) & (gy > 1e-2) & (gz > 1e-2) + assert smooth.sum() > 40 + np.testing.assert_allclose(grad[smooth], fd[smooth], atol=1e-6) + + +def test_displaced_fault_block_frames_match_the_undisplaced_fault(displaced): + old = displaced["old"] + plane, _, _ = plane_points(OLD["center"], OLD["dip"], OLD["dip_azimuth"], n=25, half=0.5) + _, down_dip, _ = dip_vectors(YOUNG["dip"], YOUNG["dip_azimuth"]) + # Footwall block of young: the old fault where it was. Hanging wall block: + # the old fault moved forward by the slip of young, on both sides of young. + for side, points in ((-1, plane), (1, plane + YOUNG["displacement"] * down_dip)): + points = points[np.all((points > 0.05) & (points < 0.95), axis=1)] + gx = old.evaluate_frame_value(points, block={"young": side}) + grad = old.evaluate_frame_gradient(points, block={"young": side}) + distance = gx / np.linalg.norm(grad, axis=1) + assert np.nanmax(np.abs(distance)) < 1e-2 + + +@pytest.fixture(scope="module") +def abutting(): + """A fault that abuts on the hanging wall of a main fault (a Y junction).""" + model = GeologicalModel(np.zeros(3), np.ones(3)) + main = add_fault(model, "main", (0.4, 0.5, 0.5), 60, 90, 0.1) + splay = add_fault(model, "splay", (0.7, 0.5, 0.6), 60, 270, 0.08) + splay.add_abutting_fault(main, positive=True) + add_layers(model, [splay, main]) + return model + + +def test_abutting_fault_is_absent_in_the_footwall_block_of_its_host(abutting): + pts = interior_points(n=2000, lo=0.05, hi=0.95) + values = { + (m, s): abutting.evaluate_feature_block_value("strat", pts, {"main": m, "splay": s}) + for m in (1, -1) + for s in (1, -1) + } + # In the footwall block of main the splay does not exist: its sides are equal. + np.testing.assert_array_equal(values[(-1, 1)], values[(-1, -1)]) + # In the hanging wall block of main the splay offsets the layers. + offset = np.abs(values[(1, 1)] - values[(1, -1)]) + assert np.median(offset) > 0.05 + # Absent is the same as the footwall of main for the splay. + absent = abutting.evaluate_feature_block_value("strat", pts, {"main": -1, "splay": 0}) + np.testing.assert_array_equal(values[(-1, 1)], absent) + + +def test_displaced_fault_block_frame_equals_the_frame_on_its_side(displaced): + old = displaced["old"] + pts = np.random.default_rng(9).uniform(0.05, 0.95, size=(2000, 3)) + gx = old.evaluate_frame_value(pts) + young_gx = displaced["young"].evaluate_frame_value(pts) + for side in (1, -1): + inside = side * young_gx > 1e-6 + block_gx = old.evaluate_frame_value(pts, block={"young": side}) + np.testing.assert_array_equal(block_gx[inside], gx[inside]) diff --git a/tests/unit/modelling/test_fault_kinematics.py b/tests/unit/modelling/test_fault_kinematics.py new file mode 100644 index 000000000..0e5377835 --- /dev/null +++ b/tests/unit/modelling/test_fault_kinematics.py @@ -0,0 +1,90 @@ +"""Kinematics of fault restoration: forward movement and displaced faults.""" + +import numpy as np +import pandas as pd +import pytest + +from LoopStructural import GeologicalModel +from tests.fixtures.fault_models import ( + COLUMNS, + OLD, + YOUNG, + add_fault, + dip_vectors, + interior_points, + plane_points, + young_forward, + young_side, +) + + +@pytest.fixture(scope="module") +def planar_fault(): + """Planar normal fault, dip 60 toward +x, constant slip 0.15 down dip.""" + model = GeologicalModel(np.zeros(3), np.ones(3)) + return add_fault(model, "f1", (0.5, 0.5, 0.5), 60, 90, 0.15) + + +def test_reverse_moves_the_hanging_wall_forward(planar_fault): + _, down_dip, _ = dip_vectors(60, 90) + pts = interior_points(n=200, lo=0.3, hi=0.7) + hanging = planar_fault.evaluate_frame_value(pts) > 0.05 + moved = planar_fault.apply_to_points(pts, reverse=True) + # Forward: the hanging wall moves 0.15 down dip; the footwall stays. + expected = np.tile(0.15 * down_dip, (int(hanging.sum()), 1)) + np.testing.assert_allclose(moved[hanging] - pts[hanging], expected, atol=2e-3) + footwall = planar_fault.evaluate_frame_value(pts) < 0 + np.testing.assert_array_equal(moved[footwall], pts[footwall]) + + +def _restore_exactly(points): + """Restore present-day points through young, then old (both translations).""" + points = np.array(points, dtype=float) + _, young_dip, _ = dip_vectors(YOUNG["dip"], YOUNG["dip_azimuth"]) + points[young_side(points) > 0] -= YOUNG["displacement"] * young_dip + old_normal, old_dip, _ = dip_vectors(OLD["dip"], OLD["dip_azimuth"]) + old_side = (points - np.asarray(OLD["center"])) @ old_normal + points[old_side > 0] -= OLD["displacement"] * old_dip + return points, old_side + + +@pytest.fixture(scope="module") +def displaced_series(): + """A series cut by an old fault that a young fault displaces. + + The values of the data are the analytic field z of each point restored + once through each fault, the kinematics that the fault frames describe. + """ + model = GeologicalModel(np.zeros(3), np.ones(3)) + young = add_fault(model, "young", YOUNG["center"], YOUNG["dip"], YOUNG["dip_azimuth"], + YOUNG["displacement"]) + plane, _, _ = plane_points(OLD["center"], OLD["dip"], OLD["dip_azimuth"], n=15) + keep = np.abs(young_side(plane)) > 0.04 + center = young_forward(np.asarray([OLD["center"]]))[0] + old = add_fault(model, "old", center, OLD["dip"], OLD["dip_azimuth"], OLD["displacement"], + points=young_forward(plane)[keep], faults=[young]) + pts = np.random.default_rng(4).uniform(0.0, 1.0, size=(1500, 3)) + restored, _ = _restore_exactly(pts) + df = pd.DataFrame( + {"X": pts[:, 0], "Y": pts[:, 1], "Z": pts[:, 2], "val": restored[:, 2], + "nx": np.nan, "ny": np.nan, "nz": np.nan, "coord": np.nan, "feature_name": "strat"} + )[COLUMNS] + model.create_and_add_foliation("strat", data=df, faults=[old, young], nelements=8000, + buffer=0.3) + return model + + +def test_displaced_fault_restores_a_series_once(displaced_series): + pts = interior_points(n=3000, lo=0.1, hi=0.9, seed=8) + exact, old_side = _restore_exactly(pts) + value = displaced_series.evaluate_feature_value("strat", pts) + # Away from both faults, the field is z of the point restored once through each fault. + far = (np.abs(young_side(pts)) > 0.03) & (np.abs(old_side) > 0.03) + np.testing.assert_allclose(value[far], exact[far, 2], atol=5e-3) + + +def test_reverse_then_restore_returns_the_points(planar_fault): + pts = interior_points(n=200, lo=0.3, hi=0.7) + hanging = planar_fault.evaluate_frame_value(pts) > 0.05 + back = planar_fault.apply_to_points(planar_fault.apply_to_points(pts, reverse=True)) + np.testing.assert_allclose(back[hanging], pts[hanging], atol=2e-3) diff --git a/tests/unit/modelling/test_fault_tip_ends.py b/tests/unit/modelling/test_fault_tip_ends.py new file mode 100644 index 000000000..0f10cf5c0 --- /dev/null +++ b/tests/unit/modelling/test_fault_tip_ends.py @@ -0,0 +1,45 @@ +"""FaultDisplacement.tip_ends: which frame coordinates carry a tip.""" + +import numpy as np + +from LoopStructural.modelling.features.fault._fault_function import ( + BaseFault, + BaseFault3D, + Composite, + CubicFunction, + FaultDisplacement, + Ones, + Zeros, + smooth_peak, +) + + +def test_library_profiles_declare_their_tips(): + assert BaseFault.fault_displacement.tip_ends == {1: (), 2: (1, -1)} + assert BaseFault3D.fault_displacement.tip_ends == {1: (1, -1), 2: (1, -1)} + constant = FaultDisplacement(gx=Composite(Ones(), Zeros()), gy=Ones(), gz=Ones()) + assert constant.tip_ends == {1: (), 2: ()} + assert smooth_peak.tip_ends == (1, -1) + + +def test_cubic_profile_with_a_zero_limit_has_a_tip_at_that_end(): + f = CubicFunction() + f.add_cstr(-1, 1) + f.add_cstr(0, 1) + f.add_cstr(1, 0) + f.add_grad(1, 0) + f.set_lim(-1, 1) + assert f.tip_ends == (1,) + assert np.all(f(np.array([1.0, 1.5, 3.0])) == 0.0) + + +def test_base_fault_displacement_is_exactly_zero_beyond_its_decay(): + # The hanging-wall and footwall cubics end at 0 at |gx| = 1: exactly 0 beyond. + gx = np.array([1.0, 1.2, 5.0, -1.0, -1.2, -5.0]) + d = BaseFault.fault_displacement(gx, np.zeros(6), np.zeros(6)) + np.testing.assert_array_equal(d, 0.0) + + +def test_undeclared_profile_is_tested(): + step = FaultDisplacement(gx=Ones(), gy=lambda v: (np.abs(v) < 1) * 1.0, gz=Ones()) + assert step.tip_ends == {1: (1, -1), 2: ()} diff --git a/tests/unit/modelling/test_feature_relations.py b/tests/unit/modelling/test_feature_relations.py new file mode 100644 index 000000000..9564f27e5 --- /dev/null +++ b/tests/unit/modelling/test_feature_relations.py @@ -0,0 +1,85 @@ +"""GeologicalModel.get_feature_relations: the relations of a model as plain data.""" + +import numpy as np +import pandas as pd +import pytest + +from LoopStructural import GeologicalModel +from tests.fixtures.fault_models import ( + COLUMNS, + OLD, + YOUNG, + add_fault, + plane_points, + young_forward, + young_side, +) + + +def _series(model, name, faults, value_of_z, seed): + pts = np.random.default_rng(seed).uniform(0.0, 1.0, size=(400, 3)) + df = pd.DataFrame( + {"X": pts[:, 0], "Y": pts[:, 1], "Z": pts[:, 2], "val": value_of_z(pts[:, 2]), + "nx": np.nan, "ny": np.nan, "nz": np.nan, "coord": np.nan, "feature_name": name} + )[COLUMNS] + return model.create_and_add_foliation(name, data=df, faults=faults, nelements=3000) + + +@pytest.fixture(scope="module") +def model(): + """young displaces old; splay abuts young on its footwall; cover above an unconformity.""" + model = GeologicalModel(np.zeros(3), np.ones(3)) + young = add_fault(model, "young", YOUNG["center"], YOUNG["dip"], YOUNG["dip_azimuth"], + YOUNG["displacement"], nelements=2000) + plane, _, _ = plane_points(OLD["center"], OLD["dip"], OLD["dip_azimuth"], n=11) + keep = np.abs(young_side(plane)) > 0.04 + center = young_forward(np.asarray([OLD["center"]]))[0] + old = add_fault(model, "old", center, OLD["dip"], OLD["dip_azimuth"], OLD["displacement"], + points=young_forward(plane)[keep], faults=[young], nelements=2000) + splay = add_fault(model, "splay", (0.85, 0.5, 0.3), 70, 90, 0.05, nelements=2000) + splay.add_abutting_fault(young, positive=False) + cover = _series(model, "cover", [young], lambda z: z - 0.6, seed=1) + model.add_unconformity(cover, 0.0) + _series(model, "basement", [old, young, splay], lambda z: z, seed=2) + return model + + +def test_relations_before_and_after_update_are_equal(model): + before = model.get_feature_relations() + model.update(progressbar=False) + assert model.get_feature_relations() == before + + +def test_fault_relations(model): + rel = model.get_feature_relations() + assert rel["faults"]["young"]["displaced_by"] == [] + assert rel["faults"]["old"]["displaced_by"] == ["young"] + assert rel["faults"]["splay"]["abuts"] == [{"fault": "young", "side": -1}] + assert rel["faults"]["old"]["abuts"] == [] + assert rel["faults"]["young"]["displacement"] == pytest.approx(YOUNG["displacement"]) + + +def test_feature_relations_and_unconformities(model): + rel = model.get_feature_relations() + # Restore order: youngest first. + assert rel["features"]["basement"]["faults"] == ["splay", "young", "old"] + assert rel["features"]["cover"]["faults"] == ["young"] + (uc_name,) = rel["unconformities"] + uc = rel["unconformities"][uc_name] + assert uc["feature"] == "cover" and uc["value"] == 0.0 and not uc["onlap"] + assert "basement" in uc["truncates"] + basement_cut = rel["features"]["basement"]["truncated_by"] + assert basement_cut == [ + {"unconformity": uc_name, "feature": "cover", "value": 0.0, "keep": "below"} + ] + # The series of the unconformity keeps the part above it. + assert rel["features"]["cover"]["truncated_by"][0]["keep"] == "above" + + +def test_event_order_is_the_order_of_creation(model): + rel = model.get_feature_relations() + names = [e["name"] for e in rel["events"]] + assert names[:3] == ["young", "old", "splay"] + assert names.index("cover") < names.index("basement") + types = {e["name"]: e["type"] for e in rel["events"]} + assert types["young"] == "FAULT" and types["basement"] == "INTERPOLATED" diff --git a/tests/unit/modelling/test_position_tolerance.py b/tests/unit/modelling/test_position_tolerance.py new file mode 100644 index 000000000..0f3d784f7 --- /dev/null +++ b/tests/unit/modelling/test_position_tolerance.py @@ -0,0 +1,84 @@ +"""The solver tolerance in length units of the model (LS-F1).""" + +import numpy as np +import pandas as pd +import pytest + +from LoopStructural import GeologicalModel +from tests.fixtures.fault_models import COLUMNS + +EXTENT = 2000.0 # metres + + +def _model(model_tolerance=None, **feature_kwargs): + """A noisy dipping series in a 2 km box that starts at a large offset.""" + origin = np.array([500000.0, 7000000.0, -1000.0]) + model = GeologicalModel(origin, origin + EXTENT) + if model_tolerance is not None: + model.position_tolerance = model_tolerance + rng = np.random.default_rng(11) + local = rng.uniform(0.0, EXTENT, size=(300, 3)) + value = local[:, 2] + 0.2 * local[:, 0] + 60.0 * np.sin(local[:, 1] / 300.0) + points = local + origin + df = pd.DataFrame( + { + "X": points[:, 0], "Y": points[:, 1], "Z": points[:, 2], "val": value, + "nx": np.nan, "ny": np.nan, "nz": np.nan, "coord": np.nan, "feature_name": "strat", + } + )[COLUMNS] + model.create_and_add_foliation("strat", data=df, nelements=8000, buffer=0.2, + **feature_kwargs) + model.update() + return model + + +def _interpolator(model): + return model["strat"].builder.interpolator + + +@pytest.fixture(scope="module") +def reference(): + return _interpolator(_model(solver_kwargs={"rtol": 1e-13, "atol": 0.0})) + + +def _position_error(interpolator, reference): + nodes = reference.support.nodes + gradient = np.linalg.norm(reference.support.evaluate_gradient(nodes, reference.c), axis=1) + return np.max(np.abs(interpolator.c - reference.c) / gradient) + + +def test_default_is_none_and_keeps_the_residual_stop(): + model = _model() + assert model.position_tolerance is None + assert "cg_stop" not in _interpolator(model).get_last_solve_timing() + + +@pytest.mark.parametrize("metres", [20.0, 0.2]) +def test_model_position_tolerance_is_in_model_units(reference, metres): + interpolator = _interpolator(_model(metres)) + timing = interpolator.get_last_solve_timing() + assert timing["cg_stop"] == "position" + assert timing["position_tolerance"] == metres + assert _position_error(interpolator, reference) <= metres + + +def test_a_tighter_tolerance_is_closer_to_the_converged_field(reference): + loose = _position_error(_interpolator(_model(20.0)), reference) + tight = _position_error(_interpolator(_model(0.02)), reference) + assert tight < loose + assert tight <= 0.02 + + +def test_feature_keyword_has_priority_over_the_model(): + model = _model(20.0) + assert _interpolator(model).get_last_solve_timing()["position_tolerance"] == 20.0 + model = _model(20.0, position_tolerance=2.0) + assert _interpolator(model).get_last_solve_timing()["position_tolerance"] == 2.0 + model = _model(position_tolerance=2.0) + assert _interpolator(model).get_last_solve_timing()["position_tolerance"] == 2.0 + + +def test_two_builds_are_bit_equal(): + a = _interpolator(_model(1.0)) + b = _interpolator(_model(1.0)) + np.testing.assert_array_equal(a.c, b.c) diff --git a/tests/unit/modelling/test_unconformity_truncates_faults.py b/tests/unit/modelling/test_unconformity_truncates_faults.py new file mode 100644 index 000000000..b1da5ad59 --- /dev/null +++ b/tests/unit/modelling/test_unconformity_truncates_faults.py @@ -0,0 +1,306 @@ +"""An unconformity truncates the faults that are older than it (LS-D2).""" + +import numpy as np +import pandas as pd +import pytest + +from LoopStructural import GeologicalModel +from LoopStructural.modelling.features import UnconformityFeature +from tests.fixtures.fault_models import ( + COLUMNS, + OLD, + YOUNG, + add_fault, + dip_vectors, + interior_points, + plane_points, + young_forward, + young_side, +) + +TILT = np.radians(20.0) +UNCONFORMITY_Z = 0.6 + + +def cover_field(p): + return p[:, 2] - UNCONFORMITY_Z + + +def basement_field(p): + return -np.sin(TILT) * p[:, 0] + np.cos(TILT) * p[:, 2] - 0.1 + + +def series(model, name, field, faults=None, n=500, seed=5): + """A series whose data are restored through its faults (given oldest first). + + ``faults=None`` leaves the fault list to the model: every fault that the + model has at this moment. + """ + pts = np.random.default_rng(seed).uniform(0.0, 1.0, size=(n, 3)) + use = faults + if use is None: + use = [f for f in model.features if f.type.name == "FAULT"] + restored = pts.copy() + for f in reversed(use): + restored = f.apply_to_points(restored) + df = pd.DataFrame( + { + "X": pts[:, 0], "Y": pts[:, 1], "Z": pts[:, 2], "val": field(restored), + "nx": np.nan, "ny": np.nan, "nz": np.nan, "coord": np.nan, "feature_name": name, + } + )[COLUMNS] + kwargs = {} if faults is None else {"faults": faults} + return model.create_and_add_foliation(name, data=df, nelements=4000, buffer=0.3, **kwargs) + + +def fault(model, name, spec, **kwargs): + return add_fault(model, name, spec["center"], spec["dip"], spec["dip_azimuth"], + spec["displacement"], **kwargs) + + +def new_model(): + return GeologicalModel(np.zeros(3), np.ones(3)) + + +def truncations(fault_feature): + return [r for r in fault_feature[0].regions if isinstance(r, UnconformityFeature)] + + +def probes(): + """Points in the hanging wall of the OLD fault, above and below the unconformity.""" + normal, _, _ = dip_vectors(OLD["dip"], OLD["dip_azimuth"]) + rng = np.random.default_rng(1) + pts = rng.uniform(0.15, 0.85, size=(4000, 3)) + side = (pts - np.asarray(OLD["center"])) @ normal + pts = pts[side > 0.05] + above = pts[pts[:, 2] > UNCONFORMITY_Z + 0.1] + below = pts[pts[:, 2] < UNCONFORMITY_Z - 0.2] + return above, below + + +def assert_truncated_by_cover(model, name): + f = model[name] + regions = truncations(f) + assert [r.parent.name for r in regions] == ["cover"] + assert regions[0].value == 0.0 and regions[0].sign is True + # the three frame features share the regions of the fault + assert all(f[i].regions is f[0].regions for i in range(3)) + above, below = probes() + # the fault surface and frame end on the unconformity + assert np.all(np.isnan(f[0].evaluate_value(above))) + assert np.all(np.isfinite(f[0].evaluate_value(below))) + # the fault moves no point above the unconformity + np.testing.assert_array_equal(f.apply_to_points(above), above) + # below it the hanging wall is restored by the displacement + moved = np.linalg.norm(f.apply_to_points(below) - below, axis=1) + np.testing.assert_allclose(moved, f.displacement, rtol=0.05) + relation = model.get_feature_relations()["faults"][name]["truncated_by"] + assert relation == [ + {"unconformity": "__cover_unconformity", "feature": "cover", "value": 0.0, + "keep": "below"} + ] + + +def assert_not_truncated(model, name): + f = model[name] + assert truncations(f) == [] + above, below = probes() + for pts in (above, below): + assert np.all(np.isfinite(f[0].evaluate_value(pts))) + moved = np.linalg.norm(f.apply_to_points(pts) - pts, axis=1) + np.testing.assert_allclose(moved, f.displacement, rtol=0.05) + + +def test_fault_left_out_of_the_cover_is_older(): + """All faults first: the fault list of the cover says which fault is older.""" + model = new_model() + post = fault(model, "f_post", YOUNG) + pre = fault(model, "f_pre", OLD, faults=[post]) + cover = series(model, "cover", cover_field, faults=[post]) + model.add_unconformity(cover, 0.0) + basement = series(model, "basement", basement_field, faults=[pre, post]) + model.update() + assert_truncated_by_cover(model, "f_pre") + # the younger fault displaces the cover and is not cut + assert truncations(model["f_post"]) == [] + assert [f.name for f in cover.faults] == ["f_post"] + # the basement is still displaced by the older fault + assert sorted(f.name for f in basement.faults) == ["f_post", "f_pre"] + + +def test_fault_added_after_the_cover_and_before_the_call_is_older(): + model = new_model() + cover = series(model, "cover", cover_field) + fault(model, "f_pre", OLD) + model.add_unconformity(cover, 0.0) + series(model, "basement", basement_field) + model.update() + assert_truncated_by_cover(model, "f_pre") + assert cover.faults == [] + # the cover is flat on both sides of the fault trace above the unconformity + above, _ = probes() + np.testing.assert_allclose(cover.evaluate_value(above), cover_field(above), atol=2e-2) + + +def test_fault_added_after_the_call_is_older(): + """The behaviour of the released versions: the new fault takes the region.""" + model = new_model() + cover = series(model, "cover", cover_field) + model.add_unconformity(cover, 0.0) + fault(model, "f_pre", OLD) + series(model, "basement", basement_field) + model.update() + assert_truncated_by_cover(model, "f_pre") + + +def test_fault_that_displaces_the_cover_is_younger(): + model = new_model() + fault(model, "f_young", OLD) + cover = series(model, "cover", cover_field) + model.add_unconformity(cover, 0.0) + series(model, "basement", basement_field) + model.update() + assert [f.name for f in cover.faults] == ["f_young"] + assert_not_truncated(model, "f_young") + + +def test_model_without_an_unconformity(): + model = new_model() + fault(model, "f", OLD) + series(model, "basement", basement_field) + model.update() + assert_not_truncated(model, "f") + + +def test_fault_that_displaces_a_younger_series_is_not_truncated(): + """Left out of the cover, but it displaces a series above an earlier unconformity.""" + model = new_model() + f = fault(model, "f", OLD) + young = series(model, "young", lambda p: p[:, 2] - 0.9) # displaced by f (model default) + model.add_unconformity(young, 0.0) + cover = series(model, "cover", cover_field, faults=[]) + model.add_unconformity(cover, 0.0) + assert truncations(f) == [] + + +def test_fault_that_displaces_only_truncated_series_is_older(): + """Basement first: the unconformity truncates the basement and the fault that cuts it.""" + model = new_model() + f = fault(model, "f_pre", OLD) + series(model, "basement", basement_field) # displaced by f_pre (model default) + cover = series(model, "cover", cover_field, faults=[], seed=6) + model.add_unconformity(cover, 0.0) + model.update() + assert_truncated_by_cover(model, "f_pre") + + +def test_older_fault_is_truncated_by_every_younger_unconformity(): + model = new_model() + old = fault(model, "f_old", OLD) + top = series(model, "cover", cover_field, faults=[]) + model.add_unconformity(top, 0.0) + middle = series(model, "middle", lambda p: p[:, 2] - 0.4, faults=[]) + model.add_unconformity(middle, 0.0) + late = fault(model, "f_late", YOUNG) # added after both: older than both + series(model, "basement", basement_field, faults=[old]) + for f in (old, late): + assert sorted(r.parent.name for r in truncations(f)) == ["cover", "middle"] + + +def test_onlap_unconformity_does_not_truncate_faults(): + """Not changed by this draft: no fault takes the region of an onlap unconformity.""" + model = new_model() + pre = fault(model, "f_pre", OLD) + cover = series(model, "cover", cover_field, faults=[]) + model.add_onlap_unconformity(cover, 0.0) + late = fault(model, "f_late", YOUNG) + assert truncations(pre) == [] + assert truncations(late) == [] + + +def test_the_region_is_added_once(): + model = new_model() + pre = fault(model, "f_pre", OLD) + cover = series(model, "cover", cover_field, faults=[]) + model.add_unconformity(cover, 0.0) + model.add_unconformity(cover, 0.0) + assert len(truncations(pre)) == 1 + + +def test_features_built_before_the_call_are_built_again(): + """A series restored through the fault before the fault was truncated is rebuilt.""" + model = new_model() + pre = fault(model, "f_pre", OLD) + basement = series(model, "basement", basement_field, faults=[pre]) + model.update() + assert basement.builder._up_to_date + cover = series(model, "cover", cover_field, faults=[], seed=6) + model.add_unconformity(cover, 0.0) + assert not basement.builder._up_to_date + + +@pytest.mark.parametrize("value", [0.0, 0.1]) +def test_the_region_uses_the_value_of_the_unconformity(value): + model = new_model() + pre = fault(model, "f_pre", OLD) + cover = series(model, "cover", cover_field, faults=[]) + model.add_unconformity(cover, value) + assert [r.value for r in truncations(pre)] == [value] + + +def _restore_once(points): + """Present-day points restored through the young fault, then through the old + fault where the restored point is below the unconformity (both translations).""" + points = np.array(points, dtype=float) + _, young_dip, _ = dip_vectors(YOUNG["dip"], YOUNG["dip_azimuth"]) + points[young_side(points) > 0] -= YOUNG["displacement"] * young_dip + once = points.copy() + old_normal, old_dip, _ = dip_vectors(OLD["dip"], OLD["dip_azimuth"]) + old_side = (points - np.asarray(OLD["center"])) @ old_normal + points[(old_side > 0) & (cover_field(once) <= 0)] -= OLD["displacement"] * old_dip + return points, once, old_side + + +def test_truncated_fault_that_a_younger_fault_displaces(): + """The old fault ends on the unconformity in the space restored by the young fault. + + The frame of the old fault is built in that space, so its region is read + there too: at the point restored once through the young fault. + """ + model = new_model() + young = fault(model, "young", YOUNG) + plane, _, _ = plane_points(OLD["center"], OLD["dip"], OLD["dip_azimuth"], n=15) + keep = np.abs(young_side(plane)) > 0.04 + center = young_forward(np.asarray([OLD["center"]]))[0] + old = add_fault(model, "old", center, OLD["dip"], OLD["dip_azimuth"], OLD["displacement"], + points=young_forward(plane)[keep], faults=[young]) + + def add_series(name, values, pts, faults): + df = pd.DataFrame( + { + "X": pts[:, 0], "Y": pts[:, 1], "Z": pts[:, 2], "val": values, + "nx": np.nan, "ny": np.nan, "nz": np.nan, "coord": np.nan, "feature_name": name, + } + )[COLUMNS] + return model.create_and_add_foliation(name, data=df, faults=faults, nelements=8000, + buffer=0.3) + + pts = np.random.default_rng(4).uniform(0.0, 1.0, size=(1500, 3)) + restored, once, _ = _restore_once(pts) + cover = add_series("cover", cover_field(once), pts, [young]) + model.add_unconformity(cover, 0.0) + add_series("basement", basement_field(restored), pts, [old, young]) + model.update() + assert [r.parent.name for r in truncations(old)] == ["cover"] + + probe = interior_points(n=4000, lo=0.1, hi=0.9, seed=8) + exact, once, old_side = _restore_once(probe) + value = model.evaluate_feature_value("basement", probe) + # below the unconformity, away from it and from both faults + far = ( + (cover_field(once) < -0.03) + & (np.abs(young_side(probe)) > 0.03) + & (np.abs(old_side) > 0.03) + ) + assert far.sum() > 500 + np.testing.assert_allclose(value[far], basement_field(exact[far]), atol=5e-3)