Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
97 commits
Select commit Hold shift + click to select a range
21febf0
docs(spec): add spec 003, faster evaluation of faulted models
lachlangrose Nov 1, 2026
546bb43
docs(spec): record the answers to the clarifications of spec 003
lachlangrose Nov 1, 2026
eb7a780
docs(spec): add the plugin model as it is as a golden model of spec 003
lachlangrose Nov 1, 2026
d22db4f
docs(spec): prepare fault evaluation implementation
lachlangrose Nov 1, 2026
c577541
test(fault-evaluation): define golden model fixture contracts
lachlangrose Nov 1, 2026
667ca33
test(fault-evaluation): check actual fold frame dependencies
lachlangrose Nov 1, 2026
9aaaed4
docs(spec): add faulted gradient prerequisite
lachlangrose Nov 1, 2026
b22517f
test(fault-evaluation): reproduce gradient output shape failure
lachlangrose Nov 1, 2026
e9b7229
fix(features): preserve gradient output during fault refinement
lachlangrose Nov 1, 2026
21a3490
test(fault-evaluation): require meaningful fixture classifications
lachlangrose Nov 1, 2026
0a7930e
test(fault-evaluation): freeze solved model fixtures
lachlangrose Nov 1, 2026
9d0c066
test(fault-evaluation): define golden reference tool contracts
lachlangrose Nov 1, 2026
caaba54
test(fault-evaluation): add immutable golden capture tools
lachlangrose Nov 1, 2026
cac2a49
fix(fault-evaluation): sample boundaries without gradient refinement
lachlangrose Nov 1, 2026
09be87b
fix(fault-evaluation): capture legacy plugin groups and boundaries
lachlangrose Nov 1, 2026
ddc333e
test(fault-evaluation): record readable reference statistics
lachlangrose Nov 1, 2026
2697c1d
test(fault-evaluation): freeze 21 golden model references
lachlangrose Nov 2, 2026
7a8c0ab
test(fault-evaluation): cover missing surface list diagnostics
lachlangrose Nov 2, 2026
c66109c
test(fault-evaluation): verify complete legacy golden replay
lachlangrose Nov 2, 2026
b4b8562
docs(fault-evaluation): clarify golden harness validation
lachlangrose Nov 2, 2026
75c0684
test(fault-evaluation): define benchmark runner contracts
lachlangrose Nov 2, 2026
7393279
chore(dev-tools): install shared skills and agents
lachlangrose Nov 2, 2026
a188e03
feat(fault-evaluation): add benchmark runner and comparison contract …
lachlangrose Nov 2, 2026
9f72830
feat(fault-evaluation): add benchmark result comparison
lachlangrose Nov 2, 2026
bfd22f3
fix(fault-evaluation): correct review findings of wave 11
lachlangrose Nov 2, 2026
88aa2ff
test(fault-evaluation): define acceptance reporting contract
lachlangrose Nov 2, 2026
9610f6a
fix(fault-evaluation): add progress output and resume to the benchmar…
lachlangrose Nov 2, 2026
290edf3
fix(fault-evaluation): correct review findings of the runner resume
lachlangrose Nov 2, 2026
2b9e143
docs(spec): add standard benchmark suite to 003-fault-evaluation-perf…
lachlangrose Nov 2, 2026
bc14daa
test(fault-evaluation): define standard suite selection contract
lachlangrose Nov 2, 2026
77bc045
feat(fault-evaluation): add standard benchmark suite and suite option
lachlangrose Nov 2, 2026
4d83d86
fix(fault-evaluation): correct review findings of wave 13
lachlangrose Nov 2, 2026
c9577a9
feat(fault-evaluation): add acceptance check and short-case repeat tests
lachlangrose Nov 2, 2026
88cb819
fix(fault-evaluation): correct review findings of wave 14
lachlangrose Nov 2, 2026
617cfea
feat(fault-evaluation): repeat short timing cases with more rounds
lachlangrose Nov 2, 2026
23f6bb7
docs(fault-evaluation): record the baseline of the standard benchmark…
lachlangrose Nov 2, 2026
cd27038
docs(fault-evaluation): correct the rounds and count statements in th…
lachlangrose Nov 2, 2026
ca403b0
test(fault-evaluation): define cache storage and grid lookup contracts
lachlangrose Nov 2, 2026
3ee1cfa
fix(fault-evaluation): correct review findings of wave 17
lachlangrose Nov 2, 2026
61588e4
fix(fault-evaluation): accept any exception in the failed-put cache t…
lachlangrose Nov 2, 2026
39e7122
feat(fault-evaluation): add restoration cache storage and single-look…
lachlangrose Nov 2, 2026
3828957
test(fault-evaluation): define one-call restoration sharing contract
lachlangrose Nov 2, 2026
612fc87
fix(fault-evaluation): correct review findings of wave 19
lachlangrose Nov 2, 2026
259b871
fix(fault-evaluation): remove an assertion that cannot hold in the re…
lachlangrose Nov 2, 2026
f695823
feat(modelling): share fault restorations inside one evaluation call
lachlangrose Nov 2, 2026
e3f4ef7
test(fault-evaluation): define cache invalidation and fingerprint con…
lachlangrose Nov 2, 2026
69bc399
test(fault-evaluation): do not require a stable revision for same-val…
lachlangrose Nov 3, 2026
b0ba48e
feat(modelling): add evaluation revision hooks and dependency fingerp…
lachlangrose Nov 3, 2026
d8759ba
fix(fault-evaluation): hash a root feature in full when a cycle retur…
lachlangrose Nov 3, 2026
ec0283e
test(fault-evaluation): define cross-call restoration reuse and cache…
lachlangrose Nov 3, 2026
9e8c703
fix(fault-evaluation): compute references before warming the cache in…
lachlangrose Nov 3, 2026
823a1d6
feat(modelling): reuse fault restorations between evaluation calls
lachlangrose Nov 3, 2026
625149b
test(fault-evaluation): define gradient sharing, concurrency, memory …
lachlangrose Nov 3, 2026
ba420cb
fix(fault-evaluation): relax two wave 25 tests that exceeded the plan
lachlangrose Nov 3, 2026
646c158
feat(modelling): share equal gradient batches and fault frame grid lo…
lachlangrose Nov 3, 2026
c8e3f9f
feat(modelling): serialise outer evaluations per model and bound the …
lachlangrose Nov 3, 2026
30a7c8e
docs(spec): mark T030 as failed after the first acceptance measurement
lachlangrose Nov 3, 2026
2b4b281
docs(spec): record the T030 acceptance failure and the cache design d…
lachlangrose Nov 3, 2026
f656c38
lachlangrose Nov 3, 2026
21616db
docs(spec): add D4a tasks for 003-fault-evaluation-performance
lachlangrose Nov 3, 2026
89f797d
docs(spec): add the cache pickle defect to T040 and T041
lachlangrose Nov 3, 2026
8e2a0f1
docs(spec): split the failed T030 results by cause (T043)
lachlangrose Nov 3, 2026
a1989c4
docs(spec): apply the spec 005 cascade to 003-fault-evaluation-perfor…
lachlangrose Nov 3, 2026
a02a413
test(fault-evaluation): add the fault-set cache key tests (T040)
lachlangrose Nov 3, 2026
7d865f7
perf(features): key stored restorations on the ordered fault set (T041)
lachlangrose Nov 3, 2026
598ef21
docs(spec): record the wave 29 review of 003
lachlangrose Nov 3, 2026
3ef8cb1
docs(spec): record the D4a profile of 003 and the failed key-time gat…
lachlangrose Nov 3, 2026
c4ea58e
docs(spec): record the T042 commit in the run state of 003
lachlangrose Nov 3, 2026
465688e
docs(spec): add the D4b frame digest tasks to 003
lachlangrose Nov 3, 2026
c1250ab
test(fault-evaluation): add the D4b frame digest tests (T044)
lachlangrose Nov 4, 2026
e492ac7
perf(features): read a small DataFrame with one call in the frame dig…
lachlangrose Nov 4, 2026
45980ad
docs(spec): record the wave 31 review of 003
lachlangrose Nov 4, 2026
31e056f
docs(spec): record the second D4a profile of 003; all gates pass (T042)
lachlangrose Nov 4, 2026
b59cf1e
docs(spec): record the T042 commit in the run state of 003
lachlangrose Nov 4, 2026
d4157a3
docs(spec): add plan and S1 tasks for 005-coordinate-frame-correctness
lachlangrose Nov 4, 2026
91e07a6
chore: remove the dev-toolkit files from the PR branch of 003
lachlangrose Nov 4, 2026
894042c
docs(spec): remove the cache between calls from 003 and change SC-006…
lachlangrose Nov 18, 2026
a90f7cb
docs(spec): carry 003-fault-evaluation-performance changes into spec 005
lachlangrose Nov 18, 2026
fe2ee9f
docs(spec): add the reduced-scope tasks T046-T051 to 003
lachlangrose Nov 18, 2026
12a7385
merge: merge master into the 003 branch and move the value lookup (T046)
lachlangrose Nov 18, 2026
8caf50d
test(fault-evaluation): change the tests for no cache and the shorter…
lachlangrose Nov 18, 2026
cf7af16
fix(fault-evaluation): correct review findings of wave 33
lachlangrose Nov 18, 2026
28d88a7
perf(features): remove the restoration cache between calls and the mo…
lachlangrose Nov 18, 2026
54d106f
test(fault-evaluation): correct the SC-006 allowance test of T049
lachlangrose Nov 18, 2026
15d095f
perf(benchmarks): make the standard suite shorter and apply the new a…
lachlangrose Nov 18, 2026
1991682
fix(benchmarks): correct review findings of wave 35
lachlangrose Nov 18, 2026
3865c80
docs(spec): record the wave 35 review of 003
lachlangrose Nov 18, 2026
808b491
docs(spec): measure the SC-003 count and SC-004 on one evaluate_model…
lachlangrose Nov 18, 2026
f446cbf
docs(spec): record the third D4a profile of 003 on the merged tree (T…
lachlangrose Nov 18, 2026
d0ffb09
test(fault-evaluation): test SC-003 and SC-004 on one evaluate_model …
lachlangrose Nov 18, 2026
c692fbc
perf(benchmarks): measure the SC-003 count and SC-004 on one evaluate…
lachlangrose Nov 18, 2026
b6ff1a8
docs(spec): record the wave 37 review of 003
lachlangrose Nov 18, 2026
dd71315
docs(spec): park the T030 acceptance run of 003 until a quiet compute…
lachlangrose Nov 18, 2026
b64c1e4
merge: bring the spec branch of 003 into the PR branch
lachlangrose Nov 18, 2026
3d4bf9d
merge: bring master into feat/003-fault-evaluation-performance
lachlangrose Nov 22, 2026
299b7be
test: update fault-evaluation tests for the spec 005 changes from master
lachlangrose Nov 22, 2026
6c2a385
feat: add fault snapshot exporter, reference data and agent brief
lachlangrose Nov 23, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 48 additions & 37 deletions LoopStructural/modelling/core/geological_model.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Main entry point for creating a geological model
"""

from __future__ import annotations

import warnings
Expand All @@ -26,6 +27,7 @@
all_heading,
gradient_vec_names,
)
from ..features._evaluation import evaluation_scope
from ..features._feature_converters import (
add_fold_to_feature as _add_fold_to_feature,
)
Expand Down Expand Up @@ -325,13 +327,17 @@ def from_processor(cls, processor):
logger.warning(f"Cannot add splay {edge[1]} or {edge[0]} are not in the model")
continue
splay = False
if "angle" in properties and float(properties["angle"]) < 30 and (
"dip_dir" not in processor.stratigraphic_column["faults"][edge[0]]
or np.abs(
processor.stratigraphic_column["faults"][edge[0]]["dip_dir"]
- processor.stratigraphic_column["faults"][edge[1]]["dip_dir"]
if (
"angle" in properties
and float(properties["angle"]) < 30
and (
"dip_dir" not in processor.stratigraphic_column["faults"][edge[0]]
or np.abs(
processor.stratigraphic_column["faults"][edge[0]]["dip_dir"]
- processor.stratigraphic_column["faults"][edge[1]]["dip_dir"]
)
< 90
)
< 90
):
# splay
region = model[edge[1]].builder.add_splay(model[edge[0]])
Expand Down Expand Up @@ -677,12 +683,10 @@ def set_stratigraphic_column(self, stratigraphic_column, cmap="tab20"):
min_val = stratigraphic_column[g][u]["min"]
max_val = stratigraphic_column[g][u].get("max", None)
thickness = max_val - min_val if max_val is not None else None
logger.info(
f"""
logger.info(f"""
model.stratigraphic_column.add_unit({u},
colour={stratigraphic_column[g][u].get("colour", None)},
thickness={thickness})"""
)
thickness={thickness})""")
self.stratigraphic_column.add_unit(
u,
colour=stratigraphic_column[g][u].get("colour", None),
Expand Down Expand Up @@ -1284,15 +1288,17 @@ def evaluate_model(self, xyz: np.ndarray, *, scale: bool = True) -> np.ndarray:
return strat_id

s_id = 0
for g in reversed(self.stratigraphic_column.get_groups()):
feature_id = self.feature_name_index.get(g.name, -1)
if feature_id >= 0:
vals = self.features[feature_id].evaluate_value(xyz)
for u in g.units:
strat_id[np.logical_and(vals < u.max(), vals > u.min())] = s_id
s_id += 1
if feature_id == -1:
logger.error(f"Model does not contain {g.name}")
# one scope for all groups: they share the restorations of equal fault sets
with evaluation_scope(self):
for g in reversed(self.stratigraphic_column.get_groups()):
feature_id = self.feature_name_index.get(g.name, -1)
if feature_id >= 0:
vals = self.features[feature_id].evaluate_value(xyz)
for u in g.units:
strat_id[np.logical_and(vals < u.max(), vals > u.min())] = s_id
s_id += 1
if feature_id == -1:
logger.error(f"Model does not contain {g.name}")

return strat_id

Expand All @@ -1316,13 +1322,15 @@ def evaluate_model_gradient(self, points: np.ndarray, *, scale: bool = True) ->
# evaluate_model.
xyz = np.array(points)
grad = np.zeros(xyz.shape)
for g in reversed(self.stratigraphic_column.get_groups()):
feature_id = self.feature_name_index.get(g.name, -1)
if feature_id >= 0:
gradt = self.features[feature_id].evaluate_gradient(xyz)
grad[~np.isnan(gradt).any(axis=1)] = gradt[~np.isnan(gradt).any(axis=1)]
if feature_id == -1:
logger.error(f"Model does not contain {g.name}")
# one scope for all groups: they share the restorations of equal fault sets
with evaluation_scope(self):
for g in reversed(self.stratigraphic_column.get_groups()):
feature_id = self.feature_name_index.get(g.name, -1)
if feature_id >= 0:
gradt = self.features[feature_id].evaluate_gradient(xyz)
grad[~np.isnan(gradt).any(axis=1)] = gradt[~np.isnan(gradt).any(axis=1)]
if feature_id == -1:
logger.error(f"Model does not contain {g.name}")

return grad

Expand All @@ -1346,10 +1354,11 @@ def evaluate_fault_displacements(self, points, scale=True):
# `scale` is retained for API-signature compatibility only -- see
# evaluate_model.
vals = np.zeros(points.shape[0])
for f in self.features:
if f.type == FeatureType.FAULT:
disp = f.displacementfeature.evaluate_value(points)
vals[~np.isnan(disp)] += disp[~np.isnan(disp)]
with evaluation_scope(self):
for f in self.features:
if f.type == FeatureType.FAULT:
disp = f.displacementfeature.evaluate_value(points)
vals[~np.isnan(disp)] += disp[~np.isnan(disp)]
return vals # convert from restoration magnutude to displacement

@public_api(tier="stable")
Expand Down Expand Up @@ -1418,7 +1427,8 @@ def evaluate_feature_value(self, feature_name, xyz, scale=True):
# evaluate_model.
feature = self.get_feature_by_name(feature_name)
if feature:
return feature.evaluate_value(xyz)
with evaluation_scope(self):
return feature.evaluate_value(xyz)
else:
return np.zeros(xyz.shape[0])

Expand Down Expand Up @@ -1576,10 +1586,8 @@ def update(self, verbose=False, progressbar=True):
total_dof += f.interpolator.dof
continue
if verbose:
logger.info(
f"Updating geological model. There are: \n {nfeatures} \
geological features that need to be interpolated\n"
)
logger.info(f"Updating geological model. There are: \n {nfeatures} \
geological features that need to be interpolated\n")

with timed_stage(logger, "update", nfeatures=nfeatures, total_dof=total_dof):
if progressbar:
Expand Down Expand Up @@ -1647,7 +1655,8 @@ def save(
# ModelFeatureFactory.build_* staticmethod; new feature types register here
# without modifying GeologicalModel's source.
FeatureBuilderRegistry.register(
"foliation", lambda model, name, **params: ModelFeatureFactory.build_foliation(model, name, **params)
"foliation",
lambda model, name, **params: ModelFeatureFactory.build_foliation(model, name, **params),
)
FeatureBuilderRegistry.register(
"fold_frame",
Expand All @@ -1659,7 +1668,9 @@ def save(
)
FeatureBuilderRegistry.register(
"folded_fold_frame",
lambda model, name, **params: ModelFeatureFactory.build_folded_fold_frame(model, name, **params),
lambda model, name, **params: ModelFeatureFactory.build_folded_fold_frame(
model, name, **params
),
)
FeatureBuilderRegistry.register(
"intrusion",
Expand Down
12 changes: 8 additions & 4 deletions LoopStructural/modelling/features/_base_geological_feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
from LoopStructural.utils.regions import BaseRegion
from LoopStructural.utils.typing import NumericInput

from ._evaluation import evaluation_scope

logger = getLogger(__name__)


Expand Down Expand Up @@ -227,8 +229,9 @@ def evaluate_normalised_value(self, pos: NumericInput):
pos : NumericInput
An array or arraylike object with locations
"""
value = self.evaluate_value(pos)
return (value - self.min()) / (self.max() - self.min())
with evaluation_scope(self.model):
value = self.evaluate_value(pos)
return (value - self.min()) / (self.max() - self.min())

