loop-interpolation 0.0.2__tar.gz → 0.1.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 (68) hide show
  1. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/PKG-INFO +1 -1
  2. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/pyproject.toml +1 -1
  3. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/__init__.py +7 -0
  4. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_discrete_fold_interpolator.py +21 -31
  5. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_discrete_interpolator.py +25 -5
  6. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_fd_fold_interpolator.py +4 -1
  7. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_finite_difference_interpolator.py +2 -0
  8. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_interpolatortype.py +1 -0
  9. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_p1interpolator.py +2 -0
  10. loop_interpolation-0.1.0/src/loop_interpolation/_p2_fold_interpolator.py +144 -0
  11. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_p2interpolator.py +23 -22
  12. loop_interpolation-0.1.0/src/loop_interpolation/_quadrature.py +75 -0
  13. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_solver_strategy.py +9 -2
  14. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation.egg-info/PKG-INFO +1 -1
  15. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation.egg-info/SOURCES.txt +5 -0
  16. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_discrete_fold_interpolator.py +41 -44
  17. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_p0_nan_constraints_skipped.py +48 -11
  18. loop_interpolation-0.1.0/tests/test_p2_fold_interpolator.py +259 -0
  19. loop_interpolation-0.1.0/tests/test_p2_fold_registration.py +39 -0
  20. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_p2_interpolator.py +32 -0
  21. loop_interpolation-0.1.0/tests/test_quadrature.py +58 -0
  22. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_solver_strategy.py +32 -0
  23. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/LICENSE +0 -0
  24. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/README.md +0 -0
  25. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/setup.cfg +0 -0
  26. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_builders.py +0 -0
  27. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_constant_norm.py +0 -0
  28. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_diagnostics.py +0 -0
  29. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_fold_event.py +0 -0
  30. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_fold_norm_alignment.py +0 -0
  31. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_fold_setup.py +0 -0
  32. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_geological_interpolator.py +0 -0
  33. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_interpolator_builder.py +0 -0
  34. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_interpolator_factory.py +0 -0
  35. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_operator.py +0 -0
  36. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_regularisation.py +0 -0
  37. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_solver_pipeline.py +0 -0
  38. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_surfe_wrapper.py +0 -0
  39. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_svariogram.py +0 -0
  40. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/_validation.py +0 -0
  41. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/constraints.py +0 -0
  42. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/fold_function/__init__.py +0 -0
  43. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/fold_function/_base_fold_rotation_angle.py +0 -0
  44. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/fold_function/_fourier_series_fold_rotation_angle.py +0 -0
  45. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/fold_function/_lambda_fold_rotation_angle.py +0 -0
  46. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/loopsolver/__init__.py +0 -0
  47. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/loopsolver/admm_constant_norm.py +0 -0
  48. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/loopsolver/admm_method.py +0 -0
  49. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation/loopsolver/admm_solver.py +0 -0
  50. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation.egg-info/dependency_links.txt +0 -0
  51. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation.egg-info/requires.txt +0 -0
  52. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/src/loop_interpolation.egg-info/top_level.txt +0 -0
  53. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_admm_matrix_free.py +0 -0
  54. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_constraint_diagnostics_report.py +0 -0
  55. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_constraints.py +0 -0
  56. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_discrete_interpolator.py +0 -0
  57. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_fd_fold_interpolator.py +0 -0
  58. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_fdi_matrix_free_regularisation.py +0 -0
  59. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_geological_interpolator.py +0 -0
  60. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_import.py +0 -0
  61. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_input_validation.py +0 -0
  62. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_interpolator_builder.py +0 -0
  63. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_normal_magnitude_interpolators.py +0 -0
  64. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_p0_surfe_nans.py +0 -0
  65. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_rectilinear_interpolator.py +0 -0
  66. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_regularisation_api.py +0 -0
  67. {loop_interpolation-0.0.2 → loop_interpolation-0.1.0}/tests/test_solver_pipeline.py +0 -0
  68. {loop_interpolation-0.0.2 → loop_interpolation-0.1.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.1.0
4
4
  Summary: Interpolation utilities for LoopStructural
5
5
  Author-email: Lachlan Grose <lachlan.grose@monash.edu>
6
6
  License: MIT
@@ -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.1.0"
9
9
  requires-python = ">=3.9"
10
10
  authors = [{ name = "Lachlan Grose", email = "lachlan.grose@monash.edu" }]
11
11
  readme = "README.md"
@@ -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 = (
@@ -346,17 +364,19 @@ class DiscreteInterpolator(GeologicalInterpolator):
346
364
  if len(A.shape) > 2:
347
365
  n_rows = A.shape[0] * A.shape[1]
348
366
  if isinstance(w, np.ndarray):
349
- w = np.tile(w, (A.shape[1]))
367
+ # reshape below puts row (i, j) at i * A.shape[1] + j, so repeat, not tile
368
+ w = np.repeat(w, A.shape[1])
350
369
  A = A.reshape((A.shape[0] * A.shape[1], A.shape[2]))
351
370
  idc = idc.reshape((idc.shape[0] * idc.shape[1], idc.shape[2]))
352
371
  B = B.reshape(A.shape[0])
353
372
  # w = w.reshape((A.shape[0]))
354
373
 
355
- # Check for nan before any row normalisation, which would otherwise
374
+ # Drop nan rows before any row normalisation, which would otherwise
356
375
  # 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}")
376
+ A, B, idc, w = _drop_nan_rows(A, B, idc, w, name)
377
+ if A.shape[0] == 0:
359
378
  return
379
+ n_rows = A.shape[0]
360
380
 
361
381
  # normalise by rows of A
362
382
  # Should this be done? It should make the solution more stable
@@ -1334,7 +1354,7 @@ class DiscreteInterpolator(GeologicalInterpolator):
1334
1354
  logger.debug("Cannot rerun interpolator")
1335
1355
  return False
1336
1356
  if not self.up_to_date:
1337
- self.setup_interpolator()
1357
+ self.setup_interpolator(**self._setup_kwargs)
1338
1358
  self.up_to_date = self.solve_system(self.solver)
1339
1359
  return self.up_to_date
1340
1360
  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),
@@ -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"
@@ -193,6 +193,8 @@ class P1Interpolator(DiscreteInterpolator):
193
193
  -------
194
194
 
195
195
  """
196
+ # kept so that update() can rebuild the system with the same options
197
+ self._setup_kwargs = dict(kwargs)
196
198
  # can't reset here, clears fold constraints
197
199
  self.reset()
198
200
  regularisation_config = self.resolve_regularisation_config(
@@ -0,0 +1,144 @@
1
+ """
2
+ Piecewise quadratic interpolator using fold constraints.
3
+
4
+ Summary of findings_1_1.md (what exists / what was added)
5
+ ---------------------------------------------------------
6
+ Existing:
7
+ - ``P2Interpolator`` and the P2 supports. ``evaluate_shape_derivatives``
8
+ gives dN of shape (n, 3, 10), node order [v0..v3, e23, e03, e01, e12, e13, e02].
9
+ - ``setup_with_fold_constraints`` (_fold_setup.py) and
10
+ ``resolve_fold_norm_target`` (_fold_norm_alignment.py), both reused as is.
11
+ - ``add_constraints_to_least_squares`` drops NaN rows, normalises the rows of A,
12
+ then applies the weight ``w``. A per-row ``w`` is therefore applied after
13
+ normalisation.
14
+ - ``get_quadrature_points`` on the support is a triangle (face) rule for edge
15
+ jumps. It does not fit a volume rule.
16
+ Added (Phase 1):
17
+ - ``_quadrature.py``: ``tet_quadrature`` / ``tet_quadrature_points``
18
+ (centroid, gauss4, weights sum to 1, tet index kept).
19
+ - P2 ``evaluate_shape_derivatives`` returns (dN, elements, inside) with NaN
20
+ rows for outside points.
21
+ - This class. ``copy()`` is overridden because the base returns P2Interpolator.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from typing import Callable
26
+
27
+ import numpy as np
28
+ from loop_common.logging import get_logger as getLogger
29
+
30
+ from ._fold_event import FoldEvent
31
+ from ._fold_norm_alignment import resolve_fold_norm_target
32
+ from ._fold_setup import setup_with_fold_constraints
33
+ from ._interpolatortype import InterpolatorType
34
+ from ._p2interpolator import P2Interpolator
35
+ from ._quadrature import tet_quadrature_points
36
+
37
+ logger = getLogger(__name__)
38
+
39
+ _SAMPLE_RULES = ("centroid", "gauss4")
40
+
41
+
42
+ class P2FoldInterpolator(P2Interpolator):
43
+ """P2 interpolator with fold constraints (Laurent et al., 2016).
44
+
45
+ ``nelements`` (when built through ``InterpolatorFactory``) is the number of
46
+ tetrahedra. P2 has a node on every edge, so 1e4 gives about 56k tets and 86k
47
+ unknowns, and 1e5 gives about 526k tets and 765k unknowns (solve about 2.5 min).
48
+ The mesh is larger than the model box because of the buffer.
49
+ """
50
+
51
+ def __init__(self, support, fold: FoldEvent | None = None):
52
+ P2Interpolator.__init__(self, support)
53
+ self.type = InterpolatorType.PIECEWISE_QUADRATIC_FOLD
54
+ self.fold = fold
55
+ logger.info(
56
+ f"P2Fold support: {support.elements.shape[0]} tets, {support.nodes.shape[0]} unknowns. "
57
+ "factory nelements requests grid cells; inspect actual tet and unknown counts"
58
+ )
59
+
60
+ def copy(self):
61
+ return P2FoldInterpolator(self.support, fold=self.fold)
62
+
63
+ def setup_interpolator(self, **kwargs):
64
+ report = setup_with_fold_constraints(
65
+ fold=self.fold,
66
+ kwargs=kwargs,
67
+ interpolator_name=self.__class__.__name__,
68
+ base_setup=super().setup_interpolator,
69
+ add_fold_constraints=self.add_fold_constraints,
70
+ finalize_report=self.finalize_setup_diagnostics_report,
71
+ )
72
+ # set after the call: includes fold_weights, which the base setup does not see
73
+ self._setup_kwargs = dict(kwargs)
74
+ return report
75
+
76
+ def add_fold_constraints(
77
+ self,
78
+ fold_orientation=10.0,
79
+ fold_axis_w=10.0,
80
+ fold_normalisation=1.0,
81
+ fold_norm=-1.0,
82
+ dgz_alignment="warn",
83
+ sample_rule="gauss4",
84
+ mask_fn: Callable | None = None,
85
+ ):
86
+ """Add the three fold constraint families at quadrature points.
87
+
88
+ Parameters
89
+ ----------
90
+ fold_orientation, fold_axis_w, fold_normalisation : float or None
91
+ weights of the families. None skips a family.
92
+ fold_norm : float
93
+ norm target, see ``resolve_fold_norm_target``
94
+ dgz_alignment : {"none", "warn", "correct"}
95
+ sample_rule : {"gauss4", "centroid"}
96
+ quadrature rule used to place sample points in every tetrahedron
97
+ mask_fn : callable, optional
98
+ called with the sample points; points where it returns True get zero weight
99
+ """
100
+ if sample_rule not in _SAMPLE_RULES:
101
+ raise ValueError(f"Unknown sample_rule '{sample_rule}', use one of {_SAMPLE_RULES}")
102
+ support = self.support
103
+ points, tet_idx, q = tet_quadrature_points(support.nodes, support.elements, sample_rule)
104
+ dN, _out_elements, inside = support.evaluate_shape_derivatives(points, elements=tet_idx)
105
+ deformed_orientation, fold_axis, dgz = self.fold.get_deformed_orientation(points)
106
+ # energy per tet must not depend on the rule: weight the residual by w*sqrt(q)
107
+ sq = np.sqrt(q)
108
+ if mask_fn is not None:
109
+ sq = sq * (~np.asarray(mask_fn(points), dtype=bool))
110
+ # keep finite rows only, so A, B, idc and w stay aligned
111
+ valid = np.asarray(inside, dtype=bool) & np.all(np.isfinite(dN), axis=(1, 2))
112
+ idc_all = support.elements[tet_idx]
113
+
114
+ def _add(vectors, target, w, name):
115
+ v = valid & np.all(np.isfinite(vectors), axis=1)
116
+ dropped = int(np.count_nonzero(~v))
117
+ if dropped:
118
+ logger.warning("Dropped %d non-finite rows from %s", dropped, name)
119
+ # no volume factor: row normalisation would cancel it
120
+ A = np.einsum("ij,ijk->ik", vectors[v], dN[v])
121
+ B = np.full(A.shape[0], float(target))
122
+ self.add_constraints_to_least_squares(A, B, idc_all[v], w=float(w) * sq[v], name=name)
123
+
124
+ if fold_orientation is not None:
125
+ logger.info(f"Adding fold orientation constraint to w = {fold_orientation}")
126
+ _add(deformed_orientation, 0.0, fold_orientation, "fold orientation")
127
+ if fold_axis_w is not None:
128
+ logger.info(f"Adding fold axis constraint to w = {fold_axis_w}")
129
+ _add(fold_axis, 0.0, fold_axis_w, "fold axis")
130
+ if fold_normalisation is not None:
131
+ logger.info(f"Adding fold normalisation constraint to w = {fold_normalisation}")
132
+ target_norm = resolve_fold_norm_target(
133
+ fold=self.fold,
134
+ normal_constraints=self.get_norm_constraints(),
135
+ fold_norm=fold_norm,
136
+ dgz_alignment=dgz_alignment,
137
+ logger=logger,
138
+ default_fold_norm=-1.0,
139
+ )
140
+ # Decision: unlike DiscreteFoldInterpolator, B is NOT multiplied by
141
+ # fold_normalisation (nor by volume). That scaling changes the target
142
+ # norm with the weight, which is a quirk. Here the weight only sets
143
+ # the importance and the target stays fold_norm.
144
+ _add(dgz, target_norm, fold_normalisation, "fold normalisation")
@@ -60,6 +60,8 @@ class P2Interpolator(DiscreteInterpolator):
60
60
  -------
61
61
 
62
62
  """
63
+ # kept so that update() can rebuild the system with the same options
64
+ self._setup_kwargs = dict(kwargs)
63
65
  self.reset()
64
66
  regularisation_config = self.resolve_regularisation_config(
65
67
  regularisation=kwargs.get("regularisation", None),
@@ -107,11 +109,11 @@ class P2Interpolator(DiscreteInterpolator):
107
109
  def add_gradient_constraints(self, w: float = 1.0):
108
110
  points = self.get_gradient_constraints()
109
111
  if points.shape[0] > 0:
110
- grad, elements = self.support.evaluate_shape_derivatives(points[:, : self.dimensions])
111
- inside = elements > -1
112
- area = self.support.element_size[elements[inside]]
113
- wt = np.ones(area.shape[0])
114
- wt *= w * area
112
+ grad, elements, inside = self.support.evaluate_shape_derivatives(
113
+ points[:, : self.dimensions]
114
+ )
115
+ # element size cancels in the row normalisation, w is applied after it
116
+ wt = np.full(int(np.sum(inside)), float(w))
115
117
  A = np.einsum(
116
118
  "ikj,ij->ik",
117
119
  grad[inside, :],
@@ -119,7 +121,7 @@ class P2Interpolator(DiscreteInterpolator):
119
121
  )
120
122
  B = np.zeros(A.shape[0])
121
123
  elements = self.support.elements[elements[inside]]
122
- self.add_constraints_to_least_squares(A * wt[:, None], B, elements, name="gradient")
124
+ self.add_constraints_to_least_squares(A, B, elements, w=wt, name="gradient")
123
125
 
124
126
  def add_gradient_orthogonal_constraints(
125
127
  self, points: np.ndarray, vector: np.ndarray, w=1.0, B=0
@@ -139,32 +141,31 @@ class P2Interpolator(DiscreteInterpolator):
139
141
 
140
142
  """
141
143
  if points.shape[0] > 0:
142
- grad, elements = self.support.evaluate_shape_derivatives(points[:, : self.dimensions])
143
- inside = elements > -1
144
- area = self.support.element_size[elements[inside]]
145
- wt = np.ones(area.shape[0])
146
- wt *= w * area
144
+ grad, elements, inside = self.support.evaluate_shape_derivatives(
145
+ points[:, : self.dimensions]
146
+ )
147
+ wt = np.full(int(np.sum(inside)), float(w))
147
148
  A = np.einsum("ijk,ij->ik", grad[inside, :], vector[inside, :])
148
149
  B = np.zeros(A.shape[0])
149
150
  elements = self.support.elements[elements[inside]]
150
151
  self.add_constraints_to_least_squares(
151
- A * wt[:, None], B, elements, name="gradient orthogonal"
152
+ A, B, elements, w=wt, name="gradient orthogonal"
152
153
  )
153
154
 
154
155
  def add_norm_constraints(self, w: float = 1.0):
155
156
  points = self.get_norm_constraints()
156
157
  if points.shape[0] > 0:
157
- grad, elements = self.support.evaluate_shape_derivatives(points[:, : self.dimensions])
158
- inside = elements > -1
159
- area = self.support.element_size[elements[inside]]
160
- wt = np.ones(area.shape[0])
161
- wt *= w * area
158
+ grad, elements, inside = self.support.evaluate_shape_derivatives(
159
+ points[:, : self.dimensions]
160
+ )
161
+ wt = np.full(int(np.sum(inside)), float(w))
162
162
  elements = np.tile(self.support.elements[elements[inside]], (self.dimensions, 1, 1))
163
163
  elements = elements.swapaxes(0, 1)
164
164
  self.add_constraints_to_least_squares(
165
- grad[inside, :, :] * wt[:, None, None],
166
- points[inside, self.dimensions : self.dimensions * 2] * wt[:, None],
165
+ grad[inside, :, :],
166
+ points[inside, self.dimensions : self.dimensions * 2],
167
167
  elements,
168
+ w=wt,
168
169
  name="norm",
169
170
  )
170
171
 
@@ -207,7 +208,7 @@ class P2Interpolator(DiscreteInterpolator):
207
208
  elements = np.arange(0, len(self.support.elements))
208
209
  mask = np.ones(self.support.neighbours.shape[0], dtype=bool)
209
210
  if not maskall:
210
- mask[:] = np.all(self.support.neighbours > 3, axis=1)
211
+ mask[:] = np.all(self.support.neighbours >= 0, axis=1)
211
212
 
212
213
  d2 = self.support.evaluate_shape_d2(elements[mask])
213
214
  # d2 shape is [ele_idx, deriv, node]
@@ -257,10 +258,10 @@ class P2Interpolator(DiscreteInterpolator):
257
258
  if callable(vector_func):
258
259
  norm = vector_func(cp[:, i, :])
259
260
  # evaluate the shape function for the edges for each neighbouring triangle
260
- cp_Dt, cp_tri1 = self.support.evaluate_shape_derivatives(
261
+ cp_Dt, cp_tri1, _inside1 = self.support.evaluate_shape_derivatives(
261
262
  cp[:, i, :], elements=self.support.shared_element_relationships[:, 0]
262
263
  )
263
- cp_Dn, cp_tri2 = self.support.evaluate_shape_derivatives(
264
+ cp_Dn, cp_tri2, _inside2 = self.support.evaluate_shape_derivatives(
264
265
  cp[:, i, :], elements=self.support.shared_element_relationships[:, 1]
265
266
  )
266
267
  # constraint for each cp is triangle - neighbour create a Nx12 matrix
@@ -0,0 +1,75 @@
1
+ """Tetrahedron volume quadrature rules.
2
+
3
+ Barycentric convention: c0 = 1 - r - s - t, c1..c3 = r, s, t.
4
+ Weights are normalised to sum to 1, so a rule gives the mean of a
5
+ function over the tetrahedron. Multiply by the element volume for
6
+ the integral.
7
+ """
8
+
9
+ import numpy as np
10
+
11
+ _GAUSS4_A = 0.1381966011250105
12
+ _GAUSS4_B = 0.5854101966249685
13
+
14
+ _RULES = ("centroid", "gauss4")
15
+
16
+
17
+ def tet_quadrature(rule):
18
+ """Return a tetrahedron quadrature rule.
19
+
20
+ Parameters
21
+ ----------
22
+ rule : str
23
+ 'centroid' (1 point, exact for linear functions) or
24
+ 'gauss4' (4 points, exact for quadratic functions).
25
+
26
+ Returns
27
+ -------
28
+ bary : np.ndarray
29
+ (n, 4) barycentric coordinates of the points.
30
+ weights : np.ndarray
31
+ (n,) weights that sum to 1.
32
+
33
+ Raises
34
+ ------
35
+ ValueError
36
+ If the rule name is not known.
37
+ """
38
+ if rule == "centroid":
39
+ return np.full((1, 4), 0.25), np.ones(1)
40
+ if rule == "gauss4":
41
+ a, b = _GAUSS4_A, _GAUSS4_B
42
+ bary = np.full((4, 4), a)
43
+ bary[np.arange(4), np.arange(4)] = b
44
+ return bary, np.full(4, 0.25)
45
+ raise ValueError(f"Unknown quadrature rule '{rule}', use one of {_RULES}")
46
+
47
+
48
+ def tet_quadrature_points(nodes, elements, rule):
49
+ """Map a quadrature rule onto tetrahedra.
50
+
51
+ Parameters
52
+ ----------
53
+ nodes : np.ndarray
54
+ (n_nodes, 3) node coordinates.
55
+ elements : np.ndarray
56
+ (m, >=4) element node indices. Only the 4 corners are used.
57
+ rule : str
58
+ Rule name, see `tet_quadrature`.
59
+
60
+ Returns
61
+ -------
62
+ points : np.ndarray
63
+ (m * n, 3) points, grouped by element.
64
+ tet_idx : np.ndarray
65
+ (m * n,) index of the element (row of `elements`) for each point.
66
+ weights : np.ndarray
67
+ (m * n,) rule weights repeated for each element (sum to 1 per element).
68
+ """
69
+ bary, w = tet_quadrature(rule)
70
+ corners = np.asarray(nodes)[np.asarray(elements)[:, :4]] # (m, 4, 3)
71
+ points = np.einsum("pk,mkd->mpd", bary, corners).reshape(-1, 3)
72
+ n = len(w)
73
+ tet_idx = np.repeat(np.arange(corners.shape[0]), n)
74
+ weights = np.tile(w, corners.shape[0])
75
+ return points, tet_idx, weights