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,1405 @@
1
+ """
2
+ Discrete interpolator base for least squares
3
+ """
4
+ from __future__ import annotations
5
+
6
+ from abc import abstractmethod
7
+ from collections import defaultdict
8
+ from time import perf_counter
9
+ from typing import Callable
10
+
11
+ import numpy as np
12
+ from loop_common.logging import get_logger as getLogger
13
+ from scipy import sparse # import sparse.coo_matrix, sparse.bmat, sparse.eye
14
+ from scipy.sparse.linalg import LinearOperator
15
+
16
+ from . import _solver_pipeline, _solver_strategy
17
+ from ._diagnostics import ConstraintDiagnosticsReport, ConstraintFamilyDiagnostics
18
+ from ._geological_interpolator import GeologicalInterpolator
19
+ from ._interpolatortype import InterpolatorType
20
+ from ._regularisation import (
21
+ DirectionalRegularisation,
22
+ RegularisationConfig,
23
+ coerce_regularisation_config,
24
+ )
25
+
26
+ logger = getLogger(__name__)
27
+
28
+
29
+ class DiscreteInterpolator(GeologicalInterpolator):
30
+ """ """
31
+
32
+ def __init__(self, support, data=None, c=None, up_to_date=False):
33
+ """
34
+ Base class for a discrete interpolator e.g. piecewise linear or finite difference which is
35
+ any interpolator that solves the system using least squares approximation
36
+
37
+ Parameters
38
+ ----------
39
+ support
40
+ A discrete mesh with, nodes, elements, etc
41
+ """
42
+ GeologicalInterpolator.__init__(self, data=data, up_to_date=up_to_date)
43
+ self.B = []
44
+ self.support = support
45
+ self.dimensions = support.dimension
46
+ self.c = (
47
+ np.array(c)
48
+ if c is not None and np.array(c).shape[0] == self.support.n_nodes
49
+ else np.zeros(self.support.n_nodes)
50
+ )
51
+ # Region masking is no longer supported; all support nodes are active.
52
+ self.region_function = lambda xyz: np.ones(xyz.shape[0], dtype=bool)
53
+
54
+ self.shape = "rectangular"
55
+ if self.shape == "square":
56
+ self.B = np.zeros(self.dof)
57
+ self.c_ = 0
58
+
59
+ self.solver = "cg"
60
+
61
+ self.eq_const_C = []
62
+ self.eq_const_row = []
63
+ self.eq_const_col = []
64
+ self.eq_const_d = []
65
+
66
+ self.equal_constraints = {}
67
+ self.eq_const_c = 0
68
+ self.ineq_constraints = {}
69
+ self.ineq_const_c = 0
70
+
71
+ self.non_linear_constraints = []
72
+ self.constraints = {}
73
+ self.interpolation_weights = {}
74
+ logger.info(f"Creating discrete interpolator with {self.dof} degrees of freedom")
75
+ self.type = InterpolatorType.BASE_DISCRETE
76
+ self.apply_scaling_matrix = True
77
+ self.add_ridge_regulatisation = True
78
+ self.ridge_factor = 1e-8
79
+ self.solver_history = None
80
+ self.latest_solve_timing = {}
81
+
82
+ def get_last_solve_timing(self) -> dict:
83
+ """Return timing metrics captured during the most recent solve."""
84
+ return dict(self.latest_solve_timing)
85
+
86
+ def set_nelements(self, nelements: int) -> int:
87
+ return self.support.set_nelements(nelements)
88
+
89
+ @property
90
+ def n_elements(self) -> int:
91
+ """Number of elements in the interpolator
92
+
93
+ Returns
94
+ -------
95
+ int
96
+ number of elements, positive
97
+ """
98
+ return self.support.n_elements
99
+
100
+ @property
101
+ def dof(self) -> int:
102
+ """Number of degrees of freedom for the interpolator
103
+
104
+ Returns
105
+ -------
106
+ int
107
+ number of degrees of freedom, positve
108
+ """
109
+ return int(self.support.n_nodes)
110
+
111
+ @property
112
+ def region(self) -> np.ndarray:
113
+ """The active region of the interpolator. A boolean
114
+ mask for all elements that are interpolated
115
+
116
+ Returns
117
+ -------
118
+ np.ndarray
119
+
120
+ """
121
+
122
+ return np.ones(self.support.n_nodes, dtype=bool)
123
+
124
+ @property
125
+ def region_map(self):
126
+ return np.arange(self.support.n_nodes, dtype=int)
127
+
128
+ def set_region(self, region=None):
129
+ """
130
+ Set the region of the support the interpolator is working on
131
+
132
+ Parameters
133
+ ----------
134
+ region - function(position)
135
+ return true when in region, false when out
136
+
137
+ Returns
138
+ -------
139
+
140
+ """
141
+ # evaluate the region function on the support to determine
142
+ # which nodes are inside update region map and degrees of freedom
143
+ # self.region_function = region
144
+ logger.info(
145
+ "Region masking has been removed; the interpolator always uses all support nodes (%s DOF).",
146
+ self.dof,
147
+ )
148
+
149
+ def set_interpolation_weights(self, weights):
150
+ """
151
+ Set the interpolation weights dictionary
152
+
153
+ Parameters
154
+ ----------
155
+ weights - dictionary
156
+ Entry of new weights to assign to self.interpolation_weights
157
+
158
+ Returns
159
+ -------
160
+
161
+ """
162
+ for key in weights:
163
+ self.up_to_date = False
164
+ self.interpolation_weights[key] = weights[key]
165
+
166
+ def _apply_isotropic_regularisation_weight(self, value: float | None, keys: tuple[str, ...]):
167
+ if value is None:
168
+ return
169
+ for key in keys:
170
+ self.interpolation_weights[key] = value
171
+
172
+ def _apply_interpolation_weight_kwargs(self, kwargs: dict, skip_keys: tuple[str, ...] = ()):
173
+ for key, value in kwargs.items():
174
+ self.up_to_date = False
175
+ if key in skip_keys:
176
+ continue
177
+ self.interpolation_weights[key] = value
178
+
179
+ def _normalise_constraint_family(self, name: str, inequality: bool = False) -> str:
180
+ name = name.lower()
181
+ if name.startswith("value"):
182
+ return "value"
183
+ if name.startswith("gradient"):
184
+ return "gradient"
185
+ if name.startswith("norm"):
186
+ return "normal"
187
+ if name.startswith("tangent"):
188
+ return "tangent"
189
+ if name.startswith("interface"):
190
+ return "interface"
191
+ if name.startswith("inequality_value"):
192
+ return "inequality_value"
193
+ if name.startswith("inequality_pairs"):
194
+ return "inequality_pairs"
195
+ if name.startswith("fold"):
196
+ return "fold"
197
+ if name.startswith("d") and len(name) in (3, 4, 5, 6, 7, 8):
198
+ return "regularisation"
199
+ if inequality:
200
+ return "inequality"
201
+ return "other"
202
+
203
+ def _build_constraint_diagnostics_report(self) -> ConstraintDiagnosticsReport:
204
+ report = super()._build_constraint_diagnostics_report()
205
+ outside = dict(report.outside_model_points)
206
+
207
+ raw_points = {
208
+ "value": int(self.get_value_constraints().shape[0]),
209
+ "gradient": int(self.get_gradient_constraints().shape[0]),
210
+ "normal": int(self.get_norm_constraints().shape[0]),
211
+ "tangent": int(self.get_tangent_constraints().shape[0]),
212
+ "interface": int(self.get_interface_constraints().shape[0]),
213
+ "inequality_value": int(self.get_inequality_value_constraints().shape[0]),
214
+ "inequality_pairs": int(self.get_inequality_pairs_constraints().shape[0]),
215
+ }
216
+
217
+ row_counts = defaultdict(int)
218
+ weight_values = defaultdict(list)
219
+
220
+ for name, constraint in self.constraints.items():
221
+ family = self._normalise_constraint_family(name)
222
+ matrix = constraint.get("matrix")
223
+ if matrix is not None:
224
+ row_counts[family] += int(matrix.shape[0])
225
+ w = constraint.get("w")
226
+ if w is not None:
227
+ w_arr = np.asarray(w, dtype=float)
228
+ if w_arr.size > 0:
229
+ weight_values[family].append(w_arr)
230
+
231
+ for name, constraint in self.ineq_constraints.items():
232
+ family = self._normalise_constraint_family(name, inequality=True)
233
+ matrix = constraint.get("matrix")
234
+ if matrix is not None:
235
+ row_counts[family] += int(matrix.shape[0])
236
+
237
+ families = {}
238
+ family_names = set(raw_points.keys()) | set(row_counts.keys()) | set(report.families.keys())
239
+
240
+ for family_name in sorted(family_names):
241
+ rows = int(row_counts.get(family_name, 0))
242
+ source_points = int(raw_points.get(family_name, 0))
243
+ outside_points = int(outside.get(family_name, 0))
244
+
245
+ dropped = None
246
+ if family_name in ("value", "normal", "tangent", "inequality_value"):
247
+ dropped = max(source_points - rows, 0)
248
+ elif family_name == "gradient":
249
+ dropped = max(source_points * 2 - rows, 0)
250
+
251
+ if len(weight_values.get(family_name, [])) > 0:
252
+ all_weights = np.concatenate(weight_values[family_name])
253
+ mean_w = float(np.mean(all_weights))
254
+ min_w = float(np.min(all_weights))
255
+ max_w = float(np.max(all_weights))
256
+ else:
257
+ mean_w = None
258
+ min_w = None
259
+ max_w = None
260
+
261
+ families[family_name] = ConstraintFamilyDiagnostics(
262
+ name=family_name,
263
+ active=rows > 0,
264
+ row_count=rows,
265
+ dropped_rows=dropped,
266
+ effective_weight_mean=mean_w,
267
+ effective_weight_min=min_w,
268
+ effective_weight_max=max_w,
269
+ source_point_count=source_points,
270
+ outside_model_point_count=outside_points,
271
+ )
272
+
273
+ return ConstraintDiagnosticsReport(
274
+ interpolator_type=report.interpolator_type,
275
+ families=families,
276
+ region_coverage=report.region_coverage,
277
+ outside_model_points=outside,
278
+ )
279
+
280
+ def finalize_setup_diagnostics_report(self) -> ConstraintDiagnosticsReport:
281
+ self.latest_diagnostics_report = self._build_constraint_diagnostics_report()
282
+ return self.latest_diagnostics_report
283
+
284
+ def _pre_solve(self):
285
+ """
286
+ Pre solve function to be run before solving the interpolation
287
+ """
288
+ self.c = np.zeros(self.support.n_nodes)
289
+ self.c[:] = np.nan
290
+ return True
291
+
292
+ def _post_solve(self):
293
+ """Post solve function(s) to be run after the solver has been called"""
294
+ self.clear_constraints()
295
+ return True
296
+
297
+ def clear_constraints(self):
298
+ """
299
+ Clear the constraints from the interpolator, this makes sure we are not storing
300
+ the constraints after the solver has been run
301
+ """
302
+ self.constraints = {}
303
+ self.ineq_constraints = {}
304
+ self.equal_constraints = {}
305
+
306
+ def reset(self):
307
+ """
308
+ Reset the interpolation constraints
309
+
310
+ """
311
+ self.constraints = {}
312
+ self.c_ = 0
313
+ self.regularisation_scale = np.ones(self.dof)
314
+ logger.info("Resetting interpolation constraints")
315
+
316
+ def add_constraints_to_least_squares(self, A, B, idc, w=1.0, name="undefined"):
317
+ """
318
+ Adds constraints to the least squares system. Automatically works
319
+ out the row
320
+ index given the shape of the input arrays
321
+
322
+ Parameters
323
+ ----------
324
+ A : numpy array / list
325
+ RxC numpy array of constraints where C is number of columns,R rows
326
+ B : numpy array /list
327
+ B values array length R
328
+ idc : numpy array/list
329
+ RxC column index
330
+
331
+ Returns
332
+ -------
333
+ list of constraint ids
334
+
335
+ """
336
+ A = np.array(A)
337
+ B = np.array(B)
338
+ idc = np.array(idc)
339
+ n_rows = A.shape[0]
340
+ # logger.debug('Adding constraints to interpolator: {} {} {}'.format(A.shape[0]))
341
+ # print(A.shape,B.shape,idc.shape)
342
+ if A.shape != idc.shape:
343
+ logger.error(f"Cannot add constraints: A and indexes have different shape : {name}")
344
+ return
345
+
346
+ if len(A.shape) > 2:
347
+ n_rows = A.shape[0] * A.shape[1]
348
+ if isinstance(w, np.ndarray):
349
+ w = np.tile(w, (A.shape[1]))
350
+ A = A.reshape((A.shape[0] * A.shape[1], A.shape[2]))
351
+ idc = idc.reshape((idc.shape[0] * idc.shape[1], idc.shape[2]))
352
+ B = B.reshape(A.shape[0])
353
+ # w = w.reshape((A.shape[0]))
354
+
355
+ # Check for nan before any row normalisation, which would otherwise
356
+ # zero out nan rows in A and mask this check further down.
357
+ if np.any(np.isnan(idc)) or np.any(np.isnan(A)) or np.any(np.isnan(B)):
358
+ logger.warning(f"Constraints contain nan not adding constraints: {name}")
359
+ return
360
+
361
+ # normalise by rows of A
362
+ # Should this be done? It should make the solution more stable
363
+ length = np.linalg.norm(A, axis=1)
364
+ # length[length>0] = 1.
365
+ B[length > 0] /= length[length > 0]
366
+ A[length > 0, :] /= length[length > 0, None]
367
+ if isinstance(w, (float, int)):
368
+ w = np.ones(A.shape[0]) * w
369
+ if not isinstance(w, np.ndarray):
370
+ raise TypeError("w must be a numpy array")
371
+
372
+ if w.shape[0] != A.shape[0]:
373
+ raise ValueError("Weight array does not match number of constraints")
374
+ rows = np.arange(0, n_rows).astype(int)
375
+ base_name = name
376
+ while name in self.constraints:
377
+ count = 0
378
+ if "_" in name:
379
+ count = int(name.split("_")[1]) + 1
380
+ name = base_name + f"_{count}"
381
+
382
+ rows = np.tile(rows, (A.shape[-1], 1)).T
383
+ self.constraints[name] = {
384
+ "matrix": sparse.coo_matrix(
385
+ (A.flatten(), (rows.flatten(), idc.flatten())), shape=(n_rows, self.dof)
386
+ ).tocsc(),
387
+ "b": B.flatten(),
388
+ "w": w,
389
+ }
390
+
391
+ @abstractmethod
392
+ def add_gradient_orthogonal_constraints(
393
+ self, points: np.ndarray, vectors: np.ndarray, w: float = 1.0
394
+ ):
395
+ pass
396
+
397
+ def get_regularisation_sample_points(self) -> np.ndarray:
398
+ raise NotImplementedError(
399
+ f"{self.__class__.__name__} does not define regularisation sample points"
400
+ )
401
+
402
+ def _add_directional_regularisation(
403
+ self,
404
+ weight: float,
405
+ vectors: np.ndarray,
406
+ name: str = "directional regularisation",
407
+ ):
408
+ raise NotImplementedError(
409
+ f"{self.__class__.__name__} does not implement directional regularisation"
410
+ )
411
+
412
+ def resolve_regularisation_config(
413
+ self,
414
+ regularisation=None,
415
+ directional_regularisation=None,
416
+ ) -> RegularisationConfig:
417
+ return coerce_regularisation_config(
418
+ regularisation=regularisation,
419
+ directional_regularisation=directional_regularisation,
420
+ )
421
+
422
+ def add_directional_regularisation(
423
+ self,
424
+ directional_regularisation,
425
+ ) -> tuple[DirectionalRegularisation, ...]:
426
+ directional_terms = self.resolve_regularisation_config(
427
+ directional_regularisation=directional_regularisation
428
+ ).directional
429
+ if len(directional_terms) == 0:
430
+ return directional_terms
431
+
432
+ sample_points = np.asarray(self.get_regularisation_sample_points(), dtype=float)
433
+ expected_shape = sample_points.shape
434
+
435
+ for term in directional_terms:
436
+ if term.weight == 0:
437
+ continue
438
+
439
+ vectors = term.direction(sample_points) if callable(term.direction) else term.direction
440
+ vectors = np.asarray(vectors, dtype=float)
441
+ if vectors.shape != expected_shape:
442
+ logger.warning(
443
+ "%s: directional regularisation vectors must have shape %s, got %s. Skipping.",
444
+ term.name,
445
+ expected_shape,
446
+ vectors.shape,
447
+ )
448
+ continue
449
+ self._add_directional_regularisation(term.weight, vectors, name=term.name)
450
+
451
+ return directional_terms
452
+
453
+ def calculate_residual_for_constraints(self):
454
+ """Calculates Ax-B for all constraints added to the interpolator
455
+ This could be a proxy to identify which constraints are controlling the model
456
+
457
+ Returns
458
+ -------
459
+ np.ndarray
460
+ vector of Ax-B
461
+ """
462
+ residuals = {}
463
+ for constraint_name, constraint in self.constraints.items():
464
+ residuals[constraint_name] = constraint["matrix"].dot(self.c) - constraint["b"].flatten()
465
+ return residuals
466
+
467
+ def add_inequality_constraints_to_matrix(
468
+ self, A: np.ndarray, bounds: np.ndarray, idc: np.ndarray, name: str = "undefined"
469
+ ):
470
+ """Adds constraints for a matrix where the linear function
471
+ l < Ax > u constrains the objective function
472
+
473
+
474
+ Parameters
475
+ ----------
476
+ A : numpy array
477
+ matrix of coefficients
478
+ bounds : numpy array
479
+ n*3 lower, upper, 1
480
+ idc : numpy array
481
+ index of constraints in the matrix
482
+ Returns
483
+ -------
484
+
485
+ """
486
+ A = np.asarray(A, dtype=float)
487
+ idc = np.asarray(idc, dtype=int)
488
+ bounds = np.asarray(bounds, dtype=float)
489
+
490
+ if A.ndim != 2 or idc.ndim != 2:
491
+ raise ValueError("A and idc must be 2D arrays")
492
+ if A.shape != idc.shape:
493
+ raise ValueError("A and idc must have the same shape")
494
+ if bounds.ndim != 2 or bounds.shape[0] != A.shape[0] or bounds.shape[1] not in (2, 3):
495
+ raise ValueError("bounds must have shape (n_rows, 2) or (n_rows, 3)")
496
+ if np.any(idc < 0) or np.any(idc >= self.dof):
497
+ raise ValueError("Inequality constraint indices are out of range")
498
+
499
+ rows = np.arange(0, idc.shape[0])
500
+ rows = np.tile(rows, (A.shape[-1], 1)).T
501
+
502
+ self.ineq_constraints[name] = {
503
+ "matrix": sparse.coo_matrix(
504
+ (A.flatten(), (rows.flatten(), idc.flatten())), shape=(rows.shape[0], self.dof)
505
+ ).tocsc(),
506
+ "bounds": bounds,
507
+ }
508
+
509
+ def add_value_inequality_constraints(self, w: float = 1.0):
510
+ points = self.get_inequality_value_constraints()
511
+ # check that we have added some points
512
+ if points.shape[0] > 0:
513
+ coords = points[:, : self.support.dimension]
514
+ _vertices, a, element, inside = self.support.get_element_for_location(coords)
515
+ a = a[inside]
516
+ cols = self.support.elements[element[inside]]
517
+ bounds = points[inside, self.support.dimension : self.support.dimension + 2]
518
+ self.add_inequality_constraints_to_matrix(a, bounds, cols, "inequality_value")
519
+
520
+ def add_inequality_pairs_constraints(
521
+ self,
522
+ w: float = 1.0,
523
+ upper_bound=1.0, # np.finfo(float).eps,
524
+ lower_bound=-np.inf,
525
+ pairs: list | None = None,
526
+ ):
527
+
528
+ points = self.get_inequality_pairs_constraints()
529
+ if points.shape[0] > 0:
530
+ # assemble a list of pairs in the model
531
+ # this will make pairs even across stratigraphic boundaries
532
+ # TODO add option to only add stratigraphic pairs
533
+ if not pairs:
534
+ pairs = {}
535
+ k = 0
536
+ for i in np.unique(points[:, self.support.dimension]):
537
+ for j in np.unique(points[:, self.support.dimension]):
538
+ if i == j:
539
+ continue
540
+ if tuple(sorted([i, j])) not in pairs:
541
+ pairs[tuple(sorted([i, j]))] = k
542
+ k += 1
543
+ pairs = list(pairs.keys())
544
+ for pair in pairs:
545
+ upper_points = points[points[:, self.support.dimension] == pair[0]]
546
+ lower_points = points[points[:, self.support.dimension] == pair[1]]
547
+
548
+ upper_coords = upper_points[:, : self.support.dimension]
549
+ lower_coords = lower_points[:, : self.support.dimension]
550
+ upper_interpolation = self.support.get_element_for_location(upper_coords)
551
+ lower_interpolation = self.support.get_element_for_location(lower_coords)
552
+ if (~upper_interpolation[3]).sum() > 0:
553
+ logger.warning(
554
+ f"Upper points not in mesh {upper_points[~upper_interpolation[3]]}"
555
+ )
556
+ if (~lower_interpolation[3]).sum() > 0:
557
+ logger.warning(
558
+ f"Lower points not in mesh {lower_points[~lower_interpolation[3]]}"
559
+ )
560
+ ij = np.array(
561
+ [
562
+ *np.meshgrid(
563
+ np.arange(0, int(upper_interpolation[3].sum()), dtype=int),
564
+ np.arange(0, int(lower_interpolation[3].sum()), dtype=int),
565
+ )
566
+ ],
567
+ dtype=int,
568
+ )
569
+
570
+ ij = ij.reshape(2, -1).T
571
+ rows = np.arange(0, ij.shape[0], dtype=int)
572
+ rows = np.tile(rows, (upper_interpolation[1].shape[-1], 1)).T
573
+ rows = np.hstack([rows, rows])
574
+ a = upper_interpolation[1][upper_interpolation[3]][ij[:, 0]]
575
+ a = np.hstack([a, -lower_interpolation[1][lower_interpolation[3]][ij[:, 1]]])
576
+ cols = np.hstack(
577
+ [
578
+ self.support.elements[
579
+ upper_interpolation[2][upper_interpolation[3]][ij[:, 0]]
580
+ ],
581
+ self.support.elements[
582
+ lower_interpolation[2][lower_interpolation[3]][ij[:, 1]]
583
+ ],
584
+ ]
585
+ )
586
+
587
+ bounds = np.zeros((ij.shape[0], 2))
588
+ bounds[:, 0] = lower_bound
589
+ bounds[:, 1] = upper_bound
590
+
591
+ self.add_inequality_constraints_to_matrix(
592
+ a, bounds, cols, f"inequality_pairs_{pair[0]}_{pair[1]}"
593
+ )
594
+
595
+ def add_inequality_feature(
596
+ self,
597
+ feature: Callable[[np.ndarray], np.ndarray],
598
+ lower: bool = True,
599
+ mask: np.ndarray | None = None,
600
+ ):
601
+ """Add an inequality constraint to the interpolator using an existing feature.
602
+ This will make the interpolator greater than or less than the exising feature.
603
+ Evaluate the feature at the interpolation nodes.
604
+ Can provide a boolean mask to restrict to only some parts
605
+
606
+ Parameters
607
+ ----------
608
+ feature : BaseFeature
609
+ the feature that will be used to constraint the interpolator
610
+ lower : bool, optional
611
+ lower or upper constraint, by default True
612
+ mask : np.ndarray, optional
613
+ restrict the nodes to evaluate on, by default None
614
+ """
615
+ # add inequality value for the nodes of the mesh
616
+ # flag lower determines whether the feature is a lower bound or upper bound
617
+ # mask is just a boolean array determining which nodes to apply it to
618
+
619
+ value = feature(self.support.nodes)
620
+ if mask is None:
621
+ mask = np.ones(value.shape[0], dtype=bool)
622
+ l = np.zeros(value.shape[0]) - np.inf
623
+ u = np.zeros(value.shape[0]) + np.inf
624
+ mask = np.logical_and(mask, ~np.isnan(value))
625
+ if lower:
626
+ l[mask] = value[mask]
627
+ if not lower:
628
+ u[mask] = value[mask]
629
+ bounds = np.column_stack([l, u])
630
+
631
+ self.add_inequality_constraints_to_matrix(
632
+ np.ones((value.shape[0], 1)),
633
+ bounds,
634
+ np.arange(0, self.dof, dtype=int)[:, None],
635
+ name="inequality_feature",
636
+ )
637
+
638
+ def add_equality_constraints(self, node_idx, values, name="undefined"):
639
+ """
640
+ Adds hard constraints to the least squares system. For now this just
641
+ sets
642
+ the node values to be fixed using a lagrangian.
643
+
644
+ Parameters
645
+ ----------
646
+ node_idx : numpy array/list
647
+ int array of node indexes
648
+ values : numpy array/list
649
+ array of node values
650
+
651
+ Returns
652
+ -------
653
+
654
+ """
655
+ idc = np.asarray(node_idx, dtype=int)
656
+ values = np.asarray(values)
657
+ inside = np.logical_and(idc >= 0, idc < self.dof)
658
+
659
+ self.equal_constraints[name] = {
660
+ "A": np.ones(idc[inside].shape[0]),
661
+ "B": values[inside],
662
+ "col": idc[inside],
663
+ # "w": w,
664
+ "row": np.arange(self.eq_const_c, self.eq_const_c + idc[inside].shape[0]),
665
+ }
666
+ self.eq_const_c += idc[inside].shape[0]
667
+
668
+ def add_tangent_constraints(self, w=1.0):
669
+ r"""Adds the constraints :math:`f(X)\cdotT=0`
670
+
671
+ Parameters
672
+ ----------
673
+ w : double
674
+
675
+
676
+ Returns
677
+ -------
678
+
679
+ """
680
+ points = self.get_tangent_constraints()
681
+ if points.shape[0] > 0:
682
+ self.add_gradient_orthogonal_constraints(points[:, :3], points[:, 3:6], w)
683
+
684
+ def _assemble_explicit_constraint_matrix(self) -> tuple[sparse.spmatrix, np.ndarray]:
685
+ """Stack every recorded explicit constraint (``self.constraints``,
686
+ i.e. data constraints and - unless ``regularisation_matrix_free`` is
687
+ active - regularisation constraints too) into a single sparse ``A, B``
688
+ pair. Extracted from ``build_matrix`` so the matrix-free-regularisation
689
+ + ``cg`` fast path (``_solve_with_cg_fused_regularisation``) can reuse
690
+ the data-only assembly without duplicating this loop.
691
+ """
692
+ mats = []
693
+ bs = []
694
+ for c in self.constraints.values():
695
+ if len(c["w"]) == 0:
696
+ continue
697
+ mats.append(c["matrix"].multiply(c["w"][:, None]))
698
+ bs.append(c["b"] * c["w"])
699
+ if len(mats) == 0:
700
+ A = sparse.csr_matrix((0, self.dof), dtype=float)
701
+ B = np.zeros(0, dtype=float)
702
+ else:
703
+ A = sparse.vstack(mats)
704
+ B = np.hstack(bs)
705
+ return A, B
706
+
707
+ def build_matrix(self):
708
+ """
709
+ Assemble constraints into interpolation matrix. Adds equaltiy
710
+ constraints
711
+ using lagrange modifiers if necessary
712
+
713
+ Parameters
714
+ ----------
715
+ damp: bool
716
+ Flag whether damping should be added to the diagonal of the matrix
717
+ Returns
718
+ -------
719
+ Interpolation matrix and B
720
+ """
721
+
722
+ A, B = self._assemble_explicit_constraint_matrix()
723
+
724
+ # Matrix-free regularisation (FiniteDifferenceInterpolator opt-in path,
725
+ # see `regularisation_matrix_free` / `get_regularisation_linear_operator`).
726
+ # When active, the structured-grid regularisation stencils were recorded
727
+ # as `matrix_free_regularisation_blocks` instead of being added to
728
+ # `self.constraints`, so `A`/`B` above only contain the explicit data
729
+ # constraints (value/gradient/normal/tangent/interface/... and anything
730
+ # else, e.g. directional regularisation, that was not diverted). Combine
731
+ # them with the matrix-free regularisation `LinearOperator` into a single
732
+ # combined `LinearOperator` so cg/lsmr can solve against the full system
733
+ # without ever materialising the regularisation stencils as a sparse
734
+ # matrix. This branch is a no-op (returns the explicit sparse matrix,
735
+ # exactly as before) unless the flag is set and blocks were recorded.
736
+ use_matrix_free_regularisation = bool(
737
+ getattr(self, "regularisation_matrix_free", False)
738
+ ) and bool(getattr(self, "matrix_free_regularisation_blocks", None))
739
+ if use_matrix_free_regularisation:
740
+ reg_operator = self.get_regularisation_linear_operator()
741
+ if reg_operator is not None:
742
+ n_data = A.shape[0]
743
+ A, B = self._combine_explicit_matrix_with_linear_operator(A, B, reg_operator)
744
+ logger.info(
745
+ "Interpolation matrix-free system is %d x %d (%d explicit rows + "
746
+ "%d matrix-free regularisation rows)",
747
+ A.shape[0],
748
+ A.shape[1],
749
+ n_data,
750
+ reg_operator.shape[0],
751
+ )
752
+ return A, B
753
+
754
+ logger.info(f"Interpolation matrix is {A.shape[0]} x {A.shape[1]}")
755
+ return A, B
756
+
757
+ def _combine_explicit_matrix_with_linear_operator(
758
+ self,
759
+ A: sparse.spmatrix,
760
+ B: np.ndarray,
761
+ reg_operator: LinearOperator,
762
+ ) -> tuple[LinearOperator, np.ndarray]:
763
+ """Combine an explicit sparse data-constraint matrix with a matrix-free
764
+ regularisation ``LinearOperator`` into a single ``LinearOperator``.
765
+
766
+ ``matvec``/``rmatvec`` stack the explicit data rows on top of the
767
+ matrix-free regularisation rows, matching the row order
768
+ ``sparse.vstack`` would otherwise use. The regularisation rows target
769
+ zero (see ``_assemble_operator``'s ``B = np.zeros(...)``), so the
770
+ combined right-hand side is the data ``B`` followed by zeros.
771
+ """
772
+ A = A.tocsr()
773
+ n_data = A.shape[0]
774
+ n_reg = reg_operator.shape[0]
775
+ dof = self.dof
776
+
777
+ def matvec(x):
778
+ x = np.asarray(x).reshape(-1)
779
+ return np.concatenate([A @ x, reg_operator.matvec(x)])
780
+
781
+ def rmatvec(y):
782
+ y = np.asarray(y).reshape(-1)
783
+ return A.T @ y[:n_data] + reg_operator.rmatvec(y[n_data:])
784
+
785
+ combined = LinearOperator(
786
+ shape=(n_data + n_reg, dof), matvec=matvec, rmatvec=rmatvec, dtype=float
787
+ )
788
+ combined_b = np.concatenate([np.asarray(B, dtype=float).reshape(-1), np.zeros(n_reg)])
789
+ return combined, combined_b
790
+
791
+ def _materialise_matrix_free_regularisation_blocks(self) -> None:
792
+ """Fallback used when a solver that cannot consume a ``LinearOperator``
793
+ (currently: ``admm``) is selected while ``regularisation_matrix_free=True``.
794
+
795
+ Converts every recorded matrix-free regularisation block back into an
796
+ explicit sparse constraint (the same rows ``_assemble_operator`` would
797
+ have built with ``regularisation_matrix_free=False``) and clears the
798
+ matrix-free state so the ordinary explicit ``build_matrix`` path is used
799
+ for this solve. This mirrors the existing ``apply_scaling_matrix``
800
+ fallback pattern in ``FiniteDifferenceInterpolator.setup_interpolator``.
801
+ """
802
+ blocks = getattr(self, "matrix_free_regularisation_blocks", None)
803
+ if not blocks:
804
+ return
805
+ for name, block in blocks.items():
806
+ idc = block["idc"]
807
+ values = block["values"]
808
+ row_w = block["w"]
809
+ a = np.tile(values, (idc.shape[0], 1))
810
+ b = np.zeros(idc.shape[0])
811
+ self.add_constraints_to_least_squares(a, b, idc, w=row_w, name=name)
812
+ self.matrix_free_regularisation_blocks = {}
813
+ self.regularisation_matrix_free = False
814
+
815
+ def compute_column_scaling_matrix(self, A: sparse.csr_matrix) -> sparse.dia_matrix:
816
+ """Compute column scaling matrix S for matrix A so that A @ S has columns with unit norm.
817
+
818
+ Parameters
819
+ ----------
820
+ A : sparse.csr_matrix
821
+ interpolation matrix
822
+
823
+ Returns
824
+ -------
825
+ scipy.sparse.dia_matrix
826
+ diagonal scaling matrix S
827
+ """
828
+ col_norms = sparse.linalg.norm(A, axis=0)
829
+ scaling_factors = np.ones(A.shape[1])
830
+ mask = col_norms > 0
831
+ scaling_factors[mask] = 1.0 / col_norms[mask]
832
+ S = sparse.diags(scaling_factors)
833
+ return S
834
+
835
+ def add_equality_block(self, A, B):
836
+ if len(self.equal_constraints) > 0:
837
+ ATA = A.T.dot(A)
838
+ ATB = A.T.dot(B)
839
+ logger.info(f"Equality block is {self.eq_const_c} x {self.dof}")
840
+ # solving constrained least squares using
841
+ # | ATA CT | |c| = b
842
+ # | C 0 | |y| d
843
+ # where A is the interpoaltion matrix
844
+ # C is the equality constraint matrix
845
+ # b is the interpolation constraints to be honoured
846
+ # in a least squares sense
847
+ # and d are the equality constraints
848
+ # c are the node values and y are the
849
+ # lagrange multipliers#
850
+ a = []
851
+ rows = []
852
+ cols = []
853
+ b = []
854
+ for c in self.equal_constraints.values():
855
+ b.extend((c["B"]).tolist())
856
+ aa = c["A"].flatten()
857
+ mask = aa == 0
858
+ a.extend(aa[~mask].tolist())
859
+ rows.extend(c["row"].flatten()[~mask].tolist())
860
+ cols.extend(c["col"].flatten()[~mask].tolist())
861
+
862
+ C = sparse.coo_matrix(
863
+ (np.array(a), (np.array(rows), cols)),
864
+ shape=(self.eq_const_c, self.dof),
865
+ dtype=float,
866
+ ).tocsr()
867
+
868
+ d = np.array(b)
869
+ ATA = sparse.bmat([[ATA, C.T], [C, None]])
870
+ ATB = np.hstack([ATB, d])
871
+
872
+ return ATA, ATB
873
+
874
+ def build_inequality_matrix(self):
875
+ mats = []
876
+ bounds = []
877
+ for c in self.ineq_constraints.values():
878
+ mats.append(c["matrix"])
879
+ bounds.append(c["bounds"])
880
+ if len(mats) == 0:
881
+ return sparse.csr_matrix((0, self.dof), dtype=float), np.zeros((0, 3))
882
+ Q = sparse.vstack(mats)
883
+ bounds = np.vstack(bounds)
884
+ return Q, bounds
885
+
886
+ def _remove_constraints_with_prefix(self, prefix: str) -> None:
887
+ to_remove = [name for name in self.constraints if name.startswith(prefix)]
888
+ for name in to_remove:
889
+ self.constraints.pop(name, None)
890
+
891
+ def _constant_norm_gradient_data(self):
892
+ support = self.support
893
+ if not hasattr(support, "elements") or not hasattr(support, "barycentre"):
894
+ return None
895
+
896
+ try:
897
+ element_indices = np.arange(support.elements.shape[0], dtype=int)
898
+ _, gradient, elements, inside = support.get_element_gradient_for_location(
899
+ support.barycentre[element_indices]
900
+ )
901
+ except (AttributeError, TypeError, ValueError) as err:
902
+ logger.debug("Unable to build constant-norm gradient rows: %s", err)
903
+ return None
904
+
905
+ inside = np.asarray(inside, dtype=bool)
906
+ gradient = np.asarray(gradient, dtype=float)
907
+ if inside.shape[0] != gradient.shape[0]:
908
+ inside = np.ones(gradient.shape[0], dtype=bool)
909
+ if not np.any(inside):
910
+ return None
911
+
912
+ element_ids = np.asarray(elements, dtype=int)[inside]
913
+ gradient = gradient[inside]
914
+ idc = np.asarray(support.elements[element_ids], dtype=int)
915
+ values = np.asarray(self.c[idc], dtype=float)
916
+ grad_vec = np.einsum("ijk,ik->ij", gradient, values)
917
+ grad_norm = np.linalg.norm(grad_vec, axis=1)
918
+ valid = np.isfinite(grad_norm) & (grad_norm > 1e-10)
919
+ if not np.any(valid):
920
+ return None
921
+
922
+ volume = np.ones(np.sum(valid), dtype=float)
923
+ if hasattr(support, "element_size"):
924
+ raw_volume = np.asarray(support.element_size, dtype=float)
925
+ if raw_volume.ndim == 0:
926
+ volume = np.full(np.sum(valid), float(raw_volume), dtype=float)
927
+ else:
928
+ volume = raw_volume[element_ids][valid]
929
+ volume = np.maximum(volume, 1e-12)
930
+
931
+ return {
932
+ "gradient": gradient[valid],
933
+ "grad_vec": grad_vec[valid],
934
+ "grad_norm": grad_norm[valid],
935
+ "idc": idc[valid],
936
+ "volume": volume,
937
+ }
938
+
939
+ def _run_constant_norm_polish(
940
+ self,
941
+ solver_kwargs: dict,
942
+ iterations: int,
943
+ base_weight: float,
944
+ target_norm: float | None,
945
+ ) -> None:
946
+ if iterations <= 0 or base_weight <= 0.0:
947
+ return
948
+
949
+ if not np.all(np.isfinite(self.c)):
950
+ logger.warning("Skipping constant-norm polish because current solution is not finite")
951
+ return
952
+
953
+ prefix = "__constant_norm_polish__"
954
+ self._remove_constraints_with_prefix(prefix)
955
+
956
+ stable_solver_kwargs = dict(solver_kwargs or {})
957
+ stable_solver_kwargs.pop("x0", None)
958
+
959
+ for i in range(int(iterations)):
960
+ grad_data = self._constant_norm_gradient_data()
961
+ if grad_data is None:
962
+ logger.warning("Constant-norm polish stopped: gradient rows unavailable")
963
+ break
964
+
965
+ if target_norm is None:
966
+ norm_target = float(np.median(grad_data["grad_norm"]))
967
+ else:
968
+ norm_target = float(target_norm)
969
+
970
+ unit_grad = grad_data["grad_vec"] / grad_data["grad_norm"][:, None]
971
+ A = np.einsum("ij,ijk->ik", unit_grad, grad_data["gradient"])
972
+ A = A / grad_data["volume"][:, None]
973
+ b = np.full(A.shape[0], norm_target, dtype=float) / grad_data["volume"]
974
+ iter_weight = float(base_weight) * float(i + 1)
975
+
976
+ self.add_constraints_to_least_squares(
977
+ A,
978
+ b,
979
+ grad_data["idc"],
980
+ w=np.full(A.shape[0], iter_weight, dtype=float),
981
+ name=f"{prefix}{i}",
982
+ )
983
+
984
+ x0_seed = np.asarray(self.c[self.region], dtype=float).copy()
985
+ polish_solver_kwargs = dict(stable_solver_kwargs)
986
+ polish_solver_kwargs["x0"] = lambda _support, x0=x0_seed: np.array(x0, copy=True)
987
+ polish_solver_kwargs["constant_norm_iterations"] = 0
988
+
989
+ solved = self.solve_system("admm", solver_kwargs=polish_solver_kwargs)
990
+ if not solved:
991
+ logger.warning("Constant-norm polish terminated because ADMM solve failed")
992
+ break
993
+
994
+ updated = self._constant_norm_gradient_data()
995
+ if updated is not None:
996
+ logger.info(
997
+ "Constant-norm iter %d: target=%.3e, grad_norm mean=%.3e, std=%.3e",
998
+ i + 1,
999
+ norm_target,
1000
+ float(np.mean(updated["grad_norm"])),
1001
+ float(np.std(updated["grad_norm"])),
1002
+ )
1003
+
1004
+ self._remove_constraints_with_prefix(prefix)
1005
+
1006
+ def _normalise_solver_choice(
1007
+ self,
1008
+ solver: Callable[[sparse.csr_matrix, np.ndarray], np.ndarray] | str | None,
1009
+ ):
1010
+ return _solver_strategy.resolve_solver_choice(solver, logger)
1011
+
1012
+ def _assemble_main_system(self, timing: dict) -> tuple[sparse.spmatrix, np.ndarray]:
1013
+ return _solver_pipeline.assemble_main_system(self.build_matrix, timing)
1014
+
1015
+ def _preprocess_main_system(
1016
+ self,
1017
+ A: sparse.spmatrix,
1018
+ b: np.ndarray,
1019
+ timing: dict,
1020
+ ) -> tuple[sparse.spmatrix, np.ndarray, sparse.spmatrix | None]:
1021
+ return _solver_pipeline.preprocess_main_system(
1022
+ A=A,
1023
+ b=b,
1024
+ add_ridge_regularisation=self.add_ridge_regulatisation,
1025
+ ridge_factor=self.ridge_factor,
1026
+ apply_scaling_matrix=self.apply_scaling_matrix,
1027
+ compute_column_scaling_matrix_fn=self.compute_column_scaling_matrix,
1028
+ logger=logger,
1029
+ timing=timing,
1030
+ )
1031
+
1032
+ def _assemble_inequality_system(self, timing: dict) -> tuple[sparse.spmatrix, np.ndarray]:
1033
+ return _solver_pipeline.assemble_inequality_system(self.build_inequality_matrix, timing)
1034
+
1035
+ def _solve_with_callable(
1036
+ self,
1037
+ solver: Callable[[sparse.csr_matrix, np.ndarray], np.ndarray],
1038
+ A: sparse.spmatrix,
1039
+ b: np.ndarray,
1040
+ timing: dict,
1041
+ ) -> bool:
1042
+ self.c, ok = _solver_strategy.solve_with_callable(solver, A, b, timing, logger)
1043
+ return ok
1044
+
1045
+ def _solve_with_cg(
1046
+ self,
1047
+ A: sparse.spmatrix,
1048
+ b: np.ndarray,
1049
+ tol: float | None,
1050
+ solver_kwargs: dict,
1051
+ timing: dict,
1052
+ ) -> bool:
1053
+ self.c, ok = _solver_strategy.solve_with_cg(A, b, tol, solver_kwargs, timing, logger)
1054
+ return ok
1055
+
1056
+ def _use_fused_cg_regularisation(self, solver_choice) -> bool:
1057
+ """Whether the fused-kernel matrix-free-regularisation CG fast path
1058
+ (``_solve_with_cg_fused_regularisation``) should be used for this
1059
+ solve, instead of the generic ``build_matrix`` + ``A.T @ A`` path.
1060
+
1061
+ Only ever true for ``solver_choice == "cg"`` with
1062
+ ``regularisation_matrix_free=True`` and recorded blocks (i.e. exactly
1063
+ the case that otherwise builds the combined rectangular
1064
+ ``LinearOperator`` via ``_combine_explicit_matrix_with_linear_operator``
1065
+ and squares it generically in ``_solver_strategy.solve_with_cg``).
1066
+ Interpolators that never set `matrix_free_regularisation_blocks`
1067
+ (P1/P2/anything else) or that don't define the fused-operator builder
1068
+ (anything but ``FiniteDifferenceInterpolator``) always take the
1069
+ existing, unmodified path.
1070
+ """
1071
+ return bool(
1072
+ solver_choice == "cg"
1073
+ and getattr(self, "regularisation_matrix_free", False)
1074
+ and getattr(self, "matrix_free_regularisation_blocks", None)
1075
+ and not getattr(self, "apply_scaling_matrix", False)
1076
+ and hasattr(self, "_build_fused_cg_regularisation_operator")
1077
+ )
1078
+
1079
+ def _solve_with_cg_fused_regularisation(
1080
+ self,
1081
+ tol: float | None,
1082
+ solver_kwargs: dict,
1083
+ timing: dict,
1084
+ ) -> bool:
1085
+ """CG fast path for ``regularisation_matrix_free=True``: assemble the
1086
+ normal-equations system ``(A_data^T A_data + R_reg^T R_reg) x =
1087
+ A_data^T b_data`` directly, using the fused single-kernel + boundary-
1088
+ corrected regularisation operator
1089
+ (``FiniteDifferenceInterpolator._build_fused_cg_regularisation_operator``)
1090
+ for the ``R_reg^T R_reg`` term, instead of assembling a combined
1091
+ rectangular ``LinearOperator`` (data rows stacked on top of
1092
+ regularisation rows) and letting ``scipy.sparse.linalg.cg`` square it
1093
+ generically via ``A.T @ A`` (which re-derives the same normal
1094
+ equations but pays for a matvec-then-rmatvec pass over the
1095
+ regularisation rows every CG iteration instead of one fused
1096
+ convolution call).
1097
+
1098
+ Ridge regularisation (``add_ridge_regulatisation``) contributes exactly
1099
+ ``ridge_factor**2 * x`` to the normal-equations LHS (and nothing to
1100
+ the RHS) for any ``x``; it's added directly to the precomputed data
1101
+ Gram matrix's diagonal rather than appended as ``ridge_factor * I``
1102
+ rows to ``A_data`` first (as ``_solver_pipeline.preprocess_main_system``
1103
+ does for the non-matrix-free case) purely so the one-off
1104
+ ``A_data.T @ A_data`` product below stays a small, cheap
1105
+ (n_data-row-driven) sparse-sparse product instead of a
1106
+ ``(n_data + dof)``-row one; both are exact and mathematically
1107
+ equivalent. ``apply_scaling_matrix`` is always forced off before this
1108
+ path can be selected (see ``_use_fused_cg_regularisation``), matching
1109
+ ``FiniteDifferenceInterpolator.setup_interpolator``'s existing
1110
+ column-scaling fallback.
1111
+
1112
+ The data-constraint block's normal-equations contribution
1113
+ (``A_data.T @ A_data``) is precomputed ONCE as an explicit sparse
1114
+ matrix here (data constraint rows are comparatively few - value/
1115
+ gradient/norm/etc. constraints, not the O(dof) regularisation rows -
1116
+ so this product is cheap and its fill-in bounded), so each CG
1117
+ iteration is a single fast precomputed-sparse-matrix matvec for the
1118
+ data term plus the fused regularisation term, instead of two
1119
+ separate sparse matvecs (``A_data @ x`` then ``A_data.T @ (...)``)
1120
+ every iteration.
1121
+ """
1122
+ assembly_started = perf_counter()
1123
+ A_data, b_data = self._assemble_explicit_constraint_matrix()
1124
+ A_data = A_data.tocsr()
1125
+ dof = self.dof
1126
+
1127
+ AtA_data = (A_data.T @ A_data).tocsr()
1128
+ rhs = np.asarray(A_data.T @ b_data).reshape(-1)
1129
+ if self.add_ridge_regulatisation:
1130
+ AtA_data = AtA_data + sparse.eye(dof, format="csr") * (self.ridge_factor**2)
1131
+
1132
+ reg_operator = self._build_fused_cg_regularisation_operator()
1133
+ timing["assembly_seconds"] = perf_counter() - assembly_started
1134
+ timing["matrix_rows"] = int(A_data.shape[0])
1135
+ timing["matrix_cols"] = int(A_data.shape[1])
1136
+ timing["matrix_nnz"] = int(A_data.nnz)
1137
+
1138
+ preprocess_started = perf_counter()
1139
+
1140
+ def matvec(x):
1141
+ x = np.asarray(x, dtype=float).reshape(-1)
1142
+ out = AtA_data @ x
1143
+ if reg_operator is not None:
1144
+ out = out + reg_operator.matvec(x)
1145
+ return np.asarray(out).reshape(-1)
1146
+
1147
+ normal_operator = LinearOperator(
1148
+ shape=(dof, dof), matvec=matvec, rmatvec=matvec, dtype=float
1149
+ )
1150
+ timing["preprocess_seconds"] = perf_counter() - preprocess_started
1151
+
1152
+ self.c, ok = _solver_strategy.solve_with_cg_normal_equations(
1153
+ normal_operator, rhs, tol, solver_kwargs, timing, logger
1154
+ )
1155
+ return ok
1156
+
1157
+ def _solve_with_lsmr(
1158
+ self,
1159
+ A: sparse.spmatrix,
1160
+ b: np.ndarray,
1161
+ tol: float | None,
1162
+ solver_kwargs: dict,
1163
+ timing: dict,
1164
+ ) -> bool:
1165
+ self.c, ok = _solver_strategy.solve_with_lsmr(A, b, tol, solver_kwargs, timing, logger)
1166
+ return ok
1167
+
1168
+ def _extract_admm_kwargs(self, solver_kwargs: dict, admm_solve) -> tuple[str, dict]:
1169
+ return _solver_strategy.extract_admm_kwargs(solver_kwargs, admm_solve)
1170
+
1171
+ def _solve_with_admm(
1172
+ self,
1173
+ A: sparse.spmatrix,
1174
+ b: np.ndarray,
1175
+ Q: sparse.spmatrix,
1176
+ bounds: np.ndarray,
1177
+ solver_kwargs: dict,
1178
+ timing: dict,
1179
+ constant_norm_iterations: int,
1180
+ constant_norm_weight: float,
1181
+ constant_norm_target: float | None,
1182
+ ) -> bool:
1183
+ logger.info("Solving using admm")
1184
+
1185
+ constant_norm_solver_kwargs = dict(solver_kwargs)
1186
+ if Q is None:
1187
+ logger.warning("No inequality constraints, using lsmr")
1188
+ return self.solve_system("lsmr", solver_kwargs=solver_kwargs)
1189
+
1190
+ try:
1191
+ c, history, ok = _solver_strategy.solve_with_admm(
1192
+ A,
1193
+ b,
1194
+ Q,
1195
+ bounds,
1196
+ solver_kwargs,
1197
+ timing,
1198
+ self.support,
1199
+ logger,
1200
+ )
1201
+ if not ok:
1202
+ return False
1203
+ self.c = c
1204
+ self.solver_history = history
1205
+
1206
+ if constant_norm_iterations > 0 and constant_norm_weight > 0.0:
1207
+ self._run_constant_norm_polish(
1208
+ solver_kwargs=constant_norm_solver_kwargs,
1209
+ iterations=constant_norm_iterations,
1210
+ base_weight=constant_norm_weight,
1211
+ target_norm=constant_norm_target,
1212
+ )
1213
+ return True
1214
+ except ValueError as e:
1215
+ logger.error(f"ADMM solver failed: {e}")
1216
+ return False
1217
+ except ImportError:
1218
+ logger.warning("Cannot import embedded admm solver. Use lsmr or cg")
1219
+ return False
1220
+
1221
+ def solve_system(
1222
+ self,
1223
+ solver: Callable[[sparse.csr_matrix, np.ndarray], np.ndarray] | str | None = None,
1224
+ tol: float | None = None,
1225
+ solver_kwargs: dict | None = None,
1226
+ ) -> bool:
1227
+ """
1228
+ Main entry point to run the solver and update the node value
1229
+ attribute for the
1230
+ discreteinterpolator class
1231
+
1232
+ Parameters
1233
+ ----------
1234
+ solver : string/callable
1235
+ solver 'cg' conjugate gradient, 'lsmr' or callable function
1236
+ solver_kwargs
1237
+ kwargs for solver check scipy documentation for more information
1238
+
1239
+ Returns
1240
+ -------
1241
+ bool
1242
+ True if the interpolation is run
1243
+
1244
+ """
1245
+ if not self._pre_solve():
1246
+ raise ValueError("Pre solve failed")
1247
+
1248
+ solve_started = perf_counter()
1249
+ solver_choice = self._normalise_solver_choice(solver)
1250
+ solver_kwargs = dict(solver_kwargs or {})
1251
+ constant_norm_iterations, constant_norm_weight, constant_norm_target = (
1252
+ _solver_pipeline.extract_constant_norm_options(solver_kwargs, logger)
1253
+ )
1254
+ timing = _solver_pipeline.init_timing(solver_choice)
1255
+
1256
+ self.solver_history = None
1257
+
1258
+ if solver_choice == "admm" and getattr(self, "regularisation_matrix_free", False) and getattr(
1259
+ self, "matrix_free_regularisation_blocks", None
1260
+ ):
1261
+ logger.warning(
1262
+ "regularisation_matrix_free=True is not supported with solver='admm' "
1263
+ "(ADMM's inequality-constrained solve needs an explicit sparse system matrix); "
1264
+ "falling back to explicit regularisation assembly for this solve."
1265
+ )
1266
+ self._materialise_matrix_free_regularisation_blocks()
1267
+
1268
+ Q, bounds = self._assemble_inequality_system(timing)
1269
+ # Legacy compatibility: ignore deprecated backend switch.
1270
+ solver_kwargs.pop("backend", None)
1271
+
1272
+ scaling_matrix = None
1273
+ if self._use_fused_cg_regularisation(solver_choice):
1274
+ # Fast path: build the CG normal equations directly, using a
1275
+ # fused single-kernel + boundary-corrected regularisation
1276
+ # operator instead of the generic combined-LinearOperator
1277
+ # `build_matrix` + `A.T @ A` route (still used, unchanged, for
1278
+ # every other solver/case below). See
1279
+ # `_solve_with_cg_fused_regularisation` / `FiniteDifferenceInterpolator.
1280
+ # _build_fused_cg_regularisation_operator`.
1281
+ self.up_to_date = self._solve_with_cg_fused_regularisation(
1282
+ tol, solver_kwargs, timing
1283
+ )
1284
+ else:
1285
+ A, b = self._assemble_main_system(timing)
1286
+ A, b, scaling_matrix = self._preprocess_main_system(A, b, timing)
1287
+
1288
+ if callable(solver_choice):
1289
+ self.up_to_date = self._solve_with_callable(solver_choice, A, b, timing)
1290
+ elif solver_choice == "cg":
1291
+ self.up_to_date = self._solve_with_cg(A, b, tol, solver_kwargs, timing)
1292
+ elif solver_choice == "lsmr":
1293
+ self.up_to_date = self._solve_with_lsmr(A, b, tol, solver_kwargs, timing)
1294
+ elif solver_choice == "admm":
1295
+ self.up_to_date = self._solve_with_admm(
1296
+ A,
1297
+ b,
1298
+ Q,
1299
+ bounds,
1300
+ solver_kwargs,
1301
+ timing,
1302
+ constant_norm_iterations,
1303
+ constant_norm_weight,
1304
+ constant_norm_target,
1305
+ )
1306
+ else:
1307
+ logger.error(f"Unknown solver {solver_choice}")
1308
+ self.up_to_date = False
1309
+
1310
+ # self._post_solve()
1311
+ # apply scaling matrix to solution
1312
+ if scaling_matrix is not None:
1313
+ self.c = scaling_matrix @ self.c
1314
+ self.latest_solve_timing = _solver_pipeline.finalize_timing(
1315
+ timing=timing,
1316
+ solve_started=solve_started,
1317
+ up_to_date=bool(self.up_to_date),
1318
+ )
1319
+ return self.up_to_date
1320
+
1321
+ def update(self) -> bool:
1322
+ """
1323
+ Check if the solver is up to date, if not rerun interpolation using
1324
+ the previously used solver. If the interpolation has not been run
1325
+ before it will
1326
+ return False
1327
+
1328
+ Returns
1329
+ -------
1330
+ bool
1331
+
1332
+ """
1333
+ if self.solver is None:
1334
+ logger.debug("Cannot rerun interpolator")
1335
+ return False
1336
+ if not self.up_to_date:
1337
+ self.setup_interpolator()
1338
+ self.up_to_date = self.solve_system(self.solver)
1339
+ return self.up_to_date
1340
+ return bool(self.up_to_date)
1341
+
1342
+ def _evaluate_value_local(self, locations: np.ndarray) -> np.ndarray:
1343
+ """Evaluate the value of the interpolator at location
1344
+
1345
+ Parameters
1346
+ ----------
1347
+ evaluation_points : np.ndarray
1348
+ location to evaluate the interpolator
1349
+
1350
+ Returns
1351
+ -------
1352
+ np.ndarray
1353
+ value of the interpolator
1354
+ """
1355
+ self.update()
1356
+ evaluation_points = np.array(locations)
1357
+ evaluated = np.zeros(evaluation_points.shape[0])
1358
+ mask = np.any(np.isnan(evaluation_points), axis=1)
1359
+
1360
+ if evaluation_points[~mask, :].shape[0] > 0:
1361
+ evaluated[~mask] = self.support.evaluate_value(evaluation_points[~mask], self.c)
1362
+ return evaluated
1363
+
1364
+ def _evaluate_gradient_local(self, locations: np.ndarray) -> np.ndarray:
1365
+ """
1366
+ Evaluate the gradient of the scalar field at the evaluation points
1367
+ Parameters
1368
+ ----------
1369
+ evaluation_points : np.array
1370
+ xyz locations to evaluate the gradient
1371
+
1372
+ Returns
1373
+ -------
1374
+
1375
+ """
1376
+ self.update()
1377
+ if locations.shape[0] > 0:
1378
+ return self.support.evaluate_gradient(locations, self.c)
1379
+ return np.zeros((0, 3))
1380
+
1381
+ def to_dict(self):
1382
+ return {
1383
+ "type": self.type.name,
1384
+ "support": self.support.to_dict(),
1385
+ "c": np.asarray(self.c).tolist(),
1386
+ **super().to_dict(),
1387
+ # 'region_function':self.region_function,
1388
+ }
1389
+
1390
+ def vtk(self):
1391
+ if self.up_to_date is False:
1392
+ self.update()
1393
+ return self.support.vtk({"c": self.c})
1394
+
1395
+ def surfaces(self, value, **kwargs):
1396
+ from loop_common.geometry._surface import Surface
1397
+
1398
+ if self.up_to_date is False:
1399
+ self.update()
1400
+ mesh = self.support.vtk({"c": self.c})
1401
+ contour = mesh.contour([value], scalars="c")
1402
+ if contour.n_points == 0:
1403
+ return []
1404
+ triangles = contour.faces.reshape(-1, 4)[:, 1:]
1405
+ return [Surface(vertices=contour.points.copy(), triangles=triangles)]