def _calculate_mask(
self, evaluation_points: np.ndarray, ignore_regions=False, block=None,
Expand Down Expand Up @@ -308,7 +311,7 @@ def evaluate_gradient(self, pos, ignore_regions=False):
"""
Evaluate the gradient of the feature at a given position.
"""

raise NotImplementedError

def min(self):
Expand Down Expand Up @@ -372,7 +375,7 @@ def surfaces(
raise ValueError("Must specify bounding box")
bounding_box = self.model.bounding_box
regions = self.regions

try:
# A region can also be a plain callable (e.g. the lambdas
# add_domain_fault_below/above attach for a domain-fault crop),
Expand Down Expand Up @@ -456,6 +459,7 @@ def gradient_norm_scalar_field(self, bounding_box=None):
)
grid.cell_properties[self.name] = value
return grid

def vector_field(self, bounding_box=None, tolerance=0.05, scale=1.0):
"""Create a vector field for the feature

Expand Down
179 changes: 179 additions & 0 deletions LoopStructural/modelling/features/_evaluation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
"""Evaluation scope that shares fault restorations inside one call.

An evaluation scope is a short-lived :class:`EvaluationContext`. It stores the restored
coordinates of the faults of a feature. The key of an entry holds the exact content of the
points, the ordered faults, ``reverse``, ``faults_enabled`` and a state token of the faults.
Two features that use the same ordered faults on equal points therefore share one
restoration.

The scope is stored in a ``contextvars.ContextVar``. It is always reset when the
outermost ``with`` block ends, also after an exception. The scope keeps
its entries for one call only. It does not keep any entry after it ends. A partial restoration is never stored.
"""

from __future__ import annotations

import hashlib
from collections.abc import Hashable, Iterator
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING

import numpy as np

from LoopStructural.utils._fault_block import restore_through

if TYPE_CHECKING:
from LoopStructural import GeologicalModel
from LoopStructural.modelling.features._base_geological_feature import BaseFeature

_CHUNK_BYTES = 1 << 20
_ACTIVE: ContextVar = ContextVar("loopstructural_evaluation_context", default=None)


def _digest(points: np.ndarray) -> bytes:
"""Return a digest of the exact content of ``points``.

The digest is made in blocks of bounded size. A contiguous array is not copied.
A non-contiguous array is copied one block of rows at a time, never as a whole.
The digest is the same for equal content in any memory layout.
"""
array = np.asarray(points)
hasher = hashlib.blake2b(digest_size=16)
if array.size == 0:
return hasher.digest()
if array.ndim == 0:
array = array.reshape(1)
if array.flags.c_contiguous:
blocks = [array]
else:
row_bytes = max(1, array.itemsize * int(np.prod(array.shape[1:], dtype=np.int64)))
rows = max(1, _CHUNK_BYTES // row_bytes)
blocks = (array[start : start + rows] for start in range(0, array.shape[0], rows))
for block in blocks:
flat = np.ascontiguousarray(block).reshape(-1).view(np.uint8)
for start in range(0, flat.size, _CHUNK_BYTES):
hasher.update(flat[start : start + _CHUNK_BYTES])
return hasher.digest()


def _fault_state(fault: BaseFeature) -> Hashable:
"""Return a token for the identity and the state of one fault."""
return (id(fault), getattr(fault, "displacement", None), getattr(fault, "steps", None))


class EvaluationContext:
"""Storage for the restorations of one evaluation scope.

Parameters
----------
model : GeologicalModel, optional
The model of the scope. None for a standalone feature.
"""

def __init__(self, model: GeologicalModel | None = None) -> None:
self.model = model
self._restorations: dict = {}

def restore(
self, feature: BaseFeature, points: np.ndarray, reverse: bool = False
) -> np.ndarray:
"""Return the points restored by the ordered faults of ``feature``.

Parameters
----------
feature : BaseFeature
The feature whose ``faults`` are applied.
points : np.ndarray
Nx3 array of points.
reverse : bool, default False
Apply the faults in the reverse direction.

Returns
-------
np.ndarray
Read-only array of the restored points.
"""
points = np.asarray(points)
faults = tuple(feature.faults) if feature.faults_enabled else ()
if not faults:
unchanged = points.view()
unchanged.flags.writeable = False
return unchanged
# Build every reachable builder before the first lookup, so a lazy build
# happens once and not between two lookups.
for fault in faults:
builder = getattr(fault, "builder", None)
if builder is not None:
builder.up_to_date()
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.
key = (
digest,
points.shape,
points.dtype.str,
tuple(_fault_state(fault) for fault in faults),
bool(reverse),
)
restored = self._restorations.get(key)
if restored is not None:
return restored
restored = np.asarray(restore_through(points, faults, reverse=reverse))
if restored is points or np.shares_memory(restored, points):
restored = restored.copy()
restored.flags.writeable = False
# The entry is stored only after all faults are applied.
self._restorations[key] = restored
return restored


@contextmanager
def evaluation_scope(model: GeologicalModel | None = None) -> Iterator[EvaluationContext]:
"""Open an evaluation scope and give its context.

A nested scope uses the active context when ``model`` is the model of the active
context, or when ``model`` is None. A scope for another model is a separate context.
The ContextVar is reset when the scope that opened the context ends.

Parameters
----------
model : GeologicalModel, optional
The model of the scope, by default None.

Yields
------
EvaluationContext
The active context.
"""
active = _ACTIVE.get()
if active is not None and (model is None or active.model is model):
yield active
return
context = EvaluationContext(model)
token = _ACTIVE.set(context)
try:
yield context
finally:
_ACTIVE.reset(token)


def restore(feature: BaseFeature, points: np.ndarray, reverse: bool = False) -> np.ndarray:
"""Restore ``points`` with the ordered faults of ``feature``, shared in the scope.

Parameters
----------
feature : BaseFeature
The feature whose faults are applied.
points : np.ndarray
Nx3 array of points.
reverse : bool, default False
Apply the faults in the reverse direction.

Returns
-------
np.ndarray
Read-only array of the restored points.
"""
with evaluation_scope(getattr(feature, "model", None)) as context:
return context.restore(feature, points, reverse)
Loading
Loading