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,110 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+ from typing import Callable, Union
6
+
7
+ import numpy as np
8
+
9
+ DirectionProvider = Union[np.ndarray, Callable[[np.ndarray], np.ndarray]]
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class DirectionalRegularisation:
14
+ weight: float
15
+ direction: DirectionProvider
16
+ name: str = "directional regularisation"
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class RegularisationConfig:
21
+ isotropic: float | None = None
22
+ directional: tuple[DirectionalRegularisation, ...] = ()
23
+
24
+
25
+ def _is_directional_mapping(value) -> bool:
26
+ if not isinstance(value, dict):
27
+ return False
28
+ return any(key in value for key in ("direction", "vector", "weight", "name"))
29
+
30
+
31
+ def _coerce_directional_term(
32
+ value, index: int = 0, default_name: str = "directional regularisation"
33
+ ) -> DirectionalRegularisation:
34
+ if isinstance(value, DirectionalRegularisation):
35
+ return value
36
+
37
+ if isinstance(value, dict):
38
+ direction = value.get("direction", value.get("vector", None))
39
+ if direction is None:
40
+ raise ValueError("Directional regularisation entries require 'direction' or 'vector'")
41
+ weight = value.get("weight", None)
42
+ if weight is None:
43
+ raise ValueError("Directional regularisation entries require 'weight'")
44
+ name = value.get("name", f"{default_name} {index + 1}")
45
+ return DirectionalRegularisation(
46
+ weight=float(weight),
47
+ direction=direction,
48
+ name=name,
49
+ )
50
+
51
+ raise TypeError("Directional regularisation must be a DirectionalRegularisation or dict entry")
52
+
53
+
54
+ def coerce_directional_regularisation(
55
+ value,
56
+ default_name: str = "directional regularisation",
57
+ ) -> tuple[DirectionalRegularisation, ...]:
58
+ if value is None:
59
+ return ()
60
+
61
+ if isinstance(value, (DirectionalRegularisation, dict)):
62
+ return (_coerce_directional_term(value, default_name=default_name),)
63
+
64
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes, np.ndarray)):
65
+ if len(value) == 0:
66
+ return ()
67
+ if all(np.isscalar(item) for item in value):
68
+ raise TypeError(
69
+ "A sequence of scalars is not a valid directional regularisation config"
70
+ )
71
+ return tuple(
72
+ _coerce_directional_term(item, index=index, default_name=default_name)
73
+ for index, item in enumerate(value)
74
+ )
75
+
76
+ raise TypeError("Unsupported directional regularisation configuration")
77
+
78
+
79
+ def coerce_regularisation_config(
80
+ regularisation=None,
81
+ directional_regularisation=None,
82
+ ) -> RegularisationConfig:
83
+ isotropic = None
84
+ directional = ()
85
+
86
+ if isinstance(regularisation, RegularisationConfig):
87
+ isotropic = regularisation.isotropic
88
+ directional = regularisation.directional
89
+ elif np.isscalar(regularisation) and regularisation is not None:
90
+ isotropic = float(regularisation)
91
+ elif _is_directional_mapping(regularisation):
92
+ directional = coerce_directional_regularisation(regularisation)
93
+ elif isinstance(regularisation, dict):
94
+ isotropic_value = regularisation.get("isotropic", regularisation.get("weight", None))
95
+ if (
96
+ isotropic_value is not None
97
+ and "direction" not in regularisation
98
+ and "vector" not in regularisation
99
+ ):
100
+ isotropic = float(isotropic_value)
101
+ directional = coerce_directional_regularisation(
102
+ regularisation.get("directional", ()),
103
+ )
104
+ elif regularisation is not None:
105
+ raise TypeError("Unsupported regularisation configuration")
106
+
107
+ if directional_regularisation is not None:
108
+ directional = directional + coerce_directional_regularisation(directional_regularisation)
109
+
110
+ return RegularisationConfig(isotropic=isotropic, directional=directional)
@@ -0,0 +1,138 @@
1
+ """Internal pipeline helpers for discrete interpolation solve flow.
2
+
3
+ This module owns solve-stage orchestration primitives that are backend-agnostic:
4
+ - timing payload setup/finalisation
5
+ - extraction of common solver options
6
+ - matrix assembly and preprocessing
7
+ - inequality assembly
8
+ """
9
+
10
+ from time import perf_counter
11
+
12
+ import numpy as np
13
+ from scipy import sparse
14
+ from scipy.sparse.linalg import LinearOperator
15
+
16
+
17
+ def extract_constant_norm_options(solver_kwargs: dict, logger):
18
+ """Pop constant-norm options from solver kwargs.
19
+
20
+ Returns
21
+ -------
22
+ tuple[int, float, Optional[float]]
23
+ iterations, base weight, optional target norm
24
+ """
25
+ constant_norm_iterations = max(0, int(solver_kwargs.pop("constant_norm_iterations", 0)))
26
+ constant_norm_weight = float(solver_kwargs.pop("constant_norm_weight", 0.0))
27
+ constant_norm_target = solver_kwargs.pop("constant_norm_target", None)
28
+ if constant_norm_target is not None:
29
+ constant_norm_target = float(constant_norm_target)
30
+ if constant_norm_target <= 0.0:
31
+ logger.warning(
32
+ "constant_norm_target must be > 0; disabling explicit target and using auto mode"
33
+ )
34
+ constant_norm_target = None
35
+ return constant_norm_iterations, constant_norm_weight, constant_norm_target
36
+
37
+
38
+ def init_timing(solver_choice) -> dict:
39
+ return {
40
+ "solver": "callable" if callable(solver_choice) else solver_choice,
41
+ "backend": "python",
42
+ }
43
+
44
+
45
+ def assemble_main_system(build_matrix_fn, timing: dict):
46
+ assembly_started = perf_counter()
47
+ A, b = build_matrix_fn()
48
+ timing["assembly_seconds"] = perf_counter() - assembly_started
49
+ timing["matrix_rows"] = int(A.shape[0])
50
+ timing["matrix_cols"] = int(A.shape[1])
51
+ # A matrix-free regularisation system (see FiniteDifferenceInterpolator's
52
+ # `regularisation_matrix_free`) returns a scipy LinearOperator here instead
53
+ # of a sparse matrix, which has no `.nnz`. Record None rather than crashing.
54
+ timing["matrix_nnz"] = int(A.nnz) if hasattr(A, "nnz") else None
55
+ return A, b
56
+
57
+
58
+ def _add_ridge_to_linear_operator(A: LinearOperator, b: np.ndarray, ridge_factor: float):
59
+ """Append ridge-regularisation rows (``ridge_factor * I``) to a matrix-free
60
+ system ``LinearOperator`` without materialising it as a sparse block.
61
+
62
+ Equivalent to the explicit ``sparse.vstack([A, sparse.eye(dof) * ridge_factor])``
63
+ used on the concrete-matrix path, but composed via matvec/rmatvec so a
64
+ matrix-free regularisation operator (from
65
+ ``DiscreteInterpolator._combine_explicit_matrix_with_linear_operator``) never
66
+ needs to be converted to a concrete matrix.
67
+ """
68
+ dof = A.shape[1]
69
+ n_rows = A.shape[0]
70
+
71
+ def matvec(x):
72
+ x = np.asarray(x).reshape(-1)
73
+ return np.concatenate([A.matvec(x), ridge_factor * x])
74
+
75
+ def rmatvec(y):
76
+ y = np.asarray(y).reshape(-1)
77
+ return A.rmatvec(y[:n_rows]) + ridge_factor * y[n_rows:]
78
+
79
+ combined = LinearOperator(
80
+ shape=(n_rows + dof, dof), matvec=matvec, rmatvec=rmatvec, dtype=float
81
+ )
82
+ combined_b = np.concatenate([np.asarray(b, dtype=float).reshape(-1), np.zeros(dof)])
83
+ return combined, combined_b
84
+
85
+
86
+ def preprocess_main_system(
87
+ A,
88
+ b,
89
+ add_ridge_regularisation: bool,
90
+ ridge_factor: float,
91
+ apply_scaling_matrix: bool,
92
+ compute_column_scaling_matrix_fn,
93
+ logger,
94
+ timing: dict,
95
+ ):
96
+ preprocess_started = perf_counter()
97
+ scaling_matrix = None
98
+ is_matrix_free = isinstance(A, LinearOperator)
99
+ if add_ridge_regularisation:
100
+ if is_matrix_free:
101
+ A, b = _add_ridge_to_linear_operator(A, b, ridge_factor)
102
+ logger.info("Adding ridge regularisation to matrix-free interpolation operator")
103
+ else:
104
+ ridge = sparse.eye(A.shape[1]) * ridge_factor
105
+ A = sparse.vstack([A, ridge])
106
+ b = np.hstack([b, np.zeros(A.shape[1])])
107
+ logger.info("Adding ridge regularisation to interpolation matrix")
108
+ if apply_scaling_matrix:
109
+ if is_matrix_free:
110
+ # Should already be prevented upstream (FiniteDifferenceInterpolator.
111
+ # setup_interpolator reverts regularisation_matrix_free to False when
112
+ # apply_scaling_matrix=True), but guard here too: column scaling needs
113
+ # explicit per-column norms and cannot be computed for a LinearOperator.
114
+ logger.warning(
115
+ "apply_scaling_matrix=True requested but the assembled system is a "
116
+ "matrix-free LinearOperator; column scaling requires an explicit sparse "
117
+ "matrix and cannot be applied to a LinearOperator. Skipping column "
118
+ "scaling for this solve."
119
+ )
120
+ else:
121
+ scaling_matrix = compute_column_scaling_matrix_fn(A)
122
+ A = A @ scaling_matrix
123
+ timing["preprocess_seconds"] = perf_counter() - preprocess_started
124
+ return A, b, scaling_matrix
125
+
126
+
127
+ def assemble_inequality_system(build_inequality_matrix_fn, timing: dict):
128
+ inequality_started = perf_counter()
129
+ Q, bounds = build_inequality_matrix_fn()
130
+ timing["inequality_seconds"] = perf_counter() - inequality_started
131
+ timing["inequality_rows"] = int(Q.shape[0])
132
+ return Q, bounds
133
+
134
+
135
+ def finalize_timing(timing: dict, solve_started: float, up_to_date: bool) -> dict:
136
+ timing["total_seconds"] = perf_counter() - solve_started
137
+ timing["up_to_date"] = bool(up_to_date)
138
+ return timing
@@ -0,0 +1,218 @@
1
+ """Internal solver strategy helpers for discrete interpolation.
2
+
3
+ This module centralises backend-specific solve behavior (CG, LSMR, ADMM)
4
+ so interpolator classes can focus on orchestration and state management.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import inspect
9
+ from typing import Callable
10
+
11
+ import numpy as np
12
+ from scipy import sparse
13
+
14
+
15
+ def resolve_solver_choice(
16
+ solver: Callable[[sparse.csr_matrix, np.ndarray], np.ndarray] | str | None, logger
17
+ ):
18
+ if callable(solver):
19
+ return solver
20
+ if isinstance(solver, str) or solver is None:
21
+ if solver not in ["cg", "lsmr", "admm", None]:
22
+ logger.warning(
23
+ "Unknown solver %s using cg. Available solvers are cg, lsmr, admm or a custom callable",
24
+ solver,
25
+ )
26
+ return "cg"
27
+ return "cg" if solver is None else solver
28
+ logger.warning("Unsupported solver type %s, using cg", type(solver).__name__)
29
+ return "cg"
30
+
31
+
32
+ def solve_with_callable(
33
+ solver: Callable[[sparse.csr_matrix, np.ndarray], np.ndarray],
34
+ A: sparse.spmatrix,
35
+ b: np.ndarray,
36
+ timing: dict,
37
+ logger,
38
+ ) -> tuple[np.ndarray, bool]:
39
+ from time import perf_counter
40
+
41
+ logger.warning("Using custom solver")
42
+ solve_step_started = perf_counter()
43
+ c = solver(A.tocsr(), b)
44
+ timing["solve_seconds"] = perf_counter() - solve_step_started
45
+ return np.asarray(c), True
46
+
47
+
48
+ def solve_with_cg(
49
+ A: sparse.spmatrix,
50
+ b: np.ndarray,
51
+ tol: float | None,
52
+ solver_kwargs: dict,
53
+ timing: dict,
54
+ logger,
55
+ ) -> tuple[np.ndarray, bool]:
56
+ from time import perf_counter
57
+
58
+ logger.info("Solving using cg")
59
+ if ("atol" not in solver_kwargs or "rtol" not in solver_kwargs) and tol is not None:
60
+ solver_kwargs["atol"] = tol
61
+
62
+ logger.info(f"Solver kwargs: {solver_kwargs}")
63
+ solve_step_started = perf_counter()
64
+ res = sparse.linalg.cg(A.T @ A, A.T @ b, **solver_kwargs)
65
+ timing["solve_seconds"] = perf_counter() - solve_step_started
66
+ if res[1] > 0:
67
+ logger.warning(
68
+ "CG reached iteration limit (%s) and did not converge; using last iteration",
69
+ res[1],
70
+ )
71
+ return np.asarray(res[0]), True
72
+
73
+
74
+ def solve_with_cg_normal_equations(
75
+ N,
76
+ rhs: np.ndarray,
77
+ tol: float | None,
78
+ solver_kwargs: dict,
79
+ timing: dict,
80
+ logger,
81
+ ) -> tuple[np.ndarray, bool]:
82
+ """Solve an already-assembled normal-equations system ``N x = rhs`` with CG.
83
+
84
+ Used by the matrix-free-regularisation ``cg`` fast path
85
+ (``DiscreteInterpolator._solve_with_cg_fused_regularisation``): unlike
86
+ :func:`solve_with_cg`, ``N``/``rhs`` here are already ``A^T A`` / ``A^T b``
87
+ (assembled with a fused, boundary-corrected regularisation contribution),
88
+ so this must NOT square an already-square system again.
89
+ """
90
+ from time import perf_counter
91
+
92
+ logger.info("Solving using cg (matrix-free fused regularisation normal equations)")
93
+ if ("atol" not in solver_kwargs or "rtol" not in solver_kwargs) and tol is not None:
94
+ solver_kwargs["atol"] = tol
95
+
96
+ logger.info(f"Solver kwargs: {solver_kwargs}")
97
+ solve_step_started = perf_counter()
98
+ res = sparse.linalg.cg(N, rhs, **solver_kwargs)
99
+ timing["solve_seconds"] = perf_counter() - solve_step_started
100
+ if res[1] > 0:
101
+ logger.warning(
102
+ "CG reached iteration limit (%s) and did not converge; using last iteration",
103
+ res[1],
104
+ )
105
+ return np.asarray(res[0]), True
106
+
107
+
108
+ def solve_with_lsmr(
109
+ A: sparse.spmatrix,
110
+ b: np.ndarray,
111
+ tol: float | None,
112
+ solver_kwargs: dict,
113
+ timing: dict,
114
+ logger,
115
+ ) -> tuple[np.ndarray, bool]:
116
+ from time import perf_counter
117
+
118
+ logger.info("Solving using lsmr")
119
+ if "btol" not in solver_kwargs and tol is not None:
120
+ solver_kwargs["btol"] = tol
121
+ solver_kwargs["atol"] = 0.0
122
+ logger.info(f"Setting lsmr btol to {tol}")
123
+ logger.info(f"Solver kwargs: {solver_kwargs}")
124
+ solve_step_started = perf_counter()
125
+ res = sparse.linalg.lsmr(A, b, **solver_kwargs)
126
+ timing["solve_seconds"] = perf_counter() - solve_step_started
127
+
128
+ if res[1] in (1, 2, 4, 5, 7):
129
+ return np.asarray(res[0]), True
130
+ if res[1] == 0:
131
+ logger.warning("Solution to least squares problem is all zeros, check input data")
132
+ return np.asarray(res[0]), True
133
+ if res[1] in (3, 6):
134
+ logger.warning("COND(A) seems to be greater than CONLIM, check input data")
135
+ return np.asarray(res[0]), True
136
+ return np.asarray(res[0]), True
137
+
138
+
139
+ def extract_admm_kwargs(solver_kwargs: dict, admm_solve) -> tuple[str, dict]:
140
+ linsys_solver = solver_kwargs.pop("linsys_solver", "lsmr")
141
+ admm_kwargs = {
142
+ "batch_size": solver_kwargs.pop("batch_size", None),
143
+ "batch_fraction": solver_kwargs.pop("batch_fraction", None),
144
+ "random_seed": solver_kwargs.pop("random_seed", None),
145
+ "adaptive_rho": solver_kwargs.pop("adaptive_rho", False),
146
+ "adaptive_rho_mu": solver_kwargs.pop("adaptive_rho_mu", 10.0),
147
+ "adaptive_rho_tau": solver_kwargs.pop("adaptive_rho_tau", 2.0),
148
+ "adaptive_rho_min": solver_kwargs.pop("adaptive_rho_min", 1e-4),
149
+ "adaptive_rho_max": solver_kwargs.pop("adaptive_rho_max", 1e3),
150
+ "admm_weight_final": solver_kwargs.pop("admm_weight_final", None),
151
+ "admm_weight_schedule": solver_kwargs.pop("admm_weight_schedule", "geometric"),
152
+ "admm_abs_tol": solver_kwargs.pop("admm_abs_tol", 1e-4),
153
+ "admm_rel_tol": solver_kwargs.pop("admm_rel_tol", 1e-3),
154
+ "min_iterations": solver_kwargs.pop("min_iterations", 5),
155
+ "reuse_inner_solve": solver_kwargs.pop("reuse_inner_solve", True),
156
+ "active_set": solver_kwargs.pop("active_set", False),
157
+ "active_set_padding": solver_kwargs.pop("active_set_padding", 1e-3),
158
+ "active_set_min_size": solver_kwargs.pop("active_set_min_size", 0),
159
+ "active_set_max_size": solver_kwargs.pop("active_set_max_size", 0),
160
+ "active_set_hysteresis": solver_kwargs.pop("active_set_hysteresis", True),
161
+ "active_set_refresh_interval": solver_kwargs.pop("active_set_refresh_interval", 1),
162
+ "cg_preconditioner": solver_kwargs.pop("cg_preconditioner", True),
163
+ "cg_preconditioner_shift": solver_kwargs.pop("cg_preconditioner_shift", 1e-12),
164
+ "matrix_free": solver_kwargs.pop("matrix_free", False),
165
+ "inner_rtol_start": solver_kwargs.pop("inner_rtol_start", None),
166
+ "inner_rtol_end": solver_kwargs.pop("inner_rtol_end", None),
167
+ "inner_atol_start": solver_kwargs.pop("inner_atol_start", None),
168
+ "inner_atol_end": solver_kwargs.pop("inner_atol_end", None),
169
+ "inner_maxiter_start": solver_kwargs.pop("inner_maxiter_start", None),
170
+ "inner_maxiter_end": solver_kwargs.pop("inner_maxiter_end", None),
171
+ "inner_maxiter_schedule": solver_kwargs.pop("inner_maxiter_schedule", "linear"),
172
+ "model_update_tol": solver_kwargs.pop("model_update_tol", 0.0),
173
+ "return_history": solver_kwargs.pop("return_history", False),
174
+ }
175
+ supported_optional = set(inspect.signature(admm_solve).parameters.keys())
176
+ admm_kwargs = {k: v for k, v in admm_kwargs.items() if k in supported_optional}
177
+ return linsys_solver, admm_kwargs
178
+
179
+
180
+ def solve_with_admm(
181
+ A: sparse.spmatrix,
182
+ b: np.ndarray,
183
+ Q: sparse.spmatrix,
184
+ bounds: np.ndarray,
185
+ solver_kwargs: dict,
186
+ timing: dict,
187
+ support,
188
+ logger,
189
+ ) -> tuple[np.ndarray, list | None, bool]:
190
+ from time import perf_counter
191
+
192
+ from .loopsolver import admm_solve
193
+
194
+ if "x0" in solver_kwargs:
195
+ x0 = solver_kwargs["x0"](support)
196
+ else:
197
+ x0 = np.zeros(A.shape[1])
198
+ solver_kwargs.pop("x0", None)
199
+
200
+ linsys_solver, admm_kwargs = extract_admm_kwargs(solver_kwargs, admm_solve)
201
+ solve_step_started = perf_counter()
202
+ res = admm_solve(
203
+ A,
204
+ b,
205
+ Q,
206
+ bounds,
207
+ x0=x0,
208
+ admm_weight=solver_kwargs.pop("admm_weight", 0.01),
209
+ nmajor=solver_kwargs.pop("nmajor", 200),
210
+ linsys_solver_kwargs=solver_kwargs,
211
+ linsys_solver=linsys_solver,
212
+ **admm_kwargs,
213
+ )
214
+ timing["solve_seconds"] = perf_counter() - solve_step_started
215
+
216
+ if isinstance(res, tuple):
217
+ return np.asarray(res[0]), res[1], True
218
+ return np.asarray(res), None, True
@@ -0,0 +1,211 @@
1
+ """
2
+ Wrapper for using surfepy
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import numpy as np
7
+ import surfepy
8
+ from loop_common.logging import get_logger as getLogger
9
+ from loop_common.math import get_vectors
10
+
11
+ from ._geological_interpolator import GeologicalInterpolator
12
+
13
+ logger = getLogger(__name__)
14
+
15
+
16
+ class SurfeRBFInterpolator(GeologicalInterpolator):
17
+ """ """
18
+
19
+ def __init__(self, method="single_surface"):
20
+ GeologicalInterpolator.__init__(self)
21
+ self.surfe = None
22
+ if not method:
23
+ method = "single_surface"
24
+ if method == "single_surface":
25
+ logger.info("Using single surface interpolator")
26
+ self.surfe = surfepy.Surfe_API(1)
27
+ if method == "Lajaunie" or method == "increments":
28
+ logger.info("Using Lajaunie method")
29
+ self.surfe = surfepy.Surfe_API(2)
30
+ if method == "horizons":
31
+ logger.info("Using surfe horizon")
32
+ self.surfe = surfepy.Surfe_API(4)
33
+
34
+ def set_region(self, **kwargs):
35
+ pass
36
+
37
+ def set_nelements(self, nelements) -> int:
38
+ return 0
39
+
40
+ def add_gradient_constraints(self, w=1):
41
+ points = self.get_gradient_constraints()
42
+ if points.shape[0] > 0:
43
+ logger.info("Adding ")
44
+ strike_vector, dip_vector = get_vectors(points[:, 3:6])
45
+
46
+ strike_vector = np.hstack([points[:, :3], strike_vector.T])
47
+ dip_vector = np.hstack([points[:, :3], dip_vector.T])
48
+ self.surfe.SetTangentConstraints(strike_vector)
49
+ self.surfe.SetTangentConstraints(dip_vector)
50
+
51
+ def add_norm_constraints(self, w=1):
52
+ points = self.get_norm_constraints()
53
+ if points.shape[0] > 0:
54
+ self.surfe.SetPlanarConstraints(points[:, :6])
55
+
56
+ def add_value_constraints(self, w=1):
57
+
58
+ points = self.get_value_constraints()
59
+ if points.shape[0] > 0:
60
+ # self.surfe.SetInterfaceConstraints(points[:,:4])
61
+ for i in range(points.shape[0]):
62
+ self.surfe.AddInterfaceConstraint(
63
+ points[i, 0],
64
+ points[i, 1],
65
+ points[i, 2],
66
+ points[i, 3],
67
+ )
68
+
69
+ def add_interface_constraints(self, w=1):
70
+ pass
71
+
72
+ def add_value_inequality_constraints(self, w=1):
73
+ ## inequalities are causing a segfault
74
+ # points = self.get_value_inequality_constraints()
75
+ # if points.shape[0] > 0:
76
+ # #
77
+ # self.surfe.AddValueInequalityConstraints(points[:,0],points[:,1],points[:,2],points[:,3])
78
+ pass
79
+
80
+ def add_inequality_pairs_constraints(
81
+ self,
82
+ w: float = 1.0,
83
+ upper_bound=None,
84
+ lower_bound=-np.inf,
85
+ pairs: list | None = None,
86
+ ):
87
+ # self.surfe.Add
88
+ pass
89
+
90
+ def reset(self):
91
+ pass
92
+
93
+ def add_tangent_constraints(self, w=1):
94
+ points = self.get_tangent_constraints()
95
+ if points.shape[0] > 0:
96
+ self.surfe.SetTangentConstraints(points[:, :6])
97
+
98
+ def solve_system(self, **kwargs):
99
+ self.surfe.ComputeInterpolant()
100
+
101
+ def setup_interpolator(self, **kwargs):
102
+ """
103
+ Setup the interpolator
104
+
105
+ Parameters
106
+ ----------
107
+ kernel: str
108
+ kernel for interpolation r3, r, Gaussian, Multiquadrics, Inverse Multiquadrics
109
+ Thin Plate Spline, WendlandC2, MaternC4
110
+ regression: float
111
+ smoothing parameter default 0
112
+ greedy: tuple
113
+ greedy parameters first is interface threshold, second is angular threshold
114
+ default (0,0)
115
+ poly_order: int
116
+ order of the polynomial used for interpolation, default 1
117
+ radius: float
118
+ radius of the kernel, default None but required for SPD kernels
119
+ anisotropy: bool
120
+ apply global anisotropy from eigenvectors of orientation constraints, default False
121
+
122
+
123
+ """
124
+ self.add_gradient_constraints()
125
+ self.add_norm_constraints()
126
+ self.add_value_constraints()
127
+ self.add_tangent_constraints()
128
+
129
+ kernel = kwargs.get("kernel", "r3")
130
+ logger.info(f"Setting surfe RBF kernel to {kernel}")
131
+ self.surfe.SetRBFKernel(kernel)
132
+ regression = kwargs.get("regression_smoothing", 0.0)
133
+ if regression > 0:
134
+ logger.info(f"Using regression smoothing {regression:f}")
135
+ self.surfe.SetRegressionSmoothing(True, regression)
136
+ greedy = kwargs.get("greedy", (0, 0))
137
+
138
+ if greedy[0] > 0 or greedy[1] > 0:
139
+ logger.info(
140
+ f"Using greedy algorithm: inferface {greedy[0]:f} and angular {greedy[1]:f}"
141
+ )
142
+ self.surfe.SetGreedyAlgorithm(True, greedy[0], greedy[1])
143
+ poly_order = kwargs.get("poly_order", None)
144
+ if poly_order:
145
+ logger.info("Setting poly order to %i", poly_order)
146
+ self.surfe.SetPolynomialOrder(poly_order)
147
+ global_anisotropy = kwargs.get("anisotropy", False)
148
+ if global_anisotropy:
149
+ logger.info("Using global anisotropy")
150
+ self.surfe.SetGlobalAnisotropy(global_anisotropy)
151
+ radius = kwargs.get("radius", False)
152
+ if radius:
153
+ logger.info(f"Setting RBF radius to {radius:f}")
154
+ self.surfe.SetRBFShapeParameter(radius)
155
+
156
+ return self.get_constraint_diagnostics_report(refresh=True)
157
+
158
+ def update(self):
159
+ return self.surfe.InterpolantComputed()
160
+
161
+ def _evaluate_value_local(self, evaluation_points):
162
+ """Evaluate surfe interpolant at points
163
+
164
+ Parameters
165
+ ----------
166
+ evaluation_points : array of locations N,3
167
+ xyz of locations to evaluate
168
+
169
+ Returns
170
+ -------
171
+ np.array (N)
172
+ value of interpolant at points
173
+ """
174
+ evaluation_points = np.array(evaluation_points)
175
+ evaluated = np.zeros(evaluation_points.shape[0])
176
+ mask = np.isnan(evaluation_points).any(axis=1)
177
+
178
+ if evaluation_points[~mask, :].shape[0] > 0:
179
+ evaluated[~mask] = self.surfe.EvaluateInterpolantAtPoints(evaluation_points[~mask])
180
+ return evaluated
181
+
182
+ def _evaluate_gradient_local(self, evaluation_points):
183
+ """Evaluate surfe interpolant gradient at points
184
+
185
+ Parameters
186
+ ----------
187
+ evaluation_points : array of locations N,3
188
+ xyz of locations to evaluate
189
+
190
+ Returns
191
+ -------
192
+ np.array (N,3)
193
+ gradient of interpolant at points
194
+
195
+ """
196
+ evaluation_points = np.array(evaluation_points)
197
+ evaluated = np.full((evaluation_points.shape[0], 3), np.nan)
198
+ mask = np.isnan(evaluation_points).any(axis=1)
199
+ if evaluation_points[~mask, :].shape[0] > 0:
200
+ evaluated[~mask, :] = self.surfe.EvaluateVectorInterpolantAtPoints(
201
+ evaluation_points[~mask]
202
+ )
203
+ return evaluated
204
+
205
+ @property
206
+ def dof(self):
207
+ return self.get_data_locations().shape[0]
208
+
209
+ @property
210
+ def n_elements(self) -> int:
211
+ return self.get_data_locations().shape[0]