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,358 @@
|
|
|
1
|
+
"""Elementary functions, user functions (``wrap``) and sensitivities (private; public names in ``calculus``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
import math
|
|
7
|
+
import warnings
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from . import _rules
|
|
12
|
+
from ._array import QuantityArray, _as_qa, _binary_fn_array, _contains_quantity, _model_of, _unary_array, array
|
|
13
|
+
from ._core import (
|
|
14
|
+
Model,
|
|
15
|
+
Quantity,
|
|
16
|
+
_add_curvature,
|
|
17
|
+
_apply_binary,
|
|
18
|
+
_apply_unary,
|
|
19
|
+
_EMPTY,
|
|
20
|
+
_form_dot,
|
|
21
|
+
_finite_real,
|
|
22
|
+
_is_number,
|
|
23
|
+
_new,
|
|
24
|
+
)
|
|
25
|
+
from .errors import (
|
|
26
|
+
InputError,
|
|
27
|
+
ModelMismatchError,
|
|
28
|
+
NumericalDerivativeError,
|
|
29
|
+
NumericalDerivativeWarning,
|
|
30
|
+
UnsupportedOperationError,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
_EPS = float(np.finfo(float).eps)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ======================================================================================================================
|
|
37
|
+
# Elementary functions
|
|
38
|
+
# ======================================================================================================================
|
|
39
|
+
def _make_unary(name: str, doc: str):
|
|
40
|
+
def fn(x):
|
|
41
|
+
if isinstance(x, Quantity):
|
|
42
|
+
return _apply_unary(name, x)
|
|
43
|
+
if isinstance(x, QuantityArray):
|
|
44
|
+
return _unary_array(name, x)
|
|
45
|
+
if (isinstance(x, np.ndarray) and x.dtype == object) or (isinstance(x, (list, tuple))
|
|
46
|
+
and _contains_quantity(x)):
|
|
47
|
+
return _unary_array(name, array(x))
|
|
48
|
+
return _rules.VALUE[name](x)
|
|
49
|
+
|
|
50
|
+
fn.__name__ = fn.__qualname__ = name
|
|
51
|
+
fn.__doc__ = (f"{doc}\n\nAccepts a number, an ndarray (plain NumPy result), a Quantity or a QuantityArray "
|
|
52
|
+
"(propagation of the sharp and, at order 2, of the bias).")
|
|
53
|
+
return fn
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
exp = _make_unary("exp", "Exponential.")
|
|
57
|
+
expm1 = _make_unary("expm1", "exp(x) - 1, accurate near 0.")
|
|
58
|
+
log = _make_unary("log", "Natural logarithm (x > 0).")
|
|
59
|
+
log1p = _make_unary("log1p", "log(1 + x), accurate near 0 (x > -1).")
|
|
60
|
+
log2 = _make_unary("log2", "Base-2 logarithm (x > 0).")
|
|
61
|
+
log10 = _make_unary("log10", "Base-10 logarithm (x > 0).")
|
|
62
|
+
sqrt = _make_unary("sqrt", "Square root (x ≥ 0; not differentiable at 0).")
|
|
63
|
+
sin = _make_unary("sin", "Sine.")
|
|
64
|
+
cos = _make_unary("cos", "Cosine.")
|
|
65
|
+
tan = _make_unary("tan", "Tangent.")
|
|
66
|
+
asin = _make_unary("asin", "Arc sine (|x| ≤ 1; not differentiable at ±1).")
|
|
67
|
+
acos = _make_unary("acos", "Arc cosine (|x| ≤ 1; not differentiable at ±1).")
|
|
68
|
+
atan = _make_unary("atan", "Arc tangent.")
|
|
69
|
+
sinh = _make_unary("sinh", "Hyperbolic sine.")
|
|
70
|
+
cosh = _make_unary("cosh", "Hyperbolic cosine.")
|
|
71
|
+
tanh = _make_unary("tanh", "Hyperbolic tangent.")
|
|
72
|
+
asinh = _make_unary("asinh", "Inverse hyperbolic sine.")
|
|
73
|
+
acosh = _make_unary("acosh", "Inverse hyperbolic cosine (x ≥ 1; not differentiable at 1).")
|
|
74
|
+
atanh = _make_unary("atanh", "Inverse hyperbolic tangent (|x| < 1).")
|
|
75
|
+
erf = _make_unary("erf", "Error function.")
|
|
76
|
+
erfc = _make_unary("erfc", "Complementary error function.")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _quantities_in(o):
|
|
80
|
+
"""A (nested) list or object array of quantities becomes a QuantityArray; anything else is left as is."""
|
|
81
|
+
if (isinstance(o, (list, tuple)) and _contains_quantity(o)) or (isinstance(o, np.ndarray) and o.dtype == object):
|
|
82
|
+
return array(o)
|
|
83
|
+
return o
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _binary_public(name: str, a, b):
|
|
87
|
+
a, b = _quantities_in(a), _quantities_in(b)
|
|
88
|
+
ours = (Quantity, QuantityArray)
|
|
89
|
+
if not isinstance(a, ours) and not isinstance(b, ours):
|
|
90
|
+
return _rules.VALUE[name](a, b)
|
|
91
|
+
if (isinstance(a, Quantity) or _is_number(a)) and (isinstance(b, Quantity) or _is_number(b)):
|
|
92
|
+
return _apply_binary(name, a, b)
|
|
93
|
+
m = _model_of((a, b))
|
|
94
|
+
return _binary_fn_array(name, _as_qa(a, m), _as_qa(b, m))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def atan2(y, x):
|
|
98
|
+
"""atan2(y, x): angle of the point (x, y) (y is the first argument, as in math and NumPy).
|
|
99
|
+
|
|
100
|
+
Not differentiable at the origin, nor on the cut y = 0, x < 0 when y carries an error.
|
|
101
|
+
"""
|
|
102
|
+
return _binary_public("atan2", y, x)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def hypot(x, y):
|
|
106
|
+
"""√(x² + y²) (not differentiable at the origin)."""
|
|
107
|
+
return _binary_public("hypot", x, y)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ======================================================================================================================
|
|
111
|
+
# The n-ary rule (wrap)
|
|
112
|
+
# ======================================================================================================================
|
|
113
|
+
def _rule_n(m: Model, args: list, f: float, g: np.ndarray, H: np.ndarray | None) -> Quantity:
|
|
114
|
+
"""F(x_1, ..., x_n) from its gradient g and (order 2) Hessian H at the nominal values."""
|
|
115
|
+
qs = [(i, a) for i, a in enumerate(args) if isinstance(a, Quantity)]
|
|
116
|
+
s: dict = {}
|
|
117
|
+
for i, q in qs:
|
|
118
|
+
gi = float(g[i])
|
|
119
|
+
if gi:
|
|
120
|
+
for k, c in q._s.items():
|
|
121
|
+
s[k] = s.get(k, 0.0) + gi * c
|
|
122
|
+
s = {k: c for k, c in s.items() if c}
|
|
123
|
+
if m._order == 1:
|
|
124
|
+
return _new(m, f, s, None, _EMPTY, None, None)
|
|
125
|
+
terms = [float(g[i]) * q._a for i, q in qs if q._a and g[i]]
|
|
126
|
+
for i, qi in qs:
|
|
127
|
+
for j, qj in qs:
|
|
128
|
+
hij = float(H[i, j])
|
|
129
|
+
if hij and qi._s and qj._s:
|
|
130
|
+
terms.append(0.5 * hij * (_form_dot(m, qi._s, qj._s)))
|
|
131
|
+
a = math.fsum(terms)
|
|
132
|
+
z = frozenset().union(*[q._z for _, q in qs]) if qs else _EMPTY
|
|
133
|
+
beta = kappa = None
|
|
134
|
+
if m._bb:
|
|
135
|
+
beta, kappa = {}, {}
|
|
136
|
+
for i, q in qs:
|
|
137
|
+
gi = float(g[i])
|
|
138
|
+
if gi:
|
|
139
|
+
for key, c in q._beta.items():
|
|
140
|
+
beta[key] = beta.get(key, 0.0) + gi * c
|
|
141
|
+
for key, c in q._kappa.items():
|
|
142
|
+
kappa[key] = kappa.get(key, 0.0) + gi * c
|
|
143
|
+
for i, qi in qs:
|
|
144
|
+
for j, qj in qs:
|
|
145
|
+
hij = float(H[i, j])
|
|
146
|
+
if hij and qi._s and qj._s: # adds 2·(¼ H_ij)·x_i♯_s x_j♯_s = ½ H_ij x_i♯_s x_j♯_s
|
|
147
|
+
kappa = _add_curvature(kappa, qi._s, qj._s, 0.0, 0.25 * hij, 0.0)
|
|
148
|
+
beta = {k: c for k, c in beta.items() if c}
|
|
149
|
+
kappa = {k: c for k, c in kappa.items() if c}
|
|
150
|
+
return _new(m, f, s, a, z, beta, kappa)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _relative_gap(D1: np.ndarray, D2: np.ndarray) -> float:
|
|
154
|
+
return float(np.max(np.abs(D1 - D2), initial=0.0) / max(float(np.max(np.abs(D1), initial=0.0)), 1e-300))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _report(what: str, D1: np.ndarray, D2: np.ndarray, floor: float, rtol: float, check: bool, strict: bool) -> None:
|
|
158
|
+
"""Step-halving check: the gap (max norm) between the two estimates, relative to max|D1|, but never
|
|
159
|
+
to less than ``floor``, the natural scale of the derivative (|f|/x for the gradient, |f|/x² for the Hessian,
|
|
160
|
+
x = max(max|x_i|, 1)). Without the floor a derivative that is zero or tiny (stationary point, linear function
|
|
161
|
+
at order 2) raised spurious alarms. Alarm when max|D1 − D2| > rtol·max(max|D1|,
|
|
162
|
+
floor)."""
|
|
163
|
+
if not (check or strict):
|
|
164
|
+
return
|
|
165
|
+
gap = float(np.max(np.abs(D1 - D2), initial=0.0))
|
|
166
|
+
scale = float(np.max(np.abs(D1), initial=0.0))
|
|
167
|
+
if gap <= rtol * max(scale, floor):
|
|
168
|
+
return
|
|
169
|
+
msg = (f"numerical {what}: the step-halving check gives a relative gap {gap / max(scale, 1e-300):.3g} > "
|
|
170
|
+
f"{rtol:.3g} (beyond the rounding noise); give the {what} explicitly, or a step= adapted to the scale of "
|
|
171
|
+
"each variable")
|
|
172
|
+
if strict:
|
|
173
|
+
raise NumericalDerivativeError(msg)
|
|
174
|
+
warnings.warn(msg, NumericalDerivativeWarning, stacklevel=3)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def wrap(func, *, gradient=None, hessian=None, n_outputs=None, step=None, check=True, strict=False,
|
|
178
|
+
gradient_rtol=1e-6, hessian_rtol=1e-3):
|
|
179
|
+
"""Turn ``func(*floats) -> float`` (or a sequence of ``n_outputs`` floats) into a function of quantities.
|
|
180
|
+
|
|
181
|
+
The wrapped function accepts numbers (it then calls ``func`` directly) or quantities. ``gradient(*floats)``
|
|
182
|
+
returns (n,) or (m, n), ``hessian(*floats)`` (n, n) or (m, n, n); at order 1 the Hessian is neither requested nor
|
|
183
|
+
computed. Missing derivatives are computed by central differences: step ``ε^(1/3)·max(|x_i|, 1)`` for the gradient,
|
|
184
|
+
differences of the gradient (exact if given) with step ``ε^(1/4)·max(|x_i|, 1)`` for the Hessian; ``step`` (a number
|
|
185
|
+
or an array of n steps) replaces both. Each numerical derivative is recomputed with half the step: if the
|
|
186
|
+
relative gap (max norm) exceeds ``gradient_rtol`` / ``hessian_rtol``, a :class:`NumericalDerivativeWarning` is
|
|
187
|
+
issued (``check=True``), or a :class:`NumericalDerivativeError` raised (``strict=True``).
|
|
188
|
+
"""
|
|
189
|
+
if not callable(func):
|
|
190
|
+
raise InputError("wrap expects a callable")
|
|
191
|
+
if gradient is not None and not callable(gradient):
|
|
192
|
+
raise InputError("gradient must be a callable")
|
|
193
|
+
if hessian is not None and not callable(hessian):
|
|
194
|
+
raise InputError("hessian must be a callable")
|
|
195
|
+
if n_outputs is not None and (not isinstance(n_outputs, int) or n_outputs < 1):
|
|
196
|
+
raise InputError("n_outputs must be a positive integer")
|
|
197
|
+
|
|
198
|
+
def values(x: np.ndarray) -> np.ndarray:
|
|
199
|
+
r = func(*[float(t) for t in x])
|
|
200
|
+
if n_outputs is None:
|
|
201
|
+
if not _is_number(r):
|
|
202
|
+
raise InputError("the wrapped function must return a number (or give n_outputs=)")
|
|
203
|
+
return np.array([float(r)])
|
|
204
|
+
out = np.asarray(r, dtype=float)
|
|
205
|
+
if out.shape != (n_outputs,):
|
|
206
|
+
raise InputError(f"the wrapped function must return {n_outputs} numbers")
|
|
207
|
+
return out
|
|
208
|
+
|
|
209
|
+
def steps(x: np.ndarray, power: float) -> np.ndarray:
|
|
210
|
+
if step is None:
|
|
211
|
+
return _EPS ** power * np.maximum(np.abs(x), 1.0)
|
|
212
|
+
h = np.broadcast_to(np.asarray(step, dtype=float), x.shape).copy()
|
|
213
|
+
if not np.all(np.isfinite(h)) or np.any(h <= 0):
|
|
214
|
+
raise InputError("step must be positive and finite")
|
|
215
|
+
return h
|
|
216
|
+
|
|
217
|
+
def central(F, x: np.ndarray, h: np.ndarray) -> np.ndarray:
|
|
218
|
+
"""Central differences of F (x -> array) along each coordinate: result (..., n)."""
|
|
219
|
+
cols = []
|
|
220
|
+
for i in range(len(x)):
|
|
221
|
+
xp, xm = x.copy(), x.copy()
|
|
222
|
+
xp[i] += h[i]
|
|
223
|
+
xm[i] -= h[i]
|
|
224
|
+
cols.append((F(xp) - F(xm)) / (xp[i] - xm[i]))
|
|
225
|
+
return np.stack(cols, axis=-1)
|
|
226
|
+
|
|
227
|
+
def grad_fn(x: np.ndarray) -> np.ndarray:
|
|
228
|
+
g = np.asarray(gradient(*[float(t) for t in x]), dtype=float)
|
|
229
|
+
mo = 1 if n_outputs is None else n_outputs
|
|
230
|
+
if g.shape == (len(x),) and mo == 1:
|
|
231
|
+
g = g[None, :]
|
|
232
|
+
if g.shape != (mo, len(x)):
|
|
233
|
+
raise InputError(f"gradient must return an array of shape ({len(x)},) or ({mo}, {len(x)})")
|
|
234
|
+
return g
|
|
235
|
+
|
|
236
|
+
def wrapped(*args):
|
|
237
|
+
if any(isinstance(a, QuantityArray) for a in args):
|
|
238
|
+
raise UnsupportedOperationError("a wrapped function takes scalar quantities (unpack the array)")
|
|
239
|
+
qs = [a for a in args if isinstance(a, Quantity)]
|
|
240
|
+
if not qs:
|
|
241
|
+
return func(*args)
|
|
242
|
+
m = qs[0]._m
|
|
243
|
+
for q in qs[1:]:
|
|
244
|
+
if q._m is not m:
|
|
245
|
+
raise ModelMismatchError("these quantities belong to two different models")
|
|
246
|
+
x = np.array([a._v if isinstance(a, Quantity) else _finite_real(a, "argument") for a in args])
|
|
247
|
+
n = len(x)
|
|
248
|
+
y = values(x)
|
|
249
|
+
mo = len(y)
|
|
250
|
+
fscale = float(np.max(np.abs(y)))
|
|
251
|
+
xscale = max(float(np.max(np.abs(x))), 1.0)
|
|
252
|
+
# gradient
|
|
253
|
+
if gradient is not None:
|
|
254
|
+
G = grad_fn(x)
|
|
255
|
+
else:
|
|
256
|
+
h1 = steps(x, 1.0 / 3.0)
|
|
257
|
+
G = central(values, x, h1)
|
|
258
|
+
if check or strict:
|
|
259
|
+
_report("gradient", G, central(values, x, h1 / 2.0), fscale / xscale, gradient_rtol, check, strict)
|
|
260
|
+
# Hessian (order 2 only)
|
|
261
|
+
H = None
|
|
262
|
+
if m._order == 2:
|
|
263
|
+
if hessian is not None:
|
|
264
|
+
H = np.asarray(hessian(*[float(t) for t in x]), dtype=float)
|
|
265
|
+
if H.shape == (n, n) and mo == 1:
|
|
266
|
+
H = H[None]
|
|
267
|
+
if H.shape != (mo, n, n):
|
|
268
|
+
raise InputError(f"hessian must return an array of shape ({n}, {n}) or ({mo}, {n}, {n})")
|
|
269
|
+
if _relative_gap(H, np.swapaxes(H, 1, 2)) > hessian_rtol:
|
|
270
|
+
raise InputError("the Hessian given is not symmetric")
|
|
271
|
+
H = 0.5 * (H + np.swapaxes(H, 1, 2))
|
|
272
|
+
else:
|
|
273
|
+
if gradient is not None:
|
|
274
|
+
gfun = grad_fn
|
|
275
|
+
else:
|
|
276
|
+
h1 = steps(x, 1.0 / 3.0)
|
|
277
|
+
gfun = lambda t: central(values, t, h1) # noqa: E731
|
|
278
|
+
h2 = steps(x, 0.25)
|
|
279
|
+
H = central(gfun, x, h2)
|
|
280
|
+
H = 0.5 * (H + np.swapaxes(H, 1, 2))
|
|
281
|
+
if check or strict:
|
|
282
|
+
H2 = central(gfun, x, h2 / 2.0)
|
|
283
|
+
H2 = 0.5 * (H2 + np.swapaxes(H2, 1, 2))
|
|
284
|
+
_report("Hessian", H, H2, fscale / xscale ** 2, hessian_rtol, check, strict)
|
|
285
|
+
outs = [_rule_n(m, list(args), float(y[o]), G[o], None if H is None else H[o]) for o in range(mo)]
|
|
286
|
+
return outs[0] if n_outputs is None else tuple(outs)
|
|
287
|
+
|
|
288
|
+
functools.update_wrapper(wrapped, func)
|
|
289
|
+
return wrapped
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
# ======================================================================================================================
|
|
293
|
+
# Sensitivities (Bouleau's "deterministic infinitesimal" case)
|
|
294
|
+
# ======================================================================================================================
|
|
295
|
+
def _scalar_result(F, what: str, model=None):
|
|
296
|
+
if isinstance(F, Quantity):
|
|
297
|
+
if model is not None and F._m is not model:
|
|
298
|
+
# a quantity captured from outside the arguments: its sharp is indexed by another model's sources
|
|
299
|
+
raise ModelMismatchError(f"{what}: the function returned a quantity of another model (computed from "
|
|
300
|
+
"quantities outside its arguments)")
|
|
301
|
+
return F
|
|
302
|
+
if _is_number(F):
|
|
303
|
+
return F
|
|
304
|
+
raise InputError(f"{what}: the function must return a scalar (a Quantity or a number)")
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _paired_form(call, x: np.ndarray, D: np.ndarray) -> np.ndarray:
|
|
308
|
+
"""Dᵀ ∇²F(x) D (p × p) for directions D (n × p), by p(p+1)/2 passes of the paired mode of the engine.
|
|
309
|
+
|
|
310
|
+
For a ≤ b, a second-order model gets n inputs of values x, zero biases and sharps (D[:, a], D[:, b]) on two
|
|
311
|
+
sources u, v, and the model's form that feeds A is <s, t>_P = s_u t_v + s_v t_u instead of Γ (forward over
|
|
312
|
+
forward in the recursion of A). The second-order rule then gives A[F] = ½ Σ_ij ∂_ij F <x_i♯, x_j♯>_P
|
|
313
|
+
= D[:, a]ᵀ ∇²F D[:, b], without subtraction between diagonal terms: each entry is exact in the sense of the
|
|
314
|
+
guarantees G1-G2, i.e. up to the rounding of the terms of its own recursion (a polarisation identity
|
|
315
|
+
would subtract diagonal terms and lose small off-diagonal ones). ``call`` maps the list of n scalar inputs to the scalar result.
|
|
316
|
+
"""
|
|
317
|
+
n, p = D.shape
|
|
318
|
+
M = np.zeros((p, p))
|
|
319
|
+
for a in range(p):
|
|
320
|
+
for b in range(a, p):
|
|
321
|
+
m2 = Model(order=2)
|
|
322
|
+
ys = m2._from_factor(x, D[:, [a, b]], np.zeros(n))
|
|
323
|
+
ids = m2._grp_sources[-1]
|
|
324
|
+
m2._pair = (ids[0], ids[1])
|
|
325
|
+
G = _scalar_result(call(ys), "the Hessian (paired mode)", m2)
|
|
326
|
+
M[a, b] = M[b, a] = G._a if isinstance(G, Quantity) else 0.0
|
|
327
|
+
return M
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def sensitivities(func, *, at, hessian=False):
|
|
331
|
+
"""Gradient of ``func`` at ``at`` (n,), computed exactly by the engine; with ``hessian=True``, also the Hessian.
|
|
332
|
+
|
|
333
|
+
The gradient comes from a first-order model whose n inputs have the basis vectors as sharps. The Hessian comes
|
|
334
|
+
from n(n+1)/2 passes of a paired mode of the second-order engine: for i ≤ j, the inputs have the sharps
|
|
335
|
+
(e_i, e_j) on two sources u, v, and the form Γ[x, y] = <x♯, y♯> is replaced, in the recursion of A, by the
|
|
336
|
+
indefinite form <s, t> = s_u t_v + s_v t_u; then A[F] = e_iᵀ ∇²F e_j = ∂_ij F, without subtraction between
|
|
337
|
+
diagonal terms (forward over forward in the Forward Laplacian recursion). Each entry is exact in the sense of the
|
|
338
|
+
guarantees G1-G2, that is, up to the rounding of the terms of its own recursion. 1 + n(n+1)/2 evaluations of
|
|
339
|
+
``func`` (cost O(n³); a RuntimeWarning beyond n = 200). ``func`` takes n positional arguments and is written
|
|
340
|
+
with the functions of errorcalculus (or passed through :func:`wrap`).
|
|
341
|
+
"""
|
|
342
|
+
x = np.atleast_1d(np.asarray(at, dtype=float))
|
|
343
|
+
if x.ndim != 1:
|
|
344
|
+
raise InputError("at must be a point (one-dimensional)")
|
|
345
|
+
if not np.all(np.isfinite(x)):
|
|
346
|
+
raise InputError("at must be finite")
|
|
347
|
+
n = len(x)
|
|
348
|
+
m1 = Model(order=1)
|
|
349
|
+
xs = m1._from_factor(x, np.eye(n), None)
|
|
350
|
+
ids = m1._grp_sources[0]
|
|
351
|
+
F = _scalar_result(func(*xs), "sensitivities", m1)
|
|
352
|
+
grad = np.array([F._s.get(k, 0.0) for k in ids]) if isinstance(F, Quantity) else np.zeros(n)
|
|
353
|
+
if not hessian:
|
|
354
|
+
return grad
|
|
355
|
+
if n > 200:
|
|
356
|
+
warnings.warn(f"sensitivities(hessian=True) with n = {n}: 1 + n(n+1)/2 evaluations, cost O(n³)", RuntimeWarning,
|
|
357
|
+
stacklevel=2)
|
|
358
|
+
return grad, _paired_form(lambda ys: func(*ys), x, np.eye(n))
|
errorcalculus/_rules.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Derivative tables of the supported functions (private).
|
|
2
|
+
|
|
3
|
+
Each table entry computes, at the nominal values, the value f and the first and second partial derivatives needed by
|
|
4
|
+
the propagation rules. Every formula is written with NumPy operations, so that the same code serves the
|
|
5
|
+
scalar engine (Python floats) and the array engine (``ndarray``): this is what makes the dense and the sparse storage
|
|
6
|
+
agree (guarantee G16). Domain predicates return ``True`` where the argument is outside the domain (``DomainError``);
|
|
7
|
+
``nondiff`` predicates return ``True`` where the function is defined but not C², or has an infinite derivative
|
|
8
|
+
(``NonDifferentiableError`` unless the error there is exactly zero).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
try: # SciPy is optional
|
|
18
|
+
from scipy import special as _special
|
|
19
|
+
|
|
20
|
+
_erf_np = _special.erf
|
|
21
|
+
_erfc_np = _special.erfc
|
|
22
|
+
ERF_UFUNCS = (_special.erf, _special.erfc)
|
|
23
|
+
except ImportError: # pragma: no cover - exercised only without SciPy
|
|
24
|
+
_erf_np = np.vectorize(math.erf, otypes=[float])
|
|
25
|
+
_erfc_np = np.vectorize(math.erfc, otypes=[float])
|
|
26
|
+
ERF_UFUNCS = ()
|
|
27
|
+
|
|
28
|
+
_LN2 = math.log(2.0)
|
|
29
|
+
_LN10 = math.log(10.0)
|
|
30
|
+
_TWO_OVER_SQRT_PI = 2.0 / math.sqrt(math.pi)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# --- one argument: name -> (derivs(x) -> (f, f1, f2), domain(x), nondiff(x)) --------------------------------------
|
|
34
|
+
def _exp(x):
|
|
35
|
+
e = np.exp(x)
|
|
36
|
+
return e, e, e
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _expm1(x):
|
|
40
|
+
e = np.exp(x)
|
|
41
|
+
return np.expm1(x), e, e
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# Formulas are written so that no intermediate overflows or underflows when the result is representable
|
|
45
|
+
# (1/x then squared, rather than 1/(x·x); hypot rather than 1 + x²).
|
|
46
|
+
def _log(x):
|
|
47
|
+
inv = 1.0 / x
|
|
48
|
+
return np.log(x), inv, -inv * inv
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _log1p(x):
|
|
52
|
+
inv = 1.0 / (1.0 + x)
|
|
53
|
+
return np.log1p(x), inv, -inv * inv
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _log2(x):
|
|
57
|
+
inv = 1.0 / x
|
|
58
|
+
return np.log2(x), inv / _LN2, -inv * inv / _LN2
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _log10(x):
|
|
62
|
+
inv = 1.0 / x
|
|
63
|
+
return np.log10(x), inv / _LN10, -inv * inv / _LN10
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _sqrt(x):
|
|
67
|
+
r = np.sqrt(x)
|
|
68
|
+
return r, 0.5 / r, -0.25 / (r * x)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _sin(x):
|
|
72
|
+
s = np.sin(x)
|
|
73
|
+
c = np.cos(x)
|
|
74
|
+
return s, c, -s
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _cos(x):
|
|
78
|
+
s = np.sin(x)
|
|
79
|
+
c = np.cos(x)
|
|
80
|
+
return c, -s, -c
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _tan(x):
|
|
84
|
+
t = np.tan(x)
|
|
85
|
+
sec2 = 1.0 + t * t
|
|
86
|
+
return t, sec2, 2.0 * t * sec2
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _asin(x):
|
|
90
|
+
w = (1.0 - x) * (1.0 + x)
|
|
91
|
+
r = np.sqrt(w)
|
|
92
|
+
return np.arcsin(x), 1.0 / r, x / (w * r)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _acos(x):
|
|
96
|
+
w = (1.0 - x) * (1.0 + x)
|
|
97
|
+
r = np.sqrt(w)
|
|
98
|
+
return np.arccos(x), -1.0 / r, -x / (w * r)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _atan(x):
|
|
102
|
+
ir = 1.0 / np.hypot(1.0, x) # 1/√(1 + x²)
|
|
103
|
+
return np.arctan(x), ir * ir, -2.0 * (x * ir) * ir * ir * ir
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _sinh(x):
|
|
107
|
+
return np.sinh(x), np.cosh(x), np.sinh(x)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _cosh(x):
|
|
111
|
+
return np.cosh(x), np.sinh(x), np.cosh(x)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _tanh(x):
|
|
115
|
+
t = np.tanh(x)
|
|
116
|
+
c = np.cosh(x)
|
|
117
|
+
sech2 = 1.0 / (c * c)
|
|
118
|
+
return t, sech2, -2.0 * t * sech2
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _asinh(x):
|
|
122
|
+
ir = 1.0 / np.hypot(1.0, x) # 1/√(1 + x²)
|
|
123
|
+
return np.arcsinh(x), ir, -(x * ir) * ir * ir
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _acosh(x):
|
|
127
|
+
ir = 1.0 / (np.sqrt(x - 1.0) * np.sqrt(x + 1.0)) # 1/√(x² − 1)
|
|
128
|
+
return np.arccosh(x), ir, -(x * ir) * ir * ir
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _atanh(x):
|
|
132
|
+
w = (1.0 - x) * (1.0 + x)
|
|
133
|
+
return np.arctanh(x), 1.0 / w, 2.0 * x / (w * w)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _erf(x):
|
|
137
|
+
g = _TWO_OVER_SQRT_PI * np.exp(-x * x)
|
|
138
|
+
return _erf_np(x), g, -2.0 * x * g
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _erfc(x):
|
|
142
|
+
g = _TWO_OVER_SQRT_PI * np.exp(-x * x)
|
|
143
|
+
return _erfc_np(x), -g, 2.0 * x * g
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _abs(x):
|
|
147
|
+
return np.abs(x), np.sign(x), np.zeros_like(np.asarray(x, dtype=float))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _pos(x):
|
|
151
|
+
return x <= 0.0
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _ge_minus_one(x):
|
|
155
|
+
return x <= -1.0
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
UNARY = {
|
|
159
|
+
# name: (derivs, domain, nondiff)
|
|
160
|
+
"exp": (_exp, None, None),
|
|
161
|
+
"expm1": (_expm1, None, None),
|
|
162
|
+
"log": (_log, _pos, None),
|
|
163
|
+
"log1p": (_log1p, _ge_minus_one, None),
|
|
164
|
+
"log2": (_log2, _pos, None),
|
|
165
|
+
"log10": (_log10, _pos, None),
|
|
166
|
+
"sqrt": (_sqrt, lambda x: x < 0.0, lambda x: x == 0.0),
|
|
167
|
+
"sin": (_sin, None, None),
|
|
168
|
+
"cos": (_cos, None, None),
|
|
169
|
+
"tan": (_tan, None, None),
|
|
170
|
+
"asin": (_asin, lambda x: np.abs(x) > 1.0, lambda x: np.abs(x) == 1.0),
|
|
171
|
+
"acos": (_acos, lambda x: np.abs(x) > 1.0, lambda x: np.abs(x) == 1.0),
|
|
172
|
+
"atan": (_atan, None, None),
|
|
173
|
+
"sinh": (_sinh, None, None),
|
|
174
|
+
"cosh": (_cosh, None, None),
|
|
175
|
+
"tanh": (_tanh, None, None),
|
|
176
|
+
"asinh": (_asinh, None, None),
|
|
177
|
+
"acosh": (_acosh, lambda x: x < 1.0, lambda x: x == 1.0),
|
|
178
|
+
"atanh": (_atanh, lambda x: np.abs(x) >= 1.0, None),
|
|
179
|
+
"erf": (_erf, None, None),
|
|
180
|
+
"erfc": (_erfc, None, None),
|
|
181
|
+
"abs": (_abs, None, lambda x: x == 0.0),
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
# Plain value of each function (used for exact operands and for numbers).
|
|
185
|
+
VALUE = {
|
|
186
|
+
"exp": np.exp, "expm1": np.expm1, "log": np.log, "log1p": np.log1p, "log2": np.log2, "log10": np.log10,
|
|
187
|
+
"sqrt": np.sqrt, "sin": np.sin, "cos": np.cos, "tan": np.tan, "asin": np.arcsin, "acos": np.arccos,
|
|
188
|
+
"atan": np.arctan, "sinh": np.sinh, "cosh": np.cosh, "tanh": np.tanh, "asinh": np.arcsinh,
|
|
189
|
+
"acosh": np.arccosh, "atanh": np.arctanh, "erf": _erf_np, "erfc": _erfc_np, "abs": np.abs,
|
|
190
|
+
"atan2": np.arctan2, "hypot": np.hypot,
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# --- two arguments: derivs(x, y) -> (f, fx, fy, fxx, fxy, fyy) ------------------------------------------------------
|
|
195
|
+
def mul(x, y):
|
|
196
|
+
return x * y, y, x, 0.0, 1.0, 0.0
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def div(x, y):
|
|
200
|
+
f = x / y
|
|
201
|
+
inv = 1.0 / y
|
|
202
|
+
return f, inv, -f * inv, 0.0, -inv * inv, 2.0 * f * inv * inv
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def pow_qq(x, y):
|
|
206
|
+
"""x ** y with both arguments carrying errors (x > 0)."""
|
|
207
|
+
f = np.power(x, y)
|
|
208
|
+
lx = np.log(x)
|
|
209
|
+
fx = y * f / x
|
|
210
|
+
return f, fx, f * lx, (y - 1.0) * fx / x, f / x * (1.0 + y * lx), f * lx * lx
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def atan2(y, x):
|
|
214
|
+
"""atan2(y, x): the first argument is y (NumPy and math order)."""
|
|
215
|
+
ir = 1.0 / np.hypot(x, y)
|
|
216
|
+
c, s = x * ir, y * ir # cos and sin of the angle
|
|
217
|
+
ir2 = ir * ir
|
|
218
|
+
f = np.arctan2(y, x)
|
|
219
|
+
return f, c * ir, -s * ir, -2.0 * c * s * ir2, (s * s - c * c) * ir2, 2.0 * c * s * ir2
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def hypot(x, y):
|
|
223
|
+
r = np.hypot(x, y)
|
|
224
|
+
c, s = x / r, y / r
|
|
225
|
+
return r, c, s, s * s / r, -c * s / r, c * c / r
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
BINARY = {"atan2": atan2, "hypot": hypot}
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def pow_number(x, p):
|
|
232
|
+
"""x ** p for a number p (array-compatible). Returns (f, f1, f2); the caller has applied the domain rules."""
|
|
233
|
+
p = np.asarray(p, dtype=float)
|
|
234
|
+
x = np.asarray(x, dtype=float)
|
|
235
|
+
p0 = p == 0.0
|
|
236
|
+
p1 = p == 1.0
|
|
237
|
+
f = np.where(p0, 1.0, np.power(x, p))
|
|
238
|
+
f1 = np.where(p0, 0.0, np.where(p1, 1.0, p * np.power(x, p - 1.0)))
|
|
239
|
+
f2 = np.where(p0 | p1, 0.0, p * (p - 1.0) * np.power(x, p - 2.0))
|
|
240
|
+
return f, f1, f2
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def pow_number_masks(x, p):
|
|
244
|
+
"""Classification of x ** p.
|
|
245
|
+
|
|
246
|
+
Returns (domain, nondiff, exact_zero_ok): ``domain`` where the operation is refused whatever the error;
|
|
247
|
+
``nondiff`` where it is refused if the operand carries an error (otherwise the result is exactly 0 when
|
|
248
|
+
``exact_zero_ok``, and a DomainError otherwise).
|
|
249
|
+
"""
|
|
250
|
+
p = np.asarray(p, dtype=float)
|
|
251
|
+
x = np.asarray(x, dtype=float)
|
|
252
|
+
integer = p == np.floor(p)
|
|
253
|
+
domain = (integer & (p < 0.0) & (x == 0.0)) | (~integer & (x < 0.0))
|
|
254
|
+
nondiff = ~integer & (x == 0.0)
|
|
255
|
+
exact_zero_ok = p > 0.0
|
|
256
|
+
return domain, nondiff, exact_zero_ok
|