loop-interpolation 0.0.2__tar.gz → 0.2.0__tar.gz

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 (75) hide show
  1. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/PKG-INFO +3 -1
  2. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/pyproject.toml +2 -1
  3. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/__init__.py +7 -0
  4. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_discrete_fold_interpolator.py +21 -31
  5. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_discrete_interpolator.py +136 -20
  6. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_fd_fold_interpolator.py +4 -1
  7. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_finite_difference_interpolator.py +26 -7
  8. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_interpolator_builder.py +12 -0
  9. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_interpolatortype.py +1 -0
  10. loop_interpolation-0.2.0/src/loop_interpolation/_native.py +562 -0
  11. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_p1interpolator.py +2 -0
  12. loop_interpolation-0.2.0/src/loop_interpolation/_p2_fold_interpolator.py +144 -0
  13. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_p2interpolator.py +23 -22
  14. loop_interpolation-0.2.0/src/loop_interpolation/_quadrature.py +75 -0
  15. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_solver_pipeline.py +70 -0
  16. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_solver_strategy.py +23 -9
  17. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation.egg-info/PKG-INFO +3 -1
  18. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation.egg-info/SOURCES.txt +11 -0
  19. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation.egg-info/requires.txt +3 -0
  20. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_discrete_fold_interpolator.py +41 -44
  21. loop_interpolation-0.2.0/tests/test_native_errors.py +254 -0
  22. loop_interpolation-0.2.0/tests/test_native_inequality.py +347 -0
  23. loop_interpolation-0.2.0/tests/test_native_no_rows.py +263 -0
  24. loop_interpolation-0.2.0/tests/test_native_parity.py +342 -0
  25. loop_interpolation-0.2.0/tests/test_native_warm_start_ridge.py +116 -0
  26. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_p0_nan_constraints_skipped.py +48 -11
  27. loop_interpolation-0.2.0/tests/test_p2_fold_interpolator.py +259 -0
  28. loop_interpolation-0.2.0/tests/test_p2_fold_registration.py +39 -0
  29. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_p2_interpolator.py +32 -0
  30. loop_interpolation-0.2.0/tests/test_quadrature.py +58 -0
  31. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_solver_pipeline.py +39 -0
  32. loop_interpolation-0.2.0/tests/test_solver_strategy.py +231 -0
  33. loop_interpolation-0.0.2/tests/test_solver_strategy.py +0 -131
  34. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/LICENSE +0 -0
  35. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/README.md +0 -0
  36. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/setup.cfg +0 -0
  37. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_builders.py +0 -0
  38. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_constant_norm.py +0 -0
  39. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_diagnostics.py +0 -0
  40. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_fold_event.py +0 -0
  41. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_fold_norm_alignment.py +0 -0
  42. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_fold_setup.py +0 -0
  43. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_geological_interpolator.py +0 -0
  44. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_interpolator_factory.py +0 -0
  45. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_operator.py +0 -0
  46. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_regularisation.py +0 -0
  47. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_surfe_wrapper.py +0 -0
  48. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_svariogram.py +0 -0
  49. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/_validation.py +0 -0
  50. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/constraints.py +0 -0
  51. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/fold_function/__init__.py +0 -0
  52. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/fold_function/_base_fold_rotation_angle.py +0 -0
  53. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/fold_function/_fourier_series_fold_rotation_angle.py +0 -0
  54. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/fold_function/_lambda_fold_rotation_angle.py +0 -0
  55. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/loopsolver/__init__.py +0 -0
  56. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/loopsolver/admm_constant_norm.py +0 -0
  57. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/loopsolver/admm_method.py +0 -0
  58. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation/loopsolver/admm_solver.py +0 -0
  59. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation.egg-info/dependency_links.txt +0 -0
  60. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/src/loop_interpolation.egg-info/top_level.txt +0 -0
  61. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_admm_matrix_free.py +0 -0
  62. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_constraint_diagnostics_report.py +0 -0
  63. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_constraints.py +0 -0
  64. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_discrete_interpolator.py +0 -0
  65. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_fd_fold_interpolator.py +0 -0
  66. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_fdi_matrix_free_regularisation.py +0 -0
  67. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_geological_interpolator.py +0 -0
  68. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_import.py +0 -0
  69. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_input_validation.py +0 -0
  70. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_interpolator_builder.py +0 -0
  71. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_normal_magnitude_interpolators.py +0 -0
  72. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_p0_surfe_nans.py +0 -0
  73. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_rectilinear_interpolator.py +0 -0
  74. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_regularisation_api.py +0 -0
  75. {loop_interpolation-0.0.2 → loop_interpolation-0.2.0}/tests/test_surfe_rbf_interpolator.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: loop-interpolation
3
- Version: 0.0.2
3
+ Version: 0.2.0
4
4
  Summary: Interpolation utilities for LoopStructural
5
5
  Author-email: Lachlan Grose <lachlan.grose@monash.edu>
6
6
  License: MIT
