From 995a3794cf2b8206d90807506a31cca03a8d0dc5 Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Wed, 25 Nov 2026 17:55:21 +1030 Subject: [PATCH 1/5] fix(modelling): keep unit ranges and group names from a stratigraphic column dict set_stratigraphic_column made the unit ranges again from the thicknesses, starting at 0. The basal unit from ProcessInputData has min=-inf and max=0, so its thickness was inf and all units above it got (inf, inf). Now the units keep the min and max values from the dict, and get_isovalues uses these values. The group names used the dict order (oldest group first), but get_groups counts the groups from the top of the column. With two or more groups, each unit got the name, and so the scalar field, of a different group. Now the names follow the position of each group in the column. Co-Authored-By: Claude Opus 5.5 --- .../modelling/core/geological_model.py | 13 +++++++- .../modelling/core/stratigraphic_column.py | 5 +-- tests/unit/input/test_data_processor.py | 31 +++++++++++++++++++ tests/unit/modelling/test_geological_model.py | 15 +++++++++ 4 files changed, 61 insertions(+), 3 deletions(-) diff --git a/LoopStructural/modelling/core/geological_model.py b/LoopStructural/modelling/core/geological_model.py index c67b5bdb0..9d87f5e18 100644 --- a/LoopStructural/modelling/core/geological_model.py +++ b/LoopStructural/modelling/core/geological_model.py @@ -667,7 +667,9 @@ 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()): + ranges = [] + groups = [] + for g in stratigraphic_column: if g == 'faults': logger.info('Not adding faults to stratigraphic column') continue @@ -677,6 +679,7 @@ 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 + ranges.append((u, min_val, max_val)) logger.info( f""" model.stratigraphic_column.add_unit({u}, @@ -692,7 +695,15 @@ 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) + # 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 + # use the given values: stacking thicknesses from 0 fails for an infinite basal unit + for u, min_val, max_val in ranges: + unit = self.stratigraphic_column.get_unit_by_name(u) + unit.min_value, unit.max_value = min_val, max_val @public_api(tier="provisional") def create_and_add_feature(self, feature_type: str, name: str, **params): diff --git a/LoopStructural/modelling/core/stratigraphic_column.py b/LoopStructural/modelling/core/stratigraphic_column.py index a2d1971f1..a5dfd92ca 100644 --- a/LoopStructural/modelling/core/stratigraphic_column.py +++ b/LoopStructural/modelling/core/stratigraphic_column.py @@ -693,8 +693,9 @@ def get_isovalues(self, where: str = 'bottom') -> dict[str, float]: for g in reversed(self.get_groups()): v = 0 for u in reversed(g.units): - base = v - v += u.thickness + # min_value/max_value are None for a column built with add_element (from_dict) + base = v if u.min_value is None else u.min_value + v = base + u.thickness if u.max_value is None else u.max_value surface_values[u.name] = { 'value': v if where == 'top' else base, 'group': g.name, diff --git a/tests/unit/input/test_data_processor.py b/tests/unit/input/test_data_processor.py index 33a4a51d6..1a7908afe 100644 --- a/tests/unit/input/test_data_processor.py +++ b/tests/unit/input/test_data_processor.py @@ -14,3 +14,34 @@ 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) + + expected = processor.stratigraphic_column["supergroup_0"] + isovalues = model.stratigraphic_column.get_isovalues() + for name, values in expected.items(): + unit = model.stratigraphic_column.get_unit_by_name(name) + assert (unit.min(), unit.max()) == (values["min"], values["max"]) + assert isovalues[name]["value"] == values["min"] diff --git a/tests/unit/modelling/test_geological_model.py b/tests/unit/modelling/test_geological_model.py index b61cca76d..ac49a5e9d 100644 --- a/tests/unit/modelling/test_geological_model.py +++ b/tests/unit/modelling/test_geological_model.py @@ -266,5 +266,20 @@ 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" + + if __name__ == "__main__": test_prepare_data_keeps_world_coordinates() From 97d236f0dd9f6cf16ff4087103fc960183d9f06c Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Wed, 25 Nov 2026 17:55:21 +1030 Subject: [PATCH 2/5] fix(modelling): return unit.id from evaluate_model evaluate_model gave a running counter (bottom group first, top unit first) in place of unit.id. Thus the values did not agree with stratigraphic_ids(). Now each point gets the id of its unit. Co-Authored-By: Claude Opus 5.5 --- .../modelling/core/geological_model.py | 4 +--- tests/unit/modelling/test_geological_model.py | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/LoopStructural/modelling/core/geological_model.py b/LoopStructural/modelling/core/geological_model.py index 9d87f5e18..2ac43d6b0 100644 --- a/LoopStructural/modelling/core/geological_model.py +++ b/LoopStructural/modelling/core/geological_model.py @@ -1294,14 +1294,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}") diff --git a/tests/unit/modelling/test_geological_model.py b/tests/unit/modelling/test_geological_model.py index ac49a5e9d..44f56806c 100644 --- a/tests/unit/modelling/test_geological_model.py +++ b/tests/unit/modelling/test_geological_model.py @@ -281,5 +281,26 @@ def test_set_stratigraphic_column_keeps_group_names(): 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() From 5485ee6b57709a922a5c15707794d4706613b806 Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Wed, 25 Nov 2026 21:17:25 +1030 Subject: [PATCH 3/5] fix(modelling): put an infinite basal unit below the 0 isovalue The first fix set the unit ranges once, but update_unit_values made them again on each add_unit or thickness change. The basal unit with an infinite thickness then gave (inf, inf) to all units above it again. Now update_unit_values gives an infinite basal unit of a group the range (-inf, 0), and the units above it start at 0. set_stratigraphic_column does not set the ranges itself any more. get_isovalues makes the values again and reads the unit ranges, so a column from from_dict also gives correct values. The Basement range changes from (0, inf) to (-inf, 0). Co-Authored-By: Claude Opus 5.5 --- .../modelling/core/geological_model.py | 8 ++----- .../modelling/core/stratigraphic_column.py | 20 +++++++++++------- tests/unit/input/test_data_processor.py | 21 ++++++++++++++----- 3 files changed, 30 insertions(+), 19 deletions(-) diff --git a/LoopStructural/modelling/core/geological_model.py b/LoopStructural/modelling/core/geological_model.py index 2ac43d6b0..b294c9c1c 100644 --- a/LoopStructural/modelling/core/geological_model.py +++ b/LoopStructural/modelling/core/geological_model.py @@ -667,7 +667,6 @@ 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") - ranges = [] groups = [] for g in stratigraphic_column: if g == 'faults': @@ -679,7 +678,6 @@ 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 - ranges.append((u, min_val, max_val)) logger.info( f""" model.stratigraphic_column.add_unit({u}, @@ -697,13 +695,11 @@ def set_stratigraphic_column(self, stratigraphic_column, cmap="tab20"): ) 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 - # use the given values: stacking thicknesses from 0 fails for an infinite basal unit - for u, min_val, max_val in ranges: - unit = self.stratigraphic_column.get_unit_by_name(u) - unit.min_value, unit.max_value = min_val, max_val @public_api(tier="provisional") def create_and_add_feature(self, feature_type: str, name: str, **params): diff --git a/LoopStructural/modelling/core/stratigraphic_column.py b/LoopStructural/modelling/core/stratigraphic_column.py index a5dfd92ca..408787912 100644 --- a/LoopStructural/modelling/core/stratigraphic_column.py +++ b/LoopStructural/modelling/core/stratigraphic_column.py @@ -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): """ @@ -690,14 +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): - # min_value/max_value are None for a column built with add_element (from_dict) - base = v if u.min_value is None else u.min_value - v = base + u.thickness if u.max_value is None else u.max_value 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, } diff --git a/tests/unit/input/test_data_processor.py b/tests/unit/input/test_data_processor.py index 1a7908afe..19d1726e8 100644 --- a/tests/unit/input/test_data_processor.py +++ b/tests/unit/input/test_data_processor.py @@ -39,9 +39,20 @@ def test_from_processor_unit_ranges_match_processor_values(): warnings.simplefilter("ignore", DeprecationWarning) model = GeologicalModel.from_processor(processor) + column = model.stratigraphic_column expected = processor.stratigraphic_column["supergroup_0"] - isovalues = model.stratigraphic_column.get_isovalues() - for name, values in expected.items(): - unit = model.stratigraphic_column.get_unit_by_name(name) - assert (unit.min(), unit.max()) == (values["min"], values["max"]) - assert isovalues[name]["value"] == values["min"] + + 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() From 64d3ba8ecaf713d2809380ba62016a2da5b390d8 Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Wed, 25 Nov 2026 21:18:09 +1030 Subject: [PATCH 4/5] fix(modelling): order the cmap colours by unit id cmap() gave the colours with the top unit first. evaluate_model now gives unit.id, which increases from the bottom, and the viewers map each value to a colour in order. Thus the block model and map colours were in the reverse order. Now cmap() gives the colours in the order of the unit ids. Co-Authored-By: Claude Opus 5.5 --- LoopStructural/modelling/core/stratigraphic_column.py | 3 ++- tests/unit/modelling/test_stratigraphic_column.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/LoopStructural/modelling/core/stratigraphic_column.py b/LoopStructural/modelling/core/stratigraphic_column.py index 408787912..5609d3136 100644 --- a/LoopStructural/modelling/core/stratigraphic_column.py +++ b/LoopStructural/modelling/core/stratigraphic_column.py @@ -822,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") diff --git a/tests/unit/modelling/test_stratigraphic_column.py b/tests/unit/modelling/test_stratigraphic_column.py index db27518b8..65fbb643b 100644 --- a/tests/unit/modelling/test_stratigraphic_column.py +++ b/tests/unit/modelling/test_stratigraphic_column.py @@ -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 From 2de0f0785b4c76b1658f1b35311feff1fd32e725 Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Wed, 25 Nov 2026 21:18:39 +1030 Subject: [PATCH 5/5] docs(modelling): record the evaluate_model id change in COMPAT.md evaluate_model is a stable method. Its values are now unit ids, and the cmap colours and the basal unit range also changed. Add a COMPAT.md row for these changes and say in the docstring that the values are unit ids. Co-Authored-By: Claude Opus 5.5 --- COMPAT.md | 1 + LoopStructural/modelling/core/geological_model.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/COMPAT.md b/COMPAT.md index 448444a76..aa38b2bbf 100644 --- a/COMPAT.md +++ b/COMPAT.md @@ -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. diff --git a/LoopStructural/modelling/core/geological_model.py b/LoopStructural/modelling/core/geological_model.py index b294c9c1c..0dfaaec62 100644 --- a/LoopStructural/modelling/core/geological_model.py +++ b/LoopStructural/modelling/core/geological_model.py @@ -1242,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 --------