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,185 @@
1
+ """FoldEvent — deformed-orientation geometry for fold-constrained interpolation.
2
+
3
+ Ported from LoopStructural/modelling/features/fold/_fold.py (Laurent et al., 2016).
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from typing import Callable
8
+
9
+ import numpy as np
10
+ from loop_common.logging import get_logger
11
+
12
+ logger = get_logger(__name__)
13
+
14
+
15
+ class FoldEvent:
16
+ """Describes fold geometry via a fold frame and two rotation-angle functions.
17
+
18
+ The fold frame provides two coordinate fields:
19
+ - ``foldframe.features[0]``: axial-surface scalar field (gx). Its gradient
20
+ (``evaluate_gradient``) gives the across-fold direction and its value
21
+ (``evaluate_value``) parameterises the fold limb rotation angle.
22
+ - ``foldframe.features[1]``: along-fold scalar field (gy). Its value is
23
+ used to parameterise the fold axis rotation angle (only when
24
+ ``fold_axis_rotation`` is supplied instead of a constant ``fold_axis``).
25
+
26
+ Parameters
27
+ ----------
28
+ foldframe
29
+ Object exposing a ``features`` sequence of at least one (two when
30
+ ``fold_axis_rotation`` is set) feature objects with
31
+ ``evaluate_value(points)`` and ``evaluate_gradient(points)`` methods.
32
+ fold_axis_rotation : callable, optional
33
+ Function ``f(gy_values) -> angles_deg`` that gives the rotation of the
34
+ fold axis from the gy gradient direction. Supply either this or
35
+ ``fold_axis``, not both.
36
+ fold_limb_rotation : callable
37
+ Function ``f(gx_values) -> angles_deg`` that gives the fold limb
38
+ rotation angle from the gx gradient direction (axial-plane rotation).
39
+ fold_axis : array-like of shape (3,), optional
40
+ Constant fold axis direction. Used when the axis is known a-priori and
41
+ ``fold_axis_rotation`` is None.
42
+ invert_norm : bool
43
+ When True, invert dgz for points where the fold direction and axis are
44
+ nearly parallel (dot product < 0). Rarely needed.
45
+ name : str
46
+ Label for logging.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ foldframe,
52
+ fold_axis_rotation: Callable | None = None,
53
+ fold_limb_rotation: Callable | None = None,
54
+ fold_axis: np.ndarray | None = None,
55
+ invert_norm: bool = False,
56
+ name: str = "Fold",
57
+ ):
58
+ self.foldframe = foldframe
59
+ self.fold_axis_rotation = fold_axis_rotation
60
+ self.fold_limb_rotation = fold_limb_rotation
61
+ self.fold_axis = np.asarray(fold_axis, dtype=float) if fold_axis is not None else None
62
+ self.invert_norm = invert_norm
63
+ self.name = name
64
+
65
+ # ------------------------------------------------------------------
66
+ # Public API
67
+ # ------------------------------------------------------------------
68
+
69
+ def get_fold_axis_orientation(self, points: np.ndarray) -> np.ndarray:
70
+ """Return unit fold-axis vectors at *points* (N×3)."""
71
+ if self.fold_axis_rotation is not None:
72
+ logger.debug("FoldEvent: evaluating fold axis via rotation function")
73
+ dgx = self.foldframe.features[0].evaluate_gradient(points)
74
+ dgy = self.foldframe.features[1].evaluate_gradient(points)
75
+ valid_x = np.all(~np.isnan(dgx), axis=1)
76
+ valid_y = np.all(~np.isnan(dgy), axis=1)
77
+ nrm = np.linalg.norm(dgx[valid_x], axis=1)
78
+ dgx[valid_x] /= np.where(nrm > 1e-12, nrm, 1.0)[:, None]
79
+ nrm = np.linalg.norm(dgy[valid_y], axis=1)
80
+ dgy[valid_y] /= np.where(nrm > 1e-12, nrm, 1.0)[:, None]
81
+ gy = self.foldframe.features[1].evaluate_value(points)
82
+ R1 = self._rot_mat(-dgx, self.fold_axis_rotation(gy))
83
+ fold_axis = np.einsum("ijk,ki->kj", R1, dgy)
84
+ nrm = np.linalg.norm(fold_axis, axis=1, keepdims=True)
85
+ nrm = np.where(nrm > 1e-12, nrm, 1.0)
86
+ return fold_axis / nrm
87
+
88
+ if self.fold_axis is not None:
89
+ logger.debug("FoldEvent: using constant fold axis")
90
+ return np.tile(self.fold_axis, (points.shape[0], 1))
91
+
92
+ raise ValueError(
93
+ f"FoldEvent '{self.name}': either fold_axis or fold_axis_rotation must be set"
94
+ )
95
+
96
+ def get_deformed_orientation(
97
+ self, points: np.ndarray
98
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
99
+ """Return the three fold-geometry direction vectors at *points*.
100
+
101
+ Returns
102
+ -------
103
+ fold_direction : np.ndarray (N, 3)
104
+ Vector in the deformed foliation plane, orthogonal to the fold axis.
105
+ fold_axis : np.ndarray (N, 3)
106
+ Fold hinge direction.
107
+ dgz : np.ndarray (N, 3)
108
+ Across-fold direction (perpendicular to both fold_direction and fold_axis).
109
+ """
110
+ if self.fold_limb_rotation is None:
111
+ raise ValueError(
112
+ f"FoldEvent '{self.name}': fold_limb_rotation must be set before calling "
113
+ "get_deformed_orientation()"
114
+ )
115
+
116
+ fold_axis = self.get_fold_axis_orientation(points)
117
+
118
+ gx = self.foldframe.features[0].evaluate_value(points)
119
+ dgx = self.foldframe.features[0].evaluate_gradient(points)
120
+ mask = np.all(~np.isnan(dgx), axis=1)
121
+ nrm = np.linalg.norm(dgx[mask], axis=1)
122
+ dgx[mask] /= np.where(nrm > 1e-12, nrm, 1.0)[:, None]
123
+
124
+ dgz = np.full_like(dgx, np.nan)
125
+ dgz[mask] = np.cross(dgx[mask], fold_axis[mask], axisa=1, axisb=1)
126
+ nrm = np.linalg.norm(dgz[mask], axis=1)
127
+ nrm = np.where(nrm > 1e-12, nrm, 1.0)
128
+ dgz[mask] /= nrm[:, None]
129
+
130
+ R2 = self._rot_mat(fold_axis, self.fold_limb_rotation(gx))
131
+ fold_direction = np.einsum("ijk,ki->kj", R2, dgx)
132
+ fd_nrm = np.linalg.norm(fold_direction, axis=1, keepdims=True)
133
+ fd_nrm = np.where(fd_nrm > 1e-12, fd_nrm, 1.0)
134
+ fold_direction = fold_direction / fd_nrm
135
+
136
+ if self.invert_norm:
137
+ d = np.einsum("ij,ij->i", fold_direction, fold_axis)
138
+ dgz[mask & (d < 0)] *= -1.0
139
+
140
+ return fold_direction, fold_axis, dgz
141
+
142
+ def vtk(self):
143
+ import pyvista as pv
144
+ points = self.foldframe.vtk().points
145
+
146
+ fold_direction, fold_axis, dgz = self.get_deformed_orientation(points)
147
+ points = pv.PolyData(points)
148
+
149
+ points['fold_direction'] = fold_direction
150
+ points['fold_axis'] = fold_axis
151
+ points['dgz'] = dgz
152
+ points['folded_normal'] = np.cross(fold_direction, fold_axis, axisa=1, axisb=1)
153
+ return points
154
+ # ------------------------------------------------------------------
155
+ # Helpers
156
+ # ------------------------------------------------------------------
157
+
158
+ @staticmethod
159
+ def _rot_mat(axis: np.ndarray, angle: np.ndarray) -> np.ndarray:
160
+ """Rodrigues rotation matrices — returns (3, 3, N) array.
161
+
162
+ Parameters
163
+ ----------
164
+ axis : (N, 3) unit vectors
165
+ angle : (N,) angles in degrees
166
+ """
167
+ c = np.cos(np.deg2rad(angle))
168
+ s = np.sin(np.deg2rad(angle))
169
+ C = 1.0 - c
170
+ x, y, z = axis[:, 0], axis[:, 1], axis[:, 2]
171
+ xs, ys, zs = x * s, y * s, z * s
172
+ xC, yC, zC = x * C, y * C, z * C
173
+ xyC, yzC, zxC = x * yC, y * zC, z * xC
174
+
175
+ R = np.zeros((3, 3, len(angle)))
176
+ R[0, 0] = x * xC + c
177
+ R[0, 1] = xyC - zs
178
+ R[0, 2] = zxC + ys
179
+ R[1, 0] = xyC + zs
180
+ R[1, 1] = y * yC + c
181
+ R[1, 2] = yzC - xs
182
+ R[2, 0] = zxC - ys
183
+ R[2, 1] = yzC + xs
184
+ R[2, 2] = z * zC + c
185
+ return R
@@ -0,0 +1,118 @@
1
+ """Helpers for fold-normal sign alignment against normal constraints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ _VALID_ALIGNMENT_MODES = {"none", "warn", "correct"}
8
+
9
+
10
+ def resolve_fold_norm_target(
11
+ *,
12
+ fold,
13
+ normal_constraints: np.ndarray,
14
+ fold_norm: float | None,
15
+ dgz_alignment: str | None,
16
+ logger,
17
+ default_fold_norm: float = -1.0,
18
+ ) -> float:
19
+ """Resolve fold_norm target with optional dgz/normal sign checks.
20
+
21
+ Parameters
22
+ ----------
23
+ fold
24
+ Fold event used to evaluate dgz at normal-constraint locations.
25
+ normal_constraints : np.ndarray
26
+ Normal constraints in ``xyz|nx ny nz|w`` format.
27
+ fold_norm : float or None
28
+ Requested fold_norm target. If None, ``default_fold_norm`` is used.
29
+ dgz_alignment : {"none", "warn", "correct"} or None
30
+ Handling mode when dgz appears opposite to normal constraints:
31
+ - ``none``: skip checks.
32
+ - ``warn``: log warning only.
33
+ - ``correct``: log warning and flip target sign.
34
+ ``None`` defaults to ``warn``.
35
+ logger
36
+ Logger used for warnings.
37
+ default_fold_norm : float
38
+ Default fold_norm target when ``fold_norm`` is None.
39
+
40
+ Returns
41
+ -------
42
+ float
43
+ Fold normalisation target value to use in ``∇f · dgz = target``.
44
+ """
45
+ target_norm = float(default_fold_norm if fold_norm is None else fold_norm)
46
+
47
+ mode = "warn" if dgz_alignment is None else str(dgz_alignment).strip().lower()
48
+ if mode not in _VALID_ALIGNMENT_MODES:
49
+ valid = ", ".join(sorted(_VALID_ALIGNMENT_MODES))
50
+ raise ValueError(f"dgz_alignment must be one of {{{valid}}}, got {dgz_alignment!r}")
51
+ if mode == "none":
52
+ return target_norm
53
+
54
+ normals = np.asarray(normal_constraints, dtype=float)
55
+ if normals.ndim != 2 or normals.shape[0] == 0 or normals.shape[1] < 6:
56
+ return target_norm
57
+
58
+ points = normals[:, :3]
59
+ normal_vectors = normals[:, 3:6]
60
+
61
+ try:
62
+ _, _, dgz = fold.get_deformed_orientation(points)
63
+ except (AttributeError, TypeError, ValueError, RuntimeError) as exc: # pragma: no cover - defensive fallback
64
+ logger.warning("Could not evaluate dgz for alignment check (%s).", exc)
65
+ return target_norm
66
+
67
+ dgz = np.asarray(dgz, dtype=float)
68
+ if dgz.ndim != 2 or dgz.shape[1] != normal_vectors.shape[1]:
69
+ logger.warning(
70
+ "Skipping dgz alignment check due to unexpected dgz shape %s.",
71
+ getattr(dgz, "shape", None),
72
+ )
73
+ return target_norm
74
+
75
+ if dgz.shape[0] != normal_vectors.shape[0]:
76
+ n_common = min(dgz.shape[0], normal_vectors.shape[0])
77
+ logger.warning(
78
+ "dgz alignment check received mismatched rows (dgz=%d, normals=%d); using first %d.",
79
+ dgz.shape[0],
80
+ normal_vectors.shape[0],
81
+ n_common,
82
+ )
83
+ if n_common == 0:
84
+ return target_norm
85
+ dgz = dgz[:n_common]
86
+ normal_vectors = normal_vectors[:n_common]
87
+
88
+ normal_norm = np.linalg.norm(normal_vectors, axis=1)
89
+ dgz_norm = np.linalg.norm(dgz, axis=1)
90
+
91
+ valid = (
92
+ np.all(np.isfinite(normal_vectors), axis=1)
93
+ & np.all(np.isfinite(dgz), axis=1)
94
+ & (normal_norm > 1e-12)
95
+ & (dgz_norm > 1e-12)
96
+ )
97
+ if not np.any(valid):
98
+ return target_norm
99
+
100
+ normal_unit = normal_vectors[valid] / normal_norm[valid, None]
101
+ dgz_unit = dgz[valid] / dgz_norm[valid, None]
102
+ median_dot = float(np.median(np.einsum("ij,ij->i", dgz_unit, normal_unit)))
103
+
104
+ # A strongly negative median indicates a systematic sign mismatch.
105
+ if median_dot < -0.2:
106
+ logger.warning(
107
+ "Detected dgz opposite to normal constraints (median dot %.3f). "
108
+ "fold_norm may need sign inversion.",
109
+ median_dot,
110
+ )
111
+ if mode == "correct":
112
+ target_norm *= -1.0
113
+ logger.warning(
114
+ "Auto-correcting fold_norm sign to %.3f using dgz_alignment='correct'.",
115
+ target_norm,
116
+ )
117
+
118
+ return target_norm
@@ -0,0 +1,39 @@
1
+ """Shared setup helpers for fold-aware interpolators."""
2
+
3
+
4
+ def setup_with_fold_constraints(
5
+ *,
6
+ fold,
7
+ kwargs: dict,
8
+ interpolator_name: str,
9
+ base_setup,
10
+ add_fold_constraints,
11
+ finalize_report,
12
+ ):
13
+ """Run common fold interpolator setup sequence.
14
+
15
+ Parameters
16
+ ----------
17
+ fold
18
+ Fold event instance or None.
19
+ kwargs : dict
20
+ Setup kwargs passed to setup_interpolator.
21
+ interpolator_name : str
22
+ Name used in error messages.
23
+ base_setup : callable
24
+ Parent setup_interpolator callable.
25
+ add_fold_constraints : callable
26
+ Method that applies fold-specific constraints.
27
+ finalize_report : callable
28
+ Callable that returns final diagnostics report.
29
+ """
30
+ if fold is None:
31
+ raise RuntimeError(
32
+ f"{interpolator_name}: no fold event set. Assign self.fold before calling setup_interpolator."
33
+ )
34
+
35
+ setup_kwargs = dict(kwargs)
36
+ fold_weights = setup_kwargs.pop("fold_weights", {})
37
+ base_setup(**setup_kwargs)
38
+ add_fold_constraints(**fold_weights)
39
+ return finalize_report()