diff --git a/specs/007-native-fault-kernel/research.md b/specs/007-native-fault-kernel/research.md new file mode 100644 index 00000000..f90dccb1 --- /dev/null +++ b/specs/007-native-fault-kernel/research.md @@ -0,0 +1,64 @@ +# Replace Euler fault steps with cached maps + +> **Note (2026-11-27).** This review was written on 2026-11-26, before the master fixes +> #427 to #429 removed the exponential cost of chains of cutting faults. After those fixes +> the cost is linear in the depth of a chain, so precomputed displacement maps are not part of +> spec 007 (see its "Out of scope"). The review is kept as background. + +The literature supports the plan: five separate fields (flow-map visualization, semi-Lagrangian CFD, diffeomorphic image registration, sharp-interface numerics and geological fault modelling) converge on storing the *integrated end-point displacement* on a regular grid, applying it by trilinear lookup, and composing maps rather than re-integrating. Once a fault's map is built, the step count stops being a runtime cost: the map can be integrated with RK4 or many sub-steps at build time, and the runtime error becomes the trilinear interpolation error, which is second order in cell size (halving the spacing cuts it about 4x) ([Hlawatsch et al. 2011](https://vcg.iwr.uni-heidelberg.de/static/publications/hlawatsch2011hlic.pdf)). For LoopStructural this replaces the current cost, which grows about 21x per level of a cutting-fault chain, with one lookup per fault per point, so a chain costs a linear sum. No published source builds per-fault, per-side displacement grids with a hanging-wall/footwall mask, and none measures fault-operator error against step count or grid spacing, so those parts of the design rest on transferred theory rather than precedent. The discontinuity is the main risk: a single interpolated map across the fault smears the slip over one to two cells, as sliding-organ registration shows ([Pace et al. 2011](https://people.csail.mit.edu/dfpace/assets/publications/slidingOrgansUsingAnisotropicDiffusive.pdf)). The XFEM and ghost-fluid literature gives the fix: store each side's field *extended smoothly* across the surface and pick the side with the sign of the exact fault level set at the query point. Restore and deform should each have their own map, and the stored round-trip residual serves as the accuracy check. + +## Ten Euler steps buy first-order accuracy at the highest cost + +The current operator in `FaultSegment.apply_to_points` (`LoopStructural/modelling/features/fault/_fault_segment.py`) takes `steps=10` explicit Euler steps. Each step re-evaluates the three frame coordinates and the gradient of the slip coordinate at the moved points. Because an older fault's frame was built in space restored by younger faults, every one of those evaluations goes back through the younger faults, which is where the growth per chain level comes from. The papers that define the operator say only that non-planar faults are restored "using Euler's method, where the displacement is applied iteratively using small linear steps". They give no step count and no error analysis ([Grose et al. 2021b](https://gmd.copernicus.org/preprints/gmd-2021-112/gmd-2021-112-manuscript-version4.pdf)), and the only published timing is about 8 minutes for a whole model, with no breakdown for the fault operator ([Grose et al. 2021a](https://gmd.copernicus.org/articles/14/3915/2021/)). The search found no published study of fault-operator cost for large cross-cutting networks, so the exponential nesting looks like an implementation issue nobody has written up. + +Ten Euler steps are also a poor accuracy buy. Forward Euler is first order. The semi-Lagrangian literature shows that one large step plus one correction is already second order. The MacCormack correction, applied to an ODE, is "identical to second order accurate Runge-Kutta". On a model problem, at the same step sizes, Euler error falls only from 6.6e-2 to 8.4e-3 (order 1.0), while MacCormack falls from 1.7e-2 to 1.8e-4 (order about 2.1) ([Selle et al. 2008](https://yingjie.math.gatech.edu/publications/SFKLR.pdf)). Atmospheric models compute departure points with a midpoint-rule trajectory solved by fixed-point iteration, where "two iterations are enough to obtain satisfactory (second order) accuracy". The iteration converges only if the time step times the maximum velocity shear is below 1, that is, if trajectories do not cross ([Diamantakis 2013](https://www.ecmwf.int/sites/default/files/elibrary/2014/9054-semi-lagrangian-technique-atmospheric-modelling-current-status-and-future-challenges.pdf); [CAPS CFD notes](https://twister.caps.ou.edu/CFD2023/Chapter6.pdf)). Applied to a point (my algebra, consistent with the Selle result), "Euler step, step back, correct by half the residual" reduces to Heun's method: x + (h/2)(v(x) + v(x + h·v(x))). Two or three Heun steps (4 to 6 field evaluations) would beat ten Euler steps (10 evaluations) wherever slip times the field's curvature is modest. Near fault tips and strongly curved surfaces the condition can fail, and there Stam's practice of sub-stepping "only in regions of high velocity gradients" is the precedent ([Stam 1999](https://cgweb.informatik.uni-freiburg.de/intern/seminar/gridFluids_StableFluids.pdf)). + +That analysis matters for two reasons even if the grid map goes ahead. Heun is a cheap fallback that cuts the current runtime cost by 2 to 5x with no new data structure. It is also the right integrator for *building* the map, although at build time cost is cheap enough that RK4 with many sub-steps is the better choice. + +## Precomputed maps trade integration error for O(h²) interpolation error + +Hierarchical line integration stores a "coordinate map" φ(x) at every node of a fixed-resolution grid. It builds longer maps by self-composition with trilinear lookups, so cost becomes logarithmic in integration length. The global error after n composition levels is bounded by roughly (c²M/2L)·e^{nL}, where c is the cell size, M the maximum second derivative of the map and L its Lipschitz constant. The error is therefore "second order in the cell size", and it concentrates where the flow stretches (high FTLE). The 95th-percentile endpoint errors on 2D test flows were 0.001 to 0.1% of the domain ([Hlawatsch et al. 2011](https://vcg.iwr.uni-heidelberg.de/static/publications/hlawatsch2011hlic.pdf)). The same paper makes two practical recommendations that carry over directly. First, store *relative* displacements (end minus start) rather than absolute positions, to avoid cancellation. Second, do the trilinear interpolation in software rather than with GPU texture hardware, which uses 9-bit weights. Storing displacement has a further benefit for faults: the zero-displacement region far from the fault is reproduced exactly. + +Registration gives the most concrete numbers. Scaling and squaring takes one Euler step x + v/2^K and composes the result with itself K times, so 2^K Euler steps cost only K grid compositions. In single precision the optimum is K of about 6 to 7 (64 to 128 equivalent steps). More squarings make the result worse, because resampling and floating-point error dominate ([Ashburner 2007](https://users.fmrib.ox.ac.uk/~jesper/papers/readgroup_071009/Ashburner07.pdf)). ITK chooses K automatically so that the first step is under 0.5 pixel: N = ceil(2 + 0.5·log2(max|v|²/spacing²)) ([ITK source](https://raw.githubusercontent.com/InsightSoftwareConsortium/ITK/master/Modules/Filtering/DisplacementField/include/itkExponentialDisplacementFieldImageFilter.hxx)). A benchmark of exponential algorithms found scaling and squaring the best trade-off, but with an *intrinsic lower bound in accuracy* that only grid oversampling raises ([Bossa, Zacur, Olmos 2008](https://mlanthology.org/cvprw/2008/bossa2008cvprw-algorithms)). The lesson for faults is that once a map exists, the grid spacing sets the accuracy, not the step count. + +Post hoc Lagrangian flow analysis is structurally the same as the fault proposal: end positions stored on a uniform grid, interpolated for new particles, and chained interval by interval. With the full basis it was "over fifteen times more accurate" than Eulerian advection, and it stayed more accurate at 1/16 of the storage. Its authors also report that one long trajectory is more accurate than a chain of short ones, because interpolation error accumulates over the chain ([Agranovsky et al. 2014](https://vis.cs.ucdavis.edu/vis2014papers/VIS_Conference/ldav/papers/agranovsky.pdf)). That favours one finely integrated map per fault over a stack of partial maps. + +LoopStructural applies each fault's map once, not 2^K times, so the exponential amplification term hardly applies. Each map contributes about (h²/8)·max|∂²d| of trilinear error (standard interpolation theory, not from these sources). That error is largest where the displacement profile varies fastest: at fault tips, in the far-field decay of D0, and on curved fault surfaces. Whether this beats the current scheme depends on the cell size relative to those length scales, and no source measures it for fault fields. A numerical comparison against a high-step-count reference is the first thing to run. + +## Compose by sequential lookup, not by regridding the chain + +There are two ways to compose maps along a cutting chain, and the literature points to one of them. + +| Option | Runtime cost per point | Resampling error | Discontinuity handling | +|---|---|---|---| +| Current: 10 Euler steps, nested restoration | ~21x per chain level (exponential in depth) | none (first-order integration error instead) | exact side test each step | +| A: apply per-fault maps in sequence (youngest first) | one trilinear lookup + one side test per fault (linear in chain length) | one interpolation per fault | exact side test per fault | +| B: pre-compose the whole chain into one grid | one lookup | n−1 extra resamplings | every younger fault's jump is baked into the older map and smeared | + +Composition on a grid means u_AB(x) = u_A(x) + u_B(x + u_A(x)), and every composition adds one resampling error. DARTEL notes that recursively composed quantities are "only an approximation because of the effect of iteratively resampling" ([Ashburner 2007](https://users.fmrib.ox.ac.uk/~jesper/papers/readgroup_071009/Ashburner07.pdf)). Option B has a worse problem for faults: the composed field is discontinuous across *every* fault in the chain, so a per-side representation no longer works. Option A keeps each map smooth on its own side and keeps the fault topology, which seismic "all faults at once" unfaulting gives up ([Grose et al. 2021b](https://gmd.copernicus.org/preprints/gmd-2021-112/gmd-2021-112-manuscript-version4.pdf)). Option A is also cheap enough that B's saving does not justify its error. + +Option A fits LoopStructural's coordinate convention, but only if each map lives in the right space. An older fault's frame is built in the space restored by its younger faults, and the code already supports evaluating it there without re-applying them (`restored_through`). The map for fault k should therefore be sampled on grid nodes in *its own frame's space* (restored through the younger faults). It is then queried with the point as it arrives from the younger faults' maps. Building each map costs one frame evaluation per node per integration sub-step, with no nested restoration. The total build cost becomes linear in the number of faults. One open point the literature cannot settle: the frame evaluation also depends on the `block` (which side of each younger fault). If that changes the map, a map key is (fault, own side, block of the younger faults). Only block combinations that actually occur in the model should be built, otherwise the count grows combinatorially. + +## The jump belongs in the side test, never in the interpolant + +Interpolating one field across a sliding interface fails in a well-documented way: "the opposing vectors near the boundary will be averaged and the motion at the interface will not be recovered" ([Pace et al. 2011](https://people.csail.mit.edu/dfpace/assets/publications/slidingOrgansUsingAnisotropicDiffusive.pdf)). Registration accepts a transition zone of 1 to 2 voxels and is only as accurate as the boundary segmentation ([Pace et al. 2013](https://people.csail.mit.edu/dfpace/assets/publications/slidingRegistration.pdf)). Piecewise-diffeomorphic registration keeps maps that are not smooth across the interface yet still almost always invertible ([Risser et al. 2013](https://portal.fis.tum.de/en/publications/piecewise-diffeomorphic-image-registration-application-to-the-mot/)). Precomputed fault fields can do better than either, because the fault surface is known exactly as the zero level set of the frame coordinate gx. + +XFEM puts faults and cracks on non-conforming meshes by adding a Heaviside function H times extra degrees of freedom to the nodes whose support the surface cuts. The side is taken from the sign of a level set, so the jump is exact. This has been applied directly to reservoir faults on structured and unstructured meshes ([Moës et al. 1999](https://research.dial.uclouvain.be/entities/publication/6b4f2ef5-581a-4106-986b-e110834db063); [Stolarska et al. 2001](https://hal.archives-ouvertes.fr/hal-01007079); [Prevost & Sukumar 2015](https://collaborate.princeton.edu/en/publications/multi-scale-x-fem-faults-simulations-for-reservoir-geomechanical-/)). The ghost fluid method does the same on fixed grids: each side gets extrapolated "ghost" values on the other side of the interface, so every stencil sees only one side's data ([Fedkiw et al. 1999](https://www.osti.gov/biblio/6369092)). PDE extrapolation fills those ghost values to constant, linear or quadratic order ([Aslam 2004](https://scholars.duke.edu/publication/1466580)). Extrapolating Cartesian derivatives keeps second- and third-order L∞ accuracy even at kinks and high curvature ([Bochkov & Gibou 2020](https://arxiv.org/abs/1912.09559)). + +Translated to the proposal, the stored field is u(x) = H(gx(x))·u_hw(x) + (1 − H(gx(x)))·u_fw(x). Here u_hw and u_fw are each extended across the fault, and H is evaluated from the exact gx at the query point, never interpolated. Three consequences follow, all inferred from these sources rather than measured. First, the extension must cover every node of every cell the fault cuts, which is one cell beyond the surface for trilinear lookup; two or three cells add a safety margin. Second, a one-sided field stored with its cutoff (for example D0 = 0 for f0 < 0) will smear within one cell. LoopStructural already has the right extension: `block_displacement` evaluates the smooth continuation of a side's profile across the fault, so the extended values come analytically, with no PDE. Third, the residual error is in *where the jump sits*. If gx itself came from a coarse interpolated copy, points in a thin sliver would get the wrong side and an error the size of the full slip. The side test should use the model's own gx. + +In LoopStructural the footwall does not move, so u_fw = 0 and only the hanging-wall field needs storing, as in u = H(gx)·u_hw. That halves memory compared with two full grids. The semi-Lagrangian limiter literature adds a useful rule: correction schemes "automatically revert to the first order accurate scheme when the upwind and downwind building blocks pull data from non-commensurate regions" ([Selle et al. 2008](https://yingjie.math.gatech.edu/publications/SFKLR.pdf)). The fault analogue: if a point's restored position lands on the other side of a fault it should not cross, or in a different block, flag it and fall back to direct integration. None of the semi-Lagrangian sources treats a discontinuous *velocity* field, so the theory behind those schemes only holds within one side. + +## Build restore and deform as separate maps, and check the round trip + +Every field surveyed obtains the inverse by integrating the negated field and storing a second map, not by inverting the forward map. Hierarchical integration keeps separate forward and backward hierarchies ([Hlawatsch et al. 2011](https://vcg.iwr.uni-heidelberg.de/static/publications/hlawatsch2011hlic.pdf)), and ITK's `ComputeInverse` simply divides the field by −2^N ([ITK source](https://raw.githubusercontent.com/InsightSoftwareConsortium/ITK/master/Modules/Filtering/DisplacementField/include/itkExponentialDisplacementFieldImageFilter.hxx)). The accuracy gap is large. With K = 6, exp(v)∘exp(−v) deviated from identity by 0.023 voxel RMS and at most 0.40 voxel. The naive inverse that subtracts the displacement gave 0.15 to 0.17 voxel RMS and up to 4.0 voxels, about 7x worse in RMS and 10x worse at the maximum ([Ashburner 2007](https://users.fmrib.ox.ac.uk/~jesper/papers/readgroup_071009/Ashburner07.pdf)). Negating a stored displacement "is oversimplified and can cause large errors for large deformations or deformations that are composites of several deformations" ([Chen et al. 2008](https://scholars.uky.edu/en/publications/a-simple-fixed-point-approach-to-invert-a-deformation-field/)). + +There are two sound routes to the inverse. The first integrates the negated field (the current `reverse=True` path) into its own grid, at the same cost as the forward map. The second inverts the stored forward map with the Chen fixed-point iteration v_n(x) = −u(x + v_{n−1}(x)), which typically converges in under ten iterations, each one a trilinear lookup ([Chen et al. 2008](https://scholars.uky.edu/en/publications/a-simple-fixed-point-approach-to-invert-a-deformation-field/)). ITK's damped version stops at 0.1 voxel maximum or 0.001 voxel mean error, within 20 iterations ([ITK InvertDisplacementFieldImageFilter](https://raw.githubusercontent.com/InsightSoftwareConsortium/ITK/master/Modules/Filtering/DisplacementField/include/itkInvertDisplacementFieldImageFilter.hxx)). The two routes answer different questions. The negated-field map is the better approximation of the true continuous inverse. The fixed-point inverse is consistent with the *discrete* forward map, which matters when a model restores data, interpolates, and then deforms again, as in the "unfault-and-refault" workflow ([Godefroy et al. 2017, via Grose et al. 2021b](https://gmd.copernicus.org/preprints/gmd-2021-112/gmd-2021-112-manuscript-version4.pdf)). For fault slip, which is close to a rigid translation along the surface, the two should agree closely. Brunton and Rowley's bidirectional map composition fails mainly where the map strongly compresses or stretches ([Brunton & Rowley 2010](https://collaborate.princeton.edu/en/publications/fast-computation-of-finite-time-lyapunov-exponent-fields-for-unst/)), which mostly excludes fault interiors but not tips. For inverses, the side test runs on the deformed-space level set, so the inverse map needs its own side mask in deformed coordinates. + +The round trip is also the cheapest error indicator. The UFLOW check traces forward, then back, and compares ([McLoughlin et al. 2010](https://people.cs.nott.ac.uk/pszrsl/research/star/geometric/mcloughlin10over.pdf)). Registration reports inverse-consistency error as the RMS and maximum of Φ∘Φ⁻¹ − identity. Jacobians compose by the chain rule, so a non-positive determinant flags folding ([Ashburner 2007](https://users.fmrib.ox.ac.uk/~jesper/papers/readgroup_071009/Ashburner07.pdf)). + +## Conclusion + +The literature changes the question from "how many Euler steps?" to "what grid spacing, and where?". Once maps are cached, integration accuracy is nearly free and interpolation accuracy is what is bought. That spending belongs near fault tips, in the far-field decay and on curved surfaces, not at the fault plane, because an exact side test removes the jump from the interpolant altogether. The design that follows is this. + +Store one map per fault, as displacement rather than position. Sample it in that fault's own frame space (restored through the younger faults). Build it at load time with RK4 or Heun sub-steps, using `block_displacement` to fill hanging-wall values smoothly at least two cells into the footwall. Keep the footwall implicit as zero. Choose the spacing so that the profile's second derivatives are resolved, with the ITK half-cell rule on the build sub-steps as a floor. At query time, apply the maps youngest first, one trilinear lookup each, gated by H of the exact gx. Never pre-compose a chain onto one grid. Build the restore map by integrating the negated field, and keep or derive a fixed-point-refined inverse wherever restore-then-deform consistency matters. Store the max and RMS round-trip residual and the minimum Jacobian determinant with each map. Fall back to direct Heun integration for points that cross blocks, leave the grid, or sit where the residual exceeds tolerance, using a border flag in the style of Hlawatsch for points that leave the domain. One gap must be closed before committing: no source quantifies this error for fault-like fields. A test of grid spacing against a 1000-step reference on a curved, tip-bounded fault is the first experiment, and it also gives the default spacing. diff --git a/specs/007-native-fault-kernel/spec.md b/specs/007-native-fault-kernel/spec.md new file mode 100644 index 00000000..7a10c8bc --- /dev/null +++ b/specs/007-native-fault-kernel/spec.md @@ -0,0 +1,376 @@ +# Feature spec: Native fault application + +**Feature**: `007-native-fault-kernel` | **Created**: 2026-11-27 | **Status**: Draft + +**Input**: Restoring points through the faults of a feature takes most of the +evaluation time of a faulted model. A Rust proof of concept restored points +6.5 to 16 times faster on one thread and 60 to 150 times faster on 20 threads. +The user wants a native fault application that LoopStructural uses when it is +available, with the Python code as the reference and the fallback. + + + +## Context + +- To evaluate a faulted feature, LoopStructural moves each point back through + the faults of the feature ("restores" the point), and then evaluates the + interpolated field at the restored point. Each fault moves a point in steps + (10 by default) along the gradient of its fault frame. +- After spec 003 and the fixes of master #424, #425, #427, #428 and #429, each + fault is applied once for each batch of points in one evaluation call, also + in networks of cutting faults. The remaining cost is the fault application + itself, in Python: + - About 7 µs for each point and fault in the golden models. + - About 40 ms of fixed cost for each fault frame that is cut by younger + faults, for each call. Most of it is Python work that finds the restore + order of the chain of cutting faults again at each call. + - A model with 94 faults (54 faults that do not touch other faults, 40 + cutting faults, chains of cuts up to 20 faults deep) evaluates 5000 points + in 2.1 s. The 40 cutting faults use 1.7 s of this time. +- A proof of concept (outside the repository, 2026-11-26) wrapped an existing + Rust port of the fault application for Python, and read the model from + exported files. Against the + Python restoration of spec 003, at 10 000 points: + - 6.5 to 11 times faster on one thread, 64 to 84 times faster on 20 threads, + for the golden models with 1 to 4 faults. + - 16 times (one thread) and 149 times (20 threads) faster for a model with + 12 faults and a chain of cuts; 58 and 505 times faster at 1000 points, + because the Python path has a fixed cost of about 50 ms for each call + on this model, which dominates a batch of 1000 points. + - The restored points differ from the Python path by up to 5.4e-5 m in a + model with a 1 km box (`f4_u0`) and 1.9e-4 m in a model with a 10 km box + (displacements 40 to 120 m). This does not pass the golden tolerance + (1e-8 × the box size: 1e-5 m and 1e-4 m). The crate was written for an + older version of the fault code; the plan must find the cause (C-007). + The NaN points are the same. +- LoopStructural already ships optional native code for its solvers (an + optional extra of the interpolation package). The plan chooses where the + native path lives. +- Dependencies: spec 003 (the golden tests, the benchmarks and the evaluation + scope) must be merged before the plan of this spec starts. The fixes of + master #425, #427, #428 and #429 are merged. +- Words used in this spec: + - **restoration**: moving points back through the faults of a feature, in + the restore order (each fault that cuts another fault first, and the whole + chain of cutting faults), as the Python path does today. + - **native path**: the compiled implementation of this spec. + - **Python path**: the present implementation. It stays the reference. + - **supported feature**: a feature whose faults and field the native path + can evaluate (FR-008). Any other feature uses the Python path. + +## User scenarios and tests + +### User story 1: The Python path finds the restore order once (priority: P1) + +A developer evaluates a model with cutting faults. The Python path computes +the restore order of the chain of cutting faults of a feature once, and not +at each call, so the fixed cost of a cut fault frame falls from about 40 ms +to at most 10 ms for each call. + +**Why this priority**: it helps every user, also users without the native +package, and it makes the Python reference fair to compare with. It has no +native code, so it is the first stage. + +**Independent test**: evaluate the 94-fault model at 500 points. The time of +a cutting fault falls, and the results are the same bits as before. + +**Acceptance scenarios**: + +1. **Given** the 94-fault model, **when** `evaluate_model` runs at 500 + points, **then** the mean time of a cutting fault is at most 10 ms + (today about 40 ms), and the model ids and values are bit-identical to + the results before this story. +2. **Given** a fault whose cutting faults change after the first evaluation, + **when** the feature is evaluated again, **then** the restore order uses + the new cutting faults. + +### User story 2: Restore points natively (priority: P1) + +A user evaluates a faulted model with the native package installed. The +restoration of the points of a supported feature runs in native code. + +**Why this priority**: the restoration is about 90 % of the evaluation time +of a faulted model. + +**Independent test**: restore the points of each golden model with the +native path and with the Python path, and compare. + +**Acceptance scenarios**: + +1. **Given** a golden model and its reference points, **when** the points + are restored with the native path, **then** the restored points agree + with the Python path within the golden tolerances (spec 003 FR-004), and + the NaN points are the same. +2. **Given** a feature with a block (a side of a fault forced), reverse + movement, or points that a younger fault already restored + (`restored_through`), **when** the native path restores the points, + **then** the result agrees with the Python path as in scenario 1. + +### User story 3: Evaluate values and gradients natively (priority: P2) + +A user evaluates feature values and gradients (`evaluate_value`, +`evaluate_gradient`, `evaluate_model`, `evaluate_model_gradient`) with the +native package installed. The field values and the gradients of a supported +feature are computed natively. + +**Why this priority**: after story 2, the field evaluation and the gradient +(which restores the corners of a tetrahedron for each point and refines it +near faults) are the next largest costs. + +**Independent test**: run the golden tests with the native path on and with +it off. + +**Acceptance scenarios**: + +1. **Given** each golden model, **when** the golden tests run with the + native path on, **then** they pass with the golden tolerances, the model + ids are the same except at a unit boundary, and the NaN points are the + same. +2. **Given** a point near a fault where the gradient tetrahedron still + crosses the fault after the refinement, **when** the gradient is + evaluated natively, **then** it is NaN, as on the Python path. + +### User story 4: On by default, with a way out (priority: P2) + +A user installs LoopStructural with the native package (for example through +the QGIS plugin). The native path is used for supported features without any +change to the user's code. A user can turn it off. + +**Why this priority**: without it, few users get the speed-up; with a switch +and a fallback, a problem in the native path never blocks a user. + +**Independent test**: run the full test suite with the native path on, off, +and with the native package not installed. + +**Acceptance scenarios**: + +1. **Given** the native package is installed, **when** a model is evaluated, + **then** the native path is used for each supported feature. +2. **Given** the configuration setting or the environment variable turns the + native path off, or the native package is not installed, **when** a model + is evaluated, **then** the Python path is used, with no error and the same + results as today. +3. **Given** the setting turns the native path on and the variable turns it + off, **when** a model is evaluated, **then** the native path is used (the + setting wins). +4. **Given** the native package is installed but its version does not match, + **when** two models are evaluated in one session, **then** the Python path + is used and exactly one warning names both versions. +5. **Given** a clean computer with Windows, macOS or Linux, **when** a user + installs LoopStructural with the native extra from the package index, + **then** a prebuilt native package installs and the native path is used. + +### User story 5: The native path is safe to use (priority: P2) + +A developer relies on the native path in an application (for example a plugin +that evaluates in background threads). The native path keeps the public API, +falls back where it must, never uses stale data, lets other threads run, and +uses the number of threads that the developer sets. + +**Why this priority**: the speed-up must not cost correctness or control. + +**Independent test**: the scenarios below, with the native path on. + +**Acceptance scenarios**: + +1. **Given** the public classes and functions of `GeologicalModel` and of the + features, **when** their signatures are compared before and after this + spec, **then** they are the same. +2. **Given** a feature with a displacement profile given as a Python + function, **when** it is evaluated, **then** the Python path is used and + the result is the same as with the native path off. +3. **Given** a model evaluated once, **when** it is evaluated again with no + change, **then** no file is read or written, and the second call does not + copy the model data again (its extra memory is at most the memory of the + points and their results). +4. **Given** a model evaluated once with the native path, **when** a fault + displacement changes and the model is evaluated again, **then** the result + equals the Python path result for the new state. +5. **Given** a native call on 10 million points in one thread, **when** a + second Python thread runs at the same time, **then** the second thread + makes progress during the native call. +6. **Given** two threads that evaluate one model at the same time, **when** + both finish, **then** each result equals the result of that thread alone. +7. **Given** the thread count setting is 1, **when** a model is evaluated, + **then** the native path uses one thread. + +### Edge cases + +- A feature has one fault or field that the native path does not support: + the whole feature uses the Python path, so that the restore order is the + same for all its faults. +- The model changes after a native evaluation (a fault is rebuilt, a + displacement changes, data change): the next evaluation uses the new model + state, never a stale copy. +- Points with a NaN coordinate, points outside the grid of a fault frame or of + the field, and an empty point array: the same results as the Python path. +- A point on a fault that cuts a fault frame (the frame has no single + gradient there): the step direction follows master #425. +- Two threads evaluate the same model at the same time (the QGIS plugin + evaluates in background threads): each gets the result it gets alone. +- A very large batch (10 million points): the extra memory stays within + spec 003 FR-010; the native path does not copy the model data for each + call. +- A long native call: it does not hold the Python global interpreter lock, + so other Python threads can run. +- The user interrupts a long native call (Ctrl-C): the interrupt reaches + Python at the latest when the native call ends, and the model state does + not change. +- The native call fails in the middle of a batch (for example an internal + error): the error reaches Python as an exception with a message, no partial + result is returned, and the model state does not change. + +## Requirements + +### Functional requirements + +- **FR-001** (story 1): The Python path MUST compute the restore order of the + faults of a feature (each cutting fault first, and the whole chain of + cutting faults) at most once for each state of the faults, not at each + evaluation call. +- **FR-002** (story 1): When a fault, its cutting faults or its build state + change, the next restoration MUST use the new restore order. +- **FR-003** (story 2): The native path MUST restore points through the + faults of a supported feature with the semantics of the Python path: the + restore order, the faults that the points were already restored through, + the block sides and the block extension, reverse movement, the number of + steps, the NaN rules (master #413) and the step direction on a cutting + fault (master #425). +- **FR-004** (story 3): The native path MUST evaluate the value and the + gradient of a supported feature at restored points, with the gradient + method of the Python path (a regular tetrahedron for each point, refined + only where it crosses a fault, at most 10 times; NaN if it still crosses, + master #421). +- **FR-005** (stories 2 and 3): Native values, gradients and restored points + MUST agree with the Python path within the golden tolerance of spec 003 + (1e-8 × the size of the model box, C-007). +- **FR-005a**: Native results MUST have the same NaN points as the Python + path. +- **FR-005b**: Native model ids MUST equal the Python model ids, except at + points within the value tolerance of a unit boundary. +- **FR-005c**: The test report MUST record the largest native difference. +- **FR-006** (story 4): The native path MUST be used automatically for + supported features when the native package is installed and its version + matches. +- **FR-006b** (story 4): A LoopStructural configuration setting and an + environment variable MUST each be able to turn the native path off; the + setting wins over the variable (C-008). +- **FR-006c** (story 4): With the native path off or without the package, the + Python path MUST give the same results as before this spec. +- **FR-006a** (story 4): When the native package is installed but its version + does not match, LoopStructural MUST use the Python path and MUST log one + warning in a session that names both versions (C-009). +- **FR-007** (story 5): The public `GeologicalModel` and feature API MUST NOT + change (constitution). The native path is an internal implementation. +- **FR-008** (story 5): A feature is supported when its fault frames and its field use + structured grids with a uniform cell lookup (an affine local frame is + allowed), and each of its fault displacement profiles is one of the + built-in profile types of LoopStructural (C-010). Its regions (for example + unconformities) stay on the Python path, on features that the native path + evaluates. A feature with a displacement profile given as a Python + function, or with any other unsupported part, MUST use the Python path. +- **FR-009** (story 5): The native path MUST read the model data in memory (grids, + node values, frames, profiles, constants). It MUST NOT write or read + files, and it MUST NOT copy the model data for each evaluation call. +- **FR-010** (story 5): The native path MUST NOT keep data from a model state after + that state changes (FR-002 applies to native data too). +- **FR-011** (story 5): The native path MUST release the Python global + interpreter lock during native work. +- **FR-011a** (story 5): The native path MUST give the same results when two + threads evaluate one model at the same time. +- **FR-012** (story 5): The number of threads of the native path MUST be configurable. + The default is all available cores. +- **FR-013**: The test suite MUST run with the native path on and with it + off, and the golden tests and the spec 003 benchmarks MUST be able to + select either path. +- **FR-014** (story 4): The release process MUST build and publish prebuilt + native packages for Windows, macOS and Linux (64-bit x86 on each, and 64-bit + ARM on macOS), for the Python versions that LoopStructural supports + (C-011). +- **FR-015**: `ROADMAP.md` MUST record the decision to add the native path, + and each stage of this spec when it completes (constitution). + +## Success criteria + +- **SC-001** (story 1): For the 94-fault model at 500 points, the mean time + of a cutting fault in one evaluation is at most 10 ms (baseline about + 40 ms), with bit-identical results. +- **SC-002** (story 2): For each of the golden models `f1_u0`, `f4_u0`, + `f4_u3`, `cutting_faults` and `plugin` at 10 000 points, the native + restoration on one thread takes at most 20 % of the time of the Python + path (the proof of concept: 9 % to 15 %). Measured on the spec 003 T030 + computer (Intel i7-12700H, 20 threads, Linux). +- **SC-003** (story 2): For the same models and computer, with all 20 + threads, the native restoration at 10 000 points takes at most 3 % of the + time of the Python path (the proof of concept: 1.2 % to 1.6 %). +- **SC-004** (stories 2 and 3): For the 94-fault model, `evaluate_model` at + 5000 points takes at most 0.5 s with the native path (baseline 2.1 s with + the Python path of spec 003). +- **SC-005** (story 3): All golden tests pass with the native path on + (FR-005). +- **SC-006** (story 4): The full test suite passes with the native path on, + with it off, and without the native package. +- **SC-008** (story 4): A prebuilt native package installs on a clean + computer for each platform of FR-014, and the golden tests pass there with + the native path on. +- **SC-007**: For 10 million points, the extra memory of the native path is + within spec 003 FR-010. + +## Out of scope + +- Precomputed displacement maps on grids (the literature review of + 2026-11-26, `research.md` in this folder). After the + ordering fixes the cost is linear in the depth of a chain of cuts, so they + are not needed now. +- A change of the fault displacement method (for example fewer steps, Heun + steps, or a single step with a correction): the native path implements the + present method. A new method needs its own spec. +- Native interpolation (the solvers), native region masks, and supports other + than structured grids. +- The QGIS plugin and how it installs the native package (separate + repository). This spec publishes the prebuilt packages (FR-014); the plugin + decides how to use them. +- Fault displacement profiles given as Python functions: they use the Python + path. + +## Clarifications + +Answered on 2026-11-27. + +- **C-001 Exactness.** Must the native results be bit-identical to the + Python path? **Answer**: no. They must pass the golden tests with the + tolerances of spec 003 FR-004, with the same NaN points and model ids + (except at a unit boundary). The proof of concept differs by at most + 1.9e-4 m. +- **C-002 Default.** Is the native path on by default? **Answer**: yes, when + the native package is installed and its version matches, with a switch to + turn it off. +- **C-003 Scope of the first version.** **Answer**: restoration, feature + values and gradients (stories 2 and 3). Masks and regions stay in Python + and use features that the native path evaluates. +- **C-004 The Python bookkeeping.** Is the per-call computation of the + restore order part of this spec? **Answer**: yes, as stage 1 (story 1). +- **C-005 Fallback unit (default; the maintainer can change it).** If one + fault of a feature is not supported, the whole feature uses the Python + path, so that all its faults use one restore order. +- **C-006 Threads (default; the maintainer can change it).** The number of + threads is configurable; the default is all available cores. +- **C-007 Native tolerance (from the review).** The proof of concept differs + by more than the golden tolerance. Must the native path meet the golden + tolerance of spec 003, or a looser tolerance of its own? **Answer**: spec 003 FR-004 + (1e-8 × the box size). The plan must find and remove the difference of the + proof of concept. +- **C-008 The switch.** How does a user turn the native path off? + **Answer**: with a LoopStructural configuration setting or an environment + variable. The setting wins over the variable. +- **C-009 Version mismatch.** **Answer**: use the Python path and log one + warning in a session that names both versions. +- **C-010 Supported profiles.** **Answer**: all built-in fault displacement + profile types of LoopStructural (including the default profile). A + profile given as a Python function uses the Python path. +- **C-011 Prebuilt packages.** Are native packages for Windows, macOS and + Linux part of this spec? **Answer**: yes. Most QGIS users are on Windows, + and story 4 has value only with prebuilt packages. diff --git a/specs/README.md b/specs/README.md index d643bebd..1096b7e0 100644 --- a/specs/README.md +++ b/specs/README.md @@ -11,6 +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. | ## Cascade of 005