errorcalculus 0.1.1__tar.gz → 0.1.2__tar.gz
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-0.1.1 → errorcalculus-0.1.2}/CHANGELOG.md +27 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/CITATION.cff +1 -1
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/CONTRIBUTING.md +14 -3
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/PKG-INFO +2 -2
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/README.md +1 -1
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/docs/GUARANTEES.md +4 -4
- errorcalculus-0.1.2/docs/_inventories/numpy.inv +5 -0
- errorcalculus-0.1.2/docs/_inventories/python.inv +3 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/docs/conf.py +8 -3
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/docs/index.md +1 -1
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus/__init__.py +1 -1
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus/errors.py +1 -1
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus.egg-info/PKG-INFO +2 -2
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus.egg-info/SOURCES.txt +2 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/_helpers.py +9 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/parity/test_g15_parity.py +1 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_api_names.py +45 -3
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g01_g02_global_rules.py +3 -3
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g09_correlated.py +1 -1
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g14_taylor2.py +6 -5
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g18_linalg.py +108 -21
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g20_sensitivities.py +46 -21
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/LICENSE +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/MANIFEST.in +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/docs/api.md +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/docs/changelog.md +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/docs/comparison.md +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/docs/concepts.md +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/docs/getting-started.md +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/docs/references.md +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/pyproject.toml +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/setup.cfg +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus/_array.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus/_core.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus/_functions.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus/_rules.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus/calculus.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus/compare.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus/linalg.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus/operators.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus.egg-info/dependency_links.txt +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus.egg-info/requires.txt +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/src/errorcalculus.egg-info/top_level.txt +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/_reference_cases.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/conftest.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_compare_api.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g03_gamma_symmetric_positive.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g04_gamma_via_bias.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g05_transport.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g06_identity_does_not_amplify.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g07_orders_bitwise.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g08_first_order_refusals.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g10_contributions.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g11_assumed_zero_bias.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g12_sigma_points.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g13_monte_carlo.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g16_array_vs_scalar.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g17_domain.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g19_wrap.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g21_g22_models.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_g23_g24_operator_scale.py +0 -0
- {errorcalculus-0.1.1 → errorcalculus-0.1.2}/tests/test_regressions.py +0 -0
|
@@ -5,6 +5,33 @@ signatures, and says so below.
|
|
|
5
5
|
|
|
6
6
|
## Unreleased
|
|
7
7
|
|
|
8
|
+
## 0.1.2 — 2026-12-03
|
|
9
|
+
|
|
10
|
+
No change in the computations: tests, documentation and publication.
|
|
11
|
+
|
|
12
|
+
### Tests
|
|
13
|
+
|
|
14
|
+
- `linalg.solve` with a right-hand side that shares the error sources of `a`: `solve(a, aᵀ)`, whose bias holds a
|
|
15
|
+
non-zero covariation term g (it is 0 in `solve(a, a)`), against differences of a⁻¹aᵀ at 100 digits; matrix and vector
|
|
16
|
+
right-hand sides, and the split of the bias by source. The bound on the bias of `solve(a, a)` is now relative to the
|
|
17
|
+
terms that cancel.
|
|
18
|
+
- `linalg.solve` and `linalg.det` of matrices that are themselves non-linear functions of the inputs: the split of the
|
|
19
|
+
bias by source was only tested on inputs.
|
|
20
|
+
- The factor L that the oracles of G1, G14 and G15 (folx) take from the sharps of the inputs is checked against the
|
|
21
|
+
declared covariance, L Lᵀ = C.
|
|
22
|
+
- G20: the scale of an entry is the sum of the absolute values of the terms of the chain rule on the expression as
|
|
23
|
+
written, and no longer depends on the simplifications of sympy; a case whose derivatives cancel up to rounding.
|
|
24
|
+
- `docs/api.md` is compared with the public names, and its list of exceptions with `errors.__all__`.
|
|
25
|
+
- No comparison relies any more on the default tolerances of `numpy.allclose`.
|
|
26
|
+
|
|
27
|
+
### Documentation and publication
|
|
28
|
+
|
|
29
|
+
- The `release` workflow runs the whole `ci` workflow on the tagged commit, and publishes only if it succeeds.
|
|
30
|
+
- The documentation builds when docs.python.org or numpy.org does not answer (the references it needs are
|
|
31
|
+
kept in `docs/_inventories/`).
|
|
32
|
+
- `CONTRIBUTING.md`: `inspect.getsource` does not find the source of the exceptions, an accepted consequence of their
|
|
33
|
+
public module name.
|
|
34
|
+
|
|
8
35
|
## 0.1.1 — 2026-12-03
|
|
9
36
|
|
|
10
37
|
### Fixed
|
|
@@ -50,9 +50,20 @@ installed:
|
|
|
50
50
|
.venv/bin/python -m sphinx -n -W --keep-going -b html docs docs/_build/html
|
|
51
51
|
```
|
|
52
52
|
|
|
53
|
+
References to Python and NumPy are resolved with the inventories of their sites (`objects.inv`), or with the files of
|
|
54
|
+
`docs/_inventories/` when a site does not answer. Those files are plain text and list only the references that the build
|
|
55
|
+
needs: a new reference to NumPy needs a line there (name, type, page).
|
|
56
|
+
|
|
57
|
+
## Exceptions
|
|
58
|
+
|
|
59
|
+
The exceptions are defined in `src/errorcalculus/errors.py` and carry the module name `errorcalculus`, their public
|
|
60
|
+
path. The consequence is accepted: `inspect.getsource(errorcalculus.DomainError)` raises `OSError` (read the file
|
|
61
|
+
instead). A new exception is added to `errors.__all__`, to [docs/api.md](docs/api.md) and to `tests/test_api_names.py`,
|
|
62
|
+
which compares the three lists.
|
|
63
|
+
|
|
53
64
|
## Versions
|
|
54
65
|
|
|
55
66
|
The 0.x series has no stable API. Versions follow `MAJOR.MINOR.PATCH`; each release is tagged `vX.Y.Z` and listed in
|
|
56
|
-
the changelog.
|
|
57
|
-
|
|
58
|
-
|
|
67
|
+
the changelog. When a tag is pushed, the `release` workflow runs the whole `ci` workflow on the tagged commit, builds
|
|
68
|
+
the distributions from the tag and tests the wheel, and publishes to PyPI by trusted publishing (no token) only if all
|
|
69
|
+
of that succeeds. A tag is still pushed only once `ci` has passed on `main`: a published tag does not move.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: errorcalculus
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: Bouleau's error calculus for Python: error variances (Γ) and biases (A) propagated through computations
|
|
5
5
|
Author: Victor Rabiet
|
|
6
6
|
License-Expression: BSD-3-Clause
|
|
@@ -59,7 +59,7 @@ F♯ = Σᵢ ∂ᵢF · xᵢ♯ (the "sharp
|
|
|
59
59
|
A[F] = Σᵢ ∂ᵢF A[xᵢ] + ½ Σᵢⱼ ∂ᵢⱼF Γ[xᵢ, xⱼ]
|
|
60
60
|
```
|
|
61
61
|
|
|
62
|
-
> **Status: 0.1.
|
|
62
|
+
> **Status: 0.1.2, alpha.** This is the first layer of the library (finite dimension). The API of the 0.x series is
|
|
63
63
|
> not stable: names and signatures may still change, and every change is listed in the [changelog](https://github.com/HubHubHubHubHub/errorcalculus/blob/main/CHANGELOG.md).
|
|
64
64
|
|
|
65
65
|
## Install
|
|
@@ -12,7 +12,7 @@ F♯ = Σᵢ ∂ᵢF · xᵢ♯ (the "sharp
|
|
|
12
12
|
A[F] = Σᵢ ∂ᵢF A[xᵢ] + ½ Σᵢⱼ ∂ᵢⱼF Γ[xᵢ, xⱼ]
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
> **Status: 0.1.
|
|
15
|
+
> **Status: 0.1.2, alpha.** This is the first layer of the library (finite dimension). The API of the 0.x series is
|
|
16
16
|
> not stable: names and signatures may still change, and every change is listed in the [changelog](https://github.com/HubHubHubHubHub/errorcalculus/blob/main/CHANGELOG.md).
|
|
17
17
|
|
|
18
18
|
## Install
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
A guarantee is a property of the code that a named test file checks, against an oracle that does not use the code
|
|
4
4
|
under test wherever that is possible (symbolic derivatives with sympy, extended precision with mpmath, closed forms,
|
|
5
|
-
other libraries). The register below is the contract of version 0.1.
|
|
5
|
+
other libraries). The register below is the contract of version 0.1.2: a change that weakens a guarantee changes this
|
|
6
6
|
page and the changelog in the same pull request.
|
|
7
7
|
|
|
8
8
|
**Tolerances.** "Relative to the scale of the terms" means that the gap is divided by the sum of the absolute values of
|
|
@@ -27,13 +27,13 @@ that C = L Lᵀ is the matrix of Γ[xᵢ, xⱼ]; b: the input biases; F: a C² f
|
|
|
27
27
|
| G11 | `assumed_zero_bias` lists exactly the groups without a declared bias on which the quantity depends (a structural dependency; an input with `std=0` and no bias is an exact constant, without a group); `require_bias=True` raises `MissingBiasError` | constructed cases (inputs, propagation, arrays, linear algebra) | exact | `tests/test_g11_assumed_zero_bias.py` |
|
|
28
28
|
| G12 | Sigma points: \| − A\| and \|Γ̂ − Γ\| decrease as O(s) (fitted slope in [0.9, 1.1] over s = 1e-2 … 1e-5); for a quadratic F,  − A = ½ s bᵀHb and Γ̂ − Γ = 2s ∇FᵀCHb + s² bᵀHCHb, so both are exact when b = 0 | five reference cases (random compositions); quadratic polynomials with b = 0 and b ≠ 0 against these closed forms | slope; 1e-12, relative to \|F\|/s for  and F²/s for Γ̂ (the scale of the differences of F) | `tests/test_g12_sigma_points.py` |
|
|
29
29
|
| G13 | Monte Carlo: Γ̂ and  lie within 4 standard errors of Γ and A at s = 1e-4, with a fixed seed; the standard errors are calibrated from `n_samples = 400`; an asymmetric user-supplied law is sampled as given (not symmetrised); the variance is estimated without bias, the correlation within antithetic pairs included | five reference cases, 10⁶ samples; standard deviation of z-scores over 400 seeds; an exponential law; the variance estimate at P = 2 pairs over 40 000 replicates (σ² in closed form, ρ = −1 and ρ = 1/3); a linear F with its draws reproduced from the seed | 4 standard errors | `tests/test_g13_monte_carlo.py` |
|
|
30
|
-
| G14 | `taylor2_variance` returns the exact mean and variance of the quadratic Taylor polynomial of F under normal inputs | moments of the polynomial computed symbolically (sympy, exact rationals, E[zᵐ] = (m − 1)!!); Monte Carlo on the polynomial itself | 1e-10 | `tests/test_g14_taylor2.py` |
|
|
30
|
+
| G14 | `taylor2_variance` returns the exact mean and variance of the quadratic Taylor polynomial of F under normal inputs | moments of the polynomial computed symbolically (sympy, exact rationals, E[zᵐ] = (m − 1)!!), with a factor L checked against the declared covariance (L Lᵀ = C); Monte Carlo on the polynomial itself | 1e-10 | `tests/test_g14_taylor2.py` |
|
|
31
31
|
| G15 | Parity with other libraries: `uncertainties` (value, standard deviation, covariance matrix, error components), GTC (value, standard uncertainty, signed components, correlated inputs; `mul2(estimated=False)` = `taylor2_variance` of x·y), soerp (mean and second-order variance), folx (Γ and A from the Jacobian and the Laplacian); and the second-order mean correction ½ Σ f_ij u(xᵢ, xⱼ) in closed form | the libraries themselves (folx in float64) and sympy | 1e-12 (soerp variance: 1e-10; closed form: 1e-14) | `tests/parity/test_g15_parity.py` (marker `parity`) |
|
|
32
32
|
| G16 | `QuantityArray` (dense storage) agrees with `Quantity` element by element (sparse storage) | random arrays, ufuncs, broadcasting, `matmul`, shape operations | 1e-14, scale of the component | `tests/test_g16_array_vs_scalar.py` |
|
|
33
33
|
| G17 | Domain: outside the domain → `DomainError`; at a point where the function is not C² or has an infinite derivative, with a non-empty sharp → `NonDifferentiableError`; overflow → `NonFiniteError`, in propagation and in the readings (Γ, `covariance_matrix`, `QuantityArray.cov()`, `contributions`, `summary`); never a nan or an inf returned in silence, except the nan that `correlation_matrix` returns, by definition, for a quantity without error; the same domain refusals (`DomainError`, `NonDifferentiableError`) at both orders, and at order 2 a bias alone cannot be carried through a singular point (`NonFiniteError`) | the functions at the edges of their domains, both orders; extreme arguments | — | `tests/test_g17_domain.py`, `tests/test_regressions.py` |
|
|
34
|
-
| G18 | Linear algebra: `solve`, `inv`, `det` follow the global rule; a matrix with a zero row or column, or with a scaled condition number κ_s = ρ(\|a⁻¹\|\|a\|) above 1/(100 ε), is refused with `DomainError`; results and refusals do not depend on the units of rows and columns, at both orders, through `solve`, `inv` and `det`; exactly invertible but badly scaled matrices are accepted and exact, also when their entries span more than the floating-point range and when a row is in subnormal units (value, sharp and bias of `solve`); a result that is not representable raises `NonFiniteError`; the bias of `solve(a, a)` is 0 | 2×2 and 3×3 against sympy; 4×4 and 5×5 against a Gaussian elimination written with scalar quantities; mpmath at 50 digits; diag(1e9, 1e-9); [[1, 1e20], [1, 1]]; random diagonal scalings of dense and sparse matrices; a column of subnormal entries next to a zero; entries from 2⁻⁹⁰⁰ to 2⁹⁰²; a row of subnormal entries | 1e-10 (1e-12 against mpmath) | `tests/test_g18_linalg.py` |
|
|
34
|
+
| G18 | Linear algebra: `solve`, `inv`, `det` follow the global rule; a matrix with a zero row or column, or with a scaled condition number κ_s = ρ(\|a⁻¹\|\|a\|) above 1/(100 ε), is refused with `DomainError`; results and refusals do not depend on the units of rows and columns, at both orders, through `solve`, `inv` and `det`; exactly invertible but badly scaled matrices are accepted and exact, also when their entries span more than the floating-point range and when a row is in subnormal units (value, sharp and bias of `solve`); a result that is not representable raises `NonFiniteError`; the bias of `solve(a, a)` is 0; a right-hand side that shares the error sources of `a` is handled exactly (the covariation Γ[aᵢⱼ, xⱼ] in the bias, and its split by source), as are matrices computed from the inputs | 2×2 and 3×3 against sympy; 4×4 and 5×5 against a Gaussian elimination written with scalar quantities; mpmath at 50 digits; `solve(a, aᵀ)`, and `solve` and `det` of non-linear functions of the inputs, against differences at 100 digits; diag(1e9, 1e-9); [[1, 1e20], [1, 1]]; random diagonal scalings of dense and sparse matrices; a column of subnormal entries next to a zero; entries from 2⁻⁹⁰⁰ to 2⁹⁰²; a row of subnormal entries | 1e-10 (1e-12 against mpmath; 1e-13 against differences and for the bias of `solve(a, a)`) | `tests/test_g18_linalg.py` |
|
|
35
35
|
| G19 | `wrap` without derivatives, homogeneous scales: gradient within 1e-7 and Hessian within 1e-4 of the exact values (largest entry), off-diagonal terms included; the step-halving check warns on heterogeneous scales (√(x² + y² + z²) at (1, 2, 200)) and does not raise false alarms at stationary points | test functions; the heterogeneous case | 1e-7; 1e-4 | `tests/test_g19_wrap.py`, `tests/test_regressions.py` |
|
|
36
|
-
| G20 | `sensitivities` returns the gradient and the Hessian exactly, term by term (each entry up to the rounding of its own terms, with no subtraction between diagonal terms): a coupling of 1e-3 between variables of curvature 5e10 is returned to 1e-12 | sympy, on random compositions and constructed cases; through arrays, `matmul`, `linalg.solve`, `linalg.inv`, `linalg.det` and `wrap` | 1e-12 of each entry, with a floor of 1e-13 of the largest entry (through those operations: 1e-12 of the scale of the entry's own terms, and of the largest entry; an entry
|
|
36
|
+
| G20 | `sensitivities` returns the gradient and the Hessian exactly, term by term (each entry up to the rounding of its own terms, with no subtraction between diagonal terms): a coupling of 1e-3 between variables of curvature 5e10 is returned to 1e-12 | sympy, on random compositions and constructed cases; through arrays, `matmul`, `linalg.solve`, `linalg.inv`, `linalg.det` and `wrap` | 1e-12 of each entry, with a floor of 1e-13 of the largest entry (through those operations: 1e-12 of the scale of the entry's own terms, those that the chain rule adds up node by node, without simplification, and of the largest entry; an entry without any term must be 0) | `tests/test_g20_sensitivities.py` |
|
|
37
37
|
| G21 | Any operation between quantities of two models raises `ModelMismatchError`; `==` returns `False` | direct tests | — | `tests/test_g21_g22_models.py`, `tests/test_regressions.py` |
|
|
38
38
|
| G22 | A model and its quantities, pickled together, reload with the same values, sharps and biases (bit for bit) and remain combinable | pickle round trip | bit for bit | `tests/test_g21_g22_models.py` |
|
|
39
39
|
| G23 | `BiasOperator.from_inputs(xs).apply(φ, at=values) == φ(*xs).bias`, and `.gamma(φ, ψ, at=values) == gamma(φ(*xs), ψ(*xs))` | random compositions | 1e-12 | `tests/test_g23_g24_operator_scale.py` |
|
|
@@ -20,17 +20,22 @@ extensions = [
|
|
|
20
20
|
"sphinx.ext.intersphinx",
|
|
21
21
|
"myst_parser",
|
|
22
22
|
]
|
|
23
|
+
# The inventory of each site is downloaded; if the site does not answer, the file kept in _inventories/ is used instead, so
|
|
24
|
+
# that the build (where a warning is an error) does not depend on the availability of either site. Those files are plain
|
|
25
|
+
# text (format 1) and hold only the references that the documentation needs.
|
|
23
26
|
intersphinx_mapping = {
|
|
24
|
-
"python": ("https://docs.python.org/3", None),
|
|
25
|
-
"numpy": ("https://numpy.org/doc/stable", None),
|
|
27
|
+
"python": ("https://docs.python.org/3", (None, "_inventories/python.inv")),
|
|
28
|
+
"numpy": ("https://numpy.org/doc/stable", (None, "_inventories/numpy.inv")),
|
|
26
29
|
}
|
|
30
|
+
intersphinx_timeout = 20
|
|
31
|
+
intersphinx_cache_limit = 0 # otherwise an incremental build reads the local file although the site answers
|
|
27
32
|
nitpicky = True
|
|
28
33
|
# words of NumPy-style type fields ("order : 1 or 2", "name : str, optional"), not classes
|
|
29
34
|
nitpick_ignore = [("py:class", "1"), ("py:class", "2"), ("py:class", "optional")]
|
|
30
35
|
source_suffix = {".rst": "restructuredtext", ".md": "markdown"}
|
|
31
36
|
myst_enable_extensions = ["dollarmath"]
|
|
32
37
|
myst_heading_anchors = 3
|
|
33
|
-
exclude_patterns = ["_build"]
|
|
38
|
+
exclude_patterns = ["_build", "_inventories"]
|
|
34
39
|
|
|
35
40
|
autodoc_member_order = "bysource"
|
|
36
41
|
autodoc_typehints = "signature"
|
|
@@ -13,7 +13,7 @@ A[F] = \sum_i \partial_i F\, A[x_i] + \tfrac12 \sum_{i,j} \partial_{ij} F\, \Gam
|
|
|
13
13
|
$$
|
|
14
14
|
|
|
15
15
|
```{note}
|
|
16
|
-
Version 0.1.
|
|
16
|
+
Version 0.1.2 is an alpha release of the first layer of the library (finite dimension). The API of the 0.x series is
|
|
17
17
|
not stable: names and signatures may still change, and every change is listed in the {doc}`changelog`.
|
|
18
18
|
```
|
|
19
19
|
|
|
@@ -112,7 +112,7 @@ class NumericalDerivativeWarning(UserWarning):
|
|
|
112
112
|
|
|
113
113
|
|
|
114
114
|
# The public name of every exception is at the root of the package (``errorcalculus.DomainError``): tracebacks, the
|
|
115
|
-
# documentation and pickle use it.
|
|
115
|
+
# documentation and pickle use it. Consequence: inspect.getsource does not find their source, and raises OSError.
|
|
116
116
|
for _name in __all__:
|
|
117
117
|
globals()[_name].__module__ = "errorcalculus"
|
|
118
118
|
del _name
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: errorcalculus
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: Bouleau's error calculus for Python: error variances (Γ) and biases (A) propagated through computations
|
|
5
5
|
Author: Victor Rabiet
|
|
6
6
|
License-Expression: BSD-3-Clause
|
|
@@ -59,7 +59,7 @@ F♯ = Σᵢ ∂ᵢF · xᵢ♯ (the "sharp
|
|
|
59
59
|
A[F] = Σᵢ ∂ᵢF A[xᵢ] + ½ Σᵢⱼ ∂ᵢⱼF Γ[xᵢ, xⱼ]
|
|
60
60
|
```
|
|
61
61
|
|
|
62
|
-
> **Status: 0.1.
|
|
62
|
+
> **Status: 0.1.2, alpha.** This is the first layer of the library (finite dimension). The API of the 0.x series is
|
|
63
63
|
> not stable: names and signatures may still change, and every change is listed in the [changelog](https://github.com/HubHubHubHubHub/errorcalculus/blob/main/CHANGELOG.md).
|
|
64
64
|
|
|
65
65
|
## Install
|
|
@@ -135,6 +135,15 @@ def sharp_matrix(m: ec.Model, xs) -> np.ndarray:
|
|
|
135
135
|
return np.array([[q.sharp.get(s, 0.0) for s in names] for q in xs])
|
|
136
136
|
|
|
137
137
|
|
|
138
|
+
def checked_factor(m: ec.Model, xs, C) -> np.ndarray:
|
|
139
|
+
"""sharp_matrix(m, xs), after checking L Lᵀ = C, the DECLARED covariance: an oracle that takes L from the library
|
|
140
|
+
would otherwise follow a wrong factorisation of the inputs."""
|
|
141
|
+
L = sharp_matrix(m, xs)
|
|
142
|
+
sd = np.sqrt(np.diag(C))
|
|
143
|
+
assert np.all(np.abs(L @ L.T - C) <= 1e-14 * np.outer(sd, sd)), (L @ L.T, C)
|
|
144
|
+
return L
|
|
145
|
+
|
|
146
|
+
|
|
138
147
|
def sharp_vector(m: ec.Model, q) -> np.ndarray:
|
|
139
148
|
if not isinstance(q, ec.Quantity):
|
|
140
149
|
return np.zeros(len(m.sources))
|
|
@@ -152,6 +152,7 @@ def test_g15_folx(name):
|
|
|
152
152
|
b = np.array([0.01, -0.02, 0.005])
|
|
153
153
|
m, xs, F = ours(name, order=2, correlated=True, bias=b)
|
|
154
154
|
L = np.array([[q.sharp.get(s, 0.0) for s in m.sources] for q in xs])
|
|
155
|
+
assert np.all(np.abs(L @ L.T - COV) <= 1e-14 * np.outer(SD, SD)) # L is a factor of the declared covariance
|
|
155
156
|
x0 = jnp.array(X0)
|
|
156
157
|
Lj = jnp.array(L)
|
|
157
158
|
g = lambda z: FUNCS[name](M, *(x0 + Lj @ z)) # noqa: E731
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
"""Inventory of the public names of layer 1."""
|
|
1
|
+
"""Inventory of the public names of layer 1, and of their documentation."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
import pathlib
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
2
8
|
|
|
3
9
|
import errorcalculus as ec
|
|
4
10
|
import errorcalculus.calculus as calc
|
|
@@ -59,9 +65,45 @@ def test_exceptions_carry_their_public_name():
|
|
|
59
65
|
assert type(e) is cls and e.args == ("message",)
|
|
60
66
|
|
|
61
67
|
|
|
62
|
-
def
|
|
63
|
-
|
|
68
|
+
def test_source_of_an_exception_is_never_wrong():
|
|
69
|
+
"""Their __module__ is the package root, not the file that defines them: inspect.getsource does not find the
|
|
70
|
+
source (documented in CONTRIBUTING.md). It must then raise, never return unrelated lines of __init__.py."""
|
|
71
|
+
for n in EXCEPTIONS:
|
|
72
|
+
try:
|
|
73
|
+
source = inspect.getsource(getattr(ec, n))
|
|
74
|
+
except OSError:
|
|
75
|
+
continue
|
|
76
|
+
assert source.startswith(f"class {n}(")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
API_PAGE = pathlib.Path(__file__).resolve().parents[1] / "docs" / "api.md"
|
|
64
80
|
|
|
81
|
+
|
|
82
|
+
def test_documentation_lists_every_exception():
|
|
83
|
+
"""docs/api.md names the exceptions one by one: the list is errors.__all__, in the same order."""
|
|
84
|
+
page = API_PAGE.read_text(encoding="utf-8")
|
|
85
|
+
section = page.split("## Exceptions and warnings", 1)[1]
|
|
86
|
+
listed = re.findall(r"^\.\. auto(?:exception|class):: errorcalculus\.(\w+)$", section, flags=re.MULTILINE)
|
|
87
|
+
assert listed == errs.__all__
|
|
88
|
+
assert listed == EXCEPTIONS
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_documentation_names_every_public_name():
|
|
92
|
+
"""Every name exported at the root appears in docs/api.md, as an autodoc directive or, for the elementary
|
|
93
|
+
functions, in the list of the section."""
|
|
94
|
+
page = API_PAGE.read_text(encoding="utf-8")
|
|
95
|
+
directives = set(re.findall(r"^\.\. auto\w+:: errorcalculus\.(\w+)", page, flags=re.MULTILINE))
|
|
96
|
+
elementary = set(re.findall(r"`(\w+)`", page.split("## Elementary functions", 1)[1].split("Each accepts", 1)[0]))
|
|
97
|
+
assert elementary == set(FUNCTIONS)
|
|
98
|
+
missing = set(ec.__all__) - directives - elementary - {"__version__", "compare"}
|
|
99
|
+
assert not missing, missing
|
|
100
|
+
members = re.search(r"automodule:: errorcalculus\.linalg\n :members: (.+)$", page, flags=re.MULTILINE).group(1)
|
|
101
|
+
assert set(members.split(", ")) == set(ec.linalg.__all__)
|
|
102
|
+
for n in cmp.__all__:
|
|
103
|
+
assert re.search(rf"^\.\. auto\w+:: errorcalculus\.(?:compare\.)?{n}$", page, flags=re.MULTILINE), n
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_quantity_not_constructible():
|
|
65
107
|
with pytest.raises(TypeError):
|
|
66
108
|
ec.Quantity(1.0)
|
|
67
109
|
m = ec.Model(order=2)
|
|
@@ -10,7 +10,7 @@ import numpy as np
|
|
|
10
10
|
import pytest
|
|
11
11
|
|
|
12
12
|
import errorcalculus as ec
|
|
13
|
-
from _helpers import SYMBOLS3, oracle, random_setup, random_tree,
|
|
13
|
+
from _helpers import SYMBOLS3, oracle, random_setup, random_tree, checked_factor, sharp_vector
|
|
14
14
|
|
|
15
15
|
N_CASES = 200
|
|
16
16
|
|
|
@@ -28,11 +28,11 @@ def test_g01_g02_composition(k):
|
|
|
28
28
|
q = tree.fun(xs)
|
|
29
29
|
F, g, H = oracle(tree, 3, vals)
|
|
30
30
|
if not isinstance(q, ec.Quantity): # the composition does not involve the inputs
|
|
31
|
-
assert np.
|
|
31
|
+
assert np.all(g == 0.0) and abs(float(q) - F) <= 1e-12 * max(abs(F), 1.0)
|
|
32
32
|
return
|
|
33
33
|
assert abs(q.value - F) <= 1e-12 * max(abs(F), 1.0), tree.desc
|
|
34
34
|
# G1
|
|
35
|
-
L =
|
|
35
|
+
L = checked_factor(m, xs, C)
|
|
36
36
|
expected = g @ L
|
|
37
37
|
got = sharp_vector(m, q)
|
|
38
38
|
scale = np.abs(g) @ np.abs(L)
|
|
@@ -23,7 +23,7 @@ def test_g09_full_rank(seed):
|
|
|
23
23
|
M = ec.covariance_matrix(xs)
|
|
24
24
|
assert np.max(np.abs(M - C)) <= 1e-14 * np.max(np.abs(C)) * n
|
|
25
25
|
L = m.factor("c0")
|
|
26
|
-
assert L.shape == (n, n) and np.
|
|
26
|
+
assert L.shape == (n, n) and np.all(np.triu(L, 1) == 0.0) # Cholesky
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
@pytest.mark.parametrize("seed", range(20))
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
Oracle: the polynomial Q(z) = ∇F·δ + ½ δᵀHδ, δ = √s L z + s b, is built in sympy with exact rationals (∇F and H from
|
|
4
4
|
sympy at 40 digits), and its moments are computed monomial by monomial with E[z^m] = (m − 1)!! (independent
|
|
5
5
|
standard normals), without retyping the formula; plus a Monte Carlo on the polynomial itself. 1e-10.
|
|
6
|
-
No oracle here takes a derivative, a variance or a bias from the library
|
|
6
|
+
No oracle here takes a derivative, a variance or a bias from the library; the factor L is that of the library, checked
|
|
7
|
+
against the declared covariance (L Lᵀ = C)."""
|
|
7
8
|
|
|
8
9
|
import math
|
|
9
10
|
import random
|
|
@@ -13,7 +14,7 @@ import pytest
|
|
|
13
14
|
import sympy as sp
|
|
14
15
|
|
|
15
16
|
import errorcalculus as ec
|
|
16
|
-
from _helpers import SYMBOLS3, oracle, random_setup, random_tree
|
|
17
|
+
from _helpers import SYMBOLS3, checked_factor, oracle, random_setup, random_tree
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
def gaussian_expectation(poly: sp.Poly) -> sp.Rational:
|
|
@@ -60,12 +61,12 @@ def test_g14_random_compositions(k, s):
|
|
|
60
61
|
if not isinstance(F, ec.Quantity):
|
|
61
62
|
pytest.skip("constant composition")
|
|
62
63
|
_, grad, H = oracle(tree, 3, vals)
|
|
63
|
-
L =
|
|
64
|
+
L = checked_factor(m, xs, C)
|
|
64
65
|
mean, var, _, _ = moments(grad, H, L, b, s)
|
|
65
66
|
r = ec.compare.taylor2_variance(func, list(xs), scale=float(s))
|
|
66
67
|
scale_var = abs(var) + float(s) * float(np.abs(grad) @ np.abs(C) @ np.abs(grad))
|
|
67
68
|
assert abs(r.variance - var) <= 1e-10 * scale_var, (r.variance, var)
|
|
68
|
-
scale_mean = abs(mean) + float(s) * (abs(grad) @ np.abs(b) + 0.5 * np.sum(np.abs(H) * np.abs(
|
|
69
|
+
scale_mean = abs(mean) + float(s) * (abs(grad) @ np.abs(b) + 0.5 * np.sum(np.abs(H) * np.abs(C)))
|
|
69
70
|
assert abs(r.bias - mean) <= 1e-10 * scale_mean, (r.bias, mean)
|
|
70
71
|
p = 4 if np.any(b != 0) else 3
|
|
71
72
|
assert r.n_evaluations == 1 + p * (p + 1) // 2
|
|
@@ -80,7 +81,7 @@ def test_g14_monte_carlo_on_the_polynomial(k):
|
|
|
80
81
|
if not isinstance(func(*xs), ec.Quantity):
|
|
81
82
|
pytest.skip("constant composition")
|
|
82
83
|
_, grad, H = oracle(tree, 3, vals)
|
|
83
|
-
L =
|
|
84
|
+
L = checked_factor(m, xs, C)
|
|
84
85
|
s = 0.25
|
|
85
86
|
r = ec.compare.taylor2_variance(func, list(xs), scale=s)
|
|
86
87
|
Z = np.random.default_rng(k).standard_normal((L.shape[1], 400_000))
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""G18: linear algebra. solve, inv, det = global rule (2×2 and 3×3 against sympy; 4×4 and 5×5 against a Gaussian
|
|
2
2
|
elimination written with scalar quantities, a code path independent of linalg); singular matrix → DomainError.
|
|
3
|
-
Tolerance 1e-10
|
|
3
|
+
Tolerance 1e-10; 1e-12 against mpmath (50 digits), 1e-13 against differences at 100 digits (right-hand sides and
|
|
4
|
+
matrices that share or transform the error sources of a)."""
|
|
4
5
|
|
|
5
6
|
import mpmath
|
|
6
7
|
import numpy as np
|
|
@@ -100,21 +101,14 @@ def close_q(q1, q2, m, tol=1e-10):
|
|
|
100
101
|
assert abs(q1.bias - q2.bias) <= tol * max(abs(q2.bias), np.max(np.abs(s2)) ** 2, 1e-300)
|
|
101
102
|
|
|
102
103
|
|
|
103
|
-
def identity_bias_term_scale(av,
|
|
104
|
-
"""X = a⁻¹a = I does not depend on a: X♯ = 0 and A[X] = 0 exactly.
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
for r in range(n):
|
|
112
|
-
for p in range(n):
|
|
113
|
-
inner[r, p] = (2 * abs(mpmath.mpf(float(a_b[r, p])))
|
|
114
|
-
+ 2 * mpmath.mpf(float(a_sd[r, p])) ** 2 * abs(ai[p, r]))
|
|
115
|
-
absai = mpmath.matrix([[abs(ai[i, j]) for j in range(n)] for i in range(n)])
|
|
116
|
-
scale = absai * inner
|
|
117
|
-
return np.array([[float(scale[i, j]) for j in range(n)] for i in range(n)])
|
|
104
|
+
def identity_bias_term_scale(av, a_b):
|
|
105
|
+
"""X = a⁻¹a = I does not depend on a: X♯ = 0 and A[X] = 0 exactly. In A[X] = a⁻¹(A[a] − A[a]X − g) the term
|
|
106
|
+
g = Σ_j Γ[a_ij, X_jp] is 0 since X♯ = 0, so the terms that cancel are A[a] and A[a]X, of scale 2|a⁻¹||A[a]| (the rounding of g, of order ε|a⁻¹|²σ², is far below the
|
|
107
|
+
bound with the biases used here). The identity does not detect a missing or rescaled g:
|
|
108
|
+
test_g18_right_hand_side_sharing_the_sources_of_a does."""
|
|
109
|
+
with mpmath.workdps(50):
|
|
110
|
+
ai = mpmath.matrix([[mpmath.mpf(float(t)) for t in r] for r in av]) ** -1
|
|
111
|
+
return 2.0 * np.abs(np.array(ai.tolist(), dtype=float)) @ np.abs(a_b)
|
|
118
112
|
|
|
119
113
|
|
|
120
114
|
@pytest.mark.parametrize("bb", [False, True])
|
|
@@ -136,9 +130,102 @@ def test_g18_gauss(seed, n, bb):
|
|
|
136
130
|
assert all(abs(d1.get(k, 0.0) - d2.get(k, 0.0)) <= 1e-10 * scale for k in set(d1) | set(d2))
|
|
137
131
|
# matrix right-hand side sharing the sources of a: X = a⁻¹a = I exactly, without error and without bias
|
|
138
132
|
X = ec.linalg.solve(a, a)
|
|
139
|
-
assert np.allclose(X.values, np.eye(n), atol=1e-12)
|
|
133
|
+
assert np.allclose(X.values, np.eye(n), rtol=0, atol=1e-12)
|
|
140
134
|
assert np.max(np.abs(X.std)) <= 1e-12
|
|
141
|
-
assert np.all(np.abs(X.bias) <= 1e-
|
|
135
|
+
assert np.all(np.abs(X.bias) <= 1e-13 * identity_bias_term_scale(av, a_b))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def difference_oracle(F, av, a_sd, a_b):
|
|
139
|
+
"""F(a), a matrix, with independent errors on the entries of a: value, and per source s (entries of a, row-major)
|
|
140
|
+
the sharp ∂_sF σ_s, the drift ∂_sF b_s and the curvature ½ ∂²_sF σ_s²; drift and curvature sum to A[F]. The
|
|
141
|
+
derivatives are central differences of F itself (step 1e-25, 100 digits: exact far beyond double precision), so that
|
|
142
|
+
the rules of linalg (implicit differentiation, term g) are not used."""
|
|
143
|
+
n = av.shape[0]
|
|
144
|
+
|
|
145
|
+
def arr(M):
|
|
146
|
+
return np.array([[float(M[i, j]) for j in range(M.cols)] for i in range(M.rows)])
|
|
147
|
+
|
|
148
|
+
with mpmath.workdps(100):
|
|
149
|
+
h = mpmath.mpf(10) ** -25
|
|
150
|
+
a = mpmath.matrix([[mpmath.mpf(float(t)) for t in r] for r in av])
|
|
151
|
+
F0 = F(a)
|
|
152
|
+
sharp, drift, curvature = (np.zeros((F0.rows, F0.cols, n * n)) for _ in range(3))
|
|
153
|
+
for i in range(n):
|
|
154
|
+
for j in range(n):
|
|
155
|
+
up, down = a.copy(), a.copy()
|
|
156
|
+
up[i, j] += h
|
|
157
|
+
down[i, j] -= h
|
|
158
|
+
Fu, Fd = F(up), F(down)
|
|
159
|
+
d1, d2 = arr((Fu - Fd) / (2 * h)), arr((Fu - 2 * F0 + Fd) / h**2)
|
|
160
|
+
s = i * n + j
|
|
161
|
+
sharp[:, :, s] = d1 * a_sd[i, j]
|
|
162
|
+
drift[:, :, s] = d1 * a_b[i, j]
|
|
163
|
+
curvature[:, :, s] = 0.5 * d2 * a_sd[i, j] ** 2
|
|
164
|
+
return arr(F0), sharp, drift, curvature
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def make_a(seed, n, bb):
|
|
168
|
+
m = ec.Model(order=2, bias_breakdown=bb)
|
|
169
|
+
rs = np.random.default_rng(300 + seed)
|
|
170
|
+
av = rs.normal(size=(n, n)) + n * np.eye(n)
|
|
171
|
+
a_sd = rs.uniform(0.01, 0.1, (n, n))
|
|
172
|
+
a_b = rs.uniform(-0.02, 0.02, (n, n))
|
|
173
|
+
return m, m.input_array(av, std=a_sd, bias=a_b, name="a"), av, a_sd, a_b
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def check_against_differences(m, entries, expected, bb):
|
|
177
|
+
"""entries: (quantity, i, p) to compare with the entry (i, p) of ``expected`` (difference_oracle); with the split of
|
|
178
|
+
the bias by source (curvature under the source, drift under "source:bias") if bb."""
|
|
179
|
+
value, sharp, drift, curvature = expected
|
|
180
|
+
scale = np.abs(drift) + np.abs(curvature)
|
|
181
|
+
for q, i, p in entries:
|
|
182
|
+
assert abs(q.value - value[i, p]) <= 1e-13 * max(abs(value[i, p]), 1.0)
|
|
183
|
+
got = np.array([q.sharp.get(s, 0.0) for s in m.sources])
|
|
184
|
+
assert np.max(np.abs(got - sharp[i, p])) <= 1e-13 * np.max(np.abs(sharp[i, p]))
|
|
185
|
+
assert abs(q.bias - (drift[i, p] + curvature[i, p]).sum()) <= 1e-13 * scale[i, p].sum()
|
|
186
|
+
if bb:
|
|
187
|
+
parts = ec.contributions(q, kind="bias", by="source")
|
|
188
|
+
assert set(parts) <= set(m.sources) | {f"{s}:bias" for s in m.sources}
|
|
189
|
+
for k, s in enumerate(m.sources):
|
|
190
|
+
assert abs(parts.get(s, 0.0) - curvature[i, p, k]) <= 1e-13 * scale[i, p].max()
|
|
191
|
+
assert abs(parts.get(f"{s}:bias", 0.0) - drift[i, p, k]) <= 1e-13 * scale[i, p].max()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@pytest.mark.parametrize("bb", [False, True])
|
|
195
|
+
@pytest.mark.parametrize("n", [2, 4])
|
|
196
|
+
@pytest.mark.parametrize("seed", range(3))
|
|
197
|
+
def test_g18_right_hand_side_sharing_the_sources_of_a(seed, n, bb):
|
|
198
|
+
"""solve(a, aᵀ), whose solution is correlated with a: the term g_ip = Σ_j Γ[a_ij, X_jp] of the bias is not 0
|
|
199
|
+
(in solve(a, a) it is). Matrix right-hand side, and its first column as a vector (the first row of a)."""
|
|
200
|
+
m, a, *data = make_a(seed, n, bb)
|
|
201
|
+
X = ec.linalg.solve(a, a.T)
|
|
202
|
+
x = ec.linalg.solve(a, a[0])
|
|
203
|
+
entries = [(X[i, p], i, p) for i in range(n) for p in range(n)] + [(x[i], i, 0) for i in range(n)]
|
|
204
|
+
check_against_differences(m, entries, difference_oracle(lambda M: M ** -1 * M.T, *data), bb)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@pytest.mark.parametrize("bb", [False, True])
|
|
208
|
+
@pytest.mark.parametrize("n", [2, 3])
|
|
209
|
+
@pytest.mark.parametrize("seed", range(3))
|
|
210
|
+
def test_g18_matrices_that_are_not_inputs(seed, n, bb):
|
|
211
|
+
"""solve and det of matrices computed from the inputs by non-linear operations, whose entries already carry a
|
|
212
|
+
curvature by source: S = a ∘ a + n² I, solve(S, aᵀ ∘ aᵀ + a) (matrix, and first column as a vector), det(S)."""
|
|
213
|
+
m, a, *data = make_a(seed, n, bb)
|
|
214
|
+
|
|
215
|
+
def S(M):
|
|
216
|
+
return mpmath.matrix([[M[i, j] ** 2 + (n * n if i == j else 0) for j in range(n)] for i in range(n)])
|
|
217
|
+
|
|
218
|
+
def solution(M):
|
|
219
|
+
return S(M) ** -1 * mpmath.matrix([[M[j, i] ** 2 + M[i, j] for j in range(n)] for i in range(n)])
|
|
220
|
+
|
|
221
|
+
s = a * a + n * n * np.eye(n)
|
|
222
|
+
rhs = a.T * a.T + a
|
|
223
|
+
X = ec.linalg.solve(s, rhs)
|
|
224
|
+
x = ec.linalg.solve(s, rhs[:, 0])
|
|
225
|
+
entries = [(X[i, p], i, p) for i in range(n) for p in range(n)] + [(x[i], i, 0) for i in range(n)]
|
|
226
|
+
check_against_differences(m, entries, difference_oracle(solution, *data), bb)
|
|
227
|
+
det = difference_oracle(lambda M: mpmath.matrix([[mpmath.det(S(M))]]), *data)
|
|
228
|
+
check_against_differences(m, [(ec.linalg.det(s), 0, 0)], det, bb)
|
|
142
229
|
|
|
143
230
|
|
|
144
231
|
def test_g18_singular():
|
|
@@ -579,6 +666,6 @@ def test_g18_numpy_routing():
|
|
|
579
666
|
m = ec.Model(order=1)
|
|
580
667
|
a = m.input_array([[2.0, 1.0], [1.0, 3.0]], std=0.1)
|
|
581
668
|
assert np.linalg.det(a).value == pytest.approx(5.0)
|
|
582
|
-
assert np.allclose(np.linalg.inv(a).values, np.linalg.inv([[2.0, 1.0], [1.0, 3.0]]))
|
|
583
|
-
assert np.allclose(np.linalg.solve(a, np.array([1.0, 2.0])).values,
|
|
584
|
-
assert np.allclose(np.dot(a, a).values,
|
|
669
|
+
assert np.allclose(np.linalg.inv(a).values, np.linalg.inv([[2.0, 1.0], [1.0, 3.0]]), rtol=1e-14, atol=0)
|
|
670
|
+
assert np.allclose(np.linalg.solve(a, np.array([1.0, 2.0])).values, [0.2, 0.6], rtol=1e-14, atol=0)
|
|
671
|
+
assert np.allclose(np.dot(a, a).values, [[5.0, 5.0], [5.0, 10.0]], rtol=1e-15, atol=0)
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
The Hessian is tested through every contraction site that feeds A (scalar engine, arrays, matmul, linalg.solve,
|
|
4
4
|
linalg.det, wrap): a site left in the ordinary mode would give a wrong Hessian silently. Through those sites, each
|
|
5
|
-
entry is checked at the scale of its own
|
|
5
|
+
entry is checked at the scale of its own terms, those that the chain rule adds up node by node.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
import random
|
|
@@ -157,6 +157,10 @@ def _site_wrap_numeric(a, b, c):
|
|
|
157
157
|
return f(a, b * c)
|
|
158
158
|
|
|
159
159
|
|
|
160
|
+
def _site_cancelling(a, b, c):
|
|
161
|
+
return ec.exp(a + b) * ec.exp(-a / 3) * ec.exp(-2 * a / 3) + c * c
|
|
162
|
+
|
|
163
|
+
|
|
160
164
|
def _site_dense_unary_binary(a, b, c):
|
|
161
165
|
v = ec.array([a, b])
|
|
162
166
|
w = ec.array([c, a])
|
|
@@ -175,41 +179,62 @@ SITES = [
|
|
|
175
179
|
("det", _site_det,
|
|
176
180
|
sp.Matrix([[A + 2, B * C, sp.Rational(1, 2)], [sp.sin(A), C + 3, B], [A * B, 1, C * C + 2]]).det()),
|
|
177
181
|
("wrap", _site_wrap, (A * C) ** 2 * sp.sin(B) + sp.sin(B) ** 3 + A),
|
|
182
|
+
# = exp(b) + c²: the derivatives in a are 0, sums of terms that cancel up to rounding, and sympy would simplify
|
|
183
|
+
# the product as soon as it is built
|
|
184
|
+
("cancelling", _site_cancelling,
|
|
185
|
+
sp.Mul(sp.exp(A + B), sp.exp(-A / 3), sp.exp(-2 * A / 3), evaluate=False) + C**2),
|
|
178
186
|
("dense_unary_binary", _site_dense_unary_binary,
|
|
179
187
|
sum(sp.atan(p / (2 + q**2)) + sp.sqrt(p**2 + q**2) + (p**2 + 1)**qv + (p**2 + 1)**q
|
|
180
188
|
for p, q, qv in [(A, C, sp.Float(AT[2], 40)), (B, A, sp.Float(AT[0], 40))])),
|
|
181
189
|
]
|
|
182
190
|
|
|
183
191
|
|
|
184
|
-
def
|
|
185
|
-
"""
|
|
186
|
-
the
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
def value_and_scale(d):
|
|
191
|
-
terms = [t.evalf(40, subs=subs) for t in sp.Add.make_args(d)]
|
|
192
|
-
return float(sum(terms)), float(sum(abs(t) for t in terms))
|
|
193
|
-
|
|
192
|
+
def chain_rule_scales(expr, syms, at):
|
|
193
|
+
"""For each entry of ∇F and ∇²F, the sum of the absolute values of the terms that the chain rule adds up, node by
|
|
194
|
+
node on the tree of ``expr`` as it is written: for a node f(u₁, …, u_r),
|
|
195
|
+
G = Σ|f_k| G_k and 𝓗 = Σ|f_k| 𝓗_k + Σ|f_kl| G_k G_lᵀ. The derivative is never formed as a symbolic expression, so
|
|
196
|
+
that sympy cannot merge terms which a computation adds separately. The scale bounds the entry from above, and it
|
|
197
|
+
is 0 only if every term of the entry is 0 at the point."""
|
|
194
198
|
n = len(syms)
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
199
|
+
subs = {s: sp.Float(float(v), 40) for s, v in zip(syms, at)}
|
|
200
|
+
index = {s: i for i, s in enumerate(syms)}
|
|
201
|
+
|
|
202
|
+
def visit(node):
|
|
203
|
+
if node in index:
|
|
204
|
+
return np.eye(n)[index[node]], np.zeros((n, n))
|
|
205
|
+
if not node.free_symbols:
|
|
206
|
+
return np.zeros(n), np.zeros((n, n))
|
|
207
|
+
# the arguments that depend on the variables become dummies; the others (exponents, coefficients) stay numbers
|
|
208
|
+
pos = [k for k, u in enumerate(node.args) if u.free_symbols]
|
|
209
|
+
dummies = sp.symbols(f"u0:{len(pos)}", real=True)
|
|
210
|
+
args = list(node.args)
|
|
211
|
+
for d, k in zip(dummies, pos):
|
|
212
|
+
args[k] = d
|
|
213
|
+
f = node.func(*args)
|
|
214
|
+
here = {d: node.args[k].evalf(40, subs=subs) for d, k in zip(dummies, pos)}
|
|
215
|
+
children = [visit(node.args[k]) for k in pos]
|
|
216
|
+
g, H = np.zeros(n), np.zeros((n, n))
|
|
217
|
+
for d, (gd, Hd) in zip(dummies, children):
|
|
218
|
+
fd = sp.diff(f, d)
|
|
219
|
+
w = abs(float(fd.evalf(40, subs=here)))
|
|
220
|
+
g += w * gd
|
|
221
|
+
H += w * Hd
|
|
222
|
+
for e, (ge, _) in zip(dummies, children):
|
|
223
|
+
H += abs(float(sp.diff(fd, e).evalf(40, subs=here))) * np.outer(gd, ge)
|
|
224
|
+
return g, H
|
|
225
|
+
|
|
226
|
+
return visit(expr)
|
|
203
227
|
|
|
204
228
|
|
|
205
229
|
@pytest.mark.parametrize("name, func, expr", SITES, ids=[s[0] for s in SITES])
|
|
206
230
|
def test_g20_through_sites(name, func, expr):
|
|
207
231
|
"""Each entry to 1e-12 of the scale of its own terms (no floor at the largest entry): a small entry next to large
|
|
208
|
-
ones is checked at its own scale, and an
|
|
232
|
+
ones is checked at its own scale, and an entry without any term (the coupling b-c of the dense site) must be 0.
|
|
209
233
|
The bound relative to the largest entry is kept as well: where the terms of an entry cancel, their scale can
|
|
210
234
|
exceed the largest entry, and the per-entry bound alone would then be the looser one."""
|
|
211
235
|
g, H = ec.sensitivities(func, at=AT, hessian=True)
|
|
212
|
-
g_exp,
|
|
236
|
+
g_exp, H_exp = sym_hessian(expr, (A, B, C), AT)
|
|
237
|
+
g_scale, H_scale = chain_rule_scales(expr, (A, B, C), AT)
|
|
213
238
|
assert np.all(np.abs(g - g_exp) <= 1e-12 * g_scale), (g, g_exp)
|
|
214
239
|
assert np.all(np.abs(H - H_exp) <= 1e-12 * H_scale), (H, H_exp)
|
|
215
240
|
assert np.max(np.abs(g - g_exp)) <= 1e-12 * np.max(np.abs(g_exp))
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|