Skip to content

Commit e1c10ef

Browse files
authored
fix: resize paths, non-mutating diagnostics and residual report, stage S5 (spec 005) (#402)
* docs(spec): plan stage S5 of 005 and record its review decisions * docs(spec): add tasks for 005 stage S5 (T069 to T088) * docs(spec): start S5 run state and settle five gaps in the task texts * test(005): add S5 tests for resize paths, cell centres and the residual report * fix(tests): correct review findings of wave 32 * docs(spec): record wave 32 review * feat(loop_interpolation): add residual summary and exclusion record types * docs(spec): record wave 33 review * fix(loop_common): keep the extent on resize of structured grids, derive 2D counts, reject rectilinear resize * docs(spec): record wave 34 review * test(005): review and regenerate the 3D structured support golden data for S5 * docs(spec): record wave 35 review * test(005): add S5 misfit diagnostics tests and record resize results * docs(spec): record wave 36 review * test(005): add S5 stale model and report block tests * docs(spec): record wave 37 review and settle T084 unsolved rule * docs(spec): record S5 diagnostics pre-fix failures * docs(spec): record wave 38 review * fix(features): make misfit methods non-mutating, world-correct and stale-safe * docs(spec): record wave 39 review * feat(features): add GeologicalFeature.verification_report with residual and exclusion blocks * docs(spec): record wave 40 review * docs(005): record S5 notices, misfit decision and rollback checks * docs(spec): record wave 41 review * docs(005): record S5 gates, results and status log * fix(features): read the real stale state of fault builders in misfit checks * docs(spec): record spec review findings * docs(spec): record S5 final gates
1 parent 62c420e commit e1c10ef

18 files changed

Lines changed: 3807 additions & 248 deletions

File tree

‎COMPAT.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ unchanged, but the new path is preferred going forward.
5454
| Fold `mask_fn`, custom fold providers (`get_deformed_orientation`), `directional_regularisation` direction callables and arrays, and the P2 `steepness_wtfunc` received or returned local (computational-frame) points and directions | They receive world points and give world directions; the interpolator converts to its local frame once. With an identity frame nothing changes (spec 005, stage S2) | 2026-11-04 |
5555
| `copy()` returned an interpolator with no frame; a transform change after constraints existed gave a stale result | New payloads carry `format_version: 2`, `constraint_space`, `transform` and `bounding_box`. `copy()` keeps the frame. A transform change after constraints exist raises `StaleFrameError` at the next set, evaluate or save (spec 005, stage S3). Loading a legacy payload with no choice is deprecated: see the deprecation table | 2026-11-05 |
5656
| `GeologicalFeature.get_data()` (used by `Loop2DView.add_data` and `ModelExporter.save`) returned locations moved by the local origin and rotated a second time; the intrusion classification evaluated the model at such points | Both use the stored world locations. With an identity frame nothing changes (spec 005, stage S4) | 2026-11-05 |
57+
| `GeologicalFeature.evaluate_gradient_misfit()` changed the stored constraint arrays in place, compared a local vector with a world vector and read one column. Its value was a dot product with an unnormalised model gradient | The name and the public shape stay. The method changes no stored array. It gives the cosine between the world data direction and the model gradient for each row, so the value differs from the old value. Use `evaluate_gradient_cosines()` for a 1-D array. Two families of different length give one row of shape `(1, N1 + N2)`; before, this raised `ValueError` (spec 005, stage S5) | 2026-11-05 |
58+
| `evaluate_gradient_misfit()` and `evaluate_value_misfit()` rebuilt a stale model | Both methods write one `UserWarning` and return NaN. They do not rebuild. Build the model first. The new public method `GeologicalFeature.verification_report()` gives the constraint diagnostics (residuals and exclusions) and does not build the model. A PLI model ignores gradient data, so its report shows an `unattributed` record for the gradient rows (spec 005, stage S5) | 2026-11-05 |
59+
| `evaluate_value_misfit()` divided by the field range, with a division by zero for a zero range | It keeps the normalisation by the field range. A zero or not finite range gives the absolute difference. `evaluate_value_residuals()` gives the unnormalised 1-D result (spec 005, stage S5) | 2026-11-05 |
60+
| Assignment of `nsteps` or `step_vector` on a 3D structured grid, and `set_nelements` | The extent stays the same. Assignment gives a new step, not a product rule. `nsteps` must be whole and at least 2. `set_nelements` keeps `maximum`. Grid steps and solved values can change slightly (spec 005, stage S5) | 2026-11-05 |
61+
| Assignment of `origin`, `nsteps` or `step_vector` on a `RectilinearGrid` | It raises `NotImplementedError`. The node arrays are fixed (spec 005, stage S5) | 2026-11-05 |
62+
| The 2D structured grid: `nsteps_cells`, `n_cell_x` and `n_cell_y` were separate values, and `maximum` could be assigned | The grid derives `nsteps_cells`, `n_cell_x` and `n_cell_y` from `nsteps`. `maximum` is read-only (assignment raises `AttributeError`) and keeps its legacy value (spec 005, stage S5) | 2026-11-05 |
63+
| `ConstraintDiagnosticsReport` had no residual or exclusion fields | It has three new optional fields: `physical_residuals`, `assembled_residuals` and `exclusions`. With an identity frame and no resize, the value misfit is the same as before (spec 005, stage S5) | 2026-11-05 |
5764

5865
The following stable methods remain part of the documented public API surface after the package extraction work and are covered by the snapshot-based contract test: add_onlap_unconformity, add_unconformity, create_and_add_domain_fault, create_and_add_fault, create_and_add_fold_frame, create_and_add_folded_fold_frame, create_and_add_folded_foliation, create_and_add_foliation, evaluate_model, evaluate_model_gradient, from_file, get_fault_surfaces, get_feature_by_name, get_stratigraphic_surfaces, rescale, save, scale.
5966

‎LoopStructural/modelling/features/_geological_feature.py‎

Lines changed: 279 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,18 @@
66

77
from __future__ import annotations
88

9+
import dataclasses
10+
import warnings
11+
912
import numpy as np
13+
from loop_interpolation import DiscreteInterpolator
14+
from loop_interpolation._diagnostics import (
15+
ConstraintDiagnosticsReport,
16+
ResidualSummary,
17+
build_exclusion_records,
18+
direction_cosines,
19+
summarise_residuals,
20+
)
1021

1122
from LoopStructural.utils.maths import gradient_from_tetrahedron, regular_tetraherdron_for_points
1223

@@ -205,12 +216,12 @@ def evaluate_gradient(
205216
while not resolved:
206217
resolved = True
207218
for f in self.faults:
208-
v = (
219+
side = (
209220
f[0]
210221
.evaluate_value(tetrahedron.reshape(-1, 3), fillnan='nearest')
211222
.reshape(tetrahedron.shape[0], 4)
212223
)
213-
flag = np.logical_or(np.all(v > 0, axis=1), np.all(v < 0, axis=1))
224+
flag = np.logical_or(np.all(side > 0, axis=1), np.all(side < 0, axis=1))
214225
if np.any(~flag):
215226
logger.warning(
216227
f"Points are too close to fault {f[0].name}. Refining the tetrahedron"
@@ -237,55 +248,285 @@ def evaluate_gradient(
237248
logger.info(f'Gradient calculated for {self.name}')
238249
return v
239250

240-
def evaluate_gradient_misfit(self):
251+
@staticmethod
252+
def _first_stale(builder, label: str) -> str | None:
253+
"""Find the first stale builder or interpolator below a builder.
254+
255+
The method only reads flags. It follows the rule of
256+
``BaseBuilder.up_to_date``. A structural frame builder or a fault
257+
builder has no flag of its own, so the method reads its component
258+
builders. It also reads the faults of each builder.
259+
260+
Parameters
261+
----------
262+
builder : object or None
263+
Builder to check.
264+
label : str
265+
Name of the builder in the text of the result.
266+
267+
Returns
268+
-------
269+
str or None
270+
Text that names the first stale object, or None if none is stale.
241271
"""
272+
if builder is None:
273+
return None
274+
for fault in getattr(builder, "faults", None) or []:
275+
fault_builder = getattr(fault, "builder", fault)
276+
fault_name = getattr(fault, "name", "a fault")
277+
reason = GeologicalFeature._first_stale(fault_builder, f"the fault {fault_name}")
278+
if reason is not None:
279+
return reason
280+
components = getattr(builder, "builders", None)
281+
if components is not None:
282+
for index, component in enumerate(components):
283+
name = getattr(component, "name", index)
284+
reason = GeologicalFeature._first_stale(component, f"{label} ({name})")
285+
if reason is not None:
286+
return reason
287+
return None
288+
if getattr(builder, "_up_to_date", True) is False:
289+
return f"The builder of {label} is stale. Build the model first."
290+
interpolator = getattr(builder, "_interpolator", None)
291+
if getattr(interpolator, "up_to_date", True) is False:
292+
return f"The interpolator of {label} is stale. Build the model first."
293+
return None
294+
295+
def _stale_reason(self) -> str | None:
296+
"""Find the first stale object of the model.
297+
298+
The method only reads flags. It does not build the model.
242299
243300
Returns
244301
-------
245-
misfit : np.array(N,dtype=double)
246-
dot product between interpolated gradient and constraints
302+
str or None
303+
Text that names the first stale object and says to build the model
304+
first, or None if no object is stale.
247305
"""
248-
if self.builder is not None:
249-
self.builder.up_to_date()
250-
grad = self.interpolator.get_gradient_constraints()
251-
norm = self.interpolator.get_norm_constraints()
252-
253-
dot = []
254-
if grad.shape[0] > 0:
255-
grad /= np.linalg.norm(grad, axis=1)[:, None]
256-
positions = grad[:, :3]
257-
if self.interpolator.bounding_box is not None:
258-
positions = self.interpolator.bounding_box.reproject(positions)
259-
model_grad = self.evaluate_gradient(positions)
260-
dot.append(np.einsum("ij,ij->i", model_grad, grad[:, :3:6]).tolist())
261-
262-
if norm.shape[0] > 0:
263-
norm /= np.linalg.norm(norm, axis=1)[:, None]
264-
positions = norm[:, :3]
265-
if self.interpolator.bounding_box is not None:
266-
positions = self.interpolator.bounding_box.reproject(positions)
267-
model_norm = self.evaluate_gradient(positions)
268-
dot.append(np.einsum("ij,ij->i", model_norm, norm[:, :3:6]))
269-
270-
return np.array(dot)
271-
272-
def evaluate_value_misfit(self):
306+
reason = self._first_stale(self.builder, self.name)
307+
if reason is not None:
308+
return reason
309+
for fault in getattr(self, "faults", None) or []:
310+
reason = self._first_stale(
311+
getattr(fault, "builder", None), f"the fault {getattr(fault, 'name', 'a fault')}"
312+
)
313+
if reason is not None:
314+
return reason
315+
if getattr(self.interpolator, "up_to_date", True) is False:
316+
return f"The interpolator of {self.name} is stale. Build the model first."
317+
return None
318+
319+
def _constraint_row_counts(self) -> list:
320+
"""Count the stored rows of the gradient, normal and value constraints.
321+
322+
Returns
323+
-------
324+
list of int
325+
Row counts of the gradient, normal and value arrays.
273326
"""
327+
return [
328+
int(np.shape(self.interpolator.get_gradient_constraints())[0]),
329+
int(np.shape(self.interpolator.get_norm_constraints())[0]),
330+
int(np.shape(self.interpolator.get_value_constraints())[0]),
331+
]
332+
333+
def _gradient_cosines_fresh(self) -> list:
334+
"""Compute the gradient and normal cosines without a stale check.
335+
336+
The method copies the stored arrays. It does not change them.
274337
275338
Returns
276339
-------
277-
misfit : np.array(N,dtype=double)
278-
difference between interpolated scalar field and value constraints
340+
list of numpy.ndarray
341+
One array of cosines for each non-empty family (gradient first,
342+
then normal).
279343
"""
280-
if self.builder is not None:
281-
self.builder.up_to_date()
344+
bounding_box = self.interpolator.bounding_box
345+
cosines = []
346+
for array in (
347+
self.interpolator.get_gradient_constraints(),
348+
self.interpolator.get_norm_constraints(),
349+
):
350+
if np.shape(array)[0] == 0:
351+
continue
352+
rows = np.array(array, dtype=float, copy=True)
353+
positions = rows[:, :3]
354+
data = rows[:, 3:6]
355+
if bounding_box is not None:
356+
positions = bounding_box.reproject(positions)
357+
data = self.interpolator.local_to_world_vectors(data)
358+
model = self.evaluate_gradient(positions)
359+
cosines.append(direction_cosines(model, data))
360+
return cosines
361+
362+
def _value_residuals_fresh(self) -> np.ndarray:
363+
"""Compute the value residuals without a stale check.
282364
283-
locations = self.interpolator.get_value_constraints()
284-
positions = locations[:, :3]
365+
Returns
366+
-------
367+
numpy.ndarray
368+
Absolute difference in field units, shape (N,).
369+
"""
370+
rows = np.array(self.interpolator.get_value_constraints(), dtype=float, copy=True)
371+
positions = rows[:, :3]
285372
if self.interpolator.bounding_box is not None:
286373
positions = self.interpolator.bounding_box.reproject(positions)
287-
diff = np.abs(locations[:, 3] - self.evaluate_value(positions))
288-
diff /= self.max() - self.min()
374+
return np.abs(rows[:, 3] - self.evaluate_value(positions))
375+
376+
def _physical_residual_summaries(self) -> dict[str, ResidualSummary]:
377+
"""Summarise the physical residuals of the value, gradient and normal data.
378+
379+
The method does not check if the model is stale. The caller must check.
380+
381+
Returns
382+
-------
383+
dict of str to ResidualSummary
384+
One summary for each non-empty family. The value summary uses field
385+
units. The gradient and normal summaries use degrees.
386+
"""
387+
summaries: dict[str, ResidualSummary] = {}
388+
counts = self._constraint_row_counts()
389+
if counts[2] > 0:
390+
summaries["value"] = summarise_residuals(
391+
"value", "physical", "field", self._value_residuals_fresh()
392+
)
393+
# The cosine list has one array for each non-empty family, in this order.
394+
names = [name for name, count in zip(("gradient", "normal"), counts[:2]) if count > 0]
395+
for name, cosine in zip(names, self._gradient_cosines_fresh()):
396+
angles = np.degrees(np.arccos(np.clip(cosine, -1, 1)))
397+
summaries[name] = summarise_residuals(name, "physical", "degree", angles)
398+
return summaries
399+
400+
def verification_report(self) -> ConstraintDiagnosticsReport:
401+
"""Build a report of the constraints, residuals and exclusions.
402+
403+
The method returns a new object. It does not store the report, build the
404+
model or change the state of the model.
405+
406+
Returns
407+
-------
408+
ConstraintDiagnosticsReport
409+
The report. The residual blocks are empty if the model is not
410+
solved. On a stale model the method warns, leaves the residual
411+
blocks empty and still gives the exclusions.
412+
"""
413+
base = self.interpolator._build_constraint_diagnostics_report()
414+
physical: dict[str, ResidualSummary] = {}
415+
assembled: dict[str, ResidualSummary] = {}
416+
reason = self._stale_reason()
417+
if reason is not None:
418+
warnings.warn(reason, UserWarning, stacklevel=2)
419+
elif getattr(self.interpolator, "c", None) is not None:
420+
physical = self._physical_residual_summaries()
421+
if hasattr(self.interpolator, "calculate_residual_for_constraints"):
422+
residuals = self.interpolator.calculate_residual_for_constraints()
423+
for name, residual in residuals.items():
424+
assembled[name] = summarise_residuals(name, "assembled", "assembled", residual)
425+
excluded = getattr(self.builder, "excluded_rows", {}) if self.builder is not None else {}
426+
rows_per_point = (
427+
{"gradient": 2} if isinstance(self.interpolator, DiscreteInterpolator) else None
428+
)
429+
return dataclasses.replace(
430+
base,
431+
physical_residuals=physical,
432+
assembled_residuals=assembled,
433+
exclusions=build_exclusion_records(excluded, base.families, rows_per_point),
434+
)
435+
436+
def evaluate_gradient_cosines(self) -> np.ndarray:
437+
"""Compute the cosine between the model gradient and the gradient data.
438+
439+
The cosine uses world coordinates (see COMPAT.md). The gradient rows come
440+
first and the normal rows come second. The method does not change the
441+
model or the stored constraints.
442+
443+
Returns
444+
-------
445+
numpy.ndarray
446+
Cosines, shape (N,). The array is empty if there are no rows. On a
447+
stale model the method warns and returns NaN for each row.
448+
"""
449+
reason = self._stale_reason()
450+
if reason is not None:
451+
warnings.warn(reason, UserWarning, stacklevel=2)
452+
n = sum(self._constraint_row_counts()[:2])
453+
return np.full(n, np.nan)
454+
cosines = self._gradient_cosines_fresh()
455+
if len(cosines) == 0:
456+
return np.zeros(0)
457+
return np.concatenate(cosines)
458+
459+
def evaluate_value_residuals(self) -> np.ndarray:
460+
"""Compute the residual between the model field and the value data.
461+
462+
The method does not change the model or the stored constraints.
463+
464+
Returns
465+
-------
466+
numpy.ndarray
467+
Absolute difference in field units, shape (N,), in the order of the
468+
value rows. On a stale model the method warns and returns NaN for
469+
each row.
470+
"""
471+
reason = self._stale_reason()
472+
if reason is not None:
473+
warnings.warn(reason, UserWarning, stacklevel=2)
474+
return np.full(self._constraint_row_counts()[2], np.nan)
475+
return self._value_residuals_fresh()
476+
477+
@staticmethod
478+
def _misfit_shape(counts: list) -> tuple:
479+
"""Give the shape of the old gradient misfit array for the row counts."""
480+
if len(counts) == 0:
481+
return (0,)
482+
if len(counts) == 2 and counts[0] == counts[1]:
483+
return (2, counts[0])
484+
return (1, sum(counts))
485+
486+
def evaluate_gradient_misfit(self) -> np.ndarray:
487+
"""Compute the cosine misfit of the gradient and normal constraints.
488+
489+
The value is a cosine in world coordinates (see COMPAT.md).
490+
491+
Returns
492+
-------
493+
numpy.ndarray
494+
Shape (1, N) for one family, (2, N) for two families of equal
495+
length, (1, N1 + N2) for two families of different length and (0,)
496+
with no rows. On a stale model the method warns and returns NaN in
497+
the same shape.
498+
"""
499+
reason = self._stale_reason()
500+
if reason is not None:
501+
warnings.warn(reason, UserWarning, stacklevel=2)
502+
counts = [n for n in self._constraint_row_counts()[:2] if n > 0]
503+
return np.full(self._misfit_shape(counts), np.nan)
504+
cosines = self._gradient_cosines_fresh()
505+
if len(cosines) == 0:
506+
return np.zeros(0)
507+
if len(cosines) == 2 and len(cosines[0]) == len(cosines[1]):
508+
return np.vstack(cosines)
509+
return np.concatenate(cosines)[None, :]
510+
511+
def evaluate_value_misfit(self) -> np.ndarray:
512+
"""Compute the value misfit.
513+
514+
Returns
515+
-------
516+
numpy.ndarray
517+
Absolute difference between the model field and the value data,
518+
shape (N,). The difference is divided by the range of the field
519+
only if the range is finite and larger than zero. On a stale model
520+
the method warns and returns NaN for each row.
521+
"""
522+
reason = self._stale_reason()
523+
if reason is not None:
524+
warnings.warn(reason, UserWarning, stacklevel=2)
525+
return np.full(self._constraint_row_counts()[2], np.nan)
526+
diff = self._value_residuals_fresh()
527+
value_range = self.max() - self.min()
528+
if np.isfinite(value_range) and value_range > 0:
529+
diff = diff / value_range
289530
return diff
290531

291532
def copy(self, name=None):

0 commit comments

Comments
 (0)