diff --git a/.dev-tools/project.json b/.dev-tools/project.json index e1a1687d8..ec0f2dc58 100644 --- a/.dev-tools/project.json +++ b/.dev-tools/project.json @@ -27,6 +27,14 @@ "format": "cargo fmt --check", "lint": "cargo clippy --all-targets -- -D warnings" } + }, + "packages/loop_model_core": { + "commands": { + "check": "cargo check --all-targets", + "test": "cargo test --release", + "format": "cargo fmt --check", + "lint": "cargo clippy --all-targets -- -D warnings" + } } } } diff --git a/.github/workflows/model-core-wheels.yml b/.github/workflows/model-core-wheels.yml new file mode 100644 index 000000000..d0d85e7b4 --- /dev/null +++ b/.github/workflows/model-core-wheels.yml @@ -0,0 +1,127 @@ +name: "Native model wheels" + +# Build the wheels and the sdist of loop-model-core. +# pypi.yml calls this workflow and then publishes the files. +# A pull request that changes the crate also runs it, so a broken wheel +# build shows before a release. +# +# The crate uses abi3-py39, so one wheel for each platform works with all +# Python versions from 3.9. + +on: + workflow_call: + pull_request: + branches: + - master + paths: + - 'packages/loop_model_core/**' + - '.github/workflows/model-core-wheels.yml' + workflow_dispatch: + +permissions: + contents: read + +env: + MANIFEST: packages/loop_model_core/Cargo.toml + +jobs: + wheels: + name: Wheel ${{ matrix.platform.name }} + runs-on: ${{ matrix.platform.runner }} + strategy: + fail-fast: false + matrix: + platform: + - { name: linux-x86_64, runner: ubuntu-latest, target: x86_64, smoke: true } + - { name: linux-aarch64, runner: ubuntu-24.04-arm, target: aarch64, smoke: true } + - { name: macos-arm64, runner: macos-latest, target: aarch64, smoke: true } + # Cross-compiled on the arm64 runner, so it is not run here. + - { name: macos-x86_64, runner: macos-latest, target: x86_64, smoke: false } + - { name: windows-x86_64, runner: windows-latest, target: x64, smoke: true } + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + # On Linux the build runs in a manylinux container. + - name: Build the wheel + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.platform.target }} + manylinux: auto + args: --release --out dist --manifest-path ${{ env.MANIFEST }} + - name: Install the wheel and restore points across a fault + if: matrix.platform.smoke + shell: bash + run: | + python -m pip install numpy + python -m pip install --no-index --find-links dist loop-model-core + python - <<'EOF' + import numpy as np + import loop_model_core as core + + i, j, k = np.meshgrid(np.arange(21.0), np.arange(21.0), np.arange(21.0), indexing="ij") + x = i.ravel(order="F") + y = j.ravel(order="F") + z = k.ravel(order="F") + + + def grid(values): + return { + "origin": [0.0, 0.0, 0.0], + "nsteps": [21, 21, 21], + "step_vector": [1.0, 1.0, 1.0], + "local_origin": None, + "local_rotation": None, + "values": np.asarray(values, dtype=np.float64), + } + + + spec = { + "version": 1, + "block": {"side_epsilon": 1e-9, "extension": "smooth", "exact": 0.25, "limit": 0.5, "step": 1e-3}, + "faults": [ + { + "name": "f", + "displacement": 10.0, + "steps": 10, + "frame": [grid(x - 10), grid(y), grid(z)], + "cutters": [], + "regions": [[], [], []], + "profile": {"scale": 1.0, "gx": {"kind": "ones"}, "gy": {"kind": "ones"}, "gz": {"kind": "ones"}}, + } + ], + } + chain = core.FaultChain(spec) + out = chain.restore( + np.array([[5.0, 5.0, 5.0], [12.0, 4.0, 8.0]]), + np.array([0], dtype=np.int64), + False, + np.array([2], dtype=np.int8), + np.array([False]), + 0, + ) + assert np.allclose(out, [[5, 15, 5], [12, 14, 8]], rtol=0, atol=1e-12), out + print("fault kernel restore ok") + EOF + - uses: actions/upload-artifact@v4 + with: + name: model-core-wheel-${{ matrix.platform.name }} + path: dist/*.whl + if-no-files-found: error + + sdist: + name: Sdist + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Build the sdist + uses: PyO3/maturin-action@v1 + with: + command: sdist + args: --out dist --manifest-path ${{ env.MANIFEST }} + - uses: actions/upload-artifact@v4 + with: + name: model-core-sdist + path: dist/*.tar.gz + if-no-files-found: error diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml index 9a652c01a..436cac1f9 100644 --- a/.github/workflows/native.yml +++ b/.github/workflows/native.yml @@ -9,14 +9,20 @@ on: - master paths: - 'packages/loop_interpolation_core/**' + - 'packages/loop_model_core/**' - 'packages/loop_interpolation/src/loop_interpolation/_native.py' + - 'LoopStructural/modelling/features/_native_faults.py' + - 'LoopStructural/utils/_fault_block.py' - '.github/workflows/native.yml' pull_request: branches: - master paths: - 'packages/loop_interpolation_core/**' + - 'packages/loop_model_core/**' - 'packages/loop_interpolation/src/loop_interpolation/_native.py' + - 'LoopStructural/modelling/features/_native_faults.py' + - 'LoopStructural/utils/_fault_block.py' - '.github/workflows/native.yml' workflow_dispatch: @@ -26,6 +32,7 @@ permissions: env: CARGO_TERM_COLOR: always MANIFEST: packages/loop_interpolation_core/Cargo.toml + MODEL_MANIFEST: packages/loop_model_core/Cargo.toml jobs: # Format, lint and test the crate with all feature sets. @@ -44,7 +51,8 @@ jobs: ~/.cargo/registry ~/.cargo/git packages/loop_interpolation_core/target - key: rust-${{ runner.os }}-${{ hashFiles('packages/loop_interpolation_core/Cargo.lock') }} + packages/loop_model_core/target + key: rust-${{ runner.os }}-${{ hashFiles('packages/loop_interpolation_core/Cargo.lock', 'packages/loop_model_core/Cargo.lock') }} restore-keys: rust-${{ runner.os }}- - name: Format run: cargo fmt --manifest-path "$MANIFEST" --check @@ -61,6 +69,18 @@ jobs: run: cargo test --manifest-path "$MANIFEST" --release - name: Test, parallel run: cargo test --manifest-path "$MANIFEST" --release --features parallel + - name: Model core format + run: cargo fmt --manifest-path "$MODEL_MANIFEST" --check + - name: Model core clippy, no features + run: cargo clippy --manifest-path "$MODEL_MANIFEST" --all-targets -- -D warnings + - name: Model core clippy, parallel + run: cargo clippy --manifest-path "$MODEL_MANIFEST" --all-targets --features parallel -- -D warnings + - name: Model core clippy, python + run: cargo clippy --manifest-path "$MODEL_MANIFEST" --all-targets --features python -- -D warnings + - name: Model core test, no features + run: cargo test --manifest-path "$MODEL_MANIFEST" --release + - name: Model core test, parallel + run: cargo test --manifest-path "$MODEL_MANIFEST" --release --features parallel # Build the Python wheel and run the Python tests with the native core installed. wheel: @@ -81,7 +101,8 @@ jobs: ~/.cargo/registry ~/.cargo/git packages/loop_interpolation_core/target - key: wheel-${{ runner.os }}-${{ hashFiles('packages/loop_interpolation_core/Cargo.lock') }} + packages/loop_model_core/target + key: wheel-${{ runner.os }}-${{ hashFiles('packages/loop_interpolation_core/Cargo.lock', 'packages/loop_model_core/Cargo.lock') }} restore-keys: wheel-${{ runner.os }}- # maturin develop needs a virtual environment. # The Linux and macOS folder is bin. The Windows folder is Scripts. @@ -95,6 +116,9 @@ jobs: python -m pip install -e packages/loop_common -e packages/loop_interpolation maturin develop --release -m packages/loop_interpolation_core/Cargo.toml python -m pytest packages/loop_interpolation/tests -q + maturin develop --release -m packages/loop_model_core/Cargo.toml + python -m pip install -e . + python -m pytest tests/fault_evaluation -q # Build the WebAssembly package, check its size and run the browser tests. wasm: diff --git a/.github/workflows/pypi.yml b/.github/workflows/pypi.yml index e825c37c2..0ef0ea333 100644 --- a/.github/workflows/pypi.yml +++ b/.github/workflows/pypi.yml @@ -6,10 +6,11 @@ permissions: contents: read jobs: - # loop-interpolation-core is the Rust core behind the optional extra - # loop-interpolation[native]. It has compiled wheels, so it is built by - # core-wheels.yml and not by the sdist matrix below. No other package - # waits for it: a failed core upload does not stop their release. + # loop-interpolation-core (the solver behind loop-interpolation[native]) + # and loop-model-core (the fault kernel) are Rust cores with compiled + # wheels, so they are built by core-wheels.yml and model-core-wheels.yml + # and not by the sdist matrix below. No other package waits for them: a + # failed core upload does not stop their release. build_core: name: Build loop-interpolation-core uses: ./.github/workflows/core-wheels.yml @@ -33,6 +34,29 @@ jobs: skip-existing: true verbose: true + build_model_core: + name: Build loop-model-core + uses: ./.github/workflows/model-core-wheels.yml + + # Trusted publishing (OIDC): no password. PyPI must list this repository + # and the workflow file pypi.yml as a trusted publisher of the project loop-model-core. + upload_model_core_to_pypi: + name: Upload loop-model-core to PyPI + needs: ["build_model_core"] + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - uses: actions/download-artifact@v4 + with: + pattern: model-core-* + path: dist + merge-multiple: true + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + skip-existing: true + verbose: true + # loop_common/loop_interpolation/loopstructural_visualisation are # workspace-local deps of LoopStructural (see [tool.uv.sources] in # pyproject.toml) — loop_common/loop_interpolation are runtime deps, diff --git a/.release-please-config.json b/.release-please-config.json index ba601927a..dc4264b9c 100644 --- a/.release-please-config.json +++ b/.release-please-config.json @@ -10,6 +10,7 @@ "packages/loop_common", "packages/loop_interpolation", "packages/loop_interpolation_core", + "packages/loop_model_core", "packages/map2loop", "packages/loop_link", "packages/loopstructural_visualisation" @@ -34,6 +35,17 @@ } ] }, + "packages/loop_model_core": { + "release-type": "python", + "component": "loop-model-core", + "extra-files": [ + { + "type": "toml", + "path": "Cargo.toml", + "jsonpath": "$.package.version" + } + ] + }, "packages/map2loop": { "release-type": "python", "component": "map2loop" diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6ca23c6f5..e659cfdeb 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -3,6 +3,7 @@ "packages/loop_common": "0.2.0", "packages/loop_interpolation": "0.3.0", "packages/loop_interpolation_core": "0.1.0", + "packages/loop_model_core": "0.0.0", "packages/map2loop": "3.5.1", "packages/loopstructural_visualisation": "0.2.2", "packages/loop_link": "0.1.0" diff --git a/LoopStructural/__init__.py b/LoopStructural/__init__.py index dc13952a4..e683420c6 100644 --- a/LoopStructural/__init__.py +++ b/LoopStructural/__init__.py @@ -4,6 +4,8 @@ """ +from __future__ import annotations + import logging from dataclasses import dataclass from logging.config import dictConfig @@ -59,6 +61,12 @@ class LoopStructuralConfig: ---------- nelements : int, optional The default number of elements to use in interpolation, by default 10_000 + native_faults : bool, optional + Turns the native fault kernel on (True) or off (False). If None, the + environment variable ``LOOPSTRUCTURAL_NATIVE_FAULTS`` decides. + native_threads : int, optional + The number of threads for the native fault kernel. If None, the kernel + uses its default (0). Examples -------- @@ -68,6 +76,8 @@ class LoopStructuralConfig: """ nelements: int = 10_000 + native_faults: bool | None = None + native_threads: int | None = None from .geometry import BoundingBox from .interpolators import InterpolatorBuilder diff --git a/LoopStructural/modelling/features/_base_geological_feature.py b/LoopStructural/modelling/features/_base_geological_feature.py index 11f6bd389..11d1b1832 100644 --- a/LoopStructural/modelling/features/_base_geological_feature.py +++ b/LoopStructural/modelling/features/_base_geological_feature.py @@ -291,12 +291,24 @@ def _apply_faults( """ if self.faults_enabled: + from . import _native_faults + + native = _native_faults.restore( + self, + evaluation_points, + reverse=reverse, + block=block, + restored_through=restored_through, + ) + if native is not None: + return native evaluation_points = restore_through( evaluation_points, self.faults, reverse=reverse, block=block, restored_through=restored_through, + owner=self, ) return evaluation_points diff --git a/LoopStructural/modelling/features/_evaluation.py b/LoopStructural/modelling/features/_evaluation.py index 7f05a9601..0632209aa 100644 --- a/LoopStructural/modelling/features/_evaluation.py +++ b/LoopStructural/modelling/features/_evaluation.py @@ -82,6 +82,16 @@ def _fault_state(fault: BaseFeature) -> Hashable: ) +def _restore_direct(feature: BaseFeature, points: np.ndarray, reverse: bool) -> np.ndarray: + """Restore points with the native kernel if it can, else with the Python path.""" + from . import _native_faults + + native = _native_faults.restore(feature, points, reverse=reverse) + if native is not None: + return native + return restore_through(points, feature.faults, reverse=reverse, owner=feature) + + class EvaluationContext: """Storage for the restorations of one evaluation scope. @@ -133,7 +143,7 @@ def restore( if points.dtype.hasobject: # An array of Python objects has no bytes to compare. Restore it without # sharing, as the legacy path does (apply_to_points makes it float). - return restore_through(points, faults, reverse=reverse) + return _restore_direct(feature, points, reverse) digest = _digest(points) # The scope key holds the faults only. Features with the same ordered faults share # one restoration inside the scope. The model does not change inside one scope. @@ -156,7 +166,7 @@ def restore( self._batches.pop(slot, None) self._depth += 1 try: - restored = np.asarray(restore_through(points, faults, reverse=reverse)) + restored = np.asarray(_restore_direct(feature, points, reverse)) finally: self._depth -= 1 if restored is points or np.shares_memory(restored, points): diff --git a/LoopStructural/modelling/features/_geological_feature.py b/LoopStructural/modelling/features/_geological_feature.py index 54c9a653b..6ef103c55 100644 --- a/LoopStructural/modelling/features/_geological_feature.py +++ b/LoopStructural/modelling/features/_geological_feature.py @@ -28,6 +28,7 @@ from . import FeatureType from ._base_geological_feature import BaseFeature from ._evaluation import evaluation_scope, probe_points, restore +from ._native_faults import _native_inputs, chain_for, field_for, native_threads logger = getLogger(__name__) @@ -205,7 +206,17 @@ def evaluate_value( if mask.dtype not in [int, bool]: logger.error(f"Unable to evaluate value for {self.name}") else: - v[mask] = self.interpolator.evaluate_value(evaluation_points[mask, :]) + field = field_for(self) + if field is None: + v[mask] = self.interpolator.evaluate_value(evaluation_points[mask, :]) + else: + # Same stale-frame check as the Python interpolator. + self.interpolator._check_frame() + self.interpolator.update() + v[mask] = field.values( + np.ascontiguousarray(evaluation_points[mask, :], dtype=float), + native_threads(), + ) if fillnan == 'nearest': from scipy import spatial @@ -268,6 +279,36 @@ def evaluate_gradient( # then evaluate the gradient at these points faults = self._unrestored_faults(restored_through) if len(faults) > 0: + field = field_for(self) + inputs = ( + _native_inputs(self, False, block, restored_through) + if field is not None + else None + ) + if inputs is not None: + chain, order, sides, restored = inputs + # A fault that the block names has no jump, so a tetrahedron may cross it. + jumping = [ + any(f is g for g in faults) and (not block or f.name not in block) + for f in chain_for(self)[1] + ] + grads, count = chain.feature_gradient( + field, + np.ascontiguousarray(pos, dtype=float), + order, + sides, + restored, + np.asarray(jumping, dtype=bool), + float(element_scale_parameter), + native_threads(), + ) + # Rows outside the mask stay NaN. + v[mask, :] = grads[mask, :] + if count > 0: + logger.warning( + f"{count} points are too close to a fault. Refining the tetrahedron" + ) + return v # generate a regular tetrahedron for each point # we will then move these points by the fault and then recalculate the gradient. # this should work... @@ -320,7 +361,15 @@ def straddles(tet): if mask.dtype not in [int, bool]: logger.error(f"Unable to evaluate gradient for {self.name}") else: - v[mask, :] = self.interpolator.evaluate_gradient(pos[mask, :]) + field = field_for(self) + if field is None: + v[mask, :] = self.interpolator.evaluate_gradient(pos[mask, :]) + else: + self.interpolator._check_frame() + self.interpolator.update() + v[mask, :] = field.gradients( + np.ascontiguousarray(pos[mask, :], dtype=float), native_threads() + ) logger.info(f'Gradient calculated for {self.name}') return v diff --git a/LoopStructural/modelling/features/_native_faults.py b/LoopStructural/modelling/features/_native_faults.py new file mode 100644 index 000000000..f9a855a19 --- /dev/null +++ b/LoopStructural/modelling/features/_native_faults.py @@ -0,0 +1,452 @@ +"""Decide if LoopStructural uses the native fault kernel. + +The native fault kernel is the Rust package ``loop_model_core``. +""" + +from __future__ import annotations + +import os +from collections.abc import Sequence + +import numpy as np + +from ...utils import getLogger + +logger = getLogger(__name__) + +REQUIRED_FAULT_KERNEL_VERSION: int = 1 + +_core = None +_core_checked = False +_version_warned = False + + +def native_enabled() -> bool: + """Return True if the native fault kernel can be used and is not turned off. + + The setting ``LoopStructuralConfig.native_faults`` has priority over the + environment variable ``LOOPSTRUCTURAL_NATIVE_FAULTS``. The kernel import + and the version check run once for each session. + + Returns + ------- + bool + True if the kernel is on, installed and has the required version. + """ + global _core, _core_checked, _version_warned + from LoopStructural import LoopStructuralConfig + + setting = LoopStructuralConfig.native_faults + if setting is None: + if os.environ.get("LOOPSTRUCTURAL_NATIVE_FAULTS", "").lower() in { + "0", + "false", + "off", + "no", + }: + return False + elif not setting: + return False + if not _core_checked: + _core_checked = True + try: + import loop_model_core + + _core = loop_model_core + except ImportError: + _core = None + if _core is None: + return False + found = getattr(_core, "FAULT_KERNEL_VERSION", None) + if found != REQUIRED_FAULT_KERNEL_VERSION: + if not _version_warned: + _version_warned = True + logger.warning( + f"native fault kernel version {found} found, LoopStructural needs " + f"version {REQUIRED_FAULT_KERNEL_VERSION}; using the Python path" + ) + return False + return True + + +def native_threads() -> int: + """Return the thread count for the native fault kernel. + + Returns + ------- + int + The setting ``LoopStructuralConfig.native_threads``, or 0 if it is None. + A negative value means all cores, as -1 in joblib. + """ + from LoopStructural import LoopStructuralConfig + + setting = LoopStructuralConfig.native_threads + if setting is None: + return 0 + return max(int(setting), 0) + + +class _Unsupported(Exception): + """Raised when a model part cannot go to the native kernel.""" + + +def _grid(member: object, refs: list, grids: list) -> dict: + """Return the grid dict of one frame member or unconformity field.""" + from loop_common.supports import StructuredGrid + from loop_interpolation import DiscreteInterpolator + + if member.builder is not None: + member.builder.up_to_date() + interpolator = member.interpolator + if not isinstance(interpolator, DiscreteInterpolator): + raise _Unsupported("interpolator") + for name in ("evaluate_value", "_evaluate_value_local", "_evaluate_gradient_local"): + if getattr(type(interpolator), name) is not getattr(DiscreteInterpolator, name): + raise _Unsupported("interpolator") + support = interpolator.support + if not isinstance(support, StructuredGrid) or not support._has_uniform_lookup(): + raise _Unsupported("support") + # Same stale-frame check as the Python path. + interpolator._check_frame() + interpolator.update() + box = interpolator.bounding_box + grid = { + "origin": np.asarray(support.origin, dtype=float).tolist(), + "nsteps": [int(n) for n in support.nsteps], + "step_vector": np.asarray(support.step_vector, dtype=float).tolist(), + "local_origin": None if box is None else np.asarray(box.local_origin, dtype=float).tolist(), + "local_rotation": ( + None if box is None else np.asarray(box.local_rotation, dtype=float).tolist() + ), + # The raw array is kept here; it is converted only when a kernel is built. + "values": interpolator.c, + } + refs.append(interpolator.c) + grids.append(grid) + return grid + + +def _part(function: object) -> dict: + """Return the profile dict of one profile function.""" + from .fault._fault_function import Composite, CubicFunction, Ones, Zeros, smooth_peak + + if function is smooth_peak: + return {"kind": "smooth_peak"} + kind = type(function) + if kind is Ones: + return {"kind": "ones"} + if kind is Zeros: + return {"kind": "zeros"} + if kind is Composite: + return { + "kind": "composite", + "positive": _part(function.positive), + "negative": _part(function.negative), + } + if kind is CubicFunction: + function.solve() + return { + "kind": "cubic", + "w": [float(x) for x in function.w], + "lim": [float(function.lim[0]), float(function.lim[1])], + "min": float(function.min_v), + "max": float(function.max_v), + "value_points": [[float(x), float(y)] for x, y in function.value_points], + } + raise _Unsupported("profile") + + +class _Build: + """State of one spec build: the chain faults, their specs and the arrays used.""" + + def __init__(self) -> None: + self.faults: list = [] + self.index: dict = {} + self.specs: list = [] + self.refs: list = [] + self.grids: list = [] + + def add(self, fault: object) -> int: + """Return the chain index of a fault; append it if it is new.""" + i = self.index.get(id(fault)) + if i is None: + i = len(self.faults) + self.index[id(fault)] = i + self.faults.append(fault) + return i + + def indices(self, faults: object, owner: object) -> list: + """Return the chain indices of the faults in restore order (cached on owner).""" + from ...utils._fault_block import restore_order + + return [self.add(f) for f in restore_order(faults, owner=owner)] + + +def _region(region: object, build: _Build) -> dict: + """Return the region dict of one region object.""" + from ...utils.regions import NegativeRegion, PositiveRegion + from ._unconformity_feature import UnconformityFeature + from .fault._fault_segment import FaultSegment + + if type(region) is UnconformityFeature: + return { + "kind": "unconformity", + "field": _grid(region, build.refs, build.grids), + "faults": build.indices(region.faults, region), + "value": float(region.value), + "sign": bool(region.sign), + } + if type(region) in (PositiveRegion, NegativeRegion): + if type(region.feature) is not FaultSegment or region.vector is None: + raise _Unsupported("region") + if region.point is None: + raise _Unsupported("region") + return { + "kind": "positive" if isinstance(region, PositiveRegion) else "negative", + "fault": build.add(region.feature), + "vector": [float(x) for x in region.vector], + "point": [float(x) for x in region.point], + } + raise _Unsupported("region") + + +def _fault_spec(fault: object, build: _Build) -> dict: + """Return the spec dict of one fault of the chain.""" + from ._geological_feature import GeologicalFeature + from .fault._fault_function import FaultDisplacement + from .fault._fault_segment import FaultSegment + + if type(fault) is not FaultSegment: + raise _Unsupported("fault") + if fault.builder is not None: + fault.builder.up_to_date() + function = fault.faultfunction + if type(function) is not FaultDisplacement or int(fault.steps) < 1: + raise _Unsupported("profile") + members = [fault[i] for i in range(3)] + for member in members: + if type(member).evaluate_value is not GeologicalFeature.evaluate_value: + raise _Unsupported("member") + if type(member).evaluate_gradient is not GeologicalFeature.evaluate_gradient: + raise _Unsupported("member") + same = len(member.faults) == len(members[0].faults) and all( + a is b for a, b in zip(member.faults, members[0].faults) + ) + if not same or (len(member.faults) > 0 and not member.faults_enabled): + raise _Unsupported("member faults") + return { + "name": str(fault.name), + "displacement": float(fault.displacement), + "steps": int(fault.steps), + "frame": [_grid(m, build.refs, build.grids) for m in members], + "cutters": build.indices(members[0].faults, members[0]), + "regions": [[_region(r, build) for r in m.regions] for m in members], + "profile": { + "scale": float(function.scale), + "gx": _part(function.gx), + "gy": _part(function.gy), + "gz": _part(function.gz), + }, + } + + +def _freeze(value: object) -> object: + """Return a hashable copy of a spec part; an array of node values becomes its id.""" + if isinstance(value, dict): + return tuple((k, id(v) if k == "values" else _freeze(v)) for k, v in sorted(value.items())) + if isinstance(value, (list, tuple)): + return tuple(_freeze(v) for v in value) + return value + + +def chain_for(feature: object) -> tuple | None: + """Return the native fault kernel of a feature and its faults, or None. + + None means that the Python path must be used (FR-008). The kernel is kept + in ``feature._native_chain`` and is made again only if the state token + changes (FR-009, FR-010). + + Parameters + ---------- + feature : BaseFeature + The feature whose faults are restored. + + Returns + ------- + tuple or None + ``(FaultChain, faults, specs)`` where ``faults`` is the chain list and + ``specs`` the spec dict of each fault, or None if any part is not + supported. + """ + from ...utils import _fault_block as fb + + if not native_enabled() or not getattr(feature, "faults_enabled", False): + return None + if not feature.faults: + return None + block = { + "side_epsilon": fb.BLOCK_SIDE_EPSILON, + "extension": fb.BLOCK_EXTENSION, + "exact": fb.BLOCK_EXTENSION_EXACT, + "limit": fb.BLOCK_EXTENSION_LIMIT, + "step": fb.BLOCK_EXTENSION_STEP, + } + build = _Build() + try: + # Only the set of faults is needed here, so no order is computed. + for f in fb.with_cutters(feature.faults): + build.add(f) + k = 0 + while k < len(build.faults): + build.specs.append(_fault_spec(build.faults[k], build)) + k += 1 + except (_Unsupported, TypeError, ValueError, IndexError, KeyError, AttributeError): + return None + spec = {"version": 1, "block": block, "faults": build.specs} + token = (tuple(block.items()), tuple(id(f) for f in build.faults), _freeze(build.specs)) + cached = getattr(feature, "_native_chain", None) + if cached is not None and cached[0] == token: + return cached[2], cached[3], cached[4] + for grid in build.grids: + grid["values"] = np.asarray(grid["values"], dtype=float) + chain = _core.FaultChain(spec) + try: + feature._native_chain = (token, build.refs, chain, build.faults, build.specs) + except AttributeError: + pass + return chain, build.faults, build.specs + + +def _native_inputs( + feature: object, + reverse: bool, + block: dict | None, + restored_through: Sequence, +) -> tuple | None: + """Return the inputs of the native kernel for one restoration, or None. + + Parameters + ---------- + feature : BaseFeature + The feature whose faults are restored. + reverse : bool + Move the points forward instead of restoring them. + block : dict, optional + Fault block, see ``check_block``. + restored_through : sequence of FaultSegment + Faults whose restoration the points already have. + + Returns + ------- + tuple or None + ``(chain, order, sides, restored)`` as arrays for the kernel, or None + if the Python path must be used. + """ + from ...utils._fault_block import check_block, is_in, restore_order + + found = chain_for(feature) + if found is None: + return None + chain, faults, specs = found + index = {id(f): i for i, f in enumerate(faults)} + ordered = restore_order(feature.faults, reverse=reverse, owner=feature) + order = [index[id(f)] for f in ordered if not is_in(f, restored_through)] + named = check_block(block) or {} + sides = [named.get(f.name, 2) for f in faults] + restored = [is_in(f, restored_through) for f in faults] + # A cutter that is not restored at the turn of its fault needs the Python path. + done = {i for i, flag in enumerate(restored) if flag} + for i in order: + if not all(c in done for c in specs[i]["cutters"]): + return None + done.add(i) + return ( + chain, + np.asarray(order, dtype=np.int64), + np.asarray(sides, dtype=np.int8), + np.asarray(restored, dtype=bool), + ) + + +def field_for(feature: object) -> object | None: + """Return the native scalar field of a feature, or None. + + None means that the Python interpolator must be used. The field is kept in + ``feature._native_field`` and is made again only if the state token changes. + + Parameters + ---------- + feature : GeologicalFeature + The feature whose field is evaluated. + + Returns + ------- + GridField or None + The native field, or None if the interpolator or the support is not + supported. + """ + from ._geological_feature import GeologicalFeature + + if not native_enabled(): + return None + for name in ("evaluate_value", "evaluate_gradient"): + if getattr(type(feature), name) is not getattr(GeologicalFeature, name): + return None + refs: list = [] + grids: list = [] + try: + grid = _grid(feature, refs, grids) + except (_Unsupported, TypeError, ValueError, IndexError, KeyError, AttributeError): + return None + token = _freeze(grid) + cached = getattr(feature, "_native_field", None) + if cached is not None and cached[0] == token: + return cached[2] + grid["values"] = np.asarray(grid["values"], dtype=float) + field = _core.GridField(grid) + try: + feature._native_field = (token, refs, field) + except AttributeError: + pass + return field + + +def restore( + feature: object, + points: np.ndarray, + *, + reverse: bool = False, + block: dict | None = None, + restored_through: Sequence = (), +) -> np.ndarray | None: + """Restore points through the faults of a feature with the native kernel. + + Parameters + ---------- + feature : BaseFeature + The feature whose faults are restored. + points : np.ndarray + Float array of shape (N, 3). + reverse : bool + Move the points forward instead of restoring them. + block : dict, optional + Fault block, see ``check_block``. + restored_through : sequence of FaultSegment + Faults whose restoration the points already have. + + Returns + ------- + np.ndarray or None + The restored points, or None if the Python path must be used. + """ + if not native_enabled(): + return None + points = np.asarray(points) + if points.dtype.kind != "f" or points.ndim != 2 or points.shape[1] != 3: + return None + inputs = _native_inputs(feature, reverse, block, restored_through) + if inputs is None: + return None + chain, order, sides, restored = inputs + points = np.ascontiguousarray(points, dtype=float) + return chain.restore(points, order, bool(reverse), sides, restored, native_threads()) diff --git a/LoopStructural/modelling/features/fault/_fault_segment.py b/LoopStructural/modelling/features/fault/_fault_segment.py index df1aea6a0..858024162 100644 --- a/LoopStructural/modelling/features/fault/_fault_segment.py +++ b/LoopStructural/modelling/features/fault/_fault_segment.py @@ -17,6 +17,9 @@ logger = getLogger(__name__) +# Switch for tests: false gives the old calls, one restoration for each member. +_SHARE_CUT_FRAME_RESTORATION = True + class FaultSegment(StructuralFrame): @@ -452,6 +455,13 @@ def _evaluate_frame_legacy( kwargs["restored_through"] = tuple(restored_through) member0, member1, member2 = (self.__getitem__(i) for i in range(3)) gx = gy = gz = g = None + if _SHARE_CUT_FRAME_RESTORATION and self._share_restoration( + (member0, member1, member2) + ): + return self._evaluate_frame_shared( + (member0, member1, member2), + points, block, restored_through, need_gradient, need_values, need_gx, + ) if need_values: if need_gx: gx = member0.evaluate_value(points, **kwargs) @@ -463,6 +473,71 @@ def _evaluate_frame_legacy( return gx, gy, gz, g return gx, gy, gz + @staticmethod + def _share_restoration(members): + """Tell if the three members can use one restoration of the points. + + True only if each member is a plain GeologicalFeature with faults + enabled, and the three members have the same non-empty fault list + (each item is the same object). + """ + from .._geological_feature import GeologicalFeature + + for member in members: + if type(member) is not GeologicalFeature: + return False + if type(member).evaluate_value is not GeologicalFeature.evaluate_value: + return False + if type(member).evaluate_gradient is not GeologicalFeature.evaluate_gradient: + return False + if not member.faults_enabled or len(member.faults) == 0: + return False + first = members[0].faults + return all( + len(m.faults) == len(first) and all(a is b for a, b in zip(m.faults, first)) + for m in members[1:] + ) + + @staticmethod + def _evaluate_frame_shared( + members, points, block, restored_through, need_gradient, need_values, need_gx + ): + """Evaluate the frame with one restoration of the points for the three members. + + The result is the same as the legacy calls. The masks use the points + before the restoration, as GeologicalFeature.evaluate_value does. + """ + from LoopStructural.utils._fault_block import restore_through + + m0 = members[0] + for member in members: + if member.builder is not None: + member.builder.up_to_date() + gx = gy = gz = g = None + if need_values: + restored = restore_through( + points, m0.faults, block=block, restored_through=restored_through, owner=m0 + ) + out = [None, None, None] + for i, member in enumerate(members): + if i == 0 and not need_gx: + continue + v = np.full(points.shape[0], np.nan) + mask = member._calculate_mask( + points, block=block, restored_through=restored_through + ) + v[mask] = member.interpolator.evaluate_value(restored[mask, :]) + out[i] = v + gx, gy, gz = out + if need_gradient: + # The old gradient of a member with faults uses tetrahedra, so it keeps its own calls. + kwargs = block_kwargs(block) + if restored_through: + kwargs["restored_through"] = tuple(restored_through) + g = members[1].evaluate_gradient(points, ignore_regions=True, **kwargs) + return gx, gy, gz, g + 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. diff --git a/LoopStructural/utils/_fault_block.py b/LoopStructural/utils/_fault_block.py index b3b4e711f..37a043244 100644 --- a/LoopStructural/utils/_fault_block.py +++ b/LoopStructural/utils/_fault_block.py @@ -207,7 +207,54 @@ def cutters_first(faults: Iterable) -> list: return ordered -def restore_through(points, faults, *, reverse=False, block=None, restored_through=()): +def restore_order(faults: Iterable, *, reverse: bool = False, owner: object = None) -> list: + """Give the faults in the order to restore through them. + + The list holds the faults and the faults that cut them (see with_cutters), + with each cutting fault before the fault it cuts. When ``reverse`` is true + the cutting fault comes last. The returned list can be kept in the cache of + ``owner``: do not change it in place. + + Parameters + ---------- + faults : iterable of FaultSegment + faults in the order to apply them + reverse : bool + order for a forward movement of the points + owner : object, optional + object that keeps the last order in its attribute ``_restore_order``. + The order is computed again only when the faults, their cutters or + ``reverse`` change. + + Returns + ------- + list + the faults in the order to restore through them + """ + chain = with_cutters(faults) + if owner is None: + key = None + else: + key = (bool(reverse), tuple((id(f), tuple(id(c) for c in _cutters(f))) for f in chain)) + cached = getattr(owner, "_restore_order", None) + if cached is not None and cached[0] == key: + return cached[2] + # Forward movement: a cutting fault moves after the faults it cuts. Without + # such relations the order of the list does not change. + ordered = cutters_first(chain[::-1])[::-1] if reverse else cutters_first(chain) + if owner is not None: + try: + # One assignment: the key, the chain and the order stay together. + # The chain keeps the faults alive, so their ids stay unique. + owner._restore_order = (key, chain, ordered) + except AttributeError: + pass + return ordered + + +def restore_through( + points, faults, *, reverse=False, block=None, restored_through=(), owner: object = None +): """Restore points through a list of faults, each fault once. The faults are applied in the order of the list (a feature keeps its @@ -231,6 +278,8 @@ def restore_through(points, faults, *, reverse=False, block=None, restored_throu checked fault block restored_through : sequence of FaultSegment faults whose restoration the points already have; they are skipped + owner : object, optional + object that keeps the order of the faults (see restore_order) Returns ------- @@ -239,13 +288,7 @@ def restore_through(points, faults, *, reverse=False, block=None, restored_throu """ done = list(restored_through) # The chain of cutting faults is restored too (see with_cutters). - faults = with_cutters(faults) - if reverse: - # Forward movement: a cutting fault moves after the faults it cuts. Without - # such relations the order of the list does not change. - ordered = cutters_first(faults[::-1])[::-1] - else: - ordered = cutters_first(faults) + ordered = restore_order(faults, reverse=reverse, owner=owner) for fault in ordered: if is_in(fault, done): continue diff --git a/ROADMAP.md b/ROADMAP.md index 7e664cc07..d72bf7e90 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -172,6 +172,27 @@ One class now lives in `loop_common`. `LoopStructural.utils` re-exports it. This reverses item 2c-5 of the stage sequence, which was closed as deferred. The notice is in `COMPAT.md`. +### Native fault application (spec 007) +Decision date: 2026-11-27 (spec 007, FR-015). + +The native path is an optional Rust kernel in the package `loop-model-core` (module +`loop_model_core`), separate from the solver core `loop_interpolation_core`. +The Python path stays the reference and the fallback. +The `uv.lock` of the repository needs a new lock on master to include `loop-model-core` (spec 007 plan, Answers, T038). + +The native path is on by default when the kernel is installed and +`FAULT_KERNEL_VERSION` matches. To turn it off, set +`LoopStructuralConfig.native_faults = False` or the environment variable +`LOOPSTRUCTURAL_NATIVE_FAULTS=0`. The setting wins over the environment +variable. + +The tolerance is 1e-8 times the model box (spec 003 FR-004). + +The stages are: S1 computes the restore order once. S2 is the native restore. S3 +gives the native values and gradients. S4 builds the wheels. + +See `specs/007-native-fault-kernel/spec.md`. + ## Stage sequence - [x] **Stage 0 — Planning infra.** This file, release/versioning/compat @@ -926,3 +947,8 @@ deferred. The notice is in `COMPAT.md`. `packages/loop_link` exist (`specs/006-loop-link`). The package is new. - **2026-11-07:** Stage 7 stage S5 implemented: tool connection, select, read selection, fetch and round trip in `packages/loop_link`. - **2026-11-09:** Stage 7 stage S4 implemented: filter and colour calls, colour in `send` and the fake commands endpoint in `packages/loop_link`. +- **2026-11-27:** spec 007 S1: restore order computed once for each state of the faults (`restore_order`). SC-001 (94 faults, 500 points, mean time of a cutting fault): 39.1 ms before S1; 13.6 ms after D1a (order cache); 10.7 ms after D1b (one shared restoration for the members of a cut frame). Target is 10 ms, so SC-001 fails by a small margin. D1b: used. +- **2026-11-27:** spec 007 S2: native fault restoration in `loop_interpolation_core` (`FaultChain`, `FAULT_KERNEL_VERSION = 1`). SC-002 (1 thread, 10 000 points, native time / Python time, target 0.20 or less): fails. The 5 golden models give 0.23 to 0.30. The native restore is 3.3 to 4.3 times faster than Python on 1 thread. SC-003 (20 threads, target 0.03 or less): passes, 0.022 to 0.028 for all 5 models. SC-007 (10 million points, extra memory): passes, native 685 MB and Python 6430 MB. Largest native difference on the golden models: 9.3e-10 m (plugin, 3e-14 of the box); tolerance 1e-8 x box. +- **2026-11-27:** spec 007 S3: native field values and gradients (`GridField`, `FaultChain.feature_gradient`). SC-004 (94 faults, `evaluate_model` at 5000 points, target 0.5 s or less): passes, 0.059 s with the native path (Python 0.971 s in the same run; 2.09 s on master before spec 007). SC-005 (golden tests with the native path on): passes, 23 of 23. Largest native difference of the field values and gradients: 1.16e-10. Supported features evaluate values, grid gradients and the gradient of a faulted feature (tetrahedron method) natively. A fold feature on a tetrahedral mesh keeps the Python path. +- **2026-11-27:** spec 007 S4: prebuilt native packages with the fault kernel. SC-008: Linux x86_64 checked locally (wheel, clean install, smoke test and golden tests pass); Linux aarch64, macOS arm64 and Windows x64 need a CI run of `core-wheels.yml`; macOS x86_64 needs a maintainer check. SC-006: the full suite passes with the native path on (3341 passed), off (3341 passed) and not installed (3296 passed). One known failure with the core installed, `test_the_native_fault_frame_is_the_cg_fault_frame`, is also on master. Ruff: no new errors. +- **2026-11-27:** spec 007 S5: the fault kernel moves to the new package `loop-model-core`, with its own wheels and release; a negative `native_threads` means all cores; subclasses of the supported fault types use the Python path. diff --git a/benchmarks/fault_evaluation/many_faults.py b/benchmarks/fault_evaluation/many_faults.py new file mode 100644 index 000000000..1af23f9e5 --- /dev/null +++ b/benchmarks/fault_evaluation/many_faults.py @@ -0,0 +1,325 @@ +"""The 94-fault model of spec 007 (SC-001, SC-004): build it, time it, check its results. + +Usage:: + + python -m benchmarks.fault_evaluation.many_faults --output RESULT.json \ + [--save-reference REF.npz | --compare REF.npz] [--points 500 2000 5000] + +The model is deterministic (seed 100): 54 isolated faults in the east of a +10 x 10 x 3 km box, 40 long faults of two crossing strike families in the west +(each cut by at most its 3 youngest crossing faults; chains up to 20 deep), and +two stratigraphic groups with one unconformity. The build solves every +interpolator and takes about 7 minutes, so this is a local benchmark only: it +is not part of the standard suite and no test builds the model. + +The result holds, for each point count, the ``evaluate_model`` time and fault +calls, and the mean time of one isolated and one cutting fault (outermost +``apply_to_points`` calls only). ``--save-reference`` stores the model ids and +the values of each group; ``--compare`` checks them bit for bit (SC-001). +""" + +# ruff: noqa: ANN001, ANN002, ANN003, ANN201, ANN202, ANN204, D103 (a measurement script) + +from __future__ import annotations + +import argparse +import json +import logging +import time +from pathlib import Path + +import numpy as np +import pandas as pd + +from LoopStructural import GeologicalModel +from LoopStructural.modelling.core.stratigraphic_column import StratigraphicColumn +from LoopStructural.modelling.features.fault._fault_segment import FaultSegment + +SEED = 100 +ORIGIN = np.array([0.0, 0.0, -3000.0]) +MAXIMUM = np.array([10000.0, 10000.0, 0.0]) +MAX_CUTTERS = 3 # each fault is cut by at most its 3 youngest crossing faults +GROUPS = ("group_1", "group_0") + + +def _unit(v): + v = np.asarray(v, float) + return v / np.linalg.norm(v) + + +def _plane(dip_direction, dip): + dd, d = np.radians(dip_direction), np.radians(dip) + normal = [np.sin(d) * np.sin(dd), np.sin(d) * np.cos(dd), np.cos(d)] + down_dip = [np.cos(d) * np.sin(dd), np.cos(d) * np.cos(dd), -np.sin(d)] + strike = [np.sin(dd - np.pi / 2), np.cos(dd - np.pi / 2), 0.0] + return _unit(normal), _unit(down_dip), _unit(strike) + + +def _traces_cross(a, b, buffer): + """Two traces (centre, strike, half length) cross or come within ``buffer``.""" + pa, da, la = a + pb, db, lb = b + samples_a = pa + np.linspace(-la, la, 60)[:, None] * da + samples_b = pb + np.linspace(-lb, lb, 60)[:, None] * db + dist = np.linalg.norm(samples_a[:, None, :] - samples_b[None, :, :], axis=2) + return bool(dist.min() < buffer) + + +def fault_specs(n_isolated=60, n_long=40): + """Return the faults, youngest first. ``cut_by`` holds the indices of the cutting faults.""" + rng = np.random.default_rng(SEED) + specs = [] + for i in range(n_long): + dip_direction = (120.0 if i % 2 == 0 else 30.0) + rng.normal(0, 8) + dip = rng.uniform(60, 75) + centre = np.array([rng.uniform(1800, 3200), rng.uniform(2000, 8000), -1500.0]) + specs.append( + dict( + kind="cutting", + dip_direction=dip_direction, + dip=dip, + centre=centre, + half_length=rng.uniform(1200, 1900), + displacement=rng.uniform(40, 120), + ) + ) + # Isolated faults on a jittered 6 x 13 grid of 700 m cells from x = 5600. + cells = [(i, j) for i in range(6) for j in range(13)] + rng.shuffle(cells) + for i, j in cells: + if sum(s["kind"] == "isolated" for s in specs) == n_isolated: + break + centre = np.array( + [5600 + i * 700 + rng.uniform(-80, 80), 350 + j * 700 + rng.uniform(-80, 80), -1500.0] + ) + specs.append( + dict( + kind="isolated", + dip_direction=rng.uniform(0, 360), + dip=rng.uniform(55, 85), + centre=centre, + half_length=rng.uniform(150, 250), + displacement=rng.uniform(10, 30), + ) + ) + for s in specs: + s["normal"], s["slip"], s["strike"] = _plane(s["dip_direction"], s["dip"]) + s["major_axis"] = s["half_length"] + s["intermediate_axis"] = 1500.0 if s["kind"] == "cutting" else 600.0 + s["minor_axis"] = s["displacement"] * 6 + traces = [(s["centre"][:2], s["strike"][:2], s["half_length"]) for s in specs] + # Drop the isolated faults that touch any other fault. + keep = [ + k + for k, s in enumerate(specs) + if s["kind"] != "isolated" + or not any( + _traces_cross(traces[k], traces[m], s["minor_axis"] + specs[m]["minor_axis"]) + for m in range(len(specs)) + if m != k + ) + ] + specs = [specs[k] for k in keep] + traces = [traces[k] for k in keep] + # Index 0 is the youngest. A younger cutting fault that crosses an older one cuts it. + for k, s in enumerate(specs): + s["name"] = f"fault_{k:03d}" + s["cut_by"] = [] + if s["kind"] == "cutting": + s["cut_by"] = [ + m + for m in range(k) + if specs[m]["kind"] == "cutting" and _traces_cross(traces[k], traces[m], 200.0) + ][-MAX_CUTTERS:] + return specs + + +def _strat_data(): + rng = np.random.default_rng(SEED + 1) + rows = [] + for name, base, tilt in (("group_0", -2200.0, 0.02), ("group_1", -900.0, -0.03)): + for value in (0.0, 200.0, 400.0): + xy = rng.uniform(0, 10000, (80, 2)) + z = base + value + tilt * (xy[:, 0] - 5000) + rows += [ + {"X": x, "Y": y, "Z": zz, "val": value, "feature_name": name} + for (x, y), zz in zip(xy, z) + ] + rows.append( + {"X": 5000.0, "Y": 5000.0, "Z": base, "gx": -tilt, "gy": 0.0, "gz": 1.0, "feature_name": name} + ) + return pd.DataFrame(rows) + + +def _fault_data(specs): + """Three trace points (value 0) and the normal at the centre of each fault.""" + rows = [] + for s in specs: + for t in (-0.5, 0.0, 0.5): + x, y, z = s["centre"] + t * s["half_length"] * s["strike"] + rows.append({"X": x, "Y": y, "Z": z, "val": 0.0, "feature_name": s["name"]}) + x, y, z = s["centre"] + gx, gy, gz = s["normal"] + rows.append({"X": x, "Y": y, "Z": z, "gx": gx, "gy": gy, "gz": gz, "feature_name": s["name"]}) + return pd.DataFrame(rows) + + +def _set_column(model): + column = StratigraphicColumn() + column.clear(basement=False) + intervals = [] + for k in (0, 1): # oldest first + for name, low, high in ( + (f"unit_{k}_high", 300.0, 1e5), + (f"unit_{k}_mid", 100.0, 300.0), + (f"unit_{k}_low", -1e5, 100.0), + ): + intervals.append((column.add_unit(name, thickness=high - low), low, high)) + if k == 0: + column.add_unconformity("unconformity_1") + for unit, low, high in intervals: + unit.min_value, unit.max_value = low, high + column.group_mapping.update({"Group_0": "group_1", "Group_1": "group_0"}) + model.stratigraphic_column = column + + +def build(nelements=3000): + """Build and solve the model. Return the model and the fault specs.""" + specs = fault_specs() + model = GeologicalModel(ORIGIN, MAXIMUM) + model.data = pd.concat((_strat_data(), _fault_data(specs)), ignore_index=True) + created = {} + for k, s in enumerate(specs): + kwargs = dict( + fault_center=s["centre"], + fault_normal_vector=s["normal"], + fault_slip_vector=s["slip"], + major_axis=s["major_axis"], + minor_axis=s["minor_axis"], + intermediate_axis=s["intermediate_axis"], + nelements=nelements, + ) + if s["cut_by"]: + kwargs["faults"] = [created[m] for m in s["cut_by"]] + created[k] = model.create_and_add_fault(s["name"], s["displacement"], **kwargs) + young = model.create_and_add_foliation("group_1", nelements=nelements * 3) + model.add_unconformity(young, -900.0) + model.create_and_add_foliation("group_0", nelements=nelements * 3) + _set_column(model) + model.update() + return model, specs + + +def points(count): + return np.random.default_rng(1).uniform(ORIGIN, MAXIMUM, (count, 3)) + + +class _FaultTimer: + """Count every fault call and time the outermost ``apply_to_points`` call of each fault.""" + + def __init__(self): + self.calls, self.seconds, self._depth = {}, {}, 0 + self._original = FaultSegment.apply_to_points + + def __enter__(self): + timer, original = self, self._original + + def timed(fault, *args, **kwargs): + timer._depth += 1 + start = time.perf_counter() + try: + return original(fault, *args, **kwargs) + finally: + timer._depth -= 1 + timer.calls[fault.name] = timer.calls.get(fault.name, 0) + 1 + if timer._depth == 0: + elapsed = time.perf_counter() - start + timer.seconds[fault.name] = timer.seconds.get(fault.name, 0.0) + elapsed + + FaultSegment.apply_to_points = timed + return self + + def __exit__(self, *exc): + FaultSegment.apply_to_points = self._original + + +def _fault_summary(per): + """Mean and max fault times in ms; None when no Python fault call was timed (native path).""" + + def mean(values): + return float(np.mean(values)) if values else None + + return dict( + isolated_mean_ms=mean(per["isolated"]), + cutting_mean_ms=mean(per["cutting"]), + cutting_max_ms=float(np.max(per["cutting"])) if per["cutting"] else None, + ) + + +def measure(model, specs, counts): + kind = {s["name"]: s["kind"] for s in specs} + result, arrays = {}, {} + for n in counts: + xyz = points(n) + with _FaultTimer() as timer: + start = time.perf_counter() + ids = model.evaluate_model(xyz) + seconds = time.perf_counter() - start + per = {"isolated": [], "cutting": []} + for name, value in timer.seconds.items(): + per[kind[name]].append(1000 * value) + result[str(n)] = dict( + evaluate_model_seconds=seconds, + fault_calls=sum(timer.calls.values()), + **_fault_summary(per), + ) + arrays[f"model_ids_{n}"] = np.asarray(ids) + for group in GROUPS: + arrays[f"{group}_{n}"] = model.evaluate_feature_value(group, xyz) + print(f"{n:6d} points: {seconds:6.2f} s, {result[str(n)]}", flush=True) + return result, arrays + + +def compare(arrays, reference_path): + """Return the names of the arrays that differ from the reference (NaN equals NaN).""" + with np.load(reference_path) as reference: + names = sorted(set(reference.files) | set(arrays)) + return [ + name + for name in names + if name not in reference.files + or name not in arrays + or not np.array_equal(reference[name], arrays[name], equal_nan=True) + ] + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--points", type=int, nargs="+", default=[500, 2000, 5000]) + group = parser.add_mutually_exclusive_group() + group.add_argument("--save-reference", type=Path) + group.add_argument("--compare", type=Path) + options = parser.parse_args(argv) + logging.disable(logging.WARNING) + start = time.perf_counter() + model, specs = build() + result = dict( + faults=len(specs), + isolated=sum(s["kind"] == "isolated" for s in specs), + cutting=sum(s["kind"] == "cutting" for s in specs), + build_seconds=time.perf_counter() - start, + ) + print(f"built {result['faults']} faults in {result['build_seconds']:.0f} s", flush=True) + result["cases"], arrays = measure(model, specs, options.points) + if options.save_reference: + np.savez_compressed(options.save_reference, **arrays) + if options.compare: + result["differences"] = compare(arrays, options.compare) + print("bit-identical" if not result["differences"] else f"differ: {result['differences']}") + options.output.write_text(json.dumps(result, indent=1), encoding="utf8") + return 1 if result.get("differences") else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/benchmarks/fault_evaluation/run.py b/benchmarks/fault_evaluation/run.py index f5bbdb64a..c6f464e81 100644 --- a/benchmarks/fault_evaluation/run.py +++ b/benchmarks/fault_evaluation/run.py @@ -22,6 +22,7 @@ from typing import Any from benchmarks.fault_evaluation.instrumentation import PeakMemory, rss_to_bytes +from LoopStructural import LoopStructuralConfig from tests.fault_evaluation.models import model_names SCHEMA_VERSION = 1 @@ -505,6 +506,7 @@ def _merge( passes: dict[str, dict[str, Any]], suite_wall_seconds: float | None = None, suite: str | None = None, + native_faults: str = "off", ) -> dict[str, Any]: """Combine the timing, counter and memory passes by case id.""" counters = {row["case_id"]: row for row in passes["counters"]["cases"]} @@ -532,6 +534,8 @@ def _merge( result["suite_wall_seconds"] = suite_wall_seconds if suite is not None: result["suite"] = suite + # The suite value stays a string. Other tools compare it with "standard". + result["native_faults"] = native_faults return result @@ -600,9 +604,19 @@ def main(argv: list[str] | None = None) -> int: default="standard", help="Cases to run: the standard suite (default) or the full suite.", ) + parser.add_argument( + "--native-faults", + choices=("on", "off"), + default="off", + help="Use the native fault kernel (on) or the Python path (off, default).", + ) options = parser.parse_args(argv) if options.rounds < 1: parser.error("--rounds must be at least 1") + # The class attribute serves in-process use. The environment variable reaches the + # fresh subprocesses of each pass. + LoopStructuralConfig.native_faults = options.native_faults == "on" + os.environ["LOOPSTRUCTURAL_NATIVE_FAULTS"] = "1" if options.native_faults == "on" else "0" work_dir = options.work_dir or options.output.with_name(options.output.name + ".work") # The work directory and the output file are not changes of the code. _set_dirty_excludes(work_dir, options.output) @@ -631,6 +645,7 @@ def main(argv: list[str] | None = None) -> int: passes, suite_wall_seconds=float(sum(meta["wall_seconds"].values())), suite=options.suite, + native_faults=options.native_faults, ) validate_result(result) options.output.parent.mkdir(parents=True, exist_ok=True) diff --git a/packages/loop_interpolation_core/README.md b/packages/loop_interpolation_core/README.md index ac3df2b0f..d0917d2e4 100644 --- a/packages/loop_interpolation_core/README.md +++ b/packages/loop_interpolation_core/README.md @@ -134,3 +134,7 @@ npm --prefix packages/loop_interpolation_core/tests_web test ## Source Source: loop-rs crates/interpolation-fd, commit bff51342da8ebff7ca3c87e07c1d4fbd31279c8b, branch lachlan/drillhole + +## Fault kernel + +The fault kernel is in the package `packages/loop_model_core`. diff --git a/packages/loop_model_core/Cargo.lock b/packages/loop_model_core/Cargo.lock new file mode 100644 index 000000000..3d51c6f05 --- /dev/null +++ b/packages/loop_model_core/Cargo.lock @@ -0,0 +1,280 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "loop-model-core" +version = "0.0.0" +dependencies = [ + "numpy", + "pyo3", + "rayon", +] + +[[package]] +name = "matrixmultiply" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" +dependencies = [ + "autocfg", + "rawpointer", +] + +[[package]] +name = "ndarray" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" +dependencies = [ + "matrixmultiply", + "num-complex", + "num-integer", + "num-traits", + "portable-atomic", + "portable-atomic-util", + "rawpointer", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "numpy" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a5b15d63a5ff39e378daed0e1340d3a5964703ea9712eb09a0dc66fade996f4" +dependencies = [ + "libc", + "ndarray", + "num-complex", + "num-integer", + "num-traits", + "pyo3", + "pyo3-build-config", + "rustc-hash", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pyo3" +version = "0.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "700d18fa267b73b9b521fd7e13580e2f446916f176cacee1ab63fcc8191f1655" +dependencies = [ + "libc", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", +] + +[[package]] +name = "pyo3-build-config" +version = "0.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b3fc0c4d08f6bb10e71fe39dfb9e2f59c6eb6854e22ec8092f50c69a4499adb" +dependencies = [ + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfc0b8e19df29aad7086cf977bb0c2a2f143e30567eb113e9cf72b62ca698330" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6100e8a4b5eba53afaa5ed078364851a0b2499c553a44c31026b929049b49dc6" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6143877a16e82b5a727b7127ff4cd86858a24a28d745d72f43e6f227c7b1bdb3" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "target-lexicon" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" diff --git a/packages/loop_model_core/Cargo.toml b/packages/loop_model_core/Cargo.toml new file mode 100644 index 000000000..c574f6d2d --- /dev/null +++ b/packages/loop_model_core/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "loop-model-core" +version = "0.0.0" +edition = "2024" + +[lib] +name = "loop_model_core" +crate-type = ["cdylib", "rlib"] + +[dependencies] +rayon = { version = "1.10", optional = true } +pyo3 = { version = "0.29", features = ["extension-module", "abi3-py39"], optional = true } +numpy = { version = "0.29", optional = true } + +[features] +default = [] +parallel = ["dep:rayon"] +python = ["dep:pyo3", "dep:numpy"] diff --git a/packages/loop_model_core/README.md b/packages/loop_model_core/README.md new file mode 100644 index 000000000..0a6f8cd77 --- /dev/null +++ b/packages/loop_model_core/README.md @@ -0,0 +1,25 @@ +# loop-model-core + +Native (Rust) model evaluation for LoopStructural. + +## Fault kernel + +The fault kernel restores points through the faults of a LoopStructural +feature. It also evaluates values and gradients. LoopStructural uses it +automatically. Install it with `pip install loopstructural[native]`. + +The kernel version is `FAULT_KERNEL_VERSION = 1`. If the version does not +match, LoopStructural logs one warning and uses the Python path. + +The classes are `FaultChain` (`restore`, `frame_value`, `feature_gradient`) +and `GridField` (`values`, `gradients`). + +The native path is on by default. The switch is +`LoopStructuralConfig.native_faults`. It wins over the environment variable +`LOOPSTRUCTURAL_NATIVE_FAULTS=0`. + +The kernel releases the Python GIL and uses a thread pool. Set +`LoopStructuralConfig.native_threads` to the thread count. `None` or `0` +uses all cores. + +For the spec dict, see [specs/007-native-fault-kernel/plan.md](../../specs/007-native-fault-kernel/plan.md) (D2b). diff --git a/packages/loop_model_core/pyproject.toml b/packages/loop_model_core/pyproject.toml new file mode 100644 index 000000000..b5db52d48 --- /dev/null +++ b/packages/loop_model_core/pyproject.toml @@ -0,0 +1,33 @@ +[build-system] +requires = ["maturin>=1,<2"] +build-backend = "maturin" + +[project] +name = "loop-model-core" +version = "0.0.0" +description = "Native (Rust) model evaluation for LoopStructural: fault restoration, field values and gradients" +readme = "README.md" +requires-python = ">=3.9" +dependencies = ["numpy"] +authors = [{ name = "Lachlan Grose", email = "lachlan.grose@monash.edu" }] +license = { text = "MIT" } +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Science/Research", + "Topic :: Scientific/Engineering :: Information Analysis", + "License :: OSI Approved :: MIT License", + "Operating System :: Microsoft :: Windows", + "Operating System :: POSIX :: Linux", + "Operating System :: MacOS", + "Programming Language :: Python :: 3", + "Programming Language :: Rust", +] + +[project.urls] +Documentation = "https://Loop3d.org/LoopStructural/" +"Bug Tracker" = "https://github.com/loop3d/loopstructural/issues" +"Source Code" = "https://github.com/loop3d/loopstructural" + +[tool.maturin] +features = ["python", "parallel"] +module-name = "loop_model_core" diff --git a/packages/loop_model_core/src/fault/gradient.rs b/packages/loop_model_core/src/fault/gradient.rs new file mode 100644 index 000000000..2d13ae8e1 --- /dev/null +++ b/packages/loop_model_core/src/fault/gradient.rs @@ -0,0 +1,183 @@ +//! Gradient of a faulted field. + +use super::nearest::KdTree; +use super::{FaultChain, GridField, Side}; + +type Tet = [[f64; 3]; 4]; + +/// Return the gradient of `field` at `points` after restore through `order`. +/// The second result is the number of points refined at least once. +#[allow(clippy::too_many_arguments)] +pub fn feature_gradient( + chain: &FaultChain, + field: &GridField, + points: &[[f64; 3]], + order: &[usize], + sides: &[Side], + restored: &[bool], + jumping: &[bool], + scale: f64, +) -> (Vec<[f64; 3]>, usize) { + feature_gradient_threads( + chain, field, points, order, sides, restored, jumping, scale, 1, + ) +} + +/// Same as `feature_gradient`. Use `threads` threads (0 is all cores) for the +/// work on each corner with the feature `parallel`; otherwise `threads` has no effect. +#[allow(clippy::too_many_arguments)] +pub fn feature_gradient_threads( + chain: &FaultChain, + field: &GridField, + points: &[[f64; 3]], + order: &[usize], + sides: &[Side], + restored: &[bool], + jumping: &[bool], + scale: f64, + threads: usize, +) -> (Vec<[f64; 3]>, usize) { + let mut tets: Vec = points.iter().map(|&p| tetrahedron(p, scale)).collect(); + let mut active: Vec = (0..points.len()).collect(); + active = straddling(chain, jumping, sides, &tets, &active, threads); + let count = active.len(); + let mut scale = scale; + for _ in 0..10 { + if active.is_empty() { + break; + } + scale *= 0.5; + for &i in &active { + tets[i] = tetrahedron(points[i], scale); + } + active = straddling(chain, jumping, sides, &tets, &active, threads); + } + let mut bad = vec![false; points.len()]; + for &i in &active { + bad[i] = true; + } + let grads = map(&tets, threads, |i, t| { + if bad[i] { + return [f64::NAN; 3]; + } + let v: [f64; 4] = std::array::from_fn(|c| { + field.value(chain.restore(order, t[c], false, sides, restored)) + }); + gradient_from_tetrahedron(t, &v) + }); + (grads, count) +} + +/// Run `f(index, item)` for each item, in order. Parallel with the feature `parallel`. +#[cfg(feature = "parallel")] +fn map( + items: &[T], + threads: usize, + f: impl Fn(usize, &T) -> R + Sync + Send, +) -> Vec { + use rayon::prelude::*; + super::pool::pool(threads) + .install(|| items.par_iter().enumerate().map(|(i, t)| f(i, t)).collect()) +} + +#[cfg(not(feature = "parallel"))] +fn map(items: &[T], _threads: usize, f: impl Fn(usize, &T) -> R) -> Vec { + items.iter().enumerate().map(|(i, t)| f(i, t)).collect() +} + +/// Return the regular tetrahedron of size `scale` around `p`. +fn tetrahedron(p: [f64; 3], scale: f64) -> Tet { + let a = (8.0f64 / 9.0).sqrt(); + let b = (2.0f64 / 9.0).sqrt(); + let c = (2.0f64 / 3.0).sqrt(); + let r = [ + [a, 0.0, -1.0 / 3.0], + [-b, c, -1.0 / 3.0], + [-b, -c, -1.0 / 3.0], + [0.0, 0.0, 1.0], + ]; + // The regular tetrahedron is scaled first, then moved to the centre. + std::array::from_fn(|i| std::array::from_fn(|k| p[k] + r[i][k] * scale)) +} + +/// Return the points (from `active`) whose tetrahedron has a fault between its corners. +fn straddling( + chain: &FaultChain, + jumping: &[bool], + sides: &[Side], + tets: &[Tet], + active: &[usize], + threads: usize, +) -> Vec { + let corners: Vec<[f64; 3]> = active.iter().flat_map(|&i| tets[i]).collect(); + let all_false = vec![false; chain.faults.len()]; + let mut out = vec![false; active.len()]; + for j in (0..jumping.len()).filter(|&j| jumping[j]) { + let cutters = &chain.faults[j].cutters; + let q = map(&corners, threads, |_, &c| { + chain.restore(cutters, c, false, sides, &all_false) + }); + let mut v = map(&corners, threads, |_, &c| { + chain.frame_value(j, 0, c, sides, &all_false) + }); + fill_nearest(&mut v, &q); + for (k, o) in out.iter_mut().enumerate() { + let s = &v[4 * k..4 * k + 4]; + *o |= !(s.iter().all(|&x| x > 0.0) || s.iter().all(|&x| x < 0.0)); + } + } + active + .iter() + .zip(out) + .filter(|(_, o)| *o) + .map(|(&i, _)| i) + .collect() +} + +/// Give each NaN value the value of the nearest known point of the same batch. +fn fill_nearest(v: &mut [f64], q: &[[f64; 3]]) { + let known: Vec = (0..v.len()).filter(|&i| !v[i].is_nan()).collect(); + let nan: Vec = (0..v.len()) + .filter(|&i| v[i].is_nan() && q[i].iter().all(|x| x.is_finite())) + .collect(); + if known.is_empty() || nan.is_empty() { + return; + } + let tree = KdTree::new(&known.iter().map(|&i| q[i]).collect::>()); + for i in nan { + v[i] = v[known[tree.nearest(q[i])]]; + } +} + +/// Return the gradient of the linear field with `value` at the corners of `t`. +fn gradient_from_tetrahedron(t: &Tet, value: &[f64; 4]) -> [f64; 3] { + // The rows of `e` are the edges from corner 0. + let e: [[f64; 3]; 3] = std::array::from_fn(|i| std::array::from_fn(|k| t[i + 1][k] - t[0][k])); + let inv = invert(&e); + // G = inv * I, with I the matrix of the corner differences. + let i_mat = [ + [-1.0, 1.0, 0.0, 0.0], + [-1.0, 0.0, 1.0, 0.0], + [-1.0, 0.0, 0.0, 1.0], + ]; + std::array::from_fn(|a| { + (0..4) + .map(|c| (0..3).map(|k| inv[a][k] * i_mat[k][c]).sum::() * value[c]) + .sum() + }) +} + +/// Return the inverse of a 3x3 matrix. A singular matrix gives NaN. +fn invert(m: &[[f64; 3]; 3]) -> [[f64; 3]; 3] { + let c = |a: usize, b: usize, c: usize, d: usize| m[a][b] * m[c][d] - m[a][d] * m[c][b]; + let adj = [ + [c(1, 1, 2, 2), -c(0, 1, 2, 2), c(0, 1, 1, 2)], + [-c(1, 0, 2, 2), c(0, 0, 2, 2), -c(0, 0, 1, 2)], + [c(1, 0, 2, 1), -c(0, 0, 2, 1), c(0, 0, 1, 1)], + ]; + let det = m[0][0] * adj[0][0] + m[0][1] * adj[1][0] + m[0][2] * adj[2][0]; + if det == 0.0 { + return [[f64::NAN; 3]; 3]; + } + adj.map(|r| r.map(|x| x / det)) +} diff --git a/packages/loop_model_core/src/fault/grid_field.rs b/packages/loop_model_core/src/fault/grid_field.rs new file mode 100644 index 000000000..47b3057d7 --- /dev/null +++ b/packages/loop_model_core/src/fault/grid_field.rs @@ -0,0 +1,151 @@ +//! A scalar field on a regular 3D grid. + +/// A scalar field on a regular 3D grid with trilinear interpolation. +#[derive(Debug, Clone)] +pub struct GridField { + /// The world position of the first grid node. + pub origin: [f64; 3], + /// The number of nodes along each axis. + pub nsteps: [usize; 3], + /// The distance between nodes along each axis. + pub step_vector: [f64; 3], + /// The origin of the local frame, if the grid has one. + pub local_origin: Option<[f64; 3]>, + /// The rotation from the world frame to the local frame, if the grid has one. + pub local_rotation: Option<[[f64; 3]; 3]>, + /// The node values. + pub values: Vec, +} + +impl GridField { + /// Return the field value at `p`. Return NaN outside the grid or for NaN input. + pub fn value(&self, p: [f64; 3]) -> f64 { + match self.lookup(p) { + Some((corners, t)) => { + let w = trilinear(t); + (0..8).map(|c| w[c] * self.values[corners[c]]).sum() + } + None => f64::NAN, + } + } + + /// Return the field gradient at `p`, in world axes. + /// Return NaN for NaN input. Return zero outside the grid (as the Python code does). + pub fn gradient(&self, p: [f64; 3]) -> [f64; 3] { + if p.iter().any(|v| v.is_nan()) { + return [f64::NAN; 3]; + } + let Some((corners, t)) = self.lookup(p) else { + return [0.0; 3]; + }; + let w = gradient_weights(t); + let mut g = [0.0; 3]; + for (axis, ga) in g.iter_mut().enumerate() { + *ga = (0..8) + .map(|c| w[axis][c] * self.values[corners[c]]) + .sum::() + / self.step_vector[axis]; + } + // Rotate the gradient from the local frame to the world frame (transpose of R). + match self.local_rotation { + Some(r) => std::array::from_fn(|i| (0..3).map(|j| r[j][i] * g[j]).sum()), + None => g, + } + } + + /// Find the 8 corner node indexes and the local cell coordinates of a world point. + /// Return None when the point is outside the grid or has a NaN coordinate. + fn lookup(&self, p: [f64; 3]) -> Option<([usize; 8], [f64; 3])> { + // World to local frame: R (p - local_origin). + let mut q = p; + if let Some(o) = self.local_origin { + q = std::array::from_fn(|i| p[i] - o[i]); + } + if let Some(r) = self.local_rotation { + q = std::array::from_fn(|i| (0..3).map(|j| r[i][j] * q[j]).sum()); + } + let mut cell = [0usize; 3]; + let mut t = [0.0; 3]; + for a in 0..3 { + let ncells = self.nsteps[a] - 1; + let max = self.origin[a] + ncells as f64 * self.step_vector[a]; + // The boundary has a small tolerance, as in the Python grid. + let tol = f64::EPSILON * 32.0 * (max - self.origin[a]).abs().max(1.0); + // The negated form is also false for NaN. + if !(q[a] >= self.origin[a] - tol && q[a] <= max + tol) { + return None; + } + let f = ((q[a] - self.origin[a]) / self.step_vector[a]).floor(); + // A point on the maximum boundary belongs to the last cell. + cell[a] = (f.max(0.0) as usize).min(ncells - 1); + let local = (q[a] - (self.origin[a] + self.step_vector[a] * cell[a] as f64)) + / self.step_vector[a]; + t[a] = local.clamp(0.0, 1.0); + } + let (nx, ny) = (self.nsteps[0], self.nsteps[1]); + let g = cell[0] + nx * cell[1] + nx * ny * cell[2]; + let offsets = [ + 0, + 1, + nx, + nx + 1, + nx * ny, + nx * ny + 1, + nx * ny + nx, + nx * ny + nx + 1, + ]; + Some((offsets.map(|o| g + o), t)) + } +} + +/// Return the trilinear weights of the 8 cell corners (x runs fastest). +fn trilinear(t: [f64; 3]) -> [f64; 8] { + let [x, y, z] = t; + [ + (1.0 - x) * (1.0 - y) * (1.0 - z), + x * (1.0 - y) * (1.0 - z), + (1.0 - x) * y * (1.0 - z), + x * y * (1.0 - z), + (1.0 - x) * (1.0 - y) * z, + x * (1.0 - y) * z, + (1.0 - x) * y * z, + x * y * z, + ] +} + +/// Return the gradient weights of the 8 cell corners for each axis, in cell units. +fn gradient_weights(t: [f64; 3]) -> [[f64; 8]; 3] { + let [x, y, z] = t; + [ + [ + (1.0 - z) * (y - 1.0), + (1.0 - y) * (1.0 - z), + -y * (1.0 - z), + y * (1.0 - z), + -(1.0 - y) * z, + (1.0 - y) * z, + -y * z, + y * z, + ], + [ + (x - 1.0) * (1.0 - z), + -x * (1.0 - z), + (1.0 - x) * (1.0 - z), + x * (1.0 - z), + -(1.0 - x) * z, + -x * z, + (1.0 - x) * z, + x * z, + ], + [ + -(1.0 - x) * (1.0 - y), + -x * (1.0 - y), + -(1.0 - x) * y, + -x * y, + (1.0 - x) * (1.0 - y), + x * (1.0 - y), + (1.0 - x) * y, + x * y, + ], + ] +} diff --git a/packages/loop_model_core/src/fault/mod.rs b/packages/loop_model_core/src/fault/mod.rs new file mode 100644 index 000000000..365c54ac2 --- /dev/null +++ b/packages/loop_model_core/src/fault/mod.rs @@ -0,0 +1,78 @@ +//! Native fault kernel: restore and apply fault displacement to points. + +pub mod gradient; +pub mod grid_field; +pub mod nearest; +#[cfg(feature = "parallel")] +pub mod pool; +pub mod profile; +pub mod region; +pub mod restore; + +pub use grid_field::GridField; +pub use profile::{Profile, Profile1}; +pub use region::Region; + +/// A set of faults that act together on one model. +#[derive(Debug, Clone)] +pub struct FaultChain { + /// The faults of the chain. + pub faults: Vec, + /// The settings for the block displacement. + pub block: BlockSettings, +} + +/// One fault with its frame, cutters, regions and displacement profile. +#[derive(Debug, Clone)] +pub struct Fault { + /// The three frame coordinate fields. + pub frame: [GridField; 3], + /// The indices of the faults that cut this fault, in restore order. + pub cutters: Vec, + /// The regions where the fault is active: one list for each frame member. + /// A member has a value only where all regions of its own list contain the point. + pub regions: [Vec; 3], + /// The displacement profile of the fault. + pub profile: Profile, + /// The maximum displacement of the fault. + pub displacement: f64, + /// The number of steps in which the displacement is applied. + pub steps: usize, +} + +/// Settings for the displacement of the fault blocks. +#[derive(Debug, Clone)] +pub struct BlockSettings { + /// The small distance used to decide on which side of the fault a point is. + pub side_epsilon: f64, + /// The way in which the profile is continued outside its limits. + pub extension: Extension, + /// The value of the frame coordinate inside which the displacement is exact. + pub exact: f64, + /// The limit of the frame coordinate for the displacement. + pub limit: f64, + /// The step size for the continuation of the profile. + pub step: f64, +} + +/// The way in which a profile is continued outside its limits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Extension { + /// Continue the profile smoothly. + Smooth, + /// Mirror the profile. + Mirror, +} + +/// The side of a fault on which a point is forced to be. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Side { + /// No side is forced (Python 2). + Free, + /// The fault is absent (Python 0). + Absent, + /// The hanging wall (Python +1). + Hanging, + /// The foot wall (Python -1). + Foot, +} diff --git a/packages/loop_model_core/src/fault/nearest.rs b/packages/loop_model_core/src/fault/nearest.rs new file mode 100644 index 000000000..bef2f1939 --- /dev/null +++ b/packages/loop_model_core/src/fault/nearest.rs @@ -0,0 +1,95 @@ +//! Exact nearest-point search in 3D. + +/// A set of 3D points for nearest-point search. +/// +/// The tree is implicit. Each range of the arrays has its median point in the +/// middle. The two halves of the range are the two subtrees. +#[derive(Debug, Clone)] +pub struct KdTree { + /// The points, in tree order. + pts: Vec<[f64; 3]>, + /// The index in the input of each point of `pts`. + ids: Vec, + /// The split axis of each point of `pts`. + axes: Vec, +} + +fn build(pts: &mut [([f64; 3], usize)], axes: &mut [u8]) { + if pts.len() < 2 { + return; + } + // Split on the axis with the largest spread. + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for (p, _) in pts.iter() { + for k in 0..3 { + lo[k] = lo[k].min(p[k]); + hi[k] = hi[k].max(p[k]); + } + } + let mut axis = 0; + for k in 1..3 { + if hi[k] - lo[k] > hi[axis] - lo[axis] { + axis = k; + } + } + let mid = pts.len() / 2; + pts.select_nth_unstable_by(mid, |a, b| a.0[axis].total_cmp(&b.0[axis])); + axes[mid] = axis as u8; + let (pl, pr) = pts.split_at_mut(mid); + let (al, ar) = axes.split_at_mut(mid); + build(pl, al); + build(&mut pr[1..], &mut ar[1..]); +} + +impl KdTree { + /// Make a tree from `points`. + pub fn new(points: &[[f64; 3]]) -> KdTree { + let mut tmp: Vec<([f64; 3], usize)> = points + .iter() + .copied() + .enumerate() + .map(|(i, p)| (p, i)) + .collect(); + let mut axes = vec![0u8; tmp.len()]; + build(&mut tmp, &mut axes); + KdTree { + pts: tmp.iter().map(|t| t.0).collect(), + ids: tmp.iter().map(|t| t.1).collect(), + axes, + } + } + + /// Return the index of the point nearest to `p`. For equal distances, return the lowest index. + /// Return `usize::MAX` if the tree has no points. + pub fn nearest(&self, p: [f64; 3]) -> usize { + let mut best = (f64::INFINITY, usize::MAX); + self.search(0, self.pts.len(), p, &mut best); + best.1 + } + + fn search(&self, lo: usize, hi: usize, p: [f64; 3], best: &mut (f64, usize)) { + if lo >= hi { + return; + } + let mid = lo + (hi - lo) / 2; + let q = self.pts[mid]; + let d = (0..3).map(|k| (q[k] - p[k]) * (q[k] - p[k])).sum::(); + // A NaN query gives no `<` match: the first point is kept. + if d < best.0 || (d == best.0 && self.ids[mid] < best.1) || best.1 == usize::MAX { + *best = (d, self.ids[mid]); + } + let axis = self.axes[mid] as usize; + let diff = p[axis] - q[axis]; + let (near, far) = if diff < 0.0 { + ((lo, mid), (mid + 1, hi)) + } else { + ((mid + 1, hi), (lo, mid)) + }; + self.search(near.0, near.1, p, best); + // Strict `>`: an equal-distance point with a lower index must stay reachable. + if diff * diff <= best.0 { + self.search(far.0, far.1, p, best); + } + } +} diff --git a/packages/loop_model_core/src/fault/pool.rs b/packages/loop_model_core/src/fault/pool.rs new file mode 100644 index 000000000..30ba13e79 --- /dev/null +++ b/packages/loop_model_core/src/fault/pool.rs @@ -0,0 +1,26 @@ +//! Thread pools for the fault kernel. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; + +static POOLS: OnceLock>>> = OnceLock::new(); + +/// Return the thread pool for `threads` threads. Zero means all cores. +/// The function keeps one pool for each thread count. +pub fn pool(threads: usize) -> Arc { + let mut pools = POOLS + .get_or_init(Default::default) + .lock() + .unwrap_or_else(|e| e.into_inner()); + pools + .entry(threads) + .or_insert_with(|| { + Arc::new( + rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build() + .expect("cannot build the thread pool"), + ) + }) + .clone() +} diff --git a/packages/loop_model_core/src/fault/profile.rs b/packages/loop_model_core/src/fault/profile.rs new file mode 100644 index 000000000..ca2a0b8e7 --- /dev/null +++ b/packages/loop_model_core/src/fault/profile.rs @@ -0,0 +1,184 @@ +//! Displacement profiles of a fault. + +use super::{BlockSettings, Extension, Side}; + +/// A one-dimensional displacement profile. +#[derive(Debug, Clone)] +pub enum Profile1 { + /// The value is always one. + Ones, + /// The value is always zero. + Zeros, + /// A smooth peak function. + SmoothPeak, + /// A cubic function with limits. + Cubic { + /// The cubic coefficients. + w: [f64; 4], + /// The lower and upper limit of the input. + lim: [f64; 2], + /// The minimum output value. + min: f64, + /// The maximum output value. + max: f64, + /// The points (input, value) that define the function. + value_points: Vec<(f64, f64)>, + }, + /// One profile for positive input and one for negative input. + Composite { + /// The profile for positive input. + positive: Box, + /// The profile for negative input. + negative: Box, + }, +} + +impl Profile1 { + /// Return the value of the profile at `v`. + pub fn eval(&self, v: f64) -> f64 { + match self { + Profile1::Ones => 1.0, + Profile1::Zeros => 0.0, + Profile1::SmoothPeak => { + if (-1.0..=1.0).contains(&v) { + v.powi(4) - 2.0 * v.powi(2) + 1.0 + } else { + 0.0 + } + } + Profile1::Cubic { + w, + lim, + min, + max, + value_points, + } => { + let limit_value = |x: f64| { + value_points + .iter() + .find(|p| p.0 == x) + .map_or_else(|| cubic(w, x), |p| p.1) + }; + let mut e = cubic(w, v); + if v >= lim[1] { + e = limit_value(lim[1]); + } + if v <= lim[0] { + e = limit_value(lim[0]); + } + if e > *max { + e = *max; + } + if e < *min { + e = *min; + } + e + } + Profile1::Composite { positive, negative } => { + if v > 0.0 { + positive.eval(v) + } else if v < 0.0 { + negative.eval(v) + } else { + 0.0 + } + } + } + } +} + +fn cubic(w: &[f64; 4], v: f64) -> f64 { + w[0] * v.powi(3) + w[1] * v.powi(2) + w[2] * v + w[3] +} + +/// Limit a distance from the fault: the identity up to `exact`, constant +/// beyond `limit`, and C2 in between. +fn saturate(distance: f64, block: &BlockSettings) -> f64 { + let length = block.limit - block.exact; + let t = ((distance - block.exact) / length).clamp(0.0, 1.0); + distance.min(block.exact) + length * (t - t.powi(3) + 0.5 * t.powi(4)) +} + +/// Second-order expansion of `f` at the fault, seen from the side `side`. +fn taylor(f: impl Fn(f64) -> f64, x: f64, side: f64, block: &BlockSettings) -> f64 { + let h = block.step; + let x0 = side * block.side_epsilon; + let k = |i: f64| f(x0 + side * i * h); + let (f0, f1, f2, f3, f4, f5) = (k(0.0), k(1.0), k(2.0), k(3.0), k(4.0), k(5.0)); + let slope = side * (-25.0 * f0 + 48.0 * f1 - 36.0 * f2 + 16.0 * f3 - 3.0 * f4) / (12.0 * h); + let curvature = + (45.0 * f0 - 154.0 * f1 + 214.0 * f2 - 156.0 * f3 + 61.0 * f4 - 10.0 * f5) / (12.0 * h * h); + f0 + slope * (x - x0) + 0.5 * curvature * (x - x0) * (x - x0) +} + +/// Continue the profile of the side `side` to the other side of the fault. +fn continue_profile(profile: &Profile1, x: f64, side: f64, block: &BlockSettings) -> f64 { + match profile { + Profile1::Ones | Profile1::Zeros => return profile.eval(x), + _ => {} + } + let x = -side * saturate(x.abs(), block); + if let Profile1::Cubic { w, .. } = profile { + // The cubic is the profile at the fault unless a limit, a floor or a ceiling acts there. + let near = [side * block.side_epsilon, side * block.step]; + if near + .iter() + .all(|&n| (profile.eval(n) - cubic(w, n)).abs() <= 1e-12) + { + return cubic(w, x); + } + } + taylor(|v| profile.eval(v), x, side, block) +} + +/// The displacement profile of a fault in the three frame coordinates. +#[derive(Debug, Clone)] +pub struct Profile { + /// The scale of the displacement. + pub scale: f64, + /// The profile along frame coordinate 0. + pub gx: Profile1, + /// The profile along frame coordinate 1. + pub gy: Profile1, + /// The profile along frame coordinate 2. + pub gz: Profile1, +} + +impl Profile { + /// Return the displacement for the frame coordinates `gx`, `gy` and `gz`. + pub fn eval(&self, gx: f64, gy: f64, gz: f64) -> f64 { + self.scale * self.gx.eval(gx) * self.gy.eval(gy) * self.gz.eval(gz) + } + + /// Return the displacement of a block point, with `forced_gx` as the forced + /// value of frame coordinate 0 for the given `side`. + pub fn block_displacement( + &self, + gx: f64, + forced_gx: f64, + gy: f64, + gz: f64, + side: Side, + block: &BlockSettings, + ) -> f64 { + let s = match side { + Side::Hanging => 1.0, + Side::Foot => -1.0, + _ => return self.eval(forced_gx, gy, gz), + }; + if block.extension != Extension::Smooth || s * gx >= 0.0 { + return self.eval(forced_gx, gy, gz); + } + let part = match &self.gx { + Profile1::Composite { positive, negative } => { + if s > 0.0 { + positive + } else { + negative + } + } + other => other, + }; + self.scale * continue_profile(part, gx, s, block) * self.gy.eval(gy) * self.gz.eval(gz) + } +} diff --git a/packages/loop_model_core/src/fault/region.rs b/packages/loop_model_core/src/fault/region.rs new file mode 100644 index 000000000..d40daab12 --- /dev/null +++ b/packages/loop_model_core/src/fault/region.rs @@ -0,0 +1,87 @@ +//! Regions in which a fault is active. + +use super::restore::force_side; +use super::{FaultChain, GridField, Side}; + +/// A region of space in which a fault is active. +#[derive(Debug, Clone)] +pub enum Region { + /// The positive or negative side of a fault. + Sign { + /// True for the positive side. + positive: bool, + /// The index of the parent fault in the chain. + fault: usize, + /// The direction vector of the region, if any. + vector: Option<[f64; 3]>, + /// The reference point of the region, if any. + point: Option<[f64; 3]>, + }, + /// The side of an unconformity surface. + Unconformity { + /// The field of the unconformity. + field: GridField, + /// The indices of the faults that restore the point, in restore order. + faults: Vec, + /// The field value of the unconformity surface. + value: f64, + /// True if the region has field values at or below `value`. + sign: bool, + }, +} + +impl Region { + /// Return true if the point `p` is in the region. + pub fn contains( + &self, + chain: &FaultChain, + p: [f64; 3], + sides: &[Side], + restored: &[bool], + ) -> bool { + match self { + Region::Sign { + positive, + fault, + vector, + point, + } => { + // The builder always sets both. Without them the region has no side. + let (Some(v), Some(c)) = (vector, point) else { + return false; + }; + // A sign region does not take `restored`: the parent is read with no fault restored. + let heap; + let none: &[bool] = if restored.len() <= 64 { + &[false; 64][..restored.len()] + } else { + heap = vec![false; restored.len()]; + &heap + }; + let val = force_side( + chain.frame_value(*fault, 0, p, sides, none), + sides[*fault], + chain.block.side_epsilon, + ); + let distance = (0..3).map(|i| (c[i] - p[i]) * v[i]).sum::(); + let distance = force_side(distance, sides[*fault], chain.block.side_epsilon); + let (val_ok, dist_ok) = if *positive { + (val > 0.0, distance > 0.0) + } else { + (val < 0.0, distance < 0.0) + }; + if val.is_nan() { dist_ok } else { val_ok } + } + Region::Unconformity { + field, + faults, + value, + sign, + } => { + let q = chain.restore(faults, p, false, sides, restored); + let v = field.value(q); + if *sign { v <= *value } else { v >= *value } + } + } + } +} diff --git a/packages/loop_model_core/src/fault/restore.rs b/packages/loop_model_core/src/fault/restore.rs new file mode 100644 index 000000000..d0c64ad19 --- /dev/null +++ b/packages/loop_model_core/src/fault/restore.rs @@ -0,0 +1,228 @@ +//! Apply and restore fault displacement. + +use super::{FaultChain, Side}; + +/// Put the frame value `v` on the side `side` of the fault. NaN stays NaN. +/// A side other than the hanging wall or the foot wall gives `v` unchanged. +pub fn force_side(v: f64, side: Side, epsilon: f64) -> f64 { + let s = match side { + Side::Hanging => 1.0, + Side::Foot => -1.0, + _ => return v, + }; + if v.is_nan() { + v + } else { + s * v.abs().max(epsilon) + } +} + +impl FaultChain { + /// Move the point `p` through one fault. Use `reverse` to undo the displacement. + pub fn apply( + &self, + fault: usize, + p: [f64; 3], + reverse: bool, + sides: &[Side], + restored: &[bool], + ) -> [f64; 3] { + if sides[fault] == Side::Absent { + return p; + } + let f = &self.faults[fault]; + let sign = if reverse { -1.0 } else { 1.0 }; + let ([mut gx, mut gy, mut gz], mut q) = self.frame_values_at(fault, p, sides, restored); + let mut fraction = self.displacement_fraction(fault, [gx, gy, gz], sides); + // The mask uses the fraction before the displacement scale, as the Python code does. + if fraction.abs().partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) { + return p; + } + let mut p = p; + for step in 0..f.steps { + if step > 0 { + ([gx, gy, gz], q) = self.frame_values_at(fault, p, sides, restored); + fraction = self.displacement_fraction(fault, [gx, gy, gz], sides); + } + let mut g = f.frame[1].gradient(q); + // A cut frame has no single gradient on a cutting fault (#425): use the plain grid gradient. + if g.iter().any(|v| v.is_nan()) + && !p.iter().any(|v| v.is_nan()) + && !f.cutters.is_empty() + { + g = f.frame[1].gradient(p); + } + let ok = !(gx.is_nan() || gy.is_nan() || gz.is_nan()); + let d = fraction * f.displacement * sign; + let mag = if ok { + g.iter().map(|v| v * v).sum::().sqrt() + } else { + 0.0 + }; + if mag > 0.0 { + g = g.map(|v| v / mag); + } + let scale = (1.0 / f.steps as f64) * d; + for i in 0..3 { + p[i] += g[i] * scale; + } + } + p + } + + /// Move the point `p` through the faults in `order`. A fault that is already + /// restored is skipped, and each fault is marked done after it moves the point. + pub fn restore( + &self, + order: &[usize], + p: [f64; 3], + reverse: bool, + sides: &[Side], + restored: &[bool], + ) -> [f64; 3] { + // A chain of up to 64 faults uses a stack copy of `restored`: no allocation. + let mut stack = [false; 64]; + let mut heap; + let done: &mut [bool] = if restored.len() <= 64 { + let d = &mut stack[..restored.len()]; + d.copy_from_slice(restored); + d + } else { + heap = restored.to_vec(); + &mut heap + }; + let mut p = p; + for &f in order { + if done[f] { + continue; + } + p = self.apply(f, p, reverse, sides, done); + done[f] = true; + } + p + } + + /// Return one frame coordinate of a fault at `p`, with the region mask applied. + pub fn frame_value( + &self, + fault: usize, + coordinate: usize, + p: [f64; 3], + sides: &[Side], + restored: &[bool], + ) -> f64 { + self.frame_value_at(fault, coordinate, p, &mut None, sides, restored) + } + + /// As `frame_value`. `q` holds the frame point of `p` once it is known. + fn frame_value_at( + &self, + fault: usize, + coordinate: usize, + p: [f64; 3], + q: &mut Option<[f64; 3]>, + sides: &[Side], + restored: &[bool], + ) -> f64 { + let f = &self.faults[fault]; + if !f.regions[coordinate] + .iter() + .all(|r| r.contains(self, p, sides, restored)) + { + return f64::NAN; + } + let q = *q.get_or_insert_with(|| self.frame_point(fault, p, sides, restored)); + f.frame[coordinate].value(q) + } + + /// Move all points through the faults in `order`. Use `threads` threads + /// (0 is all cores) with the feature `parallel`; otherwise `threads` has no effect. + pub fn restore_batch( + &self, + order: &[usize], + points: &[[f64; 3]], + reverse: bool, + sides: &[Side], + restored: &[bool], + threads: usize, + ) -> Vec<[f64; 3]> { + self.batch(points, threads, |p| { + self.restore(order, p, reverse, sides, restored) + }) + } + + /// Return one frame coordinate of a fault at all points. + pub fn frame_value_batch( + &self, + fault: usize, + coordinate: usize, + points: &[[f64; 3]], + sides: &[Side], + restored: &[bool], + threads: usize, + ) -> Vec { + self.batch(points, threads, |p| { + self.frame_value(fault, coordinate, p, sides, restored) + }) + } + + #[cfg(feature = "parallel")] + fn batch( + &self, + points: &[[f64; 3]], + threads: usize, + f: impl Fn([f64; 3]) -> T + Sync + Send, + ) -> Vec { + use rayon::prelude::*; + super::pool::pool(threads).install(|| points.par_iter().map(|&p| f(p)).collect()) + } + + #[cfg(not(feature = "parallel"))] + fn batch(&self, points: &[[f64; 3]], _threads: usize, f: impl Fn([f64; 3]) -> T) -> Vec { + points.iter().map(|&p| f(p)).collect() + } + + /// Return the point at which the frame of `fault` is read: `p` restored + /// through the cutters that are not yet restored. + fn frame_point( + &self, + fault: usize, + p: [f64; 3], + sides: &[Side], + restored: &[bool], + ) -> [f64; 3] { + let cutters = &self.faults[fault].cutters; + if cutters.iter().all(|&c| restored[c]) { + p + } else { + self.restore(cutters, p, false, sides, restored) + } + } + + /// Return the three frame coordinates of `fault` at `p` and the frame point of `p`. + fn frame_values_at( + &self, + fault: usize, + p: [f64; 3], + sides: &[Side], + restored: &[bool], + ) -> ([f64; 3], [f64; 3]) { + let mut q = None; + let g = std::array::from_fn(|i| self.frame_value_at(fault, i, p, &mut q, sides, restored)); + let q = q.unwrap_or_else(|| self.frame_point(fault, p, sides, restored)); + (g, q) + } + + /// Return the displacement at the frame coordinates as a fraction of the displacement. + /// Return zero if a coordinate is NaN. + fn displacement_fraction(&self, fault: usize, g: [f64; 3], sides: &[Side]) -> f64 { + let side = sides[fault]; + let forced = force_side(g[0], side, self.block.side_epsilon); + if forced.is_nan() || g[1].is_nan() || g[2].is_nan() { + return 0.0; + } + self.faults[fault] + .profile + .block_displacement(g[0], forced, g[1], g[2], side, &self.block) + } +} diff --git a/packages/loop_model_core/src/lib.rs b/packages/loop_model_core/src/lib.rs new file mode 100644 index 000000000..c55786042 --- /dev/null +++ b/packages/loop_model_core/src/lib.rs @@ -0,0 +1,6 @@ +//! Native model evaluation for LoopStructural: fault restoration, field values and gradients. + +pub mod fault; + +#[cfg(feature = "python")] +mod python; diff --git a/packages/loop_model_core/src/python.rs b/packages/loop_model_core/src/python.rs new file mode 100644 index 000000000..29090d584 --- /dev/null +++ b/packages/loop_model_core/src/python.rs @@ -0,0 +1,606 @@ +//! Python bindings (PyO3) for the fault kernel. Compiled only with the feature `python`. +//! +//! The module `loop_model_core` has two classes, `FaultChain` and `GridField`. + +use numpy::{PyArray1, PyArrayMethods, PyReadonlyArray1, PyReadonlyArray2, PyUntypedArrayMethods}; +use pyo3::exceptions::{PyRuntimeError, PyValueError}; +use pyo3::prelude::*; +use pyo3::types::PyDict; + +use crate::fault::{ + BlockSettings, Extension, Fault, FaultChain, GridField, Profile, Profile1, Region, Side, +}; + +// Fault kernel +// --------------------------------------------------------------------------- + +/// Make a `ValueError`. +fn bad(ctx: &str, msg: impl std::fmt::Display) -> PyErr { + PyValueError::new_err(format!("{ctx}: {msg}")) +} + +/// Cast a value to a dict, or raise `ValueError`. +fn as_dict<'a, 'py>(ctx: &str, v: &'a Bound<'py, PyAny>) -> PyResult<&'a Bound<'py, PyDict>> { + v.cast::().map_err(|_| bad(ctx, "must be a dict")) +} + +/// Get a key of a dict, or raise `ValueError`. A key that is not in `allowed` also raises. +fn fields<'py>( + ctx: &str, + d: &Bound<'py, PyDict>, + allowed: &[&str], +) -> PyResult>>> { + for k in d.keys() { + let key: String = k.extract().map_err(|_| bad(ctx, "keys must be text"))?; + if !allowed.contains(&key.as_str()) { + return Err(bad(ctx, format!("unknown key '{key}'"))); + } + } + allowed.iter().map(|k| d.get_item(*k)).collect() +} + +/// Get a required value from the result of `fields`. +fn need<'py>(ctx: &str, key: &str, v: &Option>) -> PyResult> { + v.clone() + .ok_or_else(|| bad(ctx, format!("missing key '{key}'"))) +} + +/// Read a float, a list of floats or a numpy array of floats. +fn floats(ctx: &str, key: &str, v: &Bound<'_, PyAny>) -> PyResult> { + if let Ok(a) = v.extract::>() { + return Ok(a.as_array().to_vec()); + } + v.extract::>() + .map_err(|_| bad(ctx, format!("'{key}' must be an array of numbers"))) +} + +/// Read a fixed number of floats. +fn fixed(ctx: &str, key: &str, v: &Bound<'_, PyAny>) -> PyResult<[f64; N]> { + <[f64; N]>::try_from(floats(ctx, key, v)?) + .map_err(|_| bad(ctx, format!("'{key}' must have {N} numbers"))) +} + +fn float(ctx: &str, key: &str, v: &Bound<'_, PyAny>) -> PyResult { + v.extract::() + .map_err(|_| bad(ctx, format!("'{key}' must be a number"))) +} + +fn index(ctx: &str, key: &str, v: &Bound<'_, PyAny>, nfaults: usize) -> PyResult { + match v.extract::() { + Ok(i) if i < nfaults => Ok(i), + _ => Err(bad( + ctx, + format!("'{key}' must be an integer below {nfaults}"), + )), + } +} + +fn indices(ctx: &str, key: &str, v: &Bound<'_, PyAny>, nfaults: usize) -> PyResult> { + let items: Vec> = v + .extract() + .map_err(|_| bad(ctx, format!("'{key}' must be a list of integers")))?; + items.iter().map(|i| index(ctx, key, i, nfaults)).collect() +} + +/// Read a grid dict. +fn parse_grid(ctx: &str, v: &Bound<'_, PyAny>) -> PyResult { + let d = fields( + ctx, + as_dict(ctx, v)?, + &[ + "origin", + "nsteps", + "step_vector", + "local_origin", + "local_rotation", + "values", + ], + )?; + let k = |i: usize, key: &str| need(ctx, key, &d[i]); + let origin = fixed::<3>(ctx, "origin", &k(0, "origin")?)?; + let nsteps: Vec = k(1, "nsteps")? + .extract() + .map_err(|_| bad(ctx, "'nsteps' must have 3 positive integers"))?; + let nsteps = <[usize; 3]>::try_from(nsteps) + .ok() + .filter(|n| n.iter().all(|&c| c >= 2)) + .ok_or_else(|| bad(ctx, "'nsteps' must have 3 integers of 2 or more"))?; + let step_vector = fixed::<3>(ctx, "step_vector", &k(2, "step_vector")?)?; + let local_origin = match &d[3] { + Some(v) if !v.is_none() => Some(fixed::<3>(ctx, "local_origin", v)?), + _ => None, + }; + let local_rotation = match &d[4] { + Some(v) if !v.is_none() => { + let flat: Vec = if let Ok(a) = v.extract::>() { + a.as_array().iter().copied().collect() + } else { + let rows: Vec> = v + .extract() + .map_err(|_| bad(ctx, "'local_rotation' must be a 3x3 matrix"))?; + rows.concat() + }; + if flat.len() != 9 { + return Err(bad(ctx, "'local_rotation' must be a 3x3 matrix")); + } + Some(std::array::from_fn(|i| { + std::array::from_fn(|j| flat[3 * i + j]) + })) + } + _ => None, + }; + let values = floats(ctx, "values", &k(5, "values")?)?; + if values.len() != nsteps.iter().product::() { + return Err(bad( + ctx, + format!( + "'values' has {} numbers; 'nsteps' needs {}", + values.len(), + nsteps.iter().product::() + ), + )); + } + Ok(GridField { + origin, + nsteps, + step_vector, + local_origin, + local_rotation, + values, + }) +} + +/// Read a profile part. +fn parse_part(ctx: &str, v: &Bound<'_, PyAny>) -> PyResult { + let dict = as_dict(ctx, v)?; + let kind: String = need(ctx, "kind", &dict.get_item("kind")?)? + .extract() + .map_err(|_| bad(ctx, "'kind' must be text"))?; + let allowed: &[&str] = match kind.as_str() { + "ones" | "zeros" | "smooth_peak" => &["kind"], + "cubic" => &["kind", "w", "lim", "min", "max", "value_points"], + "composite" => &["kind", "positive", "negative"], + other => return Err(bad(ctx, format!("unknown profile kind '{other}'"))), + }; + let d = fields(ctx, dict, allowed)?; + let k = |i: usize| need(ctx, allowed[i], &d[i]); + Ok(match kind.as_str() { + "ones" => Profile1::Ones, + "zeros" => Profile1::Zeros, + "smooth_peak" => Profile1::SmoothPeak, + "cubic" => { + let points: Vec<[f64; 2]> = k(5)? + .extract() + .map_err(|_| bad(ctx, "'value_points' must be a list of [x, y]"))?; + Profile1::Cubic { + w: fixed::<4>(ctx, "w", &k(1)?)?, + lim: fixed::<2>(ctx, "lim", &k(2)?)?, + min: float(ctx, "min", &k(3)?)?, + max: float(ctx, "max", &k(4)?)?, + value_points: points.iter().map(|p| (p[0], p[1])).collect(), + } + } + _ => Profile1::Composite { + positive: Box::new(parse_part(ctx, &k(1)?)?), + negative: Box::new(parse_part(ctx, &k(2)?)?), + }, + }) +} + +/// Read a region dict. +fn parse_region(ctx: &str, v: &Bound<'_, PyAny>, nfaults: usize) -> PyResult { + let dict = as_dict(ctx, v)?; + let kind: String = need(ctx, "kind", &dict.get_item("kind")?)? + .extract() + .map_err(|_| bad(ctx, "'kind' must be text"))?; + match kind.as_str() { + "positive" | "negative" => { + let d = fields(ctx, dict, &["kind", "fault", "vector", "point"])?; + let opt = |i: usize, key: &str| match &d[i] { + Some(v) if !v.is_none() => fixed::<3>(ctx, key, v).map(Some), + _ => Ok(None), + }; + Ok(Region::Sign { + positive: kind == "positive", + fault: index(ctx, "fault", &need(ctx, "fault", &d[1])?, nfaults)?, + vector: opt(2, "vector")?, + point: opt(3, "point")?, + }) + } + "unconformity" => { + let d = fields(ctx, dict, &["kind", "field", "faults", "value", "sign"])?; + Ok(Region::Unconformity { + field: parse_grid(ctx, &need(ctx, "field", &d[1])?)?, + faults: indices(ctx, "faults", &need(ctx, "faults", &d[2])?, nfaults)?, + value: float(ctx, "value", &need(ctx, "value", &d[3])?)?, + sign: need(ctx, "sign", &d[4])? + .extract() + .map_err(|_| bad(ctx, "'sign' must be a bool"))?, + }) + } + other => Err(bad(ctx, format!("unknown region kind '{other}'"))), + } +} + +/// Read a fault dict. +fn parse_fault(i: usize, v: &Bound<'_, PyAny>, nfaults: usize) -> PyResult { + let probe = format!("faults[{i}]"); + let d = fields( + &probe, + as_dict(&probe, v)?, + &[ + "name", + "displacement", + "steps", + "frame", + "cutters", + "regions", + "profile", + ], + )?; + // The name is only for error messages. + let name: String = match &d[0] { + Some(n) => n + .extract() + .map_err(|_| bad(&probe, "'name' must be text"))?, + None => String::new(), + }; + let ctx = format!("fault {i} '{name}'"); + let k = |j: usize, key: &str| need(&ctx, key, &d[j]); + let frame: Vec> = k(3, "frame")? + .extract() + .map_err(|_| bad(&ctx, "'frame' must be a list of 3 grids"))?; + if frame.len() != 3 { + return Err(bad(&ctx, "'frame' must be a list of 3 grids")); + } + let grid = |j: usize| parse_grid(&format!("{ctx} key 'frame'[{j}]"), &frame[j]); + let frame = [grid(0)?, grid(1)?, grid(2)?]; + let rctx = format!("{ctx} key 'regions'"); + let lists: Vec>> = k(5, "regions")? + .extract() + .map_err(|_| bad(&rctx, "must be a list of 3 lists"))?; + if lists.len() != 3 { + return Err(bad(&rctx, "must be a list of 3 lists")); + } + let region = |j: usize| -> PyResult> { + lists[j] + .iter() + .map(|r| parse_region(&rctx, r, nfaults)) + .collect() + }; + let pctx = format!("{ctx} key 'profile'"); + let pd = fields( + &pctx, + as_dict(&pctx, &k(6, "profile")?)?, + &["scale", "gx", "gy", "gz"], + )?; + let part = |j: usize, key: &str| parse_part(&pctx, &need(&pctx, key, &pd[j])?); + let steps = k(2, "steps")? + .extract::() + .ok() + .filter(|&s| s > 0) + .ok_or_else(|| bad(&ctx, "'steps' must be a positive integer"))?; + Ok(Fault { + frame, + cutters: indices(&ctx, "cutters", &k(4, "cutters")?, nfaults)?, + regions: [region(0)?, region(1)?, region(2)?], + profile: Profile { + scale: float(&pctx, "scale", &need(&pctx, "scale", &pd[0])?)?, + gx: part(1, "gx")?, + gy: part(2, "gy")?, + gz: part(3, "gz")?, + }, + displacement: float(&ctx, "displacement", &k(1, "displacement")?)?, + steps, + }) +} + +/// Read the spec of a fault chain. +fn parse_chain(spec: &Bound<'_, PyAny>) -> PyResult { + let d = fields( + "spec", + as_dict("spec", spec)?, + &["version", "block", "faults"], + )?; + let version = need("spec", "version", &d[0])? + .extract::() + .map_err(|_| bad("spec", "'version' must be an integer"))?; + if version != 1 { + return Err(bad("spec", format!("unsupported version {version}; use 1"))); + } + let bctx = "spec key 'block'"; + let b = fields( + bctx, + as_dict(bctx, &need("spec", "block", &d[1])?)?, + &["side_epsilon", "extension", "exact", "limit", "step"], + )?; + let num = |i: usize, key: &str| float(bctx, key, &need(bctx, key, &b[i])?); + let extension = match need(bctx, "extension", &b[1])? + .extract::() + .as_deref() + { + Ok("smooth") => Extension::Smooth, + Ok("mirror") => Extension::Mirror, + _ => return Err(bad(bctx, "'extension' must be \"smooth\" or \"mirror\"")), + }; + let block = BlockSettings { + side_epsilon: num(0, "side_epsilon")?, + extension, + exact: num(2, "exact")?, + limit: num(3, "limit")?, + step: num(4, "step")?, + }; + let items: Vec> = need("spec", "faults", &d[2])? + .extract() + .map_err(|_| bad("spec", "'faults' must be a list"))?; + let faults = items + .iter() + .enumerate() + .map(|(i, f)| parse_fault(i, f, items.len())) + .collect::>>()?; + Ok(FaultChain { faults, block }) +} + +/// Copy an (N, 3) float64 array. +fn read_points(points: &PyReadonlyArray2<'_, f64>) -> PyResult> { + if points.shape()[1] != 3 { + return Err(PyValueError::new_err("'points' must have shape (N, 3)")); + } + Ok(points + .as_array() + .rows() + .into_iter() + .map(|r| [r[0], r[1], r[2]]) + .collect()) +} + +/// Run `work` without the GIL. A panic becomes `RuntimeError`, with no partial result. +fn guarded(py: Python<'_>, work: impl FnOnce() -> T + Send) -> PyResult { + py.detach(|| std::panic::catch_unwind(std::panic::AssertUnwindSafe(work))) + .map_err(|e| { + let msg = e + .downcast_ref::<&str>() + .map(|s| s.to_string()) + .or_else(|| e.downcast_ref::().cloned()) + .unwrap_or_else(|| "unknown error".into()); + PyRuntimeError::new_err(format!("fault kernel error: {msg}")) + }) +} + +fn rows_array<'py>(py: Python<'py>, rows: Vec<[f64; 3]>) -> PyResult> { + let n = rows.len(); + let flat: Vec = rows.into_iter().flatten().collect(); + Ok(PyArray1::from_vec(py, flat).reshape([n, 3])?.into_any()) +} + +/// One value for each fault. +fn per_fault(name: &str, a: &[T], n: usize) -> PyResult<()> { + if a.len() == n { + Ok(()) + } else { + Err(PyValueError::new_err(format!( + "'{name}' needs {n} values (one for each fault), got {}", + a.len() + ))) + } +} + +fn read_sides(sides: &PyReadonlyArray1<'_, i8>, n: usize) -> PyResult> { + let s = sides.as_array().to_vec(); + per_fault("sides", &s, n)?; + s.iter() + .map(|&v| match v { + 2 => Ok(Side::Free), + 0 => Ok(Side::Absent), + 1 => Ok(Side::Hanging), + -1 => Ok(Side::Foot), + other => Err(PyValueError::new_err(format!( + "'sides' has value {other}; use 2, 0, 1 or -1" + ))), + }) + .collect() +} + +fn read_restored(restored: &PyReadonlyArray1<'_, bool>, n: usize) -> PyResult> { + let r = restored.as_array().to_vec(); + per_fault("restored", &r, n)?; + Ok(r) +} + +/// Fault indexes in the order of use. Each index must be less than `n`. +fn read_order(order: &PyReadonlyArray1<'_, i64>, n: usize) -> PyResult> { + order + .as_array() + .iter() + .map(|&i| { + usize::try_from(i).ok().filter(|&i| i < n).ok_or_else(|| { + PyValueError::new_err(format!("'order' has index {i}; the spec has {n} faults")) + }) + }) + .collect() +} + +/// A set of faults. It is read only after it is made. +#[pyclass(name = "FaultChain", frozen)] +struct PyFaultChain { + inner: FaultChain, +} + +#[pymethods] +impl PyFaultChain { + /// Make a chain from a spec dict. A bad spec raises `ValueError`. + #[new] + fn new(spec: &Bound<'_, PyAny>) -> PyResult { + Ok(Self { + inner: parse_chain(spec)?, + }) + } + + /// Move the points through the faults in `order`. Return an (N, 3) array. + #[allow(clippy::too_many_arguments)] // the Python signature is fixed by the plan + fn restore<'py>( + &self, + py: Python<'py>, + points: PyReadonlyArray2<'py, f64>, + order: PyReadonlyArray1<'py, i64>, + reverse: bool, + sides: PyReadonlyArray1<'py, i8>, + restored: PyReadonlyArray1<'py, bool>, + threads: usize, + ) -> PyResult> { + let n = self.inner.faults.len(); + let pts = read_points(&points)?; + let sides = read_sides(&sides, n)?; + let restored = read_restored(&restored, n)?; + let order = read_order(&order, n)?; + let out = guarded(py, || { + self.inner + .restore_batch(&order, &pts, reverse, &sides, &restored, threads) + })?; + rows_array(py, out) + } + + /// Return one frame coordinate of a fault at the points. Return an (N,) array. + #[allow(clippy::too_many_arguments)] // the Python signature is fixed by the plan + fn frame_value<'py>( + &self, + py: Python<'py>, + fault: usize, + coordinate: usize, + points: PyReadonlyArray2<'py, f64>, + sides: PyReadonlyArray1<'py, i8>, + restored: PyReadonlyArray1<'py, bool>, + threads: usize, + ) -> PyResult>> { + let n = self.inner.faults.len(); + if fault >= n { + return Err(PyValueError::new_err(format!( + "'fault' is {fault}; the spec has {n} faults" + ))); + } + if coordinate >= 3 { + return Err(PyValueError::new_err("'coordinate' must be 0, 1 or 2")); + } + let pts = read_points(&points)?; + let sides = read_sides(&sides, n)?; + let restored = read_restored(&restored, n)?; + let out = guarded(py, || { + self.inner + .frame_value_batch(fault, coordinate, &pts, &sides, &restored, threads) + })?; + Ok(PyArray1::from_vec(py, out)) + } + + /// Return the gradient of the feature at the points and the count of points that + /// straddle a fault. Return a tuple of an (N, 3) array and an int. + #[allow(clippy::too_many_arguments)] // the Python signature is fixed by the plan + fn feature_gradient<'py>( + &self, + py: Python<'py>, + field: &Bound<'py, PyGridField>, + points: PyReadonlyArray2<'py, f64>, + order: PyReadonlyArray1<'py, i64>, + sides: PyReadonlyArray1<'py, i8>, + restored: PyReadonlyArray1<'py, bool>, + jumping: PyReadonlyArray1<'py, bool>, + scale: f64, + threads: usize, + ) -> PyResult<(Bound<'py, PyAny>, usize)> { + let n = self.inner.faults.len(); + if !(scale.is_finite() && scale > 0.0) { + return Err(PyValueError::new_err("'scale' must be finite and > 0")); + } + let pts = read_points(&points)?; + let order = read_order(&order, n)?; + let sides = read_sides(&sides, n)?; + let restored = read_restored(&restored, n)?; + let jumping = jumping.as_array().to_vec(); + per_fault("jumping", &jumping, n)?; + let field = field.get(); + let (out, count) = guarded(py, || { + crate::fault::gradient::feature_gradient_threads( + &self.inner, + &field.inner, + &pts, + &order, + &sides, + &restored, + &jumping, + scale, + threads, + ) + })?; + Ok((rows_array(py, out)?, count)) + } +} + +/// A scalar field on a regular grid. It is read only after it is made. +#[pyclass(name = "GridField", frozen)] +struct PyGridField { + inner: GridField, +} + +impl PyGridField { + /// Apply `f` to each point. Use the pool with the feature `parallel`. + fn map( + &self, + points: &[[f64; 3]], + threads: usize, + f: impl Fn(&GridField, [f64; 3]) -> T + Sync, + ) -> Vec { + #[cfg(feature = "parallel")] + { + use rayon::prelude::*; + crate::fault::pool::pool(threads) + .install(|| points.par_iter().map(|&p| f(&self.inner, p)).collect()) + } + #[cfg(not(feature = "parallel"))] + { + let _ = threads; + points.iter().map(|&p| f(&self.inner, p)).collect() + } + } +} + +#[pymethods] +impl PyGridField { + /// Make a field from a grid dict. A bad spec raises `ValueError`. + #[new] + fn new(spec: &Bound<'_, PyAny>) -> PyResult { + Ok(Self { + inner: parse_grid("spec", spec)?, + }) + } + + /// Return the field values at the points. Return an (N,) array. + fn values<'py>( + &self, + py: Python<'py>, + points: PyReadonlyArray2<'py, f64>, + threads: usize, + ) -> PyResult>> { + let pts = read_points(&points)?; + let out = guarded(py, || self.map(&pts, threads, |g, p| g.value(p)))?; + Ok(PyArray1::from_vec(py, out)) + } + + /// Return the field gradients at the points. Return an (N, 3) array. + fn gradients<'py>( + &self, + py: Python<'py>, + points: PyReadonlyArray2<'py, f64>, + threads: usize, + ) -> PyResult> { + let pts = read_points(&points)?; + let out = guarded(py, || self.map(&pts, threads, |g, p| g.gradient(p)))?; + rows_array(py, out) + } +} + +#[pymodule] +fn loop_model_core(m: &Bound<'_, PyModule>) -> PyResult<()> { + m.add_class::()?; + m.add_class::()?; + m.add("FAULT_KERNEL_VERSION", 1)?; + Ok(()) +} diff --git a/packages/loop_model_core/tests/fault_gradient.rs b/packages/loop_model_core/tests/fault_gradient.rs new file mode 100644 index 000000000..92ee5d353 --- /dev/null +++ b/packages/loop_model_core/tests/fault_gradient.rs @@ -0,0 +1,118 @@ +//! Tests of the native gradient of a faulted feature on hand-built fault chains. + +use loop_model_core::fault::gradient::{feature_gradient, feature_gradient_threads}; +use loop_model_core::fault::profile::{Profile, Profile1}; +use loop_model_core::fault::{BlockSettings, Extension, Fault, FaultChain, GridField, Side}; + +const N: usize = 11; + +/// A grid on [-5, 5]^3 with node values `f(x, y, z)`. +fn grid(f: impl Fn(f64, f64, f64) -> f64) -> GridField { + let mut values = Vec::new(); + for k in 0..N { + for j in 0..N { + for i in 0..N { + values.push(f(i as f64 - 5.0, j as f64 - 5.0, k as f64 - 5.0)); + } + } + } + GridField { + origin: [-5.0; 3], + nsteps: [N; 3], + step_vector: [1.0; 3], + local_origin: None, + local_rotation: None, + values, + } +} + +fn chain() -> FaultChain { + let gx = Profile1::Composite { + positive: Box::new(Profile1::Ones), + negative: Box::new(Profile1::Zeros), + }; + FaultChain { + faults: vec![Fault { + frame: [grid(|x, _, _| x), grid(|_, y, _| y), grid(|_, _, z| z)], + cutters: vec![], + regions: [vec![], vec![], vec![]], + profile: Profile { + scale: 1.0, + gx, + gy: Profile1::Ones, + gz: Profile1::Ones, + }, + displacement: 0.7, + steps: 2, + }], + block: BlockSettings { + side_epsilon: 1e-9, + extension: Extension::Smooth, + exact: 0.25, + limit: 0.5, + step: 1e-3, + }, + } +} + +fn linear() -> GridField { + grid(|x, y, z| 2.0 * x - 3.0 * y + 0.5 * z) +} + +const S: [Side; 1] = [Side::Free]; + +#[test] +fn no_fault_equals_field_gradient() { + let c = chain(); + let f = linear(); + let pts = [[1.0, 0.5, 0.25], [-2.3, 1.1, 3.0]]; + let (g, n) = feature_gradient(&c, &f, &pts, &[], &S, &[false], &[false], 0.5); + assert_eq!(n, 0); + for (p, g) in pts.iter().zip(g) { + let e = f.gradient(*p); + assert!((0..3).all(|k| (g[k] - e[k]).abs() < 1e-10), "{g:?} {e:?}"); + } +} + +#[test] +fn point_on_fault_is_nan_and_far_point_is_not() { + let c = chain(); + let f = linear(); + let pts = [[0.0, 0.5, 0.25], [3.0, 0.5, 0.25]]; + let (g, n) = feature_gradient(&c, &f, &pts, &[0], &S, &[false], &[true], 0.5); + assert_eq!(n, 1); + assert!(g[0].iter().all(|v| v.is_nan())); + assert!(g[1].iter().all(|v| v.is_finite())); + // A point near the fault is refined and then fine. + let (g, n) = feature_gradient( + &c, + &f, + &[[0.1, 0.5, 0.25]], + &[0], + &S, + &[false], + &[true], + 0.5, + ); + assert_eq!(n, 1); + assert!(g[0].iter().all(|v| v.is_finite())); +} + +#[test] +fn threads_variant_equals_plain_and_empty() { + let c = chain(); + let f = linear(); + let pts: Vec<[f64; 3]> = (0..40).map(|i| [i as f64 * 0.1 - 2.0, 0.2, 0.1]).collect(); + let a = feature_gradient(&c, &f, &pts, &[0], &S, &[false], &[true], 0.5); + for t in [0, 1, 3] { + let b = feature_gradient_threads(&c, &f, &pts, &[0], &S, &[false], &[true], 0.5, t); + assert_eq!(a.1, b.1); + for (x, y) in a.0.iter().zip(&b.0) { + for k in 0..3 { + assert!(x[k].to_bits() == y[k].to_bits()); + } + } + } + let e = feature_gradient(&c, &f, &[], &[0], &S, &[false], &[true], 0.5); + assert!(e.0.is_empty() && e.1 == 0); +} diff --git a/packages/loop_model_core/tests/fault_grid_field.rs b/packages/loop_model_core/tests/fault_grid_field.rs new file mode 100644 index 000000000..9cdc53518 --- /dev/null +++ b/packages/loop_model_core/tests/fault_grid_field.rs @@ -0,0 +1,148 @@ +//! Tests of the structured grid lookup of `GridField`. + +use loop_model_core::fault::grid_field::GridField; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() <= 1e-12 * b.abs().max(1.0) +} + +/// Build a grid with node values `f(x, y, z)` at the local node coordinates (x runs fastest). +fn grid( + origin: [f64; 3], + nsteps: [usize; 3], + step: [f64; 3], + f: impl Fn([f64; 3]) -> f64, +) -> GridField { + let mut values = Vec::new(); + for k in 0..nsteps[2] { + for j in 0..nsteps[1] { + for i in 0..nsteps[0] { + let n = [i, j, k]; + values.push(f(std::array::from_fn(|a| { + origin[a] + step[a] * n[a] as f64 + }))); + } + } + } + GridField { + origin, + nsteps, + step_vector: step, + local_origin: None, + local_rotation: None, + values, + } +} + +#[test] +fn linear_field_is_exact() { + let g = grid([1.0, -2.0, 0.5], [4, 5, 3], [0.5, 0.8, 1.0], |p| { + 2.0 * p[0] - 3.0 * p[1] + 0.5 * p[2] + 1.0 + }); + let p = [1.7, 0.3, 1.2]; + assert!(close(g.value(p), 2.0 * 1.7 - 0.9 + 0.6 + 1.0)); + let d = g.gradient(p); + assert!(close(d[0], 2.0) && close(d[1], -3.0) && close(d[2], 0.5)); +} + +#[test] +fn rotated_local_frame() { + let (c, s) = (0.3_f64.cos(), 0.3_f64.sin()); + let r = [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]; + let o = [10.0, 20.0, 30.0]; + let mut g = grid([0.0; 3], [5, 5, 5], [1.0; 3], |q| q[0] + 2.0 * q[1] - q[2]); + g.local_origin = Some(o); + g.local_rotation = Some(r); + // World point whose local coordinates are (1.5, 2.5, 3.5). + let q = [1.5, 2.5, 3.5]; + let p: [f64; 3] = std::array::from_fn(|i| o[i] + (0..3).map(|j| r[j][i] * q[j]).sum::()); + assert!(close(g.value(p), 1.5 + 5.0 - 3.5)); + // The gradient in world axes is R^T (1, 2, -1). + let a = [1.0, 2.0, -1.0]; + let d = g.gradient(p); + for i in 0..3 { + assert!(close(d[i], (0..3).map(|j| r[j][i] * a[j]).sum::())); + } +} + +#[test] +fn nan_and_outside_points() { + let g = grid([0.0; 3], [3, 3, 3], [1.0; 3], |p| p[0]); + for p in [ + [f64::NAN, 1.0, 1.0], + [1.0, f64::NAN, 1.0], + [3.0, 1.0, 1.0], + [1.0, 1.0, -0.1], + ] { + assert!(g.value(p).is_nan()); + // Outside finite points give a zero gradient. NaN points give NaN. + let is_nan_point = p.iter().any(|v| v.is_nan()); + for v in g.gradient(p) { + assert!(if is_nan_point { v.is_nan() } else { v == 0.0 }); + } + } + // The upper boundary is inside. + assert!(close(g.value([2.0, 2.0, 2.0]), 2.0)); +} + +/// Expected values come from this Python run (`.venv/bin/python -I ref.py`): +/// +/// ```python +/// import numpy as np +/// from loop_common.supports import StructuredGrid +/// g = StructuredGrid(origin=np.array([1.0, -2.0, 0.5]), nsteps=np.array([5, 4, 6]), +/// step_vector=np.array([0.7, 1.1, 0.4])) # nsteps here = cells, nodes [6, 5, 7] +/// n = g.nodes +/// c = np.sin(n[:, 0]) + np.cos(1.3 * n[:, 1]) * n[:, 2] +/// pts = np.array([[1.3, -1.5, 0.9], [2.2, 0.4, 1.7], [3.1, 1.0, 2.2], +/// [3.4, -0.3, 1.1], [4.5, 1.2, 2.9]]) +/// lk = g._lookup_points(pts) +/// val = g._values_from_coefficients(lk[0], lk[1], g.trilinear(lk[2][lk[1]]), c) +/// gr = g._evaluate_gradient_from_lookup(lk, c) +/// ``` +#[test] +fn matches_python_grid() { + let g = grid([1.0, -2.0, 0.5], [6, 5, 7], [0.7, 1.1, 0.4], |p| { + p[0].sin() + (1.3 * p[1]).cos() * p[2] + }); + let pts = [ + [1.3, -1.5, 0.9], + [2.2, 0.4, 1.7], + [3.1, 1.0, 2.2], + [3.4, -0.3, 1.1], + [4.5, 1.2, 2.9], + ]; + let val = [ + 0.644792795517428, + 2.0732095333664233, + 0.43114013843941873, + 0.5364453971641094, + -1.036275078847976, + ]; + let gr = [ + [ + 0.21456260806367436, + 1.0203058126449638, + -0.29005219078841216, + ], + [-0.4517166141447394, -1.6772996642117397, 0.7690606058743095], + [ + -0.9334836476800142, + -2.1706230948622522, + 0.17707248909369477, + ], + [-0.9334836476800141, 0.5762382938262829, 0.7044634809407484], + [ + -0.5223888953176828, + -2.861275897772968, + -0.02025688316650953, + ], + ]; + for i in 0..5 { + assert!(close(g.value(pts[i]), val[i]), "value {i}"); + let d = g.gradient(pts[i]); + for a in 0..3 { + assert!(close(d[a], gr[i][a]), "gradient {i} axis {a}"); + } + } +} diff --git a/packages/loop_model_core/tests/fault_nearest.rs b/packages/loop_model_core/tests/fault_nearest.rs new file mode 100644 index 000000000..3083ea3b9 --- /dev/null +++ b/packages/loop_model_core/tests/fault_nearest.rs @@ -0,0 +1,77 @@ +//! Tests of the exact nearest-point search. + +use loop_model_core::fault::nearest::KdTree; + +/// Small LCG with a fixed seed. Return a number in [0, 1). +fn lcg(state: &mut u64) -> f64 { + *state = state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (*state >> 11) as f64 / (1u64 << 53) as f64 +} + +fn d2(a: [f64; 3], b: [f64; 3]) -> f64 { + (0..3).map(|i| (a[i] - b[i]) * (a[i] - b[i])).sum() +} + +/// Brute-force search. Strict `<` keeps the lowest index on ties. +fn brute(points: &[[f64; 3]], p: [f64; 3]) -> usize { + let mut best = usize::MAX; + let mut best_d = f64::INFINITY; + for (i, q) in points.iter().enumerate() { + let d = d2(*q, p); + if d < best_d { + best_d = d; + best = i; + } + } + best +} + +#[test] +fn matches_brute_force() { + let mut s = 12345u64; + let points: Vec<[f64; 3]> = (0..2000) + .map(|_| [lcg(&mut s) * 10.0, lcg(&mut s) * 10.0, lcg(&mut s) * 10.0]) + .collect(); + let tree = KdTree::new(&points); + for _ in 0..500 { + let q = [ + lcg(&mut s) * 12.0 - 1.0, + lcg(&mut s) * 12.0 - 1.0, + lcg(&mut s) * 12.0 - 1.0, + ]; + assert_eq!(tree.nearest(q), brute(&points, q)); + } +} + +#[test] +fn equal_distance_gives_lowest_index() { + // Many points on a lattice: the queries have many equal-distance points. + let mut points = Vec::new(); + for x in 0..6 { + for y in 0..6 { + for z in 0..6 { + points.push([x as f64, y as f64, z as f64]); + } + } + } + let tree = KdTree::new(&points); + for q in [ + [0.5, 0.5, 0.5], + [2.5, 2.5, 2.5], + [1.0, 1.5, 2.5], + [-1.0, 3.0, 3.0], + ] { + assert_eq!(tree.nearest(q), brute(&points, q)); + } + let dup = [[1.0, 1.0, 1.0]; 5]; + assert_eq!(KdTree::new(&dup).nearest([0.0, 0.0, 0.0]), 0); +} + +#[test] +fn one_point_and_empty() { + let tree = KdTree::new(&[[1.0, 2.0, 3.0]]); + assert_eq!(tree.nearest([-9.0, 4.0, 0.0]), 0); + assert_eq!(KdTree::new(&[]).nearest([0.0, 0.0, 0.0]), usize::MAX); +} diff --git a/packages/loop_model_core/tests/fault_profile.rs b/packages/loop_model_core/tests/fault_profile.rs new file mode 100644 index 000000000..47b7aa3f0 --- /dev/null +++ b/packages/loop_model_core/tests/fault_profile.rs @@ -0,0 +1,1070 @@ +//! Tests of the fault displacement profiles against values of the Python code. +//! +//! The values come from this Python script (run in the repository root): +//! +//! import numpy as np +//! from LoopStructural.modelling.features.fault._fault_function import BaseFault, BaseFault3D, block_displacement +//! from LoopStructural.utils._fault_block import force_side +//! G = [-1.5, -1, -0.5, 0, 0.3, 1, 2] +//! for name, B in (("F2", BaseFault), ("F3", BaseFault3D)): +//! for p in ("hw", "fw"): +//! c = getattr(B, p); c.solve() +//! print(name, p, "w", [repr(float(x)) for x in c.w], "lim", c.lim, "max", c.max_v, "min", c.min_v, "vp", c.value_points) +//! fd = B.fault_displacement +//! for gx in G: +//! for gy in G: +//! for gz in G: +//! v = float(fd(np.array([gx]), np.array([gy]), np.array([gz]))[0]) +//! print("E", name, gx, gy, gz, repr(v)) +//! for side in (1, -1): +//! for gx in G: +//! for gy in (-0.5, 0.3, 2): +//! for gz in (-0.5, 0.3, 1): +//! a = np.array([float(gx)]) +//! v = float(block_displacement(fd, a, force_side(a, side), np.array([float(gy)]), np.array([float(gz)]), side)[0]) +//! print("B", name, side, gx, gy, gz, repr(v)) + +use loop_model_core::fault::profile::{Profile, Profile1}; +use loop_model_core::fault::{BlockSettings, Extension, Side}; + +const W_HW: [f64; 4] = [ + 1.9999999999999116, + -2.9999999999998748, + 2.220446049250313e-15, + 0.9999999999999765, +]; +const W_FW: [f64; 4] = [ + 1.9999999999999116, + 2.9999999999998748, + 2.220446049250313e-15, + -0.9999999999999765, +]; + +fn cubic(w: [f64; 4], lim: [f64; 2], min: f64, max: f64, vp: [(f64, f64); 2]) -> Profile1 { + Profile1::Cubic { + w, + lim, + min, + max, + value_points: vp.to_vec(), + } +} + +fn profile(three_d: bool) -> Profile { + let hv = [(0.0, 1.0), (1.0, 0.0)]; + let fv = [(0.0, -1.0), (-1.0, 0.0)]; + let (hw, fw, gy) = if three_d { + ( + cubic(W_HW, [-1.0, 1.0], -99999.0, 1.0, hv), + cubic(W_FW, [-1.0, 1.0], -1.0, 999999.0, fv), + Profile1::SmoothPeak, + ) + } else { + ( + cubic(W_HW, [0.0, 1.0], -99999.0, 999999.0, hv), + cubic(W_FW, [-1.0, 0.0], -99999.0, 999999.0, fv), + Profile1::Ones, + ) + }; + Profile { + scale: 0.5, + gx: Profile1::Composite { + positive: Box::new(hw), + negative: Box::new(fw), + }, + gy, + gz: Profile1::SmoothPeak, + } +} + +fn settings(extension: Extension) -> BlockSettings { + BlockSettings { + side_epsilon: 1e-9, + extension, + exact: 0.25, + limit: 0.5, + step: 1e-3, + } +} + +fn close(a: f64, b: f64) { + assert!((a - b).abs() <= 1e-14, "{a} != {b}"); +} + +/// (3d, side, gx, gy, gz, value); side 0 is the plain displacement. +#[rustfmt::skip] +const CASES: &[(bool, i8, f64, f64, f64, f64)] = &[ + (false, 0, -1.5, -1.5, -1.5, 0.0), + (false, 0, -1.5, -1.5, -1.0, 0.0), + (false, 0, -1.5, -1.5, -0.5, 0.0), + (false, 0, -1.5, -1.5, 0.0, 0.0), + (false, 0, -1.5, -1.5, 0.3, 0.0), + (false, 0, -1.5, -1.5, 1.0, 0.0), + (false, 0, -1.5, -1.5, 2.0, 0.0), + (false, 0, -1.5, -1.0, -1.5, 0.0), + (false, 0, -1.5, -1.0, -1.0, 0.0), + (false, 0, -1.5, -1.0, -0.5, 0.0), + (false, 0, -1.5, -1.0, 0.0, 0.0), + (false, 0, -1.5, -1.0, 0.3, 0.0), + (false, 0, -1.5, -1.0, 1.0, 0.0), + (false, 0, -1.5, -1.0, 2.0, 0.0), + (false, 0, -1.5, -0.5, -1.5, 0.0), + (false, 0, -1.5, -0.5, -1.0, 0.0), + (false, 0, -1.5, -0.5, -0.5, 0.0), + (false, 0, -1.5, -0.5, 0.0, 0.0), + (false, 0, -1.5, -0.5, 0.3, 0.0), + (false, 0, -1.5, -0.5, 1.0, 0.0), + (false, 0, -1.5, -0.5, 2.0, 0.0), + (false, 0, -1.5, 0.0, -1.5, 0.0), + (false, 0, -1.5, 0.0, -1.0, 0.0), + (false, 0, -1.5, 0.0, -0.5, 0.0), + (false, 0, -1.5, 0.0, 0.0, 0.0), + (false, 0, -1.5, 0.0, 0.3, 0.0), + (false, 0, -1.5, 0.0, 1.0, 0.0), + (false, 0, -1.5, 0.0, 2.0, 0.0), + (false, 0, -1.5, 0.3, -1.5, 0.0), + (false, 0, -1.5, 0.3, -1.0, 0.0), + (false, 0, -1.5, 0.3, -0.5, 0.0), + (false, 0, -1.5, 0.3, 0.0, 0.0), + (false, 0, -1.5, 0.3, 0.3, 0.0), + (false, 0, -1.5, 0.3, 1.0, 0.0), + (false, 0, -1.5, 0.3, 2.0, 0.0), + (false, 0, -1.5, 1.0, -1.5, 0.0), + (false, 0, -1.5, 1.0, -1.0, 0.0), + (false, 0, -1.5, 1.0, -0.5, 0.0), + (false, 0, -1.5, 1.0, 0.0, 0.0), + (false, 0, -1.5, 1.0, 0.3, 0.0), + (false, 0, -1.5, 1.0, 1.0, 0.0), + (false, 0, -1.5, 1.0, 2.0, 0.0), + (false, 0, -1.5, 2.0, -1.5, 0.0), + (false, 0, -1.5, 2.0, -1.0, 0.0), + (false, 0, -1.5, 2.0, -0.5, 0.0), + (false, 0, -1.5, 2.0, 0.0, 0.0), + (false, 0, -1.5, 2.0, 0.3, 0.0), + (false, 0, -1.5, 2.0, 1.0, 0.0), + (false, 0, -1.5, 2.0, 2.0, 0.0), + (false, 0, -1.0, -1.5, -1.5, 0.0), + (false, 0, -1.0, -1.5, -1.0, 0.0), + (false, 0, -1.0, -1.5, -0.5, 0.0), + (false, 0, -1.0, -1.5, 0.0, 0.0), + (false, 0, -1.0, -1.5, 0.3, 0.0), + (false, 0, -1.0, -1.5, 1.0, 0.0), + (false, 0, -1.0, -1.5, 2.0, 0.0), + (false, 0, -1.0, -1.0, -1.5, 0.0), + (false, 0, -1.0, -1.0, -1.0, 0.0), + (false, 0, -1.0, -1.0, -0.5, 0.0), + (false, 0, -1.0, -1.0, 0.0, 0.0), + (false, 0, -1.0, -1.0, 0.3, 0.0), + (false, 0, -1.0, -1.0, 1.0, 0.0), + (false, 0, -1.0, -1.0, 2.0, 0.0), + (false, 0, -1.0, -0.5, -1.5, 0.0), + (false, 0, -1.0, -0.5, -1.0, 0.0), + (false, 0, -1.0, -0.5, -0.5, 0.0), + (false, 0, -1.0, -0.5, 0.0, 0.0), + (false, 0, -1.0, -0.5, 0.3, 0.0), + (false, 0, -1.0, -0.5, 1.0, 0.0), + (false, 0, -1.0, -0.5, 2.0, 0.0), + (false, 0, -1.0, 0.0, -1.5, 0.0), + (false, 0, -1.0, 0.0, -1.0, 0.0), + (false, 0, -1.0, 0.0, -0.5, 0.0), + (false, 0, -1.0, 0.0, 0.0, 0.0), + (false, 0, -1.0, 0.0, 0.3, 0.0), + (false, 0, -1.0, 0.0, 1.0, 0.0), + (false, 0, -1.0, 0.0, 2.0, 0.0), + (false, 0, -1.0, 0.3, -1.5, 0.0), + (false, 0, -1.0, 0.3, -1.0, 0.0), + (false, 0, -1.0, 0.3, -0.5, 0.0), + (false, 0, -1.0, 0.3, 0.0, 0.0), + (false, 0, -1.0, 0.3, 0.3, 0.0), + (false, 0, -1.0, 0.3, 1.0, 0.0), + (false, 0, -1.0, 0.3, 2.0, 0.0), + (false, 0, -1.0, 1.0, -1.5, 0.0), + (false, 0, -1.0, 1.0, -1.0, 0.0), + (false, 0, -1.0, 1.0, -0.5, 0.0), + (false, 0, -1.0, 1.0, 0.0, 0.0), + (false, 0, -1.0, 1.0, 0.3, 0.0), + (false, 0, -1.0, 1.0, 1.0, 0.0), + (false, 0, -1.0, 1.0, 2.0, 0.0), + (false, 0, -1.0, 2.0, -1.5, 0.0), + (false, 0, -1.0, 2.0, -1.0, 0.0), + (false, 0, -1.0, 2.0, -0.5, 0.0), + (false, 0, -1.0, 2.0, 0.0, 0.0), + (false, 0, -1.0, 2.0, 0.3, 0.0), + (false, 0, -1.0, 2.0, 1.0, 0.0), + (false, 0, -1.0, 2.0, 2.0, 0.0), + (false, 0, -0.5, -1.5, -1.5, -0.0), + (false, 0, -0.5, -1.5, -1.0, -0.0), + (false, 0, -0.5, -1.5, -0.5, -0.1406249999999994), + (false, 0, -0.5, -1.5, 0.0, -0.24999999999999892), + (false, 0, -0.5, -1.5, 0.3, -0.20702499999999913), + (false, 0, -0.5, -1.5, 1.0, -0.0), + (false, 0, -0.5, -1.5, 2.0, -0.0), + (false, 0, -0.5, -1.0, -1.5, -0.0), + (false, 0, -0.5, -1.0, -1.0, -0.0), + (false, 0, -0.5, -1.0, -0.5, -0.1406249999999994), + (false, 0, -0.5, -1.0, 0.0, -0.24999999999999892), + (false, 0, -0.5, -1.0, 0.3, -0.20702499999999913), + (false, 0, -0.5, -1.0, 1.0, -0.0), + (false, 0, -0.5, -1.0, 2.0, -0.0), + (false, 0, -0.5, -0.5, -1.5, -0.0), + (false, 0, -0.5, -0.5, -1.0, -0.0), + (false, 0, -0.5, -0.5, -0.5, -0.1406249999999994), + (false, 0, -0.5, -0.5, 0.0, -0.24999999999999892), + (false, 0, -0.5, -0.5, 0.3, -0.20702499999999913), + (false, 0, -0.5, -0.5, 1.0, -0.0), + (false, 0, -0.5, -0.5, 2.0, -0.0), + (false, 0, -0.5, 0.0, -1.5, -0.0), + (false, 0, -0.5, 0.0, -1.0, -0.0), + (false, 0, -0.5, 0.0, -0.5, -0.1406249999999994), + (false, 0, -0.5, 0.0, 0.0, -0.24999999999999892), + (false, 0, -0.5, 0.0, 0.3, -0.20702499999999913), + (false, 0, -0.5, 0.0, 1.0, -0.0), + (false, 0, -0.5, 0.0, 2.0, -0.0), + (false, 0, -0.5, 0.3, -1.5, -0.0), + (false, 0, -0.5, 0.3, -1.0, -0.0), + (false, 0, -0.5, 0.3, -0.5, -0.1406249999999994), + (false, 0, -0.5, 0.3, 0.0, -0.24999999999999892), + (false, 0, -0.5, 0.3, 0.3, -0.20702499999999913), + (false, 0, -0.5, 0.3, 1.0, -0.0), + (false, 0, -0.5, 0.3, 2.0, -0.0), + (false, 0, -0.5, 1.0, -1.5, -0.0), + (false, 0, -0.5, 1.0, -1.0, -0.0), + (false, 0, -0.5, 1.0, -0.5, -0.1406249999999994), + (false, 0, -0.5, 1.0, 0.0, -0.24999999999999892), + (false, 0, -0.5, 1.0, 0.3, -0.20702499999999913), + (false, 0, -0.5, 1.0, 1.0, -0.0), + (false, 0, -0.5, 1.0, 2.0, -0.0), + (false, 0, -0.5, 2.0, -1.5, -0.0), + (false, 0, -0.5, 2.0, -1.0, -0.0), + (false, 0, -0.5, 2.0, -0.5, -0.1406249999999994), + (false, 0, -0.5, 2.0, 0.0, -0.24999999999999892), + (false, 0, -0.5, 2.0, 0.3, -0.20702499999999913), + (false, 0, -0.5, 2.0, 1.0, -0.0), + (false, 0, -0.5, 2.0, 2.0, -0.0), + (false, 0, 0.0, -1.5, -1.5, 0.0), + (false, 0, 0.0, -1.5, -1.0, 0.0), + (false, 0, 0.0, -1.5, -0.5, 0.0), + (false, 0, 0.0, -1.5, 0.0, 0.0), + (false, 0, 0.0, -1.5, 0.3, 0.0), + (false, 0, 0.0, -1.5, 1.0, 0.0), + (false, 0, 0.0, -1.5, 2.0, 0.0), + (false, 0, 0.0, -1.0, -1.5, 0.0), + (false, 0, 0.0, -1.0, -1.0, 0.0), + (false, 0, 0.0, -1.0, -0.5, 0.0), + (false, 0, 0.0, -1.0, 0.0, 0.0), + (false, 0, 0.0, -1.0, 0.3, 0.0), + (false, 0, 0.0, -1.0, 1.0, 0.0), + (false, 0, 0.0, -1.0, 2.0, 0.0), + (false, 0, 0.0, -0.5, -1.5, 0.0), + (false, 0, 0.0, -0.5, -1.0, 0.0), + (false, 0, 0.0, -0.5, -0.5, 0.0), + (false, 0, 0.0, -0.5, 0.0, 0.0), + (false, 0, 0.0, -0.5, 0.3, 0.0), + (false, 0, 0.0, -0.5, 1.0, 0.0), + (false, 0, 0.0, -0.5, 2.0, 0.0), + (false, 0, 0.0, 0.0, -1.5, 0.0), + (false, 0, 0.0, 0.0, -1.0, 0.0), + (false, 0, 0.0, 0.0, -0.5, 0.0), + (false, 0, 0.0, 0.0, 0.0, 0.0), + (false, 0, 0.0, 0.0, 0.3, 0.0), + (false, 0, 0.0, 0.0, 1.0, 0.0), + (false, 0, 0.0, 0.0, 2.0, 0.0), + (false, 0, 0.0, 0.3, -1.5, 0.0), + (false, 0, 0.0, 0.3, -1.0, 0.0), + (false, 0, 0.0, 0.3, -0.5, 0.0), + (false, 0, 0.0, 0.3, 0.0, 0.0), + (false, 0, 0.0, 0.3, 0.3, 0.0), + (false, 0, 0.0, 0.3, 1.0, 0.0), + (false, 0, 0.0, 0.3, 2.0, 0.0), + (false, 0, 0.0, 1.0, -1.5, 0.0), + (false, 0, 0.0, 1.0, -1.0, 0.0), + (false, 0, 0.0, 1.0, -0.5, 0.0), + (false, 0, 0.0, 1.0, 0.0, 0.0), + (false, 0, 0.0, 1.0, 0.3, 0.0), + (false, 0, 0.0, 1.0, 1.0, 0.0), + (false, 0, 0.0, 1.0, 2.0, 0.0), + (false, 0, 0.0, 2.0, -1.5, 0.0), + (false, 0, 0.0, 2.0, -1.0, 0.0), + (false, 0, 0.0, 2.0, -0.5, 0.0), + (false, 0, 0.0, 2.0, 0.0, 0.0), + (false, 0, 0.0, 2.0, 0.3, 0.0), + (false, 0, 0.0, 2.0, 1.0, 0.0), + (false, 0, 0.0, 2.0, 2.0, 0.0), + (false, 0, 0.3, -1.5, -1.5, 0.0), + (false, 0, 0.3, -1.5, -1.0, 0.0), + (false, 0, 0.3, -1.5, -0.5, 0.2204999999999961), + (false, 0, 0.3, -1.5, 0.0, 0.391999999999993), + (false, 0, 0.3, -1.5, 0.3, 0.3246151999999942), + (false, 0, 0.3, -1.5, 1.0, 0.0), + (false, 0, 0.3, -1.5, 2.0, 0.0), + (false, 0, 0.3, -1.0, -1.5, 0.0), + (false, 0, 0.3, -1.0, -1.0, 0.0), + (false, 0, 0.3, -1.0, -0.5, 0.2204999999999961), + (false, 0, 0.3, -1.0, 0.0, 0.391999999999993), + (false, 0, 0.3, -1.0, 0.3, 0.3246151999999942), + (false, 0, 0.3, -1.0, 1.0, 0.0), + (false, 0, 0.3, -1.0, 2.0, 0.0), + (false, 0, 0.3, -0.5, -1.5, 0.0), + (false, 0, 0.3, -0.5, -1.0, 0.0), + (false, 0, 0.3, -0.5, -0.5, 0.2204999999999961), + (false, 0, 0.3, -0.5, 0.0, 0.391999999999993), + (false, 0, 0.3, -0.5, 0.3, 0.3246151999999942), + (false, 0, 0.3, -0.5, 1.0, 0.0), + (false, 0, 0.3, -0.5, 2.0, 0.0), + (false, 0, 0.3, 0.0, -1.5, 0.0), + (false, 0, 0.3, 0.0, -1.0, 0.0), + (false, 0, 0.3, 0.0, -0.5, 0.2204999999999961), + (false, 0, 0.3, 0.0, 0.0, 0.391999999999993), + (false, 0, 0.3, 0.0, 0.3, 0.3246151999999942), + (false, 0, 0.3, 0.0, 1.0, 0.0), + (false, 0, 0.3, 0.0, 2.0, 0.0), + (false, 0, 0.3, 0.3, -1.5, 0.0), + (false, 0, 0.3, 0.3, -1.0, 0.0), + (false, 0, 0.3, 0.3, -0.5, 0.2204999999999961), + (false, 0, 0.3, 0.3, 0.0, 0.391999999999993), + (false, 0, 0.3, 0.3, 0.3, 0.3246151999999942), + (false, 0, 0.3, 0.3, 1.0, 0.0), + (false, 0, 0.3, 0.3, 2.0, 0.0), + (false, 0, 0.3, 1.0, -1.5, 0.0), + (false, 0, 0.3, 1.0, -1.0, 0.0), + (false, 0, 0.3, 1.0, -0.5, 0.2204999999999961), + (false, 0, 0.3, 1.0, 0.0, 0.391999999999993), + (false, 0, 0.3, 1.0, 0.3, 0.3246151999999942), + (false, 0, 0.3, 1.0, 1.0, 0.0), + (false, 0, 0.3, 1.0, 2.0, 0.0), + (false, 0, 0.3, 2.0, -1.5, 0.0), + (false, 0, 0.3, 2.0, -1.0, 0.0), + (false, 0, 0.3, 2.0, -0.5, 0.2204999999999961), + (false, 0, 0.3, 2.0, 0.0, 0.391999999999993), + (false, 0, 0.3, 2.0, 0.3, 0.3246151999999942), + (false, 0, 0.3, 2.0, 1.0, 0.0), + (false, 0, 0.3, 2.0, 2.0, 0.0), + (false, 0, 1.0, -1.5, -1.5, 0.0), + (false, 0, 1.0, -1.5, -1.0, 0.0), + (false, 0, 1.0, -1.5, -0.5, 0.0), + (false, 0, 1.0, -1.5, 0.0, 0.0), + (false, 0, 1.0, -1.5, 0.3, 0.0), + (false, 0, 1.0, -1.5, 1.0, 0.0), + (false, 0, 1.0, -1.5, 2.0, 0.0), + (false, 0, 1.0, -1.0, -1.5, 0.0), + (false, 0, 1.0, -1.0, -1.0, 0.0), + (false, 0, 1.0, -1.0, -0.5, 0.0), + (false, 0, 1.0, -1.0, 0.0, 0.0), + (false, 0, 1.0, -1.0, 0.3, 0.0), + (false, 0, 1.0, -1.0, 1.0, 0.0), + (false, 0, 1.0, -1.0, 2.0, 0.0), + (false, 0, 1.0, -0.5, -1.5, 0.0), + (false, 0, 1.0, -0.5, -1.0, 0.0), + (false, 0, 1.0, -0.5, -0.5, 0.0), + (false, 0, 1.0, -0.5, 0.0, 0.0), + (false, 0, 1.0, -0.5, 0.3, 0.0), + (false, 0, 1.0, -0.5, 1.0, 0.0), + (false, 0, 1.0, -0.5, 2.0, 0.0), + (false, 0, 1.0, 0.0, -1.5, 0.0), + (false, 0, 1.0, 0.0, -1.0, 0.0), + (false, 0, 1.0, 0.0, -0.5, 0.0), + (false, 0, 1.0, 0.0, 0.0, 0.0), + (false, 0, 1.0, 0.0, 0.3, 0.0), + (false, 0, 1.0, 0.0, 1.0, 0.0), + (false, 0, 1.0, 0.0, 2.0, 0.0), + (false, 0, 1.0, 0.3, -1.5, 0.0), + (false, 0, 1.0, 0.3, -1.0, 0.0), + (false, 0, 1.0, 0.3, -0.5, 0.0), + (false, 0, 1.0, 0.3, 0.0, 0.0), + (false, 0, 1.0, 0.3, 0.3, 0.0), + (false, 0, 1.0, 0.3, 1.0, 0.0), + (false, 0, 1.0, 0.3, 2.0, 0.0), + (false, 0, 1.0, 1.0, -1.5, 0.0), + (false, 0, 1.0, 1.0, -1.0, 0.0), + (false, 0, 1.0, 1.0, -0.5, 0.0), + (false, 0, 1.0, 1.0, 0.0, 0.0), + (false, 0, 1.0, 1.0, 0.3, 0.0), + (false, 0, 1.0, 1.0, 1.0, 0.0), + (false, 0, 1.0, 1.0, 2.0, 0.0), + (false, 0, 1.0, 2.0, -1.5, 0.0), + (false, 0, 1.0, 2.0, -1.0, 0.0), + (false, 0, 1.0, 2.0, -0.5, 0.0), + (false, 0, 1.0, 2.0, 0.0, 0.0), + (false, 0, 1.0, 2.0, 0.3, 0.0), + (false, 0, 1.0, 2.0, 1.0, 0.0), + (false, 0, 1.0, 2.0, 2.0, 0.0), + (false, 0, 2.0, -1.5, -1.5, 0.0), + (false, 0, 2.0, -1.5, -1.0, 0.0), + (false, 0, 2.0, -1.5, -0.5, 0.0), + (false, 0, 2.0, -1.5, 0.0, 0.0), + (false, 0, 2.0, -1.5, 0.3, 0.0), + (false, 0, 2.0, -1.5, 1.0, 0.0), + (false, 0, 2.0, -1.5, 2.0, 0.0), + (false, 0, 2.0, -1.0, -1.5, 0.0), + (false, 0, 2.0, -1.0, -1.0, 0.0), + (false, 0, 2.0, -1.0, -0.5, 0.0), + (false, 0, 2.0, -1.0, 0.0, 0.0), + (false, 0, 2.0, -1.0, 0.3, 0.0), + (false, 0, 2.0, -1.0, 1.0, 0.0), + (false, 0, 2.0, -1.0, 2.0, 0.0), + (false, 0, 2.0, -0.5, -1.5, 0.0), + (false, 0, 2.0, -0.5, -1.0, 0.0), + (false, 0, 2.0, -0.5, -0.5, 0.0), + (false, 0, 2.0, -0.5, 0.0, 0.0), + (false, 0, 2.0, -0.5, 0.3, 0.0), + (false, 0, 2.0, -0.5, 1.0, 0.0), + (false, 0, 2.0, -0.5, 2.0, 0.0), + (false, 0, 2.0, 0.0, -1.5, 0.0), + (false, 0, 2.0, 0.0, -1.0, 0.0), + (false, 0, 2.0, 0.0, -0.5, 0.0), + (false, 0, 2.0, 0.0, 0.0, 0.0), + (false, 0, 2.0, 0.0, 0.3, 0.0), + (false, 0, 2.0, 0.0, 1.0, 0.0), + (false, 0, 2.0, 0.0, 2.0, 0.0), + (false, 0, 2.0, 0.3, -1.5, 0.0), + (false, 0, 2.0, 0.3, -1.0, 0.0), + (false, 0, 2.0, 0.3, -0.5, 0.0), + (false, 0, 2.0, 0.3, 0.0, 0.0), + (false, 0, 2.0, 0.3, 0.3, 0.0), + (false, 0, 2.0, 0.3, 1.0, 0.0), + (false, 0, 2.0, 0.3, 2.0, 0.0), + (false, 0, 2.0, 1.0, -1.5, 0.0), + (false, 0, 2.0, 1.0, -1.0, 0.0), + (false, 0, 2.0, 1.0, -0.5, 0.0), + (false, 0, 2.0, 1.0, 0.0, 0.0), + (false, 0, 2.0, 1.0, 0.3, 0.0), + (false, 0, 2.0, 1.0, 1.0, 0.0), + (false, 0, 2.0, 1.0, 2.0, 0.0), + (false, 0, 2.0, 2.0, -1.5, 0.0), + (false, 0, 2.0, 2.0, -1.0, 0.0), + (false, 0, 2.0, 2.0, -0.5, 0.0), + (false, 0, 2.0, 2.0, 0.0, 0.0), + (false, 0, 2.0, 2.0, 0.3, 0.0), + (false, 0, 2.0, 2.0, 1.0, 0.0), + (false, 0, 2.0, 2.0, 2.0, 0.0), + (false, 1, -1.5, -0.5, -0.5, 0.1329345703124994), + (false, 1, -1.5, -0.5, 0.3, 0.1957033203124991), + (false, 1, -1.5, -0.5, 1.0, 0.0), + (false, 1, -1.5, 0.3, -0.5, 0.1329345703124994), + (false, 1, -1.5, 0.3, 0.3, 0.1957033203124991), + (false, 1, -1.5, 0.3, 1.0, 0.0), + (false, 1, -1.5, 2.0, -0.5, 0.1329345703124994), + (false, 1, -1.5, 2.0, 0.3, 0.1957033203124991), + (false, 1, -1.5, 2.0, 1.0, 0.0), + (false, 1, -1.0, -0.5, -0.5, 0.1329345703124994), + (false, 1, -1.0, -0.5, 0.3, 0.1957033203124991), + (false, 1, -1.0, -0.5, 1.0, 0.0), + (false, 1, -1.0, 0.3, -0.5, 0.1329345703124994), + (false, 1, -1.0, 0.3, 0.3, 0.1957033203124991), + (false, 1, -1.0, 0.3, 1.0, 0.0), + (false, 1, -1.0, 2.0, -0.5, 0.1329345703124994), + (false, 1, -1.0, 2.0, 0.3, 0.1957033203124991), + (false, 1, -1.0, 2.0, 1.0, 0.0), + (false, 1, -0.5, -0.5, -0.5, 0.1329345703124994), + (false, 1, -0.5, -0.5, 0.3, 0.1957033203124991), + (false, 1, -0.5, -0.5, 1.0, 0.0), + (false, 1, -0.5, 0.3, -0.5, 0.1329345703124994), + (false, 1, -0.5, 0.3, 0.3, 0.1957033203124991), + (false, 1, -0.5, 0.3, 1.0, 0.0), + (false, 1, -0.5, 2.0, -0.5, 0.1329345703124994), + (false, 1, -0.5, 2.0, 0.3, 0.1957033203124991), + (false, 1, -0.5, 2.0, 1.0, 0.0), + (false, 1, 0.0, -0.5, -0.5, 0.2812499999999934), + (false, 1, 0.0, -0.5, 0.3, 0.41404999999999026), + (false, 1, 0.0, -0.5, 1.0, 0.0), + (false, 1, 0.0, 0.3, -0.5, 0.2812499999999934), + (false, 1, 0.0, 0.3, 0.3, 0.41404999999999026), + (false, 1, 0.0, 0.3, 1.0, 0.0), + (false, 1, 0.0, 2.0, -0.5, 0.2812499999999934), + (false, 1, 0.0, 2.0, 0.3, 0.41404999999999026), + (false, 1, 0.0, 2.0, 1.0, 0.0), + (false, 1, 0.3, -0.5, -0.5, 0.2204999999999961), + (false, 1, 0.3, -0.5, 0.3, 0.3246151999999942), + (false, 1, 0.3, -0.5, 1.0, 0.0), + (false, 1, 0.3, 0.3, -0.5, 0.2204999999999961), + (false, 1, 0.3, 0.3, 0.3, 0.3246151999999942), + (false, 1, 0.3, 0.3, 1.0, 0.0), + (false, 1, 0.3, 2.0, -0.5, 0.2204999999999961), + (false, 1, 0.3, 2.0, 0.3, 0.3246151999999942), + (false, 1, 0.3, 2.0, 1.0, 0.0), + (false, 1, 1.0, -0.5, -0.5, 0.0), + (false, 1, 1.0, -0.5, 0.3, 0.0), + (false, 1, 1.0, -0.5, 1.0, 0.0), + (false, 1, 1.0, 0.3, -0.5, 0.0), + (false, 1, 1.0, 0.3, 0.3, 0.0), + (false, 1, 1.0, 0.3, 1.0, 0.0), + (false, 1, 1.0, 2.0, -0.5, 0.0), + (false, 1, 1.0, 2.0, 0.3, 0.0), + (false, 1, 1.0, 2.0, 1.0, 0.0), + (false, 1, 2.0, -0.5, -0.5, 0.0), + (false, 1, 2.0, -0.5, 0.3, 0.0), + (false, 1, 2.0, -0.5, 1.0, 0.0), + (false, 1, 2.0, 0.3, -0.5, 0.0), + (false, 1, 2.0, 0.3, 0.3, 0.0), + (false, 1, 2.0, 0.3, 1.0, 0.0), + (false, 1, 2.0, 2.0, -0.5, 0.0), + (false, 1, 2.0, 2.0, 0.3, 0.0), + (false, 1, 2.0, 2.0, 1.0, 0.0), + (false, -1, -1.5, -0.5, -0.5, 0.0), + (false, -1, -1.5, -0.5, 0.3, 0.0), + (false, -1, -1.5, -0.5, 1.0, 0.0), + (false, -1, -1.5, 0.3, -0.5, 0.0), + (false, -1, -1.5, 0.3, 0.3, 0.0), + (false, -1, -1.5, 0.3, 1.0, 0.0), + (false, -1, -1.5, 2.0, -0.5, 0.0), + (false, -1, -1.5, 2.0, 0.3, 0.0), + (false, -1, -1.5, 2.0, 1.0, 0.0), + (false, -1, -1.0, -0.5, -0.5, 0.0), + (false, -1, -1.0, -0.5, 0.3, 0.0), + (false, -1, -1.0, -0.5, 1.0, 0.0), + (false, -1, -1.0, 0.3, -0.5, 0.0), + (false, -1, -1.0, 0.3, 0.3, 0.0), + (false, -1, -1.0, 0.3, 1.0, 0.0), + (false, -1, -1.0, 2.0, -0.5, 0.0), + (false, -1, -1.0, 2.0, 0.3, 0.0), + (false, -1, -1.0, 2.0, 1.0, 0.0), + (false, -1, -0.5, -0.5, -0.5, -0.1406249999999994), + (false, -1, -0.5, -0.5, 0.3, -0.20702499999999913), + (false, -1, -0.5, -0.5, 1.0, -0.0), + (false, -1, -0.5, 0.3, -0.5, -0.1406249999999994), + (false, -1, -0.5, 0.3, 0.3, -0.20702499999999913), + (false, -1, -0.5, 0.3, 1.0, -0.0), + (false, -1, -0.5, 2.0, -0.5, -0.1406249999999994), + (false, -1, -0.5, 2.0, 0.3, -0.20702499999999913), + (false, -1, -0.5, 2.0, 1.0, -0.0), + (false, -1, 0.0, -0.5, -0.5, -0.2812499999999934), + (false, -1, 0.0, -0.5, 0.3, -0.41404999999999026), + (false, -1, 0.0, -0.5, 1.0, -0.0), + (false, -1, 0.0, 0.3, -0.5, -0.2812499999999934), + (false, -1, 0.0, 0.3, 0.3, -0.41404999999999026), + (false, -1, 0.0, 0.3, 1.0, -0.0), + (false, -1, 0.0, 2.0, -0.5, -0.2812499999999934), + (false, -1, 0.0, 2.0, 0.3, -0.41404999999999026), + (false, -1, 0.0, 2.0, 1.0, -0.0), + (false, -1, 0.3, -0.5, -0.5, -0.191305254280497), + (false, -1, 0.3, -0.5, 0.3, -0.2816353441238748), + (false, -1, 0.3, -0.5, 1.0, -0.0), + (false, -1, 0.3, 0.3, -0.5, -0.191305254280497), + (false, -1, 0.3, 0.3, 0.3, -0.2816353441238748), + (false, -1, 0.3, 0.3, 1.0, -0.0), + (false, -1, 0.3, 2.0, -0.5, -0.191305254280497), + (false, -1, 0.3, 2.0, 0.3, -0.2816353441238748), + (false, -1, 0.3, 2.0, 1.0, -0.0), + (false, -1, 1.0, -0.5, -0.5, -0.1329345703124994), + (false, -1, 1.0, -0.5, 0.3, -0.1957033203124991), + (false, -1, 1.0, -0.5, 1.0, -0.0), + (false, -1, 1.0, 0.3, -0.5, -0.1329345703124994), + (false, -1, 1.0, 0.3, 0.3, -0.1957033203124991), + (false, -1, 1.0, 0.3, 1.0, -0.0), + (false, -1, 1.0, 2.0, -0.5, -0.1329345703124994), + (false, -1, 1.0, 2.0, 0.3, -0.1957033203124991), + (false, -1, 1.0, 2.0, 1.0, -0.0), + (false, -1, 2.0, -0.5, -0.5, -0.1329345703124994), + (false, -1, 2.0, -0.5, 0.3, -0.1957033203124991), + (false, -1, 2.0, -0.5, 1.0, -0.0), + (false, -1, 2.0, 0.3, -0.5, -0.1329345703124994), + (false, -1, 2.0, 0.3, 0.3, -0.1957033203124991), + (false, -1, 2.0, 0.3, 1.0, -0.0), + (false, -1, 2.0, 2.0, -0.5, -0.1329345703124994), + (false, -1, 2.0, 2.0, 0.3, -0.1957033203124991), + (false, -1, 2.0, 2.0, 1.0, -0.0), + (true, 0, -1.5, -1.5, -1.5, 0.0), + (true, 0, -1.5, -1.5, -1.0, 0.0), + (true, 0, -1.5, -1.5, -0.5, 0.0), + (true, 0, -1.5, -1.5, 0.0, 0.0), + (true, 0, -1.5, -1.5, 0.3, 0.0), + (true, 0, -1.5, -1.5, 1.0, 0.0), + (true, 0, -1.5, -1.5, 2.0, 0.0), + (true, 0, -1.5, -1.0, -1.5, 0.0), + (true, 0, -1.5, -1.0, -1.0, 0.0), + (true, 0, -1.5, -1.0, -0.5, 0.0), + (true, 0, -1.5, -1.0, 0.0, 0.0), + (true, 0, -1.5, -1.0, 0.3, 0.0), + (true, 0, -1.5, -1.0, 1.0, 0.0), + (true, 0, -1.5, -1.0, 2.0, 0.0), + (true, 0, -1.5, -0.5, -1.5, 0.0), + (true, 0, -1.5, -0.5, -1.0, 0.0), + (true, 0, -1.5, -0.5, -0.5, 0.0), + (true, 0, -1.5, -0.5, 0.0, 0.0), + (true, 0, -1.5, -0.5, 0.3, 0.0), + (true, 0, -1.5, -0.5, 1.0, 0.0), + (true, 0, -1.5, -0.5, 2.0, 0.0), + (true, 0, -1.5, 0.0, -1.5, 0.0), + (true, 0, -1.5, 0.0, -1.0, 0.0), + (true, 0, -1.5, 0.0, -0.5, 0.0), + (true, 0, -1.5, 0.0, 0.0, 0.0), + (true, 0, -1.5, 0.0, 0.3, 0.0), + (true, 0, -1.5, 0.0, 1.0, 0.0), + (true, 0, -1.5, 0.0, 2.0, 0.0), + (true, 0, -1.5, 0.3, -1.5, 0.0), + (true, 0, -1.5, 0.3, -1.0, 0.0), + (true, 0, -1.5, 0.3, -0.5, 0.0), + (true, 0, -1.5, 0.3, 0.0, 0.0), + (true, 0, -1.5, 0.3, 0.3, 0.0), + (true, 0, -1.5, 0.3, 1.0, 0.0), + (true, 0, -1.5, 0.3, 2.0, 0.0), + (true, 0, -1.5, 1.0, -1.5, 0.0), + (true, 0, -1.5, 1.0, -1.0, 0.0), + (true, 0, -1.5, 1.0, -0.5, 0.0), + (true, 0, -1.5, 1.0, 0.0, 0.0), + (true, 0, -1.5, 1.0, 0.3, 0.0), + (true, 0, -1.5, 1.0, 1.0, 0.0), + (true, 0, -1.5, 1.0, 2.0, 0.0), + (true, 0, -1.5, 2.0, -1.5, 0.0), + (true, 0, -1.5, 2.0, -1.0, 0.0), + (true, 0, -1.5, 2.0, -0.5, 0.0), + (true, 0, -1.5, 2.0, 0.0, 0.0), + (true, 0, -1.5, 2.0, 0.3, 0.0), + (true, 0, -1.5, 2.0, 1.0, 0.0), + (true, 0, -1.5, 2.0, 2.0, 0.0), + (true, 0, -1.0, -1.5, -1.5, 0.0), + (true, 0, -1.0, -1.5, -1.0, 0.0), + (true, 0, -1.0, -1.5, -0.5, 0.0), + (true, 0, -1.0, -1.5, 0.0, 0.0), + (true, 0, -1.0, -1.5, 0.3, 0.0), + (true, 0, -1.0, -1.5, 1.0, 0.0), + (true, 0, -1.0, -1.5, 2.0, 0.0), + (true, 0, -1.0, -1.0, -1.5, 0.0), + (true, 0, -1.0, -1.0, -1.0, 0.0), + (true, 0, -1.0, -1.0, -0.5, 0.0), + (true, 0, -1.0, -1.0, 0.0, 0.0), + (true, 0, -1.0, -1.0, 0.3, 0.0), + (true, 0, -1.0, -1.0, 1.0, 0.0), + (true, 0, -1.0, -1.0, 2.0, 0.0), + (true, 0, -1.0, -0.5, -1.5, 0.0), + (true, 0, -1.0, -0.5, -1.0, 0.0), + (true, 0, -1.0, -0.5, -0.5, 0.0), + (true, 0, -1.0, -0.5, 0.0, 0.0), + (true, 0, -1.0, -0.5, 0.3, 0.0), + (true, 0, -1.0, -0.5, 1.0, 0.0), + (true, 0, -1.0, -0.5, 2.0, 0.0), + (true, 0, -1.0, 0.0, -1.5, 0.0), + (true, 0, -1.0, 0.0, -1.0, 0.0), + (true, 0, -1.0, 0.0, -0.5, 0.0), + (true, 0, -1.0, 0.0, 0.0, 0.0), + (true, 0, -1.0, 0.0, 0.3, 0.0), + (true, 0, -1.0, 0.0, 1.0, 0.0), + (true, 0, -1.0, 0.0, 2.0, 0.0), + (true, 0, -1.0, 0.3, -1.5, 0.0), + (true, 0, -1.0, 0.3, -1.0, 0.0), + (true, 0, -1.0, 0.3, -0.5, 0.0), + (true, 0, -1.0, 0.3, 0.0, 0.0), + (true, 0, -1.0, 0.3, 0.3, 0.0), + (true, 0, -1.0, 0.3, 1.0, 0.0), + (true, 0, -1.0, 0.3, 2.0, 0.0), + (true, 0, -1.0, 1.0, -1.5, 0.0), + (true, 0, -1.0, 1.0, -1.0, 0.0), + (true, 0, -1.0, 1.0, -0.5, 0.0), + (true, 0, -1.0, 1.0, 0.0, 0.0), + (true, 0, -1.0, 1.0, 0.3, 0.0), + (true, 0, -1.0, 1.0, 1.0, 0.0), + (true, 0, -1.0, 1.0, 2.0, 0.0), + (true, 0, -1.0, 2.0, -1.5, 0.0), + (true, 0, -1.0, 2.0, -1.0, 0.0), + (true, 0, -1.0, 2.0, -0.5, 0.0), + (true, 0, -1.0, 2.0, 0.0, 0.0), + (true, 0, -1.0, 2.0, 0.3, 0.0), + (true, 0, -1.0, 2.0, 1.0, 0.0), + (true, 0, -1.0, 2.0, 2.0, 0.0), + (true, 0, -0.5, -1.5, -1.5, -0.0), + (true, 0, -0.5, -1.5, -1.0, -0.0), + (true, 0, -0.5, -1.5, -0.5, -0.0), + (true, 0, -0.5, -1.5, 0.0, -0.0), + (true, 0, -0.5, -1.5, 0.3, -0.0), + (true, 0, -0.5, -1.5, 1.0, -0.0), + (true, 0, -0.5, -1.5, 2.0, -0.0), + (true, 0, -0.5, -1.0, -1.5, -0.0), + (true, 0, -0.5, -1.0, -1.0, -0.0), + (true, 0, -0.5, -1.0, -0.5, -0.0), + (true, 0, -0.5, -1.0, 0.0, -0.0), + (true, 0, -0.5, -1.0, 0.3, -0.0), + (true, 0, -0.5, -1.0, 1.0, -0.0), + (true, 0, -0.5, -1.0, 2.0, -0.0), + (true, 0, -0.5, -0.5, -1.5, -0.0), + (true, 0, -0.5, -0.5, -1.0, -0.0), + (true, 0, -0.5, -0.5, -0.5, -0.07910156249999965), + (true, 0, -0.5, -0.5, 0.0, -0.1406249999999994), + (true, 0, -0.5, -0.5, 0.3, -0.11645156249999951), + (true, 0, -0.5, -0.5, 1.0, -0.0), + (true, 0, -0.5, -0.5, 2.0, -0.0), + (true, 0, -0.5, 0.0, -1.5, -0.0), + (true, 0, -0.5, 0.0, -1.0, -0.0), + (true, 0, -0.5, 0.0, -0.5, -0.1406249999999994), + (true, 0, -0.5, 0.0, 0.0, -0.24999999999999892), + (true, 0, -0.5, 0.0, 0.3, -0.20702499999999913), + (true, 0, -0.5, 0.0, 1.0, -0.0), + (true, 0, -0.5, 0.0, 2.0, -0.0), + (true, 0, -0.5, 0.3, -1.5, -0.0), + (true, 0, -0.5, 0.3, -1.0, -0.0), + (true, 0, -0.5, 0.3, -0.5, -0.11645156249999951), + (true, 0, -0.5, 0.3, 0.0, -0.20702499999999913), + (true, 0, -0.5, 0.3, 0.3, -0.17143740249999928), + (true, 0, -0.5, 0.3, 1.0, -0.0), + (true, 0, -0.5, 0.3, 2.0, -0.0), + (true, 0, -0.5, 1.0, -1.5, -0.0), + (true, 0, -0.5, 1.0, -1.0, -0.0), + (true, 0, -0.5, 1.0, -0.5, -0.0), + (true, 0, -0.5, 1.0, 0.0, -0.0), + (true, 0, -0.5, 1.0, 0.3, -0.0), + (true, 0, -0.5, 1.0, 1.0, -0.0), + (true, 0, -0.5, 1.0, 2.0, -0.0), + (true, 0, -0.5, 2.0, -1.5, -0.0), + (true, 0, -0.5, 2.0, -1.0, -0.0), + (true, 0, -0.5, 2.0, -0.5, -0.0), + (true, 0, -0.5, 2.0, 0.0, -0.0), + (true, 0, -0.5, 2.0, 0.3, -0.0), + (true, 0, -0.5, 2.0, 1.0, -0.0), + (true, 0, -0.5, 2.0, 2.0, -0.0), + (true, 0, 0.0, -1.5, -1.5, 0.0), + (true, 0, 0.0, -1.5, -1.0, 0.0), + (true, 0, 0.0, -1.5, -0.5, 0.0), + (true, 0, 0.0, -1.5, 0.0, 0.0), + (true, 0, 0.0, -1.5, 0.3, 0.0), + (true, 0, 0.0, -1.5, 1.0, 0.0), + (true, 0, 0.0, -1.5, 2.0, 0.0), + (true, 0, 0.0, -1.0, -1.5, 0.0), + (true, 0, 0.0, -1.0, -1.0, 0.0), + (true, 0, 0.0, -1.0, -0.5, 0.0), + (true, 0, 0.0, -1.0, 0.0, 0.0), + (true, 0, 0.0, -1.0, 0.3, 0.0), + (true, 0, 0.0, -1.0, 1.0, 0.0), + (true, 0, 0.0, -1.0, 2.0, 0.0), + (true, 0, 0.0, -0.5, -1.5, 0.0), + (true, 0, 0.0, -0.5, -1.0, 0.0), + (true, 0, 0.0, -0.5, -0.5, 0.0), + (true, 0, 0.0, -0.5, 0.0, 0.0), + (true, 0, 0.0, -0.5, 0.3, 0.0), + (true, 0, 0.0, -0.5, 1.0, 0.0), + (true, 0, 0.0, -0.5, 2.0, 0.0), + (true, 0, 0.0, 0.0, -1.5, 0.0), + (true, 0, 0.0, 0.0, -1.0, 0.0), + (true, 0, 0.0, 0.0, -0.5, 0.0), + (true, 0, 0.0, 0.0, 0.0, 0.0), + (true, 0, 0.0, 0.0, 0.3, 0.0), + (true, 0, 0.0, 0.0, 1.0, 0.0), + (true, 0, 0.0, 0.0, 2.0, 0.0), + (true, 0, 0.0, 0.3, -1.5, 0.0), + (true, 0, 0.0, 0.3, -1.0, 0.0), + (true, 0, 0.0, 0.3, -0.5, 0.0), + (true, 0, 0.0, 0.3, 0.0, 0.0), + (true, 0, 0.0, 0.3, 0.3, 0.0), + (true, 0, 0.0, 0.3, 1.0, 0.0), + (true, 0, 0.0, 0.3, 2.0, 0.0), + (true, 0, 0.0, 1.0, -1.5, 0.0), + (true, 0, 0.0, 1.0, -1.0, 0.0), + (true, 0, 0.0, 1.0, -0.5, 0.0), + (true, 0, 0.0, 1.0, 0.0, 0.0), + (true, 0, 0.0, 1.0, 0.3, 0.0), + (true, 0, 0.0, 1.0, 1.0, 0.0), + (true, 0, 0.0, 1.0, 2.0, 0.0), + (true, 0, 0.0, 2.0, -1.5, 0.0), + (true, 0, 0.0, 2.0, -1.0, 0.0), + (true, 0, 0.0, 2.0, -0.5, 0.0), + (true, 0, 0.0, 2.0, 0.0, 0.0), + (true, 0, 0.0, 2.0, 0.3, 0.0), + (true, 0, 0.0, 2.0, 1.0, 0.0), + (true, 0, 0.0, 2.0, 2.0, 0.0), + (true, 0, 0.3, -1.5, -1.5, 0.0), + (true, 0, 0.3, -1.5, -1.0, 0.0), + (true, 0, 0.3, -1.5, -0.5, 0.0), + (true, 0, 0.3, -1.5, 0.0, 0.0), + (true, 0, 0.3, -1.5, 0.3, 0.0), + (true, 0, 0.3, -1.5, 1.0, 0.0), + (true, 0, 0.3, -1.5, 2.0, 0.0), + (true, 0, 0.3, -1.0, -1.5, 0.0), + (true, 0, 0.3, -1.0, -1.0, 0.0), + (true, 0, 0.3, -1.0, -0.5, 0.0), + (true, 0, 0.3, -1.0, 0.0, 0.0), + (true, 0, 0.3, -1.0, 0.3, 0.0), + (true, 0, 0.3, -1.0, 1.0, 0.0), + (true, 0, 0.3, -1.0, 2.0, 0.0), + (true, 0, 0.3, -0.5, -1.5, 0.0), + (true, 0, 0.3, -0.5, -1.0, 0.0), + (true, 0, 0.3, -0.5, -0.5, 0.1240312499999978), + (true, 0, 0.3, -0.5, 0.0, 0.2204999999999961), + (true, 0, 0.3, -0.5, 0.3, 0.18259604999999676), + (true, 0, 0.3, -0.5, 1.0, 0.0), + (true, 0, 0.3, -0.5, 2.0, 0.0), + (true, 0, 0.3, 0.0, -1.5, 0.0), + (true, 0, 0.3, 0.0, -1.0, 0.0), + (true, 0, 0.3, 0.0, -0.5, 0.2204999999999961), + (true, 0, 0.3, 0.0, 0.0, 0.391999999999993), + (true, 0, 0.3, 0.0, 0.3, 0.3246151999999942), + (true, 0, 0.3, 0.0, 1.0, 0.0), + (true, 0, 0.3, 0.0, 2.0, 0.0), + (true, 0, 0.3, 0.3, -1.5, 0.0), + (true, 0, 0.3, 0.3, -1.0, 0.0), + (true, 0, 0.3, 0.3, -0.5, 0.18259604999999673), + (true, 0, 0.3, 0.3, 0.0, 0.3246151999999942), + (true, 0, 0.3, 0.3, 0.3, 0.26881384711999523), + (true, 0, 0.3, 0.3, 1.0, 0.0), + (true, 0, 0.3, 0.3, 2.0, 0.0), + (true, 0, 0.3, 1.0, -1.5, 0.0), + (true, 0, 0.3, 1.0, -1.0, 0.0), + (true, 0, 0.3, 1.0, -0.5, 0.0), + (true, 0, 0.3, 1.0, 0.0, 0.0), + (true, 0, 0.3, 1.0, 0.3, 0.0), + (true, 0, 0.3, 1.0, 1.0, 0.0), + (true, 0, 0.3, 1.0, 2.0, 0.0), + (true, 0, 0.3, 2.0, -1.5, 0.0), + (true, 0, 0.3, 2.0, -1.0, 0.0), + (true, 0, 0.3, 2.0, -0.5, 0.0), + (true, 0, 0.3, 2.0, 0.0, 0.0), + (true, 0, 0.3, 2.0, 0.3, 0.0), + (true, 0, 0.3, 2.0, 1.0, 0.0), + (true, 0, 0.3, 2.0, 2.0, 0.0), + (true, 0, 1.0, -1.5, -1.5, 0.0), + (true, 0, 1.0, -1.5, -1.0, 0.0), + (true, 0, 1.0, -1.5, -0.5, 0.0), + (true, 0, 1.0, -1.5, 0.0, 0.0), + (true, 0, 1.0, -1.5, 0.3, 0.0), + (true, 0, 1.0, -1.5, 1.0, 0.0), + (true, 0, 1.0, -1.5, 2.0, 0.0), + (true, 0, 1.0, -1.0, -1.5, 0.0), + (true, 0, 1.0, -1.0, -1.0, 0.0), + (true, 0, 1.0, -1.0, -0.5, 0.0), + (true, 0, 1.0, -1.0, 0.0, 0.0), + (true, 0, 1.0, -1.0, 0.3, 0.0), + (true, 0, 1.0, -1.0, 1.0, 0.0), + (true, 0, 1.0, -1.0, 2.0, 0.0), + (true, 0, 1.0, -0.5, -1.5, 0.0), + (true, 0, 1.0, -0.5, -1.0, 0.0), + (true, 0, 1.0, -0.5, -0.5, 0.0), + (true, 0, 1.0, -0.5, 0.0, 0.0), + (true, 0, 1.0, -0.5, 0.3, 0.0), + (true, 0, 1.0, -0.5, 1.0, 0.0), + (true, 0, 1.0, -0.5, 2.0, 0.0), + (true, 0, 1.0, 0.0, -1.5, 0.0), + (true, 0, 1.0, 0.0, -1.0, 0.0), + (true, 0, 1.0, 0.0, -0.5, 0.0), + (true, 0, 1.0, 0.0, 0.0, 0.0), + (true, 0, 1.0, 0.0, 0.3, 0.0), + (true, 0, 1.0, 0.0, 1.0, 0.0), + (true, 0, 1.0, 0.0, 2.0, 0.0), + (true, 0, 1.0, 0.3, -1.5, 0.0), + (true, 0, 1.0, 0.3, -1.0, 0.0), + (true, 0, 1.0, 0.3, -0.5, 0.0), + (true, 0, 1.0, 0.3, 0.0, 0.0), + (true, 0, 1.0, 0.3, 0.3, 0.0), + (true, 0, 1.0, 0.3, 1.0, 0.0), + (true, 0, 1.0, 0.3, 2.0, 0.0), + (true, 0, 1.0, 1.0, -1.5, 0.0), + (true, 0, 1.0, 1.0, -1.0, 0.0), + (true, 0, 1.0, 1.0, -0.5, 0.0), + (true, 0, 1.0, 1.0, 0.0, 0.0), + (true, 0, 1.0, 1.0, 0.3, 0.0), + (true, 0, 1.0, 1.0, 1.0, 0.0), + (true, 0, 1.0, 1.0, 2.0, 0.0), + (true, 0, 1.0, 2.0, -1.5, 0.0), + (true, 0, 1.0, 2.0, -1.0, 0.0), + (true, 0, 1.0, 2.0, -0.5, 0.0), + (true, 0, 1.0, 2.0, 0.0, 0.0), + (true, 0, 1.0, 2.0, 0.3, 0.0), + (true, 0, 1.0, 2.0, 1.0, 0.0), + (true, 0, 1.0, 2.0, 2.0, 0.0), + (true, 0, 2.0, -1.5, -1.5, 0.0), + (true, 0, 2.0, -1.5, -1.0, 0.0), + (true, 0, 2.0, -1.5, -0.5, 0.0), + (true, 0, 2.0, -1.5, 0.0, 0.0), + (true, 0, 2.0, -1.5, 0.3, 0.0), + (true, 0, 2.0, -1.5, 1.0, 0.0), + (true, 0, 2.0, -1.5, 2.0, 0.0), + (true, 0, 2.0, -1.0, -1.5, 0.0), + (true, 0, 2.0, -1.0, -1.0, 0.0), + (true, 0, 2.0, -1.0, -0.5, 0.0), + (true, 0, 2.0, -1.0, 0.0, 0.0), + (true, 0, 2.0, -1.0, 0.3, 0.0), + (true, 0, 2.0, -1.0, 1.0, 0.0), + (true, 0, 2.0, -1.0, 2.0, 0.0), + (true, 0, 2.0, -0.5, -1.5, 0.0), + (true, 0, 2.0, -0.5, -1.0, 0.0), + (true, 0, 2.0, -0.5, -0.5, 0.0), + (true, 0, 2.0, -0.5, 0.0, 0.0), + (true, 0, 2.0, -0.5, 0.3, 0.0), + (true, 0, 2.0, -0.5, 1.0, 0.0), + (true, 0, 2.0, -0.5, 2.0, 0.0), + (true, 0, 2.0, 0.0, -1.5, 0.0), + (true, 0, 2.0, 0.0, -1.0, 0.0), + (true, 0, 2.0, 0.0, -0.5, 0.0), + (true, 0, 2.0, 0.0, 0.0, 0.0), + (true, 0, 2.0, 0.0, 0.3, 0.0), + (true, 0, 2.0, 0.0, 1.0, 0.0), + (true, 0, 2.0, 0.0, 2.0, 0.0), + (true, 0, 2.0, 0.3, -1.5, 0.0), + (true, 0, 2.0, 0.3, -1.0, 0.0), + (true, 0, 2.0, 0.3, -0.5, 0.0), + (true, 0, 2.0, 0.3, 0.0, 0.0), + (true, 0, 2.0, 0.3, 0.3, 0.0), + (true, 0, 2.0, 0.3, 1.0, 0.0), + (true, 0, 2.0, 0.3, 2.0, 0.0), + (true, 0, 2.0, 1.0, -1.5, 0.0), + (true, 0, 2.0, 1.0, -1.0, 0.0), + (true, 0, 2.0, 1.0, -0.5, 0.0), + (true, 0, 2.0, 1.0, 0.0, 0.0), + (true, 0, 2.0, 1.0, 0.3, 0.0), + (true, 0, 2.0, 1.0, 1.0, 0.0), + (true, 0, 2.0, 1.0, 2.0, 0.0), + (true, 0, 2.0, 2.0, -1.5, 0.0), + (true, 0, 2.0, 2.0, -1.0, 0.0), + (true, 0, 2.0, 2.0, -0.5, 0.0), + (true, 0, 2.0, 2.0, 0.0, 0.0), + (true, 0, 2.0, 2.0, 0.3, 0.0), + (true, 0, 2.0, 2.0, 1.0, 0.0), + (true, 0, 2.0, 2.0, 2.0, 0.0), + (true, 1, -1.5, -0.5, -0.5, 0.0747756958007809), + (true, 1, -1.5, -0.5, 0.3, 0.11008311767578076), + (true, 1, -1.5, -0.5, 1.0, 0.0), + (true, 1, -1.5, 0.3, -0.5, 0.11008311767578075), + (true, 1, -1.5, 0.3, 0.3, 0.1620619195507805), + (true, 1, -1.5, 0.3, 1.0, 0.0), + (true, 1, -1.5, 2.0, -0.5, 0.0), + (true, 1, -1.5, 2.0, 0.3, 0.0), + (true, 1, -1.5, 2.0, 1.0, 0.0), + (true, 1, -1.0, -0.5, -0.5, 0.0747756958007809), + (true, 1, -1.0, -0.5, 0.3, 0.11008311767578076), + (true, 1, -1.0, -0.5, 1.0, 0.0), + (true, 1, -1.0, 0.3, -0.5, 0.11008311767578075), + (true, 1, -1.0, 0.3, 0.3, 0.1620619195507805), + (true, 1, -1.0, 0.3, 1.0, 0.0), + (true, 1, -1.0, 2.0, -0.5, 0.0), + (true, 1, -1.0, 2.0, 0.3, 0.0), + (true, 1, -1.0, 2.0, 1.0, 0.0), + (true, 1, -0.5, -0.5, -0.5, 0.0747756958007809), + (true, 1, -0.5, -0.5, 0.3, 0.11008311767578076), + (true, 1, -0.5, -0.5, 1.0, 0.0), + (true, 1, -0.5, 0.3, -0.5, 0.11008311767578075), + (true, 1, -0.5, 0.3, 0.3, 0.1620619195507805), + (true, 1, -0.5, 0.3, 1.0, 0.0), + (true, 1, -0.5, 2.0, -0.5, 0.0), + (true, 1, -0.5, 2.0, 0.3, 0.0), + (true, 1, -0.5, 2.0, 1.0, 0.0), + (true, 1, 0.0, -0.5, -0.5, 0.15820312499999628), + (true, 1, 0.0, -0.5, 0.3, 0.23290312499999455), + (true, 1, 0.0, -0.5, 1.0, 0.0), + (true, 1, 0.0, 0.3, -0.5, 0.23290312499999452), + (true, 1, 0.0, 0.3, 0.3, 0.34287480499999196), + (true, 1, 0.0, 0.3, 1.0, 0.0), + (true, 1, 0.0, 2.0, -0.5, 0.0), + (true, 1, 0.0, 2.0, 0.3, 0.0), + (true, 1, 0.0, 2.0, 1.0, 0.0), + (true, 1, 0.3, -0.5, -0.5, 0.1240312499999978), + (true, 1, 0.3, -0.5, 0.3, 0.18259604999999676), + (true, 1, 0.3, -0.5, 1.0, 0.0), + (true, 1, 0.3, 0.3, -0.5, 0.18259604999999673), + (true, 1, 0.3, 0.3, 0.3, 0.26881384711999523), + (true, 1, 0.3, 0.3, 1.0, 0.0), + (true, 1, 0.3, 2.0, -0.5, 0.0), + (true, 1, 0.3, 2.0, 0.3, 0.0), + (true, 1, 0.3, 2.0, 1.0, 0.0), + (true, 1, 1.0, -0.5, -0.5, 0.0), + (true, 1, 1.0, -0.5, 0.3, 0.0), + (true, 1, 1.0, -0.5, 1.0, 0.0), + (true, 1, 1.0, 0.3, -0.5, 0.0), + (true, 1, 1.0, 0.3, 0.3, 0.0), + (true, 1, 1.0, 0.3, 1.0, 0.0), + (true, 1, 1.0, 2.0, -0.5, 0.0), + (true, 1, 1.0, 2.0, 0.3, 0.0), + (true, 1, 1.0, 2.0, 1.0, 0.0), + (true, 1, 2.0, -0.5, -0.5, 0.0), + (true, 1, 2.0, -0.5, 0.3, 0.0), + (true, 1, 2.0, -0.5, 1.0, 0.0), + (true, 1, 2.0, 0.3, -0.5, 0.0), + (true, 1, 2.0, 0.3, 0.3, 0.0), + (true, 1, 2.0, 0.3, 1.0, 0.0), + (true, 1, 2.0, 2.0, -0.5, 0.0), + (true, 1, 2.0, 2.0, 0.3, 0.0), + (true, 1, 2.0, 2.0, 1.0, 0.0), + (true, -1, -1.5, -0.5, -0.5, 0.0), + (true, -1, -1.5, -0.5, 0.3, 0.0), + (true, -1, -1.5, -0.5, 1.0, 0.0), + (true, -1, -1.5, 0.3, -0.5, 0.0), + (true, -1, -1.5, 0.3, 0.3, 0.0), + (true, -1, -1.5, 0.3, 1.0, 0.0), + (true, -1, -1.5, 2.0, -0.5, 0.0), + (true, -1, -1.5, 2.0, 0.3, 0.0), + (true, -1, -1.5, 2.0, 1.0, 0.0), + (true, -1, -1.0, -0.5, -0.5, 0.0), + (true, -1, -1.0, -0.5, 0.3, 0.0), + (true, -1, -1.0, -0.5, 1.0, 0.0), + (true, -1, -1.0, 0.3, -0.5, 0.0), + (true, -1, -1.0, 0.3, 0.3, 0.0), + (true, -1, -1.0, 0.3, 1.0, 0.0), + (true, -1, -1.0, 2.0, -0.5, 0.0), + (true, -1, -1.0, 2.0, 0.3, 0.0), + (true, -1, -1.0, 2.0, 1.0, 0.0), + (true, -1, -0.5, -0.5, -0.5, -0.07910156249999965), + (true, -1, -0.5, -0.5, 0.3, -0.11645156249999951), + (true, -1, -0.5, -0.5, 1.0, -0.0), + (true, -1, -0.5, 0.3, -0.5, -0.11645156249999951), + (true, -1, -0.5, 0.3, 0.3, -0.17143740249999928), + (true, -1, -0.5, 0.3, 1.0, -0.0), + (true, -1, -0.5, 2.0, -0.5, -0.0), + (true, -1, -0.5, 2.0, 0.3, -0.0), + (true, -1, -0.5, 2.0, 1.0, -0.0), + (true, -1, 0.0, -0.5, -0.5, -0.15820312499999628), + (true, -1, 0.0, -0.5, 0.3, -0.23290312499999455), + (true, -1, 0.0, -0.5, 1.0, -0.0), + (true, -1, 0.0, 0.3, -0.5, -0.23290312499999452), + (true, -1, 0.0, 0.3, 0.3, -0.34287480499999196), + (true, -1, 0.0, 0.3, 1.0, -0.0), + (true, -1, 0.0, 2.0, -0.5, -0.0), + (true, -1, 0.0, 2.0, 0.3, -0.0), + (true, -1, 0.0, 2.0, 1.0, -0.0), + (true, -1, 0.3, -0.5, -0.5, -0.10760920553277956), + (true, -1, 0.3, -0.5, 0.3, -0.15841988106967958), + (true, -1, 0.3, -0.5, 1.0, -0.0), + (true, -1, 0.3, 0.3, -0.5, -0.15841988106967958), + (true, -1, 0.3, 0.3, 0.3, -0.23322222846898075), + (true, -1, 0.3, 0.3, 1.0, -0.0), + (true, -1, 0.3, 2.0, -0.5, -0.0), + (true, -1, 0.3, 2.0, 0.3, -0.0), + (true, -1, 0.3, 2.0, 1.0, -0.0), + (true, -1, 1.0, -0.5, -0.5, -0.0747756958007809), + (true, -1, 1.0, -0.5, 0.3, -0.11008311767578076), + (true, -1, 1.0, -0.5, 1.0, -0.0), + (true, -1, 1.0, 0.3, -0.5, -0.11008311767578075), + (true, -1, 1.0, 0.3, 0.3, -0.1620619195507805), + (true, -1, 1.0, 0.3, 1.0, -0.0), + (true, -1, 1.0, 2.0, -0.5, -0.0), + (true, -1, 1.0, 2.0, 0.3, -0.0), + (true, -1, 1.0, 2.0, 1.0, -0.0), + (true, -1, 2.0, -0.5, -0.5, -0.0747756958007809), + (true, -1, 2.0, -0.5, 0.3, -0.11008311767578076), + (true, -1, 2.0, -0.5, 1.0, -0.0), + (true, -1, 2.0, 0.3, -0.5, -0.11008311767578075), + (true, -1, 2.0, 0.3, 0.3, -0.1620619195507805), + (true, -1, 2.0, 0.3, 1.0, -0.0), + (true, -1, 2.0, 2.0, -0.5, -0.0), + (true, -1, 2.0, 2.0, 0.3, -0.0), + (true, -1, 2.0, 2.0, 1.0, -0.0), +]; + +#[test] +fn displacement_matches_python() { + let smooth = settings(Extension::Smooth); + for &(d3, side, gx, gy, gz, v) in CASES { + let p = profile(d3); + if side == 0 { + close(p.eval(gx, gy, gz), v); + } else { + let s = if side > 0 { 1.0 } else { -1.0 }; + let forced = s * gx.abs().max(1e-9); + let side = if side > 0 { Side::Hanging } else { Side::Foot }; + close(p.block_displacement(gx, forced, gy, gz, side, &smooth), v); + } + } +} + +#[test] +fn mirror_and_free_use_the_forced_value() { + let p = profile(true); + let mirror = settings(Extension::Mirror); + let smooth = settings(Extension::Smooth); + close( + p.block_displacement(-0.3, 0.3, 0.3, 0.3, Side::Hanging, &mirror), + p.eval(0.3, 0.3, 0.3), + ); + close( + p.block_displacement(-0.3, 0.3, 0.3, 0.3, Side::Free, &smooth), + p.eval(0.3, 0.3, 0.3), + ); + close( + p.block_displacement(-0.3, 0.3, 0.3, 0.3, Side::Absent, &smooth), + p.eval(0.3, 0.3, 0.3), + ); +} diff --git a/packages/loop_model_core/tests/fault_restore.rs b/packages/loop_model_core/tests/fault_restore.rs new file mode 100644 index 000000000..e6b85992b --- /dev/null +++ b/packages/loop_model_core/tests/fault_restore.rs @@ -0,0 +1,197 @@ +//! Tests of the native fault restore on hand-built fault chains. +//! +//! Not done: a comparison with `FaultSegment.apply_to_points`. The frame grids of a +//! LoopStructural model are too big to copy into a test. T013 and the Python +//! tests cover that comparison. + +use loop_model_core::fault::profile::{Profile, Profile1}; +use loop_model_core::fault::{ + BlockSettings, Extension, Fault, FaultChain, GridField, Region, Side, +}; + +const N: usize = 11; + +/// A grid on [-5, 5]^3 with node values `f(x, y, z)`. +fn grid(f: impl Fn(f64, f64, f64) -> f64) -> GridField { + let mut values = Vec::new(); + for k in 0..N { + for j in 0..N { + for i in 0..N { + values.push(f(i as f64 - 5.0, j as f64 - 5.0, k as f64 - 5.0)); + } + } + } + GridField { + origin: [-5.0; 3], + nsteps: [N; 3], + step_vector: [1.0; 3], + local_origin: None, + local_rotation: None, + values, + } +} + +fn fault(x0: f64, gx: Profile1, displacement: f64, steps: usize) -> Fault { + Fault { + frame: [grid(|x, _, _| x - x0), grid(|_, y, _| y), grid(|_, _, z| z)], + cutters: vec![], + regions: [vec![], vec![], vec![]], + profile: Profile { + scale: 1.0, + gx, + gy: Profile1::Ones, + gz: Profile1::Ones, + }, + displacement, + steps, + } +} + +fn chain(faults: Vec) -> FaultChain { + FaultChain { + faults, + block: BlockSettings { + side_epsilon: 1e-9, + extension: Extension::Smooth, + exact: 0.25, + limit: 0.5, + step: 1e-3, + }, + } +} + +fn close(a: [f64; 3], b: [f64; 3], tol: f64) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() <= tol) +} + +#[test] +fn constant_displacement_shifts_along_slip() { + let c = chain(vec![fault(0.0, Profile1::Ones, 0.7, 4)]); + let s = [Side::Free]; + let r = c.restore(&[0], [1.0, 0.5, 0.25], false, &s, &[false]); + assert!(close(r, [1.0, 1.2, 0.25], 1e-12), "{r:?}"); +} + +#[test] +fn reverse_undoes_restore() { + let c = chain(vec![fault(0.0, Profile1::Ones, 0.7, 3)]); + let s = [Side::Free]; + let p = [1.0, 0.5, 0.25]; + let r = c.restore(&[0], p, false, &s, &[false]); + let b = c.restore(&[0], r, true, &s, &[false]); + assert!(close(b, p, 1e-9), "{b:?}"); +} + +#[test] +fn nan_in_gives_nan_out() { + let c = chain(vec![fault(0.0, Profile1::Ones, 0.7, 2)]); + let r = c.restore(&[0], [f64::NAN, 0.0, 0.0], false, &[Side::Free], &[false]); + assert!(r[0].is_nan()); + let r = c.restore(&[0], [1.0, f64::NAN, 0.0], false, &[Side::Free], &[false]); + assert!(r[1].is_nan()); +} + +#[test] +fn absent_side_moves_nothing() { + let c = chain(vec![fault(0.0, Profile1::Ones, 0.7, 2)]); + let p = [1.0, 0.5, 0.25]; + assert_eq!(c.apply(0, p, false, &[Side::Absent], &[false]), p); +} + +#[test] +fn footwall_point_does_not_move() { + let gx = Profile1::Composite { + positive: Box::new(Profile1::Ones), + negative: Box::new(Profile1::Zeros), + }; + let c = chain(vec![fault(0.0, gx, 0.7, 2)]); + let s = [Side::Free]; + let foot = [-1.0, 0.5, 0.25]; + assert_eq!(c.apply(0, foot, false, &s, &[false]), foot); + let hang = c.apply(0, [1.0, 0.5, 0.25], false, &s, &[false]); + assert!(close(hang, [1.0, 1.2, 0.25], 1e-12)); +} + +#[test] +fn two_faults_equal_two_applies_and_restored_skips() { + let c = chain(vec![ + fault(0.0, Profile1::Ones, 0.5, 2), + fault(0.0, Profile1::Ones, 0.25, 1), + ]); + let s = [Side::Free, Side::Free]; + let p = [1.0, 0.0, 0.0]; + let a = c.apply(0, p, false, &s, &[false, false]); + let b = c.apply(1, a, false, &s, &[true, false]); + let r = c.restore(&[0, 1], p, false, &s, &[false, false]); + assert!(close(r, b, 1e-15)); + assert!(close(r, [1.0, 0.75, 0.0], 1e-12)); + let skip = c.restore(&[0, 1], p, false, &s, &[true, false]); + assert!(close(skip, [1.0, 0.25, 0.0], 1e-12)); +} + +#[test] +fn sign_region_excludes_point() { + // The region is the positive side of fault 1 (x - 3 > 0); the point has x = 1. + let mut a = fault(0.0, Profile1::Ones, 0.7, 2); + let b = fault(3.0, Profile1::Ones, 0.0, 1); + let region = Region::Sign { + positive: true, + fault: 1, + vector: Some([1.0, 0.0, 0.0]), + point: Some([3.0, 0.0, 0.0]), + }; + a.regions[0].push(region); + let c = chain(vec![a, b]); + let s = [Side::Free, Side::Free]; + let p = [1.0, 0.5, 0.25]; + assert!(c.frame_value(0, 0, p, &s, &[false; 2]).is_nan()); + assert_eq!(c.restore(&[0], p, false, &s, &[false; 2]), p); + let q = [4.0, 0.5, 0.25]; + assert!(!c.frame_value(0, 0, q, &s, &[false; 2]).is_nan()); +} + +#[test] +fn unconformity_region() { + let mut a = fault(0.0, Profile1::Ones, 0.7, 1); + a.regions[0].push(Region::Unconformity { + field: grid(|_, _, z| z), + faults: vec![], + value: 1.0, + sign: true, + }); + let c = chain(vec![a]); + let s = [Side::Free]; + assert!(!c.frame_value(0, 0, [1.0, 0.0, 0.5], &s, &[false]).is_nan()); + assert!(c.frame_value(0, 0, [1.0, 0.0, 2.0], &s, &[false]).is_nan()); + assert!( + c.frame_value(0, 0, [1.0, 0.0, f64::NAN], &s, &[false]) + .is_nan() + ); +} + +#[test] +fn batch_equals_single_and_empty() { + let c = chain(vec![fault(0.0, Profile1::Ones, 0.7, 3)]); + let s = [Side::Free]; + let pts: Vec<[f64; 3]> = (0..50) + .map(|i| [i as f64 * 0.1 - 2.5, 0.01 * i as f64, 0.3]) + .chain([[f64::NAN, 0.0, 0.0]]) + .collect(); + for threads in [0, 1, 3] { + let b = c.restore_batch(&[0], &pts, false, &s, &[false], threads); + let v = c.frame_value_batch(0, 0, &pts, &s, &[false], threads); + for (i, p) in pts.iter().enumerate() { + let r = c.restore(&[0], *p, false, &s, &[false]); + for k in 0..3 { + assert!(b[i][k] == r[k] || (b[i][k].is_nan() && r[k].is_nan())); + } + let e = c.frame_value(0, 0, *p, &s, &[false]); + assert!(v[i] == e || (v[i].is_nan() && e.is_nan())); + } + } + assert!( + c.restore_batch(&[0], &[], false, &s, &[false], 2) + .is_empty() + ); + assert!(c.frame_value_batch(0, 0, &[], &s, &[false], 2).is_empty()); +} diff --git a/pyproject.toml b/pyproject.toml index c63ad660c..68e002714 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,7 +49,7 @@ export = ["geoh5py", "pyevtk", "dill"] jupyter = ["pyvista[all]"] inequalities = ["loopsolver"] # the Rust solver: solver='native' -native = ["loop-interpolation[native]"] +native = ["loop-interpolation[native]", "loop-model-core"] tests = ['pytest'] dev = ['ruff', 'pytest-benchmark'] docs = [ @@ -91,7 +91,7 @@ LoopStructural = [ [tool.uv.workspace] members = ["packages/*"] -exclude = ["packages/loop_interpolation_core", "packages/loop_link"] +exclude = ["packages/loop_interpolation_core", "packages/loop_model_core", "packages/loop_link"] [tool.uv.sources] loop-common = { workspace = true } @@ -103,6 +103,8 @@ LoopStructural = { workspace = true } # extra loop-interpolation[native] needs a source so that uv can lock it. # uv reads its static metadata. It builds the core only when the extra is used. loop-interpolation-core = { path = "packages/loop_interpolation_core" } +# The fault kernel loop-model-core is also built with maturin. The extra native uses it. +loop-model-core = { path = "packages/loop_model_core" } [tool.pytest.ini_options] addopts = "--import-mode=importlib" diff --git a/specs/007-native-fault-kernel/HANDOFF.md b/specs/007-native-fault-kernel/HANDOFF.md new file mode 100644 index 000000000..fc0af7da1 --- /dev/null +++ b/specs/007-native-fault-kernel/HANDOFF.md @@ -0,0 +1,65 @@ +# Spec 007 handoff: native fault application + +Instructions for the person or agent who implements spec 007. + +## Where to work + +- Worktree: `/home/lgrose/dev/LoopStructural-wt/feat-007-native-fault-kernel` +- Branch: `feat/007-native-fault-kernel`, from master `6874364c` (spec 003 merged). +- Python environment: there is no venv in this worktree yet. Make one, or use + `../feat-003-fault-evaluation/.venv` (Python 3.13, maturin, pytest-xdist) + with `PYTHONPATH=$PWD:$PWD/packages/loop_common/src:$PWD/packages/loop_interpolation/src`. + +## What to read, in this order + +1. `.specify/memory/constitution.md`: the project rules. They win over everything else. +2. `specs/007-native-fault-kernel/spec.md`: the requirements (FR-001 to FR-015), the + success criteria (SC-001 to SC-008) and the decisions (C-001 to C-011). +3. `specs/003-fault-evaluation-performance/spec.md`: FR-004 (the golden tolerance + that the native path must meet) and FR-010 (the memory rule). +4. `LoopStructural/utils/_fault_block.py` (`restore_through`, `cutters_first`, + `with_cutters`) and `LoopStructural/modelling/features/fault/_fault_segment.py` + (`apply_to_points`, `_evaluate_frame`): the Python reference. +5. The proof of concept, outside the repository: + `/home/lgrose/dev/LoopStructural-wt/_runs003/rust_poc/README.md`. It is a + starting point, not code to copy as it is: it reads exported files (the spec + asks for the in-memory model), and its results differ by up to 1.9e-4 m (the + spec asks for 1e-8 times the box size; finding the cause is part of story 2, C-007). +6. `specs/007-native-fault-kernel/research.md`: background only. Precomputed maps are out of scope. + +## Order of work + +1. Run the spec-planner skill on spec 007, to write `plan.md`. Then run spec-tasks, + to write `tasks.md`. Then build with spec-orchestrator, wave by wave. +2. Story 1 (Python only: compute the restore order once for each feature) comes + first. It needs no native code, and it must give bit-identical results. +3. Stories 2 to 5 follow, in the order of the spec. The native code goes in + `packages/loop_interpolation_core` (it already builds with maturin, PyO3 0.29, + numpy 0.29 and rayon), unless the plan records another decision. + +## How to measure + +- Golden tests and the standard suite: `pytest tests/fault_evaluation` and + `python -m benchmarks.fault_evaluation.run --suite standard` (see spec 003 + `measurements.md` for the full T030 commands). +- The 94-fault model (SC-001, SC-004): + `python -m benchmarks.fault_evaluation.many_faults --output RESULT.json`. + It builds for about 7 minutes. It prints the `evaluate_model` time and the mean + time of an isolated and a cutting fault at 500, 2000 and 5000 points. + - Before a change: add `--save-reference REF.npz`. After it: add `--compare REF.npz`. + The script exits with 1 if any model id or group value differs (bit for bit). + - The reference of master `6874364c` (Python path, 2026-11-27) is in + `/home/lgrose/dev/LoopStructural-wt/_runs007/`: `many_faults_python.json` and + `many_faults_python_ref.npz`. Build 408 s; `evaluate_model` 1.78 s / 1.89 s / + 2.09 s at 500 / 2000 / 5000 points (94 fault calls); a cutting fault 40-47 ms + (mean), an isolated fault 2.6-3.5 ms. These are the SC-001 and SC-004 baselines. +- Measure on the T030 computer (Intel i7-12700H, Linux), with no other work running. + Use `OMP_NUM_THREADS=1` for test runs with `-n`. + +## Rules + +- The public `GeologicalModel` API does not change (FR-011). +- The Python path stays the reference and the fallback. The full test suite passes + with the native path on, with it off, and without the native package (SC-006). +- Before a merge: `ruff check LoopStructural packages` and `pytest` pass. +- Ask the maintainer before you open a pull request or push with force. diff --git a/specs/007-native-fault-kernel/plan.md b/specs/007-native-fault-kernel/plan.md new file mode 100644 index 000000000..b09d932f8 --- /dev/null +++ b/specs/007-native-fault-kernel/plan.md @@ -0,0 +1,877 @@ +# Implementation plan: native fault application + +**Feature**: `007-native-fault-kernel` | **Date**: 2026-11-27 | **Spec**: [spec.md](spec.md) + + + +**Code base of this plan.** The plan was written on the spec 003 branch at +`a558a1bd`. Spec 003 merged to master as #391 (`6874364c`) on 2026-11-27. The +OP1 check found that each planned file is the same on master, except +`benchmarks/fault_evaluation/run.py` (a new medium-case repeat tier; `main()` +and its options do not change). So the plan applies to master `6874364c`. The build branch is +`feat/007-native-fault-kernel` (worktree +`/home/lgrose/dev/LoopStructural-wt/feat-007-native-fault-kernel`), which adds +the 94-fault benchmark in `907acf42`. + +## Open points + +All open points are answered (see "Answers"). + +- **OP1 Base of the plan.** Spec 003 is not merged. When it merges, compare + the private names of "Names that this plan uses" with master. If a name + changed, update this plan before a task of stage S2 starts. Default: stage + S1 can start on the spec 003 branch, because it changes only + `_fault_block.py` and two callers. +- **OP2 The 94-fault model.** The model is not in the repository. SC-001 and + SC-004 need it. Default: the maintainer gives a saved model file. The + benchmark case `network94` loads it from the path in the environment + variable `LOOPSTRUCTURAL_NETWORK94`. If the variable is not set, the case is + skipped and the stage report says that SC-001 or SC-004 was not measured. +- **OP3 Cause of the 40 ms.** The spec says that most of the 40 ms fixed cost + of a cut fault frame is the restore order. The code shows a second cost: a + cut frame uses `_evaluate_frame_legacy`, which restores the same points 4 + times for each step (gx, gy, gz and the gradient of gy). Default: task S1-a + measures first. D1a (order cache) is always done (FR-001). D1b (one shared + restoration for the members of a cut frame) is done only if SC-001 fails + after D1a. +- **OP4 Regions on a fault frame.** An abutting fault adds a + `PositiveRegion` or `NegativeRegion` to member 0 of the frame. Default: the + native path supports these two region types when their parent is a fault + of the same chain. A fault frame with any other region (for example an + unconformity) is not supported, so the feature uses the Python path + (C-005). +- **OP5 Gradient of a faulted feature (FR-004).** The tetrahedron method + checks the fault side of each corner with `fillnan='nearest'` (a k-d tree + of SciPy). Default: the loop of the method (the straddle check, at most 10 + refinements, the NaN rule) stays in Python. The native path does each + numerical part of the loop: the frame values of the side check, the + restoration of the corners and the field values. A full native loop is not + part of this spec. +- **OP6 Data kept between calls (FR-009, FR-010).** The native data of a + feature is kept on the feature until the next call that finds a changed + state. The next call never uses old data, but the memory of the old state + is released only at that call. Default: accept this. The alternative is a + weak reference to each array, which NumPy arrays do not allow on all types. +- **OP7 Copy of the points.** The native call copies the input points to Rust + memory so that it can release the GIL (24 bytes for each point). Default: + accept the copy. Task S2-h measures SC-007 at 10 million points. If SC-007 + fails, read the points in place under the GIL-free call (unsafe code), in a + new task. +- **OP8 In-place change of node values.** The state token identifies the node + values of a grid by the array object, not by its content (see D2c). A + change in place (`interpolator.c[:] = ...`) is not found. Default: accept, + because the solvers make a new array. If the maintainer knows code that + changes `c` in place, the token must add a digest of `c`. +- **OP9 The proof-of-concept crate.** The crate is outside the repository + (`/home/lgrose/dev/LoopStructural-wt/_runs003/rust_poc/loop-snapshot`, see + "Answers"). Default: task S2-a reads it (read + only) to name the cause of its difference (C-007). The new kernel is + written from the Python code, not copied from the crate. + +## Answers + +Answered by the maintainer on 2026-11-27. + +- **OP1**: done 2026-11-27 after spec 003 merged (#391, `6874364c`). No + name of "Names that this plan uses" changed. Base of the plan: master. +- **OP2**: answered 2026-11-27 by `specs/007-native-fault-kernel/HANDOFF.md` + (commit `907acf42` on `feat/007-native-fault-kernel`). The model is + `benchmarks/fault_evaluation/many_faults.py` (deterministic, seed 100; the + build takes about 7 minutes; not in the standard suite): + `python -m benchmarks.fault_evaluation.many_faults --output RESULT.json [--points 500 2000 5000] [--save-reference REF.npz | --compare REF.npz]`. + `--compare` exits with 1 if a model id or group value differs bit for bit + (SC-001). The Python-path reference from master is in + `/home/lgrose/dev/LoopStructural-wt/_runs007/` (`many_faults_python.json`, + `many_faults_python_ref.npz`): cutting fault mean 40.0 ms at 500 points, + `evaluate_model` 2.09 s at 5000 points. This plan adds no benchmark case. +- **OP3**: measure, then fix (the default). D1a always; D1b only if SC-001 + fails after D1a. +- **OP4**: support abutting regions **and** unconformity regions on a fault + frame (not only the default). D2a `region.rs`, D2b and D2c are changed. +- **OP5**: the whole tetrahedron gradient is native (not the default), + including the side check with the nearest-point fill and the 10 + refinements. D3 is changed; new file `gradient.rs` and `nearest.rs`. +- **OP6**: accept (the default). +- **OP7**: copy the points and measure SC-007 (the default). +- **OP8**: identity of the array (the default). +- **Package of the native fault kernel (2026-11-27, maintainer)**: the + fault kernel moves out of `loop_interpolation_core` into a new package + `loop-model-core` (Python module `loop_model_core`), in spec 007 (stage + S5, design D5). Reasons: the kernel evaluates a built model and shares no + code with the solver; it needs its own version; other Rust users + (kiridashi, geoviewer) need model evaluation without the solver; nothing + is released yet, so the move breaks no user. Stage S5 also fixes two end + review findings: a negative `native_threads` is treated as 0 (all cores, + the joblib meaning of -1), and the support checks use `type(x) is` for + `FaultSegment`, `FaultDisplacement` and the region classes, so a user + subclass takes the Python path. +- **T038 / uv.lock (2026-11-27, orchestrator)**: the `uv.lock` of master is + stale (release-please raised the versions of loop-common, + loop-interpolation and LoopStructural without a new lock). `uv lock` now + rewrites about 1100 lines that spec 007 does not need. Spec 007 does not + change `uv.lock`; a separate re-lock on master also adds + `loop-model-core`. Until then, `uv sync --extra native` reports an old + lock. T038 also adds `packages/loop_model_core` to the uv workspace + `exclude` list (it builds with maturin, like the solver core). +- **T021 / SC-002 (2026-11-27, maintainer)**: SC-002 fails (1 thread: + 0.23 to 0.30 of the Python time; target 0.20). SC-003 (0.023 to 0.028) + and SC-007 pass. The maintainer added task T035: profile the 1-thread + kernel, remove the hot-path costs with unchanged results, and measure + again. T022 waits for T035. +- **T016 (2026-11-27, maintainer and orchestrator)**: + - Maintainer: the spec 003 tests that count or patch calls of the Python + `FaultSegment.apply_to_points` (`tests/fault_evaluation/test_context.py`, + `test_gradient_context.py`, `test_memory.py`) run with the Python path. + New task T034 adds `tests/fault_evaluation/conftest.py` with an autouse + fixture that sets `LoopStructuralConfig.native_faults = False` for these + modules only. The orchestrator added three more modules of the same kind + under this answer: `test_concurrency.py` (patches the Python fault call), + `test_no_retention.py` (counts Python fault calls) and + `test_fault_frame_lookup.py` (counts the grid lookups of the Python frame + path). The T006 tests of D1b and of the order cache in + `test_restore_order.py` turn the native path off in the test itself. + - Orchestrator: when a fault of the order has cutters that are not all + restored at its turn (this occurs for `reverse=True` with a cutting + fault), Python takes the frame gradient with the tetrahedron method and + the kernel does not. In that case `_native_faults.restore` returns None + (Python path). The check is linear in the chain. + - Orchestrator: a row with a NaN coordinate stays as the Python path gives + it (the finite coordinates are kept). `restore` must not set the whole + row to NaN; the T018 test is corrected. + - Orchestrator: `chain_for` computes cutter orders with an owner + (`restore_order(member0.faults, owner=member0)`, and the unconformity as + owner for its faults), so the order is not computed again at each call. +- **T006 (2026-11-27, maintainer)**: D1b is bit-identical but does fewer grid + lookups than the legacy fallback. The maintainer allows T006 to change + `tests/fault_evaluation/test_fault_frame_lookup.py`: the `child_faults` + cases join the cases whose lookup count may be lower than (`<=`) the legacy + count. The values stay asserted as before. D1b shares the restoration for + the values only; the gradient of member 1 keeps the old call (sharing it + changed results by about 5e-5). +- **T005 (2026-11-27, orchestrator)**: the `_runs007` reference cannot be + reproduced bit for bit in the feat-007 venv: the unchanged pre-D1a code + (cceb9b57) also differs from it in all `group_*` arrays (model ids are + equal). The cause is the model build (CG solves with atol 1e-6 in another + environment), not the code. An in-process check on one build shows D1a is + bit-identical (ids and both groups, 500 and 5000 points, with the cache, + without it, and on a repeat). Same-environment baseline before D1a: cutting + fault mean 39.1 ms at 500 points; after D1a 13.6 ms (SC-001 still fails, so + D1b runs, OP3). From now on the bit-identity check of S1 uses one build: the + script `ab.py` pattern (cache on against off in one process). +- **T019 (2026-11-27, orchestrator)**: the benchmark result keeps `"suite"` + as a string (`compare.py` and `acceptance.py` compare it with + `"standard"`). The native switch is a new top-level key + `"native_faults": "on" | "off"`. `--native-faults` also sets + `LOOPSTRUCTURAL_NATIVE_FAULTS`, so the subprocesses of each pass use the + same path. +- **OP9**: read the proof-of-concept crate only to find the cause (the + default). Its path (from `HANDOFF.md`) is + `/home/lgrose/dev/LoopStructural-wt/_runs003/rust_poc/` (`README.md`, + `loop-snapshot/`, `pyext/`, `export_snapshot.py`), not the kiridashi + repository. + +## Summary + +The work has four stages. Each stage can merge alone. + +- **S1 (story 1, Python only).** Compute the restore order of a feature once + for each state of its faults, and keep it on the feature. +- **S2 (stories 2, 4 and 5).** A Rust fault kernel in the existing package + `loop_interpolation_core` restores points through the faults of a supported + feature. LoopStructural uses it automatically. A setting, an environment + variable, a kernel version check and a thread count control it. +- **S3 (story 3).** The same kernel evaluates the field values and grid + gradients of a supported feature, and the whole tetrahedron gradient of a + faulted feature (OP5). +- **S4 (story 4, packages).** The existing wheel workflow builds and smoke + tests the fault kernel on all platforms of FR-014. + +The native path lives in `loop_interpolation_core` because that package +already has PyO3, rayon, an abi3-py39 build, a wheel workflow for the five +platforms of FR-014 (`.github/workflows/core-wheels.yml`) and the extra +`loopstructural[native]`. A new package would repeat all of this. + +## Technical context + +- Python 3.9 or later. Rust edition 2024, PyO3 0.29, numpy 0.29, rayon 1.10 + (all already in `packages/loop_interpolation_core/Cargo.toml`). No new + dependency. +- The kernel is an optional import. Without it, LoopStructural behaves as + before (FR-006c). +- The Python path stays the reference. The native path agrees within + 1e-8 × the size of the model box (spec 003 FR-004, C-007). +- Present restore path (spec 003 branch): + `EvaluationContext.restore` and `BaseFeature._apply_faults` call + `restore_through` (`LoopStructural/utils/_fault_block.py`). It calls + `with_cutters` and `cutters_first` at each call, and then + `FaultSegment.apply_to_points` for each fault. A cut fault frame uses + `FaultSegment._evaluate_frame_legacy`, which calls `evaluate_value` of each + member, which calls `restore_through` again. +- Inside `restore_through`, each fault that cuts fault k is in the list + `done` before fault k. So the members of a cut frame are evaluated at + points that are already restored, and they use the plain grid gradient, not + the tetrahedron method. The native restoration needs no tetrahedron method. + +## Constitution check + +| Rule | Result | +|---|---| +| Purpose and scope: a Python library, staged rebuild | Pass. The kernel is an optional part of the existing package `loop_interpolation_core`. | +| Development commands: `pytest`, `black .`, `ruff check LoopStructural packages` | Pass. Each task runs them. Rust tasks also run `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings` and `cargo test --release` in `packages/loop_interpolation_core` (`.dev-tools/project.json`). | +| Merge gate: `pytest` and Ruff pass before merge | Pass. FR-013 adds a test run with the native path on and one with it off. | +| Code conventions: numpy docstrings, type hints, py39 | Pass. New Python modules use `from __future__ import annotations` for `X | None`. | +| `ROADMAP.md` is the source of truth; update it at each stage | Pass. FR-015: one task in each stage updates `ROADMAP.md`. | +| Work ships in stages that can be tested and reverted alone | Pass. S1 to S4 each merge alone. Setting `LoopStructuralConfig.native_faults = False` turns S2 and S3 off at run time. | +| The public `GeologicalModel` API is a hard boundary | Pass. No signature of `GeologicalModel` or of a feature changes (FR-007). `LoopStructuralConfig` gets two new fields with defaults; this adds to the API and breaks nothing. `tests/fixtures/api_surface_snapshot.json` does not list `LoopStructuralConfig` (checked 2026-11-27), so it does not change. | +| The QGIS plugin stays in a separate repository | Pass. No plugin change. | +| Specs live under `specs/NNN-name/` | Pass. | +| Releases use release-please for each package | Pass. The kernel ships in the next release of `loop-interpolation-core`. No new package. | + +## Design + +### D1. Restore order once for each state (stage S1, FR-001, FR-002) + +**D1a. Order cache.** New function in `LoopStructural/utils/_fault_block.py`: + +```python +def restore_order(faults: Iterable, *, reverse: bool = False, owner: object | None = None) -> list: + """Return the faults and their chain of cutting faults in restore order.""" +``` + +- Without `owner`, it returns `cutters_first(with_cutters(faults))`, or for + `reverse=True` `cutters_first(with_cutters(faults)[::-1])[::-1]`, as + `restore_through` does today. +- With `owner`, it keeps the result in `owner._restore_order`, a tuple + `(key, chain, ordered)`: + - `chain = with_cutters(faults)` (a list; it keeps a reference to each + fault, so an `id` in `key` cannot be used again by a new object while + the entry exists); + - `key = (bool(reverse), tuple((id(f), tuple(id(c) for c in _cutters(f))) for f in chain))`. +- At each call it computes `chain` and `key` (linear in the chain) and + returns the kept `ordered` list if `key` is equal. Otherwise it computes the + order (quadratic) and replaces the entry. So a change of the cutting faults + of any fault of the chain (FR-002) changes the key. A change of the build + state that changes no cutter does not change the order, so the order stays + correct. +- `owner._restore_order` is set with one assignment, so two threads that set + it at the same time keep a correct entry (FR-011a). + +`restore_through` gets a new keyword `owner: object | None = None` and calls +`restore_order(faults, reverse=reverse, owner=owner)` in place of its two +lines of order code. No other change. + +Callers that pass `owner`: + +- `BaseFeature._apply_faults` (`_base_geological_feature.py`): `owner=self`. +- `EvaluationContext.restore` (`_evaluation.py`), both calls of + `restore_through`: `owner=feature`. + +The builder calls (`_geological_feature_builder.py`) do not change. They run +once at build time. + +**D1b. One restoration for the members of a cut frame (only if OP3 needs +it).** In `FaultSegment._evaluate_frame_legacy`: if the three members have +the same fault list (compare with `is` for each item) and the list is not +empty, restore the points once with +`restore_through(points, member0.faults, block=block, restored_through=restored_through, owner=member0)`, +and then call each member with the restored points and +`restored_through=tuple(restored_through) + tuple(restore_order(member0.faults, owner=member0))`. +The masks of the members use the original points, as today. The result must +be bit-identical (SC-001). If a test shows a difference, D1b is dropped and +the stage report says so. + +### D2. Native fault kernel (stage S2) + +#### D2a. Rust module + +New folder `packages/loop_interpolation_core/src/fault/`: + +| File | Content | +|---|---| +| `mod.rs` | `pub struct FaultChain { faults: Vec, block: BlockSettings }`, `pub struct Fault { frame: [GridField; 3], cutters: Vec, regions: Vec, profile: Profile, displacement: f64, steps: usize }`, `pub struct BlockSettings { side_epsilon: f64, extension: Extension, exact: f64, limit: f64, step: f64 }`, `pub enum Extension { Smooth, Mirror }`, `pub enum Side { Free, Absent, Hanging, Foot }` (Python 2, 0, +1, -1). | +| `grid_field.rs` | `pub struct GridField { origin: [f64; 3], nsteps: [usize; 3], step_vector: [f64; 3], local_origin: Option<[f64; 3]>, local_rotation: Option<[[f64; 3]; 3]>, values: Vec }` with `fn value(&self, p: [f64; 3]) -> f64` and `fn gradient(&self, p: [f64; 3]) -> [f64; 3]`. Port of the grid methods `_lookup_points`, `trilinear`, `_values_from_coefficients` and `_evaluate_gradient_from_lookup` (`packages/loop_common/src/loop_common/supports/_3d_structured_grid.py`, `packages/loop_common/src/loop_common/geometry/_structured_grid_3d.py`), and of the interpolator methods `_project_points` and `_reproject_vectors` (the world-to-local frame of the bounding box). `value`: NaN for a NaN coordinate and outside the grid. `gradient`: NaN for a NaN coordinate and [0, 0, 0] outside the grid, as `DiscreteInterpolator._evaluate_gradient_local` and `StructuredGrid._evaluate_gradient_from_lookup` give (corrected in the wave 2 review). | +| `profile.rs` | `pub enum Profile1 { Ones, Zeros, SmoothPeak, Cubic { w: [f64; 4], lim: [f64; 2], min: f64, max: f64, value_points: Vec<(f64, f64)> }, Composite { positive: Box, negative: Box } }`, `pub struct Profile { scale: f64, gx: Profile1, gy: Profile1, gz: Profile1 }`. Port of `smooth_peak`, `CubicFunction.__call__` and `_limit_value`, `Composite`, `Ones`, `Zeros`, `FaultDisplacement.__call__`, `_saturate`, `_taylor`, `continue_profile` and `block_displacement` (`_fault_function.py`). | +| `region.rs` | `pub enum Region { Sign { positive: bool, fault: usize, vector: Option<[f64; 3]>, point: Option<[f64; 3]> }, Unconformity { field: GridField, faults: Vec, value: f64, sign: bool } }`. `Sign`: port of `BaseSignRegion._calculate_value_and_distance`, `PositiveRegion.__call__` and `NegativeRegion.__call__` (`LoopStructural/utils/regions.py`), with the value of frame coordinate 0 of the parent fault from this chain (OP4). `Unconformity`: port of `UnconformityFeature.evaluate` (`LoopStructural/modelling/features/_unconformity_feature.py`): restore the point through `faults` (indices in this chain, in restore order; the faults in `restored` are skipped, as `restored_through`), read `field`, then `value_at <= value` if `sign`, else `value_at >= value`; NaN gives false. | +| `nearest.rs` | `pub struct KdTree` over a set of 3D points, `fn nearest(&self, p: [f64; 3]) -> usize`. Exact Euclidean nearest point; for equal distances the lowest index. Port of the `fillnan='nearest'` rule of `GeologicalFeature.evaluate_value` (OP5). | +| `gradient.rs` | `fn feature_gradient(chain, field, points, order, sides, restored, jumping, scale) -> (Vec<[f64; 3]>, usize)`: port of the faulted branch of `GeologicalFeature.evaluate_gradient` (OP5): a regular tetrahedron for each point (`regular_tetraherdron_for_points`, `packages/loop_common/src/loop_common/math/_maths.py`); the side check with frame coordinate 0 of each fault in `jumping`, with NaN corner values filled from the nearest known corner of the same batch (`nearest.rs`); at most 10 refinements, each with half the scale, only for the tetrahedra that still cross; the corners restored with `restore`; the field read at the restored corners; `gradient_from_tetrahedron` (same file). A point that still crosses a fault gets NaN. The second result is the number of points refined at least once. | +| `restore.rs` | `fn apply(&self, fault: usize, p: [f64; 3], reverse: bool, sides: &[Side], restored: &[bool]) -> [f64; 3]` (`apply` does not change `restored`; `restore` keeps its own copy of the done faults): port of `FaultSegment.apply_to_points` for one point, including `force_side`, `_displacement_fraction`, the steps, the NaN rules (#413) and the step direction of #425 (a NaN gradient of a cut frame uses the grid gradient of member 1 at the point). `fn restore(&self, order: &[usize], p: [f64; 3], reverse: bool, sides: &[Side], restored: &[bool]) -> [f64; 3]`: port of the loop of `restore_through`. `fn frame_value(&self, fault: usize, coordinate: usize, p, sides, restored) -> f64`: one frame coordinate with the region mask, as `FaultSegment._evaluate_frame` gives it. | +| `pool.rs` | `pub fn pool(threads: usize) -> Arc`: one pool for each thread count, kept in a `OnceLock>>>`. `threads == 0` means all cores. | + +Each point is independent, so the batch runs as a parallel loop over chunks +of 4096 points on `pool(threads)`. The kernel is immutable after it is made, +so it is `Send + Sync` (FR-011a). + +The kernel is written from the Python code, not from the proof-of-concept +crate (OP9). + +#### D2b. Python binding (`src/python.rs`, `src/lib.rs`) + +`src/lib.rs` adds `pub mod fault;`. `src/python.rs` adds to the module +`loop_interpolation_core`: + +```python +FAULT_KERNEL_VERSION: int = 1 + +class FaultChain: + def __init__(self, spec: dict) -> None: ... + def restore(self, points: np.ndarray, order: np.ndarray, reverse: bool, + sides: np.ndarray, restored: np.ndarray, threads: int) -> np.ndarray: ... + def frame_value(self, fault: int, coordinate: int, points: np.ndarray, + sides: np.ndarray, restored: np.ndarray, threads: int) -> np.ndarray: ... + def feature_gradient(self, field: GridField, points: np.ndarray, order: np.ndarray, + sides: np.ndarray, restored: np.ndarray, jumping: np.ndarray, + scale: float, threads: int) -> tuple[np.ndarray, int]: ... + +class GridField: + def __init__(self, spec: dict) -> None: ... + def values(self, points: np.ndarray, threads: int) -> np.ndarray: ... + def gradients(self, points: np.ndarray, threads: int) -> np.ndarray: ... +``` + +- `points`: float64, shape (N, 3). `order`: int64 indices into `spec["faults"]` + in restore order. `sides`: int8, one for each fault of the spec (2 = the + block does not name the fault). `restored`: bool, one for each fault of the + spec. Returns a new float64 array, (N, 3) for `restore`, (N,) for + `frame_value` and `values`, (N, 3) for `gradients`. +- Each call copies `points` to a Rust vector, releases the GIL + (`Python::detach`; `allow_threads` before PyO3 0.26) for the work, and + returns a new array (FR-011). The model data is copied only in `__init__`. +- `feature_gradient`: `jumping` is bool, one for each fault of the spec + (true: the side check uses this fault). `scale` is the first + `element_scale_parameter`. Returns the (N, 3) gradients and the number of + refined points (D3). +- An error raises `ValueError` (bad spec or shape) or `RuntimeError` + (internal error) with a message. No partial result is returned. +- An empty `points` array returns an empty array. + +**Spec of a `FaultChain` (Python dict; shown as JSON).** Arrays are float64 +NumPy arrays; lists in JSON below stand for them. + +```json +{ + "version": 1, + "block": {"side_epsilon": 1e-9, "extension": "smooth", "exact": 0.25, "limit": 0.5, "step": 1e-3}, + "faults": [ + { + "name": "f1", + "displacement": 100.0, + "steps": 10, + "frame": [ + {"origin": [0, 0, 0], "nsteps": [20, 20, 20], "step_vector": [50, 50, 50], + "local_origin": [0, 0, 0], "local_rotation": [[1, 0, 0], [0, 1, 0], [0, 0, 1]], + "values": ""}, + "", + "" + ], + "cutters": [2], + "regions": [[""], [], []], + "profile": {"scale": 0.5, "gx": "

", "gy": "

", "gz": "

"} + } + ] +} +``` + +`local_origin` and `local_rotation` are `null` when the interpolator has no +bounding box. A profile part `P` is one of: + +```json +{"kind": "ones"} +{"kind": "zeros"} +{"kind": "smooth_peak"} +{"kind": "cubic", "w": [0, 0, 0, 1], "lim": [-1, 1], "min": -1e308, "max": 1e308, "value_points": [[0, 1], [1, 0]]} +{"kind": "composite", "positive": "

", "negative": "

"} +``` + +Rules found while building (wave 3, 2026-11-27): + +- `cutters` is the full chain of cutting faults of the frame, in restore + order: the indices of `restore_order(member0.faults)` (the members have the + same fault list). The frame restores a point through each of them that is + not in `restored`, in this order, before it reads the grids. +- `regions` has one list for each frame member. Each member is masked by its + own list only (`_evaluate_frame_legacy` calls each member with its own + `_calculate_mask`). A frame with no faults whose 3 members share the same + region objects gives the same result, so one rule serves both paths. +- A `Sign` region needs `vector` and `point` at build time (`add_abutting_fault` + sets both). If either is None, the fault is not supported (Python path). +- A region gets `restored` only if the Python region has + `takes_restored_through` (an `UnconformityFeature` has it; a sign region has + not, so it evaluates its parent fault without `restored`). + +- The chain also holds every fault that a region needs (the parent fault of + a sign region, the faults of an unconformity region) and their cutters, + appended after the faults of the restore order. The `order` argument of + `restore` names only the faults of the restore order. + +A region `R` is one of: + +```json +{"kind": "positive", "fault": 2, "vector": [1, 0, 0], "point": [500, 500, 500]} +{"kind": "negative", "fault": 2, "vector": null, "point": null} +{"kind": "unconformity", "field": "", "faults": [3, 4], "value": 12.5, "sign": true} +``` + +The spec of a `GridField` is one `frame` item. + +#### D2c. Python side: `LoopStructural/modelling/features/_native_faults.py` (new) + +```python +REQUIRED_FAULT_KERNEL_VERSION: int = 1 + +def native_enabled() -> bool +def native_threads() -> int +def chain_for(feature: BaseFeature) -> tuple[object, list] | None +def restore(feature: BaseFeature, points: np.ndarray, *, reverse: bool = False, + block: dict | None = None, restored_through: Sequence = ()) -> np.ndarray | None +``` + +- `native_enabled()` (FR-006, FR-006a, FR-006b, C-002, C-008, C-009): + 1. If `LoopStructuralConfig.native_faults` is not None, use it. + 2. Else if the environment variable `LOOPSTRUCTURAL_NATIVE_FAULTS` is + `0`, `false`, `off` or `no` (any case), the native path is off. + 3. Else on. + If on, import `loop_interpolation_core`. If the import fails: off, with no + warning. If `getattr(core, "FAULT_KERNEL_VERSION", None)` is not + `REQUIRED_FAULT_KERNEL_VERSION`: off, and log one warning for each session + (a module flag) that names both versions, for example + `native fault kernel version None found, LoopStructural needs version 1; using the Python path`. + The result of the import and the version check is kept in the module; the + setting and the variable are read at each call. +- `native_threads()`: `LoopStructuralConfig.native_threads`, or 0 (all + cores) if it is None (FR-012, C-006). +- `chain_for(feature)` returns `(FaultChain, faults)` or None (Python path). + `faults` is `restore_order(feature.faults, owner=feature)` (D1a). It is + None (not supported, FR-008, C-005, C-010) if any fault of the chain: + - is not a `FaultSegment`, or its frame members are not three + `GeologicalFeature` objects with a `DiscreteInterpolator` on a + `StructuredGrid` with `_has_uniform_lookup()` (the same checks as + `_shared_frame_members`, without the "no faults" and "same regions" + checks); + - has members whose fault lists are not the same objects in the same + order (these become `cutters`); + - has a region on a member that is not one of these (OP4): a + `PositiveRegion` or `NegativeRegion` whose parent is a fault of the + chain; an `UnconformityFeature` whose interpolator passes the checks of + `field_for` (D3) and whose faults are all in the chain. Each region + object is called with `restored_through` only if it has + `takes_restored_through` (as `_calculate_mask` does); the native region + follows the same rule; + - has a `faultfunction` that is not a `FaultDisplacement`, or a profile + part that is not `Ones`, `Zeros`, `CubicFunction`, `Composite` or the + function `smooth_peak` (compare with `is`). + The function calls `builder.up_to_date()` of each fault first, as + `EvaluationContext.restore` does. +- **State token and cache (FR-009, FR-010).** The kernel is kept in + `feature._native_chain = (token, refs, chain, faults)`. `token` is a tuple + with, for each fault of `faults`: `id(fault)`, the displacement and steps + (through `_hashable`), the `id` of each member interpolator `c` array, the + grid geometry and bounding box values, the profile parameters (the spec + dict of D2b without `values`, as a tuple), and the cutter ids. It also has + `_fault_block.BLOCK_EXTENSION` and the other block settings. `refs` keeps a + reference to each `c` array, so the ids stay valid (OP8). Each call makes + the token again (small values only, no array copy). If it differs, a new + `FaultChain` is made and the entry is replaced with one assignment. Each + feature keeps its own entry, also when two features have the same faults. + This is simple; the cost is one copy of the node values of the faults for + each faulted feature. +- `restore(...)` returns None if `native_enabled()` is False or + `chain_for(feature)` is None. Else it maps `block` to `sides` (faults not + named: 2), `restored_through` to `restored` (by identity), uses the order of + `restore_order(feature.faults, reverse=reverse, owner=feature)` with the + faults of `restored_through` removed, and calls `FaultChain.restore`. + Points with `dtype` object, or not shaped (N, 3), return None (Python + path). + +#### D2d. Where the Python path calls the native path + +- `BaseFeature._apply_faults`: first + `native = _native_faults.restore(self, evaluation_points, reverse=reverse, block=block, restored_through=restored_through)`; + if it is not None, return it; else the present code with `owner=self`. +- `EvaluationContext.restore`: replace `restore_through(points, faults, reverse=reverse)` + (both calls) with a private helper `_restore_direct(feature, points, reverse)` + in the same module that tries `_native_faults.restore(feature, points, reverse=reverse)` + and else calls `restore_through(points, faults, reverse=reverse, owner=feature)`. + The scope keeps the result as today. +- No other call changes. `FaultSegment.apply_to_points` stays Python. It is + used by `apply_to_vectors`, by the builders and by a direct user call. + +#### D2e. Settings (`LoopStructural/__init__.py`) + +Add to the dataclass `LoopStructuralConfig`: + +```python +native_faults: bool | None = None # None: use LOOPSTRUCTURAL_NATIVE_FAULTS, else on +native_threads: int | None = None # None: all cores +``` + +Docstring entries in numpy style. A user sets the class attribute, as for +`nelements` (`LoopStructuralConfig.native_faults = False`). + +#### D2f. Tests and benchmarks select a path (FR-013) + +- The test suite reads the environment variable (D2c), so + `LOOPSTRUCTURAL_NATIVE_FAULTS=0 pytest` runs the Python path. +- `benchmarks/fault_evaluation/run.py` gets the option + `--native-faults {on,off}` (default `off`, so stored baselines keep their + meaning). It sets `LoopStructuralConfig.native_faults`. The result file + records the value in its `"suite"` object as `"native_faults"`. +- CI: `.github/workflows/native.yml` (it already builds the core) gets a step + `pytest tests/fault_evaluation` with the native path on. + `.github/workflows/tester.yml` keeps its run without the core; this is the + "package not installed" run of SC-006. + +### D3. Native field values and gradients (stage S3, FR-004) + +New function in `_native_faults.py`: + +```python +def field_for(feature: BaseFeature) -> object | None +``` + +It returns a `GridField` for the interpolator of `feature`, kept in +`feature._native_field = (token, refs, field)` with the token rules of D2c. +None if the native path is off or the interpolator is not a +`DiscreteInterpolator` on a `StructuredGrid` with the uniform lookup, or if +it overrides `evaluate_value`, `_evaluate_value_local` or +`_evaluate_gradient_local` (the checks of `_shared_frame_members`). + +Changes in `GeologicalFeature` (`_geological_feature.py`): + +- `evaluate_value`: if `field_for(self)` is not None, use + `field.values(evaluation_points[mask, :], native_threads())` in place of + `self.interpolator.evaluate_value(...)`. The interpolator first runs + `_check_frame()` and `update()`, as `_evaluate_frame` does. +- `evaluate_gradient`, branch without faults: the same with + `field.gradients(...)`. +- `evaluate_gradient`, branch with faults (OP5): if `field_for(self)` and + `chain_for(self)` are not None, compute `element_scale_parameter` and the + mask in Python as today, then call + `chain.feature_gradient(field, pos, order, sides, restored, jumping, element_scale_parameter, native_threads())`. + `order` is the restore order without the faults of `restored_through`; + `jumping` is true for each fault of `self._unrestored_faults(restored_through)` + that the block does not name. Set the rows outside the mask to NaN. If the + refined count is above 0, log the one warning of the Python path + (`" points are too close to a fault. Refining the tetrahedron"`), once + for the call. Else the present Python loop runs. + +Masks and regions of the feature itself and `fillnan` of `evaluate_value` +stay in Python (C-003). + +### D4. Packages (stage S4, FR-014) + +- `.github/workflows/core-wheels.yml`: the smoke test also makes a + `FaultChain` with one fault (constant profile: `ones` for gx, gy and gz), + restores two points and checks the result to 1e-12 against the displacement + along the slip direction. All other jobs (5 platforms, abi3-py39, sdist, + publish through `pypi.yml`) stay. +- `packages/loop_interpolation_core/README.md` and `CHANGELOG.md` (by + release-please) describe the fault kernel. + +### Names that this plan uses (spec 003 branch, OP1) + +`restore_through`, `with_cutters`, `cutters_first`, `_cutters`, `is_in`, +`force_side`, `BLOCK_SIDE_EPSILON`, `BLOCK_EXTENSION`, `BLOCK_EXTENSION_EXACT`, +`BLOCK_EXTENSION_LIMIT`, `BLOCK_EXTENSION_STEP` (`_fault_block.py`); +`EvaluationContext.restore`, `_hashable` (`_evaluation.py`); +`FaultSegment.apply_to_points`, `_evaluate_frame`, `_evaluate_frame_legacy`, +`_displacement_fraction`, `_shared_frame_members` (`_fault_segment.py`); +`FaultDisplacement`, `CubicFunction`, `Composite`, `Ones`, `Zeros`, +`smooth_peak`, `_saturate`, `_taylor`, `continue_profile`, +`block_displacement` (`_fault_function.py`); `BaseFeature._apply_faults`; +`GeologicalFeature.evaluate_value`, `evaluate_gradient`; +`StructuredGrid._has_uniform_lookup`, `_lookup_points`, +`_values_from_coefficients`, `_evaluate_gradient_from_lookup`. + +### New names (each checked free with `git grep -n -w` on 2026-11-27) + +`restore_order`, `_restore_order`, `_native_faults`, `_native_chain`, +`_native_field`, `native_enabled`, `native_threads`, `native_faults`, +`chain_for`, `field_for`, `_restore_direct`, `REQUIRED_FAULT_KERNEL_VERSION`, +`FAULT_KERNEL_VERSION`, `FaultChain`, `GridField`, +`LOOPSTRUCTURAL_NATIVE_FAULTS`, `KdTree`, `feature_gradient`, +`test_restore_order`, `test_native_faults`. + +## Files + +### Stage S1 + +- `LoopStructural/utils/_fault_block.py`: `restore_order`, keyword `owner` + of `restore_through`. +- `LoopStructural/modelling/features/_base_geological_feature.py`: + `_apply_faults` passes `owner=self`. +- `LoopStructural/modelling/features/_evaluation.py`: `owner=feature`. +- `LoopStructural/modelling/features/fault/_fault_segment.py`: D1b, only if + OP3 needs it. +- `tests/fault_evaluation/test_restore_order.py` (new): the order is computed + once (count calls of `cutters_first` with a mock), a new cutter changes + the order (story 1 scenario 2), bit-identical values on `cutting_faults` + and `f4_u3`. +- `specs/007-native-fault-kernel/profile-s1.md` (new): the measurement of + S1-a, before and after. +- `ROADMAP.md`: the decision to add the native path and stage S1 (FR-015). + +### Stage S2 + +- `packages/loop_interpolation_core/src/fault/mod.rs`, `grid_field.rs`, + `profile.rs`, `region.rs`, `restore.rs`, `pool.rs` (new). `nearest.rs` and + `gradient.rs` are stage S3 files. +- `packages/loop_interpolation_core/src/lib.rs`, `src/python.rs`. +- `packages/loop_interpolation_core/tests/fault_grid_field.rs`, + `tests/fault_profile.rs`, `tests/fault_restore.rs` (new): grid lookup, + profiles against values from Python, one fault with constant displacement, + NaN input, empty input. (One file for each Rust module, so that tasks in + one wave do not share a file.) +- `LoopStructural/modelling/features/_native_faults.py` (new). +- `LoopStructural/modelling/features/_base_geological_feature.py`, + `LoopStructural/modelling/features/_evaluation.py` (D2d). +- `LoopStructural/__init__.py` (D2e). +- `tests/fault_evaluation/test_native_settings.py` (new): the setting, the + variable, the version check and the thread count, with a mock kernel + module (no build needed). +- `tests/fault_evaluation/test_native_safety.py` (new): the story 5 + scenarios (moved out of `test_native_faults.py`, so that two tasks can + write tests at the same time). +- `tests/fault_evaluation/test_native_faults.py` (new): restore parity on + each golden model (tolerance and NaN points, story 2), block, reverse and + `restored_through` (story 2 scenario 2), switch and variable (story 4 + scenarios 2 and 3, with the real kernel). The settings tests are in + `test_native_settings.py` and the story 5 tests in `test_native_safety.py`. + Each parity test records the largest difference with + `record_property("max_native_diff", value)` (FR-005c). Skip the module if + the kernel is not installed. +- `benchmarks/fault_evaluation/run.py` (D2f). +- `.github/workflows/native.yml` (D2f). +- `specs/007-native-fault-kernel/verification.md` (new): the cause of the + difference of the proof of concept (C-007), the largest native differences, + SC-002, SC-003, SC-006 and SC-007 numbers. +- `ROADMAP.md`: stage S2. + +### Stage S3 + +- `LoopStructural/modelling/features/_native_faults.py`: `field_for`. +- `packages/loop_interpolation_core/src/fault/nearest.rs`, `gradient.rs` + (new), `src/python.rs` (`feature_gradient`). +- `packages/loop_interpolation_core/tests/fault_nearest.rs` (new): `KdTree` + against a brute-force search. +- `packages/loop_interpolation_core/tests/fault_gradient.rs` (new): the + tetrahedron and its gradient against values from Python. +- `tests/fault_evaluation/test_native_field.py` (new): the S3 parity tests + (in place of more tests in `test_native_faults.py`). +- `LoopStructural/modelling/features/_geological_feature.py` (D3). +- (`test_native_field.py`, above): value and gradient parity, + model ids with the unit-boundary rule (FR-005b), a straddling tetrahedron + gives NaN (story 3 scenario 2). +- `specs/007-native-fault-kernel/verification.md`: SC-004 and SC-005. +- `ROADMAP.md`: stage S3. + +### Stage S4 + +- `.github/workflows/core-wheels.yml` (D4). +- `packages/loop_interpolation_core/README.md`. +- `.github/workflows/native.yml` is changed in S2 only. +- `specs/007-native-fault-kernel/verification.md`: SC-008 (install on each + platform, the golden tests with the native path on). +- `ROADMAP.md`: stage S4. + +## Tasks of each stage (outline for spec-tasks) + +- **S1-a** Measure the 94-fault model of spec 003 at 500 points (OP2): time of each cut + fault and a profile. Write `profile-s1.md`. +- **S1-b** Tests of D1a (red). **S1-c** D1a. **S1-d** Measure again; D1b + only if SC-001 fails (OP3). **S1-e** `ROADMAP.md`. +- **S2-a** Read the proof-of-concept crate (OP9) and the Python reference; + record each difference in `verification.md`. +- **S2-b** Rust `grid_field.rs` and `profile.rs` with Rust tests. +- **S2-c** `LoopStructuralConfig` fields and `native_enabled`, + `native_threads` with tests (no kernel needed: mock module). +- **S2-d** Rust `region.rs`, `restore.rs`, `pool.rs`, `mod.rs` with Rust + tests. +- **S2-e** PyO3 binding and `FAULT_KERNEL_VERSION`. +- **S2-f** `chain_for`, `restore`, token and cache; D2d calls. +- **S2-g** `test_native_faults.py` for story 2, 4 and 5. +- **S2-h** Benchmarks: `--native-faults`, SC-002, SC-003, SC-007. CI step. +- **S2-i** `ROADMAP.md`, `verification.md`. +- **S3-a** Rust `nearest.rs` and `gradient.rs` with Rust tests; the + `feature_gradient` binding. +- **S3-a2** `GridField` Python binding test, `field_for`, D3 changes, tests + (value, gradient, refinement warning, unconformity region on a frame). + **S3-b** SC-004, SC-005. **S3-c** `ROADMAP.md`. +- **S4-a** Wheel smoke test. **S4-b** SC-008 install check (the maintainer + runs it on each platform; CI runs it on the 4 platforms with `smoke: true`). + **S4-c** `ROADMAP.md`. + +## Stages and rollback + +| Stage | Merges alone | Rollback | +|---|---|---| +| S1 | Yes, Python only. | Revert the commit. | +| S2 | Yes, after S1 (uses `restore_order`). | `LoopStructuralConfig.native_faults = False` or `LOOPSTRUCTURAL_NATIVE_FAULTS=0`; or revert. | +| S3 | Yes, after S2. | As S2. | +| S4 | Yes, after S2. | Revert the workflow change. | + +## Requirement coverage + +| Item | Covered by | +|---|---| +| FR-001 | D1a, S1-b, S1-c | +| FR-002 | D1a key, `test_restore_order.py` (story 1 scenario 2) | +| FR-003 | D2a `restore.rs`, `profile.rs`, `region.rs`; S2-g | +| FR-004 | D3, `gradient.rs`, `nearest.rs` (OP5: fully native) | +| FR-005 | S2-g, S3-a parity tests with the spec 003 tolerance | +| FR-005a | S2-g, S3-a (NaN points equal) | +| FR-005b | S3-a (model ids, unit-boundary rule) | +| FR-005c | `record_property("max_native_diff")`, `verification.md` | +| FR-006 | D2c `native_enabled`, D2d | +| FR-006a | D2c version check and one warning | +| FR-006b | D2c, D2e | +| FR-006c | D2c (None returns the unchanged Python path); `tester.yml` run without the core; S1 bit-identical tests | +| FR-007 | No signature change; the existing test `tests/unit/test_public_api_contract.py` | +| FR-008 | D2c `chain_for` checks, D3 `field_for` checks, OP4 | +| FR-009 | D2b (data copied only in `__init__`), D2c cache; story 5 scenario 3 test | +| FR-010 | D2c token; story 5 scenario 4 test | +| FR-011 | D2b GIL release; story 5 scenario 5 test | +| FR-011a | Immutable kernel, single assignment of the cache; story 5 scenario 6 test | +| FR-012 | D2e `native_threads`, `pool.rs`; story 5 scenario 7 test | +| FR-013 | D2f | +| FR-014 | D4 (existing workflow: Linux x86_64 and aarch64, macOS arm64 and x86_64, Windows x64; abi3-py39) | +| FR-015 | S1-e, S2-i, S3-c, S4-c | +| SC-001 | S1-a, S1-d (OP2: case of spec 003; OP3) | +| SC-002 | S2-h | +| SC-003 | S2-h | +| SC-004 | S3-b (OP2: case of spec 003) | +| SC-005 | S3-b | +| SC-006 | D2f: native on (`native.yml`), off (variable), not installed (`tester.yml`) | +| SC-007 | S2-h (OP7) | +| SC-008 | S4-b | + +Gaps: + +- SC-001 and SC-004 need the 94-fault case of spec 003 (OP2). If spec 003 + merges without it, they cannot be measured. +- FR-004: the nearest-point fill uses the lowest index for equal distances. + SciPy does not define the result for equal distances, so a tie can give a + different side check. The parity tests show if this occurs. +- SC-008 on a clean computer: CI covers 4 platforms; macOS x86_64 is + cross-compiled and not run in CI, so the maintainer checks it by hand. + +## Handover + +Other specs can use these names. All are private to LoopStructural except the +two settings. + +- `LoopStructuralConfig.native_faults: bool | None`, + `LoopStructuralConfig.native_threads: int | None`, environment variable + `LOOPSTRUCTURAL_NATIVE_FAULTS`. +- `restore_order(faults, *, reverse=False, owner=None) -> list` + (`LoopStructural/utils/_fault_block.py`) and the keyword `owner` of + `restore_through`. +- `_native_faults.native_enabled()`, `native_threads()`, `chain_for(feature)`, + `field_for(feature)`, `restore(feature, points, *, reverse, block, restored_through)`. +- `loop_interpolation_core.FAULT_KERNEL_VERSION`, `FaultChain(spec)` with + `restore` and `frame_value`, `GridField(spec)` with `values` and + `gradients`; the `FaultChain` spec dict of D2b. A change of this dict or of + the semantics increases `FAULT_KERNEL_VERSION` and + `REQUIRED_FAULT_KERNEL_VERSION` together. +- Spec 005 changes grid and transform code. If it changes + `_lookup_points`, `_project_points` or the bounding box local frame, the + same commit must change `grid_field.rs` and increase the kernel version. + +## Design of stage S5 (package `loop-model-core`) + +### D5. Package layout + +New folder `packages/loop_model_core/` (a separate crate, not a cargo +workspace member of the interpolation core): + +- `Cargo.toml`: `name = "loop-model-core"`, `version = "0.0.0"` (release-please + sets the first version), edition 2024, `[lib] name = "loop_model_core"`, + `crate-type = ["cdylib", "rlib"]`; dependencies `rayon` (optional), + `pyo3` (optional, features `extension-module`, `abi3-py39`), `numpy` + (optional), with the same versions as `packages/loop_interpolation_core/Cargo.toml`; + features `default = []`, `parallel = ["dep:rayon"]`, `python = ["dep:pyo3", "dep:numpy"]`. + No `wasm` feature. +- `Cargo.lock`: generated by cargo for this crate (`cargo generate-lockfile`; + keep the dependency versions of the interpolation core's lock). +- `pyproject.toml`: maturin build backend; `name = "loop-model-core"`, + `version = "0.0.0"`, `requires-python = ">=3.9"`, `dependencies = ["numpy"]`, + the same authors, license and classifiers as the interpolation core; + `[tool.maturin] features = ["python", "parallel"]`, + `module-name = "loop_model_core"`. +- `README.md`: the "Fault kernel" section that is now in the interpolation + core README, rewritten for the new package. +- `src/lib.rs`: `pub mod fault;` and `#[cfg(feature = "python")] mod python;`. +- `src/fault/`: moved unchanged from `packages/loop_interpolation_core/src/fault/` + (`git mv`), including `pool.rs`. +- `src/python.rs`: the fault part of `packages/loop_interpolation_core/src/python.rs` + (from the comment `// Fault kernel` to the end of the fault classes), and a + `#[pymodule] fn loop_model_core` that registers `FaultChain`, `GridField` + and `FAULT_KERNEL_VERSION = 1`. Helpers that both parts used (if any) are + copied, not shared. +- `tests/fault_grid_field.rs`, `fault_profile.rs`, `fault_restore.rs`, + `fault_nearest.rs`, `fault_gradient.rs`: moved (`git mv`); `use + loop_interpolation_core::fault` becomes `use loop_model_core::fault`. + +The interpolation core loses `pub mod fault;` in `src/lib.rs`, the fault +part of `src/python.rs` and its registration, and the "Fault kernel" README +section (replaced by one line that points to `packages/loop_model_core`). + +### D5b. Python side + +- `_native_faults.py` imports `loop_model_core` (not `loop_interpolation_core`); + `FAULT_KERNEL_VERSION` and `REQUIRED_FAULT_KERNEL_VERSION` stay 1. All + names of D2c and D3 stay. +- Root `pyproject.toml`: `native = ["loop-interpolation[native]", "loop-model-core"]`; + `[tool.uv.sources]` gets `loop-model-core = { path = "packages/loop_model_core" }` + (same comment as the interpolation core). `uv lock` updates `uv.lock`. +- The native fault tests (`tests/fault_evaluation/test_native_*.py`) use + `pytest.importorskip("loop_model_core")` and `from loop_model_core import ...`; + `test_native_settings.py` uses the fake module name `loop_model_core`. +- `native_threads()`: a negative setting gives 0 (all cores). +- `chain_for` and `field_for` use `type(x) is` checks for `FaultSegment`, + `FaultDisplacement`, `PositiveRegion`, `NegativeRegion` and + `UnconformityFeature`. + +### D5c. Build, CI and release + +- `.github/workflows/model-core-wheels.yml` (new): a copy of + `core-wheels.yml` for `packages/loop_model_core` (same 5 platforms, abi3, + sdist, `workflow_call`), with the fault smoke test of T030 (import + `loop_model_core`). `core-wheels.yml` loses the fault smoke test. +- `.github/workflows/pypi.yml`: a build job that calls `model-core-wheels.yml` + and an upload job, as for the interpolation core. +- `.github/workflows/native.yml`: the `paths` lists add + `packages/loop_model_core/**`; the `rust` job also runs fmt, clippy (no + features, parallel, python) and test (no features, parallel) for + `packages/loop_model_core/Cargo.toml`; the `wheel` job also runs + `maturin develop --release -m packages/loop_model_core/Cargo.toml` before + `pytest tests/fault_evaluation`. +- `.release-please-config.json`: package `packages/loop_model_core` + (`release-type: python`, `component: loop-model-core`, extra file + `Cargo.toml` `$.package.version`), and `packages/loop_model_core` in the + `exclude-paths` of `"."`. `.release-please-manifest.json`: + `"packages/loop_model_core": "0.0.0"`. +- `.dev-tools/project.json`: a build package `packages/loop_model_core` + with the same cargo commands as the interpolation core. +- `ROADMAP.md`: the spec 007 decision section names `loop-model-core`; a + status line for stage S5. + +### Files (S5) + +- T037: `packages/loop_model_core/` (new), `packages/loop_interpolation_core/src/fault/` + (removed), `packages/loop_interpolation_core/tests/fault_grid_field.rs`, + `fault_profile.rs`, `fault_restore.rs`, `fault_nearest.rs`, + `fault_gradient.rs` (removed), `packages/loop_interpolation_core/src/lib.rs`, + `packages/loop_interpolation_core/src/python.rs`, + `packages/loop_interpolation_core/README.md`. +- T038: `LoopStructural/modelling/features/_native_faults.py`, + `tests/fault_evaluation/test_native_settings.py`, `test_native_faults.py`, + `test_native_safety.py`, `test_native_field.py`, `pyproject.toml`, `uv.lock`. +- T039: `.github/workflows/model-core-wheels.yml` (new), + `.github/workflows/core-wheels.yml`, `.github/workflows/pypi.yml`, + `.github/workflows/native.yml`, `.release-please-config.json`, + `.release-please-manifest.json`, `.dev-tools/project.json`. +- T040: `LoopStructural/modelling/features/_native_faults.py`, + `tests/fault_evaluation/test_native_settings.py`. +- T041: `ROADMAP.md`. +- T042: `specs/007-native-fault-kernel/verification.md`. + diff --git a/specs/007-native-fault-kernel/profile-s1.md b/specs/007-native-fault-kernel/profile-s1.md new file mode 100644 index 000000000..23ac2672d --- /dev/null +++ b/specs/007-native-fault-kernel/profile-s1.md @@ -0,0 +1,140 @@ +# Profile of stage S1 (spec 007) + +This file gives the cut-fault numbers of the 94-fault model before stage S1 (SC-001 baseline), and a profile of one `evaluate_model` call at 500 points. + +- Commit: `d979cff40551c7b55851f20effff81cc3b70662b` (worktree `feat-007-native-fault-kernel`). No code was changed for the measurement. +- Computer: 12th Gen Intel(R) Core(TM) i7-12700H, 20 threads (default thread settings), Ubuntu 26.04.1 LTS, kernel 7.0.0-44-generic, Python 3.13.13. +- Limit: other agents can run work on the same computer at the same time. The times are not exact. Use them to compare shares, not to set tight limits. +- Scripts: `many_faults.build()` and `many_faults.points(500)`, run from the scratch folder `tmp/t002` (`prof.py`). + +## Baseline (Python path, master) + +Source: `_runs007/many_faults_python.json`, case `"500"`. The bit-identity reference is `_runs007/many_faults_python_ref.npz`. + +| Value (500 points) | Result | +|---|---| +| `evaluate_model_seconds` | 1.78 s | +| `fault_calls` | 94 | +| `cutting_mean_ms` | 40.0 ms | +| `cutting_max_ms` | 117.4 ms | +| `isolated_mean_ms` | 2.65 ms | + +## Profile before S1 + +Calls: the first `evaluate_model` call was a warm-up. The second call, without the profiler, took 1.73 s. The third call, with `cProfile`, took 8.17 s. The profiled call is the third call. The profiler makes the run about 4.7 times slower, because the code makes 5.3 million small `is_in` calls. The shares below are therefore only a guide. Use the times without the profiler for SC-001. + +The cumulative time of a function includes the time of the functions it calls. Some functions call themselves (recursion), so the shares can add up to more than 100 percent and must not be added together. + +| Function | ncalls (primitive) | cumulative time (s) | share of 8.17 s | +|---|---|---|---| +| `_calculate_mask` | 2868 (2) | 8.098 | 99.1 % | +| `restore_through` | 2557 (1) | 8.022 | 98.1 % | +| `apply_to_points` | 94 | 8.001 | 97.9 % | +| `_evaluate_frame` | 1034 | 7.908 | 96.7 % | +| `_evaluate_frame_legacy` | 698 | 7.808 | 95.5 % | +| `cutters_first` | 2557 | 6.114 | 74.8 % | +| `_cutters` | 296025 | 5.587 | 68.4 % | +| `is_in` | 5308363 | 4.903 | 60.0 % | +| `up_to_date` (`_base_builder.py`) | 716108 (4696) | 0.667 | 8.2 % | +| `up_to_date` (`_fault_builder.py`) | 235948 (4912) | 0.647 | 7.9 % | +| `with_cutters` | 2557 | 0.596 | 7.3 % | +| `_shared_frame_members` | 754 | 0.026 | 0.3 % | + +Top 20 by cumulative time: + +| Function | ncalls | tottime (s) | cumtime (s) | +|---|---|---|---| +| `_api_registry.py:25(wrapper)` | 1 | 0.000 | 8.174 | +| `geological_model.py:1235(evaluate_model)` | 1 | 0.000 | 8.174 | +| `_geological_feature.py:38(wrapper)` | 2560 (2) | 0.006 | 8.174 | +| `_geological_feature.py:153(evaluate_value)` | 1900 (2) | 0.012 | 8.174 | +| `_geological_feature.py:143(_restore_points)` | 2560 (4) | 0.001 | 8.168 | +| `_evaluation.py:222(restore)` | 4 | 0.000 | 8.168 | +| `_evaluation.py:102(restore)` | 4 | 0.000 | 8.168 | +| `_base_geological_feature.py:236(_calculate_mask)` | 2868 (2) | 0.004 | 8.098 | +| `_unconformity_feature.py:89(__call__)` | 2 | 0.000 | 8.098 | +| `_unconformity_feature.py:65(evaluate)` | 2 | 0.000 | 8.098 | +| `_fault_block.py:210(restore_through)` | 2557 (1) | 0.007 | 8.022 | +| `_fault_segment.py:648(apply_to_points)` | 94 | 0.028 | 8.001 | +| `_fault_segment.py:355(_evaluate_frame)` | 1034 | 0.007 | 7.908 | +| `_fault_segment.py:446(_evaluate_frame_legacy)` | 698 | 0.004 | 7.808 | +| `_base_geological_feature.py:272(_apply_faults)` | 2556 | 0.002 | 6.932 | +| `_fault_block.py:189(cutters_first)` | 2557 | 0.173 | 6.114 | +| `_fault_block.py:151(_cutters)` | 296025 | 1.264 | 5.587 | +| `_fault_block.py:146(is_in)` | 5308363 | 1.996 | 4.903 | +| `~:0()` | 5261591 (5578846) | 1.670 | 2.802 | +| `_fault_block.py:148()` | 20193440 | 1.299 | 1.299 | + +The call to `is_in` and its generator, `_cutters`, `cutters_first` and `any` are in `LoopStructural/utils/_fault_block.py`. `_calculate_mask` is in `_base_geological_feature.py`. The next row after the top 20 is `evaluate_gradient` (1.978 s). + +## Where the time goes + +The restore order work is the largest part: `cutters_first` takes 74.8 % of the profiled time, and nearly all of it is in `_cutters` and `is_in` (5.3 million calls). Together with their `any` calls and generators, the self time of these functions is about 6.4 s of 8.17 s. `with_cutters` takes only 7.3 % and `_shared_frame_members` less than 1 %. The frame evaluation work (`_evaluate_frame_legacy`) is high in the cumulative column (95.5 %), but this is because it calls `restore_through` again for each cutting fault; its own time is very small. The `up_to_date` checks add about 16 % in two functions that overlap with the rest. Plan OP3: S1 must remove the `is_in` and `_cutters` loops first, because they are the main cost; the cost of the frame evaluation itself stays small in this profile. + +## After D1a + +Run: the benchmark and the profile ran one after the other, with the code of D1a (T004). No code was changed for the measurement. Limit: other agents can build Rust code on the same computer at the same time, so the times are not exact. + +Command: `python -m benchmarks.fault_evaluation.many_faults --output many_faults_d1a.json --points 500 2000 5000 --compare _runs007/many_faults_python_ref.npz`. The reference file holds arrays for 500, 2000 and 5000 points, and `compare()` marks an array that is missing from the run as a difference. Therefore the run used all three point counts. SC-001 uses the 500 case. + +| Value (500 points) | Baseline | After D1a | +|---|---|---| +| `evaluate_model_seconds` | 1.78 s | 0.730 s | +| `fault_calls` | 94 | 94 | +| `cutting_mean_ms` | 40.0 ms | 13.6 ms | +| `cutting_max_ms` | 117.4 ms | 25.4 ms | +| `isolated_mean_ms` | 2.65 ms | 2.66 ms | + +Other point counts: 2000 points: cutting mean 15.8 ms, max 27.7 ms, isolated mean 2.75 ms, `evaluate_model` 0.808 s. 5000 points: cutting mean 20.1 ms, max 32.9 ms, isolated mean 3.42 ms, `evaluate_model` 1.019 s. The model build took 195 s. + +`--compare` exit code: 1. Message: `differ: ['group_0_2000', 'group_0_500', 'group_0_5000', 'group_1_2000', 'group_1_500', 'group_1_5000']`. The arrays `model_ids_*` are bit-identical. The values of the two groups differ from the reference at all three point counts. This needs a check by the owner of D1a (the difference can come from a change in the order of the fault restore). + +SC-001: fail (13.6 ms) + +### Profile after D1a + +Calls: one warm-up `evaluate_model` call, then one call without the profiler (0.678 s), then one call with `cProfile` (2.456 s; before D1a: 1.73 s and 8.17 s). The shares are of 2.456 s. As before, cumulative times include called functions, so the shares must not be added together. + +| Function | ncalls | cumulative time (s) | share of 2.456 s | share before D1a | +|---|---|---|---|---| +| `_calculate_mask` | 2868 | 2.381 | 96.9 % | 99.1 % | +| `restore_through` (now `_fault_block.py:255`) | 2557 | 2.306 | 93.9 % | 98.1 % | +| `apply_to_points` | 94 | 2.302 | 93.7 % | 97.9 % | +| `_evaluate_frame` | 1034 | 2.213 | 90.1 % | 96.7 % | +| `_evaluate_frame_legacy` | 698 | 2.115 | 86.1 % | 95.5 % | +| `_apply_faults` | 2556 | 1.287 | 52.4 % | 84.8 % | +| `restore_order` (replaces `cutters_first`) | 2557 | 1.051 | 42.8 % | 74.8 % (`cutters_first`) | +| `is_in` | 790406 | 0.936 | 38.1 % | 60.0 % (5308363 calls) | +| `_cutters` | 52428 | 0.834 | 34.0 % | 68.4 % (296025 calls) | +| `up_to_date` (`_base_builder.py`) | 716108 | 0.649 | 26.4 % | 8.2 % | +| `up_to_date` (`_fault_builder.py`) | 235948 | 0.629 | 25.6 % | 7.9 % | +| `with_cutters` | 2557 | 0.589 | 24.0 % | 7.3 % | +| `any` (built-in) | 791078 | 0.580 | 23.6 % | n/a | + +The `is_in` and `_cutters` work is still the largest single part (about 38 % of the profiled time), but it fell from 5.3 million to 0.79 million `is_in` calls. The `up_to_date` checks and `with_cutters` now have a larger share, because the total is smaller (their absolute times are about the same). + +## After D1b + +D1b shares one restoration among the three members of a cut frame (`FaultSegment._evaluate_frame_legacy`, helper `_evaluate_frame_shared`). The masks use the original points. The gradient of member 1 keeps its own call: a member with faults, called without `restored_through`, takes the tetrahedron branch, and a direct interpolator gradient on the restored points is not bit-identical to it (it differs by about 5e-5 in `test_fault_frame_lookup`). The values (gx, gy, gz) are shared. + +Bit identity: one process, one build of the 94-fault model. `evaluate_model` and `evaluate_feature_value` of both groups at 500 and 5000 points, with D1b and with the switch `_SHARE_CUT_FRAME_RESTORATION = False` (the old path): all 6 comparisons are equal with `np.array_equal(..., equal_nan=True)`. D1b is kept. + +Timing (`many_faults`, no `--compare`, other agents built Rust code at the same time, so the timings may be too high): + +| Points | `cutting_mean_ms` | `cutting_max_ms` | `isolated_mean_ms` | `evaluate_model` | +|---|---|---|---|---| +| 500 | 10.83 | 18.74 | 2.01 | 0.571 s | +| 2000 | 12.93 | 20.84 | 2.73 | 0.692 s | +| 5000 | 17.03 | 25.98 | 3.40 | 0.894 s | + +SC-001: fail (10.8 ms) + +### Quiet run (orchestrator, 2026-11-27, no other work on the computer) + +| Points | `cutting_mean_ms` | `cutting_max_ms` | `isolated_mean_ms` | `evaluate_model` | +|---|---|---|---|---| +| 500 | 10.77 | 18.55 | 2.65 | 0.615 s | +| 2000 | 12.97 | - | - | 0.692 s | +| 5000 | 17.01 | - | - | 0.894 s | + +SC-001: fail (10.8 ms; target 10 ms; 39.1 ms before S1) diff --git a/specs/007-native-fault-kernel/run-state.json b/specs/007-native-fault-kernel/run-state.json new file mode 100644 index 000000000..1e28d0016 --- /dev/null +++ b/specs/007-native-fault-kernel/run-state.json @@ -0,0 +1,496 @@ +{ + "spec": "007-native-fault-kernel", + "worktree": "/home/lgrose/dev/LoopStructural-wt/feat-007-native-fault-kernel", + "branch": "feat/007-native-fault-kernel", + "review_mode": "wave", + "start_commit": "907acf425c967d0f1a232d010e3245090c0da993", + "baseline": { + "ruff_errors": 34, + "ruff_gate": "no new errors (34 on master 6874364c; CI runs ruff with --exit-zero)" + }, + "waves": [ + { + "wave": 1, + "base": "d979cff40551c7b55851f20effff81cc3b70662b", + "commit": "cceb9b575f540f8bb0f2a181c611f8af95ecc570", + "review": "pass (1 major rejected: plan text out of date, plan.md D2a fixed; 2 minor)" + }, + { + "wave": 2, + "base": "61b72cdc560536ab38b8ba65eac2420c67437063", + "commit": "2c719e162002ad84bdbcd506c80a6512abc32a3f", + "review": "pass after one fix round (7216f64d; recheck pass)" + }, + { + "wave": 3, + "base": "599890b6ddea087309ebb7cdba0ab264922dfb59", + "commit": "9bddcc34eb82aa7e1eec92fcf08d89a356300ce2", + "review": "pass (3 minor; 1 resolved: the benchmark tests pass with the new key)" + }, + { + "wave": 4, + "base": "c9a6b54abde9aad317e4a5546d390ff1d7cb3020", + "commit": "66af7228cab42d582d6aadf2508b79416a7a092f", + "review": "pass (4 minor)" + }, + { + "wave": 5, + "base": "60139c091dd46bdf7f91bb38517a724543af7a48", + "commit": "6d929073246616a981d214dd96861d9e25db896a", + "review": "pass (5 minor)" + }, + { + "wave": 6, + "base": "3ee22903c989150b9054a4eecce18d48374fc305", + "commit": "1fb6918d8e62042f5cc968cfea49af1af3e88419", + "review": "pass (3 minor)" + }, + { + "wave": 7, + "base": "dcad71c78bc58501456311cd57a66b028e84f88d", + "commit": "fb85400704439b71ec8df3f2dedeab9805e7a1d5", + "review": "pass after one fix round (afe0f593; recheck pass, 1 minor)" + }, + { + "wave": 8, + "base": "2d44bdaaa8746edf7c8fb2784db730b8b8b1df30", + "commit": "23134f85095598524aeb0365817fdda71e5e942f", + "review": "pass (2 minor)" + }, + { + "wave": 9, + "base": "d12101b223acf7c758a410ea0d6cdc978450b3eb", + "commit": "f8a612efce119d816d94f8524b39b8b517825328", + "review": "pass (2 minor)" + }, + { + "wave": 10, + "base": "f03510d573851dcd7e5ddd4b498868fc780f8ba9", + "commit": "fb1875ad3cd16077b55c0bf79fca1c11e9b27326", + "review": "pass (1 minor, fixed in T033)" + }, + { + "wave": 11, + "base": "3d6cc26e90383a313328a7e784612c02ad251357", + "commit": "3260064e51b1c0b3497966a898e5279fd53f19d2", + "review": "end review (opus, Focus all): no blocker; 3 major = maintainer decisions (SC-001, SC-002, SC-008); 3 minor" + }, + { + "wave": 12, + "base": "9f41453fdde37371bd82aa741963c9397fbd9571", + "commit": "51e45ca7e727c90aeca557b493c6de499b7cc6b1", + "review": "pass (no findings)" + }, + { + "wave": 13, + "base": "6c501f4edc7f9ee8a890255d73d0267e1a8aab9d", + "commit": "d666ae660f9b5df6ac9cec533d59b25c456cd91a", + "review": "pass (no findings)" + }, + { + "wave": 14, + "base": "f89026e71d2a7dc19858381d75bc9d0d805f88c4", + "commit": "02e8cb46d9f4eeefd8e1aaf256c1c8df505ef635", + "review": "pass (1 minor)" + }, + { + "wave": 15, + "base": "a95d2e7826030256e06b07b594dc2c2a16a84d82", + "commit": "2f2a06e9f648e3677a978496b4c5e372ef5bd895", + "review": "pass (1 minor)" + }, + { + "wave": 16, + "base": "5c7a673f89dccbc03460e7d2497eb63abd800de1", + "commit": "see git log", + "review": "S5 end review (opus): pass, 3 minor" + } + ], + "runs": { + "T001": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T003": [ + { + "model": "sonnet", + "result": "pass" + }, + { + "model": "sonnet", + "result": "pass (fix: removed equal_nan; sensitivity to a wrong order checked)" + } + ], + "T008": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T009": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T014": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T002": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T004": [ + { + "model": "sonnet", + "result": "blocked (T003 test used equal_nan, not accepted by numpy 2.5); passed after the T003 fix" + } + ], + "T010": [ + { + "model": "sonnet", + "result": "pass" + }, + { + "model": "sonnet", + "result": "pass (review fix)" + } + ], + "T011": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T015": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T023": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T005": [ + { + "model": "sonnet", + "result": "pass (SC-001 fail: 13.6 ms; group values differ from the _runs007 reference, cause: the reference build, not D1a)" + } + ], + "T012": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T019": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T006": [ + { + "model": "sonnet", + "result": "blocked (test_fault_frame_lookup.py lookup counts; maintainer allowed the change)" + }, + { + "model": "sonnet", + "result": "pass" + }, + { + "model": "sonnet", + "result": "pass (fix: test pins the Python path)" + } + ], + "T013": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T024": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T017": [ + { + "model": "sonnet", + "result": "pass" + }, + { + "model": "sonnet", + "result": "pass (fix: reverse fallback case)" + } + ], + "T018": [ + { + "model": "sonnet", + "result": "pass" + }, + { + "model": "sonnet", + "result": "pass" + } + ], + "T025": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T020": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T030": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T007": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T016": [ + { + "model": "sonnet", + "result": "blocked (reverse with an unrestored cutter differs; Python-internals tests count apply_to_points; NaN rows)" + }, + { + "model": "sonnet", + "result": "pass (blocked on 4 tests whose premise changed; fixed in their owner tasks)" + } + ], + "T031": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T034": [ + { + "model": "haiku", + "result": "pass" + }, + { + "model": "haiku", + "result": "pass (fix: test_concurrency)" + }, + { + "model": "haiku", + "result": "pass (fix: test_no_retention, test_fault_frame_lookup)" + } + ], + "T021": [ + { + "model": "sonnet", + "result": "pass (SC-002 fail 0.23-0.30; SC-003 pass 0.023-0.028; SC-007 pass)" + } + ], + "T026": [ + { + "model": "sonnet", + "result": "pass" + }, + { + "model": "sonnet", + "result": "pass (review fix)" + }, + { + "model": "haiku", + "result": "pass (fix: fold exclusion)" + }, + { + "model": "haiku", + "result": "pass (fix: native on in test_field_for_exists)" + } + ], + "T027": [ + { + "model": "sonnet", + "result": "pass (blocked only on a test exclusion; fixed in T026)" + } + ], + "T035": [ + { + "model": "sonnet", + "result": "pass (no measurable gain on a quiet computer; SC-002 still fails 0.23-0.30)" + }, + { + "model": "haiku", + "result": "pass (record fix: quiet numbers)" + } + ], + "T022": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T028": [ + { + "model": "sonnet", + "result": "pass (SC-004 0.059 s vs 0.5 s; SC-005 pass)" + } + ], + "T029": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T032": [ + { + "model": "sonnet", + "result": "pass (Linux x86_64 only; 4 platforms need a CI run)" + } + ], + "T036": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T033": [ + { + "model": "sonnet", + "result": "pass (native on 3341/1 known; off 3341/1 known; not installed 3296/0)" + } + ], + "T037": [ + { + "model": "sonnet", + "result": "pass (orchestrator ran cargo fmt on one moved test file)" + } + ], + "T038": [ + { + "model": "sonnet", + "result": "pass (uv.lock not changed: master lock is stale; orchestrator decision)" + } + ], + "T039": [ + { + "model": "sonnet", + "result": "pass" + } + ], + "T040": [ + { + "model": "haiku", + "result": "pass (also fixed the settings fixture: it reloads _native_faults at teardown)" + } + ], + "T041": [ + { + "model": "haiku", + "result": "pass" + } + ], + "T042": [ + { + "model": "sonnet", + "result": "pass (on 3343/1 known; off 3343/1 known; model core not installed 3311/1 known)" + } + ] + }, + "findings": { + "found": 43, + "rejected": 2, + "dropped": 0, + "fixed": 4, + "open_minor": [ + "T011: Profile::block_displacement goes on to continue_profile for a NaN gx (Python returns the profile at forced_gx); no path gives a NaN gx today.", + "T011: taylor computes 12.0*h*h, Python 12.0*h**2 (1 ulp at most).", + "T012: Region::Sign::contains allocates vec![false; n] and FaultChain::restore copies restored on each call (hot path; measure in T021).", + "T019: --native-faults default off overwrites LOOPSTRUCTURAL_NATIVE_FAULTS set by the user (the result records native_faults: off).", + "T013: FaultChain requires steps >= 1; Python allows steps = 0 (no movement). T016 must send such a fault to the Python path.", + "T013: parse_grid nsteps product can overflow in release; use checked_mul and ValueError.", + "T013: the spec parser accepts NaN/inf numbers and a zero step_vector.", + "T006: _evaluate_frame_shared calls builder.up_to_date for all 3 members even when one is not evaluated.", + "T006: _evaluate_frame_shared uses restore_through, not the scope-shared restore(); no value change.", + "T018: test_native_path_is_used cannot fail if evaluate_value skips the native path (restore() sets _native_chain first).", + "T018: test_two_threads_equal_single_thread warms the chain first, so a race while the chain is built is not exercised.", + "T018: test_bad_spec_raises_and_state_is_kept: the state check cannot fail (the bad spec never touches the feature).", + "T017: test_native_off_by_variable tests only '0' (not false/off/no).", + "T020: native.yml path filter misses _evaluation.py, _base_geological_feature.py and tests/fault_evaluation/**.", + "T017: the fallback check accepts None for any reverse case of a feature with cutters; a wrong fallback in such a case would pass.", + "T016: restore() and the forward/reverse callers share one _restore_order slot on the feature, so alternating reverse and forward calls recompute the order.", + "T016: FaultChain(spec) build errors are raised, not turned into the Python path (for example a node-value count that does not match the grid).", + "T016: the token compares floats with ==; a NaN displacement rebuilds the chain at each call.", + "T021: verification.md names the memory rule acceptance.py _check_memory; the function is _sc006.", + "T021: the SC-007 pass is relative to the Python base; native extra memory is 2.9 x the point array and the reason is open.", + "T021: the measurement scripts are in the job tmp folder, outside the repo; the method is only described.", + "T026: the parity test does not assert that _faulted(model) is not empty.", + "T035: the largest native difference of cutting_faults went from 5.7e-13 to 1.25e-12 although T035 claims the same floating-point operations; within tolerance, not explained.", + "T027: evaluate_value/evaluate_gradient call _check_frame() and update() again after field_for already did (no wrong result).", + "T027: the native binding rejects element_scale_parameter <= 0 with ValueError, where Python gave a degenerate result (edge case).", + "T028: the Python time of SC-004 includes the _FaultTimer patch overhead; the native run has none (favours native slightly).", + "T028: the SC-004 scratch script is outside the repo; rerun with the benchmark after T036.", + "End review: no test checks that native_threads = 1 really uses one thread (pool(1).current_num_threads()).", + "End review: the native unconformity region ignores faults_enabled and the regions of the UnconformityFeature (both default in current models).", + "T040: the subclass test does not first assert that chain_for gives a chain for the unchanged model.", + "T041: the ROADMAP spec 007 decision section lists stages S1 to S4 only; add S5 (kernel moved to loop-model-core).", + "S5: native.yml header comment names only loop_interpolation_core.", + "S5: the loop-model-core README and the LoopStructuralConfig docstring do not say that a negative native_threads means all cores.", + "S5 (merge): release-please makes the first loop-model-core release only for a feat/fix commit; squash-merge with a feat title or add Release-As." + ] + }, + "sc001": { + "before_s1_ms": 39.1, + "after_d1a_ms": 13.6, + "after_d1b_quiet_ms": 10.73, + "target_ms": 10, + "result": "fail (marginal); reported to the maintainer at the end" + }, + "pre_existing_failures": [ + "tests/unit/modelling/test_native_fault_frame.py::test_the_native_fault_frame_is_the_cg_fault_frame fails on 907acf42 (master + benchmark) when loop_interpolation_core is installed (native solver, #383); it was skipped before the core was installed in the venv." + ], + "native_max_diff": { + "restore": 9.3e-10, + "model": "stopped_fault" + }, + "sc002_quiet": { + "f1_u0": 0.298, + "f4_u0": 0.289, + "f4_u3": 0.294, + "cutting_faults": 0.231, + "plugin": 0.268, + "target": 0.2, + "result": "fail" + }, + "sc004": { + "native_s_5000": 0.059, + "python_same_run_s": 0.971, + "master_s": 2.09, + "target_s": 0.5, + "result": "pass" + }, + "end_review": { + "model": "opus", + "verdict": "changes needed (maintainer decisions only)", + "decisions_needed": [ + "SC-001 10.7 ms vs 10 ms", + "SC-002 0.23-0.30 vs 0.20", + "SC-008 CI run of core-wheels.yml on 4 platforms" + ] + } +} \ No newline at end of file diff --git a/specs/007-native-fault-kernel/tasks.md b/specs/007-native-fault-kernel/tasks.md new file mode 100644 index 000000000..c344e205e --- /dev/null +++ b/specs/007-native-fault-kernel/tasks.md @@ -0,0 +1,806 @@ +# Tasks: native fault application + +**Feature**: `007-native-fault-kernel` | **Plan**: [plan.md](plan.md) + + + +## Orchestrator notes + +- Run this file with the spec-orchestrator skill. It has the rules for the + worktree, the sub agents, the checks and the commits. +- Waves: 16. Tiers: [S] = simple model, [M] = standard model. +- Do not start a task with "Blocked by". + +## Phase 1: Setup + +- [x] T001 [Setup] [S] Record the decision to add the native fault path in `ROADMAP.md` (FR-015). + - Files: `ROADMAP.md` + - Needs: none + - Wave: 1 + - Done when: `ROADMAP.md` has the section `### Native fault application (spec 007)` under `## Decisions`, and `git diff --stat` shows only `ROADMAP.md`. + - Context: Add a section after the last `###` section of `## Decisions` + (before `## Stage sequence`). Content, 5 to 10 lines: the native path is + an optional Rust kernel in `loop_interpolation_core`; the Python path + stays the reference and the fallback; on by default when the kernel is + installed and `FAULT_KERNEL_VERSION` matches; off with + `LoopStructuralConfig.native_faults = False` or the environment variable + `LOOPSTRUCTURAL_NATIVE_FAULTS=0` (the setting wins); tolerance 1e-8 x the + model box (spec 003 FR-004); stages S1 (restore order once), S2 (native + restore), S3 (native values and gradients), S4 (wheels). Link + `specs/007-native-fault-kernel/spec.md`. ASD-STE100 style. + +## Phase 2: Stage S1, restore order once (story 1) + +- [x] T002 [US1] [M] Measure the cut faults of the 94-fault model before stage S1 (SC-001 baseline). + - Files: `specs/007-native-fault-kernel/profile-s1.md` + - Needs: none + - Wave: 1 + - Done when: `profile-s1.md` exists with the baseline numbers at 500 points and a `cProfile` top-20 table (by cumulative time) of one `evaluate_model` call at 500 points. + - Context: Baseline (Python path, master): copy from + `/home/lgrose/dev/LoopStructural-wt/_runs007/many_faults_python.json` + (`cases["500"]`: `cutting_mean_ms` 40.0, `cutting_max_ms` 117.4, + `isolated_mean_ms` 2.65, `evaluate_model_seconds` 1.78). The bit-identity + reference is `_runs007/many_faults_python_ref.npz`. Profile: in a script + in `$CLAUDE_JOB_DIR/tmp` or `/tmp`, call `many_faults.build()` and + `many_faults.points(500)` (`benchmarks/fault_evaluation/many_faults.py`; + the build takes about 7 minutes), then `cProfile` one + `model.evaluate_model(pts)`. Report the share of time in `with_cutters`, + `cutters_first`, `_cutters`, `_evaluate_frame_legacy` and + `restore_through` (`LoopStructural/utils/_fault_block.py`, + `LoopStructural/modelling/features/fault/_fault_segment.py`). Record the + computer and the commit. Change no code. + +- [x] T003 [US1] [M] Test: the restore order is computed once for each state of the faults (FR-001, FR-002). + - Files: `tests/fault_evaluation/test_restore_order.py` + - Needs: none + - Wave: 1 + - Done when: `pytest tests/fault_evaluation/test_restore_order.py -q` fails (no `restore_order`), then passes after T004. + - Context: New function (T004) in `LoopStructural/utils/_fault_block.py`: + `restore_order(faults, *, reverse=False, owner=None) -> list`. With + `owner`, it keeps `owner._restore_order = (key, chain, ordered)`. + Tests: (1) on `build_model("cutting_faults")` (`tests/fault_evaluation/models.py`), + evaluate a faulted feature twice; with `unittest.mock.patch` on + `LoopStructural.utils._fault_block.cutters_first` (wraps=original), the + second call does not call it. (2) Story 1 scenario 2: add a new cutter to + a fault builder (`fault.builder.builders[i].faults.append(other)`) after + the first call; the next `restore_order` result differs and puts `other` + before the fault. (3) Bit-identical: `capture(model, points)` + (`tests/fault_evaluation/golden.py`) for `cutting_faults` and `f4_u3` + with the cache equals a run with `owner=None` + (`np.testing.assert_array_equal`, `equal_nan=True`). (4) `reverse=True` + gives the reversed order rule of `restore_through`. + +- [x] T004 [US1] [M] Add `restore_order` with the order cache and pass `owner` from the two callers (D1a). + - Files: `LoopStructural/utils/_fault_block.py`, `LoopStructural/modelling/features/_base_geological_feature.py`, `LoopStructural/modelling/features/_evaluation.py` + - Needs: T003 + - Wave: 2 + - Done when: `pytest tests/fault_evaluation -q` passes. + - Context: `restore_order(faults, *, reverse=False, owner=None) -> list`. + Without owner: `cutters_first(with_cutters(faults))`; if reverse, + `cutters_first(with_cutters(faults)[::-1])[::-1]`. With owner: compute + `chain = with_cutters(faults)` and + `key = (bool(reverse), tuple((id(f), tuple(id(c) for c in _cutters(f))) for f in chain))`; + if `getattr(owner, "_restore_order", None)` has an equal key, return its + `ordered`; else compute and set `owner._restore_order = (key, chain, ordered)` + in one assignment (thread-safe). `restore_through(points, faults, *, + reverse=False, block=None, restored_through=(), owner=None)` uses + `restore_order` in place of its two order lines; nothing else changes. + `BaseFeature._apply_faults` passes `owner=self`. `EvaluationContext.restore` + passes `owner=feature` in both `restore_through` calls. Do not change the + builder calls. + +- [x] T005 [US1] [M] Measure the cut faults again after D1a and compare with SC-001. + - Files: `specs/007-native-fault-kernel/profile-s1.md` + - Needs: T002, T004 + - Wave: 3 + - Done when: `profile-s1.md` has an "After D1a" section with the numbers of T002 and one line "SC-001: pass" or "SC-001: fail ( ms)". + - Context: Run + `python -m benchmarks.fault_evaluation.many_faults --output /tmp/many_faults_d1a.json --points 500 --compare /home/lgrose/dev/LoopStructural-wt/_runs007/many_faults_python_ref.npz` + (about 7 minutes; exit 1 means a model id or group value differs bit for + bit). SC-001: `cases["500"]["cutting_mean_ms"]` at most 10 ms (baseline + 40.0) and exit code 0. Also run the T002 profile again and give the new + shares. Change no code. + +- [x] T006 [US1] [M] Share one restoration among the members of a cut frame, only if T005 reports that SC-001 fails (D1b, OP3). + - Files: `LoopStructural/modelling/features/fault/_fault_segment.py`, `tests/fault_evaluation/test_restore_order.py`, `specs/007-native-fault-kernel/profile-s1.md`, `tests/fault_evaluation/test_fault_frame_lookup.py` + - Needs: T005 + - Wave: 4 + - Done when: if T005 says "SC-001: pass", `profile-s1.md` has the line "D1b: not needed" and no code changes; else `pytest tests/fault_evaluation -q` passes, the `many_faults --compare` run of T005 exits with 0, and `profile-s1.md` has an "After D1b" section with "SC-001: pass" or "fail". + - Context: In `FaultSegment._evaluate_frame_legacy`: if the 3 members have + the same non-empty fault list (each item compared with `is`), compute + `restored = restore_through(points, m0.faults, block=block, + restored_through=restored_through, owner=m0)` once, and call each + member (`evaluate_value`, and `evaluate_gradient(ignore_regions=True)` + of member 1) with `restored` and + `restored_through=tuple(restored_through) + tuple(restore_order(m0.faults, owner=m0))`. + The masks must still use the original points; if this cannot be done + without a change of a member method, stop and report. Add a test to + `test_restore_order.py`: `capture` of `cutting_faults` is bit-identical + with and without D1b. If a difference shows, revert D1b and record + "D1b: dropped (not bit-identical)". + +- [x] T007 [US1] [S] Record stage S1 in `ROADMAP.md` (FR-015). + - Files: `ROADMAP.md` + - Needs: T001, T006 + - Wave: 5 + - Done when: `ROADMAP.md` `## Status log` has a dated line for spec 007 stage S1 with the SC-001 result from `profile-s1.md`. + - Context: Add one line at the end of `## Status log`, format as the lines + above it: date 2026-MM-DD of the day, "spec 007 S1: restore order + computed once for each state of the faults (`restore_order`)", the + SC-001 numbers (before and after) and "D1b: used / not needed / dropped" + from `specs/007-native-fault-kernel/profile-s1.md`. + +## Phase 3: Foundation, Rust module skeleton + +- [x] T008 [Found] [M] Add the Rust module `fault` with all types and function stubs (D2a). + - Files: `packages/loop_interpolation_core/src/fault/`, `packages/loop_interpolation_core/src/lib.rs` + - Needs: none + - Wave: 1 + - Done when: `cargo check --all-targets` and `cargo check --all-targets --features parallel` pass in `packages/loop_interpolation_core`. + - Context: `lib.rs`: add `pub mod fault;`. Files in `src/fault/`: + `mod.rs` (`pub struct FaultChain { pub faults: Vec, pub block: BlockSettings }`, + `pub struct Fault { pub frame: [GridField; 3], pub cutters: Vec, pub regions: Vec, pub profile: Profile, pub displacement: f64, pub steps: usize }`, + `pub struct BlockSettings { pub side_epsilon: f64, pub extension: Extension, pub exact: f64, pub limit: f64, pub step: f64 }`, + `pub enum Extension { Smooth, Mirror }`, `pub enum Side { Free, Absent, Hanging, Foot }`), + `grid_field.rs` (`GridField` with fields of plan D2a, `value`, `gradient`), + `profile.rs` (`Profile1`, `Profile`), `region.rs` (`Region` enum with + `Sign` and `Unconformity`), `restore.rs` (`apply`, `restore`, + `frame_value` on `FaultChain`), `nearest.rs` (`KdTree::new(&[[f64;3]])`, + `nearest(&self, p) -> usize`), `gradient.rs` (`feature_gradient`), + `pool.rs` (`#[cfg(feature = "parallel")] pub fn pool(threads: usize) -> Arc`). + Exact signatures: plan.md D2a. Stub bodies: `unimplemented!("T0xx")` + with the id of the task that writes the body. Derive `Debug, Clone` on + data types. Doc comment on each public item. + +- [x] T034 [Found] [S] Run the spec 003 tests of the Python path internals with the native path off (plan "Answers", T016). + - Files: `tests/fault_evaluation/conftest.py` + - Needs: none + - Wave: 1 + - Done when: `LOOPSTRUCTURAL_NATIVE_FAULTS= pytest tests/fault_evaluation/test_context.py tests/fault_evaluation/test_gradient_context.py tests/fault_evaluation/test_memory.py -q` passes with the native kernel installed and T016 code present. + - Context: New file `tests/fault_evaluation/conftest.py`. An autouse + fixture `_python_path_for_internals(request, monkeypatch)`: if + `request.module.__name__` ends with one of `test_context`, + `test_gradient_context`, `test_memory`, set + `monkeypatch.setattr(LoopStructuralConfig, "native_faults", False)` + (`from LoopStructural import LoopStructuralConfig`). Docstring: these + tests count or patch calls of the Python `FaultSegment.apply_to_points`, + which the native path does not call (spec 007 plan, Answers, T016). + `from __future__ import annotations`; numpy-style docstring. + +## Phase 4: Stage S2, native restoration (stories 2, 4 and 5) + +- [x] T009 [US2] [M] Find why the proof of concept differs from the Python path (C-007, OP9). + - Files: `specs/007-native-fault-kernel/verification.md` + - Needs: none + - Wave: 1 + - Done when: `verification.md` has a section "C-007: proof-of-concept difference" with a table: item, Python behaviour (file:line), proof-of-concept behaviour (file:line), effect on the result. + - Context: Read only, do not change: the proof of concept in + `/home/lgrose/dev/LoopStructural-wt/_runs003/rust_poc/` (`README.md`, + `loop-snapshot/`, `pyext/`, `export_snapshot.py`) and the Python reference: + `LoopStructural/modelling/features/fault/_fault_segment.py` + (`apply_to_points`, `_evaluate_frame`, `_displacement_fraction`), + `.../fault/_fault_function.py` (`CubicFunction.__call__`, + `_limit_value`, `continue_profile`, `block_displacement`, `_saturate`, + `_taylor`), `LoopStructural/utils/_fault_block.py`. Check at least: the + step direction of #425, `BLOCK_EXTENSION`, `_limit_value`, the local + frame (`_project_points`, rotation), f32 against f64, the order of the + steps and of the faults. If the folder is not there, write + "not available" and list only the risks. + +- [x] T010 [US2] [M] Port the structured grid lookup to `grid_field.rs`, with Rust tests. + - Files: `packages/loop_interpolation_core/src/fault/grid_field.rs`, `packages/loop_interpolation_core/tests/fault_grid_field.rs` + - Needs: T008 + - Wave: 2 + - Done when: `cargo test --release --test fault_grid_field` fails against the stub, then passes, also with `--features parallel`. + - Context: Port the grid methods `_lookup_points`, `trilinear`, + `_values_from_coefficients`, `_evaluate_gradient_from_lookup` + (`packages/loop_common/src/loop_common/supports/_3d_structured_grid.py`, + `packages/loop_common/src/loop_common/geometry/_structured_grid_3d.py`) + and the interpolator methods `_project_points` and `_reproject_vectors` + (world to local frame with `local_origin` and `local_rotation`; `None` + means identity). `value(p)` NaN if a coordinate is NaN or the point is + outside the grid; `gradient(p)` NaN for a NaN coordinate and [0, 0, 0] + outside the grid (as Python), returned in world axes. + Tests: a field linear in x, y, z (exact value and gradient), a rotated + local frame, a NaN point, an outside point, and 5 points with expected + values copied from a Python run of the same grid (write the Python + snippet in a comment of the test). + +- [x] T011 [US2] [M] Port the fault displacement profiles to `profile.rs`, with Rust tests. + - Files: `packages/loop_interpolation_core/src/fault/profile.rs`, `packages/loop_interpolation_core/tests/fault_profile.rs` + - Needs: T008 + - Wave: 2 + - Done when: `cargo test --release --test fault_profile` fails against the stub, then passes. + - Context: `Profile1 { Ones, Zeros, SmoothPeak, Cubic { w: [f64;4], lim: [f64;2], min: f64, max: f64, value_points: Vec<(f64,f64)> }, Composite { positive: Box, negative: Box } }`, + `Profile { scale, gx, gy, gz }`. Port from + `LoopStructural/modelling/features/fault/_fault_function.py`: + `smooth_peak`, `CubicFunction.__call__` (limits through `_limit_value`, + then floor and ceiling), `Composite.__call__` (0 at v == 0), + `FaultDisplacement.__call__` (`scale * gx * gy * gz`), `_saturate`, + `_taylor`, `continue_profile` (including the `allclose` check at + `side * [BLOCK_SIDE_EPSILON, BLOCK_EXTENSION_STEP]` with atol 1e-12) and + `block_displacement` (Smooth and Mirror). Tests: values of + `BaseFault.fault_displacement` and `BaseFault3D.fault_displacement` at + gx, gy, gz in {-1.5, -1, -0.5, 0, 0.3, 1, 2}, and `block_displacement` + for side +1 and -1, compared with values from Python to 1e-14. + +- [x] T012 [US2] [M] Implement the native restoration, regions and thread pool (`restore.rs`, `region.rs`, `pool.rs`). + - Files: `packages/loop_interpolation_core/src/fault/restore.rs`, `packages/loop_interpolation_core/src/fault/region.rs`, `packages/loop_interpolation_core/src/fault/pool.rs`, `packages/loop_interpolation_core/src/fault/mod.rs`, `packages/loop_interpolation_core/tests/fault_restore.rs` + - Needs: T010, T011 + - Wave: 3 + - Done when: `cargo test --release --test fault_restore` passes, also with `--features parallel`. + - Context: Port `FaultSegment.apply_to_points` for one point (`force_side`, + `_displacement_fraction`, `steps` Euler steps along the normalised + gradient of frame member 1, `reverse`, block sides, NaN rules of #413, + and #425: a NaN gradient of a cut frame uses the plain grid gradient of + member 1) and the loop of `restore_through` (skip faults in + `restored`, mark each fault done after it). Frame values of a fault with + `cutters` not all in `restored`: restore the point through them first + (`_evaluate_frame` semantics). `Region::Sign`: port + `BaseSignRegion._calculate_value_and_distance` and + `PositiveRegion`/`NegativeRegion.__call__` (`LoopStructural/utils/regions.py`). + `Region::Unconformity`: port `UnconformityFeature.evaluate` + (`.../features/_unconformity_feature.py`): `<= value` if `sign`, else + `>= value`, NaN gives false. `Fault.regions` is `[Vec; 3]` + (one list per member, each member masked by its own list); `cutters` is + the full cutter chain in restore order (plan D2b "Rules found while + building"). `pool(0)` = all cores; cache by thread + count. Tests: one fault with constant displacement (exact shift along + the slip direction), reverse undoes restore to 1e-9, NaN in gives NaN + out, a block side 0 moves nothing, empty input. + +- [x] T013 [US2] [M] Add the PyO3 classes `FaultChain` and `GridField` and the constant `FAULT_KERNEL_VERSION = 1` (D2b). + - Files: `packages/loop_interpolation_core/src/python.rs` + - Needs: T012 + - Wave: 4 + - Done when: `cargo clippy --all-targets --features python -- -D warnings` passes, and after `maturin develop --release -m packages/loop_interpolation_core/Cargo.toml`, `python -c "import loop_interpolation_core as c; assert c.FAULT_KERNEL_VERSION == 1; c.FaultChain; c.GridField"` passes. + - Context: Register in `#[pymodule] fn loop_interpolation_core` next to + `PyProblem`. `FaultChain(spec: dict)`: parse the dict of plan D2b + (keys `version`, `block`, `faults[*].displacement/steps/frame/cutters/regions/profile`; + `regions` is a list of 3 lists, one per member; + region `kind` = positive / negative / unconformity; profile `kind` = + ones / zeros / smooth_peak / cubic / composite); `version != 1` or a + bad key raises `ValueError`. `restore(points (N,3) f64, order i64, + reverse bool, sides i8, restored bool, threads int) -> (N,3)`, + `frame_value(fault, coordinate, points, sides, restored, threads) -> (N,)`. + `GridField(spec)` with `values(points, threads) -> (N,)`, + `gradients(points, threads) -> (N,3)`. Copy the points to a `Vec`, then + run the work in `py.detach(...)` (as `PyProblem.solve` does). Internal + error: `RuntimeError` with a message, no partial result. Empty input: + empty output. + +- [x] T014 [US4] [S] Test: the native setting, the variable, the version check and the thread count (FR-006, FR-006a, FR-006b, FR-012). + - Files: `tests/fault_evaluation/test_native_settings.py` + - Needs: none + - Wave: 1 + - Done when: `pytest tests/fault_evaluation/test_native_settings.py -q` fails (no module `_native_faults`), then passes after T015. + - Context: Module `LoopStructural.modelling.features._native_faults` with + `REQUIRED_FAULT_KERNEL_VERSION = 1`, `native_enabled() -> bool`, + `native_threads() -> int`. Settings `LoopStructuralConfig.native_faults` + (None default) and `.native_threads` (None default). Use a fake module + in `sys.modules["loop_interpolation_core"]` (`types.SimpleNamespace` with + `FAULT_KERNEL_VERSION`) and `monkeypatch`; reset the module cache of + `_native_faults` between tests (`importlib.reload`). Cases: variable + `LOOPSTRUCTURAL_NATIVE_FAULTS` in {"0","false","OFF","no"} gives False; + unset gives True; setting True with variable "0" gives True (setting + wins); setting False gives False; import fails (`sys.modules[...] = None`) + gives False and no warning; version 2 gives False and exactly one + warning that contains "2" and "1" over two calls (`caplog`); + `native_threads()` is 0 for None and 1 for 1. + +- [x] T015 [US4] [M] Add the settings and `native_enabled`, `native_threads` (D2c, D2e). + - Files: `LoopStructural/__init__.py`, `LoopStructural/modelling/features/_native_faults.py` + - Needs: T014 + - Wave: 2 + - Done when: `pytest tests/fault_evaluation/test_native_settings.py tests/unit/test_public_api_contract.py -q` passes. + - Context: `LoopStructuralConfig` (dataclass in `LoopStructural/__init__.py`): + add `native_faults: bool | None = None` and `native_threads: int | None = None` + with numpy docstring entries; the file must keep Python 3.9 syntax + (use `Optional[...]` if the file has no `from __future__ import annotations`). + New module `_native_faults.py`: `REQUIRED_FAULT_KERNEL_VERSION: int = 1`. + `native_enabled()`: setting if not None; else off if + `os.environ.get("LOOPSTRUCTURAL_NATIVE_FAULTS", "").lower()` in + {"0","false","off","no"}; else on. If on: import + `loop_interpolation_core` once (keep the result in a module variable); + import error: off, no warning; `getattr(core, "FAULT_KERNEL_VERSION", None)` + not equal to the required version: off and one warning for each session + (module flag) through `LoopStructural.utils.getLogger(__name__)`: + `"native fault kernel version {found} found, LoopStructural needs version {required}; using the Python path"`. + `native_threads()`: the setting, or 0 if None. + +- [x] T016 [US2] [M] Add `chain_for`, `restore` and the state token, and call them from the Python path (D2c, D2d). + - Files: `LoopStructural/modelling/features/_native_faults.py`, `LoopStructural/modelling/features/_base_geological_feature.py`, `LoopStructural/modelling/features/_evaluation.py` + - Needs: T004, T017, T018, T034 + - Wave: 6 + - Done when: `pytest tests/fault_evaluation -q` passes with the kernel built (`test_native_faults.py` and `test_native_safety.py` do not skip). + - Context: Follow plan.md D2c and D2d exactly (read those two sections). + `chain_for(feature) -> tuple[FaultChain, list] | None` builds the spec + dict of plan D2b from the faults of + `restore_order(feature.faults, owner=feature)`; support checks as in + D2c (FaultSegment; 3 members on `StructuredGrid` with + `_has_uniform_lookup()`; equal member fault lists; regions Sign or + Unconformity only; `FaultDisplacement` with `Ones`, `Zeros`, + `CubicFunction` (call `solve()` first), `Composite`, or `smooth_peak` by + `is`). `cutters` = indices of `restore_order(member0.faults)`; `regions` + = 3 lists (one per member); a sign region with `vector` or `point` None + is not supported (plan D2b "Rules found while building"). + Cache `feature._native_chain = (token, refs, chain, faults)`; + token and refs as D2c. `restore(feature, points, *, reverse=False, + block=None, restored_through=())` returns None for the Python path. + `_apply_faults`: try native first. `_evaluation.py`: new private + `_restore_direct(feature, points, reverse)` used by both calls. + +- [x] T017 [US2] [M] Test: native restoration agrees with the Python path on the golden models (story 2, FR-003, FR-005, FR-005a, FR-005c). + - Files: `tests/fault_evaluation/test_native_faults.py` + - Needs: T013, T015 + - Wave: 5 + - Done when: `pytest tests/fault_evaluation/test_native_faults.py -q` fails (no `_native_faults.restore`), then passes after T016. + - Context: `pytest.importorskip("loop_interpolation_core")`. Models: + `f1_u0`, `f4_u0`, `f4_u3`, `cutting_faults`, `plugin`, `stopped_fault`, + `faulted_fold` (`build_model`, `sample_points(name, 2000, seed=1)` in + `tests/fault_evaluation/models.py`). For each faulted feature: restored + points with `_native_faults.restore(feature, pts)` against + `restore_through(pts, feature.faults, owner=None)` with + `LoopStructuralConfig.native_faults = False`. Tolerance + `1e-8 * box_size` (as `assert_matches` in `golden.py`); NaN rows equal. + Also `block={fault.name: +1}`, `{name: -1}`, `{name: 0}`, `reverse=True` + and `restored_through=(feature.faults[0],)`. Record the largest + difference: `record_property("max_native_diff", value)`. Story 4 + scenarios 1 to 3 with the real kernel: native used (the function returns + an array), off by setting, off by variable. + +- [x] T018 [US5] [M] Test: the native path is safe to use (story 5 scenarios 2 to 7, edge cases). + - Files: `tests/fault_evaluation/test_native_safety.py` + - Needs: T013, T015 + - Wave: 5 + - Done when: `pytest tests/fault_evaluation/test_native_safety.py -q` fails before T016 (the native path is not used), then passes after T016. + - Context: `pytest.importorskip("loop_interpolation_core")`. Model + `build_model("f4_u0")`. (2) A fault whose `faultfunction` is a plain + Python function: `chain_for` returns None and the values equal the + native-off values. (3) Second call: no file opened (patch + `builtins.open` to fail) and `feature._native_chain[2]` is the same + object. (4) Change `fault.displacement`; the next values equal the + Python path for the new state. (5) A thread that counts in a loop makes + progress during a native `restore` on 10 million points. (6) Two threads + evaluate one model; each result equals the result alone. (7) + `LoopStructuralConfig.native_threads = 1` gives the same result as 0. + Edge: empty points; a NaN coordinate (the row equals the Python path + result: its finite coordinates are kept); `FaultChain({"version": 99})` + raises `ValueError` and the model state does not change. Reset the + settings in a fixture. + +- [x] T019 [US4] [S] Add the option `--native-faults {on,off}` to the benchmark runner (FR-013). + - Files: `benchmarks/fault_evaluation/run.py` + - Needs: T015 + - Wave: 3 + - Done when: `python -m benchmarks.fault_evaluation.run --help` lists `--native-faults`, and `pytest tests/fault_evaluation/test_benchmark_run.py tests/fault_evaluation/test_benchmark_suites.py -q` passes. + - Context: In `main(argv)`, after the `--suite` argument: + `parser.add_argument("--native-faults", choices=("on", "off"), default="off", help="Use the native fault kernel (on) or the Python path (off, default).")`. + After `parse_args`: `LoopStructuralConfig.native_faults = options.native_faults == "on"` + (import from `LoopStructural`). Record the value in the result: where + `result["suite"] = suite` is set, the `suite` dict gets + `"native_faults": options.native_faults`; pass it through the existing + call chain to that function. Schema version stays 1. + +- [x] T020 [US4] [S] Run the fault evaluation tests with the native kernel in CI (FR-013, SC-006). + - Files: `.github/workflows/native.yml` + - Needs: T013 + - Wave: 5 + - Done when: `python -c "import yaml,sys; yaml.safe_load(open('.github/workflows/native.yml'))"` passes and the `wheel` job has the new lines. + - Context: Job `wheel`, step "Install, build and test": after + `python -m pytest packages/loop_interpolation/tests -q` add + `python -m pip install -e .` and + `python -m pytest tests/fault_evaluation -q`. Add to both `paths` lists: + `'LoopStructural/modelling/features/_native_faults.py'` and + `'LoopStructural/utils/_fault_block.py'`. Change nothing else. + +- [x] T021 [US2] [M] Measure SC-002, SC-003 and SC-007 and record the native differences (FR-005c). + - Files: `specs/007-native-fault-kernel/verification.md` + - Needs: T009, T016, T019, T020 + - Wave: 7 + - Done when: `verification.md` has a section "Stage S2" with a table for SC-002, SC-003 and SC-007 (target, measured, pass or fail) and the largest native difference for each golden model. + - Context: Computer of spec 003 T030 (Intel i7-12700H, 20 threads, + Linux); if another computer is used, say so. SC-002: for `f1_u0`, + `f4_u0`, `f4_u3`, `cutting_faults`, `plugin` at 10 000 points, native + restore with `native_threads = 1` takes at most 20 % of the Python + restore time. SC-003: with all 20 threads, at most 3 %. SC-007: for 10 + million points, the extra peak memory of a native restore is within + spec 003 FR-010 (`acceptance.MEMORY_ALLOWANCE_BYTES` in + `benchmarks/fault_evaluation/acceptance.py`). Differences: from + `pytest tests/fault_evaluation/test_native_faults.py -q --junitxml=...` + (`max_native_diff`). Change no code. If a target fails, record it; do + not change a limit. + +- [x] T035 [US2] [M] Make the 1-thread native restoration faster, with the same results (SC-002; maintainer answer 2026-11-27). + - Files: `packages/loop_interpolation_core/src/fault/restore.rs`, `packages/loop_interpolation_core/src/fault/region.rs`, `packages/loop_interpolation_core/src/fault/mod.rs`, `packages/loop_interpolation_core/tests/fault_restore.rs`, `specs/007-native-fault-kernel/verification.md` + - Needs: T021 + - Wave: 8 + - Done when: `cargo test --release` (also `--features parallel`) passes, `pytest tests/fault_evaluation/test_native_faults.py tests/fault_evaluation/test_native_safety.py tests/fault_evaluation/test_golden.py -q` passes after `maturin develop --release`, and `verification.md` has a section "Stage S2 after T035" with the SC-002 and SC-003 ratios measured as in T021. + - Context: T021 measured SC-002 at 0.23 to 0.30 (target 0.20) and SC-003 + at 0.023 to 0.028 (target 0.03). Profile one restore of `f4_u0` and + `cutting_faults` at 10 000 points on 1 thread (for example `perf` or a + timing of each function) and remove the costs that the profile shows. + Known candidates (wave 3 review): `Region::Sign::contains` allocates + `vec![false; n]` on each call; `FaultChain::restore` copies `restored` + on each call; `frame_point` restores the cutters again for each member + and each step; `GridField` lookups that compute the same cell twice for + value and gradient. The public signatures of `FaultChain`, `GridField`, + `Region` and the batch functions do not change (`src/python.rs` and + `gradient.rs` call them). The results must stay the same: the Rust + tests and the Python parity tests pass, and the largest native + difference stays below 1e-8 x the box. Measure again with the T021 + method (scripts in `$CLAUDE_JOB_DIR/tmp/t021/`) and record the result; + if SC-002 still fails, record the numbers and the remaining costs. + +- [x] T022 [US2] [S] Record stage S2 in `ROADMAP.md` (FR-015). + - Files: `ROADMAP.md` + - Needs: T007, T021, T035 + - Wave: 9 + - Done when: `ROADMAP.md` `## Status log` has a dated line for spec 007 stage S2 with the SC-002, SC-003 and SC-007 results. + - Context: One line at the end of `## Status log`, as the lines above it: + "spec 007 S2: native fault restoration in `loop_interpolation_core` + (`FaultChain`, `FAULT_KERNEL_VERSION = 1`)", with the results from the + "Stage S2" section of `specs/007-native-fault-kernel/verification.md`. + +## Phase 5: Stage S3, native values and gradients (story 3) + +- [x] T023 [US3] [M] Implement the exact nearest-point search `KdTree` (OP5). + - Files: `packages/loop_interpolation_core/src/fault/nearest.rs`, `packages/loop_interpolation_core/tests/fault_nearest.rs` + - Needs: T008 + - Wave: 2 + - Done when: `cargo test --release --test fault_nearest` fails against the stub, then passes. + - Context: `pub struct KdTree`, `KdTree::new(points: &[[f64; 3]]) -> KdTree`, + `fn nearest(&self, p: [f64; 3]) -> usize` (index into `points`). + Euclidean distance, exact. For equal distances, the lowest index. Points + with a NaN coordinate are not in the tree (the caller gives only known + points). Panic-free for 1 point; `new(&[])` is allowed and `nearest` + then returns `usize::MAX`. Tests: 2000 random points (fixed seed, a + small LCG in the test, no new crate) against a brute-force search for + 500 queries; equal distances give the lowest index; 1 point. + +- [x] T024 [US3] [M] Implement the native tetrahedron gradient of a faulted feature (`gradient.rs`, OP5, FR-004). + - Files: `packages/loop_interpolation_core/src/fault/gradient.rs`, `packages/loop_interpolation_core/tests/fault_gradient.rs` + - Needs: T012, T023 + - Wave: 4 + - Done when: `cargo test --release --test fault_gradient` passes, also with `--features parallel`. + - Context: `feature_gradient(chain, field: &GridField, points, order, sides, restored, jumping: &[bool], scale: f64) -> (Vec<[f64;3]>, usize)`. + Port the faulted branch of `GeologicalFeature.evaluate_gradient` + (`LoopStructural/modelling/features/_geological_feature.py`): + `regular_tetraherdron_for_points` and `gradient_from_tetrahedron` + (`packages/loop_common/src/loop_common/math/_maths.py`); side check: + for each fault with `jumping`, `frame_value(fault, 0, corner, sides, + no faults restored)` of all corners of the batch; NaN values take the + value of the nearest known corner of the same batch (`KdTree` on the + restored corner points, as `fillnan='nearest'`); straddle = not all 4 + > 0 and not all 4 < 0. At most 10 rounds: halve the scale, rebuild only + the straddling tetrahedra, check again. Restore the corners with + `restore`, read `field`, NaN for points that still straddle. The count is + the number of points refined at least once. The batch of the nearest + fill is the whole set of straddling points of the round, as in Python. + Tests: a feature with no fault crossing equals the grid gradient to + 1e-10; a point on a fault gives NaN; count > 0 near a fault. + +- [x] T025 [US3] [M] Add the binding `FaultChain.feature_gradient` (D2b). + - Files: `packages/loop_interpolation_core/src/python.rs` + - Needs: T013, T024 + - Wave: 5 + - Done when: `cargo clippy --all-targets --features python -- -D warnings` passes and, after `maturin develop --release -m packages/loop_interpolation_core/Cargo.toml`, `python -c "import loop_interpolation_core as c; c.FaultChain.feature_gradient"` passes. + - Context: `feature_gradient(self, field: GridField, points: (N,3) f64, + order: i64, sides: i8, restored: bool, jumping: bool, scale: float, + threads: int) -> tuple[np.ndarray (N,3), int]`. Same rules as `restore` + of T013: copy the points, `py.detach`, `ValueError` for bad shapes + (`jumping`, `sides` and `restored` must have one item for each fault), + `RuntimeError` for an internal error, empty input gives `(empty, 0)`. + +- [x] T026 [US3] [M] Test: native values, gradients and model ids agree with the Python path (story 3, FR-004, FR-005, FR-005a, FR-005b). + - Files: `tests/fault_evaluation/test_native_field.py` + - Needs: T016 + - Wave: 7 + - Done when: `pytest tests/fault_evaluation/test_native_field.py -q` fails (no `field_for`), then passes after T027. + - Context: `pytest.importorskip("loop_interpolation_core")`. For the + golden models of T017 and `onlap_domain`: `capture(model, points)` + (`tests/fault_evaluation/golden.py`) with native on against native off; + compare with `assert_matches(name, actual, expected, box_size)`. + Model ids (FR-005b): equal, except at points where the Python value is + within `1e-8 * box_size` of a unit boundary. Story 3 scenario 2: a point + on a fault of `f1_u0` gives a NaN gradient with native on. The warning + "points are too close to a fault" is logged once for the call + (`caplog`). A fault frame with an unconformity region (`onlap_domain` + or a model with `add_unconformity` before a fault) uses the native path: + `_native_faults.chain_for(feature)` is not None. Record + `record_property("max_native_diff", value)`. + +- [x] T027 [US3] [M] Add `field_for` and use the native field and gradient in `GeologicalFeature` (D3). + - Files: `LoopStructural/modelling/features/_native_faults.py`, `LoopStructural/modelling/features/_geological_feature.py` + - Needs: T025, T026 + - Wave: 8 + - Done when: `pytest tests/fault_evaluation -q` passes with the kernel built. + - Context: Follow plan.md D3 exactly (read it). `field_for(feature) -> GridField | None`, + cache `feature._native_field = (token, refs, field)`, checks as + `_shared_frame_members` for one interpolator. `evaluate_value`: + `field.values(evaluation_points[mask, :], native_threads())` after + `interpolator._check_frame()` and `interpolator.update()`. + `evaluate_gradient` without faults: `field.gradients(...)`. With faults: + if `field_for` and `chain_for` are not None, call + `chain.feature_gradient(field, pos, order, sides, restored, jumping, element_scale_parameter, native_threads())`; + rows outside the mask are NaN; log the Python warning once if the count + > 0. Else keep the Python loop. Do not change the signatures (FR-007). + +- [x] T028 [US3] [M] Measure SC-004 and SC-005 with the native path. + - Files: `specs/007-native-fault-kernel/verification.md` + - Needs: T021, T027 + - Wave: 9 + - Done when: `verification.md` has a section "Stage S3" with SC-004 (measured time, target 0.5 s) and SC-005 (the golden test result with the native path on). + - Context: SC-004: run + `python -m benchmarks.fault_evaluation.many_faults --output /tmp/many_faults_native.json --points 5000` + with the kernel built and the native path on (no + `LOOPSTRUCTURAL_NATIVE_FAULTS`), on the T030 computer. + `cases["5000"]["evaluate_model_seconds"]` at most 0.5 s (baseline 2.09 s + in `/home/lgrose/dev/LoopStructural-wt/_runs007/many_faults_python.json`). + Do not use `--compare` (native results are not bit-identical, C-001). SC-005: run + `pytest tests/fault_evaluation/test_golden.py -q` with the native path on + (no `LOOPSTRUCTURAL_NATIVE_FAULTS`), and record the result and the + largest difference. Change no code; if a target fails, record it. + +- [x] T029 [US3] [S] Record stage S3 in `ROADMAP.md` (FR-015). + - Files: `ROADMAP.md` + - Needs: T022, T028 + - Wave: 10 + - Done when: `ROADMAP.md` `## Status log` has a dated line for spec 007 stage S3 with the SC-004 and SC-005 results. + - Context: One line at the end of `## Status log`: "spec 007 S3: native + field values and gradients (`GridField`, `FaultChain.feature_gradient`)", + with the results from the "Stage S3" section of + `specs/007-native-fault-kernel/verification.md`. + +- [x] T036 [US4] [S] Let the 94-fault benchmark run with the native path on (FR-013). + - Files: `benchmarks/fault_evaluation/many_faults.py`, `tests/fault_evaluation/test_many_faults.py` + - Needs: T028 + - Wave: 10 + - Done when: `pytest tests/fault_evaluation/test_many_faults.py -q` passes, and the new test fails before the change. + - Context: `measure()` in `many_faults.py` takes `np.mean` and `np.max` + of the per-fault times that `_FaultTimer` collects by patching + `FaultSegment.apply_to_points`. The native path does not call that + method, so the lists are empty and `np.max` raises `ValueError` + (found in T028). Fix: if a list is empty, write `None` for + `isolated_mean_ms`, `cutting_mean_ms` and `cutting_max_ms` (the + `fault_calls` count is then 0). Add one fast test in + `test_many_faults.py` that calls the summary code with empty per-fault + lists (extract the summary into a small private function + `_fault_summary(per: dict) -> dict` if needed, so no model build is + needed) and checks the `None` values. Keep the JSON keys and the + Python-path numbers unchanged. + +## Phase 6: Stage S4, prebuilt packages (story 4) + +- [x] T030 [US4] [S] Add a fault kernel smoke test to the wheel workflow (FR-014). + - Files: `.github/workflows/core-wheels.yml` + - Needs: T013 + - Wave: 5 + - Done when: `python -c "import yaml; yaml.safe_load(open('.github/workflows/core-wheels.yml'))"` passes and the smoke script has the fault check. + - Context: In the step "Install the wheel and solve a small problem", + add to the Python heredoc after the solve check: make + `core.FaultChain(spec)` with one fault: `displacement` 10.0, `steps` 10, + three frame grids of 21x21x21 nodes, origin 0, step 1, no local frame, + node values x - 10 (member 0), y (member 1), z (member 2); `cutters` [], + `regions` [], profile `{"scale": 1.0, "gx": {"kind": "ones"}, "gy": {"kind": "ones"}, "gz": {"kind": "ones"}}`, + block settings of plan D2b. Restore the points (5, 5, 5) and + (12, 4, 8) with `order=[0]`, `sides=[2]`, `restored=[False]`, + `threads=0`; expected (5, 15, 5) and (12, 14, 8) (the step direction is + the gradient of member 1, +y), to 1e-12. Change nothing else. + +- [x] T031 [US4] [S] Describe the fault kernel in the package README. + - Files: `packages/loop_interpolation_core/README.md` + - Needs: T025 + - Wave: 6 + - Done when: the README has a section "Fault kernel" and `git diff --stat` shows only that file. + - Context: 10 to 20 lines, ASD-STE100 style: what the kernel does + (restores points through the faults of a LoopStructural feature, and + evaluates values and gradients); it is used by LoopStructural + automatically; `FAULT_KERNEL_VERSION = 1`; the classes `FaultChain` + (`restore`, `frame_value`, `feature_gradient`) and `GridField` + (`values`, `gradients`); the switch `LoopStructuralConfig.native_faults` + and `LOOPSTRUCTURAL_NATIVE_FAULTS=0`; the thread count + `LoopStructuralConfig.native_threads` (None = all cores). Do not + document the spec dict in detail; point to + `specs/007-native-fault-kernel/plan.md` D2b. + +- [x] T032 [US4] [M] Check the prebuilt packages on each platform (SC-008). + - Files: `specs/007-native-fault-kernel/verification.md` + - Needs: T028, T030 + - Wave: 10 + - Done when: `verification.md` has a section "Stage S4" with one row for each platform of FR-014 (Linux x86_64, Linux aarch64, macOS arm64, macOS x86_64, Windows x64): wheel built, installed on a clean environment, golden tests with the native path on: pass or fail or "not checked". + - Context: Use the artifacts of the `Native wheels` workflow + (`.github/workflows/core-wheels.yml`; run it with `gh workflow run` only + if the maintainer agrees, else use the last run on the branch). CI + installs and smoke tests 4 platforms; macOS x86_64 is cross-compiled + and not run in CI: mark it "maintainer check needed" unless a result + exists. For the golden tests: `pip install loopstructural` from the + branch plus the wheel, then `pytest tests/fault_evaluation/test_golden.py -q`. + Change no code. + +## Phase 7: Finish + +- [x] T033 [Finish] [M] Run the full test suite with the native path on, off and not installed, and record stage S4 (SC-006, FR-015). + - Files: `specs/007-native-fault-kernel/verification.md`, `ROADMAP.md` + - Needs: T006, T029, T031, T032, T036 + - Wave: 11 + - Done when: `verification.md` has a section "SC-006" with the result of the three `pytest` runs, and `ROADMAP.md` `## Status log` has a dated line for spec 007 stage S4. + - Context: Three runs from the repository root: (1) kernel built + (`maturin develop --release -m packages/loop_interpolation_core/Cargo.toml`), + `pytest -q`; (2) the same with `LOOPSTRUCTURAL_NATIVE_FAULTS=0 pytest -q`; + (3) `pip uninstall -y loop-interpolation-core`, then `pytest -q`. + Also run `ruff check LoopStructural packages`. Record pass counts and + any failure with its test id. ROADMAP line: "spec 007 S4: prebuilt + native packages with the fault kernel" with the SC-008 rows of + `verification.md`. Change no code. + +## Phase 8: Stage S5, package loop-model-core (maintainer answer 2026-11-27) + +- [x] T037 [Found] [M] Move the fault kernel into the new package `packages/loop_model_core` (D5). + - Files: `packages/loop_model_core/`, `packages/loop_interpolation_core/src/fault/`, `packages/loop_interpolation_core/tests/fault_grid_field.rs`, `packages/loop_interpolation_core/tests/fault_profile.rs`, `packages/loop_interpolation_core/tests/fault_restore.rs`, `packages/loop_interpolation_core/tests/fault_nearest.rs`, `packages/loop_interpolation_core/tests/fault_gradient.rs`, `packages/loop_interpolation_core/src/lib.rs`, `packages/loop_interpolation_core/src/python.rs`, `packages/loop_interpolation_core/README.md` + - Needs: T033 + - Wave: 12 + - Done when: in `packages/loop_model_core`, `cargo test --release` (also `--features parallel`) and `cargo clippy --all-targets -- -D warnings` (no features, parallel, python, python,parallel) pass; in `packages/loop_interpolation_core` the same commands pass (and `cargo clippy --all-targets --features wasm --target wasm32-unknown-unknown -- -D warnings` if the target is installed); after `maturin develop --release` of both packages, `python -c "import loop_model_core as m; assert m.FAULT_KERNEL_VERSION == 1; m.FaultChain; m.GridField; import loop_interpolation_core as c; assert not hasattr(c, 'FaultChain')"` passes. + - Context: Follow plan.md "Design of stage S5", D5, exactly. Use + `git mv` for `src/fault/` and the five `tests/fault_*.rs` files so the + history follows them. In the moved tests replace + `loop_interpolation_core::fault` with `loop_model_core::fault`. The new + `src/python.rs` holds the fault part of the old `python.rs` (from the + comment `// Fault kernel` on) and its own `#[pymodule] fn + loop_model_core`; the old `python.rs` keeps only the solver + (`PyProblem`) and its helpers. Copy a helper that both parts use. The + old README section "Fault kernel" moves to the new README; the old + README keeps one line that points to `packages/loop_model_core`. No + new dependency versions: copy them from the interpolation core + `Cargo.toml`. Never set CARGO_TARGET_DIR; one cargo command at a time. + +- [x] T038 [US4] [M] Use `loop_model_core` from LoopStructural and the tests, and add it to the `native` extra (D5b). + - Files: `LoopStructural/modelling/features/_native_faults.py`, `tests/fault_evaluation/test_native_settings.py`, `tests/fault_evaluation/test_native_faults.py`, `tests/fault_evaluation/test_native_safety.py`, `tests/fault_evaluation/test_native_field.py`, `pyproject.toml`, `uv.lock` + - Needs: T037 + - Wave: 13 + - Done when: `pytest tests/fault_evaluation -q` passes with both cores installed, the native tests do not skip, and `uv lock --check` passes (or `uv lock` updated `uv.lock` with only the new package). + - Context: Plan D5b. `_native_faults.py`: `import loop_model_core` in + place of `loop_interpolation_core` (and the module docstring). Tests: + every `loop_interpolation_core` that names the fault kernel becomes + `loop_model_core` (`importorskip`, `from ... import FaultChain`, the + fake module name `KERNEL_NAME` in test_native_settings.py). Root + `pyproject.toml`: `native = ["loop-interpolation[native]", "loop-model-core"]` + and `[tool.uv.sources]` `loop-model-core = { path = "packages/loop_model_core" }` + with a comment like the one of the interpolation core. Run `uv lock` + (try `--offline` first). Do not change solver tests that use + `loop_interpolation_core` for the solver. + +- [x] T039 [US4] [M] Build, test and release `loop-model-core` in CI (D5c). + - Files: `.github/workflows/model-core-wheels.yml`, `.github/workflows/core-wheels.yml`, `.github/workflows/pypi.yml`, `.github/workflows/native.yml`, `.release-please-config.json`, `.release-please-manifest.json`, `.dev-tools/project.json` + - Needs: T037 + - Wave: 13 + - Done when: each changed YAML and JSON file loads (`yaml.safe_load`, `json.load`), the heredoc smoke script of `model-core-wheels.yml` runs with the local venv and prints "fault kernel restore ok", and `core-wheels.yml` no longer names `FaultChain`. + - Context: Plan D5c exactly. `model-core-wheels.yml` is a copy of + `core-wheels.yml` with `MANIFEST: packages/loop_model_core/Cargo.toml`, + package `loop-model-core`, artifact names `model-core-wheel-*` and + `model-core-sdist`, its own `paths`, and the fault smoke test (the T030 + heredoc with `import loop_model_core as core`); no solver smoke test. + `core-wheels.yml` keeps only the solver smoke test. `pypi.yml`: copy + the `build_core` / upload jobs for the new workflow (read how the + interpolation core is published and follow it). `native.yml`: plan D5c. + release-please files and `.dev-tools/project.json`: plan D5c. Change + nothing else. + +- [x] T040 [US5] [S] Treat a negative thread count as all cores, and use exact type checks for supported parts (end review findings). + - Files: `LoopStructural/modelling/features/_native_faults.py`, `tests/fault_evaluation/test_native_settings.py` + - Needs: T038 + - Wave: 14 + - Done when: `pytest tests/fault_evaluation/test_native_settings.py tests/fault_evaluation/test_native_faults.py tests/fault_evaluation/test_native_safety.py tests/fault_evaluation/test_native_field.py -q` passes, and the two new tests fail before the change. + - Context: `native_threads()` returns `max(int(setting), 0)` when the + setting is not None (a negative value means all cores, as `-1` in + joblib); say so in its docstring. In `chain_for` and `field_for` + (and their helpers), replace `isinstance(x, FaultSegment)`, + `isinstance(x, FaultDisplacement)` and the region class checks + (`PositiveRegion`, `NegativeRegion`, `UnconformityFeature`) with + `type(x) is ...`, so a subclass takes the Python path (FR-008). New + tests in test_native_settings.py: `native_threads()` is 0 for -1; + a subclass of `FaultDisplacement` makes `chain_for` return None (build + a fake chain input or use `build_model("f1_u0")` and set + `fault.faultfunction = SubclassOfFaultDisplacement(...)`, with the + kernel installed: `pytest.importorskip("loop_model_core")`). + +- [x] T041 [US4] [S] Record stage S5 and the package name in `ROADMAP.md` (FR-015). + - Files: `ROADMAP.md` + - Needs: T039, T040 + - Wave: 15 + - Done when: the spec 007 decision section names `loop-model-core` as the package of the native path, and `## Status log` has a dated line for spec 007 stage S5. + - Context: In `### Native fault application (spec 007)`, replace "an + optional Rust kernel in `loop_interpolation_core`" with "an optional + Rust kernel in the package `loop-model-core` (module + `loop_model_core`), separate from the solver core + `loop_interpolation_core`". Status line (format of the lines above it): + "2026-11-27: spec 007 S5: the fault kernel moves to the new package + `loop-model-core`, with its own wheels and release; a negative + `native_threads` means all cores; subclasses of the supported fault + types use the Python path." + +- [x] T042 [Finish] [M] Run the full test suite with the native path on, off and not installed after the move (SC-006). + - Files: `specs/007-native-fault-kernel/verification.md` + - Needs: T041 + - Wave: 16 + - Done when: `verification.md` has a section "Stage S5" with the three `pytest` runs, the Ruff result and the Rust checks of both crates. + - Context: As T033, with both cores: (1) `maturin develop --release` + of `packages/loop_interpolation_core` and `packages/loop_model_core`, + `pytest -q`; (2) `LOOPSTRUCTURAL_NATIVE_FAULTS=0 pytest -q`; (3) + uninstall `loop-model-core` only, `pytest -q` (the fault kernel is + missing, the solver core stays); then reinstall it. Known + pre-existing failure: `tests/unit/modelling/test_native_fault_frame.py::test_the_native_fault_frame_is_the_cg_fault_frame` + (native solver). Ruff: no new errors against the master baseline. Also + `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` in + both crates. Change no code. + +## Wave table + +| Wave | Tasks | Tier [S] | Tier [M] | +|---|---|---|---| +| 1 | T001, T002, T003, T008, T034, T009, T014 | 3 | 4 | +| 2 | T004, T010, T011, T015, T023 | 0 | 5 | +| 3 | T005, T012, T019 | 1 | 2 | +| 4 | T006, T013, T024 | 0 | 3 | +| 5 | T007, T017, T018, T020, T025, T030 | 3 | 3 | +| 6 | T016, T031 | 1 | 1 | +| 7 | T021, T026 | 0 | 2 | +| 8 | T035, T027 | 0 | 2 | +| 9 | T022, T028 | 1 | 1 | +| 10 | T029, T036, T032 | 2 | 1 | +| 11 | T033 | 0 | 1 | +| 12 | T037 | 0 | 1 | +| 13 | T038, T039 | 0 | 2 | +| 14 | T040 | 1 | 0 | +| 15 | T041 | 1 | 0 | +| 16 | T042 | 0 | 1 | + +## Critical path + +T008 -> T010 -> T012 -> T013 -> T017 -> T016 -> T021 -> T035 -> T022 -> T029 -> T033 -> T037 -> T038 -> T040 -> T041 -> T042 + +## Dependencies + +- S1 (T002 to T007): T003 test, then T004 code. T002 and T005 measure before + and after (the 94-fault benchmark `many_faults.py`); T006 runs D1b + only if T005 reports that SC-001 fails. +- Rust (T008 to T013): T008 makes the skeleton. The grid (T010), the + profiles (T011) and the nearest search (T023) run in parallel. T012 needs + T010 and T011. T013 (PyO3) needs T012. +- Python S2: T014 test, then T015 settings (no kernel needed). T017 and + T018 tests need T013 and T015. T016 makes them pass and needs T004. + T019 and T020 select the path in benchmarks and CI. T021 measures. +- S3: T024 needs T012 and T023; T025 binds it; T026 test needs T016; T027 + makes it pass. T028 measures. +- S4: T030 smoke test needs T013; T031 README needs T025; T032 checks the + platforms. T033 runs the full suite three ways and closes the spec. +- `ROADMAP.md` is a chain: T001, T007, T022, T029, T033. + `verification.md` is a chain: T009, T021, T028, T032, T033. +- S5 (maintainer answer): T037 moves the fault kernel into + `packages/loop_model_core`; T038 (Python side, extra, lock) and T039 (CI, + release) follow in parallel; T040 fixes two end review findings; T041 + records S5; T042 runs the suite three ways again. diff --git a/specs/007-native-fault-kernel/verification.md b/specs/007-native-fault-kernel/verification.md new file mode 100644 index 000000000..399680c22 --- /dev/null +++ b/specs/007-native-fault-kernel/verification.md @@ -0,0 +1,410 @@ +# Verification: native fault application + +This file collects the evidence of spec 007. + +## C-007: proof-of-concept difference + +Sources: the proof of concept (PoC) in `/home/lgrose/dev/LoopStructural-wt/_runs003/rust_poc/` (read only), and the Python reference in this worktree. Paths of PoC files are relative to that folder. Line numbers are those of the files when this was written. + +### Summary + +The most likely cause is the linearisation of the gy and gz profiles in the exporter. + +- The default gy and gz profile of the fault is `smooth_peak` (`_fault_function.py:12`). It is a plain function, not a `CubicFunction`. +- `export_snapshot.py:138` (`linearise`, line 60) does not export it as a formula. It samples it at 2001 points over the node range of the frame coordinate and the PoC interpolates between the samples. +- A piecewise linear curve has an error of about `h^2 * |f''| / 8` for sample step `h`. I tested this with `np.interp` on `smooth_peak`. The maximum error is 1.0e-6 for a span of 2, 4.0e-6 for a span of 4, and 8.9e-6 for a span of 6. The span is the node range of gy or gz. +- This is a relative error of 1e-6 to 1e-5 on the displacement. For a displacement of 40 to 120 m it gives about 4e-5 to 1e-3 m. The measured differences are 5.4e-5 m (f4_u0) and 1.9e-4 m (10 km box). The size and the scaling agree. +- The error exists with one fault: model f1_u0 has 1.4e-5 m (`poc_bench.json`). A step-order or fault-order cause would need two or more faults. A f32 cause is not possible (see the table). +- The cause was not proved by a run of the PoC. I tested the size of the error only. + +Other items are far smaller (rounding, about 1e-16 relative) or change only special points (NaN, cutting faults, regions). + +### Table + +The items are in order of the likely size of their effect. + +| # | Item | Python behaviour | PoC behaviour | Effect on the result | +|---|------|------------------|---------------|----------------------| +| 1 | Profile of gy and gz (`smooth_peak`, other plain functions) | Exact formula, `_fault_function.py:12-17`; used in `FaultDisplacement.__call__` (line 304) | Sampled at 2001 points and linearly interpolated: `export_snapshot.py:60-95`, `profile.rs:117` (`Linear::eval`) | Relative error 1e-6 to 1e-5 on the displacement, about 1e-4 m on 100 m. Probable main cause. Also, the curve has a kink at the sample points and at gy = +-1 | +| 2 | Slope and curvature of the continuation of a linearised profile | `_taylor`, `_fault_function.py:357-377`: finite differences of the exact function | Exact values at six points, saved as `stencil`: `export_snapshot.py:79-92`, `profile.rs:255-300` | None when the stencil is used. It affects only a block with `BLOCK_EXTENSION = "smooth"`; the restoration without a block does not use it | +| 3 | Fault with a frame cut by a younger fault (#421) | If the gradient is NaN, it uses the gradient of the frame without the cutting faults: `_fault_segment.py:716-724` | No fallback. A NaN gradient stays NaN: `fault.rs:198-207`. The comment in `README.md` says the frame is read at restored points | None on the NaN points that agree. A point on a cutting fault can differ (NaN in the PoC, finite in Python). The test models have no such point | +| 4 | Regions of the frame members | `_calculate_mask` sets values outside a region to NaN: `_fault_segment.py:422-427` | The exporter refuses a region that is not an erosional unconformity: `export_snapshot.py` (`check_regions`, `grid_to_dict`, line 195-210) | None on exported models. The PoC cannot read a model with an abutting fault | +| 5 | Point that is not finite | `v[nan_rows] = nan` for values, NaN gradient (#413): `_fault_segment.py:425-445` | A NaN local coordinate gives the value 0.0 and the gradient 0: `grid.rs:250`, `grid.rs:274-277` | The point does not move in the PoC. In Python the value is NaN, so the point also does not move (d = 0). The NaN points agreed in the tests | +| 6 | Step direction (#425) | The step moves along the gradient of frame coordinate 1 (`member1.evaluate_gradient`, `_fault_segment.py:460`), made unit length at each step, and the sign of `reverse` is applied to `d`: lines 732-741 | Same: `g1` is used (`fault.rs:148-158`), unit length, `d` multiplied by -1 for `reverse`: `fault.rs:196-212` | None. The direction agrees | +| 7 | Number of steps and the points that move | The set of moving points is fixed by `|d| > 0` before step 0: `_fault_segment.py:695`; all later steps keep it | `d0 == 0` returns the point before step 0, so the set is the same: `fault.rs:181-190` | None. A point that has `d = 0` at a later step does not move in either path | +| 8 | Order of the steps and of the faults | `restore_through`: `cutters_first(with_cutters(faults))`, `_fault_block.py:242-249` | The exporter writes the same order: `export_snapshot.py` (`cutters_first(with_cutters(...))`) | None. Each fault is applied once, in the same order | +| 9 | Local frame (`_project_points`, rotation) | `bounding_box.project` and `reproject_vectors`: `_geological_interpolator.py:253-275` | One affine map `local = A * world + b`, built by the exporter from `project` of a unit basis: `export_snapshot.py:213-218`, `grid.rs:152-158`. A rotated grid is refused | Rounding only, about 1e-16 relative. No effect at 1e-8 times the box size | +| 10 | Cell search and trilinear sum | `_lookup_points`, `_structured_grid_3d.py:515-547`: cell by `position_to_cell_index`, clip of local coordinates to [0, 1] | `lookup`, `grid.rs:164-215`: same cell rule, clamp to [0, 1], tolerance `32 * eps * max(extent, 1)` | Rounding only, about 1e-16 relative. The order of the 8 corner terms (`sum8`, `grid.rs:18`) can differ from `_values_from_coefficients` by 1 ulp | +| 11 | Cubic profile | `CubicFunction.__call__`, `_fault_function.py:163-171`, `v**3`; the limit value comes from `_limit_value` (line 152) | `Cubic::eval`, `profile.rs:79-98`, `powf(3.0)`; `limit_value` is exported from `_limit_value` | 1 ulp. The order (limit, then floor and ceiling) is the same | +| 12 | `BLOCK_EXTENSION`, `_saturate`, `continue_profile` | `_fault_function.py:345-431`; `_fault_block.py:39-61` | Constants are read from the manifest; `saturate` in `profile.rs:247` is the same formula | None, if the manifest holds the values 0.25, 0.5, 1e-3, 1e-9. This is an item to check at export | +| 13 | Single or double precision | All arrays are float64 | `= 1, `CubicFunction`, `Composite`, `Ones`, `Zeros`. If a profile has no known formula, refuse the model; do not sample it. +2. Keep the 8-term trilinear sum and the cell rule of Python (`_lookup_points`), including the clip of local coordinates to [0, 1]. +3. Compute the step in float64 only, in the order of Python: the frame at the current point, `d` from the profile, unit gradient of coordinate 1, `newp += g * (1 / steps) * d`. +4. Fix the set of moving points before step 0 (`|d| > 0`). Do not change it in later steps. +5. Apply the faults in the order of `restore_through` (`cutters_first(with_cutters(...))`), and give each fault the list of faults already restored. +6. Use the fallback gradient of #421: if the gradient is NaN and the point is finite, use the gradient of the frame without the cutting faults. Do not copy the PoC behaviour here. +7. A point that is not finite gives NaN values and a NaN gradient, as in Python (#413). Do not return 0.0 for it. +8. Apply the region mask of each frame member (value NaN outside the region), or refuse the model. Do not ignore a region. +9. Read `BLOCK_SIDE_EPSILON`, `BLOCK_EXTENSION`, `BLOCK_EXTENSION_EXACT`, `BLOCK_EXTENSION_LIMIT` and `BLOCK_EXTENSION_STEP` from `_fault_block.py` at the time of use, and write them in the manifest. Do not copy the numbers into the Rust code. +10. Build the local frame from `bounding_box.project`, as the PoC does, but also accept a rotated grid, or refuse it with a clear error. +11. Check the kernel with a model that has a fault with `smooth_peak` in gy, at the golden tolerance of 1e-8 times the box size. A pass on a model with only `Ones` profiles proves nothing about item 1. +12. To confirm the cause (open point): export the model f1_u0 with 2001, 20001 and 200001 samples and compare with Python. If the maximum difference falls with the square of the step, item 1 is the cause. + +## Stage S2 + +Measures SC-002, SC-003 and SC-007 and records the native differences (FR-005c). Task T021. + +### Set-up + +- Computer: the computer of spec 003 T030. Intel Core i7-12700H (12th Gen), 20 threads, Linux. +- Commit: `dcad71c78bc58501456311cd57a66b028e84f88d` (HEAD of the worktree). Other work was in the tree (an untracked test file of another task). +- Limit of the numbers: another agent could run tests at the same time (light load). The timings can be a little high. Each timing is the median of 7 repeats (31 repeats for runs below 10 ms), after two warm-up calls. +- Time method: for each model, 10 000 points (`sample_points(name, 10000, seed=1)`). For each faulted feature (`feature.faults` not empty, `faults_enabled`): + - Python: `restore_through(pts, feature.faults, owner=feature)` with `native_faults = False`. + - Native: `_native_faults.restore(feature, pts)` with `native_faults = True`, after one call that builds the FaultChain. `native_threads = 1` (SC-002) and `native_threads = 0` (all 20 threads, SC-003). + - The time of a model is the sum over its faulted features. Ratio = native / Python. + - Every timed feature gave the same result shape and no `None`: no feature fell back to Python and none was excluded. +- Memory method: `f4_u0`, first faulted feature (`group_0`), 10 000 000 points (`np.tile` of 10 000 sample points, float64 (N, 3), 240 MB), `native_threads = 0`. One restore in a fresh process for each path. The baseline is `VmRSS` after the points exist (and, for native, after the chain is built). The peak is `ru_maxrss` after the call. Extra = peak - baseline. The Python run took about 7.5 minutes, so the full 10 million points were used. +- Scratch scripts and results: `/home/lgrose/.claude/jobs/8f5b2ef3/tmp/t021/`. + +### SC-002: native restore, 1 thread, at most 20 % of Python + +| Model | Python ms | Native ms (1 thread) | Ratio | Target | Result | +|-------|-----------|----------------------|-------|--------|--------| +| f1_u0 | 76.4 | 22.9 | 0.299 | <= 0.20 | fail | +| f4_u0 | 314.0 | 92.8 | 0.295 | <= 0.20 | fail | +| f4_u3 | 2148.4 | 627.2 | 0.292 | <= 0.20 | fail | +| cutting_faults | 487.9 | 112.8 | 0.231 | <= 0.20 | fail | +| plugin | 725.6 | 191.6 | 0.264 | <= 0.20 | fail | + +### SC-003: native restore, 20 threads, at most 3 % of Python + +| Model | Python ms | Native ms (20 threads) | Ratio | Target | Result | +|-------|-----------|------------------------|-------|--------|--------| +| f1_u0 | 76.4 | 2.2 | 0.028 | <= 0.03 | pass | +| f4_u0 | 314.0 | 8.1 | 0.026 | <= 0.03 | pass | +| f4_u3 | 2148.4 | 57.4 | 0.027 | <= 0.03 | pass | +| cutting_faults | 487.9 | 11.2 | 0.023 | <= 0.03 | pass | +| plugin | 725.6 | 17.8 | 0.025 | <= 0.03 | pass | + +The margin of SC-003 is small (0.023 to 0.028 against 0.03). A load from other work can change the result for `f1_u0`. + +### SC-007: extra peak memory of a native restore, 10 million points + +| Path | Baseline MB | Peak MB | Extra MB | +|------|-------------|---------|----------| +| Native | 479.2 | 1164.3 | 685.1 | +| Python | 476.0 | 6912.2 | 6430.4 | + +- Rule (spec 003 FR-010, `acceptance.py` `_check_memory`, `limit = 1.20`): a new value fails only if it is above `1.20 * base` AND more than `MEMORY_ALLOWANCE_BYTES` (16 MiB) above `base`. Base = the Python extra memory. +- New (native) extra is 685.1 MB. The limit value is 1.20 * 6430.4 = 7716.5 MB. Native is below base. +- Result: pass. Native uses about 11 % of the extra memory of Python. +- Note: the native extra memory is about 2.9 times the size of the point array (240 MB). The reason was not examined. + +### Largest native difference (`max_native_diff`) + +Source: `OMP_NUM_THREADS=1 pytest tests/fault_evaluation/test_native_faults.py -q -p no:cacheprovider --junitxml=.../native.xml`. Result: 10 passed. The test uses 2000 points and compares many variants (default, reverse, block sides, `restored_through`). The box size is the largest box extent. + +| Model | Max difference (m) | Box size (m) | Difference / box | Fallback cases | +|-------|--------------------|--------------|------------------|----------------| +| f1_u0 | 2.27e-13 | 1000 | 2.3e-16 | none | +| f4_u0 | 2.27e-13 | 1000 | 2.3e-16 | none | +| f4_u3 | 2.27e-13 | 1000 | 2.3e-16 | none | +| cutting_faults | 5.68e-13 | 1000 | 5.7e-16 | `group_0` with `reverse=True` uses Python | +| plugin | 9.31e-10 | 29 656.82 | 3.1e-14 | none | +| stopped_fault | 1.14e-13 | 1000 | 1.1e-16 | none | +| faulted_fold | 1.82e-12 | 10 000 | 1.8e-16 | none | + +All differences are far below the golden tolerance of 1e-8 times the box size. The PoC difference of C-007 (5.4e-5 m) is not present. + +### Result + +- SC-002: FAIL for all 5 models. The ratio is 0.23 to 0.30 against a target of 0.20. The limit was not changed. +- SC-003: PASS for all 5 models. The ratio is 0.023 to 0.028 against a target of 0.03. +- SC-007: PASS. Native extra memory 685 MB, Python 6430 MB. +- FR-005c: the largest native difference is 9.3e-10 m (`plugin`), or 3.1e-14 of the box. For the 1000 m models it is 5.7e-13 m or less. +- One fallback case: `cutting_faults`, `group_0`, `reverse=True` (the native path returns `None`, Python is used). No fallback in the timed (non-reverse) calls. + +## Stage S2 after T035 + +Task T035. It makes the 1-thread native restore faster, with the same results. + +### What changed + +- `FaultChain::apply` reads the frame point (the point restored through the cutters) one time for each step. Before, it read it up to four times for each step. It also keeps the displacement fraction of step 0 instead of computing it again. +- `FaultChain::restore` and `Region::Sign::contains` use a stack array (up to 64 faults) in place of `to_vec()` and `vec![false; n]`. There is no allocation for each call. +- The floating-point operations and their order are the same. No public signature changed. + +### Profile + +- `perf record` is not allowed on this computer (`perf_event_paranoid`), so there is no function profile. +- The costs came from the code: the two allocations for each point and the repeated `frame_point` call (a full restore through the cutters). Both are removed. +- Remaining costs (not measured by a profile): the grid look-ups of `GridField` (`lookup` is done again for `value` and for `gradient` of the same point), and the cutter restores of `Region::Unconformity` and `Region::Sign`. `grid_field.rs` is not in the Files of T035. If SC-002 must pass, add it to a new task. + +### Set-up + +- Same method as "Stage S2" (10 000 points, median of 7 or 31 repeats, `native_threads = 1` and `0`). Script copy: `/home/lgrose/.claude/jobs/8f5b2ef3/tmp/t035/time.py`. +- Limit of the numbers: the computer had a load average of about 11 (other agents ran tests). The Python times are about 1.8 times the T021 times, and the 20-thread run is hurt most by the load. Measure again on a quiet computer before you trust a pass or fail near the target. + +### SC-002: native restore, 1 thread, at most 20 % of Python + +| Model | Python ms | Native ms (1 thread) | Ratio | Target | Result | +|-------|-----------|----------------------|-------|--------|--------| +| f1_u0 | 137.6 | 37.0 | 0.269 | <= 0.20 | fail | +| f4_u0 | 752.2 | 144.8 | 0.192 | <= 0.20 | pass | +| f4_u3 | 4654.8 | 1050.0 | 0.226 | <= 0.20 | fail | +| cutting_faults | 907.7 | 184.7 | 0.204 | <= 0.20 | fail | +| plugin | 1228.6 | 288.0 | 0.234 | <= 0.20 | fail | + +Native time of T021 (quiet computer) against now (loaded computer): the ratios went from 0.23-0.30 to 0.19-0.27. + +### SC-003: native restore, 20 threads, at most 3 % of Python + +| Model | Python ms | Native ms (20 threads) | Ratio | Target | Result | +|-------|-----------|------------------------|-------|--------|--------| +| f1_u0 | 137.6 | 6.2 | 0.045 | <= 0.03 | fail (load) | +| f4_u0 | 752.2 | 19.6 | 0.026 | <= 0.03 | pass | +| f4_u3 | 4654.8 | 136.6 | 0.029 | <= 0.03 | pass | +| cutting_faults | 907.7 | 21.9 | 0.024 | <= 0.03 | pass | +| plugin | 1228.6 | 32.1 | 0.026 | <= 0.03 | pass | + +### Largest native difference (`max_native_diff`) + +Source: `OMP_NUM_THREADS=1 pytest tests/fault_evaluation/test_native_faults.py --junitxml=...`. 10 passed. + +| Model | Max difference (m) | Box size (m) | Difference / box | +|-------|--------------------|--------------|------------------| +| f1_u0 | 2.27e-13 | 1000 | 2.3e-16 | +| f4_u0 | 2.27e-13 | 1000 | 2.3e-16 | +| f4_u3 | 2.27e-13 | 1000 | 2.3e-16 | +| cutting_faults | 1.25e-12 | 1000 | 1.3e-15 | +| plugin | 9.31e-10 | 29 656.82 | 3.1e-14 | +| stopped_fault | 1.14e-13 | 1000 | 1.1e-16 | +| faulted_fold | 1.82e-12 | 10 000 | 1.8e-16 | + +The `cutting_faults` value is higher than in T021 (5.68e-13). The Rust code computes the same operations; the Python side (sample points or solver) is the likely reason. This was not examined. All values are far below 1e-8 times the box. + +### Result + +- See the quiet re-measure below: SC-002 fails for all 5 models; SC-003 passes for all 5 models. +- Rust tests pass (`cargo test --release`, also `--features parallel`). Clippy passes for no features, `parallel`, `python`, `python,parallel`. +- Python tests pass: `test_native_faults.py`, `test_native_safety.py`, `test_golden.py` (43 passed). +- SC-002: 1 of 5 models passes (`f4_u0` 0.192), 4 fail (0.204 to 0.269), under load. Not met for all models. (measured under load; replaced by the quiet re-measure below) +- SC-003: 4 of 5 models pass; `f1_u0` (0.045) fails under load. T021 had 0.028 for this model on a quiet computer. (measured under load; replaced by the quiet re-measure below) +- FR-005c: the largest native difference is 9.3e-10 m (`plugin`), 3.1e-14 of the box. + +### Quiet re-measure (orchestrator) + +Measured on a quiet computer (load average below 3, nothing else running, 2026-11-27 15:53). Same script and method as T021: medians of 7 or more repeats, 10 000 points. + +| Model | Python ms | Native 1 thread ms | Ratio 1 thread (SC-002, target 0.20) | Native 20 threads ms | Ratio 20 threads (SC-003, target 0.03) | +|---|---|---|---|---|---| +| f1_u0 | 77.7 | 23.1 | 0.298 fail | 2.1 | 0.0275 pass | +| f4_u0 | 305.1 | 88.2 | 0.289 fail | 8.3 | 0.0273 pass | +| f4_u3 | 2157.1 | 634.4 | 0.294 fail | 58.0 | 0.0269 pass | +| cutting_faults | 493.4 | 113.8 | 0.231 fail | 11.1 | 0.0225 pass | +| plugin | 726.3 | 194.8 | 0.268 fail | 17.8 | 0.0244 pass | + +The ratios are the same as in T021 (Stage S2) within the noise. The changes of T035 did not make the 1-thread restoration measurably faster. The better ratios above this sub-section came from the load on the computer, which made the Python times longer. SC-002 fails for all 5 models. SC-003 passes for all 5 models. + +## Stage S3 + +Measures SC-004 (many-faults model) and SC-005 (golden test with the native path on). Task T028. + +### Set-up + +- Computer: the computer of spec 003 T030. Intel Core i7-12700H, 20 threads, Linux. Load average was 1.8 to 3 during the runs (another agent edited ROADMAP.md only). +- Commit: `d12101b223acf7c758a410ea0d6cdc978450b3eb` (HEAD of the worktree, kernel built, no code changed by this task). +- Native path on: `LOOPSTRUCTURAL_NATIVE_FAULTS` not set. A separate check gave `native_enabled()` = True in this venv. In the 94-fault model, `chain_for(...)` is not `None` for 3 of 3 faulted features (the features in `model.features` that have `faults`). +- Method: the model of `benchmarks/fault_evaluation/many_faults.py` (94 faults, built once), points from `many_faults.points(n)`, `evaluate_model` timed on the first call for each point count. 500, 2000 and 5000 points. Native build time: 153 s. Python build time: 176 s. +- Problem found: `python -m benchmarks.fault_evaluation.many_faults` stops with the native path on. The script times the calls of `FaultSegment.apply_to_points`. The native path does not call it, so the lists of per-fault times are empty and `np.max` raises `ValueError`. No JSON is written. The benchmark script was not changed (this task changes no code). The native times come from a scratch script (`/home/lgrose/.claude/jobs/8f5b2ef3/tmp/t028/native_run.py`) that imports `build` and `points` from the benchmark and times `evaluate_model` in the same way. The JSON is `/home/lgrose/.claude/jobs/8f5b2ef3/tmp/t028/many_faults_native.json`. The first call of each point count is the value in the table; the median of 5 repeated calls is 0.053, 0.056 and 0.060 s. +- Python run: the benchmark script with `LOOPSTRUCTURAL_NATIVE_FAULTS=0`, same venv, `many_faults_python.json` in the same folder. This is the Python path after stage S1 of spec 007. +- Baselines: (a) same venv, spec 007 S1, quiet computer: 0.615 s at 500 points, 0.894 s at 5000 points (2.05 s at 5000 points before S1). (b) `_runs007/many_faults_python.json`: 2.09 s at 5000 points. This is the master Python path before spec 007. + +### SC-004: `evaluate_model` at 5000 points, at most 0.5 s + +| Points | Native s | Python s (same run conditions) | Ratio native / Python | Python s (S1 baseline) | Master s (_runs007) | +|---|---|---|---|---|---| +| 500 | 0.059 | 0.676 | 0.087 | 0.615 | - | +| 2000 | 0.056 | 0.742 | 0.076 | - | - | +| 5000 | 0.059 | 0.971 | 0.061 | 0.894 | 2.09 | + +- Target: 0.5 s at 5000 points. Measured: 0.059 s. Pass. (The ratio to master, 2.09 s, is 0.028.) +- The native time is almost the same for 500, 2000 and 5000 points. The work is not limited by the point count in this range. +- Mean time of one fault call (Python run, 5000 points): cutting faults 18.3 ms (maximum 28.5 ms), isolated faults 3.83 ms. The native path does not call `apply_to_points`, so these means are not available for it. +- `fault_calls` is 94 in the Python run. It is not available for the native run (same reason). +- Native results are not bit-identical to Python (C-001), so `--compare` was not used. + +### SC-005: golden test with the native path on + +- Command: `OMP_NUM_THREADS=1 .venv/bin/python -m pytest tests/fault_evaluation/test_golden.py -q -n 8 -p no:cacheprovider`, no environment variable. Result: 23 passed, 0 failed (warnings only). The test prints no difference values. +- Largest field difference: `tests/fault_evaluation/test_native_field.py` gives 11 passed. The largest `max_native_diff` in the junit file is 1.16e-10 (the other values are 2.3e-13 to 1.8e-12). + +### Result + +- SC-004: pass. 0.059 s at 5000 points (target 0.5 s). Python in the same conditions: 0.971 s. +- SC-005: pass. 23 of 23 golden tests pass with the native path on. +- Largest native field difference: 1.16e-10. +- Open point: `benchmarks/fault_evaluation/many_faults.py` fails with the native path on (empty per-fault timer lists). It must write the JSON without per-fault times for the native path. A separate task is needed. (fixed by T036: the per-fault times are None on the native path) + +## Stage S4 + +Task T032, check SC-008. Date: 2026-11-27. + +The branch `feat/007-native-fault-kernel` is not pushed. No CI run of +`core-wheels.yml` exists for this code. The maintainer has not agreed to start +one. Only Linux x86_64 (this computer) is checked. + +| Platform | Wheel built | Installed clean | Smoke test | Golden tests, native on | Note | +|---|---|---|---|---|---| +| Linux x86_64 | pass | pass | pass | pass (23 passed) | Built locally, Python 3.13. Wheel tag is `manylinux_2_35_x86_64`: there is no manylinux container here. CI uses `manylinux: auto`. Python 3.9 is not installed here (only 3.12, 3.13, 3.14), so abi3-py39 is not tested on 3.9. | +| Linux aarch64 | not checked | not checked | not checked | not checked | Needs a CI run of `core-wheels.yml` on the pushed branch (maintainer decision). | +| macOS arm64 | not checked | not checked | not checked | not checked | Needs a CI run of `core-wheels.yml` on the pushed branch (maintainer decision). | +| macOS x86_64 | not checked | not checked | not checked | not checked | Not run in CI (cross-compiled). Maintainer check needed. | +| Windows x64 | not checked | not checked | not checked | not checked | Needs a CI run of `core-wheels.yml` on the pushed branch (maintainer decision). | + +### Commands (Linux x86_64) + +Run from the worktree root. `T` is the scratch directory. + +``` +.venv/bin/maturin build --release --out $T/dist -m packages/loop_interpolation_core/Cargo.toml +uv venv --python 3.13 $T/venv +uv pip install -p $T/venv/bin/python numpy scipy pandas pytest +uv pip install -p $T/venv/bin/python --no-index --find-links $T/dist loop-interpolation-core +uv pip install -p $T/venv/bin/python -e packages/loop_common -e packages/loop_interpolation -e . +$T/venv/bin/python -I -c "import loop_interpolation_core as c; print(c.__file__, c.FAULT_KERNEL_VERSION)" +$T/venv/bin/python smoke.py # heredoc of the CI step "Install the wheel and solve a small problem" +$T/venv/bin/python -m pytest tests/fault_evaluation/test_golden.py -q -p no:cacheprovider +``` + +Only the wheel is under test. LoopStructural is an editable install from the +worktree. `LOOPSTRUCTURAL_NATIVE_FAULTS` is not set, so the native path is on. + +Output: + +- `import loop_interpolation_core` loads from + `$T/venv/lib/python3.13/site-packages/loop_interpolation_core/__init__.py` + (the clean venv). `FAULT_KERNEL_VERSION` is 1. +- Smoke script: "solve converged in 78 iterations", "fault kernel restore ok". +- Golden tests: 23 passed. + +### Result + +- SC-008 is checked for Linux x86_64 only. +- Linux aarch64, macOS arm64 and Windows x64: not checked. +- macOS x86_64: not run in CI (cross-compiled). Maintainer check needed. +- Next step: run `core-wheels.yml` after the branch is pushed (maintainer + decision), then fill the other rows. + +## SC-006 + +Task T033, check SC-006 and FR-015. Date: 2026-11-27. Commands run from the +worktree root with `OMP_NUM_THREADS=1` and `-n 8 -p no:cacheprovider -rf`. + +| Run | Setting | Passed | Failed | Skipped | Failures | +|---|---|---|---|---|---| +| 1 | Core built (`maturin develop --release`), native path on | 3341 | 1 | 23 | `tests/unit/modelling/test_native_fault_frame.py::test_the_native_fault_frame_is_the_cg_fault_frame` | +| 2 | Core built, `LOOPSTRUCTURAL_NATIVE_FAULTS=0` | 3341 | 1 | 23 | the same test | +| 3 | Core uninstalled (`import loop_interpolation_core` gives `ModuleNotFoundError`) | 3296 | 0 | 40 | none | + +The one failure in runs 1 and 2 is not in scope. It fails on master `907acf42` +too, whenever the native core is installed (native solver, #383). In run 3 the +test is skipped because the core is not installed. After run 3 the core was +installed again and `import loop_interpolation_core` works. + +### Ruff + +`ruff check LoopStructural packages`: 34 errors. The baseline on master +`6874364c` also has 34 errors. No line is new (compared by file, code and +message, without line numbers). + +### Result + +- SC-006: pass, with the one known failure above. No other test fails with the native path on, off or not installed. +- FR-015: the suite runs without the core (run 3: 0 failed). +- Ruff: no new errors. + +## Stage S5 + +Task T042, check SC-006 after the package move. Date: 2026-11-27. Commands run +from the worktree root with `OMP_NUM_THREADS=1` and `-n 8 -p no:cacheprovider -rf`. + +The fault kernel is now the package `packages/loop_model_core` (module `loop_model_core`). +The solver core stays in `packages/loop_interpolation_core`. Both were built with `maturin develop --release`. + +| Run | Setting | Installed cores | Passed | Failed | Skipped | Failures | +|---|---|---|---|---|---|---| +| 1 | Native path on | `loop_interpolation_core`, `loop_model_core` | 3343 | 1 | 23 | `tests/unit/modelling/test_native_fault_frame.py::test_the_native_fault_frame_is_the_cg_fault_frame` (known failure, native solver) | +| 2 | `LOOPSTRUCTURAL_NATIVE_FAULTS=0` | `loop_interpolation_core`, `loop_model_core` | 3343 | 1 | 23 | the same test | +| 3 | `loop-model-core` uninstalled (`import loop_model_core` gives `ModuleNotFoundError`, `import loop_interpolation_core` works) | `loop_interpolation_core` | 3311 | 1 | 27 | the same test | + +In run 3 the solver core is still installed. For this reason the known solver +test still runs and fails, unlike T033 (where the solver core was removed +too). The fault kernel tests are skipped in run 3. After run 3, +`loop-model-core` was installed again with `maturin develop --release` and +`import loop_model_core` works. + +### Ruff + +`ruff check LoopStructural packages`: 34 errors. The master baseline also has +34 errors. No line is new (compared by file, code and message, without line +numbers, with `comm -13`). + +### Rust + +`cargo test --release` and `cargo test --release --features parallel` pass. + +| Check | `loop_interpolation_core` | `loop_model_core` | +|---|---|---| +| `cargo fmt --check` | pass | pass | +| `cargo clippy --all-targets -- -D warnings` | pass | pass | +| `cargo clippy --all-targets --features parallel -- -D warnings` | pass | pass | +| `cargo clippy --all-targets --features python -- -D warnings` | pass | pass | +| `cargo test --release` | pass | pass | +| `cargo test --release --features parallel` | pass | pass | + +### Result + +- SC-006: pass, with the one known failure above. No other test fails with the native path on, off or with the fault kernel not installed. +- The suite runs without `loop-model-core` (run 3: only the known solver test fails). +- Ruff: no new errors. +- Rust: all checks pass in both crates. + +## 94-fault model: native against Python (after stage S5) + +Run by the orchestrator on 2026-11-27, commit 0f35f75d, on the T030 +computer (i7-12700H, 20 threads), with `loop-model-core` and the solver core +installed. One build of `benchmarks/fault_evaluation/many_faults.py` (154 s). +The model has 3 faulted features; `chain_for` and `field_for` are not None +for all 3, so the native path runs for each of them. For each point count, +`evaluate_model` and `evaluate_feature_value` of both groups ran with the +native path on, then off, on the same build and the same points. Tolerance: +1e-8 x the box size (10000 m) = 1.0e-04. + +| Points | Native s | Python s | Max diff group_1 | Max diff group_0 | NaN points (group_1 / group_0) | Model ids that differ | +|---|---|---|---|---|---|---| +| 500 | 0.063 | 0.624 | 5.1e-13 | 8.0e-13 | 207 / 293, equal | 0 | +| 2000 | 0.058 | 0.758 | 6.8e-13 | 1.3e-12 | 772 / 1228, equal | 0 | +| 5000 | 0.063 | 0.971 | 6.8e-13 | 1.3e-12 | 1959 / 3041, equal | 0 | + +The official benchmark with the native path on +(`python -m benchmarks.fault_evaluation.many_faults --points 500 2000 5000`) +runs to the end after T036 and writes its JSON (per-fault times are None, +because the native path makes no Python fault call): 500: 0.122 s; 2000: 0.058 s; 5000: 0.063 s; The first call +at 500 points includes the build of the native chains and fields. + +Result: + +- The native results agree with the Python path on the 94-fault model + (chains of cuts up to 20 faults deep): the largest difference is 1.3e-12, + about 1e-8 of the tolerance; the NaN points are equal; no model id + differs (FR-005, FR-005a, FR-005b). +- SC-004 passes with `loop-model-core`: 0.063 s at 5000 points (target + 0.5 s; Python 0.971 s in the same run; 2.09 s on master). +- The official 94-fault benchmark works with the native path on (T036). diff --git a/specs/README.md b/specs/README.md index 347fc4a17..1c866a98a 100644 --- a/specs/README.md +++ b/specs/README.md @@ -11,7 +11,7 @@ not certify that an implementation or a numerical acceptance gate passed. | [004-matrix-free-directional-constraints](004-matrix-free-directional-constraints/spec.md) | Draft; 005 contract cascade applied; task graph checked | Review the updated plan and tasks. OP1 still requires the quadrature measurements before a default is chosen. | | [005-coordinate-frame-correctness](005-coordinate-frame-correctness/spec.md) | S1 implemented 2026-11-04 on `feat/005-coordinate-frame-correctness` (17 of 17 tasks; evidence in [verification.md](005-coordinate-frame-correctness/verification.md)); S5 planned 2026-11-05 and revised after review; S6 planned 2026-11-06 and reviewed the same day; maintainer decisions recorded ("Stage S6 design" in plan.md; OP1, OP18, OP19 and OP20 closed; spec clarification C-019 added; OP21 to OP24 have defaults and block no task) | Review and merge the S1 branch. S2 planned and tasked 2026-11-04 (T018 to T031, waves 8 to 13); run spec-orchestrator for S2. S3 planned and tasked 2026-11-05 ("Stage S3 design" in plan.md; OP4 and OP5 closed; T033 to T050, waves 14 to 22; build after S2 merges). S3 is built on `feat/005-s3-frame-persistence` (pull request #397, stacked on #396; 18 of 18 tasks, evidence in verification.md). S3 merged (#397); a follow-up keeps the legacy load backward compatible (pull request #400). S4 planned and tasked 2026-11-05 ("Stage S4 design" in plan.md; OP8 to OP10 have defaults and block nothing; T051 to T068, waves 23 to 31); run spec-orchestrator for S4. S5 planned 2026-11-05 and revised the same day after review and five maintainer answers ("Stage S5 design" in plan.md; OP13 to OP15 closed; OP12, OP16 and OP17 have defaults; OP17 blocks the S5 merge only if a parity file changes); S5 tasked 2026-11-05 (T069 to T088, waves 32 to 42; no open point blocks a task; build after S4 merges). OP1 closed 2026-11-06. S6 tasked 2026-11-06 (T089 to T108, waves 43 to 52; 20 tasks; no open point blocks a task; build after S5 merges). OP3: constant-norm accuracy check. OP2 closed 2026-11-04: the R2/R5 matrix stays in the default pytest run. 7 minor review findings are open (run-state.json). | | [006-loop-link](006-loop-link/spec.md) | S1 to S3 (stories 1 and 5) implemented 2026-11-07 on `feat/006-loop-link` (37 of 37 tasks, 13 waves; wave and end reviews passed; not merged) | Pull request 406 is open. S5 (stories 2 to 4) planned 2026-11-07 against geoviewer spec 067 ([plan.md](006-loop-link/plan.md), "Design of stage S5"); S5 tasks written 2026-11-07 (T039 to T063; the file has 62 tasks in 19 waves); next: build S5 with the spec-orchestrator skill. S4 (stories 6, 7) planned 2026-11-08 ("Design of stage S4" in plan.md) and tasked 2026-11-08 (T064 to T087) and built except T080, T081, T086 and T087; geoviewer spec 072 (protocol 1.20) answered OP15 on 2026-11-09 and the S4d tasks were rewritten (T088 to T092 added; the file has 91 tasks in 23 waves); next: build the open S4 tasks with the spec-orchestrator skill. | -| [007-native-fault-kernel](007-native-fault-kernel/spec.md) | Draft 2026-11-27, reviewed and clarified 2026-11-27 (C-001 to C-011) | Run spec-planner after spec 003 is merged. The literature review of precomputed displacement maps is in its research.md. | +| [007-native-fault-kernel](007-native-fault-kernel/spec.md) | Draft 2026-11-27, reviewed and clarified 2026-11-27 (C-001 to C-011) | Planned 2026-11-27 (written on the spec 003 branch; OP1 check after the 003 merge #391: valid on master) ([plan.md](007-native-fault-kernel/plan.md); stages S1 to S4; OP2 to OP9 answered 2026-11-27: unconformity regions on fault frames and the tetrahedron gradient are native; all open points answered). Tasks written 2026-11-27 ([tasks.md](007-native-fault-kernel/tasks.md): T001 to T033, 11 waves; no task is blocked; the 94-fault model is `benchmarks/fault_evaluation/many_faults.py`). Next: build with the spec-orchestrator skill in the worktree `feat-007-native-fault-kernel`. The literature review of precomputed displacement maps is in its research.md. | ## Cascade of 005 diff --git a/tests/fault_evaluation/conftest.py b/tests/fault_evaluation/conftest.py new file mode 100644 index 000000000..baa996669 --- /dev/null +++ b/tests/fault_evaluation/conftest.py @@ -0,0 +1,40 @@ +"""Fixtures for the fault evaluation tests.""" + +from __future__ import annotations + +import pytest + +from LoopStructural import LoopStructuralConfig + +PYTHON_PATH_MODULES = ( + "test_context", + "test_gradient_context", + "test_memory", + "test_concurrency", + "test_no_retention", + "test_fault_frame_lookup", +) + + +@pytest.fixture(autouse=True) +def _python_path_for_internals(request, monkeypatch): + """Turn off the native fault kernel for the internal path tests. + + Parameters + ---------- + request : pytest.FixtureRequest + The request of the test that uses this fixture. + monkeypatch : pytest.MonkeyPatch + Patches the configuration for the duration of the test. + + Notes + ----- + These tests count or patch calls of the Python path + (``FaultSegment.apply_to_points`` or the grid lookups). The native + path does not make these calls. See spec 007 plan, Answers, T016. + """ + # Only the modules in PYTHON_PATH_MODULES use the Python path. + module_name = request.module.__name__.rsplit(".", 1)[-1] + if module_name in PYTHON_PATH_MODULES: + # The native path does not call apply_to_points. Use Python here. + monkeypatch.setattr(LoopStructuralConfig, "native_faults", False) diff --git a/tests/fault_evaluation/test_fault_frame_lookup.py b/tests/fault_evaluation/test_fault_frame_lookup.py index 62e37dc4c..dd5d4d402 100644 --- a/tests/fault_evaluation/test_fault_frame_lookup.py +++ b/tests/fault_evaluation/test_fault_frame_lookup.py @@ -397,7 +397,9 @@ def _case_domain_region(): # The three frame members of this case share one region object. The fast path can then # use one shared mask and make fewer lookups than the legacy path. Both paths are valid. -EQUIVALENT_REGION_CASES = {"domain_region"} +# child_faults: spec 007 D1b shares one restoration among the members of a cut frame, so it +# makes fewer lookups; the values are still asserted. +EQUIVALENT_REGION_CASES = {"domain_region", "child_faults"} @pytest.fixture(params=sorted(FALLBACK_CASES)) @@ -411,7 +413,7 @@ def fallback_case(fallback_name): def _assert_lookup_count(name, actual_count, legacy_count): - """Require the exact legacy count, except when the region masks are equivalent.""" + """Require the exact legacy count, except when the region masks are equivalent or D1b shares the restoration.""" if name in EQUIVALENT_REGION_CASES: assert actual_count <= legacy_count else: diff --git a/tests/fault_evaluation/test_many_faults.py b/tests/fault_evaluation/test_many_faults.py new file mode 100644 index 000000000..8ca42eba1 --- /dev/null +++ b/tests/fault_evaluation/test_many_faults.py @@ -0,0 +1,33 @@ +"""The 94-fault benchmark model of spec 007: its fault layout is fixed (no model build).""" + +import numpy as np + +from benchmarks.fault_evaluation import many_faults + + +def test_fault_layout_is_deterministic(): + specs = many_faults.fault_specs() + assert len(specs) == 94 + assert sum(s["kind"] == "cutting" for s in specs) == 40 + # A fault is cut only by younger (lower index) cutting faults, at most 3 of them. + for k, s in enumerate(specs): + assert all(m < k and specs[m]["kind"] == "cutting" for m in s["cut_by"]) + assert len(s["cut_by"]) <= many_faults.MAX_CUTTERS + assert [s["cut_by"] for s in many_faults.fault_specs()] == [s["cut_by"] for s in specs] + + +def test_compare_reports_changed_and_missing_arrays(tmp_path): + path = tmp_path / "ref.npz" + np.savez(path, a=np.array([1.0, np.nan]), b=np.array([1])) + assert many_faults.compare({"a": np.array([1.0, np.nan]), "b": np.array([1])}, path) == [] + assert many_faults.compare({"a": np.array([1.0, 2.0])}, path) == ["a", "b"] + + +def test_fault_summary_is_none_when_no_fault_call_is_timed(): + summary = many_faults._fault_summary({"isolated": [], "cutting": []}) + assert summary == {"isolated_mean_ms": None, "cutting_mean_ms": None, "cutting_max_ms": None} + + +def test_fault_summary_of_timed_calls(): + summary = many_faults._fault_summary({"isolated": [1.0, 3.0], "cutting": [2.0, 6.0]}) + assert summary == {"isolated_mean_ms": 2.0, "cutting_mean_ms": 4.0, "cutting_max_ms": 6.0} diff --git a/tests/fault_evaluation/test_native_faults.py b/tests/fault_evaluation/test_native_faults.py new file mode 100644 index 000000000..257f78775 --- /dev/null +++ b/tests/fault_evaluation/test_native_faults.py @@ -0,0 +1,141 @@ +"""Native restoration agrees with the Python path (spec 007, story 2, FR-003, FR-005). + +The native result comes from ``_native_faults.restore``. The reference comes from +``restore_through`` with the native path turned off. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +pytest.importorskip("loop_model_core") + +from LoopStructural import LoopStructuralConfig +from LoopStructural.modelling.features import _native_faults +from LoopStructural.utils._fault_block import _cutters, check_block, restore_through +from tests.fault_evaluation.golden import _coordinates +from tests.fault_evaluation.models import build_model, sample_points + +MODELS = ["f1_u0", "f4_u0", "f4_u3", "cutting_faults", "plugin", "stopped_fault", "faulted_fold"] +MUST_BE_SUPPORTED = ["f1_u0", "f4_u0", "f4_u3", "cutting_faults"] +ENV_VAR = "LOOPSTRUCTURAL_NATIVE_FAULTS" + +_CACHE: dict = {} + + +def _case(name): + """Return (model, points, box_size, faulted features) and build each model once.""" + if name not in _CACHE: + model = build_model(name) + points = sample_points(name, 2000, seed=1) + # Same rule as ``_box_size`` in regenerate.py: the largest box extent. + box = model.bounding_box + size = float(np.max(np.asarray(box.maximum) - np.asarray(box.origin))) + features = [ + f + for f in _coordinates(model) + if getattr(f, "faults", None) and getattr(f, "faults_enabled", False) + ] + _CACHE[name] = (model, points, size, features) + return _CACHE[name] + + +@pytest.fixture +def python_path(monkeypatch): + """Turn the native path off for the reference and clear the variable.""" + monkeypatch.delenv(ENV_VAR, raising=False) + monkeypatch.setattr(LoopStructuralConfig, "native_faults", False) + + +def _variants(feature): + """Return the keyword arguments of each call to compare.""" + first = feature.faults[0] + cases = [{}, {"reverse": True}] + for fault in feature.faults: + cases += [{"block": {fault.name: side}} for side in (1, -1, 0)] + if len(feature.faults) >= 2: + cases.append({"restored_through": (first,)}) + return cases + + +@pytest.mark.parametrize("name", MODELS) +def test_native_restore_matches_python(name, monkeypatch, record_property): + """Native and Python restoration agree for every supported faulted feature.""" + _, points, size, features = _case(name) + skipped, supported, fallback, worst = [], [], [], 0.0 + for feature in features: + monkeypatch.delenv(ENV_VAR, raising=False) + monkeypatch.setattr(LoopStructuralConfig, "native_faults", None) + if _native_faults.chain_for(feature) is None: + skipped.append(feature.name) + continue + supported.append(feature.name) + for kwargs in _variants(feature): + monkeypatch.setattr(LoopStructuralConfig, "native_faults", None) + native = _native_faults.restore(feature, points, **kwargs) + if native is None: + # Documented fallback (plan.md, T016). Simple check: a reverse + # call of a feature with a cutting fault goes to the Python path. + assert kwargs.get("reverse") is True, (feature.name, kwargs) + assert any(_cutters(f) for f in feature.faults), (feature.name, kwargs) + fallback.append(f"{feature.name}:{kwargs}") + monkeypatch.setattr(LoopStructuralConfig, "native_faults", None) + public = feature._apply_faults(points, reverse=True) + monkeypatch.setattr(LoopStructuralConfig, "native_faults", False) + native = public + monkeypatch.setattr(LoopStructuralConfig, "native_faults", False) + reference = restore_through( + points, + feature.faults, + reverse=kwargs.get("reverse", False), + block=check_block(kwargs.get("block")), + restored_through=kwargs.get("restored_through", ()), + owner=None, + ) + assert native.shape == reference.shape + # NaN rows must be the same rows (FR-005a). + nan = np.isnan(native).any(axis=1) + assert np.array_equal(nan, np.isnan(reference).any(axis=1)), (feature.name, kwargs) + if not nan.all(): + diff = float(np.nanmax(np.abs(native - reference))) + worst = max(worst, diff) + assert diff <= 1e-8 * size, (feature.name, kwargs, diff) + record_property("max_native_diff", worst) + record_property("native_supported_features", ",".join(supported)) + record_property("native_fallback_cases", ";".join(fallback)) + record_property("native_skipped_features", ",".join(skipped)) + if name in MUST_BE_SUPPORTED: + assert features + assert not skipped + + +def _supported_feature(): + return _case("f1_u0")[3][0] + + +def test_native_used_by_default(monkeypatch): + """Story 4, scenario 1: with the defaults the native path is used.""" + monkeypatch.delenv(ENV_VAR, raising=False) + monkeypatch.setattr(LoopStructuralConfig, "native_faults", None) + points = _case("f1_u0")[1] + assert isinstance(_native_faults.restore(_supported_feature(), points), np.ndarray) + + +def test_native_off_by_setting(monkeypatch): + """Story 4, scenario 2: the setting False turns the native path off.""" + monkeypatch.delenv(ENV_VAR, raising=False) + monkeypatch.setattr(LoopStructuralConfig, "native_faults", False) + points = _case("f1_u0")[1] + assert _native_faults.restore(_supported_feature(), points) is None + + +def test_native_off_by_variable(monkeypatch): + """Story 4, scenario 3: the variable "0" turns it off; the setting wins over it.""" + points = _case("f1_u0")[1] + feature = _supported_feature() + monkeypatch.setenv(ENV_VAR, "0") + monkeypatch.setattr(LoopStructuralConfig, "native_faults", None) + assert _native_faults.restore(feature, points) is None + monkeypatch.setattr(LoopStructuralConfig, "native_faults", True) + assert isinstance(_native_faults.restore(feature, points), np.ndarray) diff --git a/tests/fault_evaluation/test_native_field.py b/tests/fault_evaluation/test_native_field.py new file mode 100644 index 000000000..540a65e57 --- /dev/null +++ b/tests/fault_evaluation/test_native_field.py @@ -0,0 +1,141 @@ +"""Native values, gradients and model ids agree with the Python path (spec 007, story 3). + +Covers FR-004, FR-005, FR-005a and FR-005b. The native result is ``capture`` with the +defaults. The reference is ``capture`` with ``LoopStructuralConfig.native_faults`` off. +""" + +from __future__ import annotations + +import logging + +import numpy as np +import pytest + +pytest.importorskip("loop_model_core") + +from LoopStructural import LoopStructuralConfig +from LoopStructural.modelling.features import _native_faults +from tests.fault_evaluation.golden import _coordinates, assert_matches, capture +from tests.fault_evaluation.models import build_model, sample_points + +MODELS = [ + "f1_u0", + "f4_u0", + "f4_u3", + "cutting_faults", + "plugin", + "stopped_fault", + "faulted_fold", + "onlap_domain", +] +ENV_VAR = "LOOPSTRUCTURAL_NATIVE_FAULTS" +# Map a model name to the set of feature names that cannot use the native path by design +# (a fold, or an interpolator that is not a DiscreteInterpolator on a StructuredGrid). +# Add an entry only with a comment that gives the reason. +FIELD_EXCLUSIONS: dict = { + # The fold interpolator uses a tetrahedral mesh. Spec 007 supports only structured grids + # (spec.md "Out of scope"). + "faulted_fold": {"folded_unit"}, +} +_CACHE: dict = {} + + +def _case(name): + """Return (model, points, box_size) and build each model once.""" + if name not in _CACHE: + model = build_model(name) + box = model.bounding_box + size = float(np.max(np.asarray(box.maximum) - np.asarray(box.origin))) + _CACHE[name] = (model, sample_points(name, 2000, seed=1), size) + return _CACHE[name] + + +def _faulted(model): + return [f for f in _coordinates(model) if getattr(f, "faults", None)] + + +def test_field_for_exists(monkeypatch): + """Story 3: the native field of a faulted feature is available.""" + monkeypatch.setattr(LoopStructuralConfig, "native_faults", True) + features = _faulted(_case("f1_u0")[0]) + assert features + for feature in features: + assert _native_faults.field_for(feature) is not None + + +@pytest.mark.parametrize("name", MODELS) +def test_native_capture_matches_python(name, monkeypatch, record_property): + """Values, gradients and model ids with native on equal those with native off.""" + model, points, size = _case(name) + monkeypatch.delenv(ENV_VAR, raising=False) + monkeypatch.setattr(LoopStructuralConfig, "native_faults", None) + # The native path must run, or this test compares the Python path with itself. + assert _native_faults.native_enabled() + for feature in _faulted(model): + assert _native_faults.chain_for(feature) is not None + if feature.name in FIELD_EXCLUSIONS.get(name, set()): + continue + assert _native_faults.field_for(feature) is not None + native = capture(model, points) + monkeypatch.setattr(LoopStructuralConfig, "native_faults", False) + reference = capture(model, points) + # assert_matches lets model ids differ only where the Python value is within + # 1e-8 * box_size of a unit boundary (FR-005b), using unit_boundary_distances. + assert_matches(name, native, reference, size) + worst = 0.0 + for key, value in reference.items(): + a, b = np.asarray(native[key]), np.asarray(value) + if a.dtype.kind == "f" and a.shape == b.shape and np.isfinite(a).any(): + both = np.isfinite(a) & np.isfinite(b) + if both.any(): + worst = max(worst, float(np.max(np.abs(a[both] - b[both])))) + record_property("max_native_diff", worst) + + +def _point_on_fault(feature): + """Find a point where the first fault frame value is 0, by bisection.""" + points = _case("f1_u0")[1] + frame = feature.faults[0][0] + side = frame.evaluate_value(points) + a, b = points[np.argmax(side)], points[np.argmin(side)] + assert frame.evaluate_value(a[None])[0] > 0 > frame.evaluate_value(b[None])[0] + for _ in range(80): + mid = 0.5 * (a + b) + if frame.evaluate_value(mid[None])[0] > 0: + a = mid + else: + b = mid + return 0.5 * (a + b) + + +def test_gradient_on_fault_is_nan_and_warns_once(monkeypatch, caplog): + """Story 3, scenario 2: a point on a fault has a NaN gradient and one warning.""" + monkeypatch.delenv(ENV_VAR, raising=False) + monkeypatch.setattr(LoopStructuralConfig, "native_faults", None) + feature = _faulted(_case("f1_u0")[0])[0] + point = _point_on_fault(feature) + with caplog.at_level(logging.WARNING): + gradient = feature.evaluate_gradient(point[None]) + assert gradient.shape == (1, 3) + assert np.isnan(gradient).all() + warnings = [r for r in caplog.records if "too close to a fault" in r.getMessage()] + assert len(warnings) == 1 + # The Python path must also give a NaN gradient at this point. + monkeypatch.setattr(LoopStructuralConfig, "native_faults", False) + python_gradient = feature.evaluate_gradient(point[None]) + assert python_gradient.shape == (1, 3) + assert np.isnan(python_gradient).all() + + +def test_unconformity_region_uses_native_path(monkeypatch): + """A fault frame with an unconformity region still uses the native path.""" + monkeypatch.delenv(ENV_VAR, raising=False) + monkeypatch.setattr(LoopStructuralConfig, "native_faults", None) + features = [ + f + for f in _faulted(_case("onlap_domain")[0]) + if any(type(r).__name__ == "UnconformityFeature" for x in f.faults for r in x[0].regions) + ] + assert features + for feature in features: + assert _native_faults.chain_for(feature) is not None diff --git a/tests/fault_evaluation/test_native_safety.py b/tests/fault_evaluation/test_native_safety.py new file mode 100644 index 000000000..f6a39df21 --- /dev/null +++ b/tests/fault_evaluation/test_native_safety.py @@ -0,0 +1,202 @@ +"""Tests that the native fault path is safe to use (story 5, scenarios 2 to 7, edge cases). + +The tests need the installed package ``loop_model_core``. They use the model ``f4_u0``. +""" + +from __future__ import annotations + +import builtins +import threading +from copy import deepcopy + +import numpy as np +import pytest + +pytest.importorskip("loop_model_core") + +from loop_model_core import FaultChain + +from LoopStructural import LoopStructuralConfig +from LoopStructural.modelling.features import _native_faults +from tests.fault_evaluation.golden import _faulted_features +from tests.fault_evaluation.models import build_model, sample_points + +NAME = "f4_u0" +POINT_COUNT = 2000 +BIG_COUNT = 10_000_000 + + +@pytest.fixture(autouse=True) +def settings(monkeypatch): + """Reset the native settings and the environment variable for each test.""" + monkeypatch.setattr(LoopStructuralConfig, "native_faults", None) + monkeypatch.setattr(LoopStructuralConfig, "native_threads", None) + monkeypatch.delenv("LOOPSTRUCTURAL_NATIVE_FAULTS", raising=False) + + +@pytest.fixture(scope="module") +def shared(): + """Return the model, a faulted feature and sample points. Tests must not change them.""" + model = build_model(NAME) + feature = _faulted_features(model)[0][0] + return model, feature, sample_points(NAME, POINT_COUNT) + + +@pytest.fixture +def fresh(): + """Return a new model, a faulted feature and sample points, for tests that change state.""" + model = build_model(NAME) + feature = _faulted_features(model)[0][0] + return model, feature, sample_points(NAME, POINT_COUNT) + + +def _tolerance(model) -> float: + # Box size rule of tests/fault_evaluation/regenerate.py: the longest side of the box. + box = model.bounding_box + return 1e-8 * float(np.max(np.asarray(box.maximum) - np.asarray(box.origin))) + + +def _python_values(feature, pts): + LoopStructuralConfig.native_faults = False + try: + return feature.evaluate_value(pts) + finally: + LoopStructuralConfig.native_faults = None + + +def _python_restored(feature, pts): + LoopStructuralConfig.native_faults = False + try: + return feature._apply_faults(pts) + finally: + LoopStructuralConfig.native_faults = None + + +def test_native_path_is_used(shared): + _, feature, pts = shared + assert _native_faults.restore(feature, pts) is not None + feature.evaluate_value(pts) + assert hasattr(feature, "_native_chain") + + +def test_plain_python_function_uses_python_path(fresh): + model, feature, pts = fresh + # The setter accepts any callable, so the public attribute is used. + feature.faults[0].faultfunction = lambda gx, gy, gz: np.ones_like(gx) + assert _native_faults.chain_for(feature) is None + assert _native_faults.restore(feature, pts) is None + expected = _python_values(feature, pts) + np.testing.assert_allclose( + feature.evaluate_value(pts), expected, atol=_tolerance(model), equal_nan=True + ) + + +def test_second_call_reads_no_file_and_keeps_chain(fresh, monkeypatch): + _, feature, pts = fresh + feature.evaluate_value(pts) + first_chain = feature._native_chain[2] + + def fail(*args, **kwargs): + raise AssertionError("a file was opened") + + with monkeypatch.context() as patch: + patch.setattr(builtins, "open", fail) + assert _native_faults.restore(feature, pts) is not None + feature.evaluate_value(pts) + assert feature._native_chain[2] is first_chain + + +def test_changed_displacement_is_used(fresh): + model, feature, pts = fresh + assert _native_faults.restore(feature, pts) is not None + first_chain = feature._native_chain[2] + feature.faults[0].displacement = feature.faults[0].displacement * 1.5 + 1.0 + native = feature.evaluate_value(pts) + assert feature._native_chain[2] is not first_chain + np.testing.assert_allclose( + native, _python_values(feature, pts), atol=_tolerance(model), equal_nan=True + ) + + +def test_gil_is_released_during_restore(shared): + _, feature, pts = shared + big = np.ascontiguousarray(np.tile(pts, (BIG_COUNT // len(pts), 1)), dtype=np.float64) + counter = [0] + stop = threading.Event() + + def count(): + while not stop.is_set(): + counter[0] += 1 + + worker = threading.Thread(target=count) + worker.start() + try: + before = counter[0] + result = _native_faults.restore(feature, big) + after = counter[0] + finally: + stop.set() + worker.join() + assert result is not None + assert after - before >= 1000 + + +def test_two_threads_equal_single_thread(fresh): + _, feature, pts = fresh + assert _native_faults.restore(feature, pts) is not None + other = pts[::-1].copy() + alone = [feature.evaluate_value(pts), feature.evaluate_value(other)] + results = [None, None] + + def run(index, points): + for _ in range(5): + results[index] = feature.evaluate_value(points) + + threads = [threading.Thread(target=run, args=(i, p)) for i, p in enumerate((pts, other))] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + for got, want in zip(results, alone): + assert np.array_equal(got, want, equal_nan=True) + + +def test_one_thread_equals_all_threads(shared): + _, feature, pts = shared + LoopStructuralConfig.native_threads = 0 + all_threads = _native_faults.restore(feature, pts) + LoopStructuralConfig.native_threads = 1 + one_thread = _native_faults.restore(feature, pts) + assert all_threads is not None + assert np.array_equal(all_threads, one_thread, equal_nan=True) + + +def test_empty_points(shared): + _, feature, _ = shared + result = _native_faults.restore(feature, np.zeros((0, 3))) + assert result is not None + assert result.shape == (0, 3) + + +def test_nan_coordinate(shared): + model, feature, pts = shared + pts = pts.copy() + pts[3, 1] = np.nan + result = _native_faults.restore(feature, pts) + assert result is not None + # The Python path keeps a row with a NaN coordinate as it is. The native path must do the same. + expected = _python_restored(feature, pts) + np.testing.assert_array_equal(np.isnan(result), np.isnan(expected)) + np.testing.assert_allclose(result, expected, atol=_tolerance(model)) + + +def test_bad_spec_raises_and_state_is_kept(fresh): + _, feature, pts = fresh + before = deepcopy(_native_faults.restore(feature, pts)) + assert before is not None + first_chain = feature._native_chain[2] + with pytest.raises(ValueError): + FaultChain({"version": 99}) + after = _native_faults.restore(feature, pts) + assert np.array_equal(before, after, equal_nan=True) + assert feature._native_chain[2] is first_chain diff --git a/tests/fault_evaluation/test_native_settings.py b/tests/fault_evaluation/test_native_settings.py new file mode 100644 index 000000000..3914950b8 --- /dev/null +++ b/tests/fault_evaluation/test_native_settings.py @@ -0,0 +1,181 @@ +"""Tests for the native fault kernel settings (FR-006, FR-006a, FR-006b, FR-012). + +The tests use a fake ``loop_model_core`` module. They check the setting, +the environment variable, the version check and the thread count of +``LoopStructural.modelling.features._native_faults``. + +The module is reloaded before each test. This resets its one-time warning flag. +""" + +from __future__ import annotations + +import importlib +import logging +import sys +from types import SimpleNamespace + +import pytest + +from LoopStructural import LoopStructuralConfig + +MODULE_NAME = "LoopStructural.modelling.features._native_faults" +KERNEL_NAME = "loop_model_core" +ENV_VAR = "LOOPSTRUCTURAL_NATIVE_FAULTS" + + +def _set_kernel_version(monkeypatch, version): + """Install a fake kernel module with the given ``FAULT_KERNEL_VERSION``. + + Parameters + ---------- + monkeypatch : pytest.MonkeyPatch + Fixture used to undo the change after the test. + version : int + The version number the fake kernel reports. + """ + monkeypatch.setitem(sys.modules, KERNEL_NAME, SimpleNamespace(FAULT_KERNEL_VERSION=version)) + + +@pytest.fixture +def native(monkeypatch): + """Return a freshly reloaded ``_native_faults`` module with clean settings. + + Parameters + ---------- + monkeypatch : pytest.MonkeyPatch + Fixture used to set and undo the settings, the environment and ``sys.modules``. + + Returns + ------- + module + The reloaded ``_native_faults`` module. + """ + # The settings do not exist yet, so raising=False is needed. + monkeypatch.setattr(LoopStructuralConfig, "native_faults", None, raising=False) + monkeypatch.setattr(LoopStructuralConfig, "native_threads", None, raising=False) + monkeypatch.delenv(ENV_VAR, raising=False) + _set_kernel_version(monkeypatch, 1) + module = importlib.import_module(MODULE_NAME) + importlib.reload(module) + yield module + # Drop the fake kernel from the module state, so other tests in the same worker do not use it. + importlib.reload(module) + + +@pytest.fixture +def module_log(caplog): + """Capture the warnings that the ``_native_faults`` logger emits. + + The logger does not always reach the root logger. The test therefore + attaches the caplog handler to the logger itself. + + Parameters + ---------- + caplog : pytest.LogCaptureFixture + Pytest fixture that collects the log records. + + Yields + ------ + logging.Logger + The logger of the module under test. + """ + logger = logging.getLogger(MODULE_NAME) + old_propagate = logger.propagate + logger.propagate = False + logger.addHandler(caplog.handler) + caplog.set_level(logging.WARNING, logger=MODULE_NAME) + try: + yield logger + finally: + logger.removeHandler(caplog.handler) + logger.propagate = old_propagate + + +@pytest.mark.parametrize("value", ["0", "false", "OFF", "no"]) +def test_env_variable_disables_native(monkeypatch, native, value): + """The environment variable turns the native kernel off for these values.""" + monkeypatch.setenv(ENV_VAR, value) + assert native.native_enabled() is False + + +def test_unset_variable_enables_native(native): + """With no setting and no variable, the native kernel is on.""" + assert native.native_enabled() is True + + +def test_setting_true_wins_over_env_zero(monkeypatch, native): + """A True setting wins over the environment variable value "0".""" + monkeypatch.setenv(ENV_VAR, "0") + monkeypatch.setattr(LoopStructuralConfig, "native_faults", True, raising=False) + assert native.native_enabled() is True + + +def test_setting_false_disables_native(monkeypatch, native): + """A False setting turns the native kernel off.""" + monkeypatch.setattr(LoopStructuralConfig, "native_faults", False, raising=False) + assert native.native_enabled() is False + + +def test_import_failure_disables_native_without_warning(monkeypatch, native, module_log, caplog): + """A kernel that cannot be imported gives False and no warning.""" + monkeypatch.setitem(sys.modules, KERNEL_NAME, None) + assert native.native_enabled() is False + warnings = [r for r in caplog.records if r.levelno == logging.WARNING] + assert warnings == [] + + +def test_version_mismatch_disables_native_and_warns_once(monkeypatch, native, module_log, caplog): + """A version 2 kernel gives False, and the warning is logged only once.""" + _set_kernel_version(monkeypatch, 2) + assert native.native_enabled() is False + assert native.native_enabled() is False + matches = [ + r + for r in caplog.records + if r.levelno == logging.WARNING and "2" in r.getMessage() and "1" in r.getMessage() + ] + assert len(matches) == 1 + + +def test_native_threads_none_is_zero(native): + """With no thread setting, native_threads() returns 0.""" + assert native.native_threads() == 0 + + +def test_native_threads_one(monkeypatch, native): + """A thread setting of 1 is returned as 1.""" + monkeypatch.setattr(LoopStructuralConfig, "native_threads", 1, raising=False) + assert native.native_threads() == 1 + + +def test_negative_thread_count_means_all_cores(monkeypatch, native): + """A negative thread setting means all cores, as -1 in joblib, so it is returned as 0.""" + monkeypatch.setattr(LoopStructuralConfig, "native_threads", -1, raising=False) + assert native.native_threads() == 0 + + +def test_subclass_of_fault_displacement_uses_python_path(monkeypatch): + """A subclass of FaultDisplacement takes the Python path (FR-008).""" + pytest.importorskip("loop_model_core") + from LoopStructural.modelling.features import _native_faults + from LoopStructural.modelling.features.fault._fault_function import FaultDisplacement + from tests.fault_evaluation.models import build_model + + # The fake kernel of the native fixture is undone after its test, so the real kernel is used. + monkeypatch.setattr(LoopStructuralConfig, "native_faults", True, raising=False) + monkeypatch.setattr(LoopStructuralConfig, "native_threads", None, raising=False) + monkeypatch.delenv(ENV_VAR, raising=False) + importlib.reload(_native_faults) + + class Sub(FaultDisplacement): + pass + + model = build_model("f1_u0") + feature = next(f for f in model.features if getattr(f, "faults", None)) + fault = feature.faults[0] + old = fault.faultfunction + sub = Sub.__new__(Sub) + sub.__dict__.update(old.__dict__) + fault.faultfunction = sub + assert fault.faultfunction is sub + assert _native_faults.chain_for(feature) is None diff --git a/tests/fault_evaluation/test_restore_order.py b/tests/fault_evaluation/test_restore_order.py new file mode 100644 index 000000000..f6a2d09ad --- /dev/null +++ b/tests/fault_evaluation/test_restore_order.py @@ -0,0 +1,96 @@ +"""Tests for the restore order that a feature keeps between evaluations (FR-001, FR-002). + +``restore_order(faults, reverse=..., owner=...)`` gives the order in which faults restore +points. With an owner, it computes the order once for each state of the faults and keeps it. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest import mock + +import numpy as np +import pytest + +from LoopStructural import LoopStructuralConfig +from LoopStructural.utils import _fault_block +from LoopStructural.utils._fault_block import cutters_first, restore_order, with_cutters +from tests.fault_evaluation.golden import capture +from tests.fault_evaluation.models import build_model, sample_points + + +def _fake_fault(name, cutters=()): + """Make a fault-like object whose cutters are read from its builder.""" + builder = SimpleNamespace(builders=[SimpleNamespace(faults=list(cutters))]) + return SimpleNamespace(name=name, builder=builder, features=[]) + + +def _faulted_feature(model): + return next(f for f in model.features if getattr(f, "faults", None)) + + +def test_order_is_computed_once_for_one_state(): + model = build_model("cutting_faults") + feature = _faulted_feature(model) + points = sample_points("cutting_faults", 50) + feature.evaluate_value(points) + with mock.patch.object(_fault_block, "cutters_first", wraps=cutters_first) as spy: + feature.evaluate_value(points) + assert spy.call_count == 0 + + +def test_order_changes_when_a_cutter_is_added(): + other = _fake_fault("other") + fault = _fake_fault("fault") + owner = SimpleNamespace() + first = restore_order([fault], owner=owner) + assert first == [fault] + assert restore_order([fault], owner=owner) is first + fault.builder.builders[0].faults.append(other) + second = restore_order([fault], owner=owner) + assert second != first + assert second.index(other) < second.index(fault) + + +@pytest.mark.parametrize("name", ["cutting_faults", "f4_u3"]) +def test_cache_gives_identical_values(name, monkeypatch): + # The test checks the Python path bit for bit; the native path gives equal results within the tolerance only. + monkeypatch.setattr(LoopStructuralConfig, "native_faults", False) + model = build_model(name) + points = sample_points(name, 200, seed=1) + cached = capture(model, points) + original = restore_order + with mock.patch.object( + _fault_block, "restore_order", lambda *a, **k: original(*a, **{**k, "owner": None}) + ): + plain = capture(build_model(name), points) + assert cached.keys() == plain.keys() + for key in cached: + np.testing.assert_array_equal(cached[key], plain[key]) + + +def test_reverse_order_rule(): + a = _fake_fault("a") + b = _fake_fault("b", cutters=[a]) + c = _fake_fault("c") + faults = [b, c] + expected = cutters_first(with_cutters(faults)[::-1])[::-1] + assert restore_order(faults, reverse=True) == expected + assert restore_order(faults, reverse=True, owner=SimpleNamespace()) == expected + assert restore_order(faults) == cutters_first(with_cutters(faults)) + assert expected != restore_order(faults) + + +@pytest.mark.parametrize("name", ["cutting_faults", "f4_u3"]) +def test_shared_frame_restoration_gives_identical_values(name, monkeypatch): + # The test checks the Python path bit for bit; the native path gives equal results within the tolerance only. + monkeypatch.setattr(LoopStructuralConfig, "native_faults", False) + from LoopStructural.modelling.features.fault import _fault_segment + + points = sample_points(name, 200, seed=1) + shared = capture(build_model(name), points) + with mock.patch.object(_fault_segment, "_SHARE_CUT_FRAME_RESTORATION", False): + legacy = capture(build_model(name), points) + assert shared.keys() == legacy.keys() + for key in shared: + np.testing.assert_array_equal(shared[key], legacy[key])