Skip to content
Open
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
5 changes: 2 additions & 3 deletions LoopStructural/modelling/features/builders/_fault_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand All @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -319,7 +320,8 @@ def clear_constraints(self):
"""
self.constraints = {}
self.ineq_constraints = {}
self.equal_constraints = {}
self._native_orthogonal = {}
self._native_equality = {}

def reset(self):
"""
Expand All @@ -330,6 +332,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
Expand Down Expand Up @@ -685,33 +690,71 @@ 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
----------
node_idx : numpy array/list
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`
Expand All @@ -727,7 +770,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``,
Expand All @@ -754,9 +797,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
----------
Expand Down Expand Up @@ -880,45 +921,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 = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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(
Expand Down
22 changes: 15 additions & 7 deletions packages/loop_interpolation/src/loop_interpolation/_native.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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],
Expand All @@ -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],
Expand All @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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],
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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))

Expand Down
Loading
Loading