loop-interpolation 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. loop_interpolation/__init__.py +152 -0
  2. loop_interpolation/_builders.py +149 -0
  3. loop_interpolation/_constant_norm.py +232 -0
  4. loop_interpolation/_diagnostics.py +102 -0
  5. loop_interpolation/_discrete_fold_interpolator.py +242 -0
  6. loop_interpolation/_discrete_interpolator.py +1405 -0
  7. loop_interpolation/_fd_fold_interpolator.py +237 -0
  8. loop_interpolation/_finite_difference_interpolator.py +1348 -0
  9. loop_interpolation/_fold_event.py +185 -0
  10. loop_interpolation/_fold_norm_alignment.py +118 -0
  11. loop_interpolation/_fold_setup.py +39 -0
  12. loop_interpolation/_geological_interpolator.py +920 -0
  13. loop_interpolation/_interpolator_builder.py +251 -0
  14. loop_interpolation/_interpolator_factory.py +167 -0
  15. loop_interpolation/_interpolatortype.py +20 -0
  16. loop_interpolation/_operator.py +44 -0
  17. loop_interpolation/_p1interpolator.py +299 -0
  18. loop_interpolation/_p2interpolator.py +317 -0
  19. loop_interpolation/_regularisation.py +110 -0
  20. loop_interpolation/_solver_pipeline.py +138 -0
  21. loop_interpolation/_solver_strategy.py +218 -0
  22. loop_interpolation/_surfe_wrapper.py +211 -0
  23. loop_interpolation/_svariogram.py +133 -0
  24. loop_interpolation/_validation.py +604 -0
  25. loop_interpolation/constraints.py +473 -0
  26. loop_interpolation/fold_function/__init__.py +39 -0
  27. loop_interpolation/fold_function/_base_fold_rotation_angle.py +219 -0
  28. loop_interpolation/fold_function/_fourier_series_fold_rotation_angle.py +131 -0
  29. loop_interpolation/fold_function/_lambda_fold_rotation_angle.py +53 -0
  30. loop_interpolation/loopsolver/__init__.py +2 -0
  31. loop_interpolation/loopsolver/admm_constant_norm.py +118 -0
  32. loop_interpolation/loopsolver/admm_method.py +25 -0
  33. loop_interpolation/loopsolver/admm_solver.py +463 -0
  34. loop_interpolation/loopsolver/version.py +1 -0
  35. loop_interpolation-0.0.1.dist-info/METADATA +34 -0
  36. loop_interpolation-0.0.1.dist-info/RECORD +39 -0
  37. loop_interpolation-0.0.1.dist-info/WHEEL +5 -0
  38. loop_interpolation-0.0.1.dist-info/licenses/LICENSE +21 -0
  39. loop_interpolation-0.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1348 @@
