htfa 0.1.0__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.
- htfa/__init__.py +39 -0
- htfa/_download.py +34 -0
- htfa/_engines.py +562 -0
- htfa/_kernels.py +1532 -0
- htfa/_lazy.py +437 -0
- htfa/_matching.py +71 -0
- htfa/_spatial.py +145 -0
- htfa/_validation.py +13 -0
- htfa/brainnet.py +2257 -0
- htfa/connectivity.py +137 -0
- htfa/datasets.py +457 -0
- htfa/fit.py +115 -0
- htfa/groups.py +677 -0
- htfa/htfa.py +1158 -0
- htfa/io.py +444 -0
- htfa/results.py +1265 -0
- htfa/stats.py +149 -0
- htfa/synthetic.py +453 -0
- htfa/tfa.py +1149 -0
- htfa/timecourse.py +254 -0
- htfa-0.1.0.dist-info/METADATA +234 -0
- htfa-0.1.0.dist-info/RECORD +25 -0
- htfa-0.1.0.dist-info/WHEEL +5 -0
- htfa-0.1.0.dist-info/licenses/LICENSE +20 -0
- htfa-0.1.0.dist-info/top_level.txt +1 -0
htfa/_kernels.py
ADDED
|
@@ -0,0 +1,1532 @@
|
|
|
1
|
+
"""Numerical kernels for TFA: factors, weights, residual and analytic Jacobian.
|
|
2
|
+
|
|
3
|
+
Conventions: data ``X`` is (V, T), coordinates ``R`` are (V, D) with D in {2, 3},
|
|
4
|
+
centers are (K, D) and widths ``w = 2 sigma**2`` are (K,). The parameter vector of
|
|
5
|
+
the center/width solve is ``x = [centers.ravel(), widths]`` (length K * (D + 1)).
|
|
6
|
+
All arrays are float64.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from functools import cached_property
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import scipy.linalg
|
|
15
|
+
from numpy.typing import ArrayLike, NDArray
|
|
16
|
+
from scipy.optimize import least_squares
|
|
17
|
+
from scipy.sparse.linalg import LinearOperator
|
|
18
|
+
from sklearn.cluster import KMeans
|
|
19
|
+
from threadpoolctl import threadpool_limits
|
|
20
|
+
|
|
21
|
+
from htfa._engines import (
|
|
22
|
+
EPS,
|
|
23
|
+
Engine,
|
|
24
|
+
NumpyEngine,
|
|
25
|
+
loss_terms,
|
|
26
|
+
single_threaded_accelerate,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
Array = NDArray[np.float64]
|
|
30
|
+
|
|
31
|
+
# nlss_method values: the structured bounded Levenberg-Marquardt solver (default),
|
|
32
|
+
# the same solver on the variable-projection objective (linear loss only; see
|
|
33
|
+
# `ProjectedProblem`) and the scipy least_squares methods kept for cross-checking.
|
|
34
|
+
NLSS_METHODS = ("bounded-lm", "varpro", "trf", "dogbox")
|
|
35
|
+
# Modes of the structured solver (`bounded_lm`). 'exact' falls back to the
|
|
36
|
+
# Gauss-Newton matrix wherever the Hessian is not positive definite on the free
|
|
37
|
+
# variables, and assembles the curvature in float64. 'fast' keeps the Hessian
|
|
38
|
+
# there and raises the damping instead, and forms the largest curvature
|
|
39
|
+
# products of the linear loss in float32 (`curvature_operand`).
|
|
40
|
+
SOLVER_MODES = ("fast", "exact")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def curvature_operand(a: Array, mode: str) -> NDArray[np.floating]:
|
|
44
|
+
"""``a`` as an operand of the curvature (Gauss-Newton matrix and Hessian)
|
|
45
|
+
products: a float32 copy in mode ``'fast'``, ``a`` itself otherwise.
|
|
46
|
+
|
|
47
|
+
Only the curvature is affected; costs and gradients stay in float64, so the
|
|
48
|
+
solver minimizes the same objective. Float32 curvature products trade
|
|
49
|
+
numerical precision for computation cost; the resulting step can differ
|
|
50
|
+
even though the cost and gradient calculations use float64.
|
|
51
|
+
"""
|
|
52
|
+
return a.astype(np.float32) if mode == "fast" else a
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# scipy.optimize.least_squares' default tolerances, used by the structured solver
|
|
56
|
+
# with the same meaning (see `bounded_lm`).
|
|
57
|
+
FTOL = XTOL = GTOL = 1e-8
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def ftol_for(eps: float) -> float:
|
|
61
|
+
"""``ftol`` for an engine whose arithmetic has machine epsilon ``eps``.
|
|
62
|
+
|
|
63
|
+
``FTOL`` (1e-8) is below float32 resolution: on MPS the relative noise of a
|
|
64
|
+
cost evaluation is of order 1e-8 (float32 sums over samples, float64 over
|
|
65
|
+
voxels), so near convergence steps would be accepted or rejected on noise.
|
|
66
|
+
The tolerance is raised to ``eps`` (1.2e-7 in float32; unchanged in float64).
|
|
67
|
+
"""
|
|
68
|
+
return max(FTOL, eps)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# Relative eigenvalue cutoff of the weights' gram matrix in `ProjectedProblem`
|
|
72
|
+
# (the square root of float64 epsilon: a condition number above 6.7e7).
|
|
73
|
+
GRAM_RCOND = float(np.sqrt(np.finfo(np.float64).eps))
|
|
74
|
+
# Gram eigenvalues at or below this are dropped whatever the largest one is:
|
|
75
|
+
# their reciprocals (above 4.5e291) times F^T X would overflow. Only a gram
|
|
76
|
+
# whose factors are all below about 1e-146 at every voxel has none above it.
|
|
77
|
+
GRAM_FLOOR = float(np.finfo(np.float64).tiny / np.finfo(np.float64).eps)
|
|
78
|
+
|
|
79
|
+
# `ProjectedProblem` evaluates ||X - F W||**2 + beta ||W||**2 as ||X||**2 -
|
|
80
|
+
# <F^T X, W> (exact at the ridge solution) when, at the first point it evaluates,
|
|
81
|
+
# that objective is at least this fraction of ||X||**2. The identity loses
|
|
82
|
+
# about log10(||X||**2 / objective) digits to cancellation; measured relative
|
|
83
|
+
# difference from the residual form: <= 8e-16 on development_fmri (fraction
|
|
84
|
+
# 0.95), 1.5e-13 on unstandardized synthetic data with noise 0.003 or none
|
|
85
|
+
# (fraction 3e-5 to 5e-4). Below the cutoff the problem keeps the residual form.
|
|
86
|
+
IDENTITY_MIN_FRACTION = 1e-3
|
|
87
|
+
|
|
88
|
+
# Initial damping relative to the largest diagonal entry of the scaled Hessian
|
|
89
|
+
# (Madsen, Nielsen & Tingleff 2004, sec. 3.2).
|
|
90
|
+
LM_TAU = 1e-3
|
|
91
|
+
# In mode 'fast', `bounded_lm` multiplies the damping by FAILED_FACTOR_GROWTH**k
|
|
92
|
+
# at the k-th failed Cholesky factorization within one step (counted from the
|
|
93
|
+
# step's first trial, across its rejected trials: x2, x4, x8, ...; after n
|
|
94
|
+
# failures 2**(n (n + 1) / 2) times the start) and leaves the step-rejection
|
|
95
|
+
# factor nu alone. Mode 'exact' keeps the earlier rule, lam *= nu and nu *= 2
|
|
96
|
+
# at every failure (so that nu stays raised for the step's rejections), and
|
|
97
|
+
# its results. Doubling only (at most twice the damping that works) let the
|
|
98
|
+
# fast mode's damped Newton step reach another basin on a well-conditioned
|
|
99
|
+
# synthetic problem (tests/test_fast_mode.py, case 52, two-stage loss: +2.9e-3
|
|
100
|
+
# objective, centers 1.45 lengths from the exact fit), which the growing
|
|
101
|
+
# factor keeps short.
|
|
102
|
+
FAILED_FACTOR_GROWTH = 2.0
|
|
103
|
+
|
|
104
|
+
# Relative tolerance (atol = btol) of the LSMR trust-region subproblem solve. scipy's
|
|
105
|
+
# default (1e-6) stops the outer solve ~1e-6 away from the minimizer: compressed vs.
|
|
106
|
+
# uncompressed linear-loss solves then differed by 1.5e-6 in x. Measured with
|
|
107
|
+
# 1e-8: that difference falls to 2e-8, and on V=3000, T=200, K=20 the final cost
|
|
108
|
+
# matches 1e-10 to 4e-11 relative, at ~1.7x the time of 1e-6 (0.82 s vs 0.46 s).
|
|
109
|
+
LSMR_TOL = 1e-8
|
|
110
|
+
|
|
111
|
+
# `axis_grid` describes the coordinates by axis when the distinct values, summed
|
|
112
|
+
# over the axes, number at most this fraction of the voxels. Each factor is then
|
|
113
|
+
# evaluated per axis on the distinct values and gathered: development_fmri has
|
|
114
|
+
# 37 + 45 + 32 distinct values for V = 25079 voxels, and factors() took 2.0 ms
|
|
115
|
+
# instead of 16 ms (K=100). With arbitrary coordinates (about V distinct values
|
|
116
|
+
# per axis) the per-axis tables would cost D times the direct evaluation.
|
|
117
|
+
GRID_MAX_FRACTION = 0.5
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass(frozen=True)
|
|
121
|
+
class AxisGrid:
|
|
122
|
+
"""Distinct coordinates ``values[j]`` along each axis ``j`` and the position
|
|
123
|
+
``index[j]`` (V,) of every voxel's coordinate among them."""
|
|
124
|
+
|
|
125
|
+
values: tuple[Array, ...]
|
|
126
|
+
index: tuple[NDArray[np.intp], ...]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def axis_grid(R: Array) -> AxisGrid | None:
|
|
130
|
+
"""`AxisGrid` of the coordinates ``R`` (V, D), or None when they have more
|
|
131
|
+
than ``GRID_MAX_FRACTION * V`` distinct values summed over the axes."""
|
|
132
|
+
columns = [np.unique(R[:, j], return_inverse=True) for j in range(R.shape[1])]
|
|
133
|
+
if sum(values.size for values, _ in columns) > GRID_MAX_FRACTION * R.shape[0]:
|
|
134
|
+
return None
|
|
135
|
+
return AxisGrid(
|
|
136
|
+
tuple(values for values, _ in columns),
|
|
137
|
+
tuple(index.ravel() for _, index in columns),
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def sq_distances(R: Array, centers: Array, grid: AxisGrid | None = None) -> Array:
|
|
142
|
+
"""Squared distances (V, K) between voxels ``R`` (V, D) and ``centers`` (K, D).
|
|
143
|
+
|
|
144
|
+
Summed per dimension rather than via ``|r|^2 - 2 r.c + |c|^2`` so that large
|
|
145
|
+
coordinates do not cancel catastrophically. With ``grid`` (`axis_grid` of
|
|
146
|
+
``R``) the per-axis squares are computed on the distinct coordinates and
|
|
147
|
+
gathered; the sums are the same, bit for bit.
|
|
148
|
+
"""
|
|
149
|
+
if grid is not None:
|
|
150
|
+
d = np.zeros((R.shape[0], centers.shape[0]))
|
|
151
|
+
for j, (values, index) in enumerate(zip(grid.values, grid.index, strict=True)):
|
|
152
|
+
diff = values[:, None] - centers[None, :, j]
|
|
153
|
+
d += (diff * diff)[index]
|
|
154
|
+
return d
|
|
155
|
+
d = np.zeros((R.shape[0], centers.shape[0]))
|
|
156
|
+
for j in range(R.shape[1]):
|
|
157
|
+
diff = R[:, j, None] - centers[None, :, j]
|
|
158
|
+
d += diff * diff
|
|
159
|
+
return d
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
KERNELS = ("rbf", "laplace", "mexican_hat")
|
|
163
|
+
# 'laplace' is exp(eps - sqrt(d / w + eps**2)) with eps = LAPLACE_EPS: 1 at the
|
|
164
|
+
# center with slope 0, and exp(eps) exp(-r / sqrt(w)) once r >> eps sqrt(w).
|
|
165
|
+
# The rounding scales with the width, so the profile is a function of d / w as
|
|
166
|
+
# the RBF's is, and a fit stores no extra constant.
|
|
167
|
+
LAPLACE_EPS = 0.1
|
|
168
|
+
# Mixing weights pi = softmax(0, a_2, ..., a_M) of a mixture factor, with the
|
|
169
|
+
# Start of a mixture: every component at its factor's start center, component
|
|
170
|
+
# m (from 0) with MIXTURE_WIDTH_START**m times the start width, equal weights.
|
|
171
|
+
# Equal widths would be a symmetric start that the solver never leaves.
|
|
172
|
+
MIXTURE_WIDTH_START = 0.25
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@dataclass(frozen=True)
|
|
176
|
+
class Kernel:
|
|
177
|
+
"""Shape of the factors.
|
|
178
|
+
|
|
179
|
+
A factor is ``F_k(r) = sum_m pi_km phi(||r - c_km||**2 / w_km)`` over
|
|
180
|
+
``n_components`` components ``m``, each with its own center ``c_km`` and
|
|
181
|
+
width ``w_km``, and mixing weights ``pi_k = softmax(0, a_k2, ..., a_kM)``
|
|
182
|
+
(one factor: ``pi = 1``, no logits). The profile ``phi(z)``:
|
|
183
|
+
|
|
184
|
+
- ``'rbf'``: ``exp(-z)``.
|
|
185
|
+
- ``'laplace'``: ``exp(eps - sqrt(z + eps**2))``, ``eps =`` `LAPLACE_EPS`.
|
|
186
|
+
- ``'mexican_hat'``: ``(1 - 2 z / D) exp(-z)`` in D dimensions, the
|
|
187
|
+
negative Laplacian of ``exp(-z)`` scaled to 1 at the center (the Ricker
|
|
188
|
+
wavelet): its integral is 0, positive within ``r = sqrt(D w / 2)`` and
|
|
189
|
+
negative outside, with minimum ``-exp(-2)`` (D = 2) or ``-(2 / 3)
|
|
190
|
+
exp(-5 / 2)`` (D = 3) at ``z = 1 + D / 2``. The balanced surround
|
|
191
|
+
matters for fitting: with ``(1 - z) exp(-z)`` in 3D (a surround
|
|
192
|
+
heavier than the center) the default starts reached the optimum of
|
|
193
|
+
3 of 6 synthetic 18**3 datasets, with the balanced profile 5 of 6.
|
|
194
|
+
|
|
195
|
+
``phi(0) = 1`` and the weights sum to 1, so a factor's amplitude belongs to
|
|
196
|
+
its time-series weights alone; the logit of the first component is fixed at
|
|
197
|
+
0 so that the softmax has no free common shift.
|
|
198
|
+
|
|
199
|
+
The parameter vector of the nonlinear solve is ``x = [component centers
|
|
200
|
+
(K M, D) raveled, component widths (K M,), logits (K, M - 1) raveled]``,
|
|
201
|
+
components in factor-major order (``k * M + m``); with one component it is
|
|
202
|
+
``[centers.ravel(), widths]``.
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
name: str = "rbf"
|
|
206
|
+
n_components: int = 1
|
|
207
|
+
|
|
208
|
+
def __post_init__(self) -> None:
|
|
209
|
+
if self.name not in KERNELS:
|
|
210
|
+
raise ValueError(f"kernel must be one of {KERNELS}, got {self.name!r}")
|
|
211
|
+
n = self.n_components
|
|
212
|
+
if not isinstance(n, (int, np.integer)) or isinstance(n, bool) or n < 1:
|
|
213
|
+
raise ValueError(f"n_components must be an integer >= 1, got {n!r}")
|
|
214
|
+
|
|
215
|
+
@property
|
|
216
|
+
def plain_rbf(self) -> bool:
|
|
217
|
+
"""Whether each factor is a single RBF component."""
|
|
218
|
+
return self.name == "rbf" and self.n_components == 1
|
|
219
|
+
|
|
220
|
+
def n_params(self, K: int, D: int) -> int:
|
|
221
|
+
"""Length of ``x`` for K factors in D dimensions."""
|
|
222
|
+
M = self.n_components
|
|
223
|
+
return K * M * (D + 1) + K * (M - 1)
|
|
224
|
+
|
|
225
|
+
def split(self, x: ArrayLike, K: int, D: int) -> tuple[Array, Array, Array]:
|
|
226
|
+
"""Component centers (K M, D), widths (K M,) and logits (K, M - 1) of
|
|
227
|
+
``x``."""
|
|
228
|
+
x = np.asarray(x, dtype=np.float64).ravel()
|
|
229
|
+
n = K * self.n_components
|
|
230
|
+
return (
|
|
231
|
+
x[: n * D].reshape(n, D),
|
|
232
|
+
x[n * D : n * (D + 1)],
|
|
233
|
+
x[n * (D + 1) :].reshape(K, self.n_components - 1),
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
@staticmethod
|
|
237
|
+
def join(centers: ArrayLike, widths: ArrayLike, logits: ArrayLike) -> Array:
|
|
238
|
+
"""``x`` of component centers, widths and logits (inverse of `split`)."""
|
|
239
|
+
return np.concatenate(
|
|
240
|
+
[np.ravel(centers), np.ravel(widths), np.ravel(logits)]
|
|
241
|
+
).astype(np.float64)
|
|
242
|
+
|
|
243
|
+
@staticmethod
|
|
244
|
+
def mixing(logits: Array) -> Array:
|
|
245
|
+
"""Mixing weights (K, M) ``softmax(0, logits)`` of logits (K, M - 1)."""
|
|
246
|
+
a = np.column_stack([np.zeros(len(logits)), logits])
|
|
247
|
+
# A finite box on reference-relative logits is not invariant to
|
|
248
|
+
# component relabeling. Use stable, unbounded softmax; retain positive
|
|
249
|
+
# representable weights even when exponentials underflow, so the
|
|
250
|
+
# fitted mixture can always be converted back to a warm start.
|
|
251
|
+
with np.errstate(over="ignore", under="ignore"):
|
|
252
|
+
e = np.maximum(
|
|
253
|
+
np.exp(a - a.max(axis=1, keepdims=True)), np.finfo(float).tiny
|
|
254
|
+
)
|
|
255
|
+
result: Array = e / e.sum(axis=1, keepdims=True)
|
|
256
|
+
return result
|
|
257
|
+
|
|
258
|
+
@staticmethod
|
|
259
|
+
def logits(mixing_weights: ArrayLike) -> Array:
|
|
260
|
+
"""Logits (K, M - 1) ``log(pi_m / pi_1)`` of mixing weights (K, M)."""
|
|
261
|
+
pi = np.asarray(mixing_weights, dtype=np.float64)
|
|
262
|
+
if pi.ndim != 2 or not np.all(np.isfinite(pi)) or np.any(pi <= 0):
|
|
263
|
+
raise ValueError("mixing weights must be a positive (K, M) array")
|
|
264
|
+
result: Array = np.log(pi[:, 1:]) - np.log(pi[:, :1])
|
|
265
|
+
return result
|
|
266
|
+
|
|
267
|
+
def start(self, centers: ArrayLike, widths: ArrayLike) -> Array:
|
|
268
|
+
"""``x`` of a start from factor centers (K, D) and widths (K,): each
|
|
269
|
+
factor's components at its center, with widths ``MIXTURE_WIDTH_START**m``
|
|
270
|
+
times its width, and equal mixing weights."""
|
|
271
|
+
C = np.asarray(centers, dtype=np.float64)
|
|
272
|
+
w = np.asarray(widths, dtype=np.float64).ravel()
|
|
273
|
+
M = self.n_components
|
|
274
|
+
if M == 1:
|
|
275
|
+
return np.concatenate([C.ravel(), w])
|
|
276
|
+
Cc = np.repeat(C, M, axis=0)
|
|
277
|
+
wc = (w[:, None] * MIXTURE_WIDTH_START ** np.arange(M)[None, :]).ravel()
|
|
278
|
+
return self.join(Cc, wc, np.zeros((len(w), M - 1)))
|
|
279
|
+
|
|
280
|
+
def phi(self, z: Array, D: int) -> tuple[Array, Array, Array]:
|
|
281
|
+
"""Profile ``phi(z)`` in D dimensions and its first and second
|
|
282
|
+
derivatives."""
|
|
283
|
+
if self.name == "rbf":
|
|
284
|
+
p = np.exp(-z)
|
|
285
|
+
return p, -p, p
|
|
286
|
+
if self.name == "laplace":
|
|
287
|
+
u = np.sqrt(z + LAPLACE_EPS**2)
|
|
288
|
+
p = np.exp(LAPLACE_EPS - u)
|
|
289
|
+
return p, -p / (2.0 * u), p * (1.0 + u) / (4.0 * u**3)
|
|
290
|
+
a = 2.0 / D
|
|
291
|
+
g = np.exp(-z)
|
|
292
|
+
return (1.0 - a * z) * g, (a * z - a - 1.0) * g, (1.0 + 2.0 * a - a * z) * g
|
|
293
|
+
|
|
294
|
+
def profile(self, z: Array, D: int) -> Array:
|
|
295
|
+
"""``phi(z)`` alone, in D dimensions."""
|
|
296
|
+
if self.name == "rbf":
|
|
297
|
+
return np.exp(-z)
|
|
298
|
+
if self.name == "laplace":
|
|
299
|
+
return np.exp(LAPLACE_EPS - np.sqrt(z + LAPLACE_EPS**2))
|
|
300
|
+
return (1.0 - 2.0 / D * z) * np.exp(-z)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
RBF = Kernel()
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def kernel_factors(
|
|
307
|
+
R: Array,
|
|
308
|
+
centers: Array,
|
|
309
|
+
widths: Array,
|
|
310
|
+
logits: Array,
|
|
311
|
+
kernel: Kernel,
|
|
312
|
+
grid: AxisGrid | None = None,
|
|
313
|
+
) -> Array:
|
|
314
|
+
"""Factors (V, K) of ``kernel`` from component centers (K M, D), widths
|
|
315
|
+
(K M,) and logits (K, M - 1) (see `Kernel`); `factors` for one RBF
|
|
316
|
+
component."""
|
|
317
|
+
if kernel.plain_rbf:
|
|
318
|
+
return factors(R, centers, widths, grid)
|
|
319
|
+
d = sq_distances(R, centers, grid)
|
|
320
|
+
B = kernel.profile(d / widths[None, :], R.shape[1]) # (V, K M)
|
|
321
|
+
M = kernel.n_components
|
|
322
|
+
if M == 1:
|
|
323
|
+
return B
|
|
324
|
+
K = len(logits)
|
|
325
|
+
pi = kernel.mixing(logits)
|
|
326
|
+
result: Array = np.einsum("vkm,km->vk", B.reshape(len(R), K, M), pi)
|
|
327
|
+
return result
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
@dataclass(frozen=True)
|
|
331
|
+
class FactorDerivatives:
|
|
332
|
+
"""Factors ``F`` (K, V), their derivatives ``G`` (K, A, V) in each factor's
|
|
333
|
+
A parameters (`param_positions` order) and ``curvature(M)``, the
|
|
334
|
+
contraction ``sum_v M[k, v] d2F[k, v] / dtheta_k**2`` (K, A, A)."""
|
|
335
|
+
|
|
336
|
+
F: Array
|
|
337
|
+
G: Array
|
|
338
|
+
curvature: Any
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def mixture_derivatives(
|
|
342
|
+
R: Array,
|
|
343
|
+
centers: Array,
|
|
344
|
+
widths: Array,
|
|
345
|
+
logits: Array,
|
|
346
|
+
kernel: Kernel,
|
|
347
|
+
grid: AxisGrid | None = None,
|
|
348
|
+
F: Array | None = None,
|
|
349
|
+
) -> FactorDerivatives:
|
|
350
|
+
"""`FactorDerivatives` of any kernel and number of components.
|
|
351
|
+
|
|
352
|
+
Per component, with ``z = d / w``, ``f_d = phi'(z) / w``, ``f_dd =
|
|
353
|
+
phi''(z) / w**2``: ``dB/dc_j = -2 f_d delta_j``, ``dB/dw = -z phi' / w``,
|
|
354
|
+
``d2B/dc_i dc_j = 4 f_dd delta_i delta_j + 2 f_d [i = j]``, ``d2B/dc_i dw
|
|
355
|
+
= 2 (z phi'' + phi') delta_i / w**2`` and ``d2B/dw2 = (z**2 phi'' + 2 z
|
|
356
|
+
phi') / w**2`` (``delta = r - c``). A factor ``sum_m pi_m B_m`` adds
|
|
357
|
+
``dF/da_j = sum_m B_m dpi_m/da_j`` and the cross terms through the
|
|
358
|
+
softmax, ``dpi_m/da_j = pi_m ([m = j] - pi_j)``. ``F`` (V, K) passes
|
|
359
|
+
`kernel_factors` at the same point when the caller has it.
|
|
360
|
+
"""
|
|
361
|
+
K, M = len(logits), kernel.n_components
|
|
362
|
+
n, D = centers.shape
|
|
363
|
+
V = R.shape[0]
|
|
364
|
+
A = M * (D + 1) + M - 1
|
|
365
|
+
E = np.empty((n, D, V))
|
|
366
|
+
np.subtract(np.ascontiguousarray(R.T)[None], centers[:, :, None], out=E)
|
|
367
|
+
d = np.ascontiguousarray(sq_distances(R, centers, grid).T) # (K M, V)
|
|
368
|
+
w = widths[:, None]
|
|
369
|
+
z = d / w
|
|
370
|
+
phi, phi1, phi2 = kernel.phi(z, D)
|
|
371
|
+
f_d = phi1 / w
|
|
372
|
+
Gc = np.empty((n, D + 1, V))
|
|
373
|
+
np.multiply((-2.0 * f_d)[:, None, :], E, out=Gc[:, :D])
|
|
374
|
+
Gc[:, D] = -z * phi1 / w
|
|
375
|
+
f_dd = phi2 / w**2
|
|
376
|
+
f_dw = -(z * phi2 + phi1) / w**2
|
|
377
|
+
f_ww = (z * z * phi2 + 2.0 * z * phi1) / w**2
|
|
378
|
+
pi = kernel.mixing(logits) # (K, M)
|
|
379
|
+
eye = np.eye(M)
|
|
380
|
+
dpi = pi[:, :, None] * (eye[None] - pi[:, None, :]) # (K, M, M): dpi_m/da_j
|
|
381
|
+
d2pi = pi[:, :, None, None] * (
|
|
382
|
+
(eye[None, :, :, None] - pi[:, None, :, None])
|
|
383
|
+
* (eye[None, :, None, :] - pi[:, None, None, :])
|
|
384
|
+
- pi[:, None, None, :] * (eye[None, None] - pi[:, None, :, None])
|
|
385
|
+
) # (K, M, M, M): d2pi_m / da_i da_j
|
|
386
|
+
B = phi.reshape(K, M, V)
|
|
387
|
+
pic = pi.reshape(n)
|
|
388
|
+
if F is not None: # `kernel_factors` at the same point, (V, K)
|
|
389
|
+
F = np.ascontiguousarray(F.T)
|
|
390
|
+
elif M > 1:
|
|
391
|
+
F = np.einsum("kmv,km->kv", B, pi)
|
|
392
|
+
else:
|
|
393
|
+
F = phi
|
|
394
|
+
G = np.empty((K, A, V))
|
|
395
|
+
G[:, : M * (D + 1)] = (pic[:, None, None] * Gc).reshape(K, M * (D + 1), V)
|
|
396
|
+
if M > 1:
|
|
397
|
+
G[:, M * (D + 1) :] = np.einsum("kmv,kmj->kjv", B, dpi[:, :, 1:])
|
|
398
|
+
|
|
399
|
+
def curvature(MT: Array) -> Array:
|
|
400
|
+
Mc = np.repeat(MT, M, axis=0) * pic[:, None] # (K M, V)
|
|
401
|
+
U = Mc * f_dd
|
|
402
|
+
Sc = np.empty((n, D + 1, D + 1))
|
|
403
|
+
Sc[:, :D, :D] = 4.0 * (U[:, None, :] * E) @ np.swapaxes(E, 1, 2)
|
|
404
|
+
Sc[:, range(D), range(D)] += 2.0 * np.sum(Mc * f_d, axis=1)[:, None]
|
|
405
|
+
Sc[:, :D, D] = -2.0 * np.sum(E * (Mc * f_dw)[:, None, :], axis=2)
|
|
406
|
+
Sc[:, D, :D] = Sc[:, :D, D]
|
|
407
|
+
Sc[:, D, D] = np.sum(Mc * f_ww, axis=1)
|
|
408
|
+
S = np.zeros((K, A, A))
|
|
409
|
+
Sc = Sc.reshape(K, M, D + 1, D + 1)
|
|
410
|
+
for m in range(M):
|
|
411
|
+
sl = slice(m * (D + 1), (m + 1) * (D + 1))
|
|
412
|
+
S[:, sl, sl] = Sc[:, m]
|
|
413
|
+
if M > 1:
|
|
414
|
+
# sum_v M_k dB_m/dtheta_m dpi_m/da_j, and sum_m (sum_v M_k B_m)
|
|
415
|
+
# d2pi_m / da_i da_j.
|
|
416
|
+
MG = np.einsum("kv,kmav->kma", MT, Gc.reshape(K, M, D + 1, V))
|
|
417
|
+
cross = MG[:, :, :, None] * dpi[:, :, None, 1:] # (K, M, D+1, M-1)
|
|
418
|
+
cross = cross.reshape(K, M * (D + 1), M - 1)
|
|
419
|
+
S[:, : M * (D + 1), M * (D + 1) :] = cross
|
|
420
|
+
S[:, M * (D + 1) :, : M * (D + 1)] = np.swapaxes(cross, 1, 2)
|
|
421
|
+
MB = np.einsum("kv,kmv->km", MT, B)
|
|
422
|
+
S[:, M * (D + 1) :, M * (D + 1) :] = np.einsum(
|
|
423
|
+
"km,kmij->kij", MB, d2pi[:, :, 1:, 1:]
|
|
424
|
+
)
|
|
425
|
+
return S
|
|
426
|
+
|
|
427
|
+
return FactorDerivatives(np.ascontiguousarray(F), G, curvature)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def factors(
|
|
431
|
+
R: Array, centers: Array, widths: Array, grid: AxisGrid | None = None
|
|
432
|
+
) -> Array:
|
|
433
|
+
"""Radial basis factors ``F[v, k] = exp(-||r_v - c_k||^2 / w_k)``, shape (V, K).
|
|
434
|
+
|
|
435
|
+
With ``grid`` (`axis_grid` of ``R``) each factor is the product over the axes
|
|
436
|
+
of ``exp(-(r_vj - c_kj)**2 / w_k)``, evaluated on the distinct coordinates and
|
|
437
|
+
gathered. The product and exponential-of-sum forms are mathematically
|
|
438
|
+
equivalent but can differ by floating-point rounding. Where the product
|
|
439
|
+
underflows, the
|
|
440
|
+
exponential of the sum is below the smallest normal number too.
|
|
441
|
+
`kernel_factors` evaluates the other kernels and mixtures.
|
|
442
|
+
"""
|
|
443
|
+
if grid is None:
|
|
444
|
+
return np.exp(-sq_distances(R, centers) / widths[None, :])
|
|
445
|
+
F = np.ones((R.shape[0], centers.shape[0]))
|
|
446
|
+
for j, (values, index) in enumerate(zip(grid.values, grid.index, strict=True)):
|
|
447
|
+
diff = values[:, None] - centers[None, :, j]
|
|
448
|
+
F *= np.exp(-(diff * diff) / widths[None, :])[index]
|
|
449
|
+
return F
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def gram_solve(F: Array, X: Array, beta: float) -> tuple[Array, Array, Array]:
|
|
453
|
+
"""Weights (K, T) minimizing ``||X - F W||**2 + beta ||W||**2``, the
|
|
454
|
+
(pseudo-)inverse (K, K) of ``F^T F + beta I``, from its eigendecomposition,
|
|
455
|
+
and ``F^T X`` (K, T).
|
|
456
|
+
|
|
457
|
+
Eigenvalues below `GRAM_RCOND` times the largest, or below `GRAM_FLOOR`,
|
|
458
|
+
are dropped. Small eigenvalues, for example from vanishing or nearly
|
|
459
|
+
duplicate factors, can produce large weights that cancel in ``F W`` and
|
|
460
|
+
make the residual sensitive to floating-point evaluation order. The weights
|
|
461
|
+
are the minimum-norm minimizer on the retained eigenvectors (0 where every
|
|
462
|
+
factor vanishes).
|
|
463
|
+
"""
|
|
464
|
+
vals, vecs = np.linalg.eigh(F.T @ F + beta * np.eye(F.shape[1]))
|
|
465
|
+
keep = vals > max(GRAM_RCOND * vals[-1], GRAM_FLOOR)
|
|
466
|
+
inv = (vecs[:, keep] / vals[keep]) @ vecs[:, keep].T
|
|
467
|
+
B = F.T @ X
|
|
468
|
+
return inv @ B, inv, B
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def ridge_weights(X: Array, F: Array, method: str = "rr") -> Array:
|
|
472
|
+
"""Weights (K, T) solving ``(F^T F + beta I) W = F^T X``.
|
|
473
|
+
|
|
474
|
+
``method="rr"`` uses ``beta = var(X)``; ``method="ols"`` uses ``beta = 0``.
|
|
475
|
+
A singular gram (with ``'ols'``: a factor that is 0 at every voxel, as a
|
|
476
|
+
width shrunk to a small ``lower_ratio`` can make it, or two equal factors;
|
|
477
|
+
with ``'rr'``: constant data) gets the minimum-norm weights of
|
|
478
|
+
`gram_solve`, the ones the varpro objective uses.
|
|
479
|
+
"""
|
|
480
|
+
if method not in ("rr", "ols"):
|
|
481
|
+
raise ValueError(f"weight method must be 'rr' or 'ols', got {method!r}")
|
|
482
|
+
beta = float(np.var(X)) if method == "rr" else 0.0
|
|
483
|
+
gram = F.T @ F
|
|
484
|
+
if method == "rr":
|
|
485
|
+
gram = gram + beta * np.eye(F.shape[1])
|
|
486
|
+
try:
|
|
487
|
+
result: Array = scipy.linalg.solve(gram, F.T @ X, assume_a="pos")
|
|
488
|
+
except np.linalg.LinAlgError:
|
|
489
|
+
result = gram_solve(F, X, beta)[0]
|
|
490
|
+
return result
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def max_sigma(R: Array) -> float:
|
|
494
|
+
"""BrainIAK's maximum width ``2 * max(std(R, axis=0))**2``."""
|
|
495
|
+
return 2.0 * float(np.max(np.std(R, axis=0))) ** 2
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def bounds(
|
|
499
|
+
R: Array,
|
|
500
|
+
K: int,
|
|
501
|
+
lower_ratio: float,
|
|
502
|
+
upper_ratio: float,
|
|
503
|
+
kernel: Kernel = RBF,
|
|
504
|
+
) -> tuple[Array, Array]:
|
|
505
|
+
"""Lower and upper bounds for ``x`` (see `Kernel`; ``[centers.ravel(),
|
|
506
|
+
widths]`` for one component).
|
|
507
|
+
|
|
508
|
+
Centers lie within the per-dimension coordinate range of ``R``; widths lie in
|
|
509
|
+
``[lower_ratio, upper_ratio] * max_sigma(R)``. Mixing logits are unbounded:
|
|
510
|
+
fixing their reference component must not restrict which mixtures can
|
|
511
|
+
be represented or change a mixture when its components are reordered.
|
|
512
|
+
"""
|
|
513
|
+
sigma = max_sigma(R)
|
|
514
|
+
n, M = K * kernel.n_components, kernel.n_components
|
|
515
|
+
lb = np.concatenate(
|
|
516
|
+
[
|
|
517
|
+
np.tile(np.nanmin(R, axis=0), n),
|
|
518
|
+
np.full(n, lower_ratio * sigma),
|
|
519
|
+
np.full(K * (M - 1), -np.inf),
|
|
520
|
+
]
|
|
521
|
+
)
|
|
522
|
+
ub = np.concatenate(
|
|
523
|
+
[
|
|
524
|
+
np.tile(np.nanmax(R, axis=0), n),
|
|
525
|
+
np.full(n, upper_ratio * sigma),
|
|
526
|
+
np.full(K * (M - 1), np.inf),
|
|
527
|
+
]
|
|
528
|
+
)
|
|
529
|
+
return lb, ub
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def kmeans(
|
|
533
|
+
R: Array,
|
|
534
|
+
K: int,
|
|
535
|
+
random_state: int | np.random.RandomState | None,
|
|
536
|
+
sample_weight: Array | None = None,
|
|
537
|
+
) -> KMeans:
|
|
538
|
+
"""K-means++ (``n_init=10``) on ``R``, fitted on one OpenMP and one BLAS
|
|
539
|
+
thread.
|
|
540
|
+
|
|
541
|
+
Multithreaded K-means sums in a varying order: starts differed by 1e-14
|
|
542
|
+
between identical runs, which at K=100 on real data led TFA to different
|
|
543
|
+
optima. The limit is set here, in the thread that runs the K-means, because
|
|
544
|
+
the OpenMP thread count is per thread: a limit set in another thread (for
|
|
545
|
+
example the one that starts a thread pool) does not apply. Accelerate's
|
|
546
|
+
BLAS mode is per thread as well, and rounds differently on one thread than
|
|
547
|
+
on several (sklearn limits other BLAS libraries to one thread itself).
|
|
548
|
+
"""
|
|
549
|
+
km = KMeans(n_clusters=K, init="k-means++", n_init=10, random_state=random_state)
|
|
550
|
+
with threadpool_limits(limits=1, user_api="openmp"), single_threaded_accelerate():
|
|
551
|
+
km.fit(R, sample_weight=sample_weight)
|
|
552
|
+
return km
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def init_centers_widths(
|
|
556
|
+
R: Array, K: int, random_state: int | np.random.RandomState | None
|
|
557
|
+
) -> tuple[Array, Array]:
|
|
558
|
+
"""K-means++ centers (K, D) on ``R`` (`kmeans`) and widths (K,) equal to
|
|
559
|
+
``max_sigma(R)``."""
|
|
560
|
+
km = kmeans(R, K, random_state)
|
|
561
|
+
centers = np.asarray(km.cluster_centers_, dtype=np.float64)
|
|
562
|
+
return centers, np.full(K, max_sigma(R))
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
@dataclass
|
|
566
|
+
class Prior:
|
|
567
|
+
"""HTFA template prior on one subject's centers and widths.
|
|
568
|
+
|
|
569
|
+
``centers_cov`` is a full (K, D, D) SPD covariance per factor; ``widths_var`` is
|
|
570
|
+
(K,); ``scale`` multiplies both prior terms of the squared residual.
|
|
571
|
+
|
|
572
|
+
For a kernel with M > 1 components the centers, widths and their
|
|
573
|
+
(co)variances are per component, (K M, D), (K M,), (K M, D, D) and (K M,)
|
|
574
|
+
in the order of `Kernel`, and ``logits`` (K, M - 1) and ``logits_var``
|
|
575
|
+
(K, M - 1) add an independent Gaussian prior on the mixing logits.
|
|
576
|
+
"""
|
|
577
|
+
|
|
578
|
+
centers: Array
|
|
579
|
+
widths: Array
|
|
580
|
+
centers_cov: Array
|
|
581
|
+
widths_var: Array
|
|
582
|
+
scale: float
|
|
583
|
+
logits: Array | None = None
|
|
584
|
+
logits_var: Array | None = None
|
|
585
|
+
|
|
586
|
+
def shape_mean_var(self) -> tuple[Array, Array]:
|
|
587
|
+
"""Prior means and variances of the widths followed by the logits,
|
|
588
|
+
in the order of ``x``."""
|
|
589
|
+
if self.logits is None:
|
|
590
|
+
return np.asarray(self.widths), np.asarray(self.widths_var)
|
|
591
|
+
assert self.logits_var is not None
|
|
592
|
+
return (
|
|
593
|
+
np.concatenate([np.ravel(self.widths), np.ravel(self.logits)]),
|
|
594
|
+
np.concatenate([np.ravel(self.widths_var), np.ravel(self.logits_var)]),
|
|
595
|
+
)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def x_factors(
|
|
599
|
+
R: Array, C: Array, w: Array, K: int, kernel: Kernel, grid: AxisGrid | None
|
|
600
|
+
) -> Array:
|
|
601
|
+
"""Factors (V, K) at component centers ``C`` (K M, D) and the rest of
|
|
602
|
+
``x``, ``w`` (widths, then logits): `factors` for one RBF component,
|
|
603
|
+
`kernel_factors` otherwise."""
|
|
604
|
+
if kernel.plain_rbf:
|
|
605
|
+
return factors(R, C, w, grid)
|
|
606
|
+
n = len(C)
|
|
607
|
+
return kernel_factors(R, C, w[:n], w[n:].reshape(K, -1), kernel, grid)
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def x_derivatives(
|
|
611
|
+
R: Array,
|
|
612
|
+
C: Array,
|
|
613
|
+
w: Array,
|
|
614
|
+
K: int,
|
|
615
|
+
kernel: Kernel,
|
|
616
|
+
grid: AxisGrid | None,
|
|
617
|
+
F: Array | None = None,
|
|
618
|
+
) -> Any:
|
|
619
|
+
"""`factor_derivatives` for one RBF component, `mixture_derivatives`
|
|
620
|
+
otherwise, at ``C`` and ``w`` as in `x_factors` (``F`` (V, K): the factors
|
|
621
|
+
there, when the caller has them)."""
|
|
622
|
+
if kernel.plain_rbf:
|
|
623
|
+
return factor_derivatives(R, C, w, grid, F)
|
|
624
|
+
n = len(C)
|
|
625
|
+
return mixture_derivatives(R, C, w[:n], w[n:].reshape(K, -1), kernel, grid, F)
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
class ResidualProblem:
|
|
629
|
+
"""Residual and matrix-free Jacobian of the center/width least-squares problem.
|
|
630
|
+
|
|
631
|
+
Data residual ``s * (X - F W)`` with ``s = 1 / (sqrt(2) std(X))`` (``s = 1`` for
|
|
632
|
+
constant data), followed, when a prior is given, by the K center residuals
|
|
633
|
+
``sqrt(scale * dc^T Sigma^-1 dc)`` and the K signed width residuals
|
|
634
|
+
``sqrt(scale / var) * (w - prior.widths)``. With a ``kernel`` of M > 1
|
|
635
|
+
components the center and width residuals are per component (K M each),
|
|
636
|
+
followed by the K (M - 1) signed logit residuals (see `Prior`).
|
|
637
|
+
|
|
638
|
+
``data_on_engine=True`` sends only ``W`` to the engine, whose data must
|
|
639
|
+
already be ``X`` (`ProjectedProblem` sets it once per solve).
|
|
640
|
+
|
|
641
|
+
With ``compress=True`` (exact only for a linear loss) ``(X, W)`` is replaced by
|
|
642
|
+
``(X Q, Rq^T)`` where ``W^T = Q Rq`` is the thin QR, and ``cost_offset`` holds
|
|
643
|
+
``0.5 s^2 ||X (I - Q Q^T)||_F^2`` so that costs match the uncompressed problem.
|
|
644
|
+
"""
|
|
645
|
+
|
|
646
|
+
def __init__(
|
|
647
|
+
self,
|
|
648
|
+
X: Array,
|
|
649
|
+
W: Array,
|
|
650
|
+
R: Array,
|
|
651
|
+
engine: Engine,
|
|
652
|
+
prior: Prior | None = None,
|
|
653
|
+
compress: bool = False,
|
|
654
|
+
data_on_engine: bool = False,
|
|
655
|
+
kernel: Kernel = RBF,
|
|
656
|
+
) -> None:
|
|
657
|
+
if compress and data_on_engine:
|
|
658
|
+
raise ValueError("compress needs the data sent to the engine")
|
|
659
|
+
X = np.asarray(X, dtype=np.float64)
|
|
660
|
+
W = np.asarray(W, dtype=np.float64)
|
|
661
|
+
self.R = np.ascontiguousarray(R, dtype=np.float64)
|
|
662
|
+
self.K = W.shape[0]
|
|
663
|
+
self.D = self.R.shape[1]
|
|
664
|
+
self.kernel = kernel
|
|
665
|
+
self.M = kernel.n_components
|
|
666
|
+
self.Kc = self.K * self.M # components
|
|
667
|
+
std = float(np.std(X))
|
|
668
|
+
self.s = 1.0 / (np.sqrt(2.0) * std) if std > 0 else 1.0
|
|
669
|
+
self.cost_offset = 0.0
|
|
670
|
+
if compress:
|
|
671
|
+
Q, Rq = np.linalg.qr(W.T)
|
|
672
|
+
XQ = X @ Q
|
|
673
|
+
self.cost_offset = 0.5 * self.s**2 * float(np.sum((X - XQ @ Q.T) ** 2))
|
|
674
|
+
X, W = XQ, Rq.T
|
|
675
|
+
self.engine = engine
|
|
676
|
+
if data_on_engine:
|
|
677
|
+
self.engine.set_weights(W)
|
|
678
|
+
else:
|
|
679
|
+
self.engine.set(X, W)
|
|
680
|
+
self.n_data = X.size
|
|
681
|
+
self._w_sq_norms = np.sum(W * W, axis=1)
|
|
682
|
+
self.prior = prior
|
|
683
|
+
self._last: tuple[Array, tuple[Array, Array, Array]] | None = None
|
|
684
|
+
if prior is not None:
|
|
685
|
+
inv = np.linalg.inv(np.asarray(prior.centers_cov, dtype=np.float64))
|
|
686
|
+
# Symmetrize so that Sigma^-1 dc is exactly half the quadratic's gradient.
|
|
687
|
+
self._cov_inv = 0.5 * (inv + np.swapaxes(inv, 1, 2))
|
|
688
|
+
self._width_coef = np.sqrt(prior.scale / prior.shape_mean_var()[1])
|
|
689
|
+
self.n_params = kernel.n_params(self.K, self.D)
|
|
690
|
+
n_prior = self.Kc + self.n_params - self.Kc * self.D
|
|
691
|
+
self.n_residuals = self.n_data + (n_prior if prior is not None else 0)
|
|
692
|
+
|
|
693
|
+
def _unpack(self, x: ArrayLike) -> tuple[Array, Array]:
|
|
694
|
+
"""Component centers (K M, D) and the rest of ``x``: widths (and
|
|
695
|
+
logits)."""
|
|
696
|
+
x = np.asarray(x, dtype=np.float64).ravel()
|
|
697
|
+
n = self.Kc * self.D
|
|
698
|
+
return x[:n].reshape(self.Kc, self.D), x[n:]
|
|
699
|
+
|
|
700
|
+
def _kernel_factors(self, C: Array, w: Array, grid: AxisGrid | None) -> Array:
|
|
701
|
+
"""Factors (V, K) at component centers ``C`` and widths/logits ``w``."""
|
|
702
|
+
return x_factors(self.R, C, w, self.K, self.kernel, grid)
|
|
703
|
+
|
|
704
|
+
def _derivatives(self, C: Array, w: Array, F: Array | None) -> Any:
|
|
705
|
+
"""`x_derivatives` at ``C``, ``w``."""
|
|
706
|
+
return x_derivatives(self.R, C, w, self.K, self.kernel, self._grid, F)
|
|
707
|
+
|
|
708
|
+
@cached_property
|
|
709
|
+
def _grid(self) -> AxisGrid | None:
|
|
710
|
+
"""`axis_grid` of the coordinates, for :meth:`cost` and
|
|
711
|
+
:meth:`cost_grad_hess` (computed on first use)."""
|
|
712
|
+
return axis_grid(self.R)
|
|
713
|
+
|
|
714
|
+
def _factors(self, x: ArrayLike) -> tuple[Array, Array, Array]:
|
|
715
|
+
"""Centers, widths and `factors` (V, K) at ``x``. The last point's are
|
|
716
|
+
kept: `bounded_lm` assembles the Hessian at the point it has just
|
|
717
|
+
evaluated, and reuses them unchanged."""
|
|
718
|
+
x = np.array(x, dtype=np.float64).ravel()
|
|
719
|
+
if self._last is not None and np.array_equal(self._last[0], x):
|
|
720
|
+
return self._last[1]
|
|
721
|
+
C, w = self._unpack(x)
|
|
722
|
+
out = (C, w, self._kernel_factors(C, w, self._grid))
|
|
723
|
+
self._last = (x, out)
|
|
724
|
+
return out
|
|
725
|
+
|
|
726
|
+
def _center_prior(self, C: Array) -> tuple[Array, Array]:
|
|
727
|
+
"""Center residuals r_c (K,) and their gradients dr_c/dC (K, D)."""
|
|
728
|
+
assert self.prior is not None
|
|
729
|
+
dc = C - self.prior.centers
|
|
730
|
+
sdc = np.einsum("kij,kj->ki", self._cov_inv, dc)
|
|
731
|
+
r_c = np.sqrt(np.maximum(self.prior.scale * np.sum(dc * sdc, axis=1), 0.0))
|
|
732
|
+
inv_r = np.divide(1.0, r_c, out=np.zeros_like(r_c), where=r_c > 0)
|
|
733
|
+
return r_c, (self.prior.scale * inv_r)[:, None] * sdc
|
|
734
|
+
|
|
735
|
+
def residual(self, x: ArrayLike) -> Array:
|
|
736
|
+
"""Residual vector of length ``V*T`` (+ the prior residuals)."""
|
|
737
|
+
C, w = self._unpack(x)
|
|
738
|
+
r_d = self.s * self.engine.residual(self._kernel_factors(C, w, None))
|
|
739
|
+
if self.prior is None:
|
|
740
|
+
return r_d
|
|
741
|
+
r_c, _ = self._center_prior(C)
|
|
742
|
+
r_w = self._width_coef * (w - self.prior.shape_mean_var()[0])
|
|
743
|
+
return np.concatenate([r_d, r_c, r_w])
|
|
744
|
+
|
|
745
|
+
def jacobian(self, x: ArrayLike) -> LinearOperator:
|
|
746
|
+
"""Matrix-free Jacobian of :meth:`residual` at ``x``."""
|
|
747
|
+
if not self.kernel.plain_rbf:
|
|
748
|
+
return self._kernel_jacobian(x)
|
|
749
|
+
C, w = self._unpack(x)
|
|
750
|
+
R, K, s, n_data = self.R, self.K, self.s, self.n_data
|
|
751
|
+
d = sq_distances(R, C)
|
|
752
|
+
Fw = np.exp(-d / w[None, :]) / w[None, :]
|
|
753
|
+
prior = self.prior
|
|
754
|
+
grad_c = self._center_prior(C)[1] if prior is not None else None
|
|
755
|
+
|
|
756
|
+
def matvec(p: Array) -> Array:
|
|
757
|
+
pc, pw = self._unpack(p)
|
|
758
|
+
A = Fw * (2.0 * (R @ pc.T - np.sum(C * pc, axis=1)[None, :]) + d * (pw / w))
|
|
759
|
+
data = -s * self.engine.times_w(A)
|
|
760
|
+
if grad_c is None:
|
|
761
|
+
return data
|
|
762
|
+
return np.concatenate(
|
|
763
|
+
[data, np.sum(grad_c * pc, axis=1), self._width_coef * pw]
|
|
764
|
+
)
|
|
765
|
+
|
|
766
|
+
def rmatvec(u: Array) -> Array:
|
|
767
|
+
u = np.asarray(u, dtype=np.float64).ravel()
|
|
768
|
+
G = Fw * self.engine.times_wt(u[:n_data])
|
|
769
|
+
g_c = -2.0 * s * (G.T @ R - C * np.sum(G, axis=0)[:, None])
|
|
770
|
+
g_w = -s * np.sum(G * d, axis=0) / w
|
|
771
|
+
if grad_c is not None:
|
|
772
|
+
g_c = g_c + grad_c * u[n_data : n_data + K, None]
|
|
773
|
+
g_w = g_w + self._width_coef * u[n_data + K :]
|
|
774
|
+
return np.concatenate([g_c.ravel(), g_w])
|
|
775
|
+
|
|
776
|
+
def matmat(P: Array) -> Array:
|
|
777
|
+
return np.column_stack([matvec(col) for col in np.asarray(P).T])
|
|
778
|
+
|
|
779
|
+
def rmatmat(U: Array) -> Array:
|
|
780
|
+
return np.column_stack([rmatvec(col) for col in np.asarray(U).T])
|
|
781
|
+
|
|
782
|
+
return LinearOperator(
|
|
783
|
+
(self.n_residuals, self.n_params),
|
|
784
|
+
matvec=matvec,
|
|
785
|
+
rmatvec=rmatvec,
|
|
786
|
+
matmat=matmat,
|
|
787
|
+
rmatmat=rmatmat,
|
|
788
|
+
dtype=np.float64,
|
|
789
|
+
)
|
|
790
|
+
|
|
791
|
+
def _kernel_jacobian(self, x: ArrayLike) -> LinearOperator:
|
|
792
|
+
""":meth:`jacobian` for any kernel, from `mixture_derivatives`:
|
|
793
|
+
``dr[v, t] / dtheta[k, a] = -s G[k, a, v] W[k, t]``."""
|
|
794
|
+
C, w = self._unpack(x)
|
|
795
|
+
G = self._derivatives(C, w, None).G
|
|
796
|
+
K, s, n_data, Kc = self.K, self.s, self.n_data, self.Kc
|
|
797
|
+
pos = param_positions(K, self.D, self.M)
|
|
798
|
+
grad_c = self._center_prior(C)[1] if self.prior is not None else None
|
|
799
|
+
|
|
800
|
+
def matvec(p: Array) -> Array:
|
|
801
|
+
p = np.asarray(p, dtype=np.float64).ravel()
|
|
802
|
+
A = np.einsum("kav,ka->vk", G, p[pos].reshape(K, -1))
|
|
803
|
+
data = -s * self.engine.times_w(A)
|
|
804
|
+
if grad_c is None:
|
|
805
|
+
return data
|
|
806
|
+
pc, pw = self._unpack(p)
|
|
807
|
+
return np.concatenate(
|
|
808
|
+
[data, np.sum(grad_c * pc, axis=1), self._width_coef * pw]
|
|
809
|
+
)
|
|
810
|
+
|
|
811
|
+
def rmatvec(u: Array) -> Array:
|
|
812
|
+
u = np.asarray(u, dtype=np.float64).ravel()
|
|
813
|
+
Gu = self.engine.times_wt(u[:n_data]) # (V, K)
|
|
814
|
+
g = np.empty(self.n_params)
|
|
815
|
+
g[pos] = (-s * np.einsum("kav,vk->ka", G, Gu)).ravel()
|
|
816
|
+
if grad_c is not None:
|
|
817
|
+
g[: Kc * self.D] += (grad_c * u[n_data : n_data + Kc, None]).ravel()
|
|
818
|
+
g[Kc * self.D :] += self._width_coef * u[n_data + Kc :]
|
|
819
|
+
return g
|
|
820
|
+
|
|
821
|
+
def matmat(P: Array) -> Array:
|
|
822
|
+
return np.column_stack([matvec(col) for col in np.asarray(P).T])
|
|
823
|
+
|
|
824
|
+
def rmatmat(U: Array) -> Array:
|
|
825
|
+
return np.column_stack([rmatvec(col) for col in np.asarray(U).T])
|
|
826
|
+
|
|
827
|
+
return LinearOperator(
|
|
828
|
+
(self.n_residuals, self.n_params),
|
|
829
|
+
matvec=matvec,
|
|
830
|
+
rmatvec=rmatvec,
|
|
831
|
+
matmat=matmat,
|
|
832
|
+
rmatmat=rmatmat,
|
|
833
|
+
dtype=np.float64,
|
|
834
|
+
)
|
|
835
|
+
|
|
836
|
+
def _prior_terms(
|
|
837
|
+
self, C: Array, w: Array, loss: str, derivatives: bool
|
|
838
|
+
) -> tuple[float, Array, Array]:
|
|
839
|
+
"""Prior cost ``0.5 sum rho(r**2)`` over the prior residuals, and (when
|
|
840
|
+
``derivatives``) its gradient (P,) and Hessian (P, P).
|
|
841
|
+
|
|
842
|
+
The center term is a function of ``q_k = r_ck**2 = scale dc^T S dc``, so its
|
|
843
|
+
exact Hessian ``scale rho' S + 2 rho'' scale**2 (S dc)(S dc)^T`` is used,
|
|
844
|
+
with the eigenvalue ``rho' + 2 q rho''`` along ``dc`` floored at ``EPS`` as
|
|
845
|
+
scipy floors its loss weights. The width residuals are linear in ``w``, so
|
|
846
|
+
their Hessian ``coef**2 (rho' + 2 r**2 rho'')`` is exact (same floor).
|
|
847
|
+
"""
|
|
848
|
+
assert self.prior is not None
|
|
849
|
+
K, D, P = self.Kc, self.D, self.n_params
|
|
850
|
+
dc = C - self.prior.centers
|
|
851
|
+
Sdc = np.einsum("kij,kj->ki", self._cov_inv, dc)
|
|
852
|
+
q = np.maximum(self.prior.scale * np.sum(dc * Sdc, axis=1), 0.0)
|
|
853
|
+
r_w = self._width_coef * (w - self.prior.shape_mean_var()[0])
|
|
854
|
+
rho_c, rho1_c, rho2_c = loss_terms(loss, q)
|
|
855
|
+
rho_w, rho1_w, rho2_w = loss_terms(loss, r_w * r_w)
|
|
856
|
+
cost = 0.5 * float(np.sum(rho_c) + np.sum(rho_w))
|
|
857
|
+
grad, H = np.zeros(P), np.zeros((P, P))
|
|
858
|
+
if not derivatives:
|
|
859
|
+
return cost, grad, H
|
|
860
|
+
scale = self.prior.scale
|
|
861
|
+
grad[: K * D] = (rho1_c[:, None] * scale * Sdc).ravel()
|
|
862
|
+
grad[K * D :] = rho1_w * r_w * self._width_coef
|
|
863
|
+
along = np.maximum(rho1_c + 2.0 * q * rho2_c, EPS)
|
|
864
|
+
beta = np.divide(along - rho1_c, q, out=np.zeros_like(q), where=q > 0)
|
|
865
|
+
for k in range(K):
|
|
866
|
+
block = scale * (
|
|
867
|
+
rho1_c[k] * self._cov_inv[k]
|
|
868
|
+
+ beta[k] * scale * np.outer(Sdc[k], Sdc[k])
|
|
869
|
+
)
|
|
870
|
+
H[k * D : (k + 1) * D, k * D : (k + 1) * D] = block
|
|
871
|
+
width_idx = np.arange(K * D, P)
|
|
872
|
+
H[width_idx, width_idx] = self._width_coef**2 * np.maximum(
|
|
873
|
+
rho1_w + 2.0 * r_w * r_w * rho2_w, EPS
|
|
874
|
+
)
|
|
875
|
+
return cost, grad, H
|
|
876
|
+
|
|
877
|
+
def cost(self, x: ArrayLike, loss: str) -> float:
|
|
878
|
+
"""Objective ``0.5 * sum(rho(r**2))`` over :meth:`residual` (without
|
|
879
|
+
``cost_offset``), evaluated without forming the residual vector."""
|
|
880
|
+
C, w, F = self._factors(x)
|
|
881
|
+
total = self.engine.data_cost(F, self.s, loss)
|
|
882
|
+
if self.prior is not None:
|
|
883
|
+
total += self._prior_terms(C, w, loss, derivatives=False)[0]
|
|
884
|
+
return total
|
|
885
|
+
|
|
886
|
+
def cost_grad_hess(
|
|
887
|
+
self,
|
|
888
|
+
x: ArrayLike,
|
|
889
|
+
loss: str,
|
|
890
|
+
derivatives: Any = None,
|
|
891
|
+
mode: str = "exact",
|
|
892
|
+
) -> tuple[float, Array, Array, Array]:
|
|
893
|
+
"""Cost (as :meth:`cost`), gradient (P,), positive semidefinite
|
|
894
|
+
Gauss-Newton matrix (P, P) and Hessian (P, P) of the objective.
|
|
895
|
+
``derivatives`` passes `factor_derivatives` at ``x`` when the caller has
|
|
896
|
+
them already (`mixture_derivatives` for a kernel other than one RBF
|
|
897
|
+
component). With the linear loss in ``mode='fast'`` the Gauss-Newton
|
|
898
|
+
product ``G G^T`` is formed in float32 (`curvature_operand`).
|
|
899
|
+
|
|
900
|
+
The Gauss-Newton matrix is the Hessian without the data term's
|
|
901
|
+
second-order part ``sum_i rho'_i r_i Hess(r_i)`` (the prior terms keep
|
|
902
|
+
their exact, floored Hessian, which is positive semidefinite).
|
|
903
|
+
|
|
904
|
+
The data part of the Hessian is ``J^T diag(u) J + sum_i rho'_i r_i
|
|
905
|
+
Hess(r_i)``, with scipy's loss weights ``u = max(rho' + 2 r**2 rho'', EPS)``
|
|
906
|
+
(exact wherever ``rho' + 2 r**2 rho'' >= 0``: always for the linear,
|
|
907
|
+
soft_l1 and huber losses). ``J^T diag(u) J`` is assembled from the
|
|
908
|
+
per-factor structure ``dr[v, t] / dtheta[k, a] = -s G[k, a, v] W[k, t]``
|
|
909
|
+
(`htfa._engines.Engine.gauss_newton`) instead of the V*T x P Jacobian; the
|
|
910
|
+
second-order term is block diagonal per factor,
|
|
911
|
+
``-s sum_v M[v, k] d2F[v, k] / dtheta_k^2`` with ``M = (rho' r) W^T``, and
|
|
912
|
+
costs O(V K (D+1)**2). The parameters of factor k are
|
|
913
|
+
``theta_k = (c_k1, ..., c_kD, w_k)`` (with M components, each
|
|
914
|
+
component's ``(c, w)`` in turn and then the logits; `param_positions`).
|
|
915
|
+
"""
|
|
916
|
+
K, D, P = self.K, self.D, self.n_params
|
|
917
|
+
s = self.s
|
|
918
|
+
if derivatives is None:
|
|
919
|
+
C, w, F = self._factors(x)
|
|
920
|
+
derivatives = self._derivatives(C, w, F)
|
|
921
|
+
else:
|
|
922
|
+
C, w = self._unpack(x)
|
|
923
|
+
if self.kernel.plain_rbf:
|
|
924
|
+
E, F, G = derivatives
|
|
925
|
+
else:
|
|
926
|
+
F, G = derivatives.F, derivatives.G
|
|
927
|
+
# The robust losses multiply G by float64 loss weights in the engine.
|
|
928
|
+
G_gn = curvature_operand(G, mode) if loss == "linear" else G
|
|
929
|
+
cost, M, H_ka = self.engine.gauss_newton(
|
|
930
|
+
np.ascontiguousarray(F.T), G_gn, s, loss
|
|
931
|
+
)
|
|
932
|
+
MT = np.ascontiguousarray(M.T) # (K, V)
|
|
933
|
+
grad_ka = -s * (G @ MT[:, :, None])[:, :, 0]
|
|
934
|
+
if self.kernel.plain_rbf:
|
|
935
|
+
# Second derivatives of F = exp(-d / w) per factor, contracted with
|
|
936
|
+
# M, from the moments m[k, a, b] = sum_v F M e_a e_b of e = (delta,
|
|
937
|
+
# d, 1).
|
|
938
|
+
m = ((F * MT)[:, None, :] * E) @ np.swapaxes(E, 1, 2) # (K, D+2, D+2)
|
|
939
|
+
wk = w[:, None]
|
|
940
|
+
S = np.empty((K, D + 1, D + 1))
|
|
941
|
+
S[:, :D, :D] = 4.0 / w[:, None, None] ** 2 * m[:, :D, :D]
|
|
942
|
+
S[:, range(D), range(D)] -= 2.0 / wk * m[:, D + 1, D + 1][:, None]
|
|
943
|
+
S[:, :D, D] = 2.0 / wk**2 * (m[:, :D, D] / wk - m[:, :D, D + 1])
|
|
944
|
+
S[:, D, :D] = S[:, :D, D]
|
|
945
|
+
S[:, D, D] = (m[:, D, D] / w - 2.0 * m[:, D, D + 1]) / w**3
|
|
946
|
+
else:
|
|
947
|
+
S = derivatives.curvature(MT)
|
|
948
|
+
k = np.arange(K)
|
|
949
|
+
pos = param_positions(K, D, self.M)
|
|
950
|
+
grad = np.empty(P)
|
|
951
|
+
grad[pos] = grad_ka.ravel()
|
|
952
|
+
gn = np.empty((P, P))
|
|
953
|
+
gn[np.ix_(pos, pos)] = H_ka.reshape(P, P)
|
|
954
|
+
H_ka[:] = 0.0
|
|
955
|
+
H_ka[k, :, k, :] = -s * S
|
|
956
|
+
second = np.empty((P, P))
|
|
957
|
+
second[np.ix_(pos, pos)] = H_ka.reshape(P, P)
|
|
958
|
+
if self.prior is not None:
|
|
959
|
+
c_p, g_p, H_p = self._prior_terms(C, w, loss, derivatives=True)
|
|
960
|
+
cost, grad, gn = cost + c_p, grad + g_p, gn + H_p
|
|
961
|
+
# Exactly symmetric (the two triangles are summed in different orders).
|
|
962
|
+
gn = 0.5 * (gn + gn.T)
|
|
963
|
+
hess = gn + second
|
|
964
|
+
return cost, grad, gn, 0.5 * (hess + hess.T)
|
|
965
|
+
|
|
966
|
+
def column_norms(self, x: ArrayLike) -> Array:
|
|
967
|
+
"""Exact Euclidean norms (P,) of the Jacobian columns at ``x``.
|
|
968
|
+
|
|
969
|
+
Each data column is the outer product of a (V,) factor derivative with the
|
|
970
|
+
weights of its factor, so its norm is ``s * ||a_j|| * ||W_k||``.
|
|
971
|
+
"""
|
|
972
|
+
C, w = self._unpack(x)
|
|
973
|
+
if not self.kernel.plain_rbf:
|
|
974
|
+
G = self._derivatives(C, w, None).G
|
|
975
|
+
sq = np.empty(self.n_params)
|
|
976
|
+
sq[param_positions(self.K, self.D, self.M)] = (
|
|
977
|
+
self.s**2 * self._w_sq_norms[:, None] * np.sum(G * G, axis=2)
|
|
978
|
+
).ravel()
|
|
979
|
+
if self.prior is not None:
|
|
980
|
+
n = self.Kc * self.D
|
|
981
|
+
sq[:n] += (self._center_prior(C)[1] ** 2).ravel()
|
|
982
|
+
sq[n:] += self._width_coef**2
|
|
983
|
+
return np.sqrt(sq)
|
|
984
|
+
d = sq_distances(self.R, C)
|
|
985
|
+
Fw = np.exp(-d / w[None, :]) / w[None, :]
|
|
986
|
+
s2w = self.s**2 * self._w_sq_norms
|
|
987
|
+
sq_c = np.empty((self.K, self.D))
|
|
988
|
+
for j in range(self.D):
|
|
989
|
+
a = 2.0 * Fw * (self.R[:, j, None] - C[None, :, j])
|
|
990
|
+
sq_c[:, j] = s2w * np.sum(a * a, axis=0)
|
|
991
|
+
a = Fw * d / w[None, :]
|
|
992
|
+
sq_w = s2w * np.sum(a * a, axis=0)
|
|
993
|
+
if self.prior is not None:
|
|
994
|
+
sq_c += self._center_prior(C)[1] ** 2
|
|
995
|
+
sq_w += self._width_coef**2
|
|
996
|
+
return np.sqrt(np.concatenate([sq_c.ravel(), sq_w]))
|
|
997
|
+
|
|
998
|
+
|
|
999
|
+
def factor_derivatives(
|
|
1000
|
+
R: Array,
|
|
1001
|
+
C: Array,
|
|
1002
|
+
w: Array,
|
|
1003
|
+
grid: AxisGrid | None = None,
|
|
1004
|
+
F: Array | None = None,
|
|
1005
|
+
) -> tuple[Array, Array, Array]:
|
|
1006
|
+
"""Factors and their derivatives in a factor-major, voxel-last layout.
|
|
1007
|
+
|
|
1008
|
+
Returns ``E`` (K, D + 2, V) = ``[delta_1 .. delta_D, d, 1]`` with ``delta =
|
|
1009
|
+
r_v - c_k`` and ``d = ||delta||**2``, the factors ``F`` (K, V) and ``G``
|
|
1010
|
+
(K, D + 1, V) with ``G[k, a, v] = dF[k, v] / dtheta[k, a]`` for ``theta_k =
|
|
1011
|
+
(c_k1, ..., c_kD, w_k)``. The (K, ., V) layout gives contiguous elementwise
|
|
1012
|
+
passes and per-factor sums over voxels as batched matrix products.
|
|
1013
|
+
|
|
1014
|
+
``d`` and ``F`` are, bit for bit, the transposes of `sq_distances` and
|
|
1015
|
+
`factors` with the same ``grid``; ``F`` (V, K) passes the latter when the
|
|
1016
|
+
caller has it.
|
|
1017
|
+
"""
|
|
1018
|
+
K, D = C.shape
|
|
1019
|
+
V = R.shape[0]
|
|
1020
|
+
E = np.empty((K, D + 2, V))
|
|
1021
|
+
# From a contiguous copy of R.T: 1.3 ms instead of 3.0 ms from the strided
|
|
1022
|
+
# view of R (K=100, V=25k); the values are the same.
|
|
1023
|
+
np.subtract(np.ascontiguousarray(R.T)[None], C[:, :, None], out=E[:, :D])
|
|
1024
|
+
# The sums of `sq_distances` (with or without a grid), in its order.
|
|
1025
|
+
d = E[:, D]
|
|
1026
|
+
np.multiply(E[:, 0], E[:, 0], out=d)
|
|
1027
|
+
for j in range(1, D):
|
|
1028
|
+
d += E[:, j] * E[:, j]
|
|
1029
|
+
if F is not None:
|
|
1030
|
+
F = np.ascontiguousarray(F.T)
|
|
1031
|
+
elif grid is None:
|
|
1032
|
+
F = np.exp(-d / w[:, None])
|
|
1033
|
+
else:
|
|
1034
|
+
F = np.ascontiguousarray(factors(R, C, w, grid).T)
|
|
1035
|
+
E[:, D + 1] = 1.0
|
|
1036
|
+
Fw = F / w[:, None]
|
|
1037
|
+
G = np.empty((K, D + 1, V))
|
|
1038
|
+
np.multiply((2.0 * Fw)[:, None, :], E[:, :D], out=G[:, :D])
|
|
1039
|
+
np.multiply(Fw, d / w[:, None], out=G[:, D])
|
|
1040
|
+
return E, F, G
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def param_positions(K: int, D: int, M: int = 1) -> NDArray[np.int64]:
|
|
1044
|
+
"""Position in ``x`` (see `Kernel`) of each ``(k, a)``, raveled, where
|
|
1045
|
+
factor k's parameters ``a`` are its components' ``(c_1, ..., c_D, w)`` in
|
|
1046
|
+
turn, then its M - 1 logits. With ``M = 1``, ``x = [centers.ravel(),
|
|
1047
|
+
widths]``."""
|
|
1048
|
+
if M == 1:
|
|
1049
|
+
k = np.arange(K)
|
|
1050
|
+
pos = np.empty((K, D + 1), dtype=np.int64)
|
|
1051
|
+
pos[:, :D] = k[:, None] * D + np.arange(D)[None, :]
|
|
1052
|
+
pos[:, D] = K * D + k
|
|
1053
|
+
return pos.ravel()
|
|
1054
|
+
n = K * M
|
|
1055
|
+
comp = np.arange(n).reshape(K, M)
|
|
1056
|
+
pos = np.empty((K, M * (D + 1) + M - 1), dtype=np.int64)
|
|
1057
|
+
block = np.empty((K, M, D + 1), dtype=np.int64)
|
|
1058
|
+
block[:, :, :D] = comp[:, :, None] * D + np.arange(D)
|
|
1059
|
+
block[:, :, D] = n * D + comp
|
|
1060
|
+
pos[:, : M * (D + 1)] = block.reshape(K, -1)
|
|
1061
|
+
pos[:, M * (D + 1) :] = (
|
|
1062
|
+
n * (D + 1) + np.arange(K)[:, None] * (M - 1) + np.arange(M - 1)
|
|
1063
|
+
)
|
|
1064
|
+
return pos.ravel()
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
class ProjectedProblem:
|
|
1068
|
+
"""Variable-projection objective of the linear-loss TFA problem.
|
|
1069
|
+
|
|
1070
|
+
The weights are eliminated: ``phi(x) = 0.5 s**2 (||X - F W||_F**2 + beta
|
|
1071
|
+
||W||_F**2)`` with ``W = W(x)`` the ridge solution of `ridge_weights`
|
|
1072
|
+
(``beta = var(X)`` for ``'rr'``, 0 for ``'ols'``), plus the prior terms of
|
|
1073
|
+
`ResidualProblem`. Its stationary points are exactly the fixed points of
|
|
1074
|
+
alternating `ridge_weights` with the linear-loss center/width solve, but a
|
|
1075
|
+
Newton method on ``phi`` takes the coupling between the weights and the
|
|
1076
|
+
centers/widths into account, which the alternation ignores (it then needs
|
|
1077
|
+
hundreds of outer iterations on real data).
|
|
1078
|
+
|
|
1079
|
+
The gradient is the fixed-weight gradient (envelope theorem). The Hessian
|
|
1080
|
+
is ``H_xx - H_xW H_WW^-1 H_Wx`` with the exact mixed second derivatives;
|
|
1081
|
+
the Gauss-Newton matrix is ``J^T (I - P) J`` (Kaufman's), with ``P`` the
|
|
1082
|
+
projection onto the span of the (ridge-augmented) weight columns.
|
|
1083
|
+
"""
|
|
1084
|
+
|
|
1085
|
+
def __init__(
|
|
1086
|
+
self,
|
|
1087
|
+
X: Array,
|
|
1088
|
+
R: Array,
|
|
1089
|
+
K: int,
|
|
1090
|
+
engine: Engine,
|
|
1091
|
+
prior: Prior | None = None,
|
|
1092
|
+
weight_method: str = "rr",
|
|
1093
|
+
kernel: Kernel = RBF,
|
|
1094
|
+
) -> None:
|
|
1095
|
+
self.X = np.ascontiguousarray(X, dtype=np.float64)
|
|
1096
|
+
self.R = np.ascontiguousarray(R, dtype=np.float64)
|
|
1097
|
+
self.K, self.D = K, self.R.shape[1]
|
|
1098
|
+
self.kernel = kernel
|
|
1099
|
+
self.Kc = K * kernel.n_components
|
|
1100
|
+
self.engine, self.prior = engine, prior
|
|
1101
|
+
if weight_method not in ("rr", "ols"):
|
|
1102
|
+
raise ValueError(
|
|
1103
|
+
f"weight method must be 'rr' or 'ols', got {weight_method!r}"
|
|
1104
|
+
)
|
|
1105
|
+
self.beta = float(np.var(self.X)) if weight_method == "rr" else 0.0
|
|
1106
|
+
self.weight_method = weight_method
|
|
1107
|
+
std = float(np.std(self.X))
|
|
1108
|
+
self.s = 1.0 / (np.sqrt(2.0) * std) if std > 0 else 1.0
|
|
1109
|
+
self.cost_offset = 0.0
|
|
1110
|
+
self.n_params = kernel.n_params(K, self.D)
|
|
1111
|
+
self._prior_only: ResidualProblem | None = None
|
|
1112
|
+
self._grid = axis_grid(self.R)
|
|
1113
|
+
self._last: tuple[Array, tuple[Any, ...]] | None = None
|
|
1114
|
+
self._x_sq = float(np.sum(self.X * self.X))
|
|
1115
|
+
self._identity: bool | None = None # decided at the first point
|
|
1116
|
+
# The data go to the engine once; every evaluation sends new weights.
|
|
1117
|
+
self.engine.set(self.X, np.zeros((K, self.X.shape[1])))
|
|
1118
|
+
|
|
1119
|
+
def _unpack(self, x: ArrayLike) -> tuple[Array, Array]:
|
|
1120
|
+
x = np.asarray(x, dtype=np.float64).ravel()
|
|
1121
|
+
n = self.Kc * self.D
|
|
1122
|
+
return x[:n].reshape(self.Kc, self.D), x[n:]
|
|
1123
|
+
|
|
1124
|
+
@cached_property
|
|
1125
|
+
def _x32(self) -> NDArray[np.float32]:
|
|
1126
|
+
"""The data in float32, for the curvature products of mode 'fast'."""
|
|
1127
|
+
return self.X.astype(np.float32)
|
|
1128
|
+
|
|
1129
|
+
def _weights(self, F: Array) -> tuple[Array, Array, Array]:
|
|
1130
|
+
"""`gram_solve` with this problem's data and ``beta``."""
|
|
1131
|
+
return gram_solve(F, self.X, self.beta)
|
|
1132
|
+
|
|
1133
|
+
def _at(self, x: ArrayLike) -> tuple[Any, ...]:
|
|
1134
|
+
"""Centers, widths, `factors` (V, K), weights and gram inverse at ``x``
|
|
1135
|
+
(`_weights`), and the data and ridge terms of ``phi`` from the identity
|
|
1136
|
+
``||X - F W||**2 + beta ||W||**2 = ||X||**2 - <F^T X, W>`` (None where
|
|
1137
|
+
the problem uses the residual form; see `IDENTITY_MIN_FRACTION`). The
|
|
1138
|
+
last point's are kept: `bounded_lm` assembles the Hessian at the point
|
|
1139
|
+
it has just evaluated, and reuses them unchanged."""
|
|
1140
|
+
x = np.array(x, dtype=np.float64).ravel()
|
|
1141
|
+
if self._last is not None and np.array_equal(self._last[0], x):
|
|
1142
|
+
return self._last[1]
|
|
1143
|
+
C, w = self._unpack(x)
|
|
1144
|
+
F = x_factors(self.R, C, w, self.K, self.kernel, self._grid)
|
|
1145
|
+
W, inv, B = self._weights(F)
|
|
1146
|
+
objective = self._x_sq - float(np.sum(B * W))
|
|
1147
|
+
# The form is chosen at the first point only. A solve that starts far
|
|
1148
|
+
# off and ends near an exact fit keeps the identity, whose rounding then
|
|
1149
|
+
# dominates the cost bounded_lm reports (a noiseless 'ols' fit from a
|
|
1150
|
+
# far start: 7.9e-12 against a true 5.8e-23). TFA uses only the solver's
|
|
1151
|
+
# x, not its cost (`htfa.tfa.TFA._iterate_stage`). With 'rr' the ridge
|
|
1152
|
+
# term keeps the fraction away from 0: 1.2e-3 to 4.7e-3 at the true
|
|
1153
|
+
# parameters of noiseless synthetic data (9 cases, V = 900 to 8000).
|
|
1154
|
+
if self._identity is None:
|
|
1155
|
+
self._identity = objective >= IDENTITY_MIN_FRACTION * self._x_sq > 0
|
|
1156
|
+
data = 0.5 * self.s**2 * objective if self._identity else None
|
|
1157
|
+
out = (C, w, F, W, inv, data)
|
|
1158
|
+
self._last = (x, out)
|
|
1159
|
+
return out
|
|
1160
|
+
|
|
1161
|
+
def weights(self, x: ArrayLike) -> Array:
|
|
1162
|
+
"""Ridge weights (K, T) at ``x`` (see `_weights`)."""
|
|
1163
|
+
W: Array = self._at(x)[3]
|
|
1164
|
+
return W
|
|
1165
|
+
|
|
1166
|
+
def _prior_cost(self, C: Array, w: Array) -> float:
|
|
1167
|
+
if self.prior is None:
|
|
1168
|
+
return 0.0
|
|
1169
|
+
# A one-voxel problem on its own engine carries the prior terms.
|
|
1170
|
+
if self._prior_only is None:
|
|
1171
|
+
self._prior_only = ResidualProblem(
|
|
1172
|
+
self.X[:1, :1],
|
|
1173
|
+
np.zeros((self.K, 1)),
|
|
1174
|
+
self.R[:1],
|
|
1175
|
+
NumpyEngine(1),
|
|
1176
|
+
self.prior,
|
|
1177
|
+
kernel=self.kernel,
|
|
1178
|
+
)
|
|
1179
|
+
return self._prior_only._prior_terms(C, w, "linear", derivatives=False)[0]
|
|
1180
|
+
|
|
1181
|
+
def cost(self, x: ArrayLike, loss: str = "linear") -> float:
|
|
1182
|
+
"""``phi(x)``, in the form `cost_grad_hess` uses (so that the solver
|
|
1183
|
+
compares like with like): from ``||X||**2 - <F^T X, W>``, or from the
|
|
1184
|
+
data residual ``X - F W`` on the engine (see `_at`)."""
|
|
1185
|
+
C, w, F, W, _, data = self._at(x)
|
|
1186
|
+
if data is None:
|
|
1187
|
+
self.engine.set_weights(W)
|
|
1188
|
+
data = self.engine.data_cost(F, self.s, "linear")
|
|
1189
|
+
data += 0.5 * self.s**2 * self.beta * float(np.sum(W * W))
|
|
1190
|
+
return float(data) + self._prior_cost(C, w)
|
|
1191
|
+
|
|
1192
|
+
def column_norms(self, x: ArrayLike) -> Array:
|
|
1193
|
+
"""Fixed-weight Jacobian column norms at ``x`` (for ``x_scale='jac'``)."""
|
|
1194
|
+
inner = ResidualProblem(
|
|
1195
|
+
self.X, self.weights(x), self.R, self.engine, self.prior,
|
|
1196
|
+
data_on_engine=True, kernel=self.kernel,
|
|
1197
|
+
) # fmt: skip
|
|
1198
|
+
return inner.column_norms(x)
|
|
1199
|
+
|
|
1200
|
+
def cost_grad_hess(
|
|
1201
|
+
self, x: ArrayLike, loss: str = "linear", mode: str = "exact"
|
|
1202
|
+
) -> tuple[float, Array, Array, Array]:
|
|
1203
|
+
"""``phi``, its gradient, Gauss-Newton matrix and Hessian (P, P). In
|
|
1204
|
+
``mode='fast'`` the products ``G G^T``, ``F G^T`` and ``G X`` of the
|
|
1205
|
+
curvature are formed in float32 (`curvature_operand`)."""
|
|
1206
|
+
if loss != "linear":
|
|
1207
|
+
raise ValueError(f"ProjectedProblem needs the linear loss, got {loss!r}")
|
|
1208
|
+
C, w, F_vk, W, Mi, data = self._at(x)
|
|
1209
|
+
if not Mi.any():
|
|
1210
|
+
# bounded_lm assembles the Hessian at its start and at accepted
|
|
1211
|
+
# points only; a step to such a point (cost 0.5 s**2 ||X||**2, the
|
|
1212
|
+
# largest the objective takes) is never accepted.
|
|
1213
|
+
raise ValueError(
|
|
1214
|
+
f"all {self.K} factors are 0 at every voxel at this start (gram "
|
|
1215
|
+
"eigenvalues below GRAM_FLOOR): its widths are too small or its "
|
|
1216
|
+
"centers too far from the voxels; raise lower_ratio or start "
|
|
1217
|
+
"elsewhere"
|
|
1218
|
+
)
|
|
1219
|
+
K, D = self.K, self.D
|
|
1220
|
+
P, s2 = self.n_params, self.s**2
|
|
1221
|
+
derivatives = x_derivatives(self.R, C, w, K, self.kernel, self._grid, F_vk)
|
|
1222
|
+
if self.kernel.plain_rbf:
|
|
1223
|
+
_, F, G = derivatives
|
|
1224
|
+
else:
|
|
1225
|
+
F, G = derivatives.F, derivatives.G
|
|
1226
|
+
A = G.shape[1]
|
|
1227
|
+
inner = ResidualProblem(
|
|
1228
|
+
self.X, W, self.R, self.engine, self.prior, data_on_engine=True,
|
|
1229
|
+
kernel=self.kernel,
|
|
1230
|
+
) # fmt: skip
|
|
1231
|
+
cost, grad, gn, hess = inner.cost_grad_hess(x, "linear", derivatives, mode)
|
|
1232
|
+
if data is None:
|
|
1233
|
+
cost += 0.5 * s2 * self.beta * float(np.sum(W * W))
|
|
1234
|
+
else:
|
|
1235
|
+
cost = data + self._prior_cost(C, w)
|
|
1236
|
+
G2 = curvature_operand(G.reshape(K * A, -1), mode) # [(k, a), v]
|
|
1237
|
+
X = self._x32 if mode == "fast" else self.X
|
|
1238
|
+
# (K, KA): P2[l, (k, a)] = sum_v F[l, v] G[k, a, v]
|
|
1239
|
+
P2 = np.asarray(curvature_operand(F, mode) @ G2.T, dtype=np.float64)
|
|
1240
|
+
Bt = G2 @ X - P2.T @ W # (KA, T): G_ka^T (X - F W), float64
|
|
1241
|
+
Y = Mi @ P2 # M^-1 P2
|
|
1242
|
+
WW = W @ W.T
|
|
1243
|
+
rows = np.repeat(np.arange(K), A) # factor k of each (k, a)
|
|
1244
|
+
term1 = WW[np.ix_(rows, rows)] * (P2.T @ Y)
|
|
1245
|
+
Z = (W @ Bt.T)[rows] # Z[(k, a), (k', b)] = W_k . Bt_k'b
|
|
1246
|
+
term2 = Z * Y[rows].T # times (M^-1 P_ka)[k']
|
|
1247
|
+
term4 = Mi[np.ix_(rows, rows)] * (Bt @ Bt.T)
|
|
1248
|
+
pos = param_positions(K, D, self.kernel.n_components)
|
|
1249
|
+
g1 = np.empty((P, P))
|
|
1250
|
+
g1[np.ix_(pos, pos)] = s2 * term1
|
|
1251
|
+
corr = np.empty((P, P))
|
|
1252
|
+
corr[np.ix_(pos, pos)] = s2 * (term1 - term2 - term2.T + term4)
|
|
1253
|
+
gn = gn - g1
|
|
1254
|
+
hess = hess - corr
|
|
1255
|
+
return cost, grad, 0.5 * (gn + gn.T), 0.5 * (hess + hess.T)
|
|
1256
|
+
|
|
1257
|
+
|
|
1258
|
+
def _check_finite(cost: float, g: Array, gn: Array, x: Array) -> None:
|
|
1259
|
+
if not (np.isfinite(cost) and np.all(np.isfinite(g)) and np.all(np.isfinite(gn))):
|
|
1260
|
+
raise FloatingPointError(
|
|
1261
|
+
"bounded-lm: non-finite cost, gradient or Gauss-Newton matrix at "
|
|
1262
|
+
f"x = {np.array2string(x, precision=4, threshold=12)}; check the data "
|
|
1263
|
+
"and weights for NaN/Inf"
|
|
1264
|
+
)
|
|
1265
|
+
|
|
1266
|
+
|
|
1267
|
+
def _finite_lm_scale(scale: Array, g: Array, gn: Array, hess: Array) -> Array:
|
|
1268
|
+
"""Use unit scaling only where the scaled local model is unrepresentable.
|
|
1269
|
+
|
|
1270
|
+
Vanishing mixture components can have tiny nonzero data-Jacobian norms
|
|
1271
|
+
while a center prior contributes finite curvature at its zero residual.
|
|
1272
|
+
Their inverse norms then overflow the scaled curvature. The scale changes
|
|
1273
|
+
the optimization metric, not the model, bounds, or mixture weights.
|
|
1274
|
+
"""
|
|
1275
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
1276
|
+
bad = ~np.isfinite(scale * g)
|
|
1277
|
+
for matrix in (gn, hess):
|
|
1278
|
+
if not np.isfinite(matrix).all():
|
|
1279
|
+
continue # The solver separately handles nonfinite raw curvature.
|
|
1280
|
+
scaled = scale[:, None] * matrix * scale[None, :]
|
|
1281
|
+
bad |= ~np.isfinite(scaled).all(axis=0) | ~np.isfinite(scaled).all(axis=1)
|
|
1282
|
+
reset = bad & (scale > 1)
|
|
1283
|
+
if np.any(reset):
|
|
1284
|
+
scale = scale.copy()
|
|
1285
|
+
scale[reset] = 1.0
|
|
1286
|
+
return scale
|
|
1287
|
+
|
|
1288
|
+
|
|
1289
|
+
def _lm_initial_damping(scale: Array, gn: Array) -> float:
|
|
1290
|
+
"""Initial damping, without overflowing an otherwise finite scale² * Hjj."""
|
|
1291
|
+
diagonal = np.diag(gn)
|
|
1292
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
1293
|
+
scaled = scale**2 * diagonal
|
|
1294
|
+
bad = ~np.isfinite(scaled)
|
|
1295
|
+
# Preserve ordinary arithmetic exactly; reorder only failed products.
|
|
1296
|
+
scaled[bad] = scale[bad] * (diagonal[bad] * scale[bad])
|
|
1297
|
+
return LM_TAU * max(float(np.max(scaled)), EPS)
|
|
1298
|
+
|
|
1299
|
+
|
|
1300
|
+
def _vector_norm(vector: Array) -> float:
|
|
1301
|
+
"""Euclidean norm with a scaled BLAS fallback for overflowing dot products."""
|
|
1302
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
1303
|
+
try:
|
|
1304
|
+
value = float(np.linalg.norm(vector))
|
|
1305
|
+
except FloatingPointError:
|
|
1306
|
+
value = np.inf
|
|
1307
|
+
if not np.isfinite(value):
|
|
1308
|
+
# BLAS nrm2 scales its accumulation, avoiding intermediate squares
|
|
1309
|
+
# outside float64 range when the norm itself remains representable.
|
|
1310
|
+
value = float(scipy.linalg.norm(vector))
|
|
1311
|
+
return value
|
|
1312
|
+
|
|
1313
|
+
|
|
1314
|
+
def bounded_lm(
|
|
1315
|
+
problem: "ResidualProblem | ProjectedProblem",
|
|
1316
|
+
x0: Array,
|
|
1317
|
+
bounds: tuple[Array, Array],
|
|
1318
|
+
loss: str,
|
|
1319
|
+
scale: Array,
|
|
1320
|
+
max_nfev: int | None = None,
|
|
1321
|
+
mode: str = "exact",
|
|
1322
|
+
trace: list[dict[str, Any]] | None = None,
|
|
1323
|
+
) -> tuple[Array, float, int, int]:
|
|
1324
|
+
"""Bounded Levenberg-Marquardt (damped Newton) on the structured Hessian.
|
|
1325
|
+
|
|
1326
|
+
Minimizes ``problem.cost(x, loss)`` over the box ``bounds`` from ``x0``
|
|
1327
|
+
(clipped into the box). Every iteration assembles the gradient ``g`` and the
|
|
1328
|
+
Hessian ``H`` (`ResidualProblem.cost_grad_hess`, P = len(x0) unknowns),
|
|
1329
|
+
fixes the variables at a bound whose gradient points out of the box, and
|
|
1330
|
+
solves ``(H_ff + lam diag(1 / scale_f**2)) p = -g_f`` on the free ones by
|
|
1331
|
+
Cholesky (``scale`` plays scipy's ``x_scale`` role; where the damped
|
|
1332
|
+
matrix is not positive definite, ``lam`` grows until it is, by the rule
|
|
1333
|
+
of each mode described at `FAILED_FACTOR_GROWTH`). The step
|
|
1334
|
+
``clip(x + p) - x`` is accepted only if it lowers the cost; ``lam`` follows
|
|
1335
|
+
Nielsen's rule (divided by up to 3 on success, multiplied by 2, 4, 8, ...
|
|
1336
|
+
on consecutive rejected steps).
|
|
1337
|
+
|
|
1338
|
+
Stopping rules, with scipy's defaults: ``ftol`` (as scipy: an accepted step
|
|
1339
|
+
with ratio > 0.25 lowered the cost by less than ``FTOL`` times the cost
|
|
1340
|
+
including ``problem.cost_offset``), ``xtol`` (as scipy: a trial step shorter
|
|
1341
|
+
than ``XTOL * (XTOL + ||x||)``), ``gtol`` (the largest unscaled gradient
|
|
1342
|
+
entry over the free variables is below ``GTOL``; scipy's trf instead
|
|
1343
|
+
multiplies the gradient by its Coleman-Li distance-to-bound vector) and
|
|
1344
|
+
``max_nfev`` (cost evaluations, default ``100 * P`` as for scipy's trf).
|
|
1345
|
+
Finite-precision engines (float32 on MPS) use ``ftol`` no smaller than
|
|
1346
|
+
`ftol_for` of their dtype.
|
|
1347
|
+
|
|
1348
|
+
``mode`` (see `SOLVER_MODES`) chooses the step model where the Hessian is
|
|
1349
|
+
not positive definite on the free variables. ``'exact'`` then takes the
|
|
1350
|
+
Gauss-Newton step, damped by ``lam``. ``'fast'`` keeps the Hessian and
|
|
1351
|
+
raises ``lam`` until the damped matrix is positive definite. ``'fast'``
|
|
1352
|
+
also forms the largest curvature products of the linear loss in float32
|
|
1353
|
+
(`curvature_operand`). Both modes minimize the same cost, in float64; they
|
|
1354
|
+
can end at different local minima.
|
|
1355
|
+
|
|
1356
|
+
``trace`` (a list, for diagnostics) receives one dict per accepted step:
|
|
1357
|
+
``indefinite`` (the Hessian was not positive definite on the free
|
|
1358
|
+
variables), ``model`` (``'newton'`` or ``'gauss-newton'``), ``lam`` (the
|
|
1359
|
+
damping of the step) and ``cholesky_failures`` (damped factorizations that
|
|
1360
|
+
failed within the step, across its rejected trials). Checking
|
|
1361
|
+
definiteness costs one extra factorization per step in ``'fast'`` mode,
|
|
1362
|
+
so it is done only when ``trace`` is given.
|
|
1363
|
+
|
|
1364
|
+
Raises
|
|
1365
|
+
------
|
|
1366
|
+
FloatingPointError
|
|
1367
|
+
When the cost, gradient or Gauss-Newton matrix is not finite (a
|
|
1368
|
+
non-finite Hessian alone falls back to the Gauss-Newton model).
|
|
1369
|
+
ValueError
|
|
1370
|
+
For a ``mode`` not in `SOLVER_MODES`.
|
|
1371
|
+
|
|
1372
|
+
Returns
|
|
1373
|
+
-------
|
|
1374
|
+
x : ndarray, shape (P,)
|
|
1375
|
+
Solution.
|
|
1376
|
+
cost : float
|
|
1377
|
+
``problem.cost(x, loss)`` (without ``cost_offset``).
|
|
1378
|
+
status : int
|
|
1379
|
+
0 ``max_nfev``, 1 ``gtol``, 2 ``ftol``, 3 ``xtol``, 4 ``ftol`` and ``xtol``
|
|
1380
|
+
(scipy's codes).
|
|
1381
|
+
nfev : int
|
|
1382
|
+
Cost evaluations, Hessian assemblies included.
|
|
1383
|
+
"""
|
|
1384
|
+
if mode not in SOLVER_MODES:
|
|
1385
|
+
raise ValueError(f"mode must be one of {SOLVER_MODES}, got {mode!r}")
|
|
1386
|
+
lb, ub = bounds
|
|
1387
|
+
x = np.clip(np.asarray(x0, dtype=np.float64), lb, ub)
|
|
1388
|
+
max_nfev = 100 * x.size if max_nfev is None else max_nfev
|
|
1389
|
+
ftol = ftol_for(problem.engine.eps)
|
|
1390
|
+
cost, g, gn, hess = problem.cost_grad_hess(x, loss, mode=mode)
|
|
1391
|
+
nfev, nu = 1, 2.0
|
|
1392
|
+
lam = 0.0
|
|
1393
|
+
while True:
|
|
1394
|
+
_check_finite(cost, g, gn, x)
|
|
1395
|
+
adjusted = _finite_lm_scale(scale, g, gn, hess)
|
|
1396
|
+
if nfev == 1 or adjusted is not scale:
|
|
1397
|
+
scale = adjusted
|
|
1398
|
+
lam, nu = _lm_initial_damping(scale, gn), 2.0
|
|
1399
|
+
free = ~(((x <= lb) & (g > 0)) | ((x >= ub) & (g < 0)))
|
|
1400
|
+
if not free.any() or np.max(np.abs(g[free])) < GTOL:
|
|
1401
|
+
return x, cost, 1, nfev
|
|
1402
|
+
d = scale[free]
|
|
1403
|
+
g_s = d * g[free]
|
|
1404
|
+
# 'exact': Newton model where the Hessian is positive definite on the
|
|
1405
|
+
# free variables, else the Gauss-Newton model (damping alone does not
|
|
1406
|
+
# bound a step along negative curvature, which can jump to another
|
|
1407
|
+
# basin). 'fast': Newton model wherever the Hessian is finite.
|
|
1408
|
+
H = hess
|
|
1409
|
+
H_s = d[:, None] * hess[np.ix_(free, free)] * d[None, :]
|
|
1410
|
+
indefinite = False
|
|
1411
|
+
if trace is not None:
|
|
1412
|
+
try:
|
|
1413
|
+
scipy.linalg.cho_factor(H_s)
|
|
1414
|
+
except (np.linalg.LinAlgError, ValueError):
|
|
1415
|
+
indefinite = True
|
|
1416
|
+
try:
|
|
1417
|
+
if mode == "exact":
|
|
1418
|
+
scipy.linalg.cho_factor(H_s) # ValueError if not finite
|
|
1419
|
+
elif not np.all(np.isfinite(H_s)):
|
|
1420
|
+
raise ValueError("non-finite Hessian")
|
|
1421
|
+
except (np.linalg.LinAlgError, ValueError):
|
|
1422
|
+
H = gn
|
|
1423
|
+
H_s = d[:, None] * gn[np.ix_(free, free)] * d[None, :]
|
|
1424
|
+
failures = 0
|
|
1425
|
+
while True:
|
|
1426
|
+
if nfev >= max_nfev:
|
|
1427
|
+
return x, cost, 0, nfev
|
|
1428
|
+
try:
|
|
1429
|
+
factor = scipy.linalg.cho_factor(H_s + lam * np.eye(d.size))
|
|
1430
|
+
except np.linalg.LinAlgError:
|
|
1431
|
+
# See FAILED_FACTOR_GROWTH: 'fast' multiplies by 2**k at the
|
|
1432
|
+
# step's k-th failure; 'exact' keeps the earlier rule.
|
|
1433
|
+
failures += 1
|
|
1434
|
+
if mode == "fast":
|
|
1435
|
+
lam *= FAILED_FACTOR_GROWTH**failures
|
|
1436
|
+
else:
|
|
1437
|
+
lam, nu = lam * nu, nu * 2.0
|
|
1438
|
+
continue
|
|
1439
|
+
p = np.zeros_like(x)
|
|
1440
|
+
p[free] = -d * scipy.linalg.cho_solve(factor, g_s)
|
|
1441
|
+
x_new = np.clip(x + p, lb, ub)
|
|
1442
|
+
step = x_new - x
|
|
1443
|
+
predicted = -float(g @ step + 0.5 * step @ H @ step)
|
|
1444
|
+
cost_new = problem.cost(x_new, loss)
|
|
1445
|
+
nfev += 1
|
|
1446
|
+
actual = cost - cost_new
|
|
1447
|
+
ratio = float(actual / predicted) if predicted > 0 else 0.0
|
|
1448
|
+
# Relative to the full objective: the compressed problem's cost
|
|
1449
|
+
# excludes cost_offset.
|
|
1450
|
+
ftol_ok = actual < ftol * (cost + problem.cost_offset) and ratio > 0.25
|
|
1451
|
+
xtol_ok = _vector_norm(step) < XTOL * (XTOL + _vector_norm(x))
|
|
1452
|
+
accepted = ratio > 0
|
|
1453
|
+
if accepted and trace is not None:
|
|
1454
|
+
trace.append(
|
|
1455
|
+
{
|
|
1456
|
+
"indefinite": indefinite,
|
|
1457
|
+
"model": "newton" if H is hess else "gauss-newton",
|
|
1458
|
+
"lam": lam,
|
|
1459
|
+
"cholesky_failures": failures,
|
|
1460
|
+
}
|
|
1461
|
+
)
|
|
1462
|
+
if accepted:
|
|
1463
|
+
x = x_new
|
|
1464
|
+
lam *= max(1.0 / 3.0, 1.0 - (2.0 * ratio - 1.0) ** 3)
|
|
1465
|
+
nu = 2.0
|
|
1466
|
+
else:
|
|
1467
|
+
lam, nu = lam * nu, nu * 2.0
|
|
1468
|
+
if ftol_ok or xtol_ok:
|
|
1469
|
+
status = 4 if ftol_ok and xtol_ok else (2 if ftol_ok else 3)
|
|
1470
|
+
return x, cost_new if accepted else cost, status, nfev
|
|
1471
|
+
if accepted:
|
|
1472
|
+
break
|
|
1473
|
+
cost, g, gn, hess = problem.cost_grad_hess(x, loss, mode=mode)
|
|
1474
|
+
nfev += 1
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
def solve_centers_widths(
|
|
1478
|
+
problem: "ResidualProblem | ProjectedProblem",
|
|
1479
|
+
x0: Array,
|
|
1480
|
+
bounds: tuple[Array, Array],
|
|
1481
|
+
method: str = "bounded-lm",
|
|
1482
|
+
loss: str = "soft_l1",
|
|
1483
|
+
x_scale: str | Array = "jac",
|
|
1484
|
+
max_nfev: int | None = None,
|
|
1485
|
+
mode: str = "exact",
|
|
1486
|
+
) -> tuple[Array, float]:
|
|
1487
|
+
"""Bounded nonlinear least squares for ``x = [centers.ravel(), widths]``.
|
|
1488
|
+
|
|
1489
|
+
``method='bounded-lm'`` runs `bounded_lm`; ``'trf'`` and ``'dogbox'`` run
|
|
1490
|
+
``scipy.optimize.least_squares`` with the matrix-free Jacobian and LSMR. Both
|
|
1491
|
+
minimize the same objective. ``x_scale="jac"`` uses
|
|
1492
|
+
``1 / problem.column_norms(x0)`` (1 where a norm is 0), since scipy cannot
|
|
1493
|
+
compute it for a matrix-free Jacobian. ``mode`` is `bounded_lm`'s (no
|
|
1494
|
+
effect on ``'trf'`` and ``'dogbox'``). Returns the solution and its cost
|
|
1495
|
+
plus ``problem.cost_offset``.
|
|
1496
|
+
"""
|
|
1497
|
+
if method not in NLSS_METHODS:
|
|
1498
|
+
raise ValueError(f"method must be one of {NLSS_METHODS}, got {method!r}")
|
|
1499
|
+
if (method == "varpro") != isinstance(problem, ProjectedProblem):
|
|
1500
|
+
raise ValueError("method 'varpro' takes a ProjectedProblem and only it")
|
|
1501
|
+
if isinstance(x_scale, str):
|
|
1502
|
+
if x_scale != "jac":
|
|
1503
|
+
raise ValueError(f"x_scale must be 'jac' or an array, got {x_scale!r}")
|
|
1504
|
+
norms = problem.column_norms(x0)
|
|
1505
|
+
x_scale = np.divide(1.0, norms, out=np.ones_like(norms), where=norms > 0)
|
|
1506
|
+
if method in ("bounded-lm", "varpro"):
|
|
1507
|
+
x, cost, _, _ = bounded_lm(
|
|
1508
|
+
problem,
|
|
1509
|
+
x0,
|
|
1510
|
+
bounds,
|
|
1511
|
+
loss,
|
|
1512
|
+
np.asarray(x_scale, dtype=np.float64),
|
|
1513
|
+
max_nfev,
|
|
1514
|
+
mode,
|
|
1515
|
+
)
|
|
1516
|
+
return x, cost + problem.cost_offset
|
|
1517
|
+
assert isinstance(problem, ResidualProblem)
|
|
1518
|
+
result = least_squares(
|
|
1519
|
+
problem.residual,
|
|
1520
|
+
x0,
|
|
1521
|
+
jac=problem.jacobian,
|
|
1522
|
+
bounds=bounds,
|
|
1523
|
+
method=method,
|
|
1524
|
+
loss=loss,
|
|
1525
|
+
x_scale=x_scale,
|
|
1526
|
+
tr_solver="lsmr",
|
|
1527
|
+
tr_options={"atol": LSMR_TOL, "btol": LSMR_TOL},
|
|
1528
|
+
max_nfev=max_nfev,
|
|
1529
|
+
)
|
|
1530
|
+
return np.asarray(result.x, dtype=np.float64), float(
|
|
1531
|
+
result.cost
|
|
1532
|
+
) + problem.cost_offset
|