registration1d 0.0.2__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.
@@ -0,0 +1,63 @@
1
+ '''
2
+ registration1d: linear and nonlinear registration of one-dimensional data.
3
+
4
+ Quick start:
5
+
6
+ The recommended import convention is import registration1d as reg1d
7
+
8
+ >>> import registration1d as reg1d
9
+ >>> yi = reg1d.register_linear( y, n=101 ).y # (J,101) linearly registered
10
+ >>> yr, wf = reg1d.register_srsf( yi, max_iter=5 ) # nonlinearly registered + warps
11
+
12
+ where y is a (J,Q) array or a list of J observations of different lengths.
13
+
14
+ Registration methods (all return a RegistrationResult):
15
+
16
+ register_linear interpolate to a common grid
17
+ register_shift time shift (linear)
18
+ register_affine time shift + uniform stretch (linear)
19
+ register_srsf elastic / square-root slope function (nonlinear)
20
+ register_dtw dynamic time warping (nonlinear)
21
+ register_landmark landmark registration (nonlinear)
22
+ register_continuous penalised least-squares smooth warps (nonlinear)
23
+ register_bayes Bayesian registration with posterior warp samples (nonlinear)
24
+ register_pairwise pairwise synchronisation, template-free (nonlinear)
25
+ register_sim self-modelling / shape-invariant model (nonlinear)
26
+
27
+ Copyright (C) 2026 Todd Pataky
28
+
29
+ This program is free software: you can redistribute it and/or modify it
30
+ under the terms of the GNU General Public License as published by the
31
+ Free Software Foundation, either version 3 of the License, or (at your
32
+ option) any later version.
33
+
34
+ This program is distributed in the hope that it will be useful, but
35
+ WITHOUT ANY WARRANTY; without even the implied warranty of
36
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
37
+ Public License for more details.
38
+
39
+ You should have received a copy of the GNU General Public License along
40
+ with this program. If not, see <https://www.gnu.org/licenses/>.
41
+ '''
42
+
43
+ __version__ = "0.0.2"
44
+
45
+ from . import warp
46
+ from . import linear
47
+ from . import srsf
48
+ from . import dtw
49
+ from . import landmark
50
+ from . import continuous
51
+ from . import bayes
52
+ from . import pairwise
53
+ from . import sim
54
+ from . import realtime
55
+ from . import reg
56
+ from . import plot
57
+ from ._support import get_config
58
+
59
+ from .warp import Warp1D, Warp1DList, random_warp
60
+ from .srsf import ConvergenceWarning
61
+ from .reg import (RegistrationResult, LinearRegistrationResult, NonlinearRegistrationResult,
62
+ register, register_linear, register_shift, register_affine, register_srsf, register_dtw,
63
+ register_landmark, register_continuous, register_bayes, register_pairwise, register_sim)
@@ -0,0 +1,170 @@
1
+
2
+ '''
3
+ System information for bug reports.
4
+
5
+ A bug report is actionable only when the versions that produced it are known.
6
+ "registration1d.get_config" collects them in one call in the layout the
7
+ report form expects.
8
+
9
+ The machine's name, the account name and the file paths that contain them are
10
+ not collected because a bug report is public.
11
+ '''
12
+
13
+ # Copyright (C) 2026 Todd Pataky
14
+
15
+
16
+ import os
17
+ import platform
18
+ import sys
19
+
20
+
21
+ # Packages reported for every configuration in this order.
22
+ _PACKAGES = ('registration1d', 'numpy', 'scipy', 'matplotlib')
23
+
24
+
25
+ def _version(name):
26
+ '''
27
+ Version of a package, preferring the copy that is actually running.
28
+
29
+ An imported module answers for itself through "__version__". That is the
30
+ version of the code that produced the result being reported. Installation
31
+ metadata is consulted only for packages that are not imported so that
32
+ matplotlib's version is reported without importing matplotlib. Metadata
33
+ describes what is installed. That differs from the running copy when a
34
+ source tree is run alongside an older release.
35
+ '''
36
+ mod = sys.modules.get(name)
37
+ v = None if (mod is None) else getattr(mod, '__version__', None)
38
+ if v is not None:
39
+ return str(v)
40
+ from importlib.metadata import PackageNotFoundError, version
41
+ try:
42
+ return version(name)
43
+ except PackageNotFoundError:
44
+ return 'not installed'
45
+
46
+
47
+ def _install_kind():
48
+ '''
49
+ Whether this copy was installed or is being run from a source tree.
50
+
51
+ Decided from the location of this file. The location itself is not reported
52
+ because it usually contains the account name.
53
+ '''
54
+ parts = os.path.abspath( __file__ ).split( os.sep )
55
+ inst = ('site-packages' in parts) or ('dist-packages' in parts)
56
+ return 'installed' if inst else 'source'
57
+
58
+
59
+ class Config(object):
60
+ '''
61
+ A snapshot of the versions and the platform a result was produced under.
62
+
63
+ Printing it gives the block that the bug report form asks for. The same
64
+ values are available through "asdict".
65
+ '''
66
+
67
+ def __init__(self, packages=None):
68
+ names = list( _PACKAGES if (packages is None) else packages )
69
+ #: Reported package names in order.
70
+ self.names = names
71
+ #: Version string per package name (``"not installed"`` when absent).
72
+ self.packages = dict( [(s, _version(s)) for s in names] )
73
+ #: Python version and implementation.
74
+ self.python = '%d.%d.%d (%s)' % (sys.version_info[:3]
75
+ + (platform.python_implementation(),))
76
+ #: Operating system and machine.
77
+ self.platform = platform.platform()
78
+ #: ``"installed"`` (from site-packages) or ``"source"`` (a checkout).
79
+ self.install = _install_kind()
80
+
81
+ def __repr__(self):
82
+ return self.asstr()
83
+
84
+ def _rows(self):
85
+ rows = [(s, self.packages[s]) for s in self.names]
86
+ rows.append( ('python', self.python) )
87
+ rows.append( ('platform', self.platform) )
88
+ rows.append( ('install', self.install) )
89
+ return rows
90
+
91
+ def asdict(self):
92
+ '''
93
+ Same values as a dictionary.
94
+
95
+ :Returns:
96
+
97
+ - A dictionary with one entry per reported package plus ``python``,
98
+ ``platform`` and ``install``
99
+
100
+ :Example:
101
+
102
+ >>> import registration1d as reg1d
103
+ >>> config = reg1d.get_config()
104
+ >>> print( sorted( config.asdict().keys() )[:4] )
105
+ ['install', 'matplotlib', 'numpy', 'platform']
106
+ '''
107
+ d = dict( self.packages )
108
+ d['python'] = self.python
109
+ d['platform'] = self.platform
110
+ d['install'] = self.install
111
+ return d
112
+
113
+ def asstr(self):
114
+ '''
115
+ Printed form with one "name value" pair per line and aligned columns.
116
+
117
+ :Returns:
118
+
119
+ - The block as a string. ``print( config )`` prints the same block
120
+
121
+ :Example:
122
+
123
+ >>> import registration1d as reg1d
124
+ >>> config = reg1d.get_config()
125
+ >>> print( config.asstr().splitlines()[0].split()[0] )
126
+ registration1d
127
+ '''
128
+ rows = self._rows()
129
+ n = max( [len(k) for k, v in rows] )
130
+ return '\n'.join( ['%-*s %s' % (n, k, v) for k, v in rows] )
131
+
132
+
133
+ def get_config(packages=None):
134
+ '''
135
+ Versions and platform for a bug report.
136
+
137
+ Run this and paste the result into the "Environment" field of the bug
138
+ report form.
139
+
140
+ :Parameters:
141
+
142
+ - *packages* --- sequence of additional package names to report (default
143
+ None)
144
+
145
+ :Returns:
146
+
147
+ - A **Config** object. Printing it gives the block that the form expects.
148
+ Its ``asdict`` method gives the same values as a dictionary
149
+
150
+ :Example:
151
+
152
+ >>> import registration1d as reg1d
153
+ >>> reg1d.get_config()
154
+ registration1d 0.0.2
155
+ numpy 2.1.0
156
+ scipy 1.14.0
157
+ matplotlib 3.9.0
158
+ python 3.12.4 (CPython)
159
+ platform macOS-15.1-arm64-arm-64bit
160
+ install installed
161
+
162
+ :Note:
163
+
164
+ - The machine name, the account name and file paths are not reported
165
+ because a bug report is public.
166
+ '''
167
+ names = list( _PACKAGES )
168
+ if packages is not None:
169
+ names += [s for s in packages if s not in names]
170
+ return Config( names )
@@ -0,0 +1,243 @@
1
+ '''
2
+ Bayesian registration.
3
+
4
+ A simplified implementation of the Bayesian pairwise registration model of
5
+
6
+ Cheng W, Dryden IL, Huang X (2016). Bayesian registration of functions
7
+ and curves. Bayesian Analysis 11: 447-475.
8
+ Lu Y, Herbei R, Kurtek S (2017). Bayesian registration of functions
9
+ with a Gaussian process prior. Journal of Computational and
10
+ Graphical Statistics 26: 894-904.
11
+
12
+ Model
13
+ -----
14
+ Let q1 be the SRSF of the template and q2 the SRSF of the observation to be
15
+ registered. The warp gamma is parameterised through a tangent vector v at
16
+ the identity of the unit sphere of square-root slopes,
17
+
18
+ v(t) = sum_k c_k phi_k(t), phi_k = sqrt(2) cos(k pi t), k = 1..K
19
+ psi = cos(|v|) + sin(|v|) v / |v| (exponential map at psi = 1)
20
+ gamma = int_0^t psi(s)^2 ds
21
+
22
+ so that every coefficient vector c gives a valid warp. The likelihood is a
23
+ Gaussian error model in SRSF space,
24
+
25
+ q1 = (q2 o gamma) sqrt(gamma') + epsilon, epsilon ~ N(0, sigma^2)
26
+
27
+ with prior c_k ~ N(0, tau^2 / k^2) (smooth warps a priori; Cheng et al. use
28
+ a Z-mixture prior, Lu et al. a Gaussian-process prior of which this is a
29
+ finite-basis special case) and sigma^2 ~ InverseGamma(a, b).
30
+
31
+ Inference
32
+ ---------
33
+ c is sampled with the preconditioned Crank-Nicolson (pCN) Metropolis
34
+ proposal c' = sqrt(1 - beta^2) c + beta xi, xi ~ prior, which is
35
+ reversible with respect to the prior so that the acceptance probability
36
+ depends only on the likelihood; sigma^2 is updated by Gibbs sampling. The
37
+ output is a set of posterior samples of the warp, from which posterior
38
+ means and pointwise credible intervals of the warp and the displacement
39
+ field can be computed. This quantifies the *uncertainty of the
40
+ registration itself*, which point-estimate methods (dynamic programming,
41
+ landmarks, ...) do not provide.
42
+
43
+ Copyright (C) 2026 Todd Pataky
44
+
45
+ This program is free software: you can redistribute it and/or modify it
46
+ under the terms of the GNU General Public License as published by the
47
+ Free Software Foundation, either version 3 of the License, or (at your
48
+ option) any later version. See the LICENSE file for details.
49
+ '''
50
+
51
+ import numpy as np
52
+ from scipy import integrate
53
+ from . import warp as _warp
54
+ from . import srsf as _srsf
55
+
56
+
57
+
58
+ def _basis(t, K):
59
+ k = np.arange(1, K+1)[:, None]
60
+ return np.sqrt(2) * np.cos(k * np.pi * t[None, :])
61
+
62
+
63
+ def coef_to_warp(c, B, t):
64
+ '''Warp from tangent-space coefficients c via the exponential map at the identity.'''
65
+ v = c @ B
66
+ nv = np.sqrt(max(integrate.trapezoid(v*v, t), 0.0))
67
+ if nv < 1e-12:
68
+ return t.copy()
69
+ psi = np.cos(nv) + np.sin(nv) * v / nv
70
+ g = integrate.cumulative_trapezoid(psi**2, t, initial=0)
71
+ return g / g[-1]
72
+
73
+
74
+ def _loglik_kernel(q1, q2, gam, t):
75
+ '''||q1 - (q2, gamma)||^2 (integral form).'''
76
+ d = q1 - _srsf.warp_srsf(q2, gam)
77
+ d2 = d**2 if d.ndim == 1 else (d**2).sum(axis=-1)
78
+ return integrate.trapezoid(d2, t)
79
+
80
+
81
+ def sample_pair(y_template, y, n_samples=2000, burn=500, thin=1, K=8, tau=0.3, beta=0.05,
82
+ adapt=True, a0=1.0, b0=1e-3, c0=None, n_eff=None, smooth=0, random_state=None, return_coef=False):
83
+ '''
84
+ Posterior samples of the warp aligning *y* to *y_template*.
85
+
86
+ *n_samples*, *burn*, *thin* : MCMC settings (total iterations = burn + n_samples*thin)
87
+ *K* : number of cosine basis functions for the tangent vector
88
+ *tau* : prior scale of the coefficients (c_k ~ N(0, tau^2/k^2));
89
+ larger tau allows stronger warps a priori
90
+ *beta* : initial pCN step size in (0,1]
91
+ *adapt* : adapt beta during burn-in towards an acceptance rate of ~25 %
92
+ *a0*, *b0* : InverseGamma hyper-parameters of the noise variance
93
+ *n_eff* : effective number of independent observations in the likelihood
94
+ (default Q, the number of grid points). SRSF residuals of
95
+ smooth data are strongly autocorrelated, so Q overstates the
96
+ information and the credible intervals are then optimistic;
97
+ a smaller n_eff (e.g. Q / autocorrelation length) tempers the
98
+ likelihood accordingly.
99
+ *c0* : initial coefficients (None = identity warp; a good initial value
100
+ is the projection of a dynamic-programming warp, see initial_coef)
101
+
102
+ Returns a dict with 'warps' (S,Q) posterior warp samples, 'sigma2' (S,),
103
+ 'accept' (acceptance rate after burn-in), 'beta' (final step size),
104
+ 'coef' (S,K) if return_coef.
105
+ '''
106
+ rng = np.random.default_rng(random_state)
107
+ yt = np.asarray(y_template, dtype=float)
108
+ yy = np.asarray(y, dtype=float)
109
+ Q = yt.shape[0]
110
+ t = _warp.grid(Q)
111
+ B = _basis(t, K)
112
+ f = _srsf.srsf_mv if yy.ndim == 2 else _srsf.srsf
113
+ q1, q2 = f(yt, smooth), f(yy, smooth)
114
+ prior_sd = tau / np.arange(1, K+1)
115
+ c = np.zeros(K) if c0 is None else np.asarray(c0, dtype=float).copy()
116
+ gam = coef_to_warp(c, B, t)
117
+ E = _loglik_kernel(q1, q2, gam, t)
118
+ sig2 = max(E, 1e-6)
119
+ n_eff = Q if n_eff is None else float(n_eff)
120
+ keep_w, keep_s, keep_c = [], [], []
121
+ acc = 0
122
+ acc_w = 0 # acceptances in the current adaptation window
123
+ total = burn + n_samples*thin
124
+ for it in range(total):
125
+ # --- pCN update of c
126
+ xi = rng.normal(0, prior_sd)
127
+ cp = np.sqrt(1 - beta**2) * c + beta * xi
128
+ gp = coef_to_warp(cp, B, t)
129
+ Ep = _loglik_kernel(q1, q2, gp, t)
130
+ logr = -(Ep - E) * n_eff / (2*sig2)
131
+ if np.log(rng.uniform()) < logr:
132
+ c, gam, E = cp, gp, Ep
133
+ acc_w += 1
134
+ if it >= burn:
135
+ acc += 1
136
+ # --- adapt the step size during burn-in towards ~25 % acceptance
137
+ if adapt and it < burn and (it + 1) % 50 == 0:
138
+ rate = acc_w / 50.0
139
+ beta = float(np.clip(beta * np.exp(0.5 * (rate - 0.25)), 1e-3, 1.0))
140
+ acc_w = 0
141
+ # --- Gibbs update of sigma^2 ~ InvGamma(a0 + n/2, b0 + n E / 2)
142
+ sig2 = 1.0 / rng.gamma(a0 + n_eff/2.0, 1.0 / (b0 + n_eff*E/2.0))
143
+ if it >= burn and (it - burn) % thin == 0:
144
+ keep_w.append(gam)
145
+ keep_s.append(sig2)
146
+ if return_coef:
147
+ keep_c.append(c.copy())
148
+ out = dict(warps=np.array(keep_w), sigma2=np.array(keep_s), accept=acc/(n_samples*thin), beta=beta)
149
+ if return_coef:
150
+ out['coef'] = np.array(keep_c)
151
+ return out
152
+
153
+
154
+ def initial_coef(gam, K):
155
+ '''
156
+ Tangent-space coefficients approximating a given warp (e.g. a dynamic
157
+ programming solution), obtained by the inverse exponential map at the
158
+ identity and projection onto the cosine basis. Useful as *c0* so that
159
+ the chain starts near the mode rather than at the identity.
160
+ '''
161
+ Q = gam.size
162
+ t = _warp.grid(Q)
163
+ B = _basis(t, K)
164
+ psi = _warp.warp_to_psi(gam)
165
+ one = np.ones(Q)
166
+ v = _warp._sphere_log(one, psi, t)
167
+ return np.array([integrate.trapezoid(v*b, t) for b in B])
168
+
169
+
170
+ def summarize(samples, alpha=0.05):
171
+ '''
172
+ Posterior summaries of warp samples (S,Q): Karcher-mean warp, pointwise
173
+ posterior mean and (1-alpha) credible interval of the warp and of the
174
+ displacement field.
175
+ '''
176
+ w = np.asarray(samples, dtype=float)
177
+ lo, hi = 100*alpha/2, 100*(1-alpha/2)
178
+ d = _warp.displacement_field(w)
179
+ return dict(
180
+ warp_mean = _warp.karcher_mean_warp(w),
181
+ warp_ci = np.percentile(w, [lo, hi], axis=0),
182
+ disp_mean = d.mean(axis=0),
183
+ disp_ci = np.percentile(d, [lo, hi], axis=0),
184
+ disp_samples= d,
185
+ )
186
+
187
+
188
+ def align_group(y, template='srsf', n_samples=1000, burn=500, thin=1, K=8, tau=0.3, beta=0.05,
189
+ init='dp', n_eff=None, smooth=0, center=True, anchor=None, random_state=None, verbose=False, **srsf_kwargs):
190
+ '''
191
+ Bayesian registration of a set of observations to a common template.
192
+
193
+ *template* : 'srsf' (the Karcher-mean template of register_srsf, computed
194
+ with **srsf_kwargs), an integer index, or a (Q,) array. The
195
+ template is held fixed while the warps are sampled (no
196
+ hierarchical template update).
197
+ *init* : 'dp' (start each chain at the projection of the dynamic
198
+ programming warp) or 'identity'
199
+ *center* : 'karcher' (default, = True) | 'pointwise' | 'anchor' | 'none'.
200
+ The reference warp is computed from the posterior-MEAN warps
201
+ and applied to the means and to every posterior sample, so
202
+ the credible bands are reported on the same common axis.
203
+ Other arguments as in sample_pair.
204
+
205
+ Returns a dict with keys 'y' (registered with the posterior-mean warps),
206
+ 'warps' (J,Q) posterior-mean warps, 'template', 'samples' (J,S,Q),
207
+ 'sigma2' (J,S), 'accept' (J,), 'disp_ci' (J,2,Q).
208
+ '''
209
+ y = np.asarray(y, dtype=float)
210
+ J, Q = y.shape[:2]
211
+ rng = np.random.default_rng(random_state)
212
+ if isinstance(template, str) and template == 'srsf':
213
+ r = _srsf.align_group(y, smooth=smooth, **srsf_kwargs)
214
+ tmpl = r['template']
215
+ gdp = r['warps']
216
+ elif isinstance(template, (int, np.integer)):
217
+ tmpl = y[int(template)].copy()
218
+ gdp = None
219
+ else:
220
+ tmpl = np.asarray(template, dtype=float)
221
+ gdp = None
222
+ if gdp is None and init == 'dp':
223
+ gdp = np.array([_srsf.align_pair(tmpl, yi, smooth=smooth)[1] for yi in y])
224
+ samples, sig2, acc = [], [], []
225
+ for i in range(J):
226
+ c0 = initial_coef(gdp[i], K) if init == 'dp' else None
227
+ s = sample_pair(tmpl, y[i], n_samples=n_samples, burn=burn, thin=thin, K=K, tau=tau,
228
+ beta=beta, c0=c0, n_eff=n_eff, smooth=smooth, random_state=rng.integers(2**31))
229
+ samples.append(s['warps']); sig2.append(s['sigma2']); acc.append(s['accept'])
230
+ if verbose:
231
+ print(f'observation {i+1}/{J}: acceptance rate = {s["accept"]:.2f}')
232
+ samples = np.array(samples)
233
+ wmean = np.array([_warp.karcher_mean_warp(s) for s in samples])
234
+ center = _warp.resolve_center(center, 'karcher')
235
+ if center != 'none' and J > 1:
236
+ wmean, gref = _warp.center_warps(wmean, method=center, anchor=anchor)
237
+ gi = _warp.invert(gref)
238
+ samples = np.array([[_warp.compose(w, gi) for w in s] for s in samples])
239
+ tmpl = _srsf._apply_warp_any(tmpl, gi)
240
+ yr = np.array([_srsf._apply_warp_any(y[i], wmean[i]) for i in range(J)])
241
+ disp_ci = np.array([summarize(s)['disp_ci'] for s in samples])
242
+ return dict(y=yr, warps=wmean, template=tmpl, samples=samples, sigma2=np.array(sig2),
243
+ accept=np.array(acc), disp_ci=disp_ci, center=center)
@@ -0,0 +1,174 @@
1
+ '''
2
+ Continuous (parametric, penalised least-squares) registration.
3
+
4
+ Implemented directly from
5
+
6
+ Ramsay JO, Li X (1998). Curve registration. Journal of the Royal
7
+ Statistical Society B 60: 351-363.
8
+ Ramsay JO, Silverman BW (2005). Functional Data Analysis, 2nd ed.
9
+ Springer. (Section 7.4, "Continuous registration")
10
+
11
+ The warp is parameterised through its log-derivative,
12
+
13
+ gamma(t) = int_0^t exp( W(s) ) ds / int_0^1 exp( W(s) ) ds,
14
+ W(s) = sum_k c_k phi_k(s),
15
+
16
+ which guarantees that gamma is smooth and strictly increasing for any
17
+ coefficient vector c (the "smooth monotone transformation" of Ramsay
18
+ 1998). Here phi_k are the first *n_basis* cosine functions
19
+ sqrt(2) cos(k pi s), k = 1..n_basis (a constant term would be absorbed by
20
+ the normalisation and is therefore omitted). The coefficients are found
21
+ by minimising
22
+
23
+ F(c) = int ( y(gamma(t)) - target(t) )^2 dt + lam * int W'(s)^2 ds
24
+
25
+ with a quasi-Newton optimiser. The roughness penalty shrinks the warp
26
+ towards the identity. Group registration alternates between fitting the
27
+ warps and updating the target as the cross-sectional mean of the
28
+ registered observations (Procrustes iteration).
29
+
30
+ Compared with SRSF dynamic programming, this approach produces very
31
+ smooth warps with few degrees of freedom and is therefore well suited
32
+ to data whose timing differences are gradual; it is less able to align
33
+ sharp local features, and the optimisation is local (not guaranteed
34
+ global).
35
+
36
+ Copyright (C) 2026 Todd Pataky
37
+
38
+ This program is free software: you can redistribute it and/or modify it
39
+ under the terms of the GNU General Public License as published by the
40
+ Free Software Foundation, either version 3 of the License, or (at your
41
+ option) any later version. See the LICENSE file for details.
42
+ '''
43
+
44
+ import numpy as np
45
+ from scipy import integrate, optimize
46
+ from . import warp as _warp
47
+
48
+
49
+
50
+ def _basis(t, n_basis):
51
+ k = np.arange(1, n_basis+1)[:, None]
52
+ return np.sqrt(2) * np.cos(k * np.pi * t[None, :]) # (n_basis, Q)
53
+
54
+
55
+ def _dbasis(t, n_basis):
56
+ k = np.arange(1, n_basis+1)[:, None]
57
+ return -np.sqrt(2) * k * np.pi * np.sin(k * np.pi * t[None, :])
58
+
59
+
60
+ def coef_to_warp(c, Q, n_basis=None):
61
+ '''Warp gamma(t) = int_0^t exp(W) / int_0^1 exp(W), W = sum c_k phi_k.'''
62
+ c = np.asarray(c, dtype=float)
63
+ t = _warp.grid(Q)
64
+ W = np.clip(c @ _basis(t, c.size), -20, 20)
65
+ g = integrate.cumulative_trapezoid(np.exp(W), t, initial=0)
66
+ return g / g[-1]
67
+
68
+
69
+ def _objective(c, y, target, t, B, dB, lam):
70
+ W = np.clip(c @ B, -20, 20)
71
+ g = integrate.cumulative_trapezoid(np.exp(W), t, initial=0)
72
+ g /= g[-1]
73
+ yw = np.interp(g, t, y)
74
+ sse = integrate.trapezoid((yw - target)**2, t)
75
+ pen = integrate.trapezoid((c @ dB)**2, t) if lam > 0 else 0.0
76
+ return sse + lam * pen
77
+
78
+
79
+ def align_pair(y_template, y, n_basis=4, lam=1e-2, c0=None, c_max=3.0):
80
+ '''
81
+ Register *y* to *y_template* with a smooth parametric warp.
82
+
83
+ *n_basis* : number of sine basis functions for W = log gamma'
84
+ *lam* : roughness penalty (dimensionless, relative to the variance of the template; 0 = none)
85
+ *c0* : initial coefficients (None = identity warp, fitted coarse-to-fine)
86
+ *c_max* : bound on |c_k| (limits the local slope of the warp to about exp(sqrt(2) c_max))
87
+
88
+ Returns (y_aligned, gamma, coef).
89
+ '''
90
+ y_template = np.asarray(y_template, dtype=float)
91
+ y = np.asarray(y, dtype=float)
92
+ Q = y.size
93
+ t = _warp.grid(Q)
94
+ B = _basis(t, n_basis)
95
+ dB = _dbasis(t, n_basis)
96
+ # scale the penalty relative to the data so that lam is dimensionless
97
+ scale = max(integrate.trapezoid((y_template - y_template.mean())**2, t), 1e-12)
98
+ c = np.zeros(n_basis) if c0 is None else np.asarray(c0, dtype=float).copy()
99
+ # coarse-to-fine: optimise the first k coefficients for k = 1..n_basis, warm-starting
100
+ # each stage from the previous one, which greatly reduces the risk of a poor local
101
+ # minimum when the warp is far from the identity
102
+ for k in range(1, n_basis+1):
103
+ if c0 is not None and k < n_basis:
104
+ continue
105
+ Bk, dBk = B[:k], dB[:k]
106
+ args = (y, y_template, t, Bk, dBk, lam*scale)
107
+ # the first two stages are multi-started on a small grid because the
108
+ # objective is not convex (a feature of y can lock on to the wrong feature
109
+ # of the template); later stages refine from the best solution so far
110
+ if c0 is None and k <= 2:
111
+ starts = [np.r_[c[:k-1], v] for v in np.linspace(-1.5, 1.5, 7)]
112
+ else:
113
+ starts = [c[:k]]
114
+ best = None
115
+ for s0 in starts:
116
+ res = optimize.minimize(_objective, s0, args=args, method='L-BFGS-B',
117
+ bounds=[(-c_max, c_max)]*k)
118
+ if best is None or res.fun < best.fun:
119
+ best = res
120
+ c[:k] = best.x
121
+ gam = coef_to_warp(c, Q)
122
+ return _warp.apply_warp(y, gam), gam, c
123
+
124
+
125
+ def align_group(y, template='mean', n_basis=4, lam=1e-2, max_iter=5, tol=1e-4,
126
+ center=True, anchor=None, verbose=False):
127
+ '''
128
+ Register a set of observations with smooth parametric warps
129
+ (Procrustes iteration on the cross-sectional mean).
130
+
131
+ *y* : (J,Q) array
132
+ *template* : 'mean' (iteratively updated cross-sectional mean), an
133
+ integer index (fixed), or a (Q,) array (fixed)
134
+ *n_basis* : number of sine basis functions for W = log gamma'
135
+ *lam* : roughness penalty (dimensionless; 0 = none)
136
+ *center* : 'karcher' (default, = True) | 'pointwise' | 'anchor' | 'none' (= False); see warp.center_warps
137
+ *anchor* : (J,) event times for center='anchor'
138
+
139
+ Returns a dict with keys 'y', 'warps', 'template', 'coef', 'niter'.
140
+ '''
141
+ y = np.atleast_2d(np.asarray(y, dtype=float))
142
+ J, Q = y.shape
143
+ fixed = False
144
+ if isinstance(template, str) and template == 'mean':
145
+ tmpl = y.mean(axis=0)
146
+ elif isinstance(template, (int, np.integer)):
147
+ tmpl, fixed = y[int(template)].copy(), True
148
+ else:
149
+ tmpl, fixed = np.asarray(template, dtype=float), True
150
+ gam = np.zeros((J, Q))
151
+ coef = np.zeros((J, n_basis))
152
+ niter = 0
153
+ for it in range(1 if fixed else max_iter):
154
+ niter += 1
155
+ yr = np.empty_like(y)
156
+ for i in range(J):
157
+ yr[i], gam[i], coef[i] = align_pair(tmpl, y[i], n_basis, lam, c0=(None if it == 0 else coef[i]))
158
+ sse = float(((yr - tmpl)**2).sum())
159
+ if verbose:
160
+ print(f'iteration {it+1}: sse = {sse:.6g}')
161
+ if fixed:
162
+ break
163
+ new = yr.mean(axis=0)
164
+ change = np.linalg.norm(new - tmpl) / max(np.linalg.norm(tmpl), 1e-12)
165
+ tmpl = new
166
+ if change < tol:
167
+ break
168
+ center = _warp.resolve_center(center, 'karcher')
169
+ if center != 'none' and J > 1:
170
+ gam, _ = _warp.center_warps(gam, method=center, anchor=anchor)
171
+ yr = np.array([_warp.apply_warp(y[i], gam[i]) for i in range(J)])
172
+ if not fixed:
173
+ tmpl = yr.mean(axis=0)
174
+ return dict(y=yr, warps=gam, template=tmpl, coef=coef, niter=niter, center=center)