1
+ """
2
+ FiniteDifference interpolator
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import numpy as np
7
+ from loop_common.logging import get_logger as getLogger
8
+ from loop_common.math import get_vectors
9
+ from scipy import ndimage, signal
10
+ from scipy.sparse.linalg import LinearOperator
11
+ from scipy.spatial import KDTree
12
+
13
+ from ._discrete_interpolator import DiscreteInterpolator
14
+ from ._interpolatortype import InterpolatorType
15
+ from ._operator import Operator
16
+
17
+ logger = getLogger(__name__)
18
+
19
+ # The six interior second-derivative stencil families that qualify for the
20
+ # fused single-kernel CG regularisation fast path (see
21
+ # `FiniteDifferenceInterpolator._build_fused_cg_regularisation_operator`).
22
+ # Keyed by the family name `setup_interpolator`/`support.get_operators` use.
23
+ _FUSED_FAMILY_MASKS = {
24
+ "dxx": Operator.Dxx_mask,
25
+ "dyy": Operator.Dyy_mask,
26
+ "dzz": Operator.Dzz_mask,
27
+ "dxy": Operator.Dxy_mask,
28
+ "dxz": Operator.Dxz_mask,
29
+ "dyz": Operator.Dyz_mask,
30
+ }
31
+
32
+
33
+ def _normalised_mask_xyz(mask: np.ndarray) -> np.ndarray:
34
+ """(3,3,3) mask in the Operator's native (z,y,x) index order -> normalised
35
+ (unit L2 norm over nonzero taps) mask in (x,y,z) order, i.e. matching
36
+ ``arr.reshape((nx, ny, nz), order='F')`` (axis0=x, axis1=y, axis2=z)."""
37
+ mask = np.asarray(mask, dtype=float)
38
+ active = mask != 0
39
+ norm = np.linalg.norm(mask[active])
40
+ mask_norm = mask / norm if norm > 0 else mask.copy()
41
+ return np.ascontiguousarray(mask_norm.transpose(2, 1, 0))
42
+
43
+
44
+ def _composite_kernel(mask_xyz: np.ndarray) -> np.ndarray:
45
+ """Autocorrelation of a (3,3,3) kernel -> (5,5,5) symmetric composite
46
+ kernel representing "correlate then convolve with the same kernel", i.e.
47
+ one application of ``rmatvec(matvec(x))`` for a single translation-
48
+ invariant stencil family, away from any domain boundary."""
49
+ return signal.correlate(mask_xyz, mask_xyz, mode="full")
50
+
51
+
52
+ def _dist_to_true_edge(nx: int, ny: int, nz: int) -> np.ndarray:
53
+ """For every dof (F-order flat index, ``gi = i + nx*j + nx*ny*k``), the
54
+ minimum number of grid steps to the nearest TRUE domain edge along any
55
+ axis (0 for the outermost node layer, 1 for the next layer in, ...)."""
56
+ xi = np.arange(nx)
57
+ yi = np.arange(ny)
58
+ zi = np.arange(nz)
59
+ dx = np.minimum(xi, nx - 1 - xi)
60
+ dy = np.minimum(yi, ny - 1 - yi)
61
+ dz = np.minimum(zi, nz - 1 - zi)
62
+ d = np.minimum(np.minimum(dx[:, None, None], dy[None, :, None]), dz[None, None, :])
63
+ return d.ravel(order="F")
64
+
65
+
66
+ def compute_weighting(grid_points, gradient_constraint_points, alpha=10.0, sigma=1.0):
67
+ """
68
+ Compute weights for second derivative regularization based on proximity to gradient constraints.
69
+
70
+ Parameters:
71
+ grid_points (ndarray): (N, 3) array of 3D coordinates for grid cells.
72
+ gradient_constraint_points (ndarray): (M, 3) array of 3D coordinates for gradient constraints.
73
+ alpha (float): Strength of weighting increase.
74
+ sigma (float): Decay parameter for Gaussian-like influence.
75
+
76
+ Returns:
77
+ weights (ndarray): (N,) array of weights for each grid point.
78
+ """
79
+ # Build a KDTree with the gradient constraint locations
80
+ tree = KDTree(gradient_constraint_points)
81
+
82
+ # Find the distance from each grid point to the nearest gradient constraint
83
+ distances, _ = tree.query(grid_points, k=1)
84
+
85
+ # Compute weighting function (higher weight for nearby points)
86
+ weights = 1 + alpha * np.exp(-(distances**2) / (2 * sigma**2))
87
+
88
+ return weights
89
+
90
+
91
+ class FiniteDifferenceInterpolator(DiscreteInterpolator):
92
+ def __init__(self, grid, data=None):
93
+ """
94
+ Finite difference interpolation on a regular cartesian grid
95
+
96
+ Parameters
97
+ ----------
98
+ grid : StructuredGrid
99
+ """
100
+ self.shape = "rectangular"
101
+ DiscreteInterpolator.__init__(self, grid, data=data)
102
+ self.set_interpolation_weights(
103
+ {
104
+ "dxy": 1.0,
105
+ "dyz": 1.0,
106
+ "dxz": 1.0,
107
+ "dxx": 1.0,
108
+ "dyy": 1.0,
109
+ "dzz": 1.0,
110
+ "dx": 1.0,
111
+ "dy": 1.0,
112
+ "dz": 1.0,
113
+ "cpw": 1.0,
114
+ "gpw": 1.0,
115
+ "npw": 10.0,
116
+ "tpw": 1.0,
117
+ "ipw": 1.0,
118
+ }
119
+ )
120
+
121
+ self.type = InterpolatorType.FINITE_DIFFERENCE
122
+ self.use_regularisation_weight_scale = False
123
+ self.regularisation_weight_sigma = None
124
+ self.interface_pair_mode = "auto"
125
+ self.interface_pair_threshold = 200
126
+ self.interface_pair_fallback = "star"
127
+ # Matrix-free regularisation (opt-in, StructuredGrid mask-based path only).
128
+ # See `_assemble_operator` / `get_regularisation_linear_operator`.
129
+ self.regularisation_matrix_free = False
130
+ self.matrix_free_regularisation_blocks: dict = {}
131
+
132
+ def setup_interpolator(self, **kwargs):
133
+ """
134
+
135
+ Parameters
136
+ ----------
137
+ kwargs
138
+ possible kwargs are weights for the different masks and masks.
139
+
140
+ Notes
141
+ -----
142
+ Default masks are the second derivative in x,y,z direction and the second
143
+ derivative of x wrt y and y wrt z and z wrt x. Custom masks can be used
144
+ by specifying the operator as a 3d numpy array
145
+ e.g. [ [ [ 0 0 0 ]
146
+ [ 0 1 0 ]
147
+ [ 0 0 0 ] ]
148
+ [ [ 1 1 1 ]
149
+ [ 1 1 1 ]
150
+ [ 1 1 1 ] ]
151
+ [ [ 0 0 0 ]
152
+ [ 0 1 0 ]
153
+ [ 0 0 0 ] ]
154
+
155
+ Returns
156
+ -------
157
+
158
+ """
159
+ self.reset()
160
+ regularisation_config = self.resolve_regularisation_config(
161
+ regularisation=kwargs.get("regularisation", None),
162
+ directional_regularisation=kwargs.get("directional_regularisation", None),
163
+ )
164
+ self._apply_isotropic_regularisation_weight(
165
+ regularisation_config.isotropic,
166
+ ("dxy", "dyz", "dxz", "dxx", "dyy", "dzz"),
167
+ )
168
+ self._apply_interpolation_weight_kwargs(
169
+ kwargs,
170
+ skip_keys=("regularisation", "directional_regularisation"),
171
+ )
172
+ # either use the default operators or the ones passed to the function
173
+ operators = kwargs.get(
174
+ "operators", self.support.get_operators(weights=self.interpolation_weights)
175
+ )
176
+
177
+ self.use_regularisation_weight_scale = kwargs.get("use_regularisation_weight_scale", False)
178
+ self.regularisation_weight_sigma = kwargs.get("regularisation_weight_sigma", None)
179
+ self.matrix_free_regularisation_blocks = {}
180
+ self.regularisation_matrix_free = bool(kwargs.get("regularisation_matrix_free", False))
181
+ if self.regularisation_matrix_free and self.apply_scaling_matrix:
182
+ logger.warning(
183
+ "regularisation_matrix_free=True was requested together with "
184
+ "apply_scaling_matrix=True. compute_column_scaling_matrix() needs an explicit "
185
+ "sparse matrix (it computes per-column norms) and cannot operate on a matrix-free "
186
+ "LinearOperator, so the structured-grid regularisation stencils will fall back to "
187
+ "the explicit assembly path. Set apply_scaling_matrix=False to use the matrix-free "
188
+ "path instead."
189
+ )
190
+ self.regularisation_matrix_free = False
191
+ elif self.regularisation_matrix_free:
192
+ logger.warning(
193
+ "regularisation_matrix_free=True: the structured-grid regularisation stencils "
194
+ "(dxx, dyy, dzz, dxy, dxz, dyz and the border second-derivative terms) will be "
195
+ "assembled as matrix-free LinearOperator blocks (self.matrix_free_regularisation_blocks, "
196
+ "get_regularisation_linear_operator()) instead of explicit sparse matrices. "
197
+ "build_matrix()/solve_system() combine these blocks with the explicit data-constraint "
198
+ "matrix into a single LinearOperator for the 'cg' and 'lsmr' solvers. 'admm' cannot "
199
+ "consume a LinearOperator and will fall back to explicit regularisation assembly "
200
+ "(with a warning) for that solve."
201
+ )
202
+ self.interface_pair_mode = kwargs.get("interface_pair_mode", self.interface_pair_mode)
203
+ self.interface_pair_threshold = int(
204
+ kwargs.get("interface_pair_threshold", self.interface_pair_threshold)
205
+ )
206
+ self.interface_pair_fallback = kwargs.get(
207
+ "interface_pair_fallback", self.interface_pair_fallback
208
+ )
209
+ self.add_norm_constraints(self.interpolation_weights["npw"])
210
+ self.add_gradient_constraints(self.interpolation_weights["gpw"])
211
+ self.add_value_constraints(self.interpolation_weights["cpw"])
212
+ self.add_tangent_constraints(self.interpolation_weights["tpw"])
213
+ self.add_interface_constraints(self.interpolation_weights["ipw"])
214
+ self.add_value_inequality_constraints()
215
+ self.add_inequality_pairs_constraints(
216
+ pairs=kwargs.get("inequality_pairs", None),
217
+ upper_bound=kwargs.get("inequality_pair_upper_bound", np.finfo(float).eps),
218
+ lower_bound=kwargs.get("inequality_pair_lower_bound", -np.inf),
219
+ )
220
+ for k, o in operators.items():
221
+ self.assemble_inner(o[0], o[1], name=k)
222
+ self.add_directional_regularisation(regularisation_config.directional)
223
+ self.assemble_borders()
224
+ return self.finalize_setup_diagnostics_report()
225
+
226
+ def copy(self):
227
+ """
228
+ Create a new identical interpolator
229
+
230
+ Returns
231
+ -------
232
+ returns a new empy interpolator from the same support
233
+ """
234
+ return FiniteDifferenceInterpolator(self.support)
235
+
236
+ def add_value_constraints(self, w=1.0):
237
+ """
238
+
239
+ Parameters
240
+ ----------
241
+ w : double or numpy array
242
+
243
+ Returns
244
+ -------
245
+
246
+ """
247
+
248
+ points = self.get_value_constraints()
249
+ # check that we have added some points
250
+ if points.shape[0] > 0:
251
+ node_idx, inside = self.support.position_to_cell_corners(
252
+ points[:, : self.support.dimension]
253
+ )
254
+ idc = np.asarray(node_idx, dtype=int)
255
+ a = self.support.position_to_dof_coefs(points[inside, : self.support.dimension])
256
+ # a *= w
257
+ # a/=self.support.enp.product(self.support.step_vector)
258
+ self.add_constraints_to_least_squares(
259
+ a,
260
+ points[inside, self.support.dimension],
261
+ idc[inside, :],
262
+ w=w * points[inside, self.support.dimension + 1],
263
+ name="value",
264
+ )
265
+ if np.sum(inside) <= 0:
266
+ logger.warning(
267
+ f"{np.sum(~inside)} \
268
+ value constraints not added: outside of model bounding box"
269
+ )
270
+
271
+ def _interface_pair_indices(self, n: int) -> np.ndarray:
272
+ """Return index pairs for interface constraints with scalable defaults."""
273
+ if n < 2:
274
+ return np.zeros((0, 2), dtype=int)
275
+
276
+ mode = str(self.interface_pair_mode).lower()
277
+ threshold = max(2, int(self.interface_pair_threshold))
278
+ fallback = str(self.interface_pair_fallback).lower()
279
+ if fallback not in ("star", "chain"):
280
+ fallback = "star"
281
+
282
+ if mode == "auto":
283
+ mode = fallback if n > threshold else "all"
284
+
285
+ if mode == "all":
286
+ ii, jj = np.triu_indices(n, k=1)
287
+ return np.column_stack([ii, jj]).astype(int)
288
+ if mode == "star":
289
+ return np.column_stack([np.zeros(n - 1, dtype=int), np.arange(1, n, dtype=int)])
290
+ if mode == "chain":
291
+ return np.column_stack([np.arange(0, n - 1, dtype=int), np.arange(1, n, dtype=int)])
292
+
293
+ raise ValueError(
294
+ f"Unknown interface_pair_mode '{self.interface_pair_mode}'. Use one of: auto, all, star, chain"
295
+ )
296
+
297
+ def add_interface_constraints(self, w=1.0):
298
+ """
299
+ Adds a constraint that defines all points
300
+ with the same 'id' to be the same value
301
+ Sets all P1-P2 = 0 for all pairs of points
302
+
303
+ Parameters
304
+ ----------
305
+ w : double
306
+ weight
307
+
308
+ Returns
309
+ -------
310
+
311
+ """
312
+ # get elements for points
313
+ points = self.get_interface_constraints()
314
+ if points.shape[0] > 1:
315
+ node_idx, inside = self.support.position_to_cell_corners(
316
+ points[:, : self.support.dimension]
317
+ )
318
+ idc = np.asarray(node_idx, dtype=int)[inside, :]
319
+ A = self.support.position_to_dof_coefs(points[inside, : self.support.dimension])
320
+ for unique_id in np.unique(
321
+ points[
322
+ np.logical_and(~np.isnan(points[:, self.support.dimension]), inside),
323
+ self.support.dimension,
324
+ ]
325
+ ):
326
+ mask = points[inside, self.support.dimension] == unique_id
327
+ pair_idx = self._interface_pair_indices(int(np.sum(mask)))
328
+ if pair_idx.shape[0] == 0:
329
+ continue
330
+ interface_A = np.hstack([A[mask, :][pair_idx[:, 0], :], -A[mask, :][pair_idx[:, 1], :]])
331
+ interface_idc = np.hstack(
332
+ [idc[mask, :][pair_idx[:, 0], :], idc[mask, :][pair_idx[:, 1], :]]
333
+ )
334
+ self.add_constraints_to_least_squares(
335
+ interface_A,
336
+ np.zeros(interface_A.shape[0]),
337
+ interface_idc,
338
+ w=w,
339
+ name=f"interface_{unique_id}",
340
+ )
341
+
342
+ def add_gradient_constraints(self, w=1.0):
343
+ """
344
+
345
+ Parameters
346
+ ----------
347
+ w : double / numpy array
348
+
349
+ Returns
350
+ -------
351
+
352
+ """
353
+
354
+ points = self.get_gradient_constraints()
355
+ if points.shape[0] > 0:
356
+ # calculate unit vector for orientation data
357
+
358
+ node_idx, inside = self.support.position_to_cell_corners(
359
+ points[:, : self.support.dimension]
360
+ )
361
+ # calculate unit vector for node gradients
362
+ # this means we are only constraining direction of grad not the
363
+ # magnitude
364
+ idc = np.asarray(node_idx, dtype=int)
365
+
366
+ (
367
+ _vertices,
368
+ T,
369
+ _elements,
370
+ _inside,
371
+ ) = self.support.get_element_gradient_for_location(
372
+ points[inside, : self.support.dimension]
373
+ )
374
+ # normalise constraint vector and scale element matrix by this
375
+ norm = np.linalg.norm(
376
+ points[:, self.support.dimension : self.support.dimension + self.support.dimension],
377
+ axis=1,
378
+ )
379
+ points[:, 3:6] /= norm[:, None]
380
+ T /= norm[inside, None, None]
381
+ # calculate two orthogonal vectors to constraint (strike and dip vector)
382
+ strike_vector, dip_vector = get_vectors(
383
+ points[
384
+ inside, self.support.dimension : self.support.dimension + self.support.dimension
385
+ ]
386
+ )
387
+ A = np.einsum("ij,ijk->ik", strike_vector.T, T)
388
+ B = np.zeros(points[inside, :].shape[0])
389
+ self.add_constraints_to_least_squares(A, B, idc[inside, :], w=w, name="gradient")
390
+ A = np.einsum("ij,ijk->ik", dip_vector.T, T)
391
+ self.add_constraints_to_least_squares(A, B, idc[inside, :], w=w, name="gradient")
392
+ # self.regularisation_scale += compute_weighting(
393
+ # self.support.nodes,
394
+ # points[inside, : self.support.dimension],
395
+ # sigma=self.support.nsteps[0] * 10,
396
+ # )
397
+ if np.sum(inside) <= 0:
398
+ logger.warning(
399
+ f" {np.sum(~inside)} \
400
+ norm constraints not added: outside of model bounding box"
401
+ )
402
+
403
+ def add_norm_constraints(self, w=1.0):
404
+ """
405
+ Add constraints to control the norm of the gradient of the scalar field
406
+
407
+ Parameters
408
+ ----------
409
+ w : double
410
+ weighting of this constraint (double)
411
+
412
+ Returns
413
+ -------
414
+
415
+ """
416
+ points = self.get_norm_constraints()
417
+ if points.shape[0] > 0:
418
+ # calculate unit vector for orientation data
419
+ # points[:,3:]/=np.linalg.norm(points[:,3:],axis=1)[:,None]
420
+ node_idx, inside = self.support.position_to_cell_corners(
421
+ points[:, : self.support.dimension]
422
+ )
423
+ idc = np.asarray(node_idx, dtype=int)
424
+
425
+ # calculate unit vector for node gradients and their magnitudes
426
+ # to preserve magnitude enforcement across the split 3-component constraint
427
+ (
428
+ _vertices,
429
+ T,
430
+ _elements,
431
+ _inside,
432
+ ) = self.support.get_element_gradient_for_location(
433
+ points[inside, : self.support.dimension]
434
+ )
435
+
436
+ sigma = self.regularisation_weight_sigma
437
+ if sigma is None:
438
+ sigma = self.support.nsteps[0] * 10
439
+
440
+ self.regularisation_scale += compute_weighting(
441
+ self.support.nodes,
442
+ points[inside, : self.support.dimension],
443
+ sigma=sigma,
444
+ )
445
+ # Apply optional per-constraint weights from the points array.
446
+ # For normal constraints, row format is xyz|nx ny nz|w.
447
+ point_weights = np.ones(np.sum(inside), dtype=float)
448
+ if points.shape[1] > self.support.dimension * 2:
449
+ point_weights = points[inside, self.support.dimension * 2]
450
+
451
+ # Each normal constraint is split into one row per axis below, so
452
+ # divide by the number of axes here - otherwise a single
453
+ # orientation point ends up weighted `dimension` times more
454
+ # strongly than the same-`w` value/gradient constraints, enough
455
+ # to dominate the least-squares system when data is sparse.
456
+ w = w / self.support.dimension
457
+ if isinstance(w, np.ndarray):
458
+ constraint_weights = w[inside] * point_weights
459
+ else:
460
+ constraint_weights = float(w) * point_weights
461
+
462
+ for d in range(self.support.dimension):
463
+ self.add_constraints_to_least_squares(
464
+ T[:, d, :],
465
+ points[inside, self.support.dimension + d],
466
+ idc[inside, :],
467
+ w=constraint_weights,
468
+ name=f"norm_{d}",
469
+ )
470
+
471
+ if np.sum(inside) <= 0:
472
+ logger.warning(
473
+ f"{np.sum(~inside)} \
474
+ norm constraints not added: outside of model bounding box"
475
+ )
476
+ self.up_to_date = False
477
+
478
+ def add_gradient_orthogonal_constraints(
479
+ self,
480
+ points: np.ndarray,
481
+ vectors: np.ndarray,
482
+ w: float = 1.0,
483
+ b: float = 0,
484
+ name="gradient orthogonal",
485
+ ):
486
+ """
487
+ constraints scalar field to be orthogonal to a given vector
488
+
489
+ Parameters
490
+ ----------
491
+ points : np.darray
492
+ location to add gradient orthogonal constraint
493
+ vector : np.darray
494
+ vector to be orthogonal to, should be the same shape as points
495
+ w : double
496
+ B : np.array
497
+
498
+ Returns
499
+ -------
500
+
501
+ """
502
+ if points.shape[0] > 0:
503
+ # calculate unit vector for orientation data
504
+ node_idx, inside = self.support.position_to_cell_corners(
505
+ points[:, : self.support.dimension]
506
+ )
507
+ # calculate unit vector for node gradients
508
+ # this means we are only constraining direction of grad not the
509
+ # magnitude
510
+ idc = np.asarray(node_idx, dtype=int)
511
+ # normalise vector and scale element gradient matrix by norm as well
512
+ norm = np.linalg.norm(vectors, axis=1)
513
+ vectors[norm > 0, :] /= norm[norm > 0, None]
514
+
515
+ # normalise element vector to unit vector for dot product
516
+ (
517
+ _vertices,
518
+ T,
519
+ _elements,
520
+ _inside,
521
+ ) = self.support.get_element_gradient_for_location(
522
+ points[inside, : self.support.dimension]
523
+ )
524
+ # norm_inside indexes norm over the inside-filtered subset so
525
+ # the boolean mask aligns with T (shape n_inside x ...).
526
+ norm_inside = norm[inside]
527
+ T[norm_inside > 0, :, :] /= norm_inside[norm_inside > 0, None, None]
528
+
529
+ # dot product of vector and element gradient = 0
530
+ A = np.einsum("ij,ijk->ik", vectors[inside, : self.support.dimension], T)
531
+ b_ = np.zeros(np.sum(inside)) + b
532
+ self.add_constraints_to_least_squares(A, b_, idc[inside, :], w=w, name=name)
533
+
534
+ if np.sum(inside) <= 0:
535
+ logger.warning(
536
+ f"{np.sum(~inside)} \
537
+ gradient constraints not added: outside of model bounding box"
538
+ )
539
+ self.up_to_date = False
540
+
541
+ def _full_neighbour_mask(self):
542
+ if self.support.dimension == 2:
543
+ return np.array([[-1, 0, 1, -1, 0, 1, -1, 0, 1], [1, 1, 1, 0, 0, 0, -1, -1, -1]])
544
+ return np.array(
545
+ [
546
+ [
547
+ -1,
548
+ 0,
549
+ 1,
550
+ -1,
551
+ 0,
552
+ 1,
553
+ -1,
554
+ 0,
555
+ 1,
556
+ -1,
557
+ 0,
558
+ 1,
559
+ -1,
560
+ 0,
561
+ 1,
562
+ -1,
563
+ 0,
564
+ 1,
565
+ -1,
566
+ 0,
567
+ 1,
568
+ -1,
569
+ 0,
570
+ 1,
571
+ -1,
572
+ 0,
573
+ 1,
574
+ ],
575
+ [
576
+ -1,
577
+ -1,
578
+ -1,
579
+ 0,
580
+ 0,
581
+ 0,
582
+ 1,
583
+ 1,
584
+ 1,
585
+ -1,
586
+ -1,
587
+ -1,
588
+ 0,
589
+ 0,
590
+ 0,
591
+ 1,
592
+ 1,
593
+ 1,
594
+ -1,
595
+ -1,
596
+ -1,
597
+ 0,
598
+ 0,
599
+ 0,
600
+ 1,
601
+ 1,
602
+ 1,
603
+ ],
604
+ [
605
+ -1,
606
+ -1,
607
+ -1,
608
+ -1,
609
+ -1,
610
+ -1,
611
+ -1,
612
+ -1,
613
+ -1,
614
+ 0,
615
+ 0,
616
+ 0,
617
+ 0,
618
+ 0,
619
+ 0,
620
+ 0,
621
+ 0,
622
+ 0,
623
+ 1,
624
+ 1,
625
+ 1,
626
+ 1,
627
+ 1,
628
+ 1,
629
+ 1,
630
+ 1,
631
+ 1,
632
+ ],
633
+ ]
634
+ )
635
+
636
+ def _boundary_indexes(self, axis, upper=False):
637
+ if self.support.nsteps[axis] < 3:
638
+ return None
639
+ indexes = self.support.global_index_to_node_index(np.arange(self.support.n_nodes))
640
+ boundary_index = self.support.nsteps[axis] - 2 if upper else 1
641
+ return indexes[indexes[:, axis] == boundary_index, :].T
642
+
643
+ def _assemble_operator(self, operator, w, name="regularisation", indexes=None):
644
+ active = operator.flatten() != 0
645
+ if not np.any(active):
646
+ return
647
+
648
+ full_mask = self._full_neighbour_mask()
649
+ active_mask = full_mask[:, active]
650
+ operator_values = operator.flatten()[active]
651
+
652
+ neighbour_kwargs = {"mask": active_mask}
653
+ if indexes is not None:
654
+ neighbour_kwargs["indexes"] = indexes
655
+ global_indexes = self.support.neighbour_global_indexes(**neighbour_kwargs)
656
+ if global_indexes is None or global_indexes.size == 0:
657
+ return
658
+
659
+ centre_kwargs = {"mask": np.zeros((self.support.dimension, 1), dtype=int)}
660
+ if indexes is not None:
661
+ centre_kwargs["indexes"] = indexes
662
+ centre_indexes = self.support.neighbour_global_indexes(**centre_kwargs)
663
+
664
+ idc = global_indexes.T
665
+
666
+ centre_idc = centre_indexes.T[:, 0]
667
+
668
+ row_w = (
669
+ self.regularisation_scale[centre_idc.astype(int)] * w
670
+ if self.use_regularisation_weight_scale
671
+ else w
672
+ )
673
+
674
+ if self.regularisation_matrix_free:
675
+ self._store_matrix_free_regularisation_block(
676
+ name=name,
677
+ idc=idc,
678
+ operator_values=operator_values,
679
+ row_w=row_w,
680
+ centre_idc=centre_idc,
681
+ )
682
+ return
683
+
684
+ a = np.tile(operator_values, (global_indexes.shape[1], 1))
685
+ B = np.zeros(global_indexes.shape[1])
686
+ self.add_constraints_to_least_squares(
687
+ a,
688
+ B,
689
+ idc,
690
+ w=row_w,
691
+ name=name,
692
+ )
693
+
694
+ def _store_matrix_free_regularisation_block(
695
+ self,
696
+ name: str,
697
+ idc: np.ndarray,
698
+ operator_values: np.ndarray,
699
+ row_w,
700
+ centre_idc: np.ndarray | None = None,
701
+ ) -> None:
702
+ """Record a matrix-free regularisation block for one stencil family.
703
+
704
+ Mirrors the row-normalisation that ``add_constraints_to_least_squares``
705
+ applies (dividing each row by its L2 norm) so that the stored block is
706
+ numerically equivalent to the ``coo_matrix`` that would otherwise be
707
+ built for this family, without ever materialising it.
708
+
709
+ Parameters
710
+ ----------
711
+ name : str
712
+ Family name (e.g. ``"dxx"``, ``"dx_lower"``); used as the key in
713
+ ``self.matrix_free_regularisation_blocks``.
714
+ idc : np.ndarray
715
+ (n_rows, n_active_offsets) global column indices, one row per
716
+ interior/boundary grid node.
717
+ operator_values : np.ndarray
718
+ (n_active_offsets,) nonzero stencil coefficients, shared by every
719
+ row (uniform-spacing StructuredGrid).
720
+ row_w : float or np.ndarray
721
+ Scalar or per-row weight (as computed for ``add_constraints_to_least_squares``).
722
+ centre_idc : np.ndarray, optional
723
+ (n_rows,) global dof index of the stencil's centre node for each
724
+ row (i.e. the grid node the constraint is "centred" on). Only used
725
+ by the CG matrix-free-regularisation fused fast path (see
726
+ ``_build_fused_cg_regularisation_operator``) to identify rows near
727
+ the true domain boundary; harmless to omit for callers that don't
728
+ need it (e.g. border second-derivative families).
729
+ """
730
+ idc = np.asarray(idc, dtype=np.int64)
731
+ n_rows = idc.shape[0]
732
+ if n_rows == 0:
733
+ return
734
+
735
+ norm = np.linalg.norm(operator_values)
736
+ values = (operator_values / norm if norm > 0 else operator_values).astype(float)
737
+
738
+ if isinstance(row_w, np.ndarray):
739
+ row_w_arr = np.asarray(row_w, dtype=float)
740
+ if row_w_arr.shape[0] != n_rows:
741
+ row_w_arr = np.broadcast_to(row_w_arr, (n_rows,)).copy()
742
+ else:
743
+ row_w_arr = np.full(n_rows, float(row_w))
744
+
745
+ base_name = name
746
+ count = 0
747
+ while name in self.matrix_free_regularisation_blocks:
748
+ name = f"{base_name}_{count}"
749
+ count += 1
750
+
751
+ block = {
752
+ "idc": idc,
753
+ "values": values,
754
+ "w": row_w_arr,
755
+ }
756
+ if centre_idc is not None:
757
+ block["centre_idc"] = np.asarray(centre_idc, dtype=np.int64).reshape(-1)
758
+ self.matrix_free_regularisation_blocks[name] = block
759
+
760
+ def _matrix_free_operator_from_blocks(self, blocks) -> LinearOperator:
761
+ """Build a single ``LinearOperator`` from a list of regularisation blocks.
762
+
763
+ Each block is a dict with ``idc`` (n_rows, n_offsets), ``values``
764
+ (n_offsets,) and ``w`` (n_rows,), as produced by
765
+ ``_store_matrix_free_regularisation_block``. Blocks are stacked along
766
+ the row axis (equivalent to ``sparse.vstack`` of each family's
767
+ weighted matrix in ``build_matrix``).
768
+
769
+ ``matvec`` keeps the original per-family dense gather: within one
770
+ family every row has the same number of stencil offsets, so
771
+ ``values[None, :] * x[idc]`` followed by ``.sum(axis=1)`` is a
772
+ rectangular, fully vectorised reduction with no index collisions to
773
+ worry about - profiling showed this was already competitive with the
774
+ explicit CSR matvec and looping over the (small, fixed) number of
775
+ families adds negligible overhead.
776
+
777
+ ``rmatvec`` is different: multiple rows can scatter into the *same*
778
+ column (neighbouring grid nodes share stencil columns), so the
779
+ reduction is a genuine scatter-add. The original implementation used
780
+ ``np.add.at`` once per family, which is a known-slow path in numpy (it
781
+ cannot vectorise internally because of possible index collisions).
782
+ Profiling this class of family (many rows, few offsets per row, uniform
783
+ stencil) found ``np.add.at`` to be ~8-12x slower per call than the
784
+ explicit CSR ``rmatvec`` equivalent. Precomputing one flattened
785
+ (row, col, weighted-value) triple across *every* family up front and
786
+ reducing with a single ``np.bincount`` call (instead of six ``np.add.at``
787
+ calls) removes that bottleneck: ``np.bincount`` performs the same
788
+ "sum contributions landing on the same index" reduction in one
789
+ optimised pass, and combining every family into one call also amortises
790
+ Python-level loop overhead across the whole regularisation system
791
+ rather than paying it per family.
792
+ """
793
+ blocks = list(blocks)
794
+ dof = self.dof
795
+ row_counts = [b["idc"].shape[0] for b in blocks]
796
+ n_rows_total = int(sum(row_counts))
797
+
798
+ # Flattened (row, col, weighted-value) triples across every family,
799
+ # used only by rmatvec's combined bincount scatter-add (see above).
800
+ flat_rows = []
801
+ flat_cols = []
802
+ flat_vals = []
803
+ row_offset = 0
804
+ for block in blocks:
805
+ idc = block["idc"]
806
+ values = block["values"]
807
+ w = block["w"]
808
+ n_rows, n_offsets = idc.shape
809
+ if n_rows == 0 or n_offsets == 0:
810
+ row_offset += n_rows
811
+ continue
812
+ # Global row index for every (row, offset) entry in this family.
813
+ flat_rows.append(np.repeat(np.arange(row_offset, row_offset + n_rows), n_offsets))
814
+ flat_cols.append(idc.ravel())
815
+ # w is per-row, values is per-offset (shared across rows in a
816
+ # uniform-spacing family); broadcast-multiply once and flatten.
817
+ flat_vals.append((w[:, None] * values[None, :]).ravel())
818
+ row_offset += n_rows
819
+
820
+ if flat_rows:
821
+ flat_rows = np.concatenate(flat_rows).astype(np.intp, copy=False)
822
+ flat_cols = np.concatenate(flat_cols).astype(np.intp, copy=False)
823
+ flat_vals = np.concatenate(flat_vals)
824
+ else:
825
+ flat_rows = np.zeros(0, dtype=np.intp)
826
+ flat_cols = np.zeros(0, dtype=np.intp)
827
+ flat_vals = np.zeros(0, dtype=float)
828
+
829
+ def matvec(x):
830
+ x = np.asarray(x).reshape(-1)
831
+ out = np.empty(n_rows_total, dtype=float)
832
+ offset = 0
833
+ for block in blocks:
834
+ idc = block["idc"]
835
+ values = block["values"]
836
+ w = block["w"]
837
+ n_rows = idc.shape[0]
838
+ gathered = values[None, :] * x[idc]
839
+ out[offset : offset + n_rows] = w * gathered.sum(axis=1)
840
+ offset += n_rows
841
+ return out
842
+
843
+ def rmatvec(y):
844
+ y = np.asarray(y).reshape(-1)
845
+ contributions = flat_vals * y[flat_rows]
846
+ return np.bincount(flat_cols, weights=contributions, minlength=dof)
847
+
848
+ return LinearOperator(
849
+ shape=(n_rows_total, dof), matvec=matvec, rmatvec=rmatvec, dtype=float
850
+ )
851
+
852
+ def get_regularisation_linear_operator(self, names=None) -> LinearOperator | None:
853
+ """Return a matrix-free ``LinearOperator`` for the recorded regularisation blocks.
854
+
855
+ Only populated after ``setup_interpolator(..., regularisation_matrix_free=True)``
856
+ has run (and ``apply_scaling_matrix`` is False, otherwise the explicit
857
+ path is used, see ``setup_interpolator``).
858
+
859
+ Parameters
860
+ ----------
861
+ names : iterable of str, optional
862
+ Subset of family names (keys of ``self.matrix_free_regularisation_blocks``)
863
+ to combine, e.g. ``["dxx", "dyy", "dzz"]``. Defaults to all recorded
864
+ blocks, stacked in insertion order.
865
+
866
+ Returns
867
+ -------
868
+ scipy.sparse.linalg.LinearOperator or None
869
+ ``None`` if no matrix-free regularisation blocks have been recorded.
870
+ """
871
+ if not self.matrix_free_regularisation_blocks:
872
+ return None
873
+ if names is None:
874
+ names = list(self.matrix_free_regularisation_blocks.keys())
875
+ blocks = [
876
+ self.matrix_free_regularisation_blocks[n]
877
+ for n in names
878
+ if n in self.matrix_free_regularisation_blocks
879
+ ]
880
+ if not blocks:
881
+ return None
882
+ return self._matrix_free_operator_from_blocks(blocks)
883
+
884
+ def _build_fused_cg_regularisation_operator(self) -> LinearOperator | None:
885
+ """Return a ``LinearOperator`` computing ``R_reg^T @ R_reg @ x`` (the
886
+ matrix-free regularisation block's contribution to the CG normal
887
+ equations) using a fused single-kernel convolution for the six
888
+ interior second-derivative families (dxx/dyy/dzz/dxy/dxz/dyz), plus an
889
+ exact boundary-shell correction, instead of the (rectangular,
890
+ matvec-then-rmatvec) ``get_regularisation_linear_operator`` path.
891
+
892
+ This is CG/normal-equations-specific (the fused kernel represents
893
+ ``A^T A`` directly, not ``A``, so it has no rectangular matvec and
894
+ cannot be used by lsmr) and self-adjoint by construction
895
+ (``matvec is rmatvec``).
896
+
897
+ Correctness
898
+ -----------
899
+ Composing two radius-1 stencils (correlate then convolve, i.e. one
900
+ family's ``rmatvec(matvec(x))``) is itself a translation-invariant
901
+ radius-2 stencil ONLY away from the true domain boundary: the real
902
+ two-pass computation discards/zeroes "rows" at grid nodes that are not
903
+ genuinely interior (see ``support.neighbour_global_indexes``'s default
904
+ edge mask) before scattering back, which is not translation-invariant,
905
+ so a single fused (5,5,5) kernel applied everywhere is wrong at nodes
906
+ within 1 cell of the true edge (see module-level prototypes this
907
+ implementation is derived from). This method fixes that exactly: the
908
+ fused kernel is used only for dof at distance >= 2 from the true edge
909
+ (``_dist_to_true_edge``), and the existing exact index-array
910
+ matvec/rmatvec machinery (``_matrix_free_operator_from_blocks``,
911
+ reused unmodified) is used for the outer 2-cell shell, restricted to
912
+ just the rows whose stencil footprint can reach that shell (row centre
913
+ distance <= 2) - the two contributions are masked to disjoint,
914
+ exhaustive column sets (>=2 vs <=1) so they sum to the exact result at
915
+ every single dof, not merely in the deep interior.
916
+
917
+ Families are only fused if (a) their name is one of the six canonical
918
+ interior families, (b) their stored normalised stencil coefficients
919
+ match the canonical ``Operator.*_mask`` for that name (guards against
920
+ a caller-supplied custom ``operators=`` override reusing a canonical
921
+ name for a different mask), and (c) their per-row weight is uniform
922
+ (spatially-varying weights, e.g. ``use_regularisation_weight_scale``,
923
+ are not translation-invariant, so fusing them would be wrong). Any
924
+ family that doesn't qualify (including all border second-derivative
925
+ families) is instead included, in full and unrestricted, via the
926
+ existing exact ``_matrix_free_operator_from_blocks`` two-pass - never
927
+ dropped, only computed the "slow" (but always correct) way.
928
+ """
929
+ blocks = self.matrix_free_regularisation_blocks
930
+ if not blocks:
931
+ return None
932
+
933
+ dof = self.dof
934
+
935
+ def _normal_operator_from_blocks(block_list) -> LinearOperator | None:
936
+ """Wrap the existing rectangular (rows x dof) matvec/rmatvec
937
+ LinearOperator into a (dof x dof) normal-equations operator
938
+ (``rmatvec(matvec(x))``), self-adjoint by construction. This is
939
+ the "safe, unfused, but always exact" fallback used whenever
940
+ fusion doesn't apply (2D/non-structured dof layout, or no
941
+ families qualify for fusion) - `_build_fused_cg_regularisation_operator`
942
+ must always return a square operator computing R_reg^T @ R_reg @ x,
943
+ never the rectangular forward operator itself.
944
+ """
945
+ if not block_list:
946
+ return None
947
+ rect_op = self._matrix_free_operator_from_blocks(block_list)
948
+
949
+ def _matvec(x):
950
+ x = np.asarray(x, dtype=float).reshape(-1)
951
+ return rect_op.rmatvec(rect_op.matvec(x))
952
+
953
+ return LinearOperator(shape=(dof, dof), matvec=_matvec, rmatvec=_matvec, dtype=float)
954
+
955
+ if getattr(self.support, "dimension", 3) == 3:
956
+ nsteps = np.asarray(self.support.nsteps, dtype=int).reshape(-1)
957
+ else:
958
+ nsteps = np.zeros(0, dtype=int)
959
+
960
+ if nsteps.shape[0] != 3 or int(np.prod(nsteps)) != dof:
961
+ # Not a (genuine) 3D structured grid dof layout - safe fallback,
962
+ # exact but unfused, identical to the pre-existing behaviour.
963
+ return _normal_operator_from_blocks(list(blocks.values()))
964
+
965
+ nx, ny, nz = (int(v) for v in nsteps)
966
+ dist = _dist_to_true_edge(nx, ny, nz)
967
+ deep_mask = dist >= 2
968
+ shell_rows_mask = dist <= 2 # candidate row centres near the shell
969
+
970
+ fused_terms = [] # list of (raw mask (3,3,3) z,y,x order, scalar w)
971
+ shell_blocks = [] # per-family row-restricted blocks (exact boundary fix)
972
+ remainder_blocks = [] # families handled entirely by the plain two-pass
973
+
974
+ for name, block in blocks.items():
975
+ idc = block["idc"]
976
+ values = block["values"]
977
+ w = block["w"]
978
+ centre_idc = block.get("centre_idc")
979
+
980
+ fusable = (
981
+ name in _FUSED_FAMILY_MASKS
982
+ and centre_idc is not None
983
+ and idc.shape[0] > 0
984
+ and w.shape[0] > 0
985
+ and np.all(w == w[0])
986
+ )
987
+ if fusable:
988
+ expected_xyz = _normalised_mask_xyz(_FUSED_FAMILY_MASKS[name])
989
+ expected_values = expected_xyz[expected_xyz != 0]
990
+ fusable = values.shape[0] == expected_values.shape[0] and np.allclose(
991
+ np.sort(values), np.sort(expected_values), atol=1e-12
992
+ )
993
+
994
+ if not fusable:
995
+ remainder_blocks.append(block)
996
+ continue
997
+
998
+ fused_terms.append((_FUSED_FAMILY_MASKS[name], float(w[0])))
999
+
1000
+ row_mask = shell_rows_mask[centre_idc]
1001
+ if np.any(row_mask):
1002
+ shell_blocks.append(
1003
+ {
1004
+ "idc": idc[row_mask],
1005
+ "values": values,
1006
+ "w": w[row_mask],
1007
+ }
1008
+ )
1009
+
1010
+ if not fused_terms:
1011
+ # Nothing qualified for fusion (e.g. spatially-varying weights,
1012
+ # non-canonical masks, or no interior families at all) - fall back
1013
+ # to the exact, unfused operator for everything.
1014
+ return _normal_operator_from_blocks(list(blocks.values()))
1015
+
1016
+ combined_kernel = None
1017
+ for mask, w in fused_terms:
1018
+ k = (w * w) * _composite_kernel(_normalised_mask_xyz(mask))
1019
+ combined_kernel = k if combined_kernel is None else combined_kernel + k
1020
+
1021
+ shell_operator = (
1022
+ self._matrix_free_operator_from_blocks(shell_blocks) if shell_blocks else None
1023
+ )
1024
+ remainder_operator = (
1025
+ self._matrix_free_operator_from_blocks(remainder_blocks)
1026
+ if remainder_blocks
1027
+ else None
1028
+ )
1029
+
1030
+ def matvec(x):
1031
+ x = np.asarray(x, dtype=float).reshape(-1)
1032
+ arr3d = x.reshape((nx, ny, nz), order="F")
1033
+ fused_out = ndimage.correlate(
1034
+ arr3d, combined_kernel, mode="constant", cval=0.0
1035
+ ).ravel(order="F")
1036
+ fused_out = np.where(deep_mask, fused_out, 0.0)
1037
+ out = fused_out
1038
+ if shell_operator is not None:
1039
+ shell_out = shell_operator.rmatvec(shell_operator.matvec(x))
1040
+ out = out + np.where(deep_mask, 0.0, shell_out)
1041
+ if remainder_operator is not None:
1042
+ out = out + remainder_operator.rmatvec(remainder_operator.matvec(x))
1043
+ return out
1044
+
1045
+ # Self-adjoint by construction: every term above is an A^T A
1046
+ # contribution (fused-deep-interior, boundary-shell two-pass, and
1047
+ # remainder two-pass are each individually a valid A_i^T A_i, and the
1048
+ # sum of self-adjoint operators is self-adjoint), so rmatvec is the
1049
+ # same function as matvec.
1050
+ return LinearOperator(shape=(dof, dof), matvec=matvec, rmatvec=matvec, dtype=float)
1051
+
1052
+ def assemble_borders(self):
1053
+ """Regularise the one-node-in-from-the-edge layer along each axis.
1054
+
1055
+ The centred second-derivative stencils (dxx/dyy/dzz) assembled by
1056
+ ``assemble_inner`` only ever fire at nodes that are strictly interior
1057
+ on *all three* axes (``support.neighbour_global_indexes``'s default
1058
+ edge mask), so a node that is interior along this axis but sits on a
1059
+ face/edge/corner along another axis never gets a curvature constraint
1060
+ along this axis either, even though both of its neighbours here exist.
1061
+
1062
+ This uses the same centred second-derivative mask as the interior
1063
+ pass (not a one-sided first-derivative/Neumann "zero slope" mask):
1064
+ the field's true gradient is generally nonzero and non-constant right
1065
+ up to the domain edge (e.g. a planar fault or a tilted contact), so
1066
+ forcing the slope to zero there fights the correct solution and can
1067
+ dominate the sparse-data regime enough to visibly flatten/curve
1068
+ surfaces well inside the domain. Zero curvature ("natural" boundary
1069
+ condition, as in a natural cubic spline) is compatible with any
1070
+ locally-linear field and only asks that curvature not be introduced
1071
+ artificially at the edge.
1072
+ """
1073
+ operators = []
1074
+ if self.support.dimension == 2:
1075
+ operators = [
1076
+ (
1077
+ Operator.Dxx_mask[1, :, :],
1078
+ self.interpolation_weights["dx"],
1079
+ "dx_lower",
1080
+ self._boundary_indexes(0, upper=False),
1081
+ ),
1082
+ (
1083
+ Operator.Dxx_mask[1, :, :],
1084
+ self.interpolation_weights["dx"],
1085
+ "dx_upper",
1086
+ self._boundary_indexes(0, upper=True),
1087
+ ),
1088
+ (
1089
+ Operator.Dyy_mask[1, :, :],
1090
+ self.interpolation_weights["dy"],
1091
+ "dy_lower",
1092
+ self._boundary_indexes(1, upper=False),
1093
+ ),
1094
+ (
1095
+ Operator.Dyy_mask[1, :, :],
1096
+ self.interpolation_weights["dy"],
1097
+ "dy_upper",
1098
+ self._boundary_indexes(1, upper=True),
1099
+ ),
1100
+ ]
1101
+ else:
1102
+ operators = [
1103
+ (
1104
+ Operator.Dxx_mask,
1105
+ self.interpolation_weights["dx"],
1106
+ "dx_lower",
1107
+ self._boundary_indexes(0, upper=False),
1108
+ ),
1109
+ (
1110
+ Operator.Dxx_mask,
1111
+ self.interpolation_weights["dx"],
1112
+ "dx_upper",
1113
+ self._boundary_indexes(0, upper=True),
1114
+ ),
1115
+ (
1116
+ Operator.Dyy_mask,
1117
+ self.interpolation_weights["dy"],
1118
+ "dy_lower",
1119
+ self._boundary_indexes(1, upper=False),
1120
+ ),
1121
+ (
1122
+ Operator.Dyy_mask,
1123
+ self.interpolation_weights["dy"],
1124
+ "dy_upper",
1125
+ self._boundary_indexes(1, upper=True),
1126
+ ),
1127
+ (
1128
+ Operator.Dzz_mask,
1129
+ self.interpolation_weights["dz"],
1130
+ "dz_lower",
1131
+ self._boundary_indexes(2, upper=False),
1132
+ ),
1133
+ (
1134
+ Operator.Dzz_mask,
1135
+ self.interpolation_weights["dz"],
1136
+ "dz_upper",
1137
+ self._boundary_indexes(2, upper=True),
1138
+ ),
1139
+ ]
1140
+
1141
+ for operator, weight, name, indexes in operators:
1142
+ if weight == 0 or indexes is None or indexes.shape[1] == 0:
1143
+ continue
1144
+ self._assemble_operator(operator, weight, name=name, indexes=indexes)
1145
+
1146
+ def assemble_inner(self, operator, w, name="regularisation"):
1147
+ """
1148
+
1149
+ Parameters
1150
+ ----------
1151
+ operator : Operator mask (ndarray) or None for rectilinear grids
1152
+ w : double
1153
+
1154
+ Returns
1155
+ -------
1156
+
1157
+ """
1158
+ if operator is None:
1159
+ # Rectilinear grid: operator rows are built from the grid itself
1160
+ # using the operator name as a hint for which derivative to assemble.
1161
+ self._assemble_rectilinear_operator(name, w)
1162
+ return
1163
+ self._assemble_operator(operator, w, name=name)
1164
+ return
1165
+
1166
+ def _assemble_rectilinear_operator(self, name: str, w: float):
1167
+ """Assemble a scaled FD regularisation operator for a rectilinear grid.
1168
+
1169
+ Parameters
1170
+ ----------
1171
+ name : str
1172
+ Operator name, e.g. 'dxx', 'dyy', 'dzz', 'dxy', 'dyz', 'dxz'.
1173
+ w : float
1174
+ Weight applied to every row.
1175
+ """
1176
+ axis_map = {
1177
+ "dxx": (0, -1),
1178
+ "dyy": (1, -1),
1179
+ "dzz": (2, -1),
1180
+ "dxy": (0, 1),
1181
+ "dxz": (0, 2),
1182
+ "dyz": (1, 2),
1183
+ }
1184
+ if name not in axis_map:
1185
+ logger.warning(f"Unknown rectilinear operator name '{name}', skipping.")
1186
+ return
1187
+ axis, cross = axis_map[name]
1188
+ A_values, col_global, row_global = self.support.build_scaled_operator_rows(axis, cross)
1189
+
1190
+ idc = np.asarray(col_global, dtype=int)
1191
+ centre_dof = np.asarray(row_global, dtype=int)
1192
+
1193
+ B = np.zeros(idc.shape[0])
1194
+ row_w = (
1195
+ self.regularisation_scale[centre_dof.astype(int)] * w
1196
+ if self.use_regularisation_weight_scale
1197
+ else w
1198
+ )
1199
+ self.add_constraints_to_least_squares(
1200
+ A_values,
1201
+ B,
1202
+ idc,
1203
+ w=row_w,
1204
+ name=name,
1205
+ )
1206
+
1207
+ def minimise_directional_gradient_change(
1208
+ self,
1209
+ w: float,
1210
+ vector: np.ndarray,
1211
+ name: str = "directional regularisation",
1212
+ ):
1213
+ """
1214
+ Anisotropic regularisation that penalises the directional second
1215
+ derivative ``(v·∇)²f = 0`` at each interior grid node.
1216
+
1217
+ This is the finite-difference analogue of the P1
1218
+ ``minimise_edge_jumps`` with a direction vector. For a given
1219
+ direction field ``v = (vx, vy, vz)`` sampled at every grid node, the
1220
+ constraint at each interior node is
1221
+
1222
+ .. math::
1223
+
1224
+ v_x^2 f_{xx} + v_y^2 f_{yy} + v_z^2 f_{zz}
1225
+ + 2 v_x v_y f_{xy} + 2 v_x v_z f_{xz} + 2 v_y v_z f_{yz} = 0
1226
+
1227
+ The six second-derivative operators are each weighted by the
1228
+ corresponding squared direction component so the regularisation is
1229
+ strong along ``v`` and weak across it.
1230
+
1231
+ Parameters
1232
+ ----------
1233
+ w : float
1234
+ Base regularisation weight.
1235
+ vector : np.ndarray, shape (n_nodes, 3)
1236
+ Direction field evaluated at every grid node
1237
+ (``self.support.nodes``). Typically the fold normal, fold axis,
1238
+ or deformed-orientation vector returned by
1239
+ ``FoldEvent.get_deformed_orientation``.
1240
+ name : str
1241
+ Label stored with these constraints.
1242
+ """
1243
+ if vector is None or vector.ndim != 2 or vector.shape != (self.support.n_nodes, 3):
1244
+ logger.warning(
1245
+ f"{name}: vector must have shape ({self.support.n_nodes}, 3), "
1246
+ f"got {None if vector is None else vector.shape}. Skipping."
1247
+ )
1248
+ return
1249
+
1250
+ has_scaled_rows = hasattr(self.support, "build_scaled_operator_rows")
1251
+
1252
+ # Six second-derivative operator types and the matching direction-
1253
+ # weight formula. For RectilinearGrid we use build_scaled_operator_rows
1254
+ # which gives per-node stencil coefficients scaled by the local spacing.
1255
+ # For StructuredGrid (uniform spacing) we use the fixed Operator masks via
1256
+ # neighbour_global_indexes, which mirrors how _assemble_operator works.
1257
+ axis_map = {
1258
+ "dxx": (0, -1),
1259
+ "dyy": (1, -1),
1260
+ "dzz": (2, -1),
1261
+ "dxy": (0, 1),
1262
+ "dxz": (0, 2),
1263
+ "dyz": (1, 2),
1264
+ }
1265
+ # Operator masks for the mask-based path (StructuredGrid).
1266
+ op_masks = {
1267
+ "dxx": Operator.Dxx_mask,
1268
+ "dyy": Operator.Dyy_mask,
1269
+ "dzz": Operator.Dzz_mask,
1270
+ "dxy": Operator.Dxy_mask,
1271
+ "dxz": Operator.Dxz_mask,
1272
+ "dyz": Operator.Dyz_mask,
1273
+ }
1274
+
1275
+ for op_key, (ax, cx) in axis_map.items():
1276
+ if has_scaled_rows:
1277
+ # --- RectilinearGrid path: per-node scaled stencil rows -------
1278
+ A_values, col_global, row_nodes = self.support.build_scaled_operator_rows(ax, cx)
1279
+ idc = np.asarray(col_global, dtype=int)
1280
+ row_nodes = np.asarray(row_nodes, dtype=int)
1281
+ if idc.shape[0] == 0:
1282
+ continue
1283
+ else:
1284
+ # --- StructuredGrid path: fixed stencil mask ------------------
1285
+ operator = op_masks[op_key]
1286
+ active = operator.flatten() != 0
1287
+ if not np.any(active):
1288
+ continue
1289
+ full_mask = self._full_neighbour_mask()
1290
+ active_mask = full_mask[:, active]
1291
+ operator_values = operator.flatten()[active]
1292
+
1293
+ global_indexes = self.support.neighbour_global_indexes(mask=active_mask)
1294
+ if global_indexes is None or global_indexes.size == 0:
1295
+ continue
1296
+ centre_indexes = self.support.neighbour_global_indexes(
1297
+ mask=np.zeros((self.support.dimension, 1), dtype=int)
1298
+ )
1299
+ col_global = global_indexes
1300
+ row_nodes = centre_indexes.T[:, 0] # global index of each interior centre node
1301
+ A_values = np.tile(operator_values, (col_global.shape[1], 1))
1302
+ idc = np.asarray(col_global.T, dtype=int)
1303
+ row_nodes = np.asarray(row_nodes, dtype=int)
1304
+ if idc.shape[0] == 0:
1305
+ continue
1306
+
1307
+ # Direction-component weight for this operator type.
1308
+ vx = vector[row_nodes, 0]
1309
+ vy = vector[row_nodes, 1]
1310
+ vz = vector[row_nodes, 2]
1311
+ if op_key == "dxx":
1312
+ comp_w = vx**2
1313
+ elif op_key == "dyy":
1314
+ comp_w = vy**2
1315
+ elif op_key == "dzz":
1316
+ comp_w = vz**2
1317
+ elif op_key == "dxy":
1318
+ comp_w = 2.0 * vx * vy
1319
+ elif op_key == "dxz":
1320
+ comp_w = 2.0 * vx * vz
1321
+ else: # dyz
1322
+ comp_w = 2.0 * vy * vz
1323
+
1324
+ row_w = w * comp_w
1325
+ # Skip rows where the direction weight is effectively zero.
1326
+ nonzero = np.abs(row_w) > 0.0
1327
+ if not np.any(nonzero):
1328
+ continue
1329
+
1330
+ B = np.zeros(np.sum(nonzero))
1331
+ self.add_constraints_to_least_squares(
1332
+ A_values[nonzero],
1333
+ B,
1334
+ idc[nonzero],
1335
+ w=row_w[nonzero],
1336
+ name=f"{name}_{op_key}",
1337
+ )
1338
+
1339
+ def get_regularisation_sample_points(self) -> np.ndarray:
1340
+ return self.support.nodes
1341
+
1342
+ def _add_directional_regularisation(
1343
+ self,
1344
+ weight: float,
1345
+ vectors: np.ndarray,
1346
+ name: str = "directional regularisation",
1347
+ ):
1348
+ self.minimise_directional_gradient_change(weight, vectors, name=name)