Skip to content

Commit 3dc4575

Browse files
lachlangroseclaude
andauthored
fix(loop-interpolation): equality, gradient and weight data reach the solve (#416)
* 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6449837 commit 3dc4575

12 files changed

Lines changed: 254 additions & 126 deletions

File tree

‎LoopStructural/modelling/features/builders/_fault_builder.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -738,9 +738,7 @@ def add_splay(self, splay, splay_region=None):
738738
if splay_region is None:
739739

740740
def default_splay_region(xyz):
741-
pts = (
742-
self.builders[0].data["X", "Y", "Z", "val"].to_numpy()
743-
) # get_value_constraints()
741+
pts = self.builders[0].data[["X", "Y", "Z", "val"]].to_numpy()
744742
pts = pts[pts[:, 3] == 0, :]
745743
ext_field = splay[2].evaluate_value(pts[:, :3])
746744
surf_field = splay[0].evaluate_value(pts[:, :3])
@@ -759,6 +757,7 @@ def default_splay_region(xyz):
759757
f"Not adding splay, cannot identify splay overlap region for {self.name} and {splay.name}"
760758
)
761759
return mask
760+
return mask
762761

763762
splay_region = default_splay_region
764763

‎packages/loop_interpolation/src/loop_interpolation/_discrete_interpolator.py‎

Lines changed: 69 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
import numpy as np
1212
from loop_common.logging import get_logger as getLogger
13+
from loop_common.math import get_vectors
1314
from scipy import sparse # import sparse.coo_matrix, sparse.bmat, sparse.eye
1415
from scipy.sparse.linalg import LinearOperator
1516

@@ -26,6 +27,13 @@
2627
logger = getLogger(__name__)
2728

2829

30+
# Weight of an equality row (a row with unit norm, as all rows). The default
31+
# data weights (cpw, gpw) are 1 and the regularisation weights are 0.1 to 1, so
32+
# 100 makes the equality rows dominate by 1e4 in the squared misfit, but keeps
33+
# the system well conditioned enough for cg.
34+
EQUALITY_WEIGHT = 100.0
35+
36+
2937
def _drop_nan_rows(A, B, idc, w, name):
3038
"""Remove constraint rows with a nan in A, B or idc, and log how many were dropped.
3139
@@ -86,13 +94,6 @@ def __init__(self, support, data=None, c=None, up_to_date=False):
8694

8795
self.solver = "cg"
8896

89-
self.eq_const_C = []
90-
self.eq_const_row = []
91-
self.eq_const_col = []
92-
self.eq_const_d = []
93-
94-
self.equal_constraints = {}
95-
self.eq_const_c = 0
9697
self.ineq_constraints = {}
9798
self.ineq_const_c = 0
9899

@@ -329,7 +330,8 @@ def clear_constraints(self):
329330
"""
330331
self.constraints = {}
331332
self.ineq_constraints = {}
332-
self.equal_constraints = {}
333+
self._native_orthogonal = {}
334+
self._native_equality = {}
333335