@@ -24,6 +24,8 @@ Requires-Dist: scipy
24
24
  Requires-Dist: pydantic
25
25
  Provides-Extra: tests
26
26
  Requires-Dist: pytest; extra == "tests"
27
+ Provides-Extra: native
28
+ Requires-Dist: loop-interpolation-core; extra == "native"
27
29
  Dynamic: license-file
28
30
 
29
31
  # loop-interpolation
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
  [project]
6
6
  name = "loop-interpolation"
7
7
  description = "Interpolation utilities for LoopStructural"
8
- version = "0.0.2"
8
+ version = "0.2.0"
9
9
  requires-python = ">=3.9"
10
10
  authors = [{ name = "Lachlan Grose", email = "lachlan.grose@monash.edu" }]
11
11
  readme = "README.md"
@@ -27,6 +27,7 @@ dependencies = ["loop-common", "numpy", "scipy", "pydantic"]
27
27
 
28
28
  [project.optional-dependencies]
29
29
  tests = ["pytest"]
30
+ native = ["loop-interpolation-core"]
30
31
 
31
32
  [tool.setuptools.packages.find]
32
33
  where = ["src"]
@@ -23,6 +23,7 @@ __all__ = [
23
23
  "LambdaFoldRotationAngleProfile",
24
24
  "P1Interpolator",
25
25
  "P1Unstructured2d",
26
+ "P2FoldInterpolator",
26
27
  "P2Interpolator",
27
28
  "P2Unstructured2d",
28
29
  "P2UnstructuredTetMesh",
@@ -72,6 +73,7 @@ from ._p1interpolator import P1Interpolator
72
73
  from ._p1interpolator import (
73
74
  P1Interpolator as PiecewiseLinearInterpolator,
74
75
  )
76
+ from ._p2_fold_interpolator import P2FoldInterpolator
75
77
  from ._p2interpolator import P2Interpolator
76
78
  from ._regularisation import DirectionalRegularisation, RegularisationConfig
77
79
 
@@ -96,6 +98,7 @@ interpolator_string_map = {
96
98
  "PLI": InterpolatorType.PIECEWISE_LINEAR,
97
99
  "P2": InterpolatorType.PIECEWISE_QUADRATIC,
98
100
  "P1": InterpolatorType.PIECEWISE_LINEAR,
101
+ "P2Fold": InterpolatorType.PIECEWISE_QUADRATIC_FOLD,
99
102
  "DFI": InterpolatorType.DISCRETE_FOLD,
100
103
  "surfe": InterpolatorType.SURFE,
101
104
  "FDI_CN": InterpolatorType.FINITE_DIFFERENCE_CONSTANT_NORM,
@@ -110,6 +113,7 @@ interpolator_map = {
110
113
  InterpolatorType.DISCRETE_FOLD: DiscreteFoldInterpolator,
111
114
  InterpolatorType.PIECEWISE_LINEAR: P1Interpolator,
112
115
  InterpolatorType.PIECEWISE_QUADRATIC: P2Interpolator,
116
+ InterpolatorType.PIECEWISE_QUADRATIC_FOLD: P2FoldInterpolator,
113
117
  InterpolatorType.BASE_DATA_SUPPORTED: GeologicalInterpolator,
114
118
  InterpolatorType.SURFE: SurfeRBFInterpolator,
115
119
  InterpolatorType.PIECEWISE_LINEAR_CONSTANT_NORM: ConstantNormP1Interpolator,
@@ -127,6 +131,9 @@ support_interpolator_map = {
127
131
  3: SupportType.P2UnstructuredTetMesh,
128
132
  2: SupportType.P2Unstructured2d,
129
133
  },
134
+ InterpolatorType.PIECEWISE_QUADRATIC_FOLD: {
135
+ 3: SupportType.P2UnstructuredTetMesh,
136
+ },
130
137
  InterpolatorType.SURFE: {
131
138
  3: SupportType.DataSupported,
132
139
  2: SupportType.DataSupported,
@@ -7,7 +7,6 @@ from typing import Callable
7
7
 
8
8
  import numpy as np
9
9
  from loop_common.logging import get_logger as getLogger
10
- from loop_common.math import rng
11
10
 
12
11
  from ._fold_event import FoldEvent
13
12
  from ._fold_norm_alignment import resolve_fold_norm_target
@@ -54,7 +53,7 @@ class DiscreteFoldInterpolator(PiecewiseLinearInterpolator):
54
53
  self.fold = fold
55
54
 
56
55
  def setup_interpolator(self, **kwargs):
57
- return setup_with_fold_constraints(
56
+ report = setup_with_fold_constraints(
58
57
  fold=self.fold,
59
58
  kwargs=kwargs,
60
59
  interpolator_name=self.__class__.__name__,
@@ -62,6 +61,9 @@ class DiscreteFoldInterpolator(PiecewiseLinearInterpolator):
62
61
  add_fold_constraints=self.add_fold_constraints,
63
62
  finalize_report=self.finalize_setup_diagnostics_report,
64
63
  )
64
+ # includes fold_weights, which the base setup does not see
65
+ self._setup_kwargs = dict(kwargs)
66
+ return report
65
67
 
66
68
  def add_fold_constraints(
67
69
  self,
@@ -71,7 +73,6 @@ class DiscreteFoldInterpolator(PiecewiseLinearInterpolator):
71
73
  fold_normalisation=1.0,
72
74
  fold_norm=-1.0,
73
75
  dgz_alignment="warn",
74
- step=2,
75
76
  mask_fn: Callable | None = None,
76
77
  ):
77
78
  """
@@ -92,8 +93,8 @@ class DiscreteFoldInterpolator(PiecewiseLinearInterpolator):
92
93
  How to handle detected sign mismatch between ``dgz`` and normal
93
94
  constraints (if present). ``warn`` logs only, ``correct`` flips
94
95
  the effective ``fold_norm`` sign, and ``none`` skips checks.
95
- step: int
96
- array step for adding constraints
96
+ mask_fn : callable, optional
97
+ called with the element barycentres; elements for which it returns True get zero weight
97
98
 
98
99
 
99
100
  Returns
@@ -112,8 +113,6 @@ class DiscreteFoldInterpolator(PiecewiseLinearInterpolator):
112
113
  deformed_orientation, fold_axis, dgz = self.fold.get_deformed_orientation(
113
114
  self.support.barycentre
114
115
  )
115
- element_idx = np.arange(self.support.n_elements)
116
- rng.shuffle(element_idx)
117
116
  # calculate element volume for weighting
118
117
  vecs = nodes[:, 1:, :] - nodes[:, 0, None, :]
119
118
  vol = np.abs(np.linalg.det(vecs)) / 6
@@ -124,23 +123,20 @@ class DiscreteFoldInterpolator(PiecewiseLinearInterpolator):
124
123
  """
125
124
  dot product between vector in deformed ori plane = 0
126
125
  """
127
- rng.shuffle(element_idx)
128
-
129
126
  logger.info(f"Adding fold orientation constraint to w = {fold_orientation}")
130
- selected_idx = element_idx[::step]
131
127
  A = np.einsum(
132
128
  "ij,ijk->ik",
133
- deformed_orientation[selected_idx, :],
134
- eg[selected_idx, :, :],
129
+ deformed_orientation,
130
+ eg,
135
131
  )
136
- A *= vol[selected_idx, None]
132
+ A *= vol[:, None]
137
133
  B = np.zeros(A.shape[0])
138
- idc = self.support.get_elements()[selected_idx, :]
134
+ idc = self.support.get_elements()
139
135
  self.add_constraints_to_least_squares(
140
136
  A,
141
137
  B,
142
138
  idc,
143
- w=weight[selected_idx] * fold_orientation,
139
+ w=weight * fold_orientation,
144
140
  name="fold orientation",
145
141
  )
146
142
 
@@ -148,24 +144,21 @@ class DiscreteFoldInterpolator(PiecewiseLinearInterpolator):
148
144
  """
149
145
  dot product between axis and gradient should be 0
150
146
  """
151
- rng.shuffle(element_idx)
152
-
153
147
  logger.info(f"Adding fold axis constraint to w = {fold_axis_w}")
154
- selected_idx = element_idx[::step]
155
148
  A = np.einsum(
156
149
  "ij,ijk->ik",
157
- fold_axis[selected_idx, :],
158
- eg[selected_idx, :, :],
150
+ fold_axis,
151
+ eg,
159
152
  )
160
- A *= vol[selected_idx, None]
153
+ A *= vol[:, None]
161
154
  B = np.zeros(A.shape[0]).tolist()
162
- idc = self.support.get_elements()[selected_idx, :]
155
+ idc = self.support.get_elements()
163
156
 
164
157
  self.add_constraints_to_least_squares(
165
158
  A,
166
159
  B,
167
160
  idc,
168
- w=weight[selected_idx] * fold_axis_w,
161
+ w=weight * fold_axis_w,
169
162
  name="fold axis",
170
163
  )
171
164
 
@@ -173,12 +166,9 @@ class DiscreteFoldInterpolator(PiecewiseLinearInterpolator):
173
166
  """
174
167
  specify scalar norm in X direction
175
168
  """
176
- rng.shuffle(element_idx)
177
-
178
169
  logger.info(f"Adding fold normalisation constraint to w = {fold_normalisation}")
179
- selected_idx = element_idx[::step]
180
- A = np.einsum("ij,ijk->ik", dgz[selected_idx, :], eg[selected_idx, :, :])
181
- A *= vol[selected_idx, None]
170
+ A = np.einsum("ij,ijk->ik", dgz, eg)
171
+ A *= vol[:, None]
182
172
 
183
173
  target_norm = resolve_fold_norm_target(
184
174
  fold=self.fold,
@@ -190,14 +180,14 @@ class DiscreteFoldInterpolator(PiecewiseLinearInterpolator):
190
180
  )
191
181
  B = np.ones(A.shape[0]) * target_norm
192
182
  B *= fold_normalisation
193
- B *= vol[selected_idx]
194
- idc = self.support.get_elements()[selected_idx, :]
183
+ B *= vol
184
+ idc = self.support.get_elements()
195
185
 
196
186
  self.add_constraints_to_least_squares(
197
187
  A,
198
188
  B,
199
189
  idc,
200
- w=weight[selected_idx] * fold_normalisation,
190
+ w=weight * fold_normalisation,
201
191
  name="fold normalisation",
202
192
  )
203
193
 
@@ -26,6 +26,23 @@ from ._regularisation import (
26
26
  logger = getLogger(__name__)
27
27
 
28
28
 
29
+ def _drop_nan_rows(A, B, idc, w, name):
30
+ """Remove constraint rows with a nan in A, B or idc, and log how many were dropped.
31
+
32
+ A, B, idc are 2d, 1d, 2d with one row per constraint. ``w`` is filtered
33
+ too when it is a per-row array.
34
+ """
35
+ bad = np.isnan(A).any(axis=1) | np.isnan(B) | np.isnan(idc).any(axis=1)
36
+ n_bad = int(bad.sum())
37
+ if n_bad == 0:
38
+ return A, B, idc, w
39
+ logger.warning(f"Dropping {n_bad} of {bad.shape[0]} constraint rows containing nan: {name}")
40
+ keep = ~bad
41
+ if isinstance(w, np.ndarray) and w.shape[0] == bad.shape[0]:
42
+ w = w[keep]
43
+ return A[keep], B[keep], idc[keep], w
44
+
45
+
29
46
  class DiscreteInterpolator(GeologicalInterpolator):
30
47
  """ """
31
48
 
@@ -41,6 +58,7 @@ class DiscreteInterpolator(GeologicalInterpolator):
41
58
  """
42
59
  GeologicalInterpolator.__init__(self, data=data, up_to_date=up_to_date)
43
60
  self.B = []
61
+ self._setup_kwargs = {}
44
62
  self.support = support
45
63
  self.dimensions = support.dimension
46
64
  self.c = (
@@ -309,6 +327,9 @@ class DiscreteInterpolator(GeologicalInterpolator):
309
327
 
310
328
  """
311
329
  self.constraints = {}
330
+ # setup_interpolator sets these two values again when it ends.
331
+ self._native_setup = False
332
+ self._setup_constraint_names = None
312
333
  self.c_ = 0
313
334
  self.regularisation_scale = np.ones(self.dof)
314
335
  logger.info("Resetting interpolation constraints")
@@ -346,17 +367,19 @@ class DiscreteInterpolator(GeologicalInterpolator):
346
367
  if len(A.shape) > 2:
347
368
  n_rows = A.shape[0] * A.shape[1]
348
369
  if isinstance(w, np.ndarray):
349
- w = np.tile(w, (A.shape[1]))
370
+ # reshape below puts row (i, j) at i * A.shape[1] + j, so repeat, not tile
371
+ w = np.repeat(w, A.shape[1])
350
372
  A = A.reshape((A.shape[0] * A.shape[1], A.shape[2]))
351
373
  idc = idc.reshape((idc.shape[0] * idc.shape[1], idc.shape[2]))
352
374
  B = B.reshape(A.shape[0])
353
375
  # w = w.reshape((A.shape[0]))
354
376
 
355
- # Check for nan before any row normalisation, which would otherwise
377
+ # Drop nan rows before any row normalisation, which would otherwise
356
378
  # 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}")
379
+ A, B, idc, w = _drop_nan_rows(A, B, idc, w, name)
380
+ if A.shape[0] == 0:
359
381
  return
382
+ n_rows = A.shape[0]
360
383
 
361
384
  # normalise by rows of A
362
385
  # Should this be done? It should make the solution more stable
@@ -1017,12 +1040,18 @@ class DiscreteInterpolator(GeologicalInterpolator):
1017
1040
  A: sparse.spmatrix,
1018
1041
  b: np.ndarray,
1019
1042
  timing: dict,
1043
+ add_ridge_regularisation: bool | None = None,
1044
+ ridge_factor: float | None = None,
1020
1045
  ) -> tuple[sparse.spmatrix, np.ndarray, sparse.spmatrix | None]:
1046
+ if add_ridge_regularisation is None:
1047
+ add_ridge_regularisation = self.add_ridge_regulatisation
1048
+ if ridge_factor is None:
1049
+ ridge_factor = self.ridge_factor
1021
1050
  return _solver_pipeline.preprocess_main_system(
1022
1051
  A=A,
1023
1052
  b=b,
1024
- add_ridge_regularisation=self.add_ridge_regulatisation,
1025
- ridge_factor=self.ridge_factor,
1053
+ add_ridge_regularisation=add_ridge_regularisation,
1054
+ ridge_factor=ridge_factor,
1026
1055
  apply_scaling_matrix=self.apply_scaling_matrix,
1027
1056
  compute_column_scaling_matrix_fn=self.compute_column_scaling_matrix,
1028
1057
  logger=logger,
@@ -1049,8 +1078,11 @@ class DiscreteInterpolator(GeologicalInterpolator):
1049
1078
  tol: float | None,
1050
1079
  solver_kwargs: dict,
1051
1080
  timing: dict,
1081
+ x0: np.ndarray | None = None,
1052
1082
  ) -> bool:
1053
- self.c, ok = _solver_strategy.solve_with_cg(A, b, tol, solver_kwargs, timing, logger)
1083
+ self.c, ok = _solver_strategy.solve_with_cg(
1084
+ A, b, tol, solver_kwargs, timing, logger, x0=x0
1085
+ )
1054
1086
  return ok
1055
1087
 
1056
1088
  def _use_fused_cg_regularisation(self, solver_choice) -> bool:
@@ -1081,6 +1113,9 @@ class DiscreteInterpolator(GeologicalInterpolator):
1081
1113
  tol: float | None,
1082
1114
  solver_kwargs: dict,
1083
1115
  timing: dict,
1116
+ add_ridge_regularisation: bool | None = None,
1117
+ ridge_factor: float | None = None,
1118
+ x0: np.ndarray | None = None,
1084
1119
  ) -> bool:
1085
1120
  """CG fast path for ``regularisation_matrix_free=True``: assemble the
1086
1121
  normal-equations system ``(A_data^T A_data + R_reg^T R_reg) x =
@@ -1119,6 +1154,10 @@ class DiscreteInterpolator(GeologicalInterpolator):
1119
1154
  separate sparse matvecs (``A_data @ x`` then ``A_data.T @ (...)``)
1120
1155
  every iteration.
1121
1156
  """
1157
+ if add_ridge_regularisation is None:
1158
+ add_ridge_regularisation = self.add_ridge_regulatisation
1159
+ if ridge_factor is None:
1160
+ ridge_factor = self.ridge_factor
1122
1161
  assembly_started = perf_counter()
1123
1162
  A_data, b_data = self._assemble_explicit_constraint_matrix()
1124
1163
  A_data = A_data.tocsr()
@@ -1126,8 +1165,8 @@ class DiscreteInterpolator(GeologicalInterpolator):
1126
1165
 
1127
1166
  AtA_data = (A_data.T @ A_data).tocsr()
1128
1167
  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)
1168
+ if add_ridge_regularisation:
1169
+ AtA_data = AtA_data + sparse.eye(dof, format="csr") * (ridge_factor**2)
1131
1170
 
1132
1171
  reg_operator = self._build_fused_cg_regularisation_operator()
1133
1172
  timing["assembly_seconds"] = perf_counter() - assembly_started
@@ -1150,7 +1189,7 @@ class DiscreteInterpolator(GeologicalInterpolator):
1150
1189
  timing["preprocess_seconds"] = perf_counter() - preprocess_started
1151
1190
 
1152
1191
  self.c, ok = _solver_strategy.solve_with_cg_normal_equations(
1153
- normal_operator, rhs, tol, solver_kwargs, timing, logger
1192
+ normal_operator, rhs, tol, solver_kwargs, timing, logger, x0=x0
1154
1193
  )
1155
1194
  return ok
1156
1195
 
@@ -1161,8 +1200,11 @@ class DiscreteInterpolator(GeologicalInterpolator):
1161
1200
  tol: float | None,
1162
1201
  solver_kwargs: dict,
1163
1202
  timing: dict,
1203
+ x0: np.ndarray | None = None,
1164
1204
  ) -> bool:
1165
- self.c, ok = _solver_strategy.solve_with_lsmr(A, b, tol, solver_kwargs, timing, logger)
1205
+ self.c, ok = _solver_strategy.solve_with_lsmr(
1206
+ A, b, tol, solver_kwargs, timing, logger, x0=x0
1207
+ )
1166
1208
  return ok
1167
1209
 
1168
1210
  def _extract_admm_kwargs(self, solver_kwargs: dict, admm_solve) -> tuple[str, dict]:
@@ -1179,10 +1221,13 @@ class DiscreteInterpolator(GeologicalInterpolator):
1179
1221
  constant_norm_iterations: int,
1180
1222
  constant_norm_weight: float,
1181
1223
  constant_norm_target: float | None,
1224
+ x0: np.ndarray | None = None,
1225
+ ridge_kwargs: dict | None = None,
1182
1226
  ) -> bool:
1183
1227
  logger.info("Solving using admm")
1184
1228
 
1185
- constant_norm_solver_kwargs = dict(solver_kwargs)
1229
+ # the polish re-solves must use the same ridge options as this solve
1230
+ constant_norm_solver_kwargs = {**solver_kwargs, **(ridge_kwargs or {})}
1186
1231
  if Q is None:
1187
1232
  logger.warning("No inequality constraints, using lsmr")
1188
1233
  return self.solve_system("lsmr", solver_kwargs=solver_kwargs)
@@ -1197,6 +1242,7 @@ class DiscreteInterpolator(GeologicalInterpolator):
1197
1242
  timing,
1198
1243
  self.support,
1199
1244
  logger,
1245
+ x0=x0,
1200
1246
  )
1201
1247
  if not ok:
1202
1248
  return False
@@ -1234,7 +1280,19 @@ class DiscreteInterpolator(GeologicalInterpolator):
1234
1280
  solver : string/callable
1235
1281
  solver 'cg' conjugate gradient, 'lsmr' or callable function
1236
1282
  solver_kwargs
1237
- kwargs for solver check scipy documentation for more information
1283
+ kwargs for solver check scipy documentation for more information.
1284
+ These keys are used by the interpolator and not sent to the solver:
1285
+
1286
+ - ``ridge_factor`` (float): ridge factor for this solve. 0
1287
+ disables the ridge term. Default ``self.ridge_factor``.
1288
+ - ``add_ridge_regularisation`` (bool): enable or disable the
1289
+ ridge term for this solve. Default
1290
+ ``self.add_ridge_regulatisation``.
1291
+ - ``warm_start`` (bool): start the solver from the previous
1292
+ solution. Default False.
1293
+ - ``x0`` (array or callable): initial guess, or a callable that
1294
+ takes the support and returns one. Has priority over
1295
+ ``warm_start``. A custom callable solver ignores it.
1238
1296
 
1239
1297
  Returns
1240
1298
  -------
@@ -1242,12 +1300,63 @@ class DiscreteInterpolator(GeologicalInterpolator):
1242
1300
  True if the interpolation is run
1243
1301
 
1244
1302
  """
1303
+ solver_choice = self._normalise_solver_choice(solver)
1304
+ # A native setup builds no sparse rows. A matrix solver needs them.
1305
+ # Check this before _pre_solve, so that the old field stays.
1306
+ if getattr(self, "_native_setup", False) and solver_choice != "native":
1307
+ raise ValueError(
1308
+ "The interpolator was set up with solver='native', so it has no "
1309
+ "sparse rows. Run setup again with the new solver, or use "
1310
+ "solver='native'."
1311
+ )
1312
+ # _pre_solve makes a new c array filled with NaN. A native solve that
1313
+ # does not converge must keep the old field, so keep the old array.
1314
+ # This is safe only because _pre_solve does not fill c in place.
1315
+ previous_c = self.c if solver_choice == "native" else None
1316
+ solver_kwargs = dict(solver_kwargs or {})
1317
+ # read the initial guess before _pre_solve clears the previous solution
1318
+ x0 = _solver_pipeline.extract_initial_guess(
1319
+ solver_kwargs, self.c, self.support, self.dof, logger
1320
+ )
1321
+ add_ridge, ridge_factor = _solver_pipeline.extract_ridge_options(
1322
+ solver_kwargs, self.add_ridge_regulatisation, self.ridge_factor, logger
1323
+ )
1324
+ ridge_kwargs = {"add_ridge_regularisation": add_ridge, "ridge_factor": ridge_factor}
1245
1325
  if not self._pre_solve():
1246
1326
  raise ValueError("Pre solve failed")
1247
1327
 
1248
1328
  solve_started = perf_counter()
1249
- solver_choice = self._normalise_solver_choice(solver)
1250
- solver_kwargs = dict(solver_kwargs or {})
1329
+ if solver_choice == "native":
1330
+ self.c = previous_c
1331
+ # Clear the history and the timing keys of an earlier matrix solve.
1332
+ self.solver_history = None
1333
+ self.latest_solve_timing = _solver_pipeline.init_timing("native")
1334
+ # Import here. The core is not loaded when the package is imported.
1335
+ from . import _native
1336
+
1337
+ # The ridge and start value keys are already taken out of
1338
+ # solver_kwargs. The core gets them as arguments.
1339
+ _native.check_supported(self, getattr(self, "_setup_kwargs", {}), solver_kwargs)
1340
+ if len(self.constraints) > 0:
1341
+ # The rows come from a matrix setup. The core ignores them.
1342
+ logger.warning(
1343
+ 'solver="native" saves memory only when it is set before setup'
1344
+ )
1345
+ converged = _native.solve(
1346
+ self,
1347
+ tol,
1348
+ solver_kwargs,
1349
+ x0=x0,
1350
+ ridge_factor=ridge_factor if add_ridge else 0.0,
1351
+ )
1352
+ self.up_to_date = bool(converged)
1353
+ # _native.solve sets the timing with a "total" key. Keep it.
1354
+ timing_native = dict(getattr(self, "latest_solve_timing", None) or {})
1355
+ timing_native.setdefault("solver", "native")
1356
+ timing_native.setdefault("total", perf_counter() - solve_started)
1357
+ timing_native["up_to_date"] = self.up_to_date
1358
+ self.latest_solve_timing = timing_native
1359
+ return self.up_to_date
1251
1360
  constant_norm_iterations, constant_norm_weight, constant_norm_target = (
1252
1361
  _solver_pipeline.extract_constant_norm_options(solver_kwargs, logger)
1253
1362
  )
@@ -1279,18 +1388,23 @@ class DiscreteInterpolator(GeologicalInterpolator):
1279
1388
  # `_solve_with_cg_fused_regularisation` / `FiniteDifferenceInterpolator.
1280
1389
  # _build_fused_cg_regularisation_operator`.
1281
1390
  self.up_to_date = self._solve_with_cg_fused_regularisation(
1282
- tol, solver_kwargs, timing
1391
+ tol, solver_kwargs, timing, x0=x0, **ridge_kwargs
1283
1392
  )
1284
1393
  else:
1285
1394
  A, b = self._assemble_main_system(timing)
1286
- A, b, scaling_matrix = self._preprocess_main_system(A, b, timing)
1395
+ A, b, scaling_matrix = self._preprocess_main_system(A, b, timing, **ridge_kwargs)
1396
+ if x0 is not None and scaling_matrix is not None:
1397
+ # the solver works on y where c = S @ y
1398
+ x0 = x0 / scaling_matrix.diagonal()
1287
1399
 
1288
1400
  if callable(solver_choice):
1289
1401
  self.up_to_date = self._solve_with_callable(solver_choice, A, b, timing)
1290
1402
  elif solver_choice == "cg":
1291
- self.up_to_date = self._solve_with_cg(A, b, tol, solver_kwargs, timing)
1403
+ self.up_to_date = self._solve_with_cg(A, b, tol, solver_kwargs, timing, x0=x0)
1292
1404
  elif solver_choice == "lsmr":
1293
- self.up_to_date = self._solve_with_lsmr(A, b, tol, solver_kwargs, timing)
1405
+ self.up_to_date = self._solve_with_lsmr(
1406
+ A, b, tol, solver_kwargs, timing, x0=x0
1407
+ )
1294
1408
  elif solver_choice == "admm":
1295
1409
  self.up_to_date = self._solve_with_admm(
1296
1410
  A,
@@ -1302,6 +1416,8 @@ class DiscreteInterpolator(GeologicalInterpolator):
1302
1416
  constant_norm_iterations,
1303
1417
  constant_norm_weight,
1304
1418
  constant_norm_target,
1419
+ x0=x0,
1420
+ ridge_kwargs=ridge_kwargs,
1305
1421
  )
1306
1422
  else:
1307
1423
  logger.error(f"Unknown solver {solver_choice}")
@@ -1334,7 +1450,7 @@ class DiscreteInterpolator(GeologicalInterpolator):
1334
1450
  logger.debug("Cannot rerun interpolator")
1335
1451
  return False
1336
1452
  if not self.up_to_date:
1337
- self.setup_interpolator()
1453
+ self.setup_interpolator(**self._setup_kwargs)
1338
1454
  self.up_to_date = self.solve_system(self.solver)
1339
1455
  return self.up_to_date
1340
1456
  return bool(self.up_to_date)
@@ -76,7 +76,7 @@ class FDFoldInterpolator(FiniteDifferenceInterpolator):
76
76
  All other kwargs are forwarded to the parent
77
77
  :meth:`FiniteDifferenceInterpolator.setup_interpolator`.
78
78
  """
79
- return setup_with_fold_constraints(
79
+ report = setup_with_fold_constraints(
80
80
  fold=self.fold,
81
81
  kwargs=kwargs,
82
82
  interpolator_name=self.__class__.__name__,
@@ -84,6 +84,9 @@ class FDFoldInterpolator(FiniteDifferenceInterpolator):
84
84
  add_fold_constraints=self.add_fold_constraints,
85
85
  finalize_report=self.finalize_setup_diagnostics_report,
86
86
  )
87
+ # includes fold_weights, which the base setup does not see
88
+ self._setup_kwargs = dict(kwargs)
89
+ return report
87
90
 
88
91
  # ------------------------------------------------------------------
89
92
  # Fold constraints
@@ -156,6 +156,8 @@ class FiniteDifferenceInterpolator(DiscreteInterpolator):
156
156
  -------
157
157
 
158
158
  """
159
+ # kept so that update() can rebuild the system with the same options
160
+ self._setup_kwargs = dict(kwargs)
159
161
  self.reset()
160
162
  regularisation_config = self.resolve_regularisation_config(
161
163
  regularisation=kwargs.get("regularisation", None),
@@ -177,6 +179,28 @@ class FiniteDifferenceInterpolator(DiscreteInterpolator):
177
179
  self.use_regularisation_weight_scale = kwargs.get("use_regularisation_weight_scale", False)
178
180
  self.regularisation_weight_sigma = kwargs.get("regularisation_weight_sigma", None)
179
181
  self.matrix_free_regularisation_blocks = {}
182
+ self.interface_pair_mode = kwargs.get("interface_pair_mode", self.interface_pair_mode)
183
+ self.interface_pair_threshold = int(
184
+ kwargs.get("interface_pair_threshold", self.interface_pair_threshold)
185
+ )
186
+ self.interface_pair_fallback = kwargs.get(
187
+ "interface_pair_fallback", self.interface_pair_fallback
188
+ )
189
+ if self.solver == "native":
190
+ # The native solver reads the raw data (get_*_constraints) and the
191
+ # stored weights. It does not use sparse rows, so we do not build
192
+ # them. This saves Python memory (plan D7.2).
193
+ # The weights and kwargs are stored above. This branch is safe to
194
+ # run again from update(): reset() already cleared the rows.
195
+ self.matrix_free_regularisation_blocks = {}
196
+ self.regularisation_matrix_free = False
197
+ # add_inequality_pairs_constraints and add_value_inequality_constraints
198
+ # only build sparse inequality rows. They store no raw data. The
199
+ # core reads the raw inequality data itself, so we skip them here.
200
+ self._native_setup = True
201
+ self._setup_constraint_names = frozenset(self.constraints)
202
+ # The report uses the raw data, not the rows, so it is still valid.
203
+ return self.finalize_setup_diagnostics_report()
180
204
  self.regularisation_matrix_free = bool(kwargs.get("regularisation_matrix_free", False))
181
205
  if self.regularisation_matrix_free and self.apply_scaling_matrix:
182
206
  logger.warning(
@@ -199,13 +223,6 @@ class FiniteDifferenceInterpolator(DiscreteInterpolator):
199
223
  "consume a LinearOperator and will fall back to explicit regularisation assembly "
200
224
  "(with a warning) for that solve."
201
225
  )
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
226
  self.add_norm_constraints(self.interpolation_weights["npw"])
210
227
  self.add_gradient_constraints(self.interpolation_weights["gpw"])
211
228
  self.add_value_constraints(self.interpolation_weights["cpw"])
@@ -221,6 +238,8 @@ class FiniteDifferenceInterpolator(DiscreteInterpolator):
221
238
  self.assemble_inner(o[0], o[1], name=k)
222
239
  self.add_directional_regularisation(regularisation_config.directional)
223
240
  self.assemble_borders()
241
+ # The rows up to here come from setup. Any other row is an extra row.
242
+ self._setup_constraint_names = frozenset(self.constraints)
224
243
  return self.finalize_setup_diagnostics_report()
225
244
 
226
245
  def copy(self):
@@ -79,6 +79,8 @@ class InterpolatorBuilder:
79
79
  self,
80
80
  solver: str | None = None,
81
81
  tol: float | None = None,
82
+ ridge_factor: float | None = None,
83
+ warm_start: bool | None = None,
82
84
  **solver_kwargs,
83
85
  ) -> InterpolatorBuilder:
84
86
  """Solve the configured interpolator system.
@@ -89,6 +91,12 @@ class InterpolatorBuilder:
89
91
  Override solver name for this call.
90
92
  tol : Optional[float], optional
91
93
  Optional solver tolerance.
94
+ ridge_factor : Optional[float], optional
95
+ Ridge regularisation factor for this call. 0 disables the ridge
96
+ term. If None, the interpolator default is used.
97
+ warm_start : Optional[bool], optional
98
+ If True, start the solver from the previous solution. Use
99
+ ``x0`` in ``solver_kwargs`` to give an initial guess directly.
92
100
  **solver_kwargs
93
101
  Additional arguments passed to ``solve_system``.
94
102
 
@@ -101,6 +109,10 @@ class InterpolatorBuilder:
101
109
  selected_solver = solver if solver is not None else self.solver
102
110
  merged_solver_kwargs = dict(self.solver_kwargs)
103
111
  merged_solver_kwargs.update(solver_kwargs)
112
+ if ridge_factor is not None:
113
+ merged_solver_kwargs["ridge_factor"] = ridge_factor
114
+ if warm_start is not None:
115
+ merged_solver_kwargs["warm_start"] = warm_start
104
116
  self.interpolator.solve_system(
105
117
  solver=selected_solver,
106
118
  tol=tol,
@@ -14,6 +14,7 @@ class InterpolatorType(Enum):
14
14
  DISCRETE_FOLD = "DISCRETE_FOLD"
15
15
  PIECEWISE_LINEAR = "PIECEWISE_LINEAR"
16
16
  PIECEWISE_QUADRATIC = "PIECEWISE_QUADRATIC"
17
+ PIECEWISE_QUADRATIC_FOLD = "PIECEWISE_QUADRATIC_FOLD"
17
18
  BASE_DATA_SUPPORTED = "BASE_DATA_SUPPORTED"
18
19
  SURFE = "SURFE"
19
20
  PIECEWISE_LINEAR_CONSTANT_NORM = "PIECEWISE_LINEAR_CONSTANT_NORM"