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,604 @@
1
+ """Input validation helpers for loop_interpolation.
2
+
3
+ This module provides centralized validation for constraint inputs to ensure
4
+ consistent error handling, clear error messages, and early detection of
5
+ invalid constraint combinations.
6
+
7
+ NaN handling contract
8
+ ---------------------
9
+ - **Weight column NaN** → silently replaced with 1.0 (default weight).
10
+ This lets callers pass ``np.nan`` as a sentinel for "use default weight",
11
+ which is a common pattern when assembling constraints from DataFrames.
12
+ - **Position / data column NaN or inf** → rows are silently dropped with a
13
+ warning. This preserves backward-compatible behaviour where constraints
14
+ that fall outside the model or contain missing values are ignored.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+
20
+ import numpy as np
21
+
22
+ _logger = logging.getLogger(__name__)
23
+
24
+
25
+ def _fill_nan_weights(points: np.ndarray, weight_col: int) -> np.ndarray:
26
+ """Replace NaN values in the weight column with 1.0 (default weight).
27
+
28
+ Parameters
29
+ ----------
30
+ points : np.ndarray
31
+ Constraint array, already converted to float64.
32
+ weight_col : int
33
+ Column index of the weight column.
34
+
35
+ Returns
36
+ -------
37
+ np.ndarray
38
+ Array with NaN weights replaced; a copy is returned only if any
39
+ replacements were made.
40
+ """
41
+ nan_mask = ~np.isfinite(points[:, weight_col])
42
+ if np.any(nan_mask):
43
+ n_replaced = int(np.sum(nan_mask))
44
+ _logger.warning(
45
+ "%d NaN weight value(s) replaced with 1.0 (default weight). "
46
+ "Provide explicit finite weights to suppress this warning.",
47
+ n_replaced,
48
+ )
49
+ points = points.copy()
50
+ points[nan_mask, weight_col] = 1.0
51
+ return points
52
+
53
+
54
+ def _drop_nan_data_rows(points: np.ndarray, data_cols: slice, name: str) -> np.ndarray:
55
+ """Drop rows that contain NaN or inf in the position / data columns.
56
+
57
+ Weight columns are intentionally excluded from this check because NaN
58
+ weights are handled separately by :func:`_fill_nan_weights`.
59
+
60
+ Parameters
61
+ ----------
62
+ points : np.ndarray
63
+ Constraint array, already converted to float64.
64
+ data_cols : slice
65
+ Slice selecting the position / data columns (excluding weight).
66
+ name : str
67
+ Human-readable constraint type name used in the warning message.
68
+
69
+ Returns
70
+ -------
71
+ np.ndarray
72
+ Array with invalid rows removed; the original array is returned
73
+ unchanged when no rows are dropped.
74
+ """
75
+ bad_rows = ~np.isfinite(points[:, data_cols]).all(axis=1)
76
+ if np.any(bad_rows):
77
+ n_dropped = int(np.sum(bad_rows))
78
+ _logger.warning(
79
+ "%d %s row(s) dropped: position or data columns contain NaN or inf. "
80
+ "Provide finite values to include them.",
81
+ n_dropped,
82
+ name,
83
+ )
84
+ points = points[~bad_rows]
85
+ return points
86
+
87
+
88
+ class ValidationError(ValueError):
89
+ """Base exception for constraint validation errors."""
90
+
91
+
92
+
93
+ class ShapeError(ValidationError):
94
+ """Exception for shape mismatches in constraint arrays."""
95
+
96
+
97
+
98
+ class DtypeError(ValidationError):
99
+ """Exception for data type mismatches in constraint arrays."""
100
+
101
+
102
+
103
+ class FiniteValueError(ValidationError):
104
+ """Exception for non-finite values in constraint arrays."""
105
+
106
+
107
+
108
+ class VectorError(ValidationError):
109
+ """Exception for invalid vector/direction constraints."""
110
+
111
+
112
+
113
+ class WeightError(ValidationError):
114
+ """Exception for invalid weight values."""
115
+
116
+
117
+
118
+ class UnsupportedCombinationError(ValidationError):
119
+ """Exception for unsupported constraint combinations."""
120
+
121
+
122
+
123
+ def _ensure_float_array(arr: np.ndarray, name: str = "array") -> np.ndarray:
124
+ """Convert array to float type with error handling.
125
+
126
+ Parameters
127
+ ----------
128
+ arr : np.ndarray
129
+ Input array to convert
130
+ name : str
131
+ Name of array for error messages
132
+
133
+ Returns
134
+ -------
135
+ np.ndarray
136
+ Array converted to float64
137
+
138
+ Raises
139
+ ------
140
+ DtypeError
141
+ If array cannot be converted to float
142
+ """
143
+ try:
144
+ return np.asarray(arr, dtype=np.float64)
145
+ except (TypeError, ValueError) as e:
146
+ raise DtypeError(
147
+ f"{name} could not be converted to float64. "
148
+ f"All constraint arrays must contain numeric values. Error: {e}"
149
+ )
150
+
151
+
152
+ def _check_shape(
153
+ arr: np.ndarray,
154
+ expected_shape: tuple[int | None, ...],
155
+ name: str = "array",
156
+ ) -> None:
157
+ """Validate array shape matches expectations.
158
+
159
+ Parameters
160
+ ----------
161
+ arr : np.ndarray
162
+ Array to validate
163
+ expected_shape : tuple
164
+ Expected shape. Use None for variable dimensions.
165
+ name : str
166
+ Name of array for error messages
167
+
168
+ Raises
169
+ ------
170
+ ShapeError
171
+ If shape doesn't match expected shape
172
+ """
173
+ if arr.ndim != len(expected_shape):
174
+ raise ShapeError(
175
+ f"{name} has {arr.ndim} dimensions, but {len(expected_shape)} expected. "
176
+ f"Expected shape: {expected_shape}, got {arr.shape}"
177
+ )
178
+
179
+ for i, (actual, expected) in enumerate(zip(arr.shape, expected_shape)):
180
+ if expected is not None and actual != expected:
181
+ raise ShapeError(
182
+ f"{name} dimension {i}: expected {expected}, got {actual}. "
183
+ f"Expected shape: {expected_shape}, got {arr.shape}"
184
+ )
185
+
186
+
187
+ def _check_finite(arr: np.ndarray, name: str = "array") -> None:
188
+ """Validate all values in array are finite (not NaN or inf).
189
+
190
+ Parameters
191
+ ----------
192
+ arr : np.ndarray
193
+ Array to validate
194
+ name : str
195
+ Name of array for error messages
196
+
197
+ Raises
198
+ ------
199
+ FiniteValueError
200
+ If any non-finite values are found
201
+ """
202
+ non_finite = ~np.isfinite(arr)
203
+ if np.any(non_finite):
204
+ n_invalid = int(np.sum(non_finite))
205
+ invalid_indices = np.where(non_finite)
206
+ raise FiniteValueError(
207
+ f"{name} contains {n_invalid} non-finite values (NaN or inf). "
208
+ f"All constraint values must be finite. "
209
+ f"Found at indices: {invalid_indices}"
210
+ )
211
+
212
+
213
+ def _strip_injected_weight_column(
214
+ arr: np.ndarray, points: np.ndarray, no_weight_ncols: int
215
+ ) -> np.ndarray:
216
+ """Undo the weight column that ``BaseConstraint.to_array()`` always
217
+ appends, when the caller's original input didn't include one.
218
+
219
+ The constraint classes always carry an explicit weight column
220
+ internally (defaulting to 1.0) so downstream interpolator code has a
221
+ uniform layout. The standalone ``validate_*`` helpers instead promise a
222
+ round-trip of the caller's own column layout, so the injected column is
223
+ dropped again here when it wasn't present on input.
224
+ """
225
+ pts = np.asarray(points)
226
+ if pts.ndim == 2 and pts.shape[1] == no_weight_ncols:
227
+ return arr[:, :no_weight_ncols]
228
+ return arr
229
+
230
+
231
+ def validate_value_constraint(
232
+ points: np.ndarray,
233
+ dimensions: int = 3,
234
+ ) -> np.ndarray:
235
+ """Validate value constraint input array.
236
+
237
+ Value constraints specify scalar field values at points.
238
+ Expected format: [X, Y, Z, value] or [X, Y, Z, value, weight]
239
+
240
+ Parameters
241
+ ----------
242
+ points : np.ndarray
243
+ Input point array to validate
244
+ dimensions : int
245
+ Number of spatial dimensions (default 3)
246
+
247
+ Returns
248
+ -------
249
+ np.ndarray
250
+ Validated array (float64 dtype). Rows with NaN/inf in position or
251
+ value columns are silently dropped; NaN weights are replaced with 1.0.
252
+
253
+ Raises
254
+ ------
255
+ ShapeError
256
+ If points has wrong number of dimensions or columns
257
+ DtypeError
258
+ If points cannot be converted to float
259
+ FiniteValueError
260
+ If any coordinates or values are non-finite after NaN rows are dropped
261
+ """
262
+ from .constraints import ValueConstraint
263
+
264
+ arr = ValueConstraint.from_array(points, dimensions=dimensions).to_array()
265
+ return _strip_injected_weight_column(arr, points, dimensions + 1)
266
+
267
+
268
+ def validate_gradient_constraint(
269
+ points: np.ndarray,
270
+ dimensions: int = 3,
271
+ ) -> np.ndarray:
272
+ """Validate gradient constraint input array.
273
+
274
+ Gradient constraints specify field gradients at points.
275
+ Expected format: [X, Y, Z, gx, gy, gz] or [X, Y, Z, gx, gy, gz, weight]
276
+
277
+ Parameters
278
+ ----------
279
+ points : np.ndarray
280
+ Input point array to validate
281
+ dimensions : int
282
+ Number of spatial dimensions (default 3)
283
+
284
+ Returns
285
+ -------
286
+ np.ndarray
287
+ Validated array (float64 dtype). Rows with NaN/inf in position or
288
+ gradient columns are silently dropped; NaN weights are replaced with 1.0.
289
+
290
+ Raises
291
+ ------
292
+ ShapeError
293
+ If points has wrong number of dimensions or columns
294
+ DtypeError
295
+ If points cannot be converted to float
296
+ FiniteValueError
297
+ If any coordinates or gradient values are non-finite after NaN rows are dropped
298
+ VectorError
299
+ If gradient vectors have zero magnitude (degenerate case)
300
+ """
301
+ from .constraints import GradientConstraint
302
+
303
+ arr = GradientConstraint.from_array(points, dimensions=dimensions).to_array()
304
+ return _strip_injected_weight_column(arr, points, dimensions * 2)
305
+
306
+
307
+ def validate_normal_constraint(
308
+ points: np.ndarray,
309
+ dimensions: int = 3,
310
+ ) -> np.ndarray:
311
+ """Validate normal constraint input array.
312
+
313
+ Normal constraints specify surface normals at points.
314
+ Expected format: [X, Y, Z, nx, ny, nz] or [X, Y, Z, nx, ny, nz, weight]
315
+
316
+ Parameters
317
+ ----------
318
+ points : np.ndarray
319
+ Input point array to validate
320
+ dimensions : int
321
+ Number of spatial dimensions (default 3)
322
+
323
+ Returns
324
+ -------
325
+ np.ndarray
326
+ Validated array (float64 dtype). Rows with NaN/inf in position or
327
+ normal columns are silently dropped; NaN weights are replaced with 1.0.
328
+
329
+ Raises
330
+ ------
331
+ ShapeError
332
+ If points has wrong number of dimensions or columns
333
+ DtypeError
334
+ If points cannot be converted to float
335
+ FiniteValueError
336
+ If any coordinates or normals are non-finite after NaN rows are dropped
337
+ VectorError
338
+ If normal vectors have zero magnitude
339
+ """
340
+ from .constraints import GradientConstraint
341
+
342
+ arr = GradientConstraint.from_array(points, dimensions=dimensions, is_normal=True).to_array()
343
+ return _strip_injected_weight_column(arr, points, dimensions * 2)
344
+
345
+
346
+ def validate_tangent_constraint(
347
+ points: np.ndarray,
348
+ dimensions: int = 3,
349
+ ) -> np.ndarray:
350
+ """Validate tangent constraint input array.
351
+
352
+ Tangent constraints specify tangent directions at points.
353
+ Expected format: [X, Y, Z, tx, ty, tz] or [X, Y, Z, tx, ty, tz, weight]
354
+
355
+ Parameters
356
+ ----------
357
+ points : np.ndarray
358
+ Input point array to validate
359
+ dimensions : int
360
+ Number of spatial dimensions (default 3)
361
+
362
+ Returns
363
+ -------
364
+ np.ndarray
365
+ Validated array (float64 dtype). Rows with NaN/inf in position or
366
+ tangent columns are silently dropped; NaN weights are replaced with 1.0.
367
+
368
+ Raises
369
+ ------
370
+ ShapeError
371
+ If points has wrong number of dimensions or columns
372
+ DtypeError
373
+ If points cannot be converted to float
374
+ FiniteValueError
375
+ If any coordinates or tangents are non-finite after NaN rows are dropped
376
+ VectorError
377
+ If tangent vectors have zero magnitude
378
+ """
379
+ from .constraints import GradientConstraint
380
+
381
+ arr = GradientConstraint.from_array(points, dimensions=dimensions).to_array()
382
+ return _strip_injected_weight_column(arr, points, dimensions * 2)
383
+
384
+
385
+ def validate_interface_constraint(
386
+ points: np.ndarray,
387
+ dimensions: int = 3,
388
+ ) -> np.ndarray:
389
+ """Validate interface constraint input array.
390
+
391
+ Interface constraints mark surface boundaries.
392
+ Expected format: [X, Y, Z, id] or [X, Y, Z, id, weight]
393
+
394
+ Parameters
395
+ ----------
396
+ points : np.ndarray
397
+ Input point array to validate
398
+ dimensions : int
399
+ Number of spatial dimensions (default 3)
400
+
401
+ Returns
402
+ -------
403
+ np.ndarray
404
+ Validated array (float64 dtype). Rows with NaN/inf in position or
405
+ id columns are silently dropped; NaN weights are replaced with 1.0.
406
+
407
+ Raises
408
+ ------
409
+ ShapeError
410
+ If points has wrong number of dimensions or columns
411
+ DtypeError
412
+ If points cannot be converted to float
413
+ FiniteValueError
414
+ If any coordinates are non-finite after NaN rows are dropped
415
+ """
416
+ from .constraints import InterfaceConstraint
417
+
418
+ arr = InterfaceConstraint.from_array(points, dimensions=dimensions).to_array()
419
+ return _strip_injected_weight_column(arr, points, dimensions + 1)
420
+
421
+
422
+ def validate_inequality_value_constraint(
423
+ points: np.ndarray,
424
+ dimensions: int = 3,
425
+ ) -> np.ndarray:
426
+ """Validate inequality value constraint input array.
427
+
428
+ Inequality constraints specify bounds on scalar field values.
429
+ Expected format: [X, Y, Z, lower_bound, upper_bound] or [X, Y, Z, lower_bound, upper_bound, weight]
430
+
431
+ Parameters
432
+ ----------
433
+ points : np.ndarray
434
+ Input point array to validate
435
+ dimensions : int
436
+ Number of spatial dimensions (default 3)
437
+
438
+ Returns
439
+ -------
440
+ np.ndarray
441
+ Validated array (float64 dtype)
442
+
443
+ Raises
444
+ ------
445
+ ShapeError
446
+ If points has wrong number of dimensions or columns
447
+ DtypeError
448
+ If points cannot be converted to float
449
+ FiniteValueError
450
+ If any coordinates or bounds are non-finite
451
+ ValueError
452
+ If lower bound >= upper bound for any constraint
453
+ """
454
+ from .constraints import InequalityConstraint
455
+
456
+ arr = InequalityConstraint.from_array(points, dimensions=dimensions).to_array()
457
+ return _strip_injected_weight_column(arr, points, dimensions + 2)
458
+
459
+
460
+ def validate_inequality_pairs_constraint(
461
+ points: np.ndarray,
462
+ dimensions: int = 3,
463
+ ) -> np.ndarray:
464
+ """Validate inequality pairs constraint input array.
465
+
466
+ Inequality pairs enforce ordering between pairs of points.
467
+ Expected format: [X, Y, Z, rock_id] or [X, Y, Z, rock_id, weight]
468
+
469
+ Parameters
470
+ ----------
471
+ points : np.ndarray
472
+ Input point array to validate
473
+ dimensions : int
474
+ Number of spatial dimensions (default 3)
475
+
476
+ Returns
477
+ -------
478
+ np.ndarray
479
+ Validated array (float64 dtype)
480
+
481
+ Raises
482
+ ------
483
+ ShapeError
484
+ If points has wrong number of dimensions or columns
485
+ DtypeError
486
+ If points cannot be converted to float
487
+ FiniteValueError
488
+ If any coordinates are non-finite
489
+ """
490
+ from .constraints import InequalityPair
491
+
492
+ arr = InequalityPair.from_array(points, dimensions=dimensions).to_array()
493
+ return _strip_injected_weight_column(arr, points, dimensions + 1)
494
+
495
+
496
+ def validate_weights(
497
+ weights: float | np.ndarray,
498
+ n_constraints: int,
499
+ constraint_name: str = "constraint",
500
+ ) -> float | np.ndarray:
501
+ """Validate weight values for constraints.
502
+
503
+ Weights must be positive scalars or arrays.
504
+
505
+ Parameters
506
+ ----------
507
+ weights : float or np.ndarray
508
+ Weight value(s) to validate
509
+ n_constraints : int
510
+ Number of constraints (for array validation)
511
+ constraint_name : str
512
+ Name of constraint type for error messages
513
+
514
+ Returns
515
+ -------
516
+ float or np.ndarray
517
+ Validated weights
518
+
519
+ Raises
520
+ ------
521
+ DtypeError
522
+ If weights cannot be converted to float
523
+ FiniteValueError
524
+ If weights contain non-finite values
525
+ WeightError
526
+ If weights are non-positive or wrong shape
527
+ """
528
+ if isinstance(weights, (int, float)):
529
+ if not np.isfinite(weights):
530
+ raise FiniteValueError(
531
+ f"{constraint_name} weight is non-finite. "
532
+ f"Weight must be a finite positive number. Got: {weights}"
533
+ )
534
+ if weights <= 0:
535
+ raise WeightError(f"{constraint_name} weight must be positive. Got: {weights}")
536
+ return float(weights)
537
+
538
+ weights_arr = _ensure_float_array(weights, f"{constraint_name} weights array")
539
+
540
+ if weights_arr.ndim == 1:
541
+ if weights_arr.shape[0] != n_constraints:
542
+ raise ShapeError(
543
+ f"{constraint_name} weights array has {weights_arr.shape[0]} elements, "
544
+ f"but {n_constraints} constraints provided. "
545
+ f"Weight array length must match number of constraints."
546
+ )
547
+ else:
548
+ raise ShapeError(
549
+ f"{constraint_name} weights array must be 1D. Got shape: {weights_arr.shape}"
550
+ )
551
+
552
+ _check_finite(weights_arr, f"{constraint_name} weights")
553
+
554
+ if np.any(weights_arr <= 0):
555
+ n_invalid = int(np.sum(weights_arr <= 0))
556
+ invalid_indices = np.where(weights_arr <= 0)[0]
557
+ raise WeightError(
558
+ f"Found {n_invalid} non-positive weights in {constraint_name} array. "
559
+ f"All weights must be positive. "
560
+ f"Non-positive weights at indices: {invalid_indices}"
561
+ )
562
+
563
+ return weights_arr
564
+
565
+
566
+ def check_unsupported_combinations(
567
+ data: dict,
568
+ constraint_type: str,
569
+ ) -> None:
570
+ """Check for unsupported constraint combinations.
571
+
572
+ Parameters
573
+ ----------
574
+ data : dict
575
+ Dictionary of all constraints
576
+ constraint_type : str
577
+ Type of constraint being added
578
+
579
+ Raises
580
+ ------
581
+ UnsupportedCombinationError
582
+ If unsupported combinations are detected
583
+ """
584
+ supported_constraint_types = {
585
+ "value",
586
+ "gradient",
587
+ "normal",
588
+ "tangent",
589
+ "interface",
590
+ "inequality",
591
+ "inequality_pairs",
592
+ }
593
+
594
+ if constraint_type not in supported_constraint_types:
595
+ raise UnsupportedCombinationError(
596
+ f"Unsupported constraint type '{constraint_type}'. "
597
+ f"Supported types are: {sorted(supported_constraint_types)}"
598
+ )
599
+
600
+ # Future extension point for solver-specific constraint incompatibilities.
601
+ if not isinstance(data, dict):
602
+ raise UnsupportedCombinationError(
603
+ "Constraint container must be a dict mapping constraint families to arrays."
604
+ )