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/__init__.py +15 -0
- errorcalculus/_array.py +1067 -0
- errorcalculus/_core.py +1349 -0
- errorcalculus/_functions.py +358 -0
- errorcalculus/_rules.py +256 -0
- errorcalculus/calculus.py +90 -0
- errorcalculus/compare.py +574 -0
- errorcalculus/errors.py +111 -0
- errorcalculus/linalg.py +249 -0
- errorcalculus/operators.py +207 -0
- errorcalculus-0.1.0.dist-info/METADATA +130 -0
- errorcalculus-0.1.0.dist-info/RECORD +15 -0
- errorcalculus-0.1.0.dist-info/WHEEL +5 -0
- errorcalculus-0.1.0.dist-info/licenses/LICENSE +28 -0
- errorcalculus-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Layer 1 of errorcalculus: the error calculus in finite dimension (public names, also exported at the root).
|
|
2
|
+
|
|
3
|
+
Propagation of the error variance Γ and, in a second-order model, of the bias A, through compositions of C²
|
|
4
|
+
functions evaluated at the nominal values (Bouleau's error calculus). The engine is
|
|
5
|
+
the Forward Laplacian recursion (Li et al. 2023), cited, not claimed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from ._array import QuantityArray, array
|
|
11
|
+
from ._core import (
|
|
12
|
+
ErrorSummary,
|
|
13
|
+
Model,
|
|
14
|
+
Quantity,
|
|
15
|
+
contributions,
|
|
16
|
+
correlation_matrix,
|
|
17
|
+
covariance_matrix,
|
|
18
|
+
gamma,
|
|
19
|
+
gamma_via_bias,
|
|
20
|
+
)
|
|
21
|
+
from .compare import Comparison, MethodResult, compare_methods
|
|
22
|
+
from ._functions import (
|
|
23
|
+
acos,
|
|
24
|
+
acosh,
|
|
25
|
+
asin,
|
|
26
|
+
asinh,
|
|
27
|
+
atan,
|
|
28
|
+
atan2,
|
|
29
|
+
atanh,
|
|
30
|
+
cos,
|
|
31
|
+
cosh,
|
|
32
|
+
erf,
|
|
33
|
+
erfc,
|
|
34
|
+
exp,
|
|
35
|
+
expm1,
|
|
36
|
+
hypot,
|
|
37
|
+
log,
|
|
38
|
+
log1p,
|
|
39
|
+
log2,
|
|
40
|
+
log10,
|
|
41
|
+
sensitivities,
|
|
42
|
+
sin,
|
|
43
|
+
sinh,
|
|
44
|
+
sqrt,
|
|
45
|
+
tan,
|
|
46
|
+
tanh,
|
|
47
|
+
wrap,
|
|
48
|
+
)
|
|
49
|
+
from .errors import (
|
|
50
|
+
ComparisonError,
|
|
51
|
+
CovarianceError,
|
|
52
|
+
DomainError,
|
|
53
|
+
DuplicateNameError,
|
|
54
|
+
ErrorCalculusError,
|
|
55
|
+
FirstOrderError,
|
|
56
|
+
InputError,
|
|
57
|
+
MissingBiasError,
|
|
58
|
+
ModelError,
|
|
59
|
+
ModelMismatchError,
|
|
60
|
+
NonDifferentiableError,
|
|
61
|
+
NonFiniteError,
|
|
62
|
+
NotAnInputError,
|
|
63
|
+
NotTrackedError,
|
|
64
|
+
NumericalDerivativeError,
|
|
65
|
+
NumericalDerivativeWarning,
|
|
66
|
+
OrderError,
|
|
67
|
+
TransportError,
|
|
68
|
+
UnsupportedDistributionError,
|
|
69
|
+
UnsupportedOperationError,
|
|
70
|
+
)
|
|
71
|
+
from .operators import BiasOperator
|
|
72
|
+
|
|
73
|
+
__all__ = [
|
|
74
|
+
# classes
|
|
75
|
+
"Model", "Quantity", "QuantityArray", "ErrorSummary", "BiasOperator", "Comparison", "MethodResult",
|
|
76
|
+
# readings and tools
|
|
77
|
+
"gamma", "gamma_via_bias", "covariance_matrix", "correlation_matrix", "contributions", "sensitivities", "array",
|
|
78
|
+
# elementary functions (23)
|
|
79
|
+
"exp", "expm1", "log", "log1p", "log2", "log10", "sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "atan2",
|
|
80
|
+
"sinh", "cosh", "tanh", "asinh", "acosh", "atanh", "hypot", "erf", "erfc",
|
|
81
|
+
# user functions
|
|
82
|
+
"wrap",
|
|
83
|
+
# comparison of methods (module errorcalculus.compare)
|
|
84
|
+
"compare_methods",
|
|
85
|
+
# exceptions and warning (20)
|
|
86
|
+
"ErrorCalculusError", "ModelError", "ModelMismatchError", "DuplicateNameError", "NotAnInputError", "OrderError",
|
|
87
|
+
"FirstOrderError", "InputError", "CovarianceError", "MissingBiasError", "DomainError", "NonDifferentiableError",
|
|
88
|
+
"NonFiniteError", "UnsupportedOperationError", "NotTrackedError", "NumericalDerivativeError", "TransportError",
|
|
89
|
+
"ComparisonError", "UnsupportedDistributionError", "NumericalDerivativeWarning",
|
|
90
|
+
]
|
errorcalculus/compare.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
1
|
+
"""The other cells of Bouleau's table: one model, several calculi.
|
|
2
|
+
|
|
3
|
+
:func:`compare_methods` evaluates the same function of the same inputs by several methods and reports their error
|
|
4
|
+
variances and biases side by side:
|
|
5
|
+
|
|
6
|
+
* ``"calculus"``: the error calculus of the model (Γ, and A at order 2), one pass;
|
|
7
|
+
* ``"gauss"``: the first-order calculus (Γ only), on a clone of the inputs in a first-order model;
|
|
8
|
+
* ``"sensitivity"``: the gradient (Bouleau's "deterministic infinitesimal" case);
|
|
9
|
+
* ``"sigma_points"``: 2k + 1 deterministic evaluations at finite scale s (error O(s));
|
|
10
|
+
* ``"monte_carlo"``: sampling at finite scale s (antithetic pairs for the symmetric laws "normal" and "uniform",
|
|
11
|
+
independent draws for a user law), centred variance (JCGM 101, 7.6), standard errors by batches;
|
|
12
|
+
* ``"taylor2"``: mean and variance of the quadratic Taylor polynomial under normal inputs (the "second-order
|
|
13
|
+
variance" of soerp and R propagate).
|
|
14
|
+
|
|
15
|
+
The finite-scale methods perturb the inputs as x̃ = x + s·b + √s·L z, where x are the nominal values, b the input
|
|
16
|
+
biases (0 at order 1), L the sharps of the inputs (n × k, on the k sources they carry), s = ε² the scale (Bouleau's
|
|
17
|
+
gauge, see :meth:`Quantity.summary`) and z has independent, centred, reduced components. Their variances and biases
|
|
18
|
+
are at scale s; ``gamma_estimate`` and ``bias_estimate`` divide them by s, for comparison with Γ and A.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import math
|
|
24
|
+
import numbers
|
|
25
|
+
import warnings
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from types import MappingProxyType
|
|
28
|
+
from typing import Mapping
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
|
|
32
|
+
from ._array import QuantityArray
|
|
33
|
+
from ._core import Model, Quantity, _is_number
|
|
34
|
+
from ._functions import _paired_form
|
|
35
|
+
from .errors import (
|
|
36
|
+
ComparisonError,
|
|
37
|
+
InputError,
|
|
38
|
+
ModelMismatchError,
|
|
39
|
+
NonFiniteError,
|
|
40
|
+
NotAnInputError,
|
|
41
|
+
UnsupportedDistributionError,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
__all__ = ["compare_methods", "Comparison", "MethodResult", "sigma_points", "monte_carlo", "taylor2_variance"]
|
|
45
|
+
|
|
46
|
+
METHODS = ("calculus", "gauss", "sensitivity", "sigma_points", "monte_carlo", "taylor2")
|
|
47
|
+
_BATCHES = 20
|
|
48
|
+
_MIN_PAIRS = 10 # pairs per batch, at least (Monte Carlo standard errors)
|
|
49
|
+
_TAYLOR2_WARN = 200 # directions beyond which taylor2 warns of its cost (as sensitivities beyond n = 200)
|
|
50
|
+
_CHUNK = 1 << 18 # samples per vectorised call of func (bounds the memory of the Monte Carlo method)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ======================================================================================================================
|
|
54
|
+
# Results
|
|
55
|
+
# ======================================================================================================================
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class MethodResult:
|
|
58
|
+
"""The result of one method. Variances and biases are at scale s; the estimates divide them by s."""
|
|
59
|
+
|
|
60
|
+
method: str
|
|
61
|
+
scale: float
|
|
62
|
+
value: float # F(x), at the nominal values
|
|
63
|
+
variance: float | None # at scale s
|
|
64
|
+
bias: float | None # at scale s; None if the method does not give it
|
|
65
|
+
gamma_estimate: float | None # variance / s
|
|
66
|
+
bias_estimate: float | None # bias / s
|
|
67
|
+
variance_stderr: float | None # Monte Carlo only (at scale s)
|
|
68
|
+
bias_stderr: float | None
|
|
69
|
+
gradient: np.ndarray | None # "sensitivity" only: ∂F/∂x_i, in the order of the flattened inputs
|
|
70
|
+
n_evaluations: int
|
|
71
|
+
notes: tuple = ()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Comparison:
|
|
75
|
+
"""Results of :func:`compare_methods`, by method name (in the order requested)."""
|
|
76
|
+
|
|
77
|
+
def __init__(self, results: dict):
|
|
78
|
+
self._results = dict(results)
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def results(self) -> Mapping[str, MethodResult]:
|
|
82
|
+
return MappingProxyType(self._results)
|
|
83
|
+
|
|
84
|
+
def __repr__(self) -> str:
|
|
85
|
+
return f"Comparison({', '.join(self._results)})"
|
|
86
|
+
|
|
87
|
+
def table(self) -> str:
|
|
88
|
+
"""One line per method: value, variance, std, bias (at scale s) and the number of evaluations of func."""
|
|
89
|
+
|
|
90
|
+
def fmt(v):
|
|
91
|
+
return "-" if v is None else f"{v:.6g}"
|
|
92
|
+
|
|
93
|
+
head = f"{'method':<13} {'value':>13} {'variance':>13} {'std':>13} {'bias':>13} {'evaluations':>11}"
|
|
94
|
+
lines = [head, "-" * len(head)]
|
|
95
|
+
for name, r in self._results.items():
|
|
96
|
+
std = None if r.variance is None else math.sqrt(r.variance)
|
|
97
|
+
lines.append(f"{name:<13} {fmt(r.value):>13} {fmt(r.variance):>13} {fmt(std):>13} {fmt(r.bias):>13} "
|
|
98
|
+
f"{r.n_evaluations:>11}")
|
|
99
|
+
return "\n".join(lines)
|
|
100
|
+
|
|
101
|
+
def discrepancy(self, *, reference: str = "calculus") -> dict:
|
|
102
|
+
"""Relative gaps ``(est − ref)/|ref|`` of Γ and A estimates, method by method, against ``reference``.
|
|
103
|
+
|
|
104
|
+
A key is omitted when the reference or the method does not give that quantity (never nan); a zero reference
|
|
105
|
+
gives 0 for an equal estimate and ±inf otherwise. The reference itself and the methods without variance
|
|
106
|
+
(``"sensitivity"``) are omitted.
|
|
107
|
+
"""
|
|
108
|
+
if reference not in self._results:
|
|
109
|
+
raise ComparisonError(f"the reference method {reference!r} is not among the results "
|
|
110
|
+
f"({', '.join(self._results)})")
|
|
111
|
+
ref = self._results[reference]
|
|
112
|
+
out = {}
|
|
113
|
+
for name, r in self._results.items():
|
|
114
|
+
if name == reference or r.gamma_estimate is None:
|
|
115
|
+
continue
|
|
116
|
+
d = {}
|
|
117
|
+
if ref.gamma_estimate is not None:
|
|
118
|
+
d["gamma"] = _rel(r.gamma_estimate, ref.gamma_estimate)
|
|
119
|
+
if ref.bias_estimate is not None and r.bias_estimate is not None:
|
|
120
|
+
d["bias"] = _rel(r.bias_estimate, ref.bias_estimate)
|
|
121
|
+
out[name] = d
|
|
122
|
+
return out
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _rel(est: float, ref: float) -> float:
|
|
126
|
+
if ref == 0.0:
|
|
127
|
+
return 0.0 if est == 0.0 else math.copysign(math.inf, est)
|
|
128
|
+
return (est - ref) / abs(ref)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# ======================================================================================================================
|
|
132
|
+
# Inputs: x, b, L, and the structure of the arguments of func
|
|
133
|
+
# ======================================================================================================================
|
|
134
|
+
class _Inputs:
|
|
135
|
+
"""The inputs of a comparison: n distinct scalar inputs (values x, biases b, sharps L on k sources) and the
|
|
136
|
+
structure of the arguments of func (a scalar input, or an array of inputs, per argument)."""
|
|
137
|
+
|
|
138
|
+
def __init__(self, inputs):
|
|
139
|
+
if isinstance(inputs, (Quantity, QuantityArray)) or not isinstance(inputs, (list, tuple)):
|
|
140
|
+
raise InputError("inputs must be a list (or tuple) of arguments, each an input or an array of inputs; "
|
|
141
|
+
"for a single argument write [x]")
|
|
142
|
+
model = None
|
|
143
|
+
uniq: list = []
|
|
144
|
+
pos: dict = {}
|
|
145
|
+
structure = []
|
|
146
|
+
for arg in inputs:
|
|
147
|
+
if isinstance(arg, Quantity):
|
|
148
|
+
elems, shape = [arg], None
|
|
149
|
+
elif isinstance(arg, QuantityArray):
|
|
150
|
+
if arg._objs is None:
|
|
151
|
+
raise NotAnInputError("an array argument must be made of inputs (Model.input_array, "
|
|
152
|
+
"Model.correlated(as_array=True), or errorcalculus.array of inputs)")
|
|
153
|
+
elems, shape = list(arg._objs.ravel()), arg.shape
|
|
154
|
+
else:
|
|
155
|
+
raise NotAnInputError(f"an argument of type {type(arg).__name__} is not an input of a model")
|
|
156
|
+
idx = []
|
|
157
|
+
for q in elems:
|
|
158
|
+
if model is None:
|
|
159
|
+
model = q._m
|
|
160
|
+
elif q._m is not model:
|
|
161
|
+
raise ModelMismatchError("these quantities belong to two different models")
|
|
162
|
+
if not q._inp:
|
|
163
|
+
raise NotAnInputError("compare_methods takes the inputs of a model (as declared), not derived "
|
|
164
|
+
"quantities")
|
|
165
|
+
key = id(q)
|
|
166
|
+
if key not in pos:
|
|
167
|
+
pos[key] = len(uniq)
|
|
168
|
+
uniq.append(q)
|
|
169
|
+
idx.append(pos[key])
|
|
170
|
+
structure.append(idx[0] if shape is None else np.array(idx, dtype=np.intp).reshape(shape))
|
|
171
|
+
if model is None:
|
|
172
|
+
raise InputError("inputs is empty")
|
|
173
|
+
self.model = model
|
|
174
|
+
self.quantities = uniq
|
|
175
|
+
self.structure = structure
|
|
176
|
+
n = len(uniq)
|
|
177
|
+
self.n = n
|
|
178
|
+
self.x = np.array([q._v for q in uniq])
|
|
179
|
+
self.b = np.array([q._a for q in uniq]) if model._order == 2 else np.zeros(n)
|
|
180
|
+
support = sorted(set().union(*[q._s.keys() for q in uniq]))
|
|
181
|
+
col = {s: j for j, s in enumerate(support)}
|
|
182
|
+
L = np.zeros((n, len(support)))
|
|
183
|
+
for i, q in enumerate(uniq):
|
|
184
|
+
for s, c in q._s.items():
|
|
185
|
+
L[i, col[s]] = c
|
|
186
|
+
self.L = L
|
|
187
|
+
self.k = len(support)
|
|
188
|
+
groups = sorted(set().union(*[q._z for q in uniq]))
|
|
189
|
+
self.assumed = tuple(model._grp_names[g] for g in groups)
|
|
190
|
+
|
|
191
|
+
# --- arguments of func ----------------------------------------------------------------------------------------
|
|
192
|
+
def args_from_quantities(self, qs: list) -> list:
|
|
193
|
+
"""Arguments of func from n scalar quantities (in the order of the distinct inputs)."""
|
|
194
|
+
out = []
|
|
195
|
+
for st in self.structure:
|
|
196
|
+
if isinstance(st, np.ndarray):
|
|
197
|
+
objs = np.empty(st.shape, dtype=object)
|
|
198
|
+
for ix in np.ndindex(st.shape):
|
|
199
|
+
objs[ix] = qs[int(st[ix])]
|
|
200
|
+
out.append(QuantityArray._from_quantities(objs, qs[0]._m if qs else None))
|
|
201
|
+
else:
|
|
202
|
+
out.append(qs[st])
|
|
203
|
+
return out
|
|
204
|
+
|
|
205
|
+
def args_from_values(self, X: np.ndarray) -> list:
|
|
206
|
+
"""Arguments of func from values X (n, ...): a scalar argument gets X[i], an array argument of shape S an
|
|
207
|
+
ndarray of shape S + X.shape[1:] (the axis of samples last)."""
|
|
208
|
+
return [X[st] for st in self.structure]
|
|
209
|
+
|
|
210
|
+
def notes(self) -> tuple:
|
|
211
|
+
out = []
|
|
212
|
+
if self.model._order == 1:
|
|
213
|
+
out.append("first-order model: the input biases are not declared (b = 0)")
|
|
214
|
+
elif self.assumed:
|
|
215
|
+
out.append(f"bias assumed zero for: {', '.join(self.assumed)}")
|
|
216
|
+
return tuple(out)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _check_scale(scale) -> float:
|
|
220
|
+
if isinstance(scale, bool) or not isinstance(scale, numbers.Real):
|
|
221
|
+
raise InputError("scale must be a positive number")
|
|
222
|
+
s = float(scale)
|
|
223
|
+
if not (math.isfinite(s) and s > 0.0):
|
|
224
|
+
raise InputError("scale must be positive and finite (the methods at finite scale divide by it)")
|
|
225
|
+
return s
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _scalar_output(F, method: str, model: Model | None = None):
|
|
229
|
+
if isinstance(F, QuantityArray) or (isinstance(F, np.ndarray) and F.ndim > 0):
|
|
230
|
+
raise ComparisonError(f"{method}: func must return a scalar (a vector output is not supported in 0.1.0)")
|
|
231
|
+
if isinstance(F, Quantity):
|
|
232
|
+
if model is not None and F._m is not model:
|
|
233
|
+
# a quantity captured from outside the arguments: its sharp is indexed by the sources of another model
|
|
234
|
+
raise ModelMismatchError(f"{method}: func returned a quantity of another model (computed from "
|
|
235
|
+
"quantities outside its arguments)")
|
|
236
|
+
return F
|
|
237
|
+
if _is_number(F):
|
|
238
|
+
return F
|
|
239
|
+
raise ComparisonError(f"{method}: func must return a scalar, got {type(F).__name__}")
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _eval_points(func, inp: _Inputs, X: np.ndarray, vectorized: bool, method: str) -> np.ndarray:
|
|
243
|
+
"""F at the points X (n, N): one vectorised call per chunk, or a Python loop. NumPy's floating-point warnings
|
|
244
|
+
are silenced: a non-finite value raises NonFiniteError below, with an explicit message."""
|
|
245
|
+
with np.errstate(all="ignore"):
|
|
246
|
+
return _eval_points_raw(func, inp, X, vectorized, method)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _eval_points_raw(func, inp: _Inputs, X: np.ndarray, vectorized: bool, method: str) -> np.ndarray:
|
|
250
|
+
N = X.shape[1]
|
|
251
|
+
out = np.empty(N)
|
|
252
|
+
if vectorized:
|
|
253
|
+
for start in range(0, N, _CHUNK):
|
|
254
|
+
stop = min(start + _CHUNK, N)
|
|
255
|
+
r = func(*inp.args_from_values(X[:, start:stop]))
|
|
256
|
+
if isinstance(r, (Quantity, QuantityArray)):
|
|
257
|
+
raise ComparisonError(f"{method}: func returned a quantity on plain numbers (it must be written "
|
|
258
|
+
"with the functions of errorcalculus, which return plain NumPy results on "
|
|
259
|
+
"numbers)")
|
|
260
|
+
try:
|
|
261
|
+
r = np.asarray(r, dtype=float)
|
|
262
|
+
except (TypeError, ValueError) as exc:
|
|
263
|
+
raise ComparisonError(f"{method}: func must return real numbers") from exc
|
|
264
|
+
if r.ndim == 0 and stop - start == 1:
|
|
265
|
+
r = r.reshape(1)
|
|
266
|
+
elif r.ndim == 0:
|
|
267
|
+
# a reduction over all axes (np.sum, np.linalg.norm, ... without axis=) also sums the axis of samples
|
|
268
|
+
# and returns one number: copying it to every sample gave silently wrong results
|
|
269
|
+
raise ComparisonError(f"{method}: with vectorized=True, func returned a single number for "
|
|
270
|
+
f"{stop - start} samples; it must keep the axis of samples (the last one): "
|
|
271
|
+
"reduce with axis=0 (or the axes of the argument), or pass vectorized=False")
|
|
272
|
+
if r.shape != (stop - start,):
|
|
273
|
+
raise ComparisonError(f"{method}: with vectorized=True, func must return one value per sample (shape "
|
|
274
|
+
f"({stop - start},), got {r.shape}); a vector output is not supported in "
|
|
275
|
+
"0.1.0, or pass vectorized=False")
|
|
276
|
+
out[start:stop] = r
|
|
277
|
+
else:
|
|
278
|
+
for t in range(N):
|
|
279
|
+
r = func(*[(float(a) if np.ndim(a) == 0 else a) for a in inp.args_from_values(X[:, t])])
|
|
280
|
+
r = _scalar_output(r, method)
|
|
281
|
+
if isinstance(r, Quantity):
|
|
282
|
+
raise ComparisonError(f"{method}: func returned a quantity on plain numbers")
|
|
283
|
+
out[t] = float(r)
|
|
284
|
+
if not np.all(np.isfinite(out)):
|
|
285
|
+
raise NonFiniteError(f"{method}: func is not finite at some of the perturbed inputs (they may leave its "
|
|
286
|
+
"domain): reduce the scale")
|
|
287
|
+
return out
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
# ======================================================================================================================
|
|
291
|
+
# The methods
|
|
292
|
+
# ======================================================================================================================
|
|
293
|
+
_FLOAT_FIELDS = ("value", "variance", "bias", "gamma_estimate", "bias_estimate", "variance_stderr", "bias_stderr")
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _checked(method, s, *, notes=(), n_eval=1, gradient=None, **fields) -> MethodResult:
|
|
297
|
+
"""A MethodResult whose numbers are Python floats, all finite: an overflow raises NonFiniteError, never an inf
|
|
298
|
+
returned silently (G17). ``s`` = scale."""
|
|
299
|
+
out = {}
|
|
300
|
+
for name in _FLOAT_FIELDS:
|
|
301
|
+
v = fields.get(name)
|
|
302
|
+
if v is not None:
|
|
303
|
+
v = float(v)
|
|
304
|
+
if not math.isfinite(v):
|
|
305
|
+
raise NonFiniteError(f"{method}: the {name.replace('_', ' ')} is not finite (overflow); reduce the "
|
|
306
|
+
"scale, or rescale the problem")
|
|
307
|
+
out[name] = v
|
|
308
|
+
if gradient is not None and not np.all(np.isfinite(gradient)):
|
|
309
|
+
raise NonFiniteError(f"{method}: the gradient is not finite (overflow)")
|
|
310
|
+
return MethodResult(method=method, scale=s, gradient=gradient, n_evaluations=int(n_eval), notes=tuple(notes),
|
|
311
|
+
**out)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _result(method, s, value, gamma=None, a=None, *, var_se=None, bias_se=None, gradient=None, n_eval=1, notes=()):
|
|
315
|
+
"""Result from estimates of Γ and A (gauge 1): variance = s·Γ, bias = s·A."""
|
|
316
|
+
with np.errstate(all="ignore"):
|
|
317
|
+
var = None if gamma is None else s * gamma
|
|
318
|
+
bias = None if a is None else s * a
|
|
319
|
+
return _checked(method, s, value=value, variance=var,
|
|
320
|
+
bias=bias, gamma_estimate=gamma, bias_estimate=a, variance_stderr=var_se,
|
|
321
|
+
bias_stderr=bias_se, gradient=gradient, n_eval=n_eval, notes=notes)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _calculus(func, inp: _Inputs, s: float) -> MethodResult:
|
|
325
|
+
F = _scalar_output(func(*inp.args_from_quantities(inp.quantities)), "calculus", inp.model)
|
|
326
|
+
if not isinstance(F, Quantity):
|
|
327
|
+
return _result("calculus", s, float(F), 0.0, None if inp.model._order == 1 else 0.0, notes=inp.notes())
|
|
328
|
+
notes = list(inp.notes())
|
|
329
|
+
return _result("calculus", s, F._v, F.gamma, F._a, notes=notes)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _gauss(func, inp: _Inputs, s: float) -> MethodResult:
|
|
333
|
+
m1 = Model(order=1)
|
|
334
|
+
qs = m1._from_factor(inp.x, inp.L, None)
|
|
335
|
+
F = _scalar_output(func(*inp.args_from_quantities(qs)), "gauss", m1)
|
|
336
|
+
gamma = F.gamma if isinstance(F, Quantity) else 0.0
|
|
337
|
+
value = F._v if isinstance(F, Quantity) else float(F)
|
|
338
|
+
return _result("gauss", s, value, gamma, None, notes=("first-order calculus (Gauss): error variances only",))
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _sensitivity(func, inp: _Inputs, s: float) -> MethodResult:
|
|
342
|
+
m1 = Model(order=1)
|
|
343
|
+
qs = m1._from_factor(inp.x, np.eye(inp.n), None)
|
|
344
|
+
ids = m1._grp_sources[-1]
|
|
345
|
+
F = _scalar_output(func(*inp.args_from_quantities(qs)), "sensitivity", m1)
|
|
346
|
+
if isinstance(F, Quantity):
|
|
347
|
+
grad, value = np.array([F._s.get(k, 0.0) for k in ids]), F._v
|
|
348
|
+
else:
|
|
349
|
+
grad, value = np.zeros(inp.n), float(F)
|
|
350
|
+
return _result("sensitivity", s, value, gradient=grad,
|
|
351
|
+
notes=("gradient with respect to the distinct inputs, in the order of the arguments",))
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _sigma_points(func, inp: _Inputs, s: float, vectorized: bool) -> MethodResult:
|
|
355
|
+
x, b, L, k = inp.x, inp.b, inp.L, inp.k
|
|
356
|
+
c = x + s * b
|
|
357
|
+
if k == 0:
|
|
358
|
+
X = np.stack([x, c], axis=1)
|
|
359
|
+
else:
|
|
360
|
+
D = math.sqrt(k * s) * L # x_j^± = x + s·b ± √(k s)·L e_j
|
|
361
|
+
X = np.concatenate([x[:, None], c[:, None] + D, c[:, None] - D], axis=1)
|
|
362
|
+
Fv = _eval_points(func, inp, X, vectorized, "sigma_points")
|
|
363
|
+
F0 = Fv[0]
|
|
364
|
+
notes = list(inp.notes())
|
|
365
|
+
if k == 0:
|
|
366
|
+
return _result("sigma_points", s, F0, 0.0, (Fv[1] - F0) / s, n_eval=2, notes=notes)
|
|
367
|
+
Fp, Fm = Fv[1:k + 1], Fv[k + 1:]
|
|
368
|
+
with np.errstate(all="ignore"):
|
|
369
|
+
a_hat = _fsum(0.5 * (Fp + Fm) - F0) / k / s
|
|
370
|
+
g_hat = _fsum((0.5 * (Fp - Fm)) ** 2) / k / s
|
|
371
|
+
notes.append("deterministic sigma points x + s·b ± √(k s)·L e_j: error O(s); exact for a quadratic F only if "
|
|
372
|
+
"b = 0")
|
|
373
|
+
return _result("sigma_points", s, F0, g_hat, a_hat, n_eval=2 * k + 1, notes=notes)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _fsum(a) -> float:
|
|
377
|
+
"""math.fsum, with inf instead of OverflowError (the result is then refused by _checked)."""
|
|
378
|
+
try:
|
|
379
|
+
return math.fsum(np.ravel(a))
|
|
380
|
+
except OverflowError:
|
|
381
|
+
return math.inf
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _draw(rng, distribution, shape) -> np.ndarray:
|
|
385
|
+
if callable(distribution):
|
|
386
|
+
z = np.asarray(distribution(rng, shape), dtype=float)
|
|
387
|
+
if z.shape != shape or not np.all(np.isfinite(z)):
|
|
388
|
+
raise InputError(f"the distribution callable must return finite values of shape {shape}")
|
|
389
|
+
return z
|
|
390
|
+
if distribution == "normal":
|
|
391
|
+
return rng.standard_normal(shape)
|
|
392
|
+
if distribution == "uniform":
|
|
393
|
+
r = math.sqrt(3.0)
|
|
394
|
+
return rng.uniform(-r, r, shape)
|
|
395
|
+
raise UnsupportedDistributionError(f"unknown distribution {distribution!r}: 'normal', 'uniform' or a callable "
|
|
396
|
+
"(rng, shape) -> z")
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _monte_carlo(func, inp: _Inputs, s: float, distribution, n_samples, seed, vectorized: bool) -> MethodResult:
|
|
400
|
+
n_min = 2 * _BATCHES * _MIN_PAIRS
|
|
401
|
+
if isinstance(n_samples, bool) or not isinstance(n_samples, numbers.Integral) or n_samples < n_min:
|
|
402
|
+
raise InputError(f"n_samples must be an integer ≥ {n_min} ({_BATCHES} batches of {_MIN_PAIRS} pairs at "
|
|
403
|
+
"least, for the standard error of the variance)")
|
|
404
|
+
if not (callable(distribution) or distribution in ("normal", "uniform")):
|
|
405
|
+
_draw(None, distribution, (0,))
|
|
406
|
+
x, b, L, k = inp.x, inp.b, inp.L, inp.k
|
|
407
|
+
c = x + s * b
|
|
408
|
+
notes = list(inp.notes())
|
|
409
|
+
F0 = _eval_points(func, inp, x[:, None], vectorized, "monte_carlo")[0]
|
|
410
|
+
if k == 0: # no source: deterministic
|
|
411
|
+
F1 = _eval_points(func, inp, c[:, None], vectorized, "monte_carlo")[0]
|
|
412
|
+
notes.append("no error source: deterministic shift by s·b (n_samples ignored)")
|
|
413
|
+
return _result("monte_carlo", s, F0, 0.0, (F1 - F0) / s, var_se=0.0, bias_se=0.0, n_eval=2, notes=notes)
|
|
414
|
+
rng = np.random.default_rng(seed)
|
|
415
|
+
P = int(n_samples) // 2
|
|
416
|
+
# Antithetic pairs (z, −z) only for the symmetric laws of the library: for a user law, which may be asymmetric,
|
|
417
|
+
# the pairs would simulate the symmetrised law (its odd moments lost, silently), so the 2P
|
|
418
|
+
# samples are then independent.
|
|
419
|
+
antithetic = not callable(distribution)
|
|
420
|
+
with np.errstate(all="ignore"):
|
|
421
|
+
if antithetic:
|
|
422
|
+
z = _draw(rng, distribution, (k, P))
|
|
423
|
+
D = math.sqrt(s) * (L @ z) # (n, P)
|
|
424
|
+
Dp, Dm = c[:, None] + D, c[:, None] - D
|
|
425
|
+
else:
|
|
426
|
+
z = _draw(rng, distribution, (k, 2 * P))
|
|
427
|
+
D = c[:, None] + math.sqrt(s) * (L @ z) # (n, 2P)
|
|
428
|
+
Dp, Dm = D[:, :P], D[:, P:]
|
|
429
|
+
Fp = _eval_points(func, inp, Dp, vectorized, "monte_carlo")
|
|
430
|
+
Fm = _eval_points(func, inp, Dm, vectorized, "monte_carlo")
|
|
431
|
+
with np.errstate(all="ignore"):
|
|
432
|
+
allv = np.concatenate([Fp, Fm])
|
|
433
|
+
mean = float(np.mean(allv))
|
|
434
|
+
var = float(np.sum((allv - mean) ** 2) / (allv.size - 1))
|
|
435
|
+
bias = mean - F0
|
|
436
|
+
# standard error of the bias: from the P pair means, which are independent (antithetic pairs), or from the
|
|
437
|
+
# 2P independent draws (user law)
|
|
438
|
+
units = 0.5 * (Fp + Fm) if antithetic else allv
|
|
439
|
+
bias_se = float(np.std(units, ddof=1) / math.sqrt(units.size))
|
|
440
|
+
# standard error of the variance: by _BATCHES batches of pairs (the two members of a pair are not
|
|
441
|
+
# independent), each of ≥ _MIN_PAIRS pairs (batches of one pair gave z-scores of
|
|
442
|
+
# standard deviation 1.5)
|
|
443
|
+
B = _BATCHES
|
|
444
|
+
edges = np.linspace(0, P, B + 1).astype(int)
|
|
445
|
+
bv = []
|
|
446
|
+
for lo, hi in zip(edges[:-1], edges[1:]):
|
|
447
|
+
v = np.concatenate([Fp[lo:hi], Fm[lo:hi]])
|
|
448
|
+
bv.append(float(np.sum((v - np.mean(v)) ** 2) / (v.size - 1)))
|
|
449
|
+
var_se = float(np.std(bv, ddof=1) / math.sqrt(B))
|
|
450
|
+
dname = distribution if isinstance(distribution, str) else "user callable"
|
|
451
|
+
kind = f"{P} antithetic pairs" if antithetic else "independent draws, no antithetic pairs (user law)"
|
|
452
|
+
notes.append(f"Monte Carlo: {2 * P} samples ({kind}), distribution {dname}; standard error of the bias from the "
|
|
453
|
+
f"{'pair means' if antithetic else 'draws'}, of the variance from {B} batches; centred variance "
|
|
454
|
+
"Var F(x̃) (JCGM 101)")
|
|
455
|
+
return _checked("monte_carlo", s, value=F0, variance=var, bias=bias, gamma_estimate=var / s,
|
|
456
|
+
bias_estimate=bias / s, variance_stderr=var_se, bias_stderr=bias_se, n_eval=2 * P + 1,
|
|
457
|
+
notes=notes)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _taylor2(func, inp: _Inputs, s: float) -> MethodResult:
|
|
461
|
+
x, b, L, k, n = inp.x, inp.b, inp.L, inp.k, inp.n
|
|
462
|
+
with_b = bool(np.any(b != 0.0))
|
|
463
|
+
D = np.concatenate([L, b[:, None]], axis=1) if with_b else L # directions (n × p)
|
|
464
|
+
p = D.shape[1]
|
|
465
|
+
if p > _TAYLOR2_WARN:
|
|
466
|
+
warnings.warn(f"taylor2: {p} directions, hence {p * (p + 1) // 2} evaluations of func (cost O(p³))",
|
|
467
|
+
RuntimeWarning, stacklevel=3)
|
|
468
|
+
call = lambda qs: func(*inp.args_from_quantities(qs)) # noqa: E731
|
|
469
|
+
# gradient along the directions: a first-order pass with the directions as sharps
|
|
470
|
+
m1 = Model(order=1)
|
|
471
|
+
qs = m1._from_factor(x, D, None)
|
|
472
|
+
ids = m1._grp_sources[-1]
|
|
473
|
+
F = _scalar_output(call(qs), "taylor2", m1)
|
|
474
|
+
value = F._v if isinstance(F, Quantity) else float(F)
|
|
475
|
+
gD = np.array([F._s.get(i, 0.0) for i in ids]) if isinstance(F, Quantity) else np.zeros(p)
|
|
476
|
+
M = _paired_form(call, x, D) if p else np.zeros((0, 0)) # Dᵀ ∇²F D, paired mode
|
|
477
|
+
g = gD[:k] # Lᵀ ∇F
|
|
478
|
+
Mk = M[:k, :k] # Lᵀ H L
|
|
479
|
+
with np.errstate(all="ignore"):
|
|
480
|
+
gamma = _fsum(g * g)
|
|
481
|
+
gb = gD[k] if with_b else 0.0 # ∇F · b
|
|
482
|
+
a = gb + 0.5 * _fsum(np.diag(Mk))
|
|
483
|
+
w = M[:k, k] if with_b else np.zeros(k) # Lᵀ H b
|
|
484
|
+
beta = M[k, k] if with_b else 0.0 # bᵀ H b
|
|
485
|
+
s3 = s * s * s # (not s ** 3: OverflowError on floats)
|
|
486
|
+
variance = (s * gamma + s * s * (0.5 * _fsum(Mk * Mk) + 2.0 * _fsum(g * w)) + s3 * _fsum(w * w))
|
|
487
|
+
bias = s * a + 0.5 * s * s * beta
|
|
488
|
+
notes = list(inp.notes())
|
|
489
|
+
notes.append("mean and variance of the quadratic Taylor polynomial under normal inputs (as soerp and R propagate "
|
|
490
|
+
"when b = 0); not the s² term of the true variance, which needs third derivatives (GUM 5.1.2)")
|
|
491
|
+
with np.errstate(all="ignore"):
|
|
492
|
+
g_est, a_est = variance / s, bias / s
|
|
493
|
+
return _checked("taylor2", s, value=value, variance=variance, bias=bias, gamma_estimate=g_est,
|
|
494
|
+
bias_estimate=a_est, n_eval=1 + p * (p + 1) // 2, notes=notes)
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
# ======================================================================================================================
|
|
498
|
+
# Public functions
|
|
499
|
+
# ======================================================================================================================
|
|
500
|
+
def sigma_points(func, inputs, *, scale=1.0, vectorized=True) -> MethodResult:
|
|
501
|
+
"""Deterministic sigma points at scale s: x_j^± = x + s·b ± √(k s)·L e_j, j = 1…k (2k + 1 evaluations).
|
|
502
|
+
|
|
503
|
+
 = mean_j[(F(x_j⁺) + F(x_j⁻))/2 − F(x)] / s and Γ̂ = mean_j[((F(x_j⁺) − F(x_j⁻))/2)²] / s. For a quadratic F of
|
|
504
|
+
Hessian H: Â − A = ½ s bᵀHb and Γ̂ − Γ = 2s ∇FᵀCHb + s² bᵀHCHb, so the estimates are exact only if b = 0; for a
|
|
505
|
+
general F the error is O(s). A relative of the unscented transform
|
|
506
|
+
(Julier and Uhlmann 2004), without a weight on the central point.
|
|
507
|
+
"""
|
|
508
|
+
return _sigma_points(func, _Inputs(inputs), _check_scale(scale), vectorized)
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def monte_carlo(func, inputs, *, scale=1.0, distribution="normal", n_samples=1_000_000, seed=None,
|
|
512
|
+
vectorized=True) -> MethodResult:
|
|
513
|
+
"""Monte Carlo at scale s: x̃ = x + s·b + √s·L z; centred variance Var F(x̃) (JCGM 101) and bias mean F(x̃) − F(x).
|
|
514
|
+
|
|
515
|
+
``distribution``: ``"normal"`` or ``"uniform"`` (on [−√3, √3]), sampled in antithetic pairs (z, −z), or a callable
|
|
516
|
+
``(rng, shape) -> z`` of centred, reduced values, sampled by independent draws (pairs would symmetrise an
|
|
517
|
+
asymmetric law). Standard error of the bias from the pair means (or the draws), of the variance from 20 batches
|
|
518
|
+
of pairs; ``n_samples`` ≥ 400. ``seed`` goes to :func:`numpy.random.default_rng`. With ``vectorized=True`` func
|
|
519
|
+
receives arrays with the axis of samples last and must keep it (a total reduction raises ComparisonError)."""
|
|
520
|
+
return _monte_carlo(func, _Inputs(inputs), _check_scale(scale), distribution, n_samples, seed, vectorized)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def taylor2_variance(func, inputs, *, scale=1.0) -> MethodResult:
|
|
524
|
+
"""Exact mean and variance of the quadratic Taylor polynomial of F under normal inputs x̃ = x + s·b + √s·L z.
|
|
525
|
+
|
|
526
|
+
variance = s Γ + s² [½ tr((HC)²) + 2 ∇Fᵀ C H b] + s³ bᵀHCHb, bias = s A + ½ s² bᵀHb (C = L Lᵀ). With b = 0 this
|
|
527
|
+
is the "second-order variance" of soerp and R propagate, s Γ + ½ s² tr((HC)²); it is not the s² term of the true
|
|
528
|
+
variance, which needs the third derivatives (GUM 5.1.2). The Hessian is computed by the paired mode of the engine
|
|
529
|
+
in the basis of the directions {L e_1, …, L e_k} (and b if b ≠ 0): 1 + p(p+1)/2 evaluations, p = k or k + 1.
|
|
530
|
+
"""
|
|
531
|
+
return _taylor2(func, _Inputs(inputs), _check_scale(scale))
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def compare_methods(func, inputs, *, methods=("calculus", "sigma_points", "monte_carlo"), scale=1.0,
|
|
535
|
+
distribution="normal", n_samples=1_000_000, seed=None, vectorized=True) -> Comparison:
|
|
536
|
+
"""Evaluate ``func`` of the same inputs by several methods (the cells of Bouleau's table) and compare them.
|
|
537
|
+
|
|
538
|
+
``inputs`` is a list of arguments, each an input of the model or an array of inputs (as declared: a derived
|
|
539
|
+
quantity raises :class:`NotAnInputError`), all of the same model; ``func`` receives one argument per element of
|
|
540
|
+
``inputs``, in order, as quantities (analytic methods) or as numbers / arrays of samples, the axis of samples last
|
|
541
|
+
(numerical methods), and returns a scalar. ``methods`` is an ordered subset of ``"calculus"``, ``"gauss"``,
|
|
542
|
+
``"sensitivity"``, ``"sigma_points"``, ``"monte_carlo"``, ``"taylor2"``. In a first-order model, ``"calculus"``
|
|
543
|
+
gives no bias, and the bias given by the other methods is the curvature only (b = 0), which their notes say.
|
|
544
|
+
"""
|
|
545
|
+
if isinstance(methods, str):
|
|
546
|
+
methods = (methods,)
|
|
547
|
+
methods = tuple(methods)
|
|
548
|
+
if not methods:
|
|
549
|
+
raise ComparisonError("no method requested")
|
|
550
|
+
for name in methods:
|
|
551
|
+
if name not in METHODS:
|
|
552
|
+
raise ComparisonError(f"unknown method {name!r}: choose among {', '.join(METHODS)}")
|
|
553
|
+
if len(set(methods)) != len(methods):
|
|
554
|
+
raise ComparisonError("a method is requested twice")
|
|
555
|
+
if "taylor2" in methods and distribution != "normal":
|
|
556
|
+
raise UnsupportedDistributionError("taylor2 assumes normal inputs: the terms of skewness and kurtosis need "
|
|
557
|
+
"input moments (not in 0.1.0)")
|
|
558
|
+
inp = _Inputs(inputs)
|
|
559
|
+
s = _check_scale(scale)
|
|
560
|
+
out = {}
|
|
561
|
+
for name in methods:
|
|
562
|
+
if name == "calculus":
|
|
563
|
+
out[name] = _calculus(func, inp, s)
|
|
564
|
+
elif name == "gauss":
|
|
565
|
+
out[name] = _gauss(func, inp, s)
|
|
566
|
+
elif name == "sensitivity":
|
|
567
|
+
out[name] = _sensitivity(func, inp, s)
|
|
568
|
+
elif name == "sigma_points":
|
|
569
|
+
out[name] = _sigma_points(func, inp, s, vectorized)
|
|
570
|
+
elif name == "monte_carlo":
|
|
571
|
+
out[name] = _monte_carlo(func, inp, s, distribution, n_samples, seed, vectorized)
|
|
572
|
+
else:
|
|
573
|
+
out[name] = _taylor2(func, inp, s)
|
|
574
|
+
return Comparison(out)
|