From e92a7c63b36666cf49d882d6003db4d717a3e30b Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Wed, 25 Nov 2026 21:05:45 +1030 Subject: [PATCH 1/3] fix(interpolation): make equality, gradient and weight data reach the solve - add_equality_constraints now adds least-squares rows with the weight EQUALITY_WEIGHT (100). Before, the rows went to equal_constraints and no solve used them. After a native setup, the rows go to the native core as values at the nodes. Remove the unused add_equality_block, the eq_const_* fields and equal_constraints. - P1 and P2 add gradient (direction) constraints as FDI does: two rows with the strike and dip vectors. P1 used to drop them and P2 crashed on the real (n, 3, k) shape derivative layout. P1 and P2 now write a warning for data that they do not use (P1: interface; P2: interface, inequality, inequality pairs). - Use the weight column of the data in all engines: FDI and native gradient and tangent, P1 and P2 value and normal. P1 gives eps as the upper bound of inequality pairs, as FDI does. Co-Authored-By: Claude Opus 5.5 --- .../_discrete_interpolator.py | 134 +++++++++--------- .../_finite_difference_interpolator.py | 8 +- .../src/loop_interpolation/_native.py | 22 ++- .../src/loop_interpolation/_p1interpolator.py | 23 ++- .../src/loop_interpolation/_p2interpolator.py | 26 +--- .../tests/test_equality_constraints.py | 44 ++++++ .../tests/test_gradient_and_weight_columns.py | 83 +++++++++++ .../unit/interpolator/test_p2interpolator.py | 6 +- .../test_reference_constraint_frames.py | 11 +- 9 files changed, 236 insertions(+), 121 deletions(-) create mode 100644 packages/loop_interpolation/tests/test_equality_constraints.py create mode 100644 packages/loop_interpolation/tests/test_gradient_and_weight_columns.py diff --git a/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py b/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py index 76235d22b..d07cd0309 100644 --- a/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py +++ b/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py @@ -10,6 +10,7 @@ import numpy as np from loop_common.logging import get_logger as getLogger +from loop_common.math import get_vectors from scipy import sparse # import sparse.coo_matrix, sparse.bmat, sparse.eye from scipy.sparse.linalg import LinearOperator @@ -26,6 +27,13 @@ logger = getLogger(__name__) +# Weight of an equality row (a row with unit norm, as all rows). The default +# data weights (cpw, gpw) are 1 and the regularisation weights are 0.1 to 1, so +# 100 makes the equality rows dominate by 1e4 in the squared misfit, but keeps +# the system well conditioned enough for cg. +EQUALITY_WEIGHT = 100.0 + + def _drop_nan_rows(A, B, idc, w, name): """Remove constraint rows with a nan in A, B or idc, and log how many were dropped. @@ -76,13 +84,6 @@ def __init__(self, support, data=None, c=None, up_to_date=False): self.solver = "cg" - self.eq_const_C = [] - self.eq_const_row = [] - self.eq_const_col = [] - self.eq_const_d = [] - - self.equal_constraints = {} - self.eq_const_c = 0 self.ineq_constraints = {} self.ineq_const_c = 0 @@ -319,7 +320,6 @@ def clear_constraints(self): """ self.constraints = {} self.ineq_constraints = {} - self.equal_constraints = {} def reset(self): """ @@ -330,6 +330,9 @@ def reset(self): # Gradient orthogonal constraints of a native setup, as raw data: # name -> (points, vectors, w). See add_gradient_orthogonal_constraints. self._native_orthogonal = {} + # Equality constraints of a native setup, as raw data: + # name -> (node points, values, w). See add_equality_constraints. + self._native_equality = {} # setup_interpolator sets these two values again when it ends. self._native_setup = False self._setup_constraint_names = None @@ -685,9 +688,10 @@ def add_inequality_feature( def add_equality_constraints(self, node_idx, values, name="undefined"): """ - Adds hard constraints to the least squares system. For now this just - sets - the node values to be fixed using a lagrangian. + Fix the values of some support nodes. + + The constraint is a least-squares row with the weight + EQUALITY_WEIGHT for each node, so it is strong but not exact. Parameters ---------- @@ -695,23 +699,60 @@ def add_equality_constraints(self, node_idx, values, name="undefined"): int array of node indexes values : numpy array/list array of node values - - Returns - ------- - + name : str + name of the constraint """ idc = np.asarray(node_idx, dtype=int) - values = np.asarray(values) + values = np.asarray(values, dtype=float) inside = np.logical_and(idc >= 0, idc < self.dof) + idc, values = idc[inside], values[inside] + if idc.shape[0] == 0: + return + self.up_to_date = False + if getattr(self, "_native_setup", False): + # The native core reads raw data, not sparse rows: a value at a node + # is the same row (see _native._add_data). + self._native_equality[name] = (self.support.nodes[idc], values, EQUALITY_WEIGHT) + return + self.add_constraints_to_least_squares( + np.ones((idc.shape[0], 1)), values, idc[:, None], w=EQUALITY_WEIGHT, name=name + ) - self.equal_constraints[name] = { - "A": np.ones(idc[inside].shape[0]), - "B": values[inside], - "col": idc[inside], - # "w": w, - "row": np.arange(self.eq_const_c, self.eq_const_c + idc[inside].shape[0]), - } - self.eq_const_c += idc[inside].shape[0] + def add_gradient_constraints(self, w=1.0): + """Constrain the direction of the gradient (P1 and P2 supports). + + As in the finite difference interpolator, the gradient is made + orthogonal to two vectors in the plane of the data (strike and dip). + Each row has the weight w times the weight column of the data. + """ + points = self.get_gradient_constraints() + if points.shape[0] == 0: + return + d = self.dimensions + grad, elements, inside = self.support.evaluate_shape_derivatives(points[:, :d]) + if not np.any(inside): + return + vectors = np.array(points[inside, d : 2 * d], dtype=float) + if d == 2: + directions = [np.column_stack([-vectors[:, 1], vectors[:, 0]])] + else: + directions = [v.T for v in get_vectors(vectors)] + grad = grad[inside] + A = np.vstack([np.einsum("ij,ijk->ik", v, grad) for v in directions]) + idc = np.tile(self.support.elements[elements[inside]], (len(directions), 1)) + wt = np.tile(w * points[inside, 2 * d], len(directions)) + self.add_constraints_to_least_squares(A, np.zeros(A.shape[0]), idc, w=wt, name="gradient") + self.up_to_date = False + + def _warn_ignored_data(self, families): + """Warn when data is set for a family that this interpolator does not use.""" + for family in families: + n = self.data[family].shape[0] + if n > 0: + logger.warning( + f"{type(self).__name__} does not use {family} constraints: " + f"{n} {family} points are ignored" + ) def add_tangent_constraints(self, w=1.0): r"""Adds the constraints :math:`f(X)\cdotT=0` @@ -727,7 +768,7 @@ def add_tangent_constraints(self, w=1.0): """ points = self.get_tangent_constraints() if points.shape[0] > 0: - self.add_gradient_orthogonal_constraints(points[:, :3], points[:, 3:6], w) + self.add_gradient_orthogonal_constraints(points[:, :3], points[:, 3:6], w * points[:, 6]) def _assemble_explicit_constraint_matrix(self) -> tuple[sparse.spmatrix, np.ndarray]: """Stack every recorded explicit constraint (``self.constraints``, @@ -754,9 +795,7 @@ def _assemble_explicit_constraint_matrix(self) -> tuple[sparse.spmatrix, np.ndar def build_matrix(self): """ - Assemble constraints into interpolation matrix. Adds equaltiy - constraints - using lagrange modifiers if necessary + Assemble constraints into interpolation matrix. Parameters ---------- @@ -880,45 +919,6 @@ def compute_column_scaling_matrix(self, A: sparse.csr_matrix) -> sparse.dia_matr S = sparse.diags(scaling_factors) return S - def add_equality_block(self, A, B): - if len(self.equal_constraints) > 0: - ATA = A.T.dot(A) - ATB = A.T.dot(B) - logger.info(f"Equality block is {self.eq_const_c} x {self.dof}") - # solving constrained least squares using - # | ATA CT | |c| = b - # | C 0 | |y| d - # where A is the interpoaltion matrix - # C is the equality constraint matrix - # b is the interpolation constraints to be honoured - # in a least squares sense - # and d are the equality constraints - # c are the node values and y are the - # lagrange multipliers# - a = [] - rows = [] - cols = [] - b = [] - for c in self.equal_constraints.values(): - b.extend((c["B"]).tolist()) - aa = c["A"].flatten() - mask = aa == 0 - a.extend(aa[~mask].tolist()) - rows.extend(c["row"].flatten()[~mask].tolist()) - cols.extend(c["col"].flatten()[~mask].tolist()) - - C = sparse.coo_matrix( - (np.array(a), (np.array(rows), cols)), - shape=(self.eq_const_c, self.dof), - dtype=float, - ).tocsr() - - d = np.array(b) - ATA = sparse.bmat([[ATA, C.T], [C, None]]) - ATB = np.hstack([ATB, d]) - - return ATA, ATB - def build_inequality_matrix(self): mats = [] bounds = [] diff --git a/packages/loop_interpolation/src/loop_interpolation/_finite_difference_interpolator.py b/packages/loop_interpolation/src/loop_interpolation/_finite_difference_interpolator.py index 3d861282a..f0aac50b7 100644 --- a/packages/loop_interpolation/src/loop_interpolation/_finite_difference_interpolator.py +++ b/packages/loop_interpolation/src/loop_interpolation/_finite_difference_interpolator.py @@ -408,9 +408,10 @@ def add_gradient_constraints(self, w=1.0): ) A = np.einsum("ij,ijk->ik", strike_vector.T, T) B = np.zeros(points[inside, :].shape[0]) - self.add_constraints_to_least_squares(A, B, idc[inside, :], w=w, name="gradient") + wt = w * points[inside, 2 * self.support.dimension] + self.add_constraints_to_least_squares(A, B, idc[inside, :], w=wt, name="gradient") A = np.einsum("ij,ijk->ik", dip_vector.T, T) - self.add_constraints_to_least_squares(A, B, idc[inside, :], w=w, name="gradient") + self.add_constraints_to_least_squares(A, B, idc[inside, :], w=wt, name="gradient") # self.regularisation_scale += compute_weighting( # self.support.nodes, # points[inside, : self.support.dimension], @@ -564,7 +565,8 @@ def add_gradient_orthogonal_constraints( # dot product of vector and element gradient = 0 A = np.einsum("ij,ijk->ik", vectors[inside, : self.support.dimension], T) b_ = np.zeros(np.sum(inside)) + b - self.add_constraints_to_least_squares(A, b_, idc[inside, :], w=w, name=name) + wt = np.broadcast_to(np.asarray(w, dtype=float), (points.shape[0],))[inside] + self.add_constraints_to_least_squares(A, b_, idc[inside, :], w=wt, name=name) if np.sum(inside) <= 0: logger.warning( diff --git a/packages/loop_interpolation/src/loop_interpolation/_native.py b/packages/loop_interpolation/src/loop_interpolation/_native.py index eee6ffb1a..aacbd8479 100644 --- a/packages/loop_interpolation/src/loop_interpolation/_native.py +++ b/packages/loop_interpolation/src/loop_interpolation/_native.py @@ -32,11 +32,12 @@ the core weight is ``dxy / 4`` (same for ``dxz`` and ``dyz``). * Border. ``dx dy dz`` are the same in Python and core. * Value. Weight is ``cpw * column 4``. -* Gradient (direction only). Weight is ``gpw``. The weight column is NOT - used by Python. +* Gradient (direction only). Weight is ``gpw * column 6``. * Normal (vector with length). Weight is ``npw / 3 * column 6``. When the data has no weight column, the column weight is 1. -* Tangent. Weight is ``tpw``. The weight column is NOT used by Python. +* Tangent. Weight is ``tpw * column 6``. +* Equality (``add_equality_constraints``). A value at a support node with + the weight ``EQUALITY_WEIGHT``. * Interface. Weight is ``ipw`` (one value for all points). The pairing is "star": each point is paired with the first point of its id group. * Value inequality. Columns x y z | lower | upper. The weight is 1. @@ -289,10 +290,10 @@ def _add_data(problem, interpolator) -> None: w = _weights(_weight(interpolator, "cpw"), value.shape[0]) * value[:, 4] _add_weighted(problem.add_value, value[:, :3], value[:, 3], w, name="value") - # gradient: weight = gpw (the weight column is not used) + # gradient: weight = gpw * column 6 gradient = _rows(interpolator.get_gradient_constraints()) if gradient.shape[0] > 0: - w = _weights(_weight(interpolator, "gpw"), gradient.shape[0]) + w = _weights(_weight(interpolator, "gpw"), gradient.shape[0]) * gradient[:, 6] _add_weighted( problem.add_gradient, gradient[:, :3], @@ -310,10 +311,10 @@ def _add_data(problem, interpolator) -> None: w = w * normal[:, 6] _add_weighted(problem.add_normal, normal[:, :3], normal[:, 3:6], w, name="normal") - # tangent: weight = tpw (the weight column is not used) + # tangent: weight = tpw * column 6 tangent = _rows(interpolator.get_tangent_constraints()) if tangent.shape[0] > 0: - w = _weights(_weight(interpolator, "tpw"), tangent.shape[0]) + w = _weights(_weight(interpolator, "tpw"), tangent.shape[0]) * tangent[:, 6] _add_weighted( problem.add_tangent, tangent[:, :3], @@ -338,6 +339,13 @@ def _add_data(problem, interpolator) -> None: name=name, ) + # equality constraints of a native setup: a value at a support node + equality = getattr(interpolator, "_native_equality", None) + if not isinstance(equality, dict): + equality = {} + for name, (points, values, w) in equality.items(): + _add_weighted(problem.add_value, points, values, _weights(w, points.shape[0]), name=name) + # interface: one weight (ipw) interface = _rows(interpolator.get_interface_constraints()) if interface.shape[0] > 1: diff --git a/packages/loop_interpolation/src/loop_interpolation/_p1interpolator.py b/packages/loop_interpolation/src/loop_interpolation/_p1interpolator.py index 25caefe6a..ce51aecf7 100644 --- a/packages/loop_interpolation/src/loop_interpolation/_p1interpolator.py +++ b/packages/loop_interpolation/src/loop_interpolation/_p1interpolator.py @@ -67,18 +67,13 @@ def _update_regularisation_scale_from_norm_constraints(self): sigma=sigma, ) - def add_gradient_constraints(self, w=1.0): - pass - def add_norm_constraints(self, w=1.0): points = self.get_norm_constraints() if points.shape[0] > 0: grad, elements, inside = self.support.evaluate_shape_derivatives( points[:, : self.dimensions] ) - size = self.support.element_scale[elements[inside]] - wt = np.ones(size.shape[0]) - wt *= w # s* size + wt = w * points[inside, self.dimensions * 2] elements = np.tile(self.support.elements[elements[inside]], (self.dimensions, 1, 1)) elements = elements.swapaxes(0, 1) @@ -99,10 +94,7 @@ def add_value_constraints(self, w=1.0): points = self.get_value_constraints() if points.shape[0] > 0: N, elements, inside = self.support.evaluate_shape(points[:, : self.dimensions]) - size = self.support.element_size[elements[inside]] - - wt = np.ones(size.shape[0]) - wt *= w # * size + wt = w * points[inside, self.dimensions + 1] self.add_constraints_to_least_squares( N[inside, :], points[inside, self.dimensions], @@ -243,8 +235,12 @@ def setup_interpolator(self, **kwargs): self.add_value_constraints(self.interpolation_weights["cpw"]) self.add_tangent_constraints(self.interpolation_weights["tpw"]) self.add_value_inequality_constraints() - self.add_inequality_pairs_constraints() - # self.add_interface_constraints(self.interpolation_weights["ipw"]) + self.add_inequality_pairs_constraints( + pairs=kwargs.get("inequality_pairs", None), + upper_bound=kwargs.get("inequality_pair_upper_bound", np.finfo(float).eps), + lower_bound=kwargs.get("inequality_pair_lower_bound", -np.inf), + ) + self._warn_ignored_data(("interface",)) return self.finalize_setup_diagnostics_report() def add_gradient_orthogonal_constraints( @@ -276,8 +272,7 @@ def add_gradient_orthogonal_constraints( points[:, : self.dimensions] ) size = self.support.element_size[elements[inside]] - wt = np.ones(size.shape[0]) - wt *= w * size + wt = np.broadcast_to(np.asarray(w, dtype=float), (points.shape[0],))[inside] * size elements = self.support.elements[elements[inside], :] # elements = np.tile(self.support.elements[elements[inside]], (3, 1, 1)) diff --git a/packages/loop_interpolation/src/loop_interpolation/_p2interpolator.py b/packages/loop_interpolation/src/loop_interpolation/_p2interpolator.py index 31e320234..aea0f077e 100644 --- a/packages/loop_interpolation/src/loop_interpolation/_p2interpolator.py +++ b/packages/loop_interpolation/src/loop_interpolation/_p2interpolator.py @@ -100,7 +100,7 @@ def setup_interpolator(self, **kwargs): self.add_norm_constraints(self.interpolation_weights["npw"]) self.add_value_constraints(self.interpolation_weights["cpw"]) self.add_tangent_constraints(self.interpolation_weights["tpw"]) - # self.add_interface_constraints(self.interpolation_weights["ipw"]) + self._warn_ignored_data(("interface", "inequality", "inequality_pairs")) return self.finalize_setup_diagnostics_report() def copy(self): @@ -114,23 +114,6 @@ def copy(self): """ return self._inherit_frame(P2Interpolator(self.support)) - def add_gradient_constraints(self, w: float = 1.0): - points = self.get_gradient_constraints() - if points.shape[0] > 0: - grad, elements, inside = self.support.evaluate_shape_derivatives( - points[:, : self.dimensions] - ) - # element size cancels in the row normalisation, w is applied after it - wt = np.full(int(np.sum(inside)), float(w)) - A = np.einsum( - "ikj,ij->ik", - grad[inside, :], - points[inside, self.dimensions : self.dimensions * 2], - ) - B = np.zeros(A.shape[0]) - elements = self.support.elements[elements[inside]] - self.add_constraints_to_least_squares(A, B, elements, w=wt, name="gradient") - def add_gradient_orthogonal_constraints( self, points: np.ndarray, @@ -171,7 +154,7 @@ def add_norm_constraints(self, w: float = 1.0): grad, elements, inside = self.support.evaluate_shape_derivatives( points[:, : self.dimensions] ) - wt = np.full(int(np.sum(inside)), float(w)) + wt = w * points[inside, self.dimensions * 2] elements = np.tile(self.support.elements[elements[inside]], (self.dimensions, 1, 1)) elements = elements.swapaxes(0, 1) self.add_constraints_to_least_squares( @@ -186,10 +169,7 @@ def add_value_constraints(self, w: float = 1.0): points = self.get_value_constraints() if points.shape[0] > 0: N, elements, mask = self.support.evaluate_shape(points[:, : self.dimensions]) - # mask = elements > 0 - size = self.support.element_size[elements[mask]] - wt = np.ones(size.shape[0]) - wt *= w + wt = w * points[mask, self.dimensions + 1] self.add_constraints_to_least_squares( N[mask, :], points[mask, self.dimensions], diff --git a/packages/loop_interpolation/tests/test_equality_constraints.py b/packages/loop_interpolation/tests/test_equality_constraints.py new file mode 100644 index 000000000..4382e7dc0 --- /dev/null +++ b/packages/loop_interpolation/tests/test_equality_constraints.py @@ -0,0 +1,44 @@ +"""Equality constraints must reach the solve (matrix path and native path).""" + +import numpy as np +from loop_interpolation import FiniteDifferenceInterpolator, StructuredGrid, _native + + +def _make_interpolator(solver="cg"): + grid = StructuredGrid(origin=np.zeros(3), nsteps=np.array([6, 6, 6]), step_vector=np.ones(3)) + interpolator = FiniteDifferenceInterpolator(grid) + interpolator.solver = solver + interpolator.set_value_constraints(np.array([[2.5, 2.5, 2.5, 1.0, 1.0]])) + interpolator.setup() + return interpolator + + +def test_equality_constraint_fixes_the_node_value(): + interpolator = _make_interpolator() + interpolator.add_equality_constraints([0, 5], [100.0, 50.0], name="fixed") + interpolator.solve_system("cg") + np.testing.assert_allclose(interpolator.c[[0, 5]], [100.0, 50.0], rtol=1e-2) + # a new setup removes the constraint + interpolator.setup() + assert "fixed" not in interpolator.constraints + + +def test_native_setup_sends_equality_as_node_values(): + interpolator = _make_interpolator("native") + interpolator.add_equality_constraints([0, 5], [100.0, 50.0], name="fixed") + assert "fixed" not in interpolator.constraints + _native.check_supported(interpolator, interpolator._setup_kwargs, {}) + calls = [] + + class Problem: + def add_value(self, points, values, weights): + calls.append((points, values, weights)) + + def __getattr__(self, name): + return lambda *args, **kwargs: None + + _native._add_data(Problem(), interpolator) + points, values, weights = calls[-1] + np.testing.assert_allclose(points.reshape(-1, 3), interpolator.support.nodes[[0, 5]]) + np.testing.assert_allclose(values, [100.0, 50.0]) + assert np.all(weights > 1.0) diff --git a/packages/loop_interpolation/tests/test_gradient_and_weight_columns.py b/packages/loop_interpolation/tests/test_gradient_and_weight_columns.py new file mode 100644 index 000000000..bf222c3bc --- /dev/null +++ b/packages/loop_interpolation/tests/test_gradient_and_weight_columns.py @@ -0,0 +1,83 @@ +"""Gradient constraints and the per-point weight column, for each discrete engine.""" + +import logging + +import numpy as np +import pytest +from loop_common.supports import P2TetMesh +from loop_interpolation import ( + FiniteDifferenceInterpolator, + P1Interpolator, + P2Interpolator, + StructuredGrid, + TetMesh, +) + +GRID = {"origin": np.zeros(3), "nsteps": np.array([5, 5, 5]), "step_vector": np.ones(3)} +ENGINES = { + "FDI": lambda: FiniteDifferenceInterpolator(StructuredGrid(**GRID)), + "P1": lambda: P1Interpolator(TetMesh(**GRID)), + "P2": lambda: P2Interpolator(P2TetMesh(**GRID)), +} +CENTRE = np.array([[2.5, 2.5, 2.5]]) +# two values on a vertical line fix the sign; alone they give a vertical gradient +VALUES = np.array([[2.5, 2.5, 1.0, 0.0, 1.0], [2.5, 2.5, 4.0, 3.0, 1.0]]) + + +def _gradient_at_centre(interpolator): + interpolator.setup() + interpolator.solve_system("cg") + g = interpolator.support.evaluate_gradient(CENTRE, interpolator.c)[0] + return g / np.linalg.norm(g) + + +def _gradient_row(vector, w): + return np.hstack([CENTRE[0], vector, w]) + + +@pytest.mark.parametrize("engine", ENGINES) +def test_gradient_constraints_set_the_direction(engine): + interpolator = ENGINES[engine]() + interpolator.set_value_constraints(VALUES) + interpolator.set_gradient_constraints(_gradient_row([1.0, 0.0, 1.0], 1.0)[None, :]) + g = _gradient_at_centre(interpolator) + np.testing.assert_allclose(g, [2**-0.5, 0.0, 2**-0.5], atol=0.1) + + +@pytest.mark.parametrize("engine", ENGINES) +def test_the_weight_column_is_used(engine): + # value: two points at one place, the heavy one wins + interpolator = ENGINES[engine]() + interpolator.set_value_constraints( + np.vstack([VALUES, [2.5, 2.5, 2.5, 0.0, 1.0], [2.5, 2.5, 2.5, 3.0, 100.0]]) + ) + interpolator.setup() + interpolator.solve_system("cg") + value = interpolator.support.evaluate_value(CENTRE, interpolator.c)[0] + assert value > 2.5 + # gradient: two opposite tilts at one place, the heavy one wins + interpolator = ENGINES[engine]() + interpolator.set_value_constraints(VALUES) + interpolator.set_gradient_constraints( + np.vstack([_gradient_row([1.0, 0.0, 1.0], 1.0), _gradient_row([-1.0, 0.0, 1.0], 100.0)]) + ) + g = _gradient_at_centre(interpolator) + assert g[0] < -0.5 + + +@pytest.mark.parametrize( + "engine, family, data", + [ + ("P1", "interface", [[1.0, 1.0, 1.0, 0.0, 1.0], [3.0, 3.0, 3.0, 0.0, 1.0]]), + ("P2", "interface", [[1.0, 1.0, 1.0, 0.0, 1.0], [3.0, 3.0, 3.0, 0.0, 1.0]]), + ("P2", "inequality", [[1.0, 1.0, 1.0, 0.0, 1.0, 1.0]]), + ("P2", "inequality_pairs", [[1.0, 1.0, 1.0, 0.0, 1.0], [3.0, 3.0, 3.0, 1.0, 1.0]]), + ], +) +def test_ignored_data_gives_a_warning(engine, family, data, caplog): + interpolator = ENGINES[engine]() + interpolator.set_value_constraints(VALUES) + interpolator.data[family] = np.array(data) + with caplog.at_level(logging.WARNING): + interpolator.setup() + assert f"{family} constraints" in caplog.text diff --git a/tests/unit/interpolator/test_p2interpolator.py b/tests/unit/interpolator/test_p2interpolator.py index 27a8921a7..18c82d4ed 100644 --- a/tests/unit/interpolator/test_p2interpolator.py +++ b/tests/unit/interpolator/test_p2interpolator.py @@ -21,7 +21,8 @@ def __init__(self, n_elements=2, dof_per_element=10): def evaluate_shape_derivatives(self, points): n = points.shape[0] - grad = np.ones((n, self.elements.shape[1], 3)) + # real P2 supports return (n, 3, nodes per element) + grad = np.ones((n, 3, self.elements.shape[1])) elements = np.zeros(n, dtype=int) return grad, elements, np.ones(n, dtype=bool) @@ -52,7 +53,8 @@ def test_add_gradient_constraints_uses_correct_support_indexing(interpolator): interpolator.add_gradient_constraints(w=1.0) assert "gradient" in interpolator.constraints matrix = interpolator.constraints["gradient"]["matrix"] - assert matrix.shape == (1, interpolator.dof) + # one row for the strike vector and one for the dip vector + assert matrix.shape == (2, interpolator.dof) def test_evaluate_d2_masks_nan_rows(interpolator): diff --git a/tests/unit/modelling/test_reference_constraint_frames.py b/tests/unit/modelling/test_reference_constraint_frames.py index 9047f04b8..686d63437 100644 --- a/tests/unit/modelling/test_reference_constraint_frames.py +++ b/tests/unit/modelling/test_reference_constraint_frames.py @@ -82,11 +82,12 @@ def test_equality_region_selects_world_nodes(frame_case, engine): field = _field(anchor) builder.add_equality_constraints(field, lambda p: p[:, 0] > anchor[0] + 4) builder.install_equality_constraints() - entries = builder.interpolator.equal_constraints - actual = np.concatenate([entry["col"] for entry in entries.values()]) + entries = builder.interpolator.constraints + entry = entries["reference_equality"] + actual = entry["matrix"].tocoo().col np.testing.assert_array_equal(np.sort(actual), expected) np.testing.assert_allclose( - np.concatenate([entry["B"] for entry in entries.values()]), + entry["b"], field.evaluate_value(world[expected]), rtol=0, atol=tp(50, 50), @@ -191,8 +192,8 @@ def test_restricted_reference_exclusion_counts(frame_case, engine): selected = np.all((world >= lower) & (world <= upper), axis=1) builder.add_equality_constraints(ref, lambda p: np.ones(len(p), dtype=bool)) builder.install_equality_constraints() - equality = builder.interpolator.equal_constraints - equality_rows = np.concatenate([entry["col"] for entry in equality.values()]) + equality = builder.interpolator.constraints + equality_rows = equality["restricted_equality"]["matrix"].tocoo().col np.testing.assert_array_equal(np.sort(equality_rows), np.flatnonzero(selected)) assert len(equality_rows) == int(selected.sum()) assert "restricted_equality" in equality From 749abfa7d16f7841f783fff711b40b894cc845db Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Thu, 26 Nov 2026 07:58:06 +1030 Subject: [PATCH 2/3] fix(faults): build a splay with the default region add_splay without a region read the fault data with data["X", "Y", "Z", "val"], which pandas reads as one tuple key, so the build stopped with KeyError. Select the four columns with a list. When the overlap side cannot be found, return an empty mask instead of None. clear_constraints now also clears the native orthogonal and equality data, as reset does. Co-Authored-By: Claude Opus 5.5 --- .../modelling/features/builders/_fault_builder.py | 5 ++--- .../src/loop_interpolation/_discrete_interpolator.py | 2 ++ tests/unit/modelling/test__fault_builder.py | 12 ++++++++++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/LoopStructural/modelling/features/builders/_fault_builder.py b/LoopStructural/modelling/features/builders/_fault_builder.py index 0279fc43a..6891bebd2 100644 --- a/LoopStructural/modelling/features/builders/_fault_builder.py +++ b/LoopStructural/modelling/features/builders/_fault_builder.py @@ -738,9 +738,7 @@ def add_splay(self, splay, splay_region=None): if splay_region is None: def default_splay_region(xyz): - pts = ( - self.builders[0].data["X", "Y", "Z", "val"].to_numpy() - ) # get_value_constraints() + pts = self.builders[0].data[["X", "Y", "Z", "val"]].to_numpy() pts = pts[pts[:, 3] == 0, :] ext_field = splay[2].evaluate_value(pts[:, :3]) surf_field = splay[0].evaluate_value(pts[:, :3]) @@ -759,6 +757,7 @@ def default_splay_region(xyz): f"Not adding splay, cannot identify splay overlap region for {self.name} and {splay.name}" ) return mask + return mask splay_region = default_splay_region diff --git a/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py b/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py index d07cd0309..73f460389 100644 --- a/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py +++ b/packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py @@ -320,6 +320,8 @@ def clear_constraints(self): """ self.constraints = {} self.ineq_constraints = {} + self._native_orthogonal = {} + self._native_equality = {} def reset(self): """ diff --git a/tests/unit/modelling/test__fault_builder.py b/tests/unit/modelling/test__fault_builder.py index d41476a7c..f0eb8a6fe 100644 --- a/tests/unit/modelling/test__fault_builder.py +++ b/tests/unit/modelling/test__fault_builder.py @@ -137,3 +137,15 @@ def test_fault_builder_create_data_from_geometry_without_normals(interpolatortyp # Run the tests if __name__ == "__main__": pytest.main([__file__]) + + +def test_add_splay_with_the_default_region_builds(): + from tests.fixtures.fault_models import add_fault + + model = GeologicalModel(np.zeros(3), np.ones(3)) + splay = add_fault(model, "splay", (0.5, 0.5, 0.5), 70, 100, 0.05, nelements=2000) + main = add_fault(model, "main", (0.4, 0.5, 0.5), 60, 90, 0.1, nelements=2000) + region = main.builder.add_splay(splay) + main.builder.update() + mask = region(np.random.default_rng(0).random((50, 3))) + assert mask.dtype == bool and mask.shape == (50,) From a2f7cc0b8a619880ba09bca318945c92159d93c7 Mon Sep 17 00:00:00 2001 From: Lachlan Grose Date: Thu, 26 Nov 2026 11:18:24 +1030 Subject: [PATCH 3/3] test(diagnostics): PLI gradient points inside the model now go into rows The test pinned that PLI assembled no gradient rows, so 8 gradient points were unattributed. PLI now uses gradient data, so none are. Co-Authored-By: Claude Opus 5.5 --- tests/unit/modelling/test_diagnostics_frames.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unit/modelling/test_diagnostics_frames.py b/tests/unit/modelling/test_diagnostics_frames.py index 6b8156769..8a2deee87 100644 --- a/tests/unit/modelling/test_diagnostics_frames.py +++ b/tests/unit/modelling/test_diagnostics_frames.py @@ -488,7 +488,7 @@ def test_gradient_outside_points_give_no_false_unattributed_model(): def test_gradient_outside_points_with_pli_are_measured(): - """For PLI, record the measured counts. PLI assembles no gradient rows.""" + """For PLI, the gradient points inside the model go into gradient rows.""" _, feature, _ = _build(ANCHOR, ROTATION, "PLI", select=_with_outside_gradient) records = feature.verification_report().exclusions outside = sum(r.count for r in records if (r.family, r.reason) == ("gradient", "outside_model")) @@ -496,7 +496,7 @@ def test_gradient_outside_points_with_pli_are_measured(): r.count for r in records if (r.family, r.reason) == ("gradient", "unattributed") ) assert outside == 3 - assert unattributed == 8 + assert unattributed == 0 def _faulted_built_model():