Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions COMPAT.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ unchanged, but the new path is preferred going forward.
| **Changes model results.** A fault created after two or more unconformities took the region of the last one only | It takes the region of each erosional unconformity that is before it in the model (LS-D2) | 2026-11-16 |
| **Changes model results.** The unconformity region of a fault that a younger fault displaces was read at a point restored twice through the younger fault (the same error as the double restoration of a displaced fault) | The region is read at the point restored once, so the older fault ends on the unconformity in the space in which its frame is built. Models change where a fault is truncated by an unconformity, is displaced by a younger fault, and both faults displace a series. `UnconformityFeature.evaluate` and `__call__` have a new keyword `restored_through` (LS-D2) | 2026-11-16 |
| **Bug fix that changes model results.** A feature that a fault displaces was restored twice through a younger fault when the younger fault also displaces that fault: the frame of the older fault is built in the space restored by the younger fault, and its evaluation restored the point through the younger fault a second time. The side and the slip of the older fault were read at the wrong point (all versions up to 1.11.0) | Each point is restored once through each fault. There is no flag for the old behaviour. **Models change** where a fault displaces a feature and is itself displaced by a younger fault that also displaces that feature: the restored data and the evaluated field of that feature both change (in the test model by up to 0.059, for an offset of the older fault of 0.082). **Models without displaced faults do not change.** New keyword `restored_through` on `FaultSegment.apply_to_points` / `apply_to_vectors` and `GeologicalFeature.evaluate_value` / `evaluate_gradient`. `LambdaGeologicalFeature` and `AnalyticalGeologicalFeature` keep their own fault loops and are not changed (kiridashi requirement LS-E1) | 2026-11-16 |
| `GeologicalModel.evaluate_model` gave a running index (bottom group first, top unit first in each group), not the unit id; `StratigraphicColumn.cmap()` gave the colours top unit first; the basal unit of a column with an infinite thickness had the range (0, inf), so `from_processor` gave (inf, inf) to all units above it | `evaluate_model` gives `StratigraphicUnit.id` (the same ids as `stratigraphic_ids()`), or -1 if no unit contains the point. `cmap()` gives the colours in unit id order. An infinite basal unit has the range (-inf, 0), and the units above it start at 0 (this includes the default `Basement`). Code that used the old index must use the unit id | 2026-11-25 |

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.

Expand Down
15 changes: 10 additions & 5 deletions LoopStructural/modelling/core/geological_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -667,7 +667,8 @@ def set_stratigraphic_column(self, stratigraphic_column, cmap="tab20"):
# if the colour for a unit hasn't been specified we can just sample from
# a colour map e.g. tab20
logger.info("Adding stratigraphic column to model")
for i, g in enumerate(stratigraphic_column.keys()):
groups = []
for g in stratigraphic_column:
if g == 'faults':
logger.info('Not adding faults to stratigraphic column')
continue
Expand All @@ -692,6 +693,12 @@ def set_stratigraphic_column(self, stratigraphic_column, cmap="tab20"):
self.stratigraphic_column.add_unconformity(
name=f"{g}unconformity",
)
if stratigraphic_column[g]:
groups.append(g)
# each dict group is added on top, so the first group ends at the bottom of the
# column; get_groups() and evaluate_model depend on this order
# get_groups() numbers groups from the top of the column, the last group added
for i, g in enumerate(reversed(groups)):
self.stratigraphic_column.group_mapping[f'Group_{i}'] = g

@public_api(tier="provisional")
Expand Down Expand Up @@ -1235,7 +1242,7 @@ def evaluate_model(self, xyz: np.ndarray, *, scale: bool = True) -> np.ndarray:
Returns
-------
stratigraphic_id : np.array(N,dtype=int)
the stratigraphic index for locations
unit id (StratigraphicUnit.id), -1 if unassigned

Examples
--------
Expand Down Expand Up @@ -1283,14 +1290,12 @@ def evaluate_model(self, xyz: np.ndarray, *, scale: bool = True) -> np.ndarray:
logger.warning("No stratigraphic column defined")
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
strat_id[np.logical_and(vals < u.max(), vals > u.min())] = u.id
if feature_id == -1:
logger.error(f"Model does not contain {g.name}")

Expand Down
22 changes: 14 additions & 8 deletions LoopStructural/modelling/core/stratigraphic_column.py
Original file line number Diff line number Diff line change
Expand Up @@ -601,13 +601,20 @@ def update_unit_values(
if event is not None and not event.startswith('unit/'):
return
cumulative_thickness = 0
basal = True
for element in self.order:
if isinstance(element, StratigraphicUnit):
element.min_value = cumulative_thickness
element.max_value = cumulative_thickness + (element.thickness or 0)
cumulative_thickness = element.max_value
if basal and element.thickness == np.inf:
# an infinite basal unit (e.g. basement) lies below the 0 isovalue
element.min_value, element.max_value = -np.inf, 0
else:
element.min_value = cumulative_thickness
element.max_value = cumulative_thickness + (element.thickness or 0)
cumulative_thickness = element.max_value
basal = False
elif isinstance(element, StratigraphicUnconformity):
cumulative_thickness = 0
basal = True

def update_element(self, unit_data: dict):
"""
Expand Down Expand Up @@ -690,13 +697,11 @@ def get_isovalues(self, where: str = 'bottom') -> dict[str, float]:
if where not in ('top', 'bottom'):
raise ValueError("Invalid 'where' argument. Use 'top' or 'bottom'.")
surface_values = {}
self.update_unit_values() # from_dict adds units without computing their values
for g in reversed(self.get_groups()):
v = 0
for u in reversed(g.units):
base = v
v += u.thickness
surface_values[u.name] = {
'value': v if where == 'top' else base,
'value': u.max() if where == 'top' else u.min(),
'group': g.name,
'colour': u.colour,
}
Expand Down Expand Up @@ -817,7 +822,8 @@ def cmap(self):
data.append((u.id, u.colour))
colours.append(u.colour)
boundaries.append(u.id)
# print(u,v)
# order by unit id: evaluate_model gives unit.id and viewers map it to colour in order
colours = [c for _, c in sorted(data, key=lambda d: d[0])]
cmap = colors.ListedColormap(colours)
except ImportError:
logger.warning("Cannot use predefined colours as I can't import matplotlib")
Expand Down
42 changes: 42 additions & 0 deletions tests/unit/input/test_data_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,45 @@ def test_create_processor():
contacts=df, stratigraphic_order=stratigraphic_order, thicknesses=thicknesses
)
assert (processor.data["val"].unique() == np.array([0.5, 0])).all()


def test_from_processor_unit_ranges_match_processor_values():
"""
Regression test: the basal unit (min=-inf, max=0) gave an infinite
thickness, so every unit above it got the range (inf, inf).
"""
import warnings

from LoopStructural import GeologicalModel
from LoopStructural.datasets import load_geological_map_data

contacts, orientations, thickness, order, bbox, *_ = load_geological_map_data()
processor = ProcessInputData(
contacts=contacts,
contact_orientations=orientations.rename({"formation": "name"}, axis=1),
thicknesses=dict(zip(thickness["name"], thickness["thickness"])),
stratigraphic_order=[("supergroup_0", list(order["unit name"]))],
origin=bbox.loc["origin"].to_numpy(),
maximum=bbox.loc["maximum"].to_numpy(),
)
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
model = GeologicalModel.from_processor(processor)

column = model.stratigraphic_column
expected = processor.stratigraphic_column["supergroup_0"]

def check():
isovalues = column.get_isovalues()
for name, values in expected.items():
unit = column.get_unit_by_name(name)
assert (unit.min(), unit.max()) == (values["min"], values["max"])
assert isovalues[name]["value"] == values["min"]

check()
# a later recompute of the column must keep the same ranges
column.add_unit("new_top", thickness=10)
check()
unit = column.get_unit_by_name("Bunjinah_Formation")
unit.thickness = unit.thickness
check()
36 changes: 36 additions & 0 deletions tests/unit/modelling/test_geological_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,5 +266,41 @@ def test_from_file_allow_pickle_false_raises_without_loading(tmp_path):
GeologicalModel.from_file(model_file, allow_pickle=False)


def test_set_stratigraphic_column_keeps_group_names():
"""Regression test: with two groups, each unit got the name of the other group."""
model = GeologicalModel([0, 0, 0], [1, 1, 1])
with pytest.warns(DeprecationWarning):
model.set_stratigraphic_column(
{
"A": {"a1": {"min": 0, "max": 1}, "a2": {"min": 1, "max": 2}},
"B": {"b1": {"min": 0, "max": 1}},
}
)
column = model.stratigraphic_column
assert column.get_group_for_unit_name("a1").name == "A"
assert column.get_group_for_unit_name("b1").name == "B"


def test_evaluate_model_returns_unit_ids():
"""Regression test: evaluate_model gave a running counter, not unit.id."""
from LoopStructural.modelling.features._analytical_feature import (
AnalyticalGeologicalFeature,
)

model = GeologicalModel([0, 0, 0], [10, 10, 10])
column = model.stratigraphic_column
column.clear(basement=False)
for i in (1, 2, 3):
column.add_unit(f"u{i}", thickness=1.0, id=i)
column.group_mapping["Group_0"] = "strati"
model._add_feature(
AnalyticalGeologicalFeature(
name="strati", vector=np.array([0.0, 0.0, 1.0]), origin=np.zeros(3)
)
)
points = np.array([[1.0, 1.0, z] for z in (0.5, 1.5, 2.5)])
assert model.evaluate_model(points).tolist() == [1, 2, 3]


if __name__ == "__main__":
test_prepare_data_keeps_world_coordinates()
10 changes: 10 additions & 0 deletions tests/unit/modelling/test_stratigraphic_column.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,16 @@ def test_cmap_converts_non_string_colours_to_hex(self):
assert isinstance(unit.colour, str)
assert unit.colour.startswith("#")

def test_cmap_colours_are_in_unit_id_order(self):
# evaluate_model gives unit.id, and the viewers map values to colours in order
column = StratigraphicColumn()
column.clear(basement=False)
for i, colour in enumerate(["#ff0000", "#00ff00", "#0000ff"]):
column.add_unit(f"u{i}", thickness=1.0, id=i, colour=colour)
cmap = column.cmap()
for i in range(3):
assert cmap.colors[i] == column.get_unit_by_name(f"u{i}").colour

def test_plot_returns_figure_when_no_axis_given(self):
import matplotlib

Expand Down
Loading