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.
errorcalculus/_core.py ADDED
@@ -0,0 +1,1349 @@
1
+ """Models, scalar quantities and the sparse propagation engine (private; the public names live in ``calculus``).
2
+
3
+ A quantity carries its nominal value, its *sharp* (a sparse vector: source -> coefficient) and, in a second-order
4
+ model, its bias A. With Γ[x, y] = <x♯, y♯>, the rule for a C² function f of two arguments, at the nominal values, is
5
+
6
+ (f(x, y))♯ = f_x x♯ + f_y y♯
7
+ A[f(x, y)] = f_x A[x] + f_y A[y] + ½ (f_xx Γ[x] + 2 f_xy Γ[x, y] + f_yy Γ[y]),
8
+
9
+ and functions of one argument are the case f_y = 0 (Bouleau 2003, *Error Calculus for Finance and Physics*, chap. I
10
+ for the second-order rule; chap. V § 2, p. 78-80, for the gradient and the sharp). The recursion is the one of the
11
+ Forward Laplacian (Li et al. 2023): it is cited here, not claimed.
12
+
13
+ The sharp of a quantity is the finite-dimensional realisation of Bouleau's sharp (2003, V.2.2, p. 80): each source s
14
+ is an element ĝ_s of L²(P̂) and these elements are orthonormal, so that q♯ = Σ_s q.sharp[s] ĝ_s and
15
+ Γ[q] = Σ_s q.sharp[s]². It is a gradient with values in H = R^k (V.2.1), isometrically embedded in L²(P̂).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import numbers
22
+ from dataclasses import dataclass
23
+ from types import MappingProxyType
24
+ from typing import Literal, Mapping
25
+
26
+ import numpy as np
27
+
28
+ from . import _rules
29
+ from .errors import (
30
+ CovarianceError,
31
+ DomainError,
32
+ DuplicateNameError,
33
+ FirstOrderError,
34
+ InputError,
35
+ MissingBiasError,
36
+ ModelError,
37
+ ModelMismatchError,
38
+ NonDifferentiableError,
39
+ NonFiniteError,
40
+ NotTrackedError,
41
+ UnsupportedOperationError,
42
+ )
43
+
44
+ _EMPTY = frozenset()
45
+ _isfinite = math.isfinite
46
+
47
+
48
+ # ======================================================================================================================
49
+ # Sparse helpers
50
+ # ======================================================================================================================
51
+ def _scale(c: float, d: dict) -> dict:
52
+ """c·d, with exact zeros pruned. The dict is shared when c == 1 (quantities are immutable)."""
53
+ if c == 1.0:
54
+ return d
55
+ if not c or not d:
56
+ return {}
57
+ out = {}
58
+ for k, v in d.items():
59
+ w = c * v
60
+ if w:
61
+ out[k] = w
62
+ return out
63
+
64
+
65
+ def _comb(a: float, da: dict, b: float, db: dict) -> dict:
66
+ """a·da + b·db, with exact zeros pruned."""
67
+ if not b or not db:
68
+ return _scale(a, da)
69
+ if not a or not da:
70
+ return _scale(b, db)
71
+ out = {}
72
+ for k, v in da.items():
73
+ w = a * v
74
+ if w:
75
+ out[k] = w
76
+ for k, v in db.items():
77
+ w = out.get(k, 0.0) + b * v
78
+ if w:
79
+ out[k] = w
80
+ else:
81
+ out.pop(k, None)
82
+ return out
83
+
84
+
85
+ def _dot(da: dict, db: dict) -> float:
86
+ """<da, db>, exactly rounded (math.fsum over the intersection of the supports): exactly symmetric."""
87
+ if len(da) > len(db):
88
+ da, db = db, da
89
+ try:
90
+ r = math.fsum([v * db[k] for k, v in da.items() if k in db])
91
+ except (OverflowError, ValueError) as exc:
92
+ raise NonFiniteError("Γ is not finite (overflow)") from exc
93
+ if not _isfinite(r):
94
+ raise NonFiniteError("Γ is not finite (overflow)")
95
+ return r
96
+
97
+
98
+ def _sq(d: dict) -> float:
99
+ """<d, d>, exactly rounded: exactly non-negative."""
100
+ try:
101
+ r = math.fsum([v * v for v in d.values()])
102
+ except (OverflowError, ValueError) as exc:
103
+ raise NonFiniteError("Γ is not finite (overflow)") from exc
104
+ if not _isfinite(r):
105
+ raise NonFiniteError("Γ is not finite (overflow)")
106
+ return r
107
+
108
+
109
+ def _form_sq(m: Model, d: dict) -> float:
110
+ """The form that feeds A, on a sharp with itself: Γ = <d, d>, or 2 d_u d_v in the paired mode (see _pdot)."""
111
+ if m._pair is None:
112
+ return _sq(d)
113
+ u, v = m._pair
114
+ return 2.0 * d.get(u, 0.0) * d.get(v, 0.0)
115
+
116
+
117
+ def _form_dot(m: Model, da: dict, db: dict) -> float:
118
+ """The form that feeds A: Γ[x, y] = <x♯, y♯>, or, in the private paired mode of a model with two sources u, v,
119
+ the indefinite form <s, t>_P = s_u t_v + s_v t_u (used by ``sensitivities`` and ``compare``: with inputs of
120
+ sharps (u_i, v_i) and zero biases, A[F] = uᵀ ∇²F v, without subtraction between diagonal terms). Every contraction of sharps that feeds A goes through this function (sparse engine)
121
+ or through ``_array._partner`` (dense engine, linalg)."""
122
+ if m._pair is None:
123
+ return _dot(da, db)
124
+ u, v = m._pair
125
+ return da.get(u, 0.0) * db.get(v, 0.0) + da.get(v, 0.0) * db.get(u, 0.0)
126
+
127
+
128
+ def _add_curvature(kappa: dict, sx: dict, sy: dict | None, hxx: float, hxy: float, hyy: float) -> dict:
129
+ """κ + ½(f_xx (x♯_s)² + 2 f_xy x♯_s y♯_s + f_yy (y♯_s)²) source by source; hxx = ½ f_xx, ..."""
130
+ out = dict(kappa)
131
+ if sy is None:
132
+ if hxx:
133
+ for k, v in sx.items():
134
+ out[k] = out.get(k, 0.0) + hxx * v * v
135
+ else:
136
+ for k in sx.keys() | sy.keys():
137
+ u = sx.get(k, 0.0)
138
+ w = sy.get(k, 0.0)
139
+ out[k] = out.get(k, 0.0) + (hxx * u * u + 2.0 * hxy * u * w + hyy * w * w)
140
+ return {k: v for k, v in out.items() if v}
141
+
142
+
143
+ # ======================================================================================================================
144
+ # Validation helpers
145
+ # ======================================================================================================================
146
+ def _finite_real(x, what: str) -> float:
147
+ if isinstance(x, (Quantity, bool)) or not (isinstance(x, numbers.Real) or (isinstance(x, np.ndarray)
148
+ and x.ndim == 0)):
149
+ raise InputError(f"{what} must be a real number, got {type(x).__name__}")
150
+ try:
151
+ v = float(x)
152
+ except (TypeError, ValueError) as exc:
153
+ raise InputError(f"{what} must be a real number") from exc
154
+ if not _isfinite(v):
155
+ raise InputError(f"{what} must be finite, got {v!r}")
156
+ return v
157
+
158
+
159
+ def _check_name(name) -> str:
160
+ if not isinstance(name, str) or not name:
161
+ raise InputError("a name must be a non-empty string")
162
+ if ":" in name:
163
+ raise InputError("a name may not contain ':' (reserved for the keys '<group>:bias' of contributions)")
164
+ return name
165
+
166
+
167
+ def _is_number(o) -> bool:
168
+ if isinstance(o, numbers.Real):
169
+ return not isinstance(o, Quantity)
170
+ return isinstance(o, np.ndarray) and o.ndim == 0 and o.dtype.kind in "biuf"
171
+
172
+
173
+ def _is_arraylike(o) -> bool:
174
+ from ._array import QuantityArray
175
+
176
+ return isinstance(o, (np.ndarray, QuantityArray))
177
+
178
+
179
+ # ======================================================================================================================
180
+ # Model
181
+ # ======================================================================================================================
182
+ class Model:
183
+ """A registry of error sources, and the order of the calculus.
184
+
185
+ ``order=1``: first order, error variances only (Gauss). ``order=2``: second order, error variances and biases
186
+ (Γ and A). The argument is mandatory. Quantities of two different models never combine
187
+ (:class:`ModelMismatchError`).
188
+
189
+ Parameters
190
+ ----------
191
+ order : 1 or 2
192
+ require_bias : bool
193
+ Second order only: every input must declare ``bias=`` (otherwise :class:`MissingBiasError`). By default an
194
+ undeclared bias is taken as 0 and the input's group is marked "assumed zero bias", which every result that
195
+ depends on it reports (:attr:`ErrorSummary.assumed_zero_bias`).
196
+ bias_breakdown : bool
197
+ Second order only: track the decomposition of A by group and by source (``contributions(kind="bias")``);
198
+ about twice the cost.
199
+ name : str, optional
200
+ A label for the model.
201
+ """
202
+
203
+ # Private paired mode: None, or the two source ids (u, v) whose indefinite form replaces Γ in the
204
+ # contractions that feed A. Only internal models of sensitivities and compare set it (never with bias_breakdown).
205
+ _pair = None
206
+
207
+ def __init__(self, *, order: Literal[1, 2], require_bias: bool = False, bias_breakdown: bool = False,
208
+ name: str | None = None) -> None:
209
+ if isinstance(order, bool) or not isinstance(order, numbers.Integral) or order not in (1, 2):
210
+ raise ModelError(f"order must be 1 or 2, got {order!r}")
211
+ order = int(order)
212
+ if order == 1 and require_bias:
213
+ raise FirstOrderError("require_bias concerns biases, which a first-order model does not propagate; "
214
+ "declare the model with order=2")
215
+ if order == 1 and bias_breakdown:
216
+ raise FirstOrderError("bias_breakdown concerns biases, which a first-order model does not propagate; "
217
+ "declare the model with order=2")
218
+ self._order = order
219
+ self._require_bias = bool(require_bias)
220
+ self._bb = bool(bias_breakdown)
221
+ self._name = name
222
+ self._names: set[str] = set()
223
+ self._inputs: list[Quantity] = []
224
+ self._src_names: list[str] = []
225
+ self._src_group: list[int] = []
226
+ self._grp_names: list[str] = []
227
+ self._grp_sources: list[tuple[int, ...]] = []
228
+ self._grp_factor: list[np.ndarray] = []
229
+ self._grp_assumed: list[bool] = []
230
+
231
+ # --- read-only attributes -----------------------------------------------------------------------------------
232
+ @property
233
+ def order(self) -> int:
234
+ return self._order
235
+
236
+ @property
237
+ def require_bias(self) -> bool:
238
+ return self._require_bias
239
+
240
+ @property
241
+ def bias_breakdown(self) -> bool:
242
+ return self._bb
243
+
244
+ @property
245
+ def name(self) -> str | None:
246
+ return self._name
247
+
248
+ @property
249
+ def inputs(self) -> tuple:
250
+ """Declared inputs, scalar, in order of creation (an input array is flattened)."""
251
+ return tuple(self._inputs)
252
+
253
+ @property
254
+ def sources(self) -> tuple:
255
+ """Names of the error sources (the columns of the sharp)."""
256
+ return tuple(self._src_names)
257
+
258
+ @property
259
+ def groups(self) -> Mapping[str, tuple]:
260
+ """Group -> names of its sources. An independent input is a group of one source."""
261
+ return MappingProxyType({g: tuple(self._src_names[s] for s in srcs)
262
+ for g, srcs in zip(self._grp_names, self._grp_sources)})
263
+
264
+ def factor(self, group: str) -> np.ndarray:
265
+ """The factor L (n × r) of a group: the covariance of its inputs is L Lᵀ."""
266
+ try:
267
+ gid = self._grp_names.index(group)
268
+ except ValueError:
269
+ raise InputError(f"unknown group {group!r}") from None
270
+ return self._grp_factor[gid].copy()
271
+
272
+ def __repr__(self) -> str:
273
+ label = f", name={self._name!r}" if self._name is not None else ""
274
+ return (f"Model(order={self._order}{label}, inputs={len(self._inputs)}, sources={len(self._src_names)}, "
275
+ f"groups={len(self._grp_names)})")
276
+
277
+ # --- registry -----------------------------------------------------------------------------------------------
278
+ def _new_name(self, prefix: str) -> str:
279
+ i = 0
280
+ while f"{prefix}{i}" in self._names:
281
+ i += 1
282
+ return f"{prefix}{i}"
283
+
284
+ def _reserve(self, names: list[str]) -> None:
285
+ seen = set()
286
+ for n in names:
287
+ if n in self._names or n in seen:
288
+ raise DuplicateNameError(f"the name {n!r} is already used in this model")
289
+ seen.add(n)
290
+
291
+ def _add_group(self, gname: str, factor: np.ndarray, src_names: list[str], assumed: bool) -> tuple[int, list[int]]:
292
+ gid = len(self._grp_names)
293
+ first = len(self._src_names)
294
+ ids = list(range(first, first + len(src_names)))
295
+ self._src_names.extend(src_names)
296
+ self._src_group.extend([gid] * len(src_names))
297
+ self._grp_names.append(gname)
298
+ self._grp_sources.append(tuple(ids))
299
+ f = np.array(factor, dtype=float)
300
+ f.setflags(write=False)
301
+ self._grp_factor.append(f)
302
+ self._grp_assumed.append(assumed)
303
+ self._names.add(gname)
304
+ self._names.update(src_names)
305
+ return gid, ids
306
+
307
+ def _bias_arg(self, bias, n: int | None):
308
+ """Returns (biases, declared). ``n`` is None for a scalar input."""
309
+ if self._order == 1:
310
+ if bias is not None:
311
+ raise FirstOrderError("a first-order model does not propagate biases; declare the model with order=2 "
312
+ "to give an input a bias")
313
+ return (None if n is None else [None] * n), False
314
+ if bias is None:
315
+ if self._require_bias:
316
+ raise MissingBiasError("this model was built with require_bias=True: declare bias= for every input")
317
+ return (0.0 if n is None else [0.0] * n), False
318
+ if n is None:
319
+ return _finite_real(bias, "bias"), True
320
+ b = np.asarray(bias, dtype=float)
321
+ if b.ndim == 0:
322
+ b = np.full(n, float(b))
323
+ if b.shape != (n,):
324
+ raise InputError(f"bias must be a number or have {n} elements")
325
+ if not np.all(np.isfinite(b)):
326
+ raise InputError("bias must be finite")
327
+ return [float(v) for v in b], True
328
+
329
+ # --- inputs -------------------------------------------------------------------------------------------------
330
+ def input(self, value, *, std=None, variance=None, bias=None, name=None) -> Quantity:
331
+ """Declare an independent input: its own group, with one source of coefficient ``std``.
332
+
333
+ Exactly one of ``std`` (≥ 0) and ``variance`` (≥ 0) is given; quantities are declared in physical units,
334
+ at gauge 1 (Γ[X] = std², A[X] = bias; see :meth:`Quantity.summary` for the scale). With ``std == 0`` and no
335
+ (or a zero) bias, the input is an exact constant; with ``std == 0`` and a non-zero bias, a group without
336
+ source (a purely systematic error).
337
+ """
338
+ v = _finite_real(value, "value")
339
+ sigma = _std_arg(std, variance)
340
+ b, declared = self._bias_arg(bias, None)
341
+ name = self._new_name("x") if name is None else _check_name(name)
342
+ self._reserve([name])
343
+ return self._make_input(v, sigma, b, declared, name)
344
+
345
+ def _make_input(self, v: float, sigma: float, b, declared: bool, name: str) -> Quantity:
346
+ bb = {} if self._bb else None
347
+ if sigma == 0.0 and not b:
348
+ self._names.add(name)
349
+ q = _new_input(self, v, {}, b, _EMPTY, bb, {} if self._bb else None)
350
+ elif sigma == 0.0:
351
+ gid, _ = self._add_group(name, np.zeros((1, 0)), [], assumed=False)
352
+ q = _new_input(self, v, {}, b, _EMPTY, {gid: b} if self._bb else None, {} if self._bb else None)
353
+ else:
354
+ assumed = self._order == 2 and not declared
355
+ gid, ids = self._add_group(name, np.array([[sigma]]), [name], assumed=assumed)
356
+ beta = ({gid: b} if b else {}) if self._bb else None
357
+ q = _new_input(self, v, {ids[0]: sigma}, b, frozenset((gid,)) if assumed else _EMPTY, beta,
358
+ {} if self._bb else None)
359
+ self._inputs.append(q)
360
+ return q
361
+
362
+ def input_array(self, values, *, std=None, variance=None, bias=None, name=None):
363
+ """Declare an array of independent inputs (n groups of one source each, named ``name[i]``).
364
+
365
+ ``std`` / ``variance`` / ``bias`` are numbers or arrays of the shape of ``values``. The elements of the
366
+ returned :class:`QuantityArray` are the registered inputs themselves.
367
+ """
368
+ from ._array import QuantityArray
369
+
370
+ vals = _real_array(values, "values")
371
+ if not np.all(np.isfinite(vals)):
372
+ raise InputError("values must be finite")
373
+ if (std is None) == (variance is None):
374
+ raise InputError("give exactly one of std= and variance=")
375
+ spread = _real_array(std if std is not None else variance, "std / variance", vals.shape)
376
+ if not np.all(np.isfinite(spread)) or np.any(spread < 0):
377
+ raise InputError("std / variance must be finite and non-negative")
378
+ sig = spread if std is not None else np.sqrt(spread)
379
+ if self._order == 1:
380
+ if bias is not None:
381
+ raise FirstOrderError("a first-order model does not propagate biases; declare the model with "
382
+ "order=2 to give an input a bias")
383
+ bs, declared = np.zeros(vals.shape), False
384
+ elif bias is None:
385
+ if self._require_bias:
386
+ raise MissingBiasError("this model was built with require_bias=True: declare bias= for every input")
387
+ bs, declared = np.zeros(vals.shape), False
388
+ else:
389
+ bs = _real_array(bias, "bias", vals.shape)
390
+ if not np.all(np.isfinite(bs)):
391
+ raise InputError("bias must be finite")
392
+ declared = True
393
+ base = self._new_name("x") if name is None else _check_name(name)
394
+ idxs = list(np.ndindex(vals.shape))
395
+ names = [f"{base}[{','.join(str(i) for i in ix)}]" if ix else f"{base}[()]" for ix in idxs]
396
+ self._reserve([base, *names])
397
+ self._names.add(base) # the base name of the array is reserved too
398
+ objs = np.empty(vals.shape, dtype=object)
399
+ for ix, nm in zip(idxs, names):
400
+ b = None if self._order == 1 else float(bs[ix])
401
+ objs[ix] = self._make_input(float(vals[ix]), float(sig[ix]), b, declared, nm)
402
+ return QuantityArray._from_quantities(objs, self)
403
+
404
+ def correlated(self, values, *, cov=None, std=None, corr=None, bias=None, names=None, group=None,
405
+ as_array=False):
406
+ """Declare correlated inputs: one group, whose sources are the columns of a factor L, cov = L Lᵀ.
407
+
408
+ Give either ``cov`` (n × n), or ``std`` (n) and ``corr`` (n × n). The matrix must be symmetric (to 1e-12
409
+ relative) and positive semidefinite; it is symmetrised, then factorised on its correlation matrix: by
410
+ Cholesky (the sparsest sharps) when every pivot² exceeds 1e-8, otherwise by the spectral decomposition, which
411
+ decides the rank r ≤ n (the eigenvalues greater than m·1e-15 are kept, m inputs of non-zero variance). The
412
+ sources are named ``group[0]``, ..., ``group[r-1]``.
413
+ """
414
+ from ._array import QuantityArray
415
+
416
+ vals = np.asarray(values, dtype=float)
417
+ if vals.ndim != 1:
418
+ raise InputError("values must be one-dimensional")
419
+ n = vals.shape[0]
420
+ if not np.all(np.isfinite(vals)):
421
+ raise InputError("values must be finite")
422
+ if cov is not None:
423
+ if std is not None or corr is not None:
424
+ raise InputError("give either cov=, or std= and corr=, not both")
425
+ C = np.array(cov, dtype=float)
426
+ if C.shape != (n, n):
427
+ raise CovarianceError(f"cov must have shape ({n}, {n}), got {C.shape}")
428
+ else:
429
+ if std is None or corr is None:
430
+ raise InputError("give either cov=, or std= and corr=")
431
+ sd = np.asarray(std, dtype=float)
432
+ R = np.asarray(corr, dtype=float)
433
+ if sd.shape != (n,):
434
+ raise InputError(f"std must have {n} elements")
435
+ if not np.all(np.isfinite(sd)) or np.any(sd < 0):
436
+ raise InputError("std must be finite and non-negative")
437
+ if R.shape != (n, n):
438
+ raise CovarianceError(f"corr must have shape ({n}, {n}), got {R.shape}")
439
+ if not np.all(np.isfinite(R)):
440
+ raise CovarianceError("corr must be finite")
441
+ if np.any(np.abs(np.diag(R) - 1.0) > 1e-12):
442
+ raise CovarianceError("the diagonal of corr must be 1")
443
+ C = sd[:, None] * R * sd[None, :]
444
+ if not np.all(np.isfinite(C)):
445
+ raise CovarianceError("the covariance matrix must be finite")
446
+ scale = np.max(np.abs(C)) if C.size else 0.0
447
+ if np.max(np.abs(C - C.T), initial=0.0) > 1e-12 * scale:
448
+ raise CovarianceError("the covariance matrix is not symmetric (tolerance 1e-12 relative)")
449
+ C = 0.5 * (C + C.T)
450
+ L = _factorize(C)
451
+ bs, declared = self._bias_arg(bias, n)
452
+ gname = self._new_name("c") if group is None else _check_name(group)
453
+ if names is None:
454
+ inames = []
455
+ for _ in range(n):
456
+ i = 0
457
+ while f"x{i}" in self._names or f"x{i}" in inames:
458
+ i += 1
459
+ inames.append(f"x{i}")
460
+ else:
461
+ inames = [_check_name(nm) for nm in names]
462
+ if len(inames) != n:
463
+ raise InputError(f"names must have {n} elements")
464
+ r = L.shape[1]
465
+ snames = [f"{gname}[{j}]" for j in range(r)]
466
+ self._reserve([gname, *snames, *inames])
467
+ assumed = self._order == 2 and not declared and r > 0
468
+ gid, ids = self._add_group(gname, L, snames, assumed=assumed)
469
+ out = []
470
+ for i in range(n):
471
+ s = {ids[j]: float(L[i, j]) for j in range(r) if L[i, j] != 0.0}
472
+ b = bs[i]
473
+ z = frozenset((gid,)) if (assumed and s) else _EMPTY
474
+ beta = ({gid: b} if b else {}) if self._bb else None
475
+ q = _new_input(self, float(vals[i]), s, b, z, beta, {} if self._bb else None)
476
+ self._names.add(inames[i])
477
+ self._inputs.append(q)
478
+ out.append(q)
479
+ if as_array:
480
+ objs = np.empty(n, dtype=object)
481
+ for i, q in enumerate(out):
482
+ objs[i] = q
483
+ return QuantityArray._from_quantities(objs, self)
484
+ return out
485
+
486
+ def _from_factor(self, values, L, bias) -> list:
487
+ """Private: inputs with prescribed sharps (rows of L) and declared biases, in a fresh group.
488
+
489
+ Used by :func:`sensitivities`, :class:`BiasOperator` and ``compare``.
490
+ """
491
+ L = np.asarray(L, dtype=float)
492
+ n, r = L.shape
493
+ gname = self._new_name("_g")
494
+ snames = [f"{gname}[{j}]" for j in range(r)]
495
+ gid, ids = self._add_group(gname, L, snames, assumed=False)
496
+ out = []
497
+ for i in range(n):
498
+ s = {ids[j]: float(L[i, j]) for j in range(r) if L[i, j] != 0.0}
499
+ b = None if self._order == 1 else float(bias[i])
500
+ beta = ({gid: b} if b else {}) if self._bb else None
501
+ q = _new_input(self, float(values[i]), s, b, _EMPTY, beta, {} if self._bb else None)
502
+ self._inputs.append(q)
503
+ out.append(q)
504
+ return out
505
+
506
+
507
+ def _std_arg(std, variance) -> float:
508
+ if (std is None) == (variance is None):
509
+ raise InputError("give exactly one of std= and variance=")
510
+ if std is not None:
511
+ s = _finite_real(std, "std")
512
+ if s < 0:
513
+ raise InputError("std must be non-negative")
514
+ return s
515
+ v = _finite_real(variance, "variance")
516
+ if v < 0:
517
+ raise InputError("variance must be non-negative")
518
+ return math.sqrt(v)
519
+
520
+
521
+ def _real_array(o, what: str, shape=None) -> np.ndarray:
522
+ """Real array (optionally broadcast to ``shape``); InputError otherwise (never a bare ValueError)."""
523
+ try:
524
+ raw = np.asarray(o)
525
+ if raw.dtype.kind not in "biuf":
526
+ raise TypeError
527
+ a = raw.astype(float)
528
+ return a if shape is None else np.broadcast_to(a, shape)
529
+ except (TypeError, ValueError) as exc:
530
+ target = "" if shape is None else f" of a shape compatible with {shape}"
531
+ raise InputError(f"{what} must be an array of real numbers{target}") from exc
532
+
533
+
534
+ _CHOL_MIN = 1e-8 # smallest Cholesky pivot² of the correlation matrix for the Cholesky factor to be kept
535
+
536
+
537
+ def _factorize(C: np.ndarray) -> np.ndarray:
538
+ """L with C = L Lᵀ: Cholesky, or the spectral decomposition for a singular matrix.
539
+
540
+ The factorisation is done on the correlation matrix R = D^-1/2 C D^-1/2 (D = diag C), then rescaled:
541
+ L = D^1/2 L_R. The tolerances are therefore relative to each variance, not to the largest one, and inputs in
542
+ different units (ratio of standard deviations below 1e-8) keep their errors.
543
+ """
544
+ n = C.shape[0]
545
+ if n == 0:
546
+ return np.zeros((0, 0))
547
+ diag = np.diag(C)
548
+ if np.any(diag < 0):
549
+ raise CovarianceError("the covariance matrix has a negative variance")
550
+ pos = diag > 0
551
+ if np.any(C[~pos][:, pos] != 0.0) or np.any(C[~pos][:, ~pos] != 0.0):
552
+ raise CovarianceError("the covariance matrix is not positive semidefinite (a zero variance with a non-zero "
553
+ "covariance)")
554
+ out = np.zeros((n, 0))
555
+ if not np.any(pos):
556
+ return out
557
+ d = np.sqrt(diag[pos])
558
+ R = C[np.ix_(pos, pos)] / np.outer(d, d)
559
+ m = R.shape[0]
560
+ tol = m * 1e-15
561
+ LR = None
562
+ try:
563
+ L = np.linalg.cholesky(R)
564
+ # Cholesky "succeeds" in floating point on some singular matrices, with tiny pivots. A pivot² bounds the
565
+ # smallest eigenvalue from above only (it was found 50 times larger, and on either side of tol depending on
566
+ # the BLAS library), so the rank is never decided on the pivots: Cholesky is kept only when its smallest
567
+ # pivot² is far above the rounding (> _CHOL_MIN), and the spectral decomposition decides otherwise.
568
+ if np.all(np.isfinite(L)) and np.min(np.diag(L)) ** 2 > _CHOL_MIN:
569
+ LR = L
570
+ except np.linalg.LinAlgError:
571
+ pass
572
+ if LR is None:
573
+ w, V = np.linalg.eigh(R)
574
+ if np.any(w < -tol):
575
+ raise CovarianceError("the covariance matrix is not positive semidefinite (eigenvalue "
576
+ f"{w.min():.3g} of the correlation matrix)")
577
+ keep = w > tol
578
+ LR = V[:, keep] * np.sqrt(w[keep])
579
+ L = np.zeros((n, LR.shape[1]))
580
+ L[pos] = d[:, None] * LR
581
+ return L
582
+
583
+
584
+ # ======================================================================================================================
585
+ # Quantity
586
+ # ======================================================================================================================
587
+ _set = object.__setattr__
588
+
589
+
590
+ def _new(m: Model, v, s: dict, a, z: frozenset, beta, kappa) -> Quantity:
591
+ """Create a quantity, after checking that everything is finite (never return nan or inf silently)."""
592
+ v = float(v)
593
+ if not _isfinite(v):
594
+ raise NonFiniteError(f"the value is not finite ({v!r})")
595
+ for c in s.values():
596
+ if not _isfinite(c):
597
+ raise NonFiniteError("a coefficient of the sharp is not finite (overflow)")
598
+ if a is not None:
599
+ a = float(a)
600
+ if not _isfinite(a):
601
+ raise NonFiniteError("the bias is not finite (overflow)")
602
+ if beta is not None:
603
+ for c in beta.values():
604
+ if not _isfinite(c):
605
+ raise NonFiniteError("a term of the bias breakdown is not finite (overflow)")
606
+ for c in kappa.values():
607
+ if not _isfinite(c):
608
+ raise NonFiniteError("a term of the bias breakdown is not finite (overflow)")
609
+ q = object.__new__(Quantity)
610
+ _set(q, "_m", m)
611
+ _set(q, "_v", v)
612
+ _set(q, "_s", s)
613
+ _set(q, "_a", a)
614
+ _set(q, "_z", z)
615
+ _set(q, "_beta", beta)
616
+ _set(q, "_kappa", kappa)
617
+ _set(q, "_inp", False)
618
+ return q
619
+
620
+
621
+ def _new_input(m, v, s, b, z, beta, kappa) -> Quantity:
622
+ q = _new(m, v, s, b, z, beta, kappa)
623
+ _set(q, "_inp", True)
624
+ return q
625
+
626
+
627
+ def _const(m: Model, v, z: frozenset) -> Quantity:
628
+ """An exact result (empty sharp, A = 0), still carrying the structural dependency z."""
629
+ bb = m._bb
630
+ return _new(m, v, {}, None if m._order == 1 else 0.0, z, {} if bb else None, {} if bb else None)
631
+
632
+
633
+ def _is_exact(x: Quantity) -> bool:
634
+ """Exact zero error: empty sharp and, at order 2, zero bias (the rule of == and bool)."""
635
+ return not x._s and not x._a
636
+
637
+
638
+ def _errorless(x) -> bool:
639
+ """Empty sharp (numbers included): the criterion of the domain rules, identical at both orders."""
640
+ return not isinstance(x, Quantity) or not x._s
641
+
642
+
643
+ def _singular_exact(name: str, m: Model, value, z: frozenset, *operands) -> Quantity:
644
+ """Exact result at a point where the function is not C², for operands with an empty sharp.
645
+
646
+ At order 2, an operand with an empty sharp but a non-zero bias (a purely systematic error) cannot be
647
+ propagated there (infinite or undefined derivative): NonFiniteError. The refusal concerns A only, so the domain
648
+ refusals stay identical at both orders.
649
+ """
650
+ if any(isinstance(o, Quantity) and o._a for o in operands):
651
+ raise NonFiniteError(f"{name}: the bias of the argument cannot be propagated at this point (the derivative "
652
+ "is infinite or undefined there)")
653
+ return _const(m, value, z)
654
+
655
+
656
+ def _zunion(x: Quantity, y: Quantity) -> frozenset:
657
+ if not y._z:
658
+ return x._z
659
+ if not x._z:
660
+ return y._z
661
+ return x._z | y._z
662
+
663
+
664
+ def _unary(x: Quantity, f, f1, f2) -> Quantity:
665
+ """f(x), with f1 = f′(x), f2 = f″(x) at the nominal value (f2 unused at order 1)."""
666
+ m = x._m
667
+ f1 = float(f1)
668
+ s = _scale(f1, x._s)
669
+ if m._order == 1:
670
+ return _new(m, f, s, None, _EMPTY, None, None)
671
+ f2 = float(f2)
672
+ a = f1 * x._a if x._a else 0.0
673
+ if f2 and x._s:
674
+ a += 0.5 * f2 * _form_sq(m, x._s)
675
+ beta = kappa = None
676
+ if m._bb:
677
+ beta = _scale(f1, x._beta)
678
+ kappa = _scale(f1, x._kappa)
679
+ if f2 and x._s:
680
+ kappa = _add_curvature(kappa, x._s, None, 0.5 * f2, 0.0, 0.0)
681
+ return _new(m, f, s, a, x._z, beta, kappa)
682
+
683
+
684
+ def _binary(x: Quantity, y: Quantity, f, fx, fy, fxx, fxy, fyy) -> Quantity:
685
+ """f(x, y) for two quantities of the same model."""
686
+ m = x._m
687
+ if y._m is not m:
688
+ raise ModelMismatchError("these quantities belong to two different models")
689
+ fx = float(fx)
690
+ fy = float(fy)
691
+ s = _comb(fx, x._s, fy, y._s)
692
+ if m._order == 1:
693
+ return _new(m, f, s, None, _EMPTY, None, None)
694
+ fxx, fxy, fyy = float(fxx), float(fxy), float(fyy)
695
+ a = 0.0
696
+ if x._a:
697
+ a += fx * x._a
698
+ if y._a:
699
+ a += fy * y._a
700
+ curv = 0.0
701
+ if fxx and x._s:
702
+ curv += fxx * _form_sq(m, x._s)
703
+ if fxy and x._s and y._s:
704
+ curv += 2.0 * fxy * _form_dot(m, x._s, y._s)
705
+ if fyy and y._s:
706
+ curv += fyy * _form_sq(m, y._s)
707
+ a += 0.5 * curv
708
+ beta = kappa = None
709
+ if m._bb:
710
+ beta = _comb(fx, x._beta, fy, y._beta)
711
+ kappa = _comb(fx, x._kappa, fy, y._kappa)
712
+ if (fxx and x._s) or (fxy and x._s and y._s) or (fyy and y._s):
713
+ kappa = _add_curvature(kappa, x._s, y._s, 0.5 * fxx, 0.5 * fxy, 0.5 * fyy)
714
+ return _new(m, f, s, a, _zunion(x, y), beta, kappa)
715
+
716
+
717
+ def _linear(x: Quantity, y: Quantity, sign: float) -> Quantity:
718
+ """x + sign·y (sign = ±1): exact, no curvature."""
719
+ m = x._m
720
+ if y._m is not m:
721
+ raise ModelMismatchError("these quantities belong to two different models")
722
+ s = _comb(1.0, x._s, sign, y._s)
723
+ if m._order == 1:
724
+ return _new(m, x._v + sign * y._v, s, None, _EMPTY, None, None)
725
+ beta = kappa = None
726
+ if m._bb:
727
+ beta = _comb(1.0, x._beta, sign, y._beta)
728
+ kappa = _comb(1.0, x._kappa, sign, y._kappa)
729
+ return _new(m, x._v + sign * y._v, s, x._a + sign * y._a, _zunion(x, y), beta, kappa)
730
+
731
+
732
+ def _shift(x: Quantity, c: float) -> Quantity:
733
+ """x + c, c a number."""
734
+ return _new(x._m, x._v + c, x._s, x._a, x._z, x._beta, x._kappa)
735
+
736
+
737
+ def _times(x: Quantity, c: float) -> Quantity:
738
+ """c·x, c a number: exact, no curvature."""
739
+ m = x._m
740
+ s = _scale(c, x._s)
741
+ if m._order == 1:
742
+ return _new(m, c * x._v, s, None, _EMPTY, None, None)
743
+ beta = kappa = None
744
+ if m._bb:
745
+ beta = _scale(c, x._beta)
746
+ kappa = _scale(c, x._kappa)
747
+ return _new(m, c * x._v, s, c * x._a if x._a else 0.0, x._z, beta, kappa)
748
+
749
+
750
+ def _apply_unary(name: str, x: Quantity) -> Quantity:
751
+ """One-argument elementary function of a scalar quantity, with its domain rules."""
752
+ derivs, domain, nondiff = _rules.UNARY[name]
753
+ v = x._v
754
+ if domain is not None and domain(v):
755
+ raise DomainError(f"{name}({v!r}): the argument is outside the domain of the function")
756
+ if nondiff is not None and nondiff(v):
757
+ if _errorless(x):
758
+ return _singular_exact(name, x._m, float(_rules.VALUE[name](v)), x._z, x)
759
+ raise NonDifferentiableError(f"{name} is not twice differentiable at {v!r} (or has an infinite derivative) "
760
+ "and the argument carries an error there")
761
+ with np.errstate(all="ignore"): # NumPy floats: an overflow gives inf, caught by _new (never ZeroDivisionError)
762
+ f, f1, f2 = derivs(np.float64(v))
763
+ return _unary(x, f, f1, f2)
764
+
765
+
766
+ def _apply_binary(name: str, x, y) -> Quantity:
767
+ """atan2(x, y) or hypot(x, y) with at least one scalar quantity."""
768
+ xq, yq = isinstance(x, Quantity), isinstance(y, Quantity)
769
+ if xq and yq and x._m is not y._m:
770
+ raise ModelMismatchError("these quantities belong to two different models")
771
+ xv = x._v if xq else float(x)
772
+ yv = y._v if yq else float(y)
773
+ ex = _errorless(x)
774
+ ey = _errorless(y)
775
+ if name == "atan2": # x is the ordinate, y the abscissa
776
+ at_origin = xv == 0.0 and yv == 0.0
777
+ singular = (at_origin and not (ex and ey)) or (xv == 0.0 and yv < 0.0 and not ex)
778
+ else:
779
+ singular = xv == 0.0 and yv == 0.0 and not (ex and ey)
780
+ if singular:
781
+ raise NonDifferentiableError(f"{name} is not differentiable at ({xv!r}, {yv!r}) and the arguments carry an "
782
+ "error there")
783
+ q = x if xq else y
784
+ if ex and ey and xv == 0.0 and yv == 0.0:
785
+ z = _zunion(x, y) if (xq and yq) else q._z
786
+ return _singular_exact(name, q._m, float(_rules.VALUE[name](xv, yv)), z, x, y)
787
+ if name == "atan2" and xv == 0.0 and yv < 0.0 and xq and x._a:
788
+ raise NonFiniteError("atan2: the bias of the ordinate cannot be propagated on the cut (the function is "
789
+ "discontinuous there)")
790
+ with np.errstate(all="ignore"):
791
+ f, fx, fy, fxx, fxy, fyy = _rules.BINARY[name](np.float64(xv), np.float64(yv))
792
+ if xq and yq:
793
+ return _binary(x, y, f, fx, fy, fxx, fxy, fyy)
794
+ if xq:
795
+ return _unary(x, f, fx, fxx)
796
+ return _unary(y, f, fy, fyy)
797
+
798
+
799
+ def _pow_number(x: Quantity, p: float) -> Quantity:
800
+ if not _isfinite(p):
801
+ raise DomainError("the exponent must be finite")
802
+ if p == 0.0:
803
+ return _const(x._m, 1.0, x._z)
804
+ if p == 1.0:
805
+ return x
806
+ domain, nondiff, zero_ok = (bool(t) for t in _rules.pow_number_masks(x._v, p))
807
+ if domain:
808
+ raise DomainError(f"{x._v!r} ** {p!r} is outside the domain of the power function")
809
+ if nondiff:
810
+ if _errorless(x):
811
+ if zero_ok:
812
+ return _singular_exact("pow", x._m, 0.0, x._z, x)
813
+ raise DomainError(f"0 ** {p!r} is not defined")
814
+ raise NonDifferentiableError(f"x ** {p!r} is not differentiable at x = 0 (boundary of the domain [0, ∞)) and "
815
+ "the argument carries an error there")
816
+ with np.errstate(all="ignore"):
817
+ f, f1, f2 = _rules.pow_number(x._v, p)
818
+ return _unary(x, f, f1, f2)
819
+
820
+
821
+ def _unsupported(what: str):
822
+ def method(self, *args, **kwargs):
823
+ raise UnsupportedOperationError(f"{what} is not supported on quantities with errors: it is not "
824
+ "differentiable, or would lose the error silently (use .value for the "
825
+ "nominal value)")
826
+ method.__name__ = what
827
+ return method
828
+
829
+
830
+ class Quantity:
831
+ """A scalar quantity with errors: nominal value, sharp, and (second order) bias.
832
+
833
+ Quantities are immutable, created by a :class:`Model` or by operations, never by hand.
834
+
835
+ Attributes
836
+ ----------
837
+ model : Model
838
+ value : float
839
+ Nominal value.
840
+ gamma : float
841
+ Γ[q] = <q♯, q♯>: the error variance (quadratic error) of q, at gauge 1. This is the variance of the *error*
842
+ made on q, never the variance of q.
843
+ std : float
844
+ √Γ[q].
845
+ bias : float
846
+ A[q] (second order only; :class:`FirstOrderError` at order 1).
847
+ sharp : Mapping[str, float]
848
+ Source name -> coefficient of q♯ (sparse support). See the module documentation for the link with
849
+ Bouleau's sharp (2003, V.2.2).
850
+ """
851
+
852
+ __slots__ = ("_m", "_v", "_s", "_a", "_z", "_beta", "_kappa", "_inp")
853
+ __hash__ = None # == is the exact-zero rule of uncertainties: not hashable
854
+ __array_priority__ = 1000
855
+
856
+ def __init__(self, *args, **kwargs):
857
+ raise TypeError("Quantity objects are created by a Model (Model.input, Model.correlated, ...) or by "
858
+ "operations, never by hand")
859
+
860
+ def __setattr__(self, name, value):
861
+ raise AttributeError("Quantity objects are immutable")
862
+
863
+ def __delattr__(self, name):
864
+ raise AttributeError("Quantity objects are immutable")
865
+
866
+ def __getstate__(self):
867
+ return (self._m, self._v, self._s, self._a, self._z, self._beta, self._kappa, self._inp)
868
+
869
+ def __setstate__(self, state):
870
+ for k, v in zip(Quantity.__slots__, state):
871
+ _set(self, k, v)
872
+
873
+ # --- readings -----------------------------------------------------------------------------------------------
874
+ @property
875
+ def model(self) -> Model:
876
+ return self._m
877
+
878
+ @property
879
+ def value(self) -> float:
880
+ return self._v
881
+
882
+ @property
883
+ def gamma(self) -> float:
884
+ return _sq(self._s)
885
+
886
+ @property
887
+ def std(self) -> float:
888
+ """√Γ, as a scaled norm: representable even where Γ over- or underflows."""
889
+ if not self._s:
890
+ return 0.0
891
+ M = max(abs(c) for c in self._s.values())
892
+ return M * math.sqrt(math.fsum([(c / M) ** 2 for c in self._s.values()]))
893
+
894
+ @property
895
+ def bias(self) -> float:
896
+ if self._a is None:
897
+ raise FirstOrderError("a first-order model does not propagate biases: declare the model with order=2 "
898
+ "to obtain A")
899
+ return self._a
900
+
901
+ @property
902
+ def sharp(self) -> Mapping[str, float]:
903
+ names = self._m._src_names
904
+ return MappingProxyType({names[k]: c for k, c in sorted(self._s.items())})
905
+
906
+ def summary(self, *, scale: float = 1.0) -> ErrorSummary:
907
+ """The error at scale s = ε² (Bouleau's gauge): variance s·Γ, std √(s·Γ), bias s·A, value + s·A."""
908
+ s = _finite_real(scale, "scale")
909
+ if s < 0:
910
+ raise InputError("scale must be non-negative")
911
+ g = _sq(self._s)
912
+ var = s * g
913
+ b = None if self._a is None else s * self._a
914
+ if not _isfinite(var) or (b is not None and not (_isfinite(b) and _isfinite(self._v + b))):
915
+ raise NonFiniteError(f"summary at scale {s!r} overflows")
916
+ sd = math.sqrt(s) * self.std # scaled norm: no underflow of √(s·Γ), and equal to .std at s = 1
917
+ if self._a is None:
918
+ return ErrorSummary(self._v, s, 1, var, sd, None, None, ())
919
+ names = self._m._grp_names
920
+ return ErrorSummary(self._v, s, 2, var, sd, b, self._v + b,
921
+ tuple(names[g] for g in sorted(self._z)))
922
+
923
+ def __repr__(self) -> str:
924
+ if self._a is None:
925
+ return f"Quantity(value={self._v!r}, std={self.std!r})"
926
+ return f"Quantity(value={self._v!r}, std={self.std!r}, bias={self._a!r})"
927
+
928
+ def __str__(self) -> str:
929
+ if self._a is None:
930
+ return f"{self._v!r} ± {self.std!r}"
931
+ return f"{self._v!r} ± {self.std!r} [bias {self._a!r}]"
932
+
933
+ # --- arithmetic ---------------------------------------------------------------------------------------------
934
+ def _delegate(self, ufunc, *operands):
935
+ from ._array import apply_ufunc
936
+
937
+ return apply_ufunc(ufunc, operands)
938
+
939
+ def __add__(self, o):
940
+ if isinstance(o, Quantity):
941
+ return _linear(self, o, 1.0)
942
+ if _is_number(o):
943
+ return _shift(self, float(o))
944
+ if _is_arraylike(o):
945
+ return self._delegate(np.add, self, o)
946
+ return NotImplemented
947
+
948
+ def __radd__(self, o):
949
+ if _is_number(o):
950
+ return _shift(self, float(o))
951
+ if _is_arraylike(o):
952
+ return self._delegate(np.add, o, self)
953
+ return NotImplemented
954
+
955
+ def __sub__(self, o):
956
+ if isinstance(o, Quantity):
957
+ return _linear(self, o, -1.0)
958
+ if _is_number(o):
959
+ return _shift(self, -float(o))
960
+ if _is_arraylike(o):
961
+ return self._delegate(np.subtract, self, o)
962
+ return NotImplemented
963
+
964
+ def __rsub__(self, o):
965
+ if _is_number(o):
966
+ return _shift(_times(self, -1.0), float(o))
967
+ if _is_arraylike(o):
968
+ return self._delegate(np.subtract, o, self)
969
+ return NotImplemented
970
+
971
+ def __mul__(self, o):
972
+ if isinstance(o, Quantity):
973
+ if o._m is not self._m:
974
+ raise ModelMismatchError("these quantities belong to two different models")
975
+ f, fx, fy, fxx, fxy, fyy = _rules.mul(self._v, o._v)
976
+ return _binary(self, o, f, fx, fy, fxx, fxy, fyy)
977
+ if _is_number(o):
978
+ return _times(self, float(o))
979
+ if _is_arraylike(o):
980
+ return self._delegate(np.multiply, self, o)
981
+ return NotImplemented
982
+
983
+ def __rmul__(self, o):
984
+ if _is_number(o):
985
+ return _times(self, float(o))
986
+ if _is_arraylike(o):
987
+ return self._delegate(np.multiply, o, self)
988
+ return NotImplemented
989
+
990
+ def __truediv__(self, o):
991
+ if isinstance(o, Quantity):
992
+ if o._m is not self._m:
993
+ raise ModelMismatchError("these quantities belong to two different models")
994
+ if o._v == 0.0:
995
+ raise DomainError("division by a quantity of nominal value 0")
996
+ with np.errstate(all="ignore"):
997
+ d = _rules.div(self._v, o._v)
998
+ return _binary(self, o, *d)
999
+ if _is_number(o):
1000
+ c = float(o)
1001
+ if c == 0.0:
1002
+ raise DomainError("division by zero")
1003
+ return _new_div_number(self, c)
1004
+ if _is_arraylike(o):
1005
+ return self._delegate(np.true_divide, self, o)
1006
+ return NotImplemented
1007
+
1008
+ def __rtruediv__(self, o):
1009
+ if _is_number(o):
1010
+ if self._v == 0.0:
1011
+ raise DomainError("division by a quantity of nominal value 0")
1012
+ c = float(o)
1013
+ with np.errstate(all="ignore"):
1014
+ f, _, fy, _, _, fyy = _rules.div(c, self._v)
1015
+ return _unary(self, f, fy, fyy)
1016
+ if _is_arraylike(o):
1017
+ return self._delegate(np.true_divide, o, self)
1018
+ return NotImplemented
1019
+
1020
+ def __pow__(self, o, mod=None):
1021
+ if mod is not None:
1022
+ raise UnsupportedOperationError("pow with a modulus is not supported on quantities")
1023
+ if isinstance(o, Quantity):
1024
+ if o._m is not self._m:
1025
+ raise ModelMismatchError("these quantities belong to two different models")
1026
+ if not self._v > 0.0:
1027
+ raise DomainError("x ** y with an exponent carrying errors requires x > 0")
1028
+ with np.errstate(all="ignore"):
1029
+ d = _rules.pow_qq(self._v, o._v)
1030
+ return _binary(self, o, *d)
1031
+ if _is_number(o):
1032
+ return _pow_number(self, float(o))
1033
+ if _is_arraylike(o):
1034
+ return self._delegate(np.power, self, o)
1035
+ return NotImplemented
1036
+
1037
+ def __rpow__(self, o):
1038
+ if _is_number(o):
1039
+ b = float(o)
1040
+ if not b > 0.0 or not _isfinite(b):
1041
+ raise DomainError("b ** y with an exponent carrying errors requires b > 0")
1042
+ lb = math.log(b)
1043
+ with np.errstate(all="ignore"):
1044
+ f = np.power(b, self._v)
1045
+ return _unary(self, f, f * lb, f * lb * lb)
1046
+ if _is_arraylike(o):
1047
+ return self._delegate(np.power, o, self)
1048
+ return NotImplemented
1049
+
1050
+ def __neg__(self):
1051
+ return _times(self, -1.0)
1052
+
1053
+ def __pos__(self):
1054
+ return self
1055
+
1056
+ def __abs__(self):
1057
+ return _apply_unary("abs", self)
1058
+
1059
+ # --- comparisons --------------------------------------------------------------------------------------------
1060
+ def __eq__(self, o):
1061
+ # Values are compared first, so that == never overflows; then the difference must
1062
+ # carry exactly zero error.
1063
+ if isinstance(o, Quantity):
1064
+ if o._m is not self._m or o._v != self._v:
1065
+ return False
1066
+ try:
1067
+ d = _linear(self, o, -1.0)
1068
+ except NonFiniteError:
1069
+ return False
1070
+ elif _is_number(o):
1071
+ c = float(o)
1072
+ if not _isfinite(c) or c != self._v:
1073
+ return False
1074
+ return _is_exact(self)
1075
+ elif _is_arraylike(o):
1076
+ return self._delegate(np.equal, self, o)
1077
+ else:
1078
+ return NotImplemented
1079
+ return _is_exact(d)
1080
+
1081
+ def __ne__(self, o):
1082
+ r = self.__eq__(o)
1083
+ if r is NotImplemented:
1084
+ return r
1085
+ if isinstance(r, np.ndarray):
1086
+ return ~r
1087
+ return not r
1088
+
1089
+ def _cmp_value(self, o, op):
1090
+ if isinstance(o, Quantity):
1091
+ if o._m is not self._m:
1092
+ raise ModelMismatchError("these quantities belong to two different models")
1093
+ return op(self._v, o._v)
1094
+ if _is_number(o):
1095
+ return op(self._v, float(o))
1096
+ if _is_arraylike(o):
1097
+ from ._array import QuantityArray
1098
+
1099
+ other = o.values if isinstance(o, QuantityArray) else o
1100
+ if isinstance(o, QuantityArray) and o._m is not self._m:
1101
+ raise ModelMismatchError("these quantities belong to two different models")
1102
+ return op(self._v, other)
1103
+ return NotImplemented
1104
+
1105
+ def __lt__(self, o):
1106
+ return self._cmp_value(o, lambda a, b: a < b)
1107
+
1108
+ def __le__(self, o):
1109
+ return self._cmp_value(o, lambda a, b: a <= b)
1110
+
1111
+ def __gt__(self, o):
1112
+ return self._cmp_value(o, lambda a, b: a > b)
1113
+
1114
+ def __ge__(self, o):
1115
+ return self._cmp_value(o, lambda a, b: a >= b)
1116
+
1117
+ def __bool__(self):
1118
+ return not (self._v == 0.0 and _is_exact(self))
1119
+
1120
+ # --- refused conversions and non-differentiable operations --------------------------------------------------
1121
+ __float__ = _unsupported("float()")
1122
+ __int__ = _unsupported("int()")
1123
+ __index__ = _unsupported("index conversion")
1124
+ __complex__ = _unsupported("complex()")
1125
+ __round__ = _unsupported("round()")
1126
+ round = _unsupported("round()") # np.round(q) calls q.round(...)
1127
+ __round__ = _unsupported("round()")
1128
+ __floor__ = _unsupported("floor()")
1129
+ __ceil__ = _unsupported("ceil()")
1130
+ __trunc__ = _unsupported("trunc()")
1131
+ __mod__ = _unsupported("%")
1132
+ __rmod__ = _unsupported("%")
1133
+ __floordiv__ = _unsupported("//")
1134
+ __rfloordiv__ = _unsupported("//")
1135
+ __divmod__ = _unsupported("divmod()")
1136
+ __rdivmod__ = _unsupported("divmod()")
1137
+
1138
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
1139
+ from ._array import array_ufunc
1140
+
1141
+ return array_ufunc(ufunc, method, inputs, kwargs)
1142
+
1143
+
1144
+ def _new_div_number(x: Quantity, c: float) -> Quantity:
1145
+ """x / c, c a non-zero number: exact, no curvature. The value is computed as x.value / c (not x.value·(1/c))."""
1146
+ m = x._m
1147
+ inv = 1.0 / c
1148
+ s = _scale(inv, x._s)
1149
+ if m._order == 1:
1150
+ return _new(m, x._v / c, s, None, _EMPTY, None, None)
1151
+ beta = kappa = None
1152
+ if m._bb:
1153
+ beta = _scale(inv, x._beta)
1154
+ kappa = _scale(inv, x._kappa)
1155
+ return _new(m, x._v / c, s, inv * x._a if x._a else 0.0, x._z, beta, kappa)
1156
+
1157
+
1158
+ # ======================================================================================================================
1159
+ # Error summary
1160
+ # ======================================================================================================================
1161
+ @dataclass(frozen=True)
1162
+ class ErrorSummary:
1163
+ """The error of a quantity at a given scale s = ε² (a record, not a computation).
1164
+
1165
+ ``variance`` = s·Γ, ``std`` = √(s·Γ), ``bias`` = s·A and ``corrected_value`` = value + s·A (the "mean" of soerp
1166
+ and R propagate); ``bias`` and ``corrected_value`` are ``None`` at order 1. ``assumed_zero_bias`` lists
1167
+ the groups on which the quantity depends and whose bias was assumed to be zero.
1168
+ """
1169
+
1170
+ value: float
1171
+ scale: float
1172
+ order: int
1173
+ variance: float
1174
+ std: float
1175
+ bias: float | None
1176
+ corrected_value: float | None
1177
+ assumed_zero_bias: tuple
1178
+
1179
+ def __str__(self) -> str:
1180
+ text = f"{self.value!r} ± {self.std!r}"
1181
+ if self.scale != 1.0:
1182
+ text += f" (scale {self.scale!r})"
1183
+ if self.bias is not None:
1184
+ text += f" [bias {self.bias!r}, corrected value {self.corrected_value!r}]"
1185
+ if self.assumed_zero_bias:
1186
+ text += f" (bias assumed zero for: {', '.join(self.assumed_zero_bias)})"
1187
+ return text
1188
+
1189
+
1190
+ # ======================================================================================================================
1191
+ # Readings
1192
+ # ======================================================================================================================
1193
+ def gamma(f, g=None):
1194
+ """Γ[f] (``g`` omitted) or Γ[f, g]: the error variance, or error covariance, at gauge 1.
1195
+
1196
+ Numbers are exact (Γ = 0). Quantity arrays are read element by element.
1197
+ """
1198
+ from ._array import QuantityArray, elementwise_gamma
1199
+
1200
+ if isinstance(f, QuantityArray) or isinstance(g, QuantityArray):
1201
+ return elementwise_gamma(f, g)
1202
+ if g is None:
1203
+ if isinstance(f, Quantity):
1204
+ return _sq(f._s)
1205
+ if _is_number(f):
1206
+ return 0.0
1207
+ raise InputError("gamma expects quantities or numbers")
1208
+ if isinstance(f, Quantity) and isinstance(g, Quantity):
1209
+ if f._m is not g._m:
1210
+ raise ModelMismatchError("these quantities belong to two different models")
1211
+ return _dot(f._s, g._s)
1212
+ for q in (f, g):
1213
+ if not (isinstance(q, Quantity) or _is_number(q)):
1214
+ raise InputError("gamma expects quantities or numbers")
1215
+ return 0.0
1216
+
1217
+
1218
+ def gamma_via_bias(f, g=None) -> float:
1219
+ """A[f·g] − f·A[g] − g·A[f], which is Γ[f, g] by the product rule (second order only).
1220
+
1221
+ This exposes the identity Γ(F, G) = L(FG) − F L(G) − G L(F) (the carré du champ formula); with
1222
+ ``g=None``, Γ[f] = A[f²] − 2 f A[f].
1223
+ """
1224
+ if g is None:
1225
+ g = f
1226
+ for q in (f, g):
1227
+ if isinstance(q, Quantity):
1228
+ if q._m._order == 1:
1229
+ raise FirstOrderError("gamma_via_bias uses the bias operator A, which a first-order model does not "
1230
+ "propagate: declare the model with order=2")
1231
+ elif not _is_number(q):
1232
+ raise InputError("gamma_via_bias expects scalar quantities or numbers")
1233
+ if not isinstance(f, Quantity) and not isinstance(g, Quantity):
1234
+ return 0.0
1235
+ p = f * g
1236
+ fv, fa = (f._v, f._a) if isinstance(f, Quantity) else (float(f), 0.0)
1237
+ gv, ga = (g._v, g._a) if isinstance(g, Quantity) else (float(g), 0.0)
1238
+ return p._a - fv * ga - gv * fa
1239
+
1240
+
1241
+ def _collect(seq) -> tuple[Model | None, list]:
1242
+ from ._array import QuantityArray
1243
+
1244
+ if isinstance(seq, QuantityArray):
1245
+ seq = seq._tolist_flat()
1246
+ items = list(seq)
1247
+ model = None
1248
+ sharps = []
1249
+ for q in items:
1250
+ if isinstance(q, Quantity):
1251
+ if model is None:
1252
+ model = q._m
1253
+ elif q._m is not model:
1254
+ raise ModelMismatchError("these quantities belong to two different models")
1255
+ sharps.append(q._s)
1256
+ elif _is_number(q):
1257
+ sharps.append({})
1258
+ else:
1259
+ raise InputError("expected a sequence of quantities (or numbers)")
1260
+ return model, sharps
1261
+
1262
+
1263
+ def _sharp_matrix(sharps: list) -> np.ndarray:
1264
+ support = sorted(set().union(*sharps)) if sharps else []
1265
+ col = {k: j for j, k in enumerate(support)}
1266
+ S = np.zeros((len(sharps), len(support)))
1267
+ for i, s in enumerate(sharps):
1268
+ for k, c in s.items():
1269
+ S[i, col[k]] = c
1270
+ return S
1271
+
1272
+
1273
+ def covariance_matrix(seq) -> np.ndarray:
1274
+ """Matrix of Γ[q_i, q_j] (the covariance of the errors), symmetrised explicitly."""
1275
+ _, sharps = _collect(seq)
1276
+ S = _sharp_matrix(sharps)
1277
+ with np.errstate(all="ignore"):
1278
+ M = S @ S.T
1279
+ M = 0.5 * (M + M.T)
1280
+ if not np.all(np.isfinite(M)):
1281
+ raise NonFiniteError("the covariance matrix is not finite (overflow)")
1282
+ return M
1283
+
1284
+
1285
+ def correlation_matrix(seq) -> np.ndarray:
1286
+ """Matrix of correlations of the errors. A quantity without error gives nan on its row (NumPy RuntimeWarning)."""
1287
+ C = covariance_matrix(seq)
1288
+ d = np.sqrt(np.diag(C))
1289
+ R = C / np.outer(d, d)
1290
+ idx = np.flatnonzero(d > 0)
1291
+ R[idx, idx] = 1.0
1292
+ return R
1293
+
1294
+
1295
+ def contributions(q, *, by: Literal["group", "source"] = "group",
1296
+ kind: Literal["variance", "bias"] = "variance") -> dict:
1297
+ """Breakdown of Γ[q] (``kind="variance"``) or of A[q] (``kind="bias"``) by group or by source.
1298
+
1299
+ Variance: by source s, (q♯_s)²; by group g, Σ_{s∈g} (q♯_s)² = ∇Fᵀ C_g ∇F. The sum is Γ[q]. The split by group
1300
+ does not depend on the factorisation of a correlated group; the split by source does.
1301
+
1302
+ Bias (second order, ``bias_breakdown=True``): the keys ``"<group>:bias"`` carry the input-bias terms β_g, the
1303
+ other keys (``"<group>"`` by group, the source names by source) the curvature terms κ. The sum is A[q].
1304
+ """
1305
+ from ._array import QuantityArray, elementwise_contributions
1306
+
1307
+ if by not in ("group", "source"):
1308
+ raise InputError("by must be 'group' or 'source'")
1309
+ if kind not in ("variance", "bias"):
1310
+ raise InputError("kind must be 'variance' or 'bias'")
1311
+ if isinstance(q, QuantityArray):
1312
+ return elementwise_contributions(q, by=by, kind=kind)
1313
+ if _is_number(q):
1314
+ return {}
1315
+ if not isinstance(q, Quantity):
1316
+ raise InputError("contributions expects a quantity")
1317
+ m = q._m
1318
+ if kind == "bias":
1319
+ if m._order == 1:
1320
+ raise FirstOrderError("a first-order model does not propagate biases: declare the model with order=2")
1321
+ if not m._bb:
1322
+ raise NotTrackedError("the bias breakdown is tracked only in a model built with bias_breakdown=True")
1323
+ out = _bias_breakdown(m, q._beta, q._kappa, by)
1324
+ else:
1325
+ out = _variance_breakdown(m, q._s, by)
1326
+ if not all(math.isfinite(v) for v in out.values()):
1327
+ raise NonFiniteError(f"a contribution to the {kind} is not finite (overflow)")
1328
+ return out
1329
+
1330
+
1331
+ def _variance_breakdown(m: Model, s: dict, by: str) -> dict:
1332
+ if by == "source":
1333
+ return {m._src_names[k]: c * c for k, c in sorted(s.items())}
1334
+ per: dict[int, list] = {}
1335
+ for k, c in s.items():
1336
+ per.setdefault(m._src_group[k], []).append(c * c)
1337
+ return {m._grp_names[g]: math.fsum(v) for g, v in sorted(per.items())}
1338
+
1339
+
1340
+ def _bias_breakdown(m: Model, beta: dict, kappa: dict, by: str) -> dict:
1341
+ out = {f"{m._grp_names[g]}:bias": c for g, c in sorted(beta.items())}
1342
+ if by == "source":
1343
+ out.update({m._src_names[k]: c for k, c in sorted(kappa.items())})
1344
+ return out
1345
+ per: dict[int, list] = {}
1346
+ for k, c in kappa.items():
1347
+ per.setdefault(m._src_group[k], []).append(c)
1348
+ out.update({m._grp_names[g]: math.fsum(v) for g, v in sorted(per.items())})
1349
+ return out