errorcalculus 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.
@@ -0,0 +1,111 @@
1
+ """Exceptions and warnings of errorcalculus.
2
+
3
+ Every exception derives from :class:`ErrorCalculusError` and, where it makes sense, from the standard exception that
4
+ Python code already catches (``ValueError``, ``ArithmeticError``, ``TypeError``), so that ``except ValueError`` keeps
5
+ working.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ __all__ = [
11
+ "ErrorCalculusError",
12
+ "ModelError",
13
+ "ModelMismatchError",
14
+ "DuplicateNameError",
15
+ "NotAnInputError",
16
+ "OrderError",
17
+ "FirstOrderError",
18
+ "InputError",
19
+ "CovarianceError",
20
+ "MissingBiasError",
21
+ "DomainError",
22
+ "NonDifferentiableError",
23
+ "NonFiniteError",
24
+ "UnsupportedOperationError",
25
+ "NotTrackedError",
26
+ "NumericalDerivativeError",
27
+ "TransportError",
28
+ "ComparisonError",
29
+ "UnsupportedDistributionError",
30
+ "NumericalDerivativeWarning",
31
+ ]
32
+
33
+
34
+ class ErrorCalculusError(Exception):
35
+ """Base class of every exception raised by errorcalculus."""
36
+
37
+
38
+ class ModelError(ErrorCalculusError, ValueError):
39
+ """Invalid model, or invalid use of a model (``order`` not in {1, 2}, ...)."""
40
+
41
+
42
+ class ModelMismatchError(ModelError):
43
+ """Quantities that belong to two different models were combined."""
44
+
45
+
46
+ class DuplicateNameError(ModelError):
47
+ """A name (input, group or source) is already taken in the model."""
48
+
49
+
50
+ class NotAnInputError(ModelError):
51
+ """A declared input was expected, and a derived quantity was given."""
52
+
53
+
54
+ class OrderError(ErrorCalculusError):
55
+ """The requested quantity does not exist at the order of the model."""
56
+
57
+
58
+ class FirstOrderError(OrderError):
59
+ """Biases (the operator A) are refused in a first-order model."""
60
+
61
+
62
+ class InputError(ErrorCalculusError, ValueError):
63
+ """Invalid declaration of an input or invalid argument."""
64
+
65
+
66
+ class CovarianceError(InputError):
67
+ """Covariance matrix of wrong shape, not symmetric, or not positive semidefinite."""
68
+
69
+
70
+ class MissingBiasError(InputError):
71
+ """``require_bias=True`` and an input of a second-order model declares no bias."""
72
+
73
+
74
+ class DomainError(ErrorCalculusError, ValueError, ArithmeticError):
75
+ """Argument outside the domain of a function, division by zero, singular matrix."""
76
+
77
+
78
+ class NonDifferentiableError(DomainError):
79
+ """The function is not C² (or has an infinite derivative) at the point, and the error there is not zero."""
80
+
81
+
82
+ class NonFiniteError(ErrorCalculusError, ArithmeticError):
83
+ """A value, a coefficient of the sharp or a bias is not finite (overflow)."""
84
+
85
+
86
+ class UnsupportedOperationError(ErrorCalculusError, TypeError):
87
+ """Operation not supported on quantities with errors (``float(q)``, ``floor``, an unsupported NumPy function...)."""
88
+
89
+
90
+ class NotTrackedError(ErrorCalculusError):
91
+ """The bias breakdown was requested from a model built without ``bias_breakdown=True``."""
92
+
93
+
94
+ class NumericalDerivativeError(ErrorCalculusError, ArithmeticError):
95
+ """A numerical derivative failed its step-halving check (``strict=True``)."""
96
+
97
+
98
+ class TransportError(ErrorCalculusError, ValueError):
99
+ """Transport of an operator by a map that is not a diffeomorphism of R^m, or an inconsistent inverse."""
100
+
101
+
102
+ class ComparisonError(ErrorCalculusError, ValueError):
103
+ """Unknown comparison method, or unsupported output."""
104
+
105
+
106
+ class UnsupportedDistributionError(ComparisonError):
107
+ """The comparison method does not support the requested error distribution."""
108
+
109
+
110
+ class NumericalDerivativeWarning(UserWarning):
111
+ """A numerical derivative failed its step-halving check (``check=True``)."""
@@ -0,0 +1,249 @@
1
+ """Linear algebra on arrays of quantities: ``solve``, ``inv``, ``det`` (implicit differentiation, no global Hessian).
2
+
3
+ * ``solve``: x = a⁻¹b; x♯ = a⁻¹(b♯ − a♯ x); at order 2, applying A to the identity (a x)_i = b_i with the product
4
+ rule, A[x] = a⁻¹(A[b] − A[a] x − g), g_i = Σ_j Γ[a_ij, x_j].
5
+ * ``inv(a)`` = ``solve(a, I)``.
6
+ * ``det``: d = det a; d♯_s = d · tr(a⁻¹ a♯_s); at order 2,
7
+ A[d] = d · [tr(a⁻¹ A[a]) + ½ Σ_s ((tr a⁻¹ a♯_s)² − tr(a⁻¹ a♯_s a⁻¹ a♯_s))].
8
+
9
+ **Singular matrices.** The nominal matrix is first equilibrated by powers of 2, which is exact in floating point:
10
+ S = D₁ a D₂, with D₁ from the maxima of the rows of a, then D₂ from the maxima of the columns of D₁ a. ``solve``,
11
+ ``inv`` and ``det`` raise :class:`DomainError` if a row or a column of a is zero, if S cannot be factorised, or if
12
+ the scaled condition number ::
13
+
14
+ κ_s(a) = ρ(|a⁻¹| |a|) = ρ(|S⁻¹| |S|)
15
+
16
+ exceeds 1/(100 ε_mach) ≈ 4.5e13 (the message gives κ_s). κ_s does not depend on the units of the rows or columns
17
+ (``|(D₁aD₂)⁻¹| |D₁aD₂| = D₂⁻¹ |a⁻¹| |a| D₂`` is similar to ``|a⁻¹| |a|``), and it is a lower bound of
18
+ κ_∞(D₁ a D₂) for all diagonal D₁, D₂ (ρ(N) ≤ ‖N‖_∞ ≤ ‖S⁻¹‖_∞ ‖S‖_∞), indeed their minimum (F. L. Bauer, Optimally
19
+ scaled matrices, Numer. Math. 5, 1963, Theorem Ia): an exactly invertible matrix in badly chosen units, such as
20
+ diag(1e9, 1e-9), is accepted (κ_s = 1). Below the threshold nothing is refused: as for any linear solve, the error
21
+ of each component of a result is typically of order ``n ε (|a⁻¹| |a| |x|)_i``, that is, about log₁₀ κ_s digits for
22
+ a component of the size of the others, and more for a much smaller component (the componentwise bound of an LU
23
+ factorisation with partial pivoting holds with ``|L| |U|`` in place of ``|a|``, which can be larger). Near the
24
+ threshold the decision can depend on the BLAS library (κ_s is computed in floating point). Every computation
25
+ (value, sharp, bias) is done on S and scaled back
26
+ (a⁻¹R = D₂ S⁻¹ D₁ R; det through the exponents): without that, a = [[1, 1e20], [1, 1]] (κ_s = 1) would be solved
27
+ wrongly by a direct elimination. A non-finite result raises :class:`NonFiniteError`.
28
+
29
+ For ``det``, refusing a singular matrix is a limitation of version 0.1.0 (det is C² everywhere; a cofactor version
30
+ valid at d = 0 will come later).
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import numpy as np
36
+
37
+ from ._array import (
38
+ QuantityArray,
39
+ _as_qa,
40
+ _contains_quantity,
41
+ _EMPTY_IDX,
42
+ _expand,
43
+ _model_of,
44
+ _partner,
45
+ _union,
46
+ array,
47
+ )
48
+ from ._core import _new
49
+ from .errors import DomainError, InputError, NonFiniteError
50
+
51
+ __all__ = ["solve", "inv", "det"]
52
+
53
+ _EPS = float(np.finfo(float).eps)
54
+ _KAPPA_MAX = 1.0 / (100.0 * _EPS)
55
+
56
+
57
+ def _lift(o):
58
+ """A (nested) list or tuple holding quantities as a QuantityArray, as the elementwise functions accept it."""
59
+ if isinstance(o, (list, tuple)) and _contains_quantity(o):
60
+ return array(o)
61
+ if isinstance(o, np.ndarray) and o.dtype == object and _contains_quantity(o.tolist()):
62
+ return array(o.tolist())
63
+ return o
64
+
65
+
66
+ def _square(a: QuantityArray) -> int:
67
+ if a.ndim != 2 or a.shape[0] != a.shape[1]:
68
+ raise InputError(f"expected a square matrix, got shape {a.shape}")
69
+ return a.shape[0]
70
+
71
+
72
+ class _Equilibrated:
73
+ """S = D₁ a D₂ (powers of 2), S⁻¹, and the singularity checks."""
74
+
75
+ def __init__(self, av: np.ndarray):
76
+ if av.size == 0:
77
+ raise DomainError("empty matrix")
78
+ absa = np.abs(av)
79
+ rmax = absa.max(axis=1)
80
+ if np.any(rmax == 0.0):
81
+ raise DomainError("the matrix is singular (a row is zero)")
82
+ if np.any(absa.max(axis=0) == 0.0):
83
+ raise DomainError("the matrix is singular (a column is zero)")
84
+ # exponents: |x| ∈ [2^(e-1), 2^e) for x = m·2^e, 0.5 ≤ |m| < 1. The column exponents are computed from the
85
+ # exponents of the entries (exact integers), and S is formed by ONE ldexp with the total exponent er_i + ec_j:
86
+ # no intermediate matrix that could pass through subnormals (two successive ldexp lost bits
87
+ # for entries 2^1022 times smaller than their row maximum). Every row of S has its maximum in [1/2, 1] and
88
+ # every column in [1/2, 1), so an entry of S can underflow only if it is below 2^-1022 times its row
89
+ # maximum, far below the rounding of the row.
90
+ self.er = -np.frexp(rmax)[1]
91
+ e = np.frexp(av)[1] + self.er[:, None] # exponent of each entry of D₁ a (exact)
92
+ # maximum over the non-zero entries of each column (every column has one, checked above). No sentinel value:
93
+ # an int64 sentinel in np.where is cast to the int32 of the exponents under NumPy 2 and becomes 0, which
94
+ # disabled the scaling of every column holding a zero.
95
+ self.ec = -np.max(e, axis=0, where=(av != 0.0), initial=np.iinfo(e.dtype).min)
96
+ S = np.ldexp(av, self.er[:, None] + self.ec[None, :])
97
+ try:
98
+ Si = np.linalg.inv(S)
99
+ except np.linalg.LinAlgError as exc:
100
+ raise DomainError("the matrix is singular (the factorisation fails)") from exc
101
+ if not np.all(np.isfinite(Si)):
102
+ raise DomainError("the matrix is singular (the inverse is not finite)")
103
+ N = np.abs(Si) @ np.abs(S)
104
+ if not np.all(np.isfinite(N)):
105
+ raise DomainError("the matrix is singular to working precision (|S⁻¹||S| is not finite)")
106
+ # ρ(N) ≤ ‖N‖_∞: the eigenvalues are computed only when the cheap bound exceeds the threshold
107
+ kappa = float(N.sum(axis=1).max())
108
+ if kappa > _KAPPA_MAX:
109
+ kappa = float(np.max(np.abs(np.linalg.eigvals(N))))
110
+ if not np.isfinite(kappa) or kappa > _KAPPA_MAX:
111
+ raise DomainError(f"the matrix is singular to working precision: its scaled condition number "
112
+ f"ρ(|a⁻¹||a|) = {kappa:.3g} exceeds 1/(100 ε) = {_KAPPA_MAX:.3g}")
113
+ self.kappa = kappa
114
+ self.S = S
115
+ self.Si = Si
116
+ self.n = av.shape[0]
117
+
118
+ def row(self, R: np.ndarray) -> np.ndarray:
119
+ """D₁ R (R of shape (n, ...))."""
120
+ return np.ldexp(R, self.er.reshape((-1,) + (1,) * (R.ndim - 1)))
121
+
122
+ def lsolve(self, R: np.ndarray) -> np.ndarray:
123
+ """a⁻¹ R = D₂ S⁻¹ D₁ R, R of shape (n, ...), solved on S."""
124
+ n = self.n
125
+ if R.size == 0:
126
+ return np.zeros(R.shape)
127
+ Y = np.linalg.solve(self.S, self.row(R).reshape(n, -1)).reshape(R.shape)
128
+ return np.ldexp(Y, self.ec.reshape((-1,) + (1,) * (R.ndim - 1)))
129
+
130
+ def scaled(self, M: np.ndarray) -> np.ndarray:
131
+ """D₁ M D₂ on the first two axes of M (n, n, ...)."""
132
+ tail = (1,) * (M.ndim - 2)
133
+ return np.ldexp(M, (self.er[:, None] + self.ec[None, :]).reshape((self.n, self.n) + tail))
134
+
135
+
136
+ def solve(a, b):
137
+ """Solution x of a x = b (a: n × n; b: n or n × p), with the rules of the module documentation."""
138
+ a, b = _lift(a), _lift(b)
139
+ m = _model_of((a, b))
140
+ if m is None:
141
+ return np.linalg.solve(a, b)
142
+ A_ = _as_qa(a, m)
143
+ B_ = _as_qa(b, m)
144
+ n = _square(A_)
145
+ if B_.ndim not in (1, 2) or B_.shape[0] != n:
146
+ raise InputError(f"b must have shape ({n},) or ({n}, p), got {B_.shape}")
147
+ av, bv = A_._v, B_._v
148
+ eq = _Equilibrated(av)
149
+ lsolve = eq.lsolve
150
+ with np.errstate(all="ignore"):
151
+ x = lsolve(bv)
152
+ if not np.all(np.isfinite(x)):
153
+ raise NonFiniteError("the solution is not finite (overflow)")
154
+ vec = B_.ndim == 1
155
+ sup = _union(A_._sup, B_._sup)
156
+ k = len(sup)
157
+ Sa = _expand(A_._S, A_._sup, sup) # (n, n, k)
158
+ Sb = _expand(B_._S, B_._sup, sup) # (n, [p,] k)
159
+
160
+ if vec:
161
+ Xs = lsolve(Sb - np.einsum("ijk,j->ik", Sa, x))
162
+ else:
163
+ Xs = lsolve(Sb - np.einsum("ijk,jp->ipk", Sa, x))
164
+ A = Z = B = K = None
165
+ zg = bg = _EMPTY_IDX
166
+ if m._order == 1:
167
+ Z = np.zeros(x.shape + (0,), dtype=bool)
168
+ return QuantityArray._make(m, x, Xs, sup, None, Z, zg, None, bg, None)
169
+ Px = _partner(m, Xs, sup) # Γ[a_ij, x_j] (or the paired form)
170
+ if vec:
171
+ g = np.einsum("ijk,jk->i", Sa, Px)
172
+ Ax = lsolve(B_._A - A_._A @ x - g)
173
+ else:
174
+ g = np.einsum("ijk,jpk->ip", Sa, Px)
175
+ Ax = lsolve(B_._A - A_._A @ x - g)
176
+ zg = _union(A_._zg, B_._zg)
177
+ dep = (_expand(A_._Z, A_._zg, zg, bool).reshape(A_.size, len(zg)).any(axis=0)
178
+ | _expand(B_._Z, B_._zg, zg, bool).reshape(B_.size, len(zg)).any(axis=0))
179
+ Z = np.broadcast_to(dep, x.shape + (len(zg),)).copy()
180
+ if m._bb:
181
+ bg = _union(A_._bg, B_._bg)
182
+ Ba = _expand(A_._B, A_._bg, bg)
183
+ Bb = _expand(B_._B, B_._bg, bg)
184
+ Ka = _expand(A_._K, A_._sup, sup)
185
+ Kb = _expand(B_._K, B_._sup, sup)
186
+ if vec:
187
+ B = lsolve(Bb - np.einsum("ijg,j->ig", Ba, x))
188
+ K = lsolve(Kb - np.einsum("ijk,j->ik", Ka, x) - np.einsum("ijk,jk->ik", Sa, Xs))
189
+ else:
190
+ B = lsolve(Bb - np.einsum("ijg,jp->ipg", Ba, x))
191
+ K = lsolve(Kb - np.einsum("ijk,jp->ipk", Ka, x) - np.einsum("ijk,jpk->ipk", Sa, Xs))
192
+ return QuantityArray._make(m, x, Xs, sup, Ax, Z, zg, B, bg, K)
193
+
194
+
195
+ def inv(a):
196
+ """Inverse of a square matrix: ``solve(a, I)``."""
197
+ a = _lift(a)
198
+ m = _model_of((a,))
199
+ if m is None:
200
+ return np.linalg.inv(a)
201
+ n = _square(_as_qa(a, m))
202
+ return solve(a, np.eye(n))
203
+
204
+
205
+ def det(a):
206
+ """Determinant of a square matrix (a :class:`Quantity`), with the rules of the module documentation."""
207
+ a = _lift(a)
208
+ m = _model_of((a,))
209
+ if m is None:
210
+ return np.linalg.det(a)
211
+ A_ = _as_qa(a, m)
212
+ _square(A_)
213
+ eq = _Equilibrated(A_._v)
214
+ # det a = det S · 2^-(Σ er + Σ ec); tr(a⁻¹ X) = tr(S⁻¹ D₁ X D₂): everything on the scaled matrix
215
+ try:
216
+ dS = float(np.linalg.det(eq.S))
217
+ except np.linalg.LinAlgError as exc: # pragma: no cover - S was inverted above
218
+ raise DomainError("the matrix is singular") from exc
219
+ with np.errstate(all="ignore"):
220
+ d = float(np.ldexp(dS, -int(eq.er.sum() + eq.ec.sum())))
221
+ if not np.isfinite(d) or abs(d) < np.finfo(float).tiny:
222
+ e2 = int(np.frexp(dS)[1]) - int(eq.er.sum() + eq.ec.sum())
223
+ raise NonFiniteError(f"the determinant overflows or is subnormal (|det| ≈ 2^{e2}): a subnormal determinant "
224
+ "would lose its digits silently; rescale the matrix")
225
+ M = eq.Si
226
+ sup = A_._sup
227
+ Sa = eq.scaled(A_._S) # D₁ a♯_s D₂, (n, n, k)
228
+ tr = np.einsum("ij,jik->k", M, Sa) # tr(a⁻¹ a♯_s)
229
+ ds = d * tr
230
+ s = {int(sup[j]): float(ds[j]) for j in np.flatnonzero(ds)}
231
+ if m._order == 1:
232
+ return _new(m, d, s, None, frozenset(), None, None)
233
+ P = np.einsum("ij,jlk->ilk", M, Sa) # a⁻¹ a♯_s (similar, same traces)
234
+ trPP = np.einsum("ilk,lik->k", P, P) # tr(a⁻¹ a♯_s a⁻¹ a♯_s)
235
+ curv = 0.5 * (tr * tr - trPP) # per source
236
+ if m._pair is not None: # paired form: ½ Σ_s (tr_s tr_s' − tr(P_s P_s'))
237
+ Pp = _partner(m, P, sup)
238
+ curv_a = 0.5 * (tr * _partner(m, tr, sup) - np.einsum("ilk,lik->k", P, Pp))
239
+ else:
240
+ curv_a = curv
241
+ Ad = d * (float(np.einsum("ij,ji->", M, eq.scaled(A_._A))) + float(np.sum(curv_a)))
242
+ z = frozenset(int(g) for g in A_._zg[A_._Z.reshape(A_.size, len(A_._zg)).any(axis=0)])
243
+ beta = kappa = None
244
+ if m._bb:
245
+ bterm = d * np.einsum("ij,jig->g", M, eq.scaled(A_._B))
246
+ kterm = d * (np.einsum("ij,jik->k", M, eq.scaled(A_._K)) + curv)
247
+ beta = {int(A_._bg[j]): float(bterm[j]) for j in np.flatnonzero(bterm)}
248
+ kappa = {int(sup[j]): float(kterm[j]) for j in np.flatnonzero(kterm)}
249
+ return _new(m, d, s, Ad, z, beta, kappa)
@@ -0,0 +1,207 @@
1
+ """The bias operator L as an operator on functions, and its transport by a diffeomorphism.
2
+
3
+ For coefficients b (drift, m) and D (diffusion,
4
+ m × m, positive semidefinite), possibly depending on the point w,
5
+
6
+ (L φ)(w) = Σ_k b_k ∂_k φ + ½ Σ_kl D_kl ∂_kl φ, Γ(φ, ψ)(w) = Σ_kl D_kl ∂_k φ ∂_l ψ,
7
+
8
+ and Γ(φ, ψ) = L(φψ) − φ L(ψ) − ψ L(φ). In the language of Bouleau 2003 (chap. II–III), L is the generator A of an
9
+ error structure on R^m restricted to C² functions, and the formulas above are the functional calculus of that
10
+ generator. Each value is computed by the engine: a second-order model is built at the point, with inputs whose sharps
11
+ are the rows of a factor of D and whose biases are b; φ is evaluated on these inputs and A or Γ is read.
12
+
13
+ The transport θ_u(L) φ = L(φ ∘ u) ∘ u⁻¹ has, at w, the coefficients b′(w) = (A[u_k(V)]) and D′(w) = (Γ[u_k(V), u_l(V)]),
14
+ computed by the engine at v = u⁻¹(w) with the coefficients of L at v. Coherence: θ_{v∘u}(L) = θ_v(θ_u(L)).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Sequence
20
+
21
+ import numpy as np
22
+
23
+ from ._core import Model, Quantity, _factorize, _is_number, covariance_matrix
24
+ from ._core import gamma as _gamma
25
+ from ._core import gamma_via_bias as _gamma_via_bias
26
+ from .errors import (
27
+ CovarianceError,
28
+ FirstOrderError,
29
+ InputError,
30
+ ModelMismatchError,
31
+ NotAnInputError,
32
+ TransportError,
33
+ )
34
+
35
+ __all__ = ["BiasOperator"]
36
+
37
+
38
+ def _symmetric_psd(D: np.ndarray, m: int) -> np.ndarray:
39
+ D = np.asarray(D, dtype=float)
40
+ if D.shape != (m, m):
41
+ raise CovarianceError(f"the diffusion must have shape ({m}, {m}), got {D.shape}")
42
+ if not np.all(np.isfinite(D)):
43
+ raise CovarianceError("the diffusion must be finite")
44
+ scale = float(np.max(np.abs(D), initial=0.0))
45
+ if float(np.max(np.abs(D - D.T), initial=0.0)) > 1e-12 * scale:
46
+ raise CovarianceError("the diffusion is not symmetric (tolerance 1e-12 relative)")
47
+ return 0.5 * (D + D.T)
48
+
49
+
50
+ def _drift(b, m: int) -> np.ndarray:
51
+ b = np.asarray(b, dtype=float)
52
+ if b.shape != (m,):
53
+ raise InputError(f"the drift must have shape ({m},), got {b.shape}")
54
+ if not np.all(np.isfinite(b)):
55
+ raise InputError("the drift must be finite")
56
+ return b
57
+
58
+
59
+ class BiasOperator:
60
+ """The operator L of coefficients ``drift`` (m) and ``diffusion`` (m × m), constant or callables ``w -> array``.
61
+
62
+ ``apply``, ``gamma`` and ``gamma_via_bias`` take functions of m positional arguments written with the functions of
63
+ errorcalculus; ``transport`` gives θ_u(L) for a diffeomorphism u of R^m with inverse ``inverse``.
64
+ """
65
+
66
+ def __init__(self, *, drift, diffusion, dimension: int) -> None:
67
+ if isinstance(dimension, bool) or not isinstance(dimension, (int, np.integer)) or dimension < 1:
68
+ raise InputError("dimension must be a positive integer")
69
+ self._m = int(dimension)
70
+ if not callable(drift):
71
+ drift = _drift(drift, self._m)
72
+ if not callable(diffusion):
73
+ diffusion = _symmetric_psd(diffusion, self._m)
74
+ _factorize(diffusion) # raises CovarianceError if not positive semidefinite
75
+ self._drift = drift
76
+ self._diffusion = diffusion
77
+ self._coef = None
78
+
79
+ @classmethod
80
+ def _from_coefficients(cls, coef, dimension: int) -> BiasOperator:
81
+ op = cls.__new__(cls)
82
+ op._m = dimension
83
+ op._drift = op._diffusion = None
84
+ op._coef = coef
85
+ return op
86
+
87
+ @classmethod
88
+ def from_inputs(cls, inputs: Sequence[Quantity]) -> BiasOperator:
89
+ """L with constant coefficients: drift = (A[x_i]), diffusion = covariance_matrix(inputs).
90
+
91
+ The quantities must be declared inputs of one second-order model.
92
+ """
93
+ qs = list(inputs)
94
+ if not qs:
95
+ raise InputError("from_inputs needs at least one input")
96
+ model = None
97
+ for q in qs:
98
+ if not isinstance(q, Quantity):
99
+ raise NotAnInputError("from_inputs expects declared inputs of a model")
100
+ if model is None:
101
+ model = q._m
102
+ elif q._m is not model:
103
+ raise ModelMismatchError("these quantities belong to two different models")
104
+ if model._order == 1:
105
+ raise FirstOrderError("a first-order model has no bias operator: declare the model with order=2")
106
+ for q in qs:
107
+ if not q._inp:
108
+ raise NotAnInputError("from_inputs expects declared inputs of the model, not derived quantities")
109
+ return cls(drift=np.array([q._a for q in qs]), diffusion=covariance_matrix(qs), dimension=len(qs))
110
+
111
+ @property
112
+ def dimension(self) -> int:
113
+ return self._m
114
+
115
+ def _point(self, at) -> np.ndarray:
116
+ w = np.atleast_1d(np.asarray(at, dtype=float))
117
+ if w.shape != (self._m,):
118
+ raise InputError(f"the point must have {self._m} coordinates")
119
+ if not np.all(np.isfinite(w)):
120
+ raise InputError("the point must be finite")
121
+ return w
122
+
123
+ def coefficients(self, *, at) -> tuple[np.ndarray, np.ndarray]:
124
+ """(drift, diffusion) at the point ``at``."""
125
+ w = self._point(at)
126
+ if self._coef is not None:
127
+ b, D = self._coef(w)
128
+ else:
129
+ b = self._drift(w) if callable(self._drift) else self._drift
130
+ D = self._diffusion(w) if callable(self._diffusion) else self._diffusion
131
+ return _drift(b, self._m).copy(), _symmetric_psd(D, self._m)
132
+
133
+ def _inputs_at(self, w: np.ndarray) -> list:
134
+ b, D = self.coefficients(at=w)
135
+ model = Model(order=2)
136
+ return model._from_factor(w, _factorize(D), b)
137
+
138
+ def apply(self, phi, *, at) -> float:
139
+ """(L φ)(at) = Σ drift_k ∂_k φ + ½ Σ diffusion_kl ∂_kl φ."""
140
+ xs = self._inputs_at(self._point(at))
141
+ F = _own(phi(*xs), xs, "phi")
142
+ if isinstance(F, Quantity):
143
+ return F._a
144
+ if _is_number(F):
145
+ return 0.0
146
+ raise InputError("phi must return a scalar")
147
+
148
+ def gamma(self, phi, psi=None, *, at) -> float:
149
+ """Γ(φ, ψ)(at) = Σ diffusion_kl ∂_k φ ∂_l ψ (Γ(φ) with ψ omitted)."""
150
+ xs = self._inputs_at(self._point(at))
151
+ F = _own(phi(*xs), xs, "phi")
152
+ G = F if psi is None else _own(psi(*xs), xs, "psi")
153
+ return _gamma(F, G)
154
+
155
+ def gamma_via_bias(self, phi, psi=None, *, at) -> float:
156
+ """L(φψ) − φ L(ψ) − ψ L(φ) at the point: equal to Γ(φ, ψ)."""
157
+ xs = self._inputs_at(self._point(at))
158
+ F = _own(phi(*xs), xs, "phi")
159
+ G = F if psi is None else _own(psi(*xs), xs, "psi")
160
+ return _gamma_via_bias(F, G)
161
+
162
+ def transport(self, u, *, inverse, check_tol: float = 1e-10) -> BiasOperator:
163
+ """θ_u(L): the operator φ ↦ L(φ ∘ u) ∘ u⁻¹, for a diffeomorphism u of R^m with inverse ``inverse``.
164
+
165
+ At each evaluation, ‖u(u⁻¹(w)) − w‖ ≤ check_tol·(1 + ‖w‖) is checked (:class:`TransportError` otherwise);
166
+ u and its inverse take m positional arguments and return m values.
167
+ """
168
+ if not callable(u) or not callable(inverse):
169
+ raise TransportError("u and inverse must be callables")
170
+ parent = self
171
+ m = self._m
172
+
173
+ def coef(w: np.ndarray):
174
+ v = _vector(inverse(*[float(t) for t in w]), m, "inverse")
175
+ uv = _vector(u(*[float(t) for t in v]), m, "u")
176
+ if np.linalg.norm(uv - w) > check_tol * (1.0 + np.linalg.norm(w)):
177
+ raise TransportError("the inverse given is inconsistent with u: ‖u(inverse(w)) − w‖ = "
178
+ f"{np.linalg.norm(uv - w):.3g}")
179
+ xs = parent._inputs_at(v)
180
+ U = u(*xs)
181
+ if not isinstance(U, (list, tuple)) or len(U) != m:
182
+ raise TransportError(f"u must map R^{m} to R^{m} (return a sequence of {m} values)")
183
+ for q in U:
184
+ _own(q, xs, "u")
185
+ b = np.array([q._a if isinstance(q, Quantity) else 0.0 for q in U])
186
+ return b, covariance_matrix(U)
187
+
188
+ return BiasOperator._from_coefficients(coef, m)
189
+
190
+
191
+ def _own(F, xs, what: str):
192
+ """F, after checking that a quantity returned by ``what`` belongs to the model of the inputs ``xs`` (a quantity
193
+ captured from outside the arguments has its sharp indexed by the sources of another model)."""
194
+ if isinstance(F, Quantity) and xs and F._m is not xs[0]._m:
195
+ raise ModelMismatchError(f"{what} returned a quantity of another model (computed from quantities outside "
196
+ "its arguments)")
197
+ return F
198
+
199
+
200
+ def _vector(r, m: int, what: str) -> np.ndarray:
201
+ try:
202
+ out = np.asarray(r, dtype=float)
203
+ except (TypeError, ValueError) as exc:
204
+ raise TransportError(f"{what} must return {m} numbers when called with numbers") from exc
205
+ if out.shape != (m,):
206
+ raise TransportError(f"{what} must map R^{m} to R^{m} (return {m} numbers)")
207
+ return out