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,920 @@
1
+ """Base geological interpolator for LoopStructural.
2
+
3
+ This module contains the abstract base class for all geological interpolators
4
+ used in LoopStructural geological modelling framework.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from abc import ABCMeta, abstractmethod
10
+
11
+ import numpy as np
12
+ from loop_common.interfaces.representation import BaseRepresentation
13
+ from loop_common.logging import get_logger as getLogger
14
+
15
+ from ._diagnostics import (
16
+ ConstraintDiagnosticsReport,
17
+ ConstraintFamilyDiagnostics,
18
+ RegionCoverageDiagnostics,
19
+ )
20
+ from ._interpolatortype import InterpolatorType
21
+ from ._validation import (
22
+ ValidationError,
23
+ check_unsupported_combinations,
24
+ )
25
+ from .constraints import (
26
+ GradientConstraint,
27
+ InequalityConstraint,
28
+ InequalityPair,
29
+ InterfaceConstraint,
30
+ ValueConstraint,
31
+ )
32
+
33
+ logger = getLogger(__name__)
34
+
35
+
36
+ class LoopTypeError(TypeError):
37
+ pass
38
+
39
+
40
+ class GeologicalInterpolator(BaseRepresentation, metaclass=ABCMeta):
41
+ """Abstract base class for geological interpolators.
42
+
43
+ This class defines the interface for all geological interpolators in
44
+ LoopStructural, providing methods for setting constraints and evaluating
45
+ the interpolated scalar field.
46
+
47
+ Attributes
48
+ ----------
49
+ data : dict
50
+ Dictionary containing numpy arrays for gradient, value, normal, and tangent data
51
+ n_g : int
52
+ Number of gradient constraints
53
+ n_i : int
54
+ Number of interface/value constraints
55
+ n_n : int
56
+ Number of normal constraints
57
+ n_t : int
58
+ Number of tangent constraints
59
+ type : InterpolatorType
60
+ The type of interpolator
61
+ up_to_date : bool
62
+ Whether the interpolator needs to be rebuilt
63
+ constraints : list
64
+ List of applied constraints
65
+ valid : bool
66
+ Whether the interpolator is in a valid state
67
+ dimensions : int
68
+ Number of spatial dimensions (default 3)
69
+ support : object
70
+ The support structure used by the interpolator
71
+ """
72
+
73
+ @abstractmethod
74
+ def __init__(self, data=None, up_to_date=False):
75
+ """Initialize the geological interpolator.
76
+
77
+ This method sets up the basic data structures and parameters required
78
+ for geological interpolation.
79
+
80
+ Parameters
81
+ ----------
82
+ data : dict, optional
83
+ Dictionary containing constraint data arrays, by default {}
84
+ up_to_date : bool, optional
85
+ Whether the interpolator is already built and up to date, by default False
86
+
87
+ Notes
88
+ -----
89
+ This is an abstract method that must be implemented by subclasses.
90
+ All subclasses should call this parent constructor to ensure proper
91
+ initialization of the base data structures.
92
+ """
93
+ self._data = {}
94
+ self.data = data # None
95
+ self.clean() # init data structure
96
+
97
+ self.n_g = 0
98
+ self.n_i = 0
99
+ self.n_n = 0
100
+ self.n_t = 0
101
+
102
+ self.type = InterpolatorType.BASE
103
+ self.up_to_date = up_to_date
104
+ self.constraints = []
105
+ self.__str = "Base Geological Interpolator"
106
+ self.valid = True
107
+ self.dimensions = 3 # default to 3d
108
+ self.support = None
109
+ self.bounding_box = None
110
+ self.latest_diagnostics_report: ConstraintDiagnosticsReport | None = None
111
+
112
+ @abstractmethod
113
+ def set_nelements(self, nelements: int) -> int:
114
+ """Set the number of elements for the interpolation support.
115
+
116
+ Parameters
117
+ ----------
118
+ nelements : int
119
+ Target number of elements
120
+
121
+ Returns
122
+ -------
123
+ int
124
+ Actual number of elements set
125
+
126
+ Notes
127
+ -----
128
+ This is an abstract method that must be implemented by subclasses.
129
+ The actual number of elements may differ from the requested number
130
+ depending on the interpolator's constraints.
131
+ """
132
+
133
+ @property
134
+ @abstractmethod
135
+ def n_elements(self) -> int:
136
+ """Get the number of elements in the interpolation support.
137
+
138
+ Returns
139
+ -------
140
+ int
141
+ Number of elements
142
+
143
+ Notes
144
+ -----
145
+ This is an abstract property that must be implemented by subclasses.
146
+ """
147
+
148
+ @property
149
+ def data(self):
150
+ """Get the constraint data dictionary.
151
+
152
+ Returns
153
+ -------
154
+ dict
155
+ Dictionary containing constraint data arrays
156
+ """
157
+ return self._data
158
+
159
+ @data.setter
160
+ def data(self, data):
161
+ """Set the constraint data dictionary.
162
+
163
+ Parameters
164
+ ----------
165
+ data : dict or None
166
+ Dictionary containing constraint data arrays. If None, an empty dict is used.
167
+ """
168
+ if data is None:
169
+ data = {}
170
+ for k, v in data.items():
171
+ self._data[k] = np.array(v)
172
+
173
+ def __str__(self):
174
+ """Return string representation of the interpolator.
175
+
176
+ Returns
177
+ -------
178
+ str
179
+ String describing the interpolator type and constraint counts
180
+ """
181
+ name = f"{self.type} \n"
182
+ name += f"{self.n_g} gradient points\n"
183
+ name += f"{self.n_i} interface points\n"
184
+ name += f"{self.n_n} normal points\n"
185
+ name += f"{self.n_t} tangent points\n"
186
+ name += f"{self.n_g + self.n_i + self.n_n + self.n_t} total points\n"
187
+ return name
188
+
189
+ def check_array(self, array: np.ndarray):
190
+ """Validate and convert input to numpy array.
191
+
192
+ Parameters
193
+ ----------
194
+ array : array_like
195
+ Input array to validate and convert
196
+
197
+ Returns
198
+ -------
199
+ np.ndarray
200
+ Validated numpy array
201
+
202
+ Raises
203
+ ------
204
+ LoopTypeError
205
+ If the array cannot be converted to a numpy array
206
+ """
207
+ try:
208
+ return np.array(array)
209
+ except (TypeError, ValueError) as e:
210
+ raise LoopTypeError(str(e))
211
+
212
+ def _coerce_value_constraint(
213
+ self, points: np.ndarray | ValueConstraint
214
+ ) -> ValueConstraint:
215
+ if isinstance(points, ValueConstraint):
216
+ return points
217
+ return ValueConstraint.from_array(points, dimensions=self.dimensions)
218
+
219
+ def _coerce_gradient_constraint(
220
+ self, points: np.ndarray | GradientConstraint, is_normal: bool = False
221
+ ) -> GradientConstraint:
222
+ if isinstance(points, GradientConstraint):
223
+ return points
224
+ return GradientConstraint.from_array(
225
+ points, dimensions=self.dimensions, is_normal=is_normal
226
+ )
227
+
228
+ def _coerce_interface_constraint(
229
+ self, points: np.ndarray | InterfaceConstraint
230
+ ) -> InterfaceConstraint:
231
+ if isinstance(points, InterfaceConstraint):
232
+ return points
233
+ return InterfaceConstraint.from_array(points, dimensions=self.dimensions)
234
+
235
+ def _coerce_inequality_constraint(
236
+ self, points: np.ndarray | InequalityConstraint
237
+ ) -> InequalityConstraint:
238
+ if isinstance(points, InequalityConstraint):
239
+ return points
240
+ return InequalityConstraint.from_array(points, dimensions=self.dimensions)
241
+
242
+ def _coerce_inequality_pair_constraint(
243
+ self, points: np.ndarray | InequalityPair
244
+ ) -> InequalityPair:
245
+ if isinstance(points, InequalityPair):
246
+ return points
247
+ return InequalityPair.from_array(points, dimensions=self.dimensions)
248
+
249
+ def _project_points(self, points: np.ndarray) -> np.ndarray:
250
+ """World -> local coordinates for point locations (translation + rotation)."""
251
+ if self.bounding_box is None:
252
+ return points
253
+ return self.bounding_box.project(points)
254
+
255
+ def _reproject_points(self, points: np.ndarray) -> np.ndarray:
256
+ """Local -> world coordinates for point locations (translation + rotation)."""
257
+ if self.bounding_box is None:
258
+ return points
259
+ return self.bounding_box.reproject(points)
260
+
261
+ def _project_vectors(self, vectors: np.ndarray) -> np.ndarray:
262
+ """World -> local for direction vectors (rotation only, no translation)."""
263
+ if self.bounding_box is None:
264
+ return vectors
265
+ return self.bounding_box.project_vectors(vectors)
266
+
267
+ def _reproject_vectors(self, vectors: np.ndarray) -> np.ndarray:
268
+ """Local -> world for direction vectors (rotation only, no translation)."""
269
+ if self.bounding_box is None:
270
+ return vectors
271
+ return self.bounding_box.reproject_vectors(vectors)
272
+
273
+ def _project_constraint_array(self, array: np.ndarray, has_vector: bool = False) -> np.ndarray:
274
+ """Project the leading xyz (and, for gradient/normal/tangent constraints,
275
+ the following gx/gy/gz) columns of a constraint array from world into
276
+ the interpolator's local coordinate frame. Trailing id/value/weight
277
+ columns are left untouched.
278
+ """
279
+ if self.bounding_box is None or array.shape[0] == 0:
280
+ return array
281
+ d = self.dimensions
282
+ array = array.copy()
283
+ array[:, :d] = self._project_points(array[:, :d])
284
+ if has_vector:
285
+ array[:, d : 2 * d] = self._project_vectors(array[:, d : 2 * d])
286
+ return array
287
+
288
+ @abstractmethod
289
+ def set_region(self, **kwargs):
290
+ """Set the interpolation region.
291
+
292
+ Parameters
293
+ ----------
294
+ **kwargs : dict
295
+ Region parameters specific to the interpolator implementation
296
+
297
+ Notes
298
+ -----
299
+ This is an abstract method that must be implemented by subclasses.
300
+ The specific parameters depend on the interpolator type.
301
+ """
302
+
303
+ def set_value_constraints(self, points: np.ndarray | ValueConstraint):
304
+ """Set value constraints for the interpolation.
305
+
306
+ Parameters
307
+ ----------
308
+ points : np.ndarray
309
+ Array containing the value constraints with shape (n_points, 4-5).
310
+ Columns should be [X, Y, Z, value, weight]. If weight is not provided,
311
+ a weight of 1.0 is assumed for all points.
312
+
313
+ Raises
314
+ ------
315
+ ValidationError
316
+ If points array fails shape, dtype, finiteness, or logical checks
317
+
318
+ Notes
319
+ -----
320
+ Value constraints specify known scalar field values at specific locations.
321
+ These are typically used for interface points or measured data values.
322
+ All values must be finite (not NaN or inf), and array must be convertible
323
+ to float64.
324
+ """
325
+ try:
326
+ check_unsupported_combinations(self.data, "value")
327
+ points = self._coerce_value_constraint(points).to_array()
328
+ points = self._project_constraint_array(points)
329
+ self.data["value"] = points.copy()
330
+ self.n_i = points.shape[0]
331
+ self.up_to_date = False
332
+ except ValidationError as e:
333
+ raise ValidationError(f"Failed to set value constraints: {e}") from e
334
+
335
+ def set_gradient_constraints(self, points: np.ndarray | GradientConstraint):
336
+ """Set gradient constraints for the interpolation.
337
+
338
+ Parameters
339
+ ----------
340
+ points : np.ndarray
341
+ Array containing gradient constraints with shape (n_points, 7-8).
342
+ Columns should be [X, Y, Z, gx, gy, gz, weight]. If weight is not
343
+ provided, a weight of 1.0 is assumed for all points.
344
+
345
+ Raises
346
+ ------
347
+ ValidationError
348
+ If points array fails shape, dtype, finiteness, or logical checks.
349
+ Also raised if gradient vectors have zero magnitude.
350
+
351
+ Notes
352
+ -----
353
+ Gradient constraints specify the direction and magnitude of the scalar
354
+ field gradient at specific locations. These are typically derived from
355
+ structural measurements like bedding or foliation orientations.
356
+ All values must be finite (not NaN or inf), and gradient vectors must
357
+ have non-zero magnitude.
358
+ """
359
+ try:
360
+ check_unsupported_combinations(self.data, "gradient")
361
+ points = self._coerce_gradient_constraint(points).to_array()
362
+ points = self._project_constraint_array(points, has_vector=True)
363
+ self.n_g = points.shape[0]
364
+ self.data["gradient"] = points.copy()
365
+ self.up_to_date = False
366
+ except ValidationError as e:
367
+ raise ValidationError(f"Failed to set gradient constraints: {e}") from e
368
+
369
+ def set_normal_constraints(self, points: np.ndarray | GradientConstraint):
370
+ """Set normal constraints for the interpolation.
371
+
372
+ Parameters
373
+ ----------
374
+ points : np.ndarray
375
+ Array containing normal constraints with shape (n_points, 7-8).
376
+ Columns should be [X, Y, Z, nx, ny, nz, weight]. If weight is not
377
+ provided, a weight of 1.0 is assumed for all points.
378
+
379
+ Raises
380
+ ------
381
+ ValidationError
382
+ If points array fails shape, dtype, finiteness, or logical checks.
383
+ Also raised if normal vectors have zero magnitude.
384
+
385
+ Notes
386
+ -----
387
+ Normal constraints specify surface normal directions at specific locations.
388
+ All values must be finite (not NaN or inf), and normal vectors must
389
+ have non-zero magnitude.
390
+ If no weights are provided, w = 1 is assigned to each normal constraint.
391
+ """
392
+ try:
393
+ check_unsupported_combinations(self.data, "normal")
394
+ points = self._coerce_gradient_constraint(points, is_normal=True).to_array()
395
+ points = self._project_constraint_array(points, has_vector=True)
396
+ self.n_n = points.shape[0]
397
+ self.data["normal"] = points.copy()
398
+ self.up_to_date = False
399
+ except ValidationError as e:
400
+ raise ValidationError(f"Failed to set normal constraints: {e}") from e
401
+
402
+ def set_tangent_constraints(self, points: np.ndarray | GradientConstraint):
403
+ """Set tangent constraints for the interpolation.
404
+
405
+ Parameters
406
+ ----------
407
+ points : np.ndarray
408
+ Array containing tangent constraints with shape (n_points, 7-8).
409
+ Columns should be [X, Y, Z, tx, ty, tz, weight]. If weight is not
410
+ provided, a weight of 1.0 is assumed for all points.
411
+
412
+ Raises
413
+ ------
414
+ ValidationError
415
+ If points array fails shape, dtype, finiteness, or logical checks.
416
+ Also raised if tangent vectors have zero magnitude.
417
+
418
+ Notes
419
+ -----
420
+ Tangent constraints specify tangent directions at specific locations.
421
+ All values must be finite (not NaN or inf), and tangent vectors must
422
+ have non-zero magnitude. If no weights are provided, w = 1 is assigned
423
+ to each tangent constraint.
424
+ """
425
+ try:
426
+ check_unsupported_combinations(self.data, "tangent")
427
+ points = self._coerce_gradient_constraint(points).to_array()
428
+ points = self._project_constraint_array(points, has_vector=True)
429
+ self.n_t = points.shape[0]
430
+ self.data["tangent"] = points.copy()
431
+ self.up_to_date = False
432
+ except ValidationError as e:
433
+ raise ValidationError(f"Failed to set tangent constraints: {e}") from e
434
+
435
+ def set_interface_constraints(self, points: np.ndarray | InterfaceConstraint):
436
+ """Set interface constraints for the interpolation.
437
+
438
+ Parameters
439
+ ----------
440
+ points : np.ndarray
441
+ Array containing interface constraints with shape (n_points, 4-5).
442
+ Columns should be [X, Y, Z, interface_id, weight]. If weight is not
443
+ provided, a weight of 1.0 is assumed for all points.
444
+
445
+ Raises
446
+ ------
447
+ ValidationError
448
+ If points array fails shape, dtype, or finiteness checks.
449
+
450
+ Notes
451
+ -----
452
+ Interface constraints mark surface boundaries between different units.
453
+ All values must be finite (not NaN or inf).
454
+ """
455
+ try:
456
+ check_unsupported_combinations(self.data, "interface")
457
+ points = self._coerce_interface_constraint(points).to_array()
458
+ points = self._project_constraint_array(points)
459
+ self.data["interface"] = points.copy()
460
+ self.up_to_date = False
461
+ except ValidationError as e:
462
+ raise ValidationError(f"Failed to set interface constraints: {e}") from e
463
+
464
+ def set_value_inequality_constraints(self, points: np.ndarray | InequalityConstraint):
465
+ """Set inequality value constraints for the interpolation.
466
+
467
+ Parameters
468
+ ----------
469
+ points : np.ndarray
470
+ Array containing inequality constraints with shape (n_points, 5-6).
471
+ Columns should be [X, Y, Z, lower_bound, upper_bound, weight].
472
+ If weight is not provided, a weight of 1.0 is assumed for all points.
473
+
474
+ Raises
475
+ ------
476
+ ValidationError
477
+ If points array fails shape, dtype, finiteness, or logical checks.
478
+ Also raised if lower_bound >= upper_bound for any constraint.
479
+
480
+ Notes
481
+ -----
482
+ Inequality constraints specify bounds on scalar field values at points.
483
+ For each constraint, lower_bound must be strictly less than upper_bound.
484
+ All values must be finite (not NaN or inf).
485
+ """
486
+ try:
487
+ check_unsupported_combinations(self.data, "inequality")
488
+ points = self._coerce_inequality_constraint(points).to_array()
489
+ points = self._project_constraint_array(points)
490
+ self.data["inequality"] = points.copy()
491
+ self.up_to_date = False
492
+ except ValidationError as e:
493
+ raise ValidationError(f"Failed to set inequality value constraints: {e}") from e
494
+
495
+ def set_inequality_pairs_constraints(self, points: np.ndarray | InequalityPair):
496
+ """Set inequality pairs constraints for the interpolation.
497
+
498
+ Parameters
499
+ ----------
500
+ points : np.ndarray
501
+ Array containing inequality pairs constraints with shape (n_points, 4-5).
502
+ Columns should be [X, Y, Z, rock_id, weight]. If weight is not
503
+ provided, a weight of 1.0 is assumed for all points.
504
+
505
+ Raises
506
+ ------
507
+ ValidationError
508
+ If points array fails shape, dtype, or finiteness checks.
509
+
510
+ Notes
511
+ -----
512
+ Inequality pairs constraints enforce ordering relationships between pairs
513
+ of points. All values must be finite (not NaN or inf).
514
+ """
515
+ try:
516
+ check_unsupported_combinations(self.data, "inequality_pairs")
517
+ points = self._coerce_inequality_pair_constraint(points).to_array()
518
+ points = self._project_constraint_array(points)
519
+ self.data["inequality_pairs"] = points.copy()
520
+ self.up_to_date = False
521
+ except ValidationError as e:
522
+ raise ValidationError(f"Failed to set inequality pairs constraints: {e}") from e
523
+
524
+ def get_value_constraints(self):
525
+ """
526
+
527
+ Returns
528
+ -------
529
+ numpy array
530
+ """
531
+ return self.data["value"]
532
+
533
+ def get_gradient_constraints(self):
534
+ """
535
+
536
+ Returns
537
+ -------
538
+ numpy array
539
+ """
540
+ return self.data["gradient"]
541
+
542
+ def get_tangent_constraints(self):
543
+ """
544
+
545
+ Returns
546
+ -------
547
+ numpy array
548
+ """
549
+
550
+ return self.data["tangent"]
551
+
552
+ def get_norm_constraints(self):
553
+ """
554
+
555
+ Returns
556
+ -------
557
+ numpy array
558
+ """
559
+ return self.data["normal"]
560
+
561
+ def get_data_locations(self):
562
+ """Get the location of all data points
563
+
564
+ Returns
565
+ -------
566
+ numpy array
567
+ Nx3 - X,Y,Z location of all data points
568
+ """
569
+ return np.vstack([d[:, :3] for d in self.data.values()])
570
+
571
+ def get_interface_constraints(self):
572
+ """Get the location of interface constraints
573
+
574
+ Returns
575
+ -------
576
+ numpy array
577
+ Nx4 - X,Y,Z,id location of all interface constraints
578
+ """
579
+ return self.data["interface"]
580
+
581
+ def get_inequality_value_constraints(self):
582
+ return self.data["inequality"]
583
+
584
+ def get_inequality_pairs_constraints(self):
585
+ return self.data["inequality_pairs"]
586
+
587
+ def _outside_model_points_from_data(self) -> dict[str, int]:
588
+ if self.support is None or not hasattr(self.support, "inside"):
589
+ return {}
590
+
591
+ mapping = {
592
+ "value": "value",
593
+ "gradient": "gradient",
594
+ "normal": "normal",
595
+ "tangent": "tangent",
596
+ "interface": "interface",
597
+ "inequality": "inequality_value",
598
+ "inequality_pairs": "inequality_pairs",
599
+ }
600
+
601
+ outside = {}
602
+ for data_key, family_name in mapping.items():
603
+ points = self.data.get(data_key)
604
+ if points is None or points.shape[0] == 0:
605
+ outside[family_name] = 0
606
+ continue
607
+ xyz = np.asarray(points[:, : self.dimensions], dtype=float)
608
+ try:
609
+ inside = self.support.inside(xyz)
610
+ outside[family_name] = int((~inside).sum())
611
+ except (ValueError, TypeError) as e:
612
+ logger.warning(
613
+ f"Failed to compute outside-model coverage for constraint family '{family_name}': {e}. "
614
+ f"Using zero outside points."
615
+ )
616
+ outside[family_name] = 0
617
+ return outside
618
+
619
+ def _weight_stats_from_points(self, points: np.ndarray):
620
+ if points.shape[1] <= self.dimensions + 1:
621
+ return None, None, None
622
+ weights = np.asarray(points[:, -1], dtype=float)
623
+ if weights.size == 0:
624
+ return None, None, None
625
+ return (
626
+ float(np.mean(weights)),
627
+ float(np.min(weights)),
628
+ float(np.max(weights)),
629
+ )
630
+
631
+ def _build_constraint_diagnostics_report(self) -> ConstraintDiagnosticsReport:
632
+ mapping = {
633
+ "value": "value",
634
+ "gradient": "gradient",
635
+ "normal": "normal",
636
+ "tangent": "tangent",
637
+ "interface": "interface",
638
+ "inequality": "inequality_value",
639
+ "inequality_pairs": "inequality_pairs",
640
+ }
641
+
642
+ outside = self._outside_model_points_from_data()
643
+ families = {}
644
+ for data_key, family_name in mapping.items():
645
+ points = self.data.get(data_key)
646
+ if points is None:
647
+ points = np.zeros((0, self.dimensions + 1), dtype=float)
648
+ row_count = int(points.shape[0])
649
+ mean_w, min_w, max_w = self._weight_stats_from_points(points)
650
+ families[family_name] = ConstraintFamilyDiagnostics(
651
+ name=family_name,
652
+ active=row_count > 0,
653
+ row_count=row_count,
654
+ dropped_rows=outside.get(family_name, 0),
655
+ effective_weight_mean=mean_w,
656
+ effective_weight_min=min_w,
657
+ effective_weight_max=max_w,
658
+ source_point_count=row_count,
659
+ outside_model_point_count=outside.get(family_name, 0),
660
+ )
661
+
662
+ region_coverage = None
663
+ if self.support is not None and hasattr(self.support, "n_nodes"):
664
+ total_nodes = int(self.support.n_nodes)
665
+ region_mask = np.ones(total_nodes, dtype=bool)
666
+ if hasattr(self, "region"):
667
+ try:
668
+ region_mask = np.asarray(self.region, dtype=bool)
669
+ except (ValueError, TypeError) as e:
670
+ logger.warning(
671
+ f"Failed to interpret region mask (expected array-like bool): {e}. "
672
+ f"Using full domain (all nodes active)."
673
+ )
674
+ region_mask = np.ones(total_nodes, dtype=bool)
675
+ active_nodes = int(np.sum(region_mask))
676
+ region_coverage = RegionCoverageDiagnostics(
677
+ total_support_nodes=total_nodes,
678
+ active_region_nodes=active_nodes,
679
+ inactive_region_nodes=total_nodes - active_nodes,
680
+ active_fraction=0.0 if total_nodes == 0 else float(active_nodes / total_nodes),
681
+ )
682
+
683
+ return ConstraintDiagnosticsReport(
684
+ interpolator_type=self.type.name,
685
+ families=families,
686
+ region_coverage=region_coverage,
687
+ outside_model_points=outside,
688
+ )
689
+
690
+ def get_constraint_diagnostics_report(
691
+ self, refresh: bool = False
692
+ ) -> ConstraintDiagnosticsReport:
693
+ if self.latest_diagnostics_report is None or refresh:
694
+ self.latest_diagnostics_report = self._build_constraint_diagnostics_report()
695
+ return self.latest_diagnostics_report
696
+
697
+ # @abstractmethod
698
+ def setup(self, **kwargs) -> ConstraintDiagnosticsReport:
699
+ """Run setup and return a diagnostics report."""
700
+ report = self.setup_interpolator(**kwargs)
701
+ if isinstance(report, ConstraintDiagnosticsReport):
702
+ self.latest_diagnostics_report = report
703
+ return report
704
+ return self.get_constraint_diagnostics_report(refresh=True)
705
+
706
+ @abstractmethod
707
+ def setup_interpolator(self, **kwargs):
708
+ """
709
+ Runs all of the required setting up stuff
710
+ """
711
+ raise NotImplementedError("setup_interpolator must be implemented by subclasses")
712
+
713
+ @abstractmethod
714
+ def solve_system(self, solver, solver_kwargs: dict | None = None) -> bool:
715
+ """
716
+ Solves the interpolation equations
717
+ """
718
+
719
+ @abstractmethod
720
+ def update(self) -> bool:
721
+ return False
722
+
723
+ def evaluate_value(self, locations: np.ndarray):
724
+ """Evaluate the scalar field value at world-coordinate locations.
725
+
726
+ Projects ``locations`` into the interpolator's local coordinate
727
+ frame (a no-op if no ``bounding_box`` is set) before delegating to
728
+ the subclass's ``_evaluate_value_local``.
729
+ """
730
+ return self._evaluate_value_local(self._project_points(locations))
731
+
732
+ def evaluate_gradient(self, locations: np.ndarray):
733
+ """Evaluate the gradient at world-coordinate locations, returned in
734
+ world-coordinate directions.
735
+
736
+ Projects ``locations`` into the local frame, evaluates the gradient
737
+ there, then reprojects the resulting vectors back to world (rotation
738
+ only -- both are no-ops if no ``bounding_box`` is set).
739
+ """
740
+ gradient = self._evaluate_gradient_local(self._project_points(locations))
741
+ return self._reproject_vectors(gradient)
742
+
743
+ @abstractmethod
744
+ def _evaluate_value_local(self, locations: np.ndarray):
745
+ """Evaluate the scalar field value at locations already expressed in
746
+ the interpolator's local coordinate frame. Implemented by subclasses.
747
+ """
748
+ raise NotImplementedError("_evaluate_value_local not implemented")
749
+
750
+ @abstractmethod
751
+ def _evaluate_gradient_local(self, locations: np.ndarray):
752
+ """Evaluate the gradient at locations already expressed in the
753
+ interpolator's local coordinate frame, returning local-frame
754
+ direction vectors. Implemented by subclasses.
755
+ """
756
+ raise NotImplementedError("_evaluate_gradient_local not implemented")
757
+
758
+ def surfaces(self, value):
759
+ raise NotImplementedError("Surface extraction not implemented for this representation")
760
+
761
+ @abstractmethod
762
+ def reset(self):
763
+ pass
764
+
765
+ @abstractmethod
766
+ def add_value_constraints(self, w: float = 1.0):
767
+ pass
768
+
769
+ @abstractmethod
770
+ def add_gradient_constraints(self, w: float = 1.0):
771
+ pass
772
+
773
+ @abstractmethod
774
+ def add_norm_constraints(self, w: float = 1.0):
775
+ pass
776
+
777
+ @abstractmethod
778
+ def add_tangent_constraints(self, w: float = 1.0):
779
+ pass
780
+
781
+ @abstractmethod
782
+ def add_interface_constraints(self, w: float = 1.0):
783
+ pass
784
+
785
+ @abstractmethod
786
+ def add_value_inequality_constraints(self, w: float = 1.0):
787
+ pass
788
+
789
+ @abstractmethod
790
+ def add_inequality_pairs_constraints(
791
+ self,
792
+ w: float = 1.0,
793
+ upper_bound=None,
794
+ lower_bound=-np.inf,
795
+ pairs: list | None = None,
796
+ ):
797
+ pass
798
+
799
+ def to_dict(self):
800
+ def _to_json_safe(value):
801
+ if isinstance(value, np.ndarray):
802
+ return value.tolist()
803
+ if isinstance(value, (np.floating, np.integer)):
804
+ return value.item()
805
+ if isinstance(value, dict):
806
+ return {k: _to_json_safe(v) for k, v in value.items()}
807
+ if isinstance(value, (list, tuple)):
808
+ return [_to_json_safe(v) for v in value]
809
+ return value
810
+
811
+ payload = {
812
+ "type": self.type.value,
813
+ "data": _to_json_safe({k: np.asarray(v) for k, v in self.data.items()}),
814
+ "up_to_date": self.up_to_date,
815
+ "valid": self.valid,
816
+ }
817
+ if self.support is not None and hasattr(self.support, "to_dict"):
818
+ support_dict = _to_json_safe(self.support.to_dict())
819
+ if (
820
+ isinstance(support_dict, dict)
821
+ and "nsteps" in support_dict
822
+ and hasattr(self.support, "nsteps_cells")
823
+ ):
824
+ support_dict["nsteps"] = _to_json_safe(np.asarray(self.support.nsteps_cells))
825
+ if isinstance(support_dict, dict) and "type" not in support_dict:
826
+ support_type = getattr(self.support, "type", None)
827
+ if support_type is not None:
828
+ support_dict["type"] = getattr(support_type, "numerator", support_type)
829
+ payload["support"] = support_dict
830
+ return payload
831
+
832
+ def to_json(self, indent: int = 2) -> str:
833
+ return json.dumps(self.to_dict(), indent=indent)
834
+
835
+ @classmethod
836
+ def from_json(cls, json_str: str) -> GeologicalInterpolator:
837
+ return cls.from_dict(json.loads(json_str))
838
+
839
+ def to_yaml(self, file_path: str | None = None) -> None | str:
840
+ try:
841
+ import yaml
842
+ except ImportError as exc:
843
+ raise ImportError("PyYAML is required for YAML export: pip install pyyaml") from exc
844
+ if file_path is None:
845
+ return yaml.safe_dump(self.to_dict(), sort_keys=False, allow_unicode=True)
846
+ with open(file_path, "w") as f:
847
+ yaml.safe_dump(self.to_dict(), f, sort_keys=False, allow_unicode=True)
848
+
849
+ @classmethod
850
+ def from_yaml(cls, yaml_str: str) -> GeologicalInterpolator:
851
+ try:
852
+ import yaml
853
+ except ImportError as exc:
854
+ raise ImportError("PyYAML is required for YAML import: pip install pyyaml") from exc
855
+ payload = yaml.safe_load(yaml_str)
856
+ return cls.from_dict(payload)
857
+
858
+ @classmethod
859
+ def from_dict(cls, data):
860
+ from ._interpolator_factory import InterpolatorFactory
861
+
862
+ return InterpolatorFactory.from_dict(data.copy())
863
+
864
+ def clean(self):
865
+ """
866
+ Removes all of the data from an interpolator
867
+
868
+ Returns
869
+ -------
870
+
871
+ """
872
+ self.data = {
873
+ "gradient": np.zeros((0, 7)),
874
+ "value": np.zeros((0, 5)),
875
+ "normal": np.zeros((0, 7)),
876
+ "tangent": np.zeros((0, 7)),
877
+ "interface": np.zeros((0, 5)),
878
+ "inequality": np.zeros((0, 6)),
879
+ "inequality_pairs": np.zeros((0, 4)),
880
+ }
881
+ self.up_to_date = False
882
+ self.n_g = 0
883
+ self.n_i = 0
884
+ self.n_n = 0
885
+ self.n_t = 0
886
+
887
+ def debug(self):
888
+ """Helper function for debugging when the interpolator isn't working"""
889
+ error_string = ""
890
+ error_code = 0
891
+ if (
892
+ self.type > InterpolatorType.BASE_DISCRETE
893
+ and self.type < InterpolatorType.BASE_DATA_SUPPORTED
894
+ ):
895
+
896
+ def mask(xyz):
897
+ return self.support.inside(xyz)
898
+
899
+ else:
900
+
901
+ def mask(xyz):
902
+ return np.ones(xyz.shape[0], dtype=bool)
903
+
904
+ if (
905
+ len(
906
+ np.unique(
907
+ self.get_value_constraints()[mask(self.get_value_constraints()[:, :3]), 3]
908
+ )
909
+ )
910
+ == 1
911
+ ):
912
+ error_code += 1
913
+ error_string += "There is only one unique value in the model interpolation support \n"
914
+ error_string += "Try increasing the model bounding box \n"
915
+ if len(self.get_norm_constraints()[mask(self.get_norm_constraints()[:, :3]), :]) == 0:
916
+ error_code += 1
917
+ error_string += "There are no norm constraints in the model interpolation support \n"
918
+ error_string += "Try increasing the model bounding box or adding more data\n"
919
+ if error_code > 1:
920
+ print(error_string)