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.
- loop_interpolation/__init__.py +152 -0
- loop_interpolation/_builders.py +149 -0
- loop_interpolation/_constant_norm.py +232 -0
- loop_interpolation/_diagnostics.py +102 -0
- loop_interpolation/_discrete_fold_interpolator.py +242 -0
- loop_interpolation/_discrete_interpolator.py +1405 -0
- loop_interpolation/_fd_fold_interpolator.py +237 -0
- loop_interpolation/_finite_difference_interpolator.py +1348 -0
- loop_interpolation/_fold_event.py +185 -0
- loop_interpolation/_fold_norm_alignment.py +118 -0
- loop_interpolation/_fold_setup.py +39 -0
- loop_interpolation/_geological_interpolator.py +920 -0
- loop_interpolation/_interpolator_builder.py +251 -0
- loop_interpolation/_interpolator_factory.py +167 -0
- loop_interpolation/_interpolatortype.py +20 -0
- loop_interpolation/_operator.py +44 -0
- loop_interpolation/_p1interpolator.py +299 -0
- loop_interpolation/_p2interpolator.py +317 -0
- loop_interpolation/_regularisation.py +110 -0
- loop_interpolation/_solver_pipeline.py +138 -0
- loop_interpolation/_solver_strategy.py +218 -0
- loop_interpolation/_surfe_wrapper.py +211 -0
- loop_interpolation/_svariogram.py +133 -0
- loop_interpolation/_validation.py +604 -0
- loop_interpolation/constraints.py +473 -0
- loop_interpolation/fold_function/__init__.py +39 -0
- loop_interpolation/fold_function/_base_fold_rotation_angle.py +219 -0
- loop_interpolation/fold_function/_fourier_series_fold_rotation_angle.py +131 -0
- loop_interpolation/fold_function/_lambda_fold_rotation_angle.py +53 -0
- loop_interpolation/loopsolver/__init__.py +2 -0
- loop_interpolation/loopsolver/admm_constant_norm.py +118 -0
- loop_interpolation/loopsolver/admm_method.py +25 -0
- loop_interpolation/loopsolver/admm_solver.py +463 -0
- loop_interpolation/loopsolver/version.py +1 -0
- loop_interpolation-0.0.1.dist-info/METADATA +34 -0
- loop_interpolation-0.0.1.dist-info/RECORD +39 -0
- loop_interpolation-0.0.1.dist-info/WHEEL +5 -0
- loop_interpolation-0.0.1.dist-info/licenses/LICENSE +21 -0
- loop_interpolation-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Abstract base class for fold rotation-angle profiles."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from abc import ABCMeta, abstractmethod
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import numpy.typing as npt
|
|
8
|
+
from loop_common.logging import get_logger
|
|
9
|
+
from scipy.optimize import curve_fit
|
|
10
|
+
|
|
11
|
+
from .._svariogram import SVariogram
|
|
12
|
+
|
|
13
|
+
logger = get_logger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class BaseFoldRotationAngleProfile(metaclass=ABCMeta):
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
rotation_angle: npt.NDArray[np.float64] | None = None,
|
|
20
|
+
fold_frame_coordinate: npt.NDArray[np.float64] | None = None,
|
|
21
|
+
):
|
|
22
|
+
"""Base class for callable fold-rotation-angle functions.
|
|
23
|
+
|
|
24
|
+
Parameters
|
|
25
|
+
----------
|
|
26
|
+
rotation_angle
|
|
27
|
+
Observed fold rotation angles in degrees.
|
|
28
|
+
fold_frame_coordinate
|
|
29
|
+
Fold-frame scalar-field values at the observation locations.
|
|
30
|
+
"""
|
|
31
|
+
self.rotation_angle = rotation_angle
|
|
32
|
+
self.fold_frame_coordinate = fold_frame_coordinate
|
|
33
|
+
self._evaluation_points: np.ndarray | None = None
|
|
34
|
+
self._observers: list = []
|
|
35
|
+
self._svariogram: SVariogram | None = None
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def svario(self) -> SVariogram:
|
|
39
|
+
if self.fold_frame_coordinate is None or self.rotation_angle is None:
|
|
40
|
+
raise ValueError("rotation_angle and fold_frame_coordinate must be set first")
|
|
41
|
+
if self._svariogram is None:
|
|
42
|
+
self._svariogram = SVariogram(self.fold_frame_coordinate, self.rotation_angle)
|
|
43
|
+
return self._svariogram
|
|
44
|
+
|
|
45
|
+
@svario.setter
|
|
46
|
+
def svario(self, value: SVariogram):
|
|
47
|
+
if not isinstance(value, SVariogram):
|
|
48
|
+
raise TypeError("svario must be a SVariogram instance")
|
|
49
|
+
self._svariogram = value
|
|
50
|
+
|
|
51
|
+
def add_observer(self, watcher) -> None:
|
|
52
|
+
self._observers.append(watcher)
|
|
53
|
+
|
|
54
|
+
def notify_observers(self) -> None:
|
|
55
|
+
for observer in self._observers:
|
|
56
|
+
observer.set_not_up_to_date(self)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def evaluation_points(self) -> np.ndarray:
|
|
60
|
+
if self._evaluation_points is not None:
|
|
61
|
+
return self._evaluation_points
|
|
62
|
+
return np.linspace(
|
|
63
|
+
np.min(self.fold_frame_coordinate), np.max(self.fold_frame_coordinate), 300
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
@evaluation_points.setter
|
|
67
|
+
def evaluation_points(self, value: np.ndarray) -> None:
|
|
68
|
+
self._evaluation_points = value
|
|
69
|
+
|
|
70
|
+
def estimate_wavelength(
|
|
71
|
+
self, svariogram_parameters: dict | None = None, wavelength_number: int = 1
|
|
72
|
+
) -> float | np.ndarray:
|
|
73
|
+
if svariogram_parameters is None:
|
|
74
|
+
svariogram_parameters = {}
|
|
75
|
+
wl = self.svario.find_wavelengths(**svariogram_parameters)
|
|
76
|
+
logger.info(f"Estimated fold rotation wavelength(s): {wl}")
|
|
77
|
+
return wl[0] if wavelength_number == 1 else wl
|
|
78
|
+
|
|
79
|
+
def calculate_misfit(
|
|
80
|
+
self,
|
|
81
|
+
rotation_angle: np.ndarray,
|
|
82
|
+
fold_frame_coordinate: np.ndarray,
|
|
83
|
+
) -> np.ndarray:
|
|
84
|
+
return np.tan(np.deg2rad(rotation_angle)) - np.tan(
|
|
85
|
+
np.deg2rad(self.__call__(fold_frame_coordinate))
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def fit(self, params: dict | None = None) -> bool:
|
|
89
|
+
if params is None:
|
|
90
|
+
params = {}
|
|
91
|
+
if len(self.params) > 0:
|
|
92
|
+
if self.rotation_angle is None or self.fold_frame_coordinate is None:
|
|
93
|
+
logger.error("rotation_angle and fold_frame_coordinate must be set before fitting")
|
|
94
|
+
return False
|
|
95
|
+
|
|
96
|
+
# Exclude NaNs and extreme angles (|alpha| >= 89°) whose tan blows up
|
|
97
|
+
# and causes the optimizer to diverge.
|
|
98
|
+
mask = (
|
|
99
|
+
~np.isnan(self.fold_frame_coordinate)
|
|
100
|
+
& ~np.isnan(self.rotation_angle)
|
|
101
|
+
& (np.abs(self.rotation_angle) < 89.0)
|
|
102
|
+
)
|
|
103
|
+
n_nan = np.sum(np.isnan(self.fold_frame_coordinate) | np.isnan(self.rotation_angle))
|
|
104
|
+
n_extreme = np.sum(np.abs(self.rotation_angle) >= 89.0) - np.sum(np.isnan(self.rotation_angle))
|
|
105
|
+
logger.info(
|
|
106
|
+
f"Fitting fold rotation angle; excluded {n_nan} NaN, {n_extreme} extreme (>=89 deg)"
|
|
107
|
+
)
|
|
108
|
+
x = self.fold_frame_coordinate[mask]
|
|
109
|
+
|
|
110
|
+
# Divide the fold-frame coordinate by its range so curve_fit and the
|
|
111
|
+
# variogram both operate at O(1) scale. Only division is used (no
|
|
112
|
+
# shift), so the wavelength transforms as w_orig = w_scaled * x_scale
|
|
113
|
+
# while c0/c1/c2 are identical in both spaces.
|
|
114
|
+
x_scale = float(np.max(x) - np.min(x)) if len(x) > 1 else 1.0
|
|
115
|
+
if x_scale < 1e-12:
|
|
116
|
+
x_scale = 1.0
|
|
117
|
+
x_scaled = x / x_scale
|
|
118
|
+
|
|
119
|
+
# Temporarily substitute scaled coordinates so the variogram and
|
|
120
|
+
# initial_guess operate in the normalised range.
|
|
121
|
+
_orig_ffc = self.fold_frame_coordinate
|
|
122
|
+
_orig_svario = self._svariogram
|
|
123
|
+
self.fold_frame_coordinate = self.fold_frame_coordinate / x_scale
|
|
124
|
+
self._svariogram = None
|
|
125
|
+
try:
|
|
126
|
+
guess_raw = params.get("guess", None)
|
|
127
|
+
if guess_raw is not None:
|
|
128
|
+
# User-supplied guess is in original space; scale w to match.
|
|
129
|
+
guess = np.array(guess_raw, dtype=float)
|
|
130
|
+
guess[-1] /= x_scale
|
|
131
|
+
else:
|
|
132
|
+
guess = np.array(
|
|
133
|
+
self.initial_guess(
|
|
134
|
+
wavelength=(
|
|
135
|
+
params["wavelength"] / x_scale
|
|
136
|
+
if params.get("wavelength") is not None
|
|
137
|
+
else None
|
|
138
|
+
),
|
|
139
|
+
reset=params.get("reset", False),
|
|
140
|
+
svariogram_parameters=params.get("svariogram_parameters", {}),
|
|
141
|
+
calculate_wavelength=params.get("calculate_wavelength", True),
|
|
142
|
+
),
|
|
143
|
+
dtype=float,
|
|
144
|
+
)
|
|
145
|
+
finally:
|
|
146
|
+
self.fold_frame_coordinate = _orig_ffc
|
|
147
|
+
self._svariogram = _orig_svario
|
|
148
|
+
|
|
149
|
+
# Bounds in scaled space: w in [5%, 400%] of the scaled data range (=1.0).
|
|
150
|
+
lo_w, hi_w = 0.05, 4.0
|
|
151
|
+
guess[-1] = float(np.clip(guess[-1], lo_w, hi_w))
|
|
152
|
+
bounds = (
|
|
153
|
+
[-np.inf] * (len(guess) - 1) + [lo_w],
|
|
154
|
+
[np.inf] * (len(guess) - 1) + [hi_w],
|
|
155
|
+
)
|
|
156
|
+
logger.info(
|
|
157
|
+
f"curve_fit w bounds (scaled): [{lo_w}, {hi_w}], "
|
|
158
|
+
f"initial w_scaled={guess[-1]:.4g} (~{guess[-1]*x_scale:.4g} orig)"
|
|
159
|
+
)
|
|
160
|
+
try:
|
|
161
|
+
res = curve_fit(
|
|
162
|
+
self._function,
|
|
163
|
+
x_scaled,
|
|
164
|
+
np.tan(np.deg2rad(self.rotation_angle[mask])),
|
|
165
|
+
p0=guess,
|
|
166
|
+
bounds=bounds,
|
|
167
|
+
maxfev=5000,
|
|
168
|
+
full_output=True,
|
|
169
|
+
)
|
|
170
|
+
guess = res[0]
|
|
171
|
+
except (TypeError, ValueError, RuntimeError) as e:
|
|
172
|
+
logger.error(f"curve_fit failed ({e}); using initial guess as fallback")
|
|
173
|
+
|
|
174
|
+
# Scale wavelength back to original coordinate space.
|
|
175
|
+
guess[-1] *= x_scale
|
|
176
|
+
|
|
177
|
+
try:
|
|
178
|
+
self.update_params(guess)
|
|
179
|
+
except (TypeError, ValueError, RuntimeError):
|
|
180
|
+
logger.error("update_params failed after fit")
|
|
181
|
+
return False
|
|
182
|
+
return True
|
|
183
|
+
return True
|
|
184
|
+
|
|
185
|
+
@abstractmethod
|
|
186
|
+
def update_params(self, params: list | npt.NDArray[np.float64]) -> None:
|
|
187
|
+
pass
|
|
188
|
+
|
|
189
|
+
@abstractmethod
|
|
190
|
+
def initial_guess(
|
|
191
|
+
self,
|
|
192
|
+
wavelength: float | None = None,
|
|
193
|
+
calculate_wavelength: bool = True,
|
|
194
|
+
svariogram_parameters: dict | None = None,
|
|
195
|
+
reset: bool = False,
|
|
196
|
+
) -> np.ndarray:
|
|
197
|
+
pass
|
|
198
|
+
|
|
199
|
+
@staticmethod
|
|
200
|
+
@abstractmethod
|
|
201
|
+
def _function(s, *args, **kwargs):
|
|
202
|
+
pass
|
|
203
|
+
|
|
204
|
+
@property
|
|
205
|
+
@abstractmethod
|
|
206
|
+
def params(self) -> dict:
|
|
207
|
+
pass
|
|
208
|
+
|
|
209
|
+
def plot(self, ax=None, show_data: bool = True, **kwargs):
|
|
210
|
+
if ax is None:
|
|
211
|
+
import matplotlib.pyplot as plt
|
|
212
|
+
_fig, ax = plt.subplots()
|
|
213
|
+
if show_data and self.fold_frame_coordinate is not None:
|
|
214
|
+
ax.scatter(self.fold_frame_coordinate, self.rotation_angle, c="r")
|
|
215
|
+
ax.plot(self.evaluation_points, self(self.evaluation_points), **kwargs)
|
|
216
|
+
return ax
|
|
217
|
+
|
|
218
|
+
def __call__(self, s: np.ndarray) -> np.ndarray:
|
|
219
|
+
return np.rad2deg(np.arctan(self._function(s, **self.params)))
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Fourier-series fold rotation-angle profile (Laurent et al., 2016)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import numpy.typing as npt
|
|
6
|
+
from loop_common.logging import get_logger
|
|
7
|
+
|
|
8
|
+
from ._base_fold_rotation_angle import BaseFoldRotationAngleProfile
|
|
9
|
+
|
|
10
|
+
logger = get_logger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FourierSeriesFoldRotationAngleProfile(BaseFoldRotationAngleProfile):
|
|
14
|
+
"""Fold limb-rotation angle as a truncated Fourier series:
|
|
15
|
+
|
|
16
|
+
``tan(α(s)) = c0 + c1·cos(2π/w·s) + c2·sin(2π/w·s)``
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
rotation_angle: npt.NDArray[np.float64] | None = None,
|
|
22
|
+
fold_frame_coordinate: npt.NDArray[np.float64] | None = None,
|
|
23
|
+
c0: float = 0.0,
|
|
24
|
+
c1: float = 0.0,
|
|
25
|
+
c2: float = 0.0,
|
|
26
|
+
w: float = 1.0,
|
|
27
|
+
):
|
|
28
|
+
super().__init__(rotation_angle, fold_frame_coordinate)
|
|
29
|
+
self._c0 = c0
|
|
30
|
+
self._c1 = c1
|
|
31
|
+
self._c2 = c2
|
|
32
|
+
self._w = w
|
|
33
|
+
|
|
34
|
+
# --- properties with observer notification ---
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def c0(self) -> float:
|
|
38
|
+
return self._c0
|
|
39
|
+
|
|
40
|
+
@c0.setter
|
|
41
|
+
def c0(self, value: float) -> None:
|
|
42
|
+
self.notify_observers()
|
|
43
|
+
self._c0 = value
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def c1(self) -> float:
|
|
47
|
+
return self._c1
|
|
48
|
+
|
|
49
|
+
@c1.setter
|
|
50
|
+
def c1(self, value: float) -> None:
|
|
51
|
+
self.notify_observers()
|
|
52
|
+
self._c1 = value
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def c2(self) -> float:
|
|
56
|
+
return self._c2
|
|
57
|
+
|
|
58
|
+
@c2.setter
|
|
59
|
+
def c2(self, value: float) -> None:
|
|
60
|
+
self.notify_observers()
|
|
61
|
+
self._c2 = value
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def w(self) -> float:
|
|
65
|
+
return self._w
|
|
66
|
+
|
|
67
|
+
@w.setter
|
|
68
|
+
def w(self, value: float) -> None:
|
|
69
|
+
if value <= 0:
|
|
70
|
+
raise ValueError("wavelength must be > 0")
|
|
71
|
+
self.notify_observers()
|
|
72
|
+
self._w = value
|
|
73
|
+
|
|
74
|
+
# --- profile function ---
|
|
75
|
+
|
|
76
|
+
@staticmethod
|
|
77
|
+
def _function(x: np.ndarray, c0: float, c1: float, c2: float, w: float) -> np.ndarray:
|
|
78
|
+
return c0 + c1 * np.cos(2 * np.pi / w * x) + c2 * np.sin(2 * np.pi / w * x)
|
|
79
|
+
|
|
80
|
+
# --- params ---
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def params(self) -> dict:
|
|
84
|
+
return {"c0": self.c0, "c1": self.c1, "c2": self.c2, "w": self.w}
|
|
85
|
+
|
|
86
|
+
@params.setter
|
|
87
|
+
def params(self, params: dict) -> None:
|
|
88
|
+
if "w" in params and params["w"] <= 0:
|
|
89
|
+
raise ValueError("wavelength must be > 0")
|
|
90
|
+
self._c0 = params["c0"]
|
|
91
|
+
self._c1 = params["c1"]
|
|
92
|
+
self._c2 = params["c2"]
|
|
93
|
+
self._w = params["w"]
|
|
94
|
+
self.notify_observers()
|
|
95
|
+
|
|
96
|
+
def update_params(self, params: list[float] | npt.NDArray[np.float64]) -> None:
|
|
97
|
+
if len(params) != 4:
|
|
98
|
+
raise ValueError("params must have 4 elements: [c0, c1, c2, w]")
|
|
99
|
+
self._c0 = params[0]
|
|
100
|
+
self._c1 = params[1]
|
|
101
|
+
self._c2 = params[2]
|
|
102
|
+
self._w = params[3]
|
|
103
|
+
self.notify_observers()
|
|
104
|
+
|
|
105
|
+
def initial_guess(
|
|
106
|
+
self,
|
|
107
|
+
wavelength: float | None = None,
|
|
108
|
+
calculate_wavelength: bool = True,
|
|
109
|
+
svariogram_parameters: dict | None = None,
|
|
110
|
+
reset: bool = False,
|
|
111
|
+
) -> np.ndarray:
|
|
112
|
+
if svariogram_parameters is None:
|
|
113
|
+
svariogram_parameters = {}
|
|
114
|
+
if reset:
|
|
115
|
+
# Clip to ±89° before tan to avoid singularities at ±90°.
|
|
116
|
+
ang = np.clip(self.rotation_angle, -89.0, 89.0)
|
|
117
|
+
tan_vals = np.tan(np.deg2rad(ang))
|
|
118
|
+
self.c0 = float(np.nanmean(tan_vals))
|
|
119
|
+
self.c1 = 0.0
|
|
120
|
+
self.c2 = float(np.nanmax(tan_vals))
|
|
121
|
+
self.w = 1.0
|
|
122
|
+
if calculate_wavelength:
|
|
123
|
+
self.w = self.estimate_wavelength(svariogram_parameters=svariogram_parameters)
|
|
124
|
+
if wavelength is not None:
|
|
125
|
+
self.w = wavelength
|
|
126
|
+
return np.array([self.c0, self.c1, self.c2, self.w])
|
|
127
|
+
|
|
128
|
+
def calculate_misfit(
|
|
129
|
+
self, s: np.ndarray, rotation_angle: np.ndarray
|
|
130
|
+
) -> np.ndarray:
|
|
131
|
+
return np.tan(np.deg2rad(rotation_angle)) - np.tan(np.deg2rad(self.__call__(s)))
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Lambda (arbitrary callable) fold rotation-angle profile."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Callable
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import numpy.typing as npt
|
|
8
|
+
|
|
9
|
+
from ._base_fold_rotation_angle import BaseFoldRotationAngleProfile
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LambdaFoldRotationAngleProfile(BaseFoldRotationAngleProfile):
|
|
13
|
+
"""Fold rotation-angle profile backed by an arbitrary callable.
|
|
14
|
+
|
|
15
|
+
``__call__(s)`` simply delegates to the supplied function and returns
|
|
16
|
+
degrees (the function is expected to return degrees directly).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
fn: Callable[[np.ndarray], np.ndarray],
|
|
22
|
+
rotation_angle: npt.NDArray[np.float64] | None = None,
|
|
23
|
+
fold_frame_coordinate: npt.NDArray[np.float64] | None = None,
|
|
24
|
+
):
|
|
25
|
+
super().__init__(rotation_angle, fold_frame_coordinate)
|
|
26
|
+
self._fn = fn
|
|
27
|
+
|
|
28
|
+
# Override __call__ — the base computes arctan(_function(...)), but for a
|
|
29
|
+
# lambda profile the function already returns angles in degrees.
|
|
30
|
+
def __call__(self, s: np.ndarray) -> np.ndarray:
|
|
31
|
+
return self._fn(s)
|
|
32
|
+
|
|
33
|
+
@staticmethod
|
|
34
|
+
def _function(s, *args, **kwargs):
|
|
35
|
+
raise NotImplementedError("LambdaFoldRotationAngleProfile uses a supplied callable")
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def params(self) -> dict:
|
|
39
|
+
return {}
|
|
40
|
+
|
|
41
|
+
def update_params(self, params) -> None:
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
def initial_guess(
|
|
45
|
+
self,
|
|
46
|
+
wavelength: float | None = None,
|
|
47
|
+
calculate_wavelength: bool = True,
|
|
48
|
+
svariogram_parameters: dict | None = None,
|
|
49
|
+
reset: bool = False,
|
|
50
|
+
) -> np.ndarray:
|
|
51
|
+
if svariogram_parameters is None:
|
|
52
|
+
svariogram_parameters = {}
|
|
53
|
+
return np.array([])
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Callable
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from scipy.sparse import csr_matrix, vstack
|
|
7
|
+
from scipy.sparse.linalg import lsmr
|
|
8
|
+
|
|
9
|
+
from .admm_method import ADMM
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Config:
|
|
14
|
+
verbose: bool = False
|
|
15
|
+
progress: bool = True
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
progressbar = lambda x: x
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
tqdm_module = importlib.import_module("tqdm")
|
|
22
|
+
|
|
23
|
+
if Config.progress:
|
|
24
|
+
progressbar = tqdm_module.tqdm
|
|
25
|
+
else:
|
|
26
|
+
progressbar = lambda x: x
|
|
27
|
+
except ModuleNotFoundError:
|
|
28
|
+
Config.progress = False
|
|
29
|
+
progressbar = lambda x: x
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def admm_solve_constant_norm(
|
|
33
|
+
A: csr_matrix,
|
|
34
|
+
b: np.ndarray,
|
|
35
|
+
Q: csr_matrix,
|
|
36
|
+
bounds: np.ndarray,
|
|
37
|
+
t: np.ndarray,
|
|
38
|
+
update_r: Callable,
|
|
39
|
+
x0: np.ndarray,
|
|
40
|
+
admm_weight: float = 0.1,
|
|
41
|
+
nmajor=200,
|
|
42
|
+
linsys_solver_kwargs=None,
|
|
43
|
+
):
|
|
44
|
+
if linsys_solver_kwargs is None:
|
|
45
|
+
linsys_solver_kwargs = {"maxiter": 100}
|
|
46
|
+
if A.shape[1] != x0.shape[0]:
|
|
47
|
+
raise ValueError("Number of columns in interpolation matrix does not match x0")
|
|
48
|
+
if A.shape[1] != Q.shape[1]:
|
|
49
|
+
raise ValueError(
|
|
50
|
+
"Number of columns in interpolation matrix and inequality matrix are different "
|
|
51
|
+
)
|
|
52
|
+
if Q.shape[0] != bounds.shape[0]:
|
|
53
|
+
raise ValueError("Number of rows in inequality matrix and bounds are different")
|
|
54
|
+
if bounds.shape[1] == 2:
|
|
55
|
+
bounds = np.hstack([bounds, np.ones((bounds.shape[0], 1))])
|
|
56
|
+
if bounds.shape[1] != 3:
|
|
57
|
+
raise ValueError("Bounds must have two columns")
|
|
58
|
+
if A.shape[0] != b.shape[0]:
|
|
59
|
+
raise ValueError("Number of rows in interpolation matrix and b are different")
|
|
60
|
+
# if R.shape[0] != t.shape[0]:
|
|
61
|
+
# raise ValueError("Number of rows in R matrix and t are different")
|
|
62
|
+
# if R.shape[1] != x0.shape[0]:
|
|
63
|
+
# raise ValueError("Number of columns in R matrix does not match x0")
|
|
64
|
+
n_ie = bounds.shape[0]
|
|
65
|
+
qx_val = np.zeros((Q.shape[0], 1))
|
|
66
|
+
model = np.zeros(A.shape[1])
|
|
67
|
+
model[:] = x0[:]
|
|
68
|
+
# initialise the admm method, sets up the u and v matrices as 0s
|
|
69
|
+
admm_method = ADMM(n_ie)
|
|
70
|
+
b0 = np.zeros(b.shape[0] + t.shape[0])
|
|
71
|
+
b0[: b.shape[0]] = b[:]
|
|
72
|
+
b0[b.shape[0] :] = t[:]
|
|
73
|
+
# the b vector used for the lsqr soln is the size of A + Q
|
|
74
|
+
b = np.zeros(A.shape[0] + t.shape[0] + Q.shape[0])
|
|
75
|
+
A_size = A.shape[0] + t.shape[0]
|
|
76
|
+
xmin = bounds[:, [0]]
|
|
77
|
+
xmax = bounds[:, [1]]
|
|
78
|
+
x0_ADMM = np.zeros(Q.shape[0])
|
|
79
|
+
# scale the Q matrix by the admm f
|
|
80
|
+
Q *= admm_weight
|
|
81
|
+
|
|
82
|
+
# matrix = vstack([A, Q])
|
|
83
|
+
for _i in progressbar(range(nmajor)):
|
|
84
|
+
# current model value
|
|
85
|
+
R = update_r(model, _i)
|
|
86
|
+
matrix = vstack([A, R, Q])
|
|
87
|
+
Mx = matrix @ model # np.dot(A, model)
|
|
88
|
+
|
|
89
|
+
qx_val[:, 0] = Mx[A_size:,] / admm_weight
|
|
90
|
+
x0_ADMM = admm_method.admm_method_iterate_admm_array(xmin, xmax, qx_val)
|
|
91
|
+
# print(x0_ADMM, qx_val.shape)
|
|
92
|
+
# raise Exception
|
|
93
|
+
b[:A_size] = b0[:A_size] - Mx[:A_size]
|
|
94
|
+
b[A_size:] = -admm_weight * (qx_val[:, 0] - x0_ADMM)
|
|
95
|
+
cost_data1 = np.linalg.norm(b[:A_size])
|
|
96
|
+
cost_data2 = np.linalg.norm(b0[A_size:])
|
|
97
|
+
model_norm = np.linalg.norm(model)
|
|
98
|
+
if Config.verbose:
|
|
99
|
+
cost_data = -1.0
|
|
100
|
+
cost_data_model = 0.0
|
|
101
|
+
if cost_data2 > 0:
|
|
102
|
+
cost_data = cost_data1 / cost_data2
|
|
103
|
+
if model_norm > 0:
|
|
104
|
+
cost_data_model = cost_data1 / model_norm
|
|
105
|
+
cost_admm1 = np.linalg.norm(qx_val - admm_method.z)
|
|
106
|
+
cost_admm2 = np.linalg.norm(admm_method.z)
|
|
107
|
+
cost_admm = -1.0
|
|
108
|
+
if cost_admm2 > 0:
|
|
109
|
+
cost_admm = cost_admm1 / cost_admm2
|
|
110
|
+
print("----------------------------------------")
|
|
111
|
+
print(f"it = {_i}")
|
|
112
|
+
print("cost_data = ", cost_data)
|
|
113
|
+
print("cost_data_model = ", cost_data_model)
|
|
114
|
+
print("cost_admm = ", cost_admm)
|
|
115
|
+
print("----------------------------------------")
|
|
116
|
+
x = lsmr(matrix, b, **linsys_solver_kwargs)
|
|
117
|
+
model += x[0]
|
|
118
|
+
return model
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ADMM:
|
|
5
|
+
def __init__(self, nelements: int):
|
|
6
|
+
if nelements < 1:
|
|
7
|
+
raise ValueError("nelements must be greater than 0")
|
|
8
|
+
self.z = np.zeros(nelements)
|
|
9
|
+
self.u = np.zeros(nelements)
|
|
10
|
+
self.nelements = nelements
|
|
11
|
+
|
|
12
|
+
def admm_method_iterate_admm_array(self, xmin, xmax, x):
|
|
13
|
+
|
|
14
|
+
arg = np.nan
|
|
15
|
+
inside = False
|
|
16
|
+
arg = x[:, 0] + self.u
|
|
17
|
+
inside = np.logical_and(arg >= xmin[:, 0], arg <= xmax[:, 0])
|
|
18
|
+
self.z[inside] = arg[inside]
|
|
19
|
+
below = np.logical_and(arg < xmin[:, 0], ~inside)
|
|
20
|
+
above = np.logical_and(arg > xmax[:, 0], ~inside)
|
|
21
|
+
self.z[below] = xmin[below, 0]
|
|
22
|
+
self.z[above] = xmax[above, 0]
|
|
23
|
+
# calculate the
|
|
24
|
+
self.u = self.u + x[:, 0] - self.z
|
|
25
|
+
return self.z - self.u
|