334336
def reset(self):
335337
"""
@@ -340,6 +342,9 @@ def reset(self):
340342
# Gradient orthogonal constraints of a native setup, as raw data:
341343
# name -> (points, vectors, w). See add_gradient_orthogonal_constraints.
342344
self._native_orthogonal = {}
345+
# Equality constraints of a native setup, as raw data:
346+
# name -> (node points, values, w). See add_equality_constraints.
347+
self._native_equality = {}
343348
# setup_interpolator sets these two values again when it ends.
344349
self._native_setup = False
345350
self._setup_constraint_names = None
@@ -695,33 +700,71 @@ def add_inequality_feature(
695700

696701
def add_equality_constraints(self, node_idx, values, name="undefined"):
697702
"""
698-
Adds hard constraints to the least squares system. For now this just
699-
sets
700-
the node values to be fixed using a lagrangian.
703+
Fix the values of some support nodes.
704+
705+
The constraint is a least-squares row with the weight
706+
EQUALITY_WEIGHT for each node, so it is strong but not exact.
701707
702708
Parameters
703709
----------
704710
node_idx : numpy array/list
705711
int array of node indexes
706712
values : numpy array/list
707713
array of node values
708-
709-
Returns
710-
-------
711-
714+
name : str
715+
name of the constraint
712716
"""
713717
idc = np.asarray(node_idx, dtype=int)
714-
values = np.asarray(values)
718+
values = np.asarray(values, dtype=float)
715719
inside = np.logical_and(idc >= 0, idc < self.dof)
720+
idc, values = idc[inside], values[inside]
721+
if idc.shape[0] == 0:
722+
return
723+
self.up_to_date = False
724+
if getattr(self, "_native_setup", False):
725+
# The native core reads raw data, not sparse rows: a value at a node
726+
# is the same row (see _native._add_data).
727+
self._native_equality[name] = (self.support.nodes[idc], values, EQUALITY_WEIGHT)
728+
return
729+
self.add_constraints_to_least_squares(
730+
np.ones((idc.shape[0], 1)), values, idc[:, None], w=EQUALITY_WEIGHT, name=name
731+
)
716732

717-
self.equal_constraints[name] = {
718-
"A": np.ones(idc[inside].shape[0]),
719-
"B": values[inside],
720-
"col": idc[inside],
721-
# "w": w,
722-
"row": np.arange(self.eq_const_c, self.eq_const_c + idc[inside].shape[0]),
723-
}
724-
self.eq_const_c += idc[inside].shape[0]
733+
def add_gradient_constraints(self, w=1.0):
734+
"""Constrain the direction of the gradient (P1 and P2 supports).
735+
736+
As in the finite difference interpolator, the gradient is made
737+
orthogonal to two vectors in the plane of the data (strike and dip).
738+
Each row has the weight w times the weight column of the data.
739+
"""
740+
points = self.get_gradient_constraints()
741+
if points.shape[0] == 0:
742+
return
743+
d = self.dimensions
744+
grad, elements, inside = self.support.evaluate_shape_derivatives(points[:, :d])
745+
if not np.any(inside):
746+
return
747+
vectors = np.array(points[inside, d : 2 * d], dtype=float)
748+
if d == 2:
749+
directions = [np.column_stack([-vectors[:, 1], vectors[:, 0]])]
750+
else:
751+
directions = [v.T for v in get_vectors(vectors)]
752+
grad = grad[inside]
753+
A = np.vstack([np.einsum("ij,ijk->ik", v, grad) for v in directions])
754+
idc = np.tile(self.support.elements[elements[inside]], (len(directions), 1))
755+
wt = np.tile(w * points[inside, 2 * d], len(directions))
756+
self.add_constraints_to_least_squares(A, np.zeros(A.shape[0]), idc, w=wt, name="gradient")
757+
self.up_to_date = False
758+
759+
def _warn_ignored_data(self, families):
760+
"""Warn when data is set for a family that this interpolator does not use."""
761+
for family in families:
762+
n = self.data[family].shape[0]
763+
if n > 0:
764+
logger.warning(
765+
f"{type(self).__name__} does not use {family} constraints: "
766+
f"{n} {family} points are ignored"
767+
)
725768

726769
def add_tangent_constraints(self, w=1.0):
727770
r"""Adds the constraints :math:`f(X)\cdotT=0`
@@ -737,7 +780,7 @@ def add_tangent_constraints(self, w=1.0):
737780
"""
738781
points = self.get_tangent_constraints()
739782
if points.shape[0] > 0:
740-
self.add_gradient_orthogonal_constraints(points[:, :3], points[:, 3:6], w)
783+
self.add_gradient_orthogonal_constraints(points[:, :3], points[:, 3:6], w * points[:, 6])
741784

742785
def _assemble_explicit_constraint_matrix(self) -> tuple[sparse.spmatrix, np.ndarray]:
743786
"""Stack every recorded explicit constraint (``self.constraints``,
@@ -764,9 +807,7 @@ def _assemble_explicit_constraint_matrix(self) -> tuple[sparse.spmatrix, np.ndar
764807

765808
def build_matrix(self):
766809
"""
767-
Assemble constraints into interpolation matrix. Adds equaltiy
768-
constraints
769-
using lagrange modifiers if necessary
810+
Assemble constraints into interpolation matrix.
770811
771812
Parameters
772813
----------
@@ -890,45 +931,6 @@ def compute_column_scaling_matrix(self, A: sparse.csr_matrix) -> sparse.dia_matr
890931
S = sparse.diags(scaling_factors)
891932
return S
892933

893-
def add_equality_block(self, A, B):
894-
if len(self.equal_constraints) > 0:
895-
ATA = A.T.dot(A)
896-
ATB = A.T.dot(B)
897-
logger.info(f"Equality block is {self.eq_const_c} x {self.dof}")
898-
# solving constrained least squares using
899-
# | ATA CT | |c| = b
900-
# | C 0 | |y| d
901-
# where A is the interpoaltion matrix
902-
# C is the equality constraint matrix
903-
# b is the interpolation constraints to be honoured
904-
# in a least squares sense
905-
# and d are the equality constraints
906-
# c are the node values and y are the
907-
# lagrange multipliers#
908-
a = []
909-
rows = []
910-
cols = []
911-
b = []
912-
for c in self.equal_constraints.values():
913-
b.extend((c["B"]).tolist())
914-
aa = c["A"].flatten()
915-
mask = aa == 0
916-
a.extend(aa[~mask].tolist())
917-
rows.extend(c["row"].flatten()[~mask].tolist())
918-
cols.extend(c["col"].flatten()[~mask].tolist())
919-
920-
C = sparse.coo_matrix(
921-
(np.array(a), (np.array(rows), cols)),
922-
shape=(self.eq_const_c, self.dof),
923-
dtype=float,
924-
).tocsr()
925-
926-
d = np.array(b)
927-
ATA = sparse.bmat([[ATA, C.T], [C, None]])
928-
ATB = np.hstack([ATB, d])
929-
930-
return ATA, ATB
931-
932934
def build_inequality_matrix(self):
933935
mats = []
934936
bounds = []

‎packages/loop_interpolation/src/loop_interpolation/_finite_difference_interpolator.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -408,9 +408,10 @@ def add_gradient_constraints(self, w=1.0):
408408
)
409409
A = np.einsum("ij,ijk->ik", strike_vector.T, T)
410410
B = np.zeros(points[inside, :].shape[0])
411-
self.add_constraints_to_least_squares(A, B, idc[inside, :], w=w, name="gradient")
411+
wt = w * points[inside, 2 * self.support.dimension]
412+
self.add_constraints_to_least_squares(A, B, idc[inside, :], w=wt, name="gradient")
412413
A = np.einsum("ij,ijk->ik", dip_vector.T, T)
413-
self.add_constraints_to_least_squares(A, B, idc[inside, :], w=w, name="gradient")
414+
self.add_constraints_to_least_squares(A, B, idc[inside, :], w=wt, name="gradient")
414415
# self.regularisation_scale += compute_weighting(
415416
# self.support.nodes,
416417
# points[inside, : self.support.dimension],
@@ -565,7 +566,8 @@ def add_gradient_orthogonal_constraints(
565566
# dot product of vector and element gradient = 0
566567
A = np.einsum("ij,ijk->ik", vectors[inside, : self.support.dimension], T)
567568
b_ = np.zeros(np.sum(inside)) + b
568-
self.add_constraints_to_least_squares(A, b_, idc[inside, :], w=w, name=name)
569+
wt = np.broadcast_to(np.asarray(w, dtype=float), (points.shape[0],))[inside]
570+
self.add_constraints_to_least_squares(A, b_, idc[inside, :], w=wt, name=name)
569571

570572
if np.sum(inside) <= 0:
571573
logger.warning(

‎packages/loop_interpolation/src/loop_interpolation/_native.py‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,12 @@
3232
the core weight is ``dxy / 4`` (same for ``dxz`` and ``dyz``).
3333
* Border. ``dx dy dz`` are the same in Python and core.
3434
* Value. Weight is ``cpw * column 4``.
35-
* Gradient (direction only). Weight is ``gpw``. The weight column is NOT
36-
used by Python.
35+
* Gradient (direction only). Weight is ``gpw * column 6``.
3736
* Normal (vector with length). Weight is ``npw / 3 * column 6``. When the
3837
data has no weight column, the column weight is 1.
39-
* Tangent. Weight is ``tpw``. The weight column is NOT used by Python.
38+
* Tangent. Weight is ``tpw * column 6``.
39+
* Equality (``add_equality_constraints``). A value at a support node with
40+
the weight ``EQUALITY_WEIGHT``.
4041
* Interface. Weight is ``ipw`` (one value for all points). The pairing is
4142
"star": each point is paired with the first point of its id group.
4243
* Value inequality. Columns x y z | lower | upper. The weight is 1.
@@ -289,10 +290,10 @@ def _add_data(problem, interpolator) -> None:
289290
w = _weights(_weight(interpolator, "cpw"), value.shape[0]) * value[:, 4]
290291
_add_weighted(problem.add_value, value[:, :3], value[:, 3], w, name="value")
291292

292-
# gradient: weight = gpw (the weight column is not used)
293+
# gradient: weight = gpw * column 6
293294
gradient = _rows(interpolator.get_gradient_constraints())
294295
if gradient.shape[0] > 0:
295-
w = _weights(_weight(interpolator, "gpw"), gradient.shape[0])
296+
w = _weights(_weight(interpolator, "gpw"), gradient.shape[0]) * gradient[:, 6]
296297
_add_weighted(
297298
problem.add_gradient,
298299
gradient[:, :3],
@@ -310,10 +311,10 @@ def _add_data(problem, interpolator) -> None:
310311
w = w * normal[:, 6]
311312
_add_weighted(problem.add_normal, normal[:, :3], normal[:, 3:6], w, name="normal")
312313

313-
# tangent: weight = tpw (the weight column is not used)
314+
# tangent: weight = tpw * column 6
314315
tangent = _rows(interpolator.get_tangent_constraints())
315316
if tangent.shape[0] > 0:
316-
w = _weights(_weight(interpolator, "tpw"), tangent.shape[0])
317+
w = _weights(_weight(interpolator, "tpw"), tangent.shape[0]) * tangent[:, 6]
317318
_add_weighted(
318319
problem.add_tangent,
319320
tangent[:, :3],
@@ -338,6 +339,13 @@ def _add_data(problem, interpolator) -> None:
338339
name=name,
339340
)
340341

342+
# equality constraints of a native setup: a value at a support node
343+
equality = getattr(interpolator, "_native_equality", None)
344+
if not isinstance(equality, dict):
345+
equality = {}
346+
for name, (points, values, w) in equality.items():
347+
_add_weighted(problem.add_value, points, values, _weights(w, points.shape[0]), name=name)
348+
341349
# interface: one weight (ipw)
342350
interface = _rows(interpolator.get_interface_constraints())
343351
if interface.shape[0] > 1:

‎packages/loop_interpolation/src/loop_interpolation/_p1interpolator.py‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -67,18 +67,13 @@ def _update_regularisation_scale_from_norm_constraints(self):
6767
sigma=sigma,
6868
)
6969

70-
def add_gradient_constraints(self, w=1.0):
71-
pass
72-
7370
def add_norm_constraints(self, w=1.0):
7471
points = self.get_norm_constraints()
7572
if points.shape[0] > 0:
7673
grad, elements, inside = self.support.evaluate_shape_derivatives(
7774
points[:, : self.dimensions]
7875
)
79-
size = self.support.element_scale[elements[inside]]
80-
wt = np.ones(size.shape[0])
81-
wt *= w # s* size
76+
wt = w * points[inside, self.dimensions * 2]
8277
elements = np.tile(self.support.elements[elements[inside]], (self.dimensions, 1, 1))
8378

8479
elements = elements.swapaxes(0, 1)
@@ -99,10 +94,7 @@ def add_value_constraints(self, w=1.0):
9994
points = self.get_value_constraints()
10095
if points.shape[0] > 0:
10196
N, elements, inside = self.support.evaluate_shape(points[:, : self.dimensions])
102-
size = self.support.element_size[elements[inside]]
103-
104-
wt = np.ones(size.shape[0])
105-
wt *= w # * size
97+
wt = w * points[inside, self.dimensions + 1]
10698
self.add_constraints_to_least_squares(
10799
N[inside, :],
108100
points[inside, self.dimensions],
@@ -243,8 +235,12 @@ def setup_interpolator(self, **kwargs):
243235
self.add_value_constraints(self.interpolation_weights["cpw"])
244236
self.add_tangent_constraints(self.interpolation_weights["tpw"])
245237
self.add_value_inequality_constraints()
246-
self.add_inequality_pairs_constraints()
247-
# self.add_interface_constraints(self.interpolation_weights["ipw"])
238+
self.add_inequality_pairs_constraints(
239+
pairs=kwargs.get("inequality_pairs", None),
240+
upper_bound=kwargs.get("inequality_pair_upper_bound", np.finfo(float).eps),
241+
lower_bound=kwargs.get("inequality_pair_lower_bound", -np.inf),
242+
)
243+
self._warn_ignored_data(("interface",))
248244
return self.finalize_setup_diagnostics_report()
249245

250246
def add_gradient_orthogonal_constraints(
@@ -276,8 +272,7 @@ def add_gradient_orthogonal_constraints(
276272
points[:, : self.dimensions]
277273
)
278274
size = self.support.element_size[elements[inside]]
279-
wt = np.ones(size.shape[0])
280-
wt *= w * size
275+
wt = np.broadcast_to(np.asarray(w, dtype=float), (points.shape[0],))[inside] * size
281276
elements = self.support.elements[elements[inside], :]
282277
# elements = np.tile(self.support.elements[elements[inside]], (3, 1, 1))
283278

0 commit comments

Comments
 (0)