errorcalculus 0.1.0__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.
Files changed (64) hide show
  1. errorcalculus-0.1.2/CHANGELOG.md +91 -0
  2. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/CITATION.cff +1 -1
  3. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/CONTRIBUTING.md +15 -2
  4. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/PKG-INFO +3 -3
  5. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/README.md +2 -2
  6. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/docs/GUARANTEES.md +5 -7
  7. errorcalculus-0.1.2/docs/_inventories/numpy.inv +5 -0
  8. errorcalculus-0.1.2/docs/_inventories/python.inv +3 -0
  9. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/docs/api.md +23 -1
  10. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/docs/comparison.md +6 -3
  11. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/docs/conf.py +14 -1
  12. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/docs/getting-started.md +1 -1
  13. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/docs/index.md +1 -1
  14. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus/__init__.py +1 -1
  15. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus/_core.py +2 -2
  16. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus/compare.py +28 -7
  17. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus/errors.py +8 -1
  18. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus/linalg.py +47 -23
  19. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus.egg-info/PKG-INFO +3 -3
  20. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus.egg-info/SOURCES.txt +2 -0
  21. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/_helpers.py +9 -0
  22. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/parity/test_g15_parity.py +16 -4
  23. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_api_names.py +56 -3
  24. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_compare_api.py +4 -4
  25. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g01_g02_global_rules.py +3 -3
  26. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g09_correlated.py +1 -1
  27. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g10_contributions.py +1 -1
  28. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g12_sigma_points.py +1 -1
  29. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g13_monte_carlo.py +39 -2
  30. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g14_taylor2.py +21 -13
  31. errorcalculus-0.1.2/tests/test_g18_linalg.py +671 -0
  32. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g20_sensitivities.py +55 -2
  33. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g23_g24_operator_scale.py +3 -3
  34. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_regressions.py +5 -5
  35. errorcalculus-0.1.0/CHANGELOG.md +0 -30
  36. errorcalculus-0.1.0/tests/test_g18_linalg.py +0 -391
  37. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/LICENSE +0 -0
  38. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/MANIFEST.in +0 -0
  39. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/docs/changelog.md +0 -0
  40. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/docs/concepts.md +0 -0
  41. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/docs/references.md +0 -0
  42. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/pyproject.toml +0 -0
  43. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/setup.cfg +0 -0
  44. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus/_array.py +0 -0
  45. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus/_functions.py +0 -0
  46. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus/_rules.py +0 -0
  47. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus/calculus.py +0 -0
  48. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus/operators.py +0 -0
  49. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus.egg-info/dependency_links.txt +0 -0
  50. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus.egg-info/requires.txt +0 -0
  51. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/src/errorcalculus.egg-info/top_level.txt +0 -0
  52. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/_reference_cases.py +0 -0
  53. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/conftest.py +0 -0
  54. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g03_gamma_symmetric_positive.py +0 -0
  55. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g04_gamma_via_bias.py +0 -0
  56. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g05_transport.py +0 -0
  57. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g06_identity_does_not_amplify.py +0 -0
  58. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g07_orders_bitwise.py +0 -0
  59. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g08_first_order_refusals.py +0 -0
  60. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g11_assumed_zero_bias.py +0 -0
  61. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g16_array_vs_scalar.py +0 -0
  62. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g17_domain.py +0 -0
  63. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g19_wrap.py +0 -0
  64. {errorcalculus-0.1.0 → errorcalculus-0.1.2}/tests/test_g21_g22_models.py +0 -0
@@ -0,0 +1,91 @@
1
+ # Changelog
2
+
3
+ All notable changes are listed here. The 0.x series has no stable API: a minor version may change names and
4
+ signatures, and says so below.
5
+
6
+ ## Unreleased
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
+
35
+ ## 0.1.1 — 2026-12-03
36
+
37
+ ### Fixed
38
+
39
+ - `compare.monte_carlo` (and the `"monte_carlo"` method of `compare_methods`): under antithetic pairs (laws
40
+ `"normal"` and `"uniform"`) the variance was Σ(v − v̄)²/(2P − 1) over the 2P samples, whose expectation is
41
+ σ²(2P − 1 − ρ)/(2P − 1), ρ the correlation within a pair: a relative bias of −ρ/(2P − 1), at most 0.25 % at
42
+ `n_samples = 400` and about 1e-6 at the default `n_samples`. The estimate is now unbiased,
43
+ Σ(v − v̄)²/(2P) + s²/P with s² the empirical variance of the P pair means; the variances of the batches that
44
+ give the standard error use the same estimate. Independent draws (a user-supplied law) are unchanged.
45
+ - `linalg.solve` (hence `inv`): the right-hand sides of the sharp and the bias (b♯ − a♯x, A[b] − A[a]x − g) were
46
+ formed before the scaling of the rows; with a row of `a` in subnormal units the products lost digits and the sharp
47
+ and the bias of the solution were wrong (by 0.4 % and 1 % in a 2 × 2 example), without any error. Each product
48
+ (a♯ᵢⱼ xⱼ, A[a]ᵢⱼ xⱼ, …) is now formed with a single scaling, its row's included, so that neither a row in tiny units
49
+ nor a row in huge units (a small entry times a large xⱼ) loses digits before the scaling.
50
+
51
+ ### Changed
52
+
53
+ - The exceptions and the warning carry their public name, `errorcalculus.<Name>` (`__module__`), in tracebacks,
54
+ the documentation and pickle; they are documented under that name.
55
+
56
+ ### Documentation and tests
57
+
58
+ - Cross-references to Python and NumPy through intersphinx; the documentation builds with `sphinx -n -W`
59
+ (every reference resolved), in the CI and on Read the Docs.
60
+ - Releases are published to PyPI by trusted publishing, from the `release` workflow, when a tag is pushed.
61
+ - Independent oracles (sympy) for the gradient and the Hessian in the tests of `taylor2` and of the parity with
62
+ folx; tolerances at the scale of each term in the Hessian test across the engine; `linalg`: bias of
63
+ `solve(a, a)`, invariance of the decisions under a change of units at order 2 and through `inv`, and matrices
64
+ whose entries span more than the floating-point range.
65
+ - Tests compared with `pytest.approx` without an explicit absolute tolerance, whose default (1e-12) made some checks
66
+ of small values vacuous; every such comparison now states `abs=0.0`. One expected value, hidden by that default,
67
+ was wrong in the test (the error of a determinant: √6, not √5); the library was right.
68
+
69
+ ## 0.1.0 — 2026-12-03
70
+
71
+ First release: layer 1 of the library, the error calculus in finite dimension.
72
+
73
+ - `Model(order=1 | 2)`: a registry of error sources and the order of the calculus (mandatory). Independent inputs
74
+ (`input`, `input_array`) and correlated inputs (`correlated`: Cholesky, or a spectral factorisation of the
75
+ correlation matrix for a singular covariance). Input biases are declared at order 2; an undeclared bias is taken as
76
+ zero and reported (`assumed_zero_bias`), or refused with `require_bias=True`.
77
+ - `Quantity` and `QuantityArray` (NumPy protocols for the supported ufuncs and functions): value, sharp, error
78
+ variance Γ, standard deviation, bias A (order 2; `FirstOrderError` at order 1).
79
+ - 23 elementary functions with explicit domain rules (`DomainError`, `NonDifferentiableError`, `NonFiniteError`:
80
+ never a nan or an inf returned in silence).
81
+ - `linalg.solve`, `linalg.inv`, `linalg.det`, computed on a matrix equilibrated by powers of 2, refused above a
82
+ scaled condition number κ_s = ρ(|a⁻¹||a|) of 1/(100 ε).
83
+ - `wrap` (user functions with given or numerical derivatives, checked by step halving) and `sensitivities` (exact
84
+ gradient and Hessian, the latter by a paired mode of the engine).
85
+ - Readings: `gamma`, `covariance_matrix`, `correlation_matrix`, `contributions` (error variance by group or source;
86
+ bias by source with `bias_breakdown=True`), `summary(scale=s)`.
87
+ - `BiasOperator`: the bias operator on functions, `gamma_via_bias`, transport by a diffeomorphism.
88
+ - `compare_methods` and `errorcalculus.compare`: error calculus, first order, sensitivities, sigma points, Monte Carlo
89
+ and second-order Taylor moments of the same model.
90
+ - Guarantees G1–G24, each with its test file ([docs/GUARANTEES.md](docs/GUARANTEES.md)); parity with
91
+ `uncertainties`, GTC, soerp and folx (G15).
@@ -2,7 +2,7 @@ cff-version: 1.2.0
2
2
  message: "If you use errorcalculus, please cite it as below."
3
3
  title: "errorcalculus: Bouleau's error calculus for Python"
4
4
  type: software
5
- version: 0.1.0
5
+ version: 0.1.2
6
6
  date-released: 2026-12-03
7
7
  authors:
8
8
  - family-names: Rabiet
@@ -47,10 +47,23 @@ installed:
47
47
 
48
48
  ```sh
49
49
  .venv/bin/python -m pip install -e '.[docs]'
50
- .venv/bin/python -m sphinx -W --keep-going -b html docs docs/_build/html
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.
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.0
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.0, alpha.** This is the first layer of the library (finite dimension). The API of the 0.x series is
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
@@ -93,7 +93,7 @@ print(f.summary(scale=1.0)) # ... (bias assumed zero for: y)
93
93
  In a first-order model, asking for a bias raises `FirstOrderError` instead of returning 0 or `None`: Gauss's calculus
94
94
  excludes biases by construction, and the library says so.
95
95
 
96
- ## What is in 0.1.0
96
+ ## What is in 0.1
97
97
 
98
98
  - `Model`, `Quantity`, `QuantityArray`: independent and correlated inputs (Cholesky, or a spectral factorisation for
99
99
  singular covariances), NumPy arrays of quantities, 23 elementary functions with their domain rules, linear algebra
@@ -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.0, alpha.** This is the first layer of the library (finite dimension). The API of the 0.x series is
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
@@ -46,7 +46,7 @@ print(f.summary(scale=1.0)) # ... (bias assumed zero for: y)
46
46
  In a first-order model, asking for a bias raises `FirstOrderError` instead of returning 0 or `None`: Gauss's calculus
47
47
  excludes biases by construction, and the library says so.
48
48
 
49
- ## What is in 0.1.0
49
+ ## What is in 0.1
50
50
 
51
51
  - `Model`, `Quantity`, `QuantityArray`: independent and correlated inputs (Cholesky, or a spectral factorisation for
52
52
  singular covariances), NumPy arrays of quantities, 23 elementary functions with their domain rules, linear algebra
@@ -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.0: a change that weakens a guarantee changes this
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
@@ -26,14 +26,14 @@ that C = L Lᵀ is the matrix of Γ[xᵢ, xⱼ]; b: the input biases; F: a C² f
26
26
  | G10 | Contributions: their sum is Γ[q]; with `bias_breakdown=True`, the bias contributions sum to A[q]; by group, the variance part is ∇Fᵀ C_g ∇F and the curvature part ½ tr(∇²F C_g) | random compositions; symbolic oracle by group | 1e-14; 1e-12 | `tests/test_g10_contributions.py` |
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
- | 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) | five reference cases, 10⁶ samples; standard deviation of z-scores over 400 seeds; an exponential law | 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` |
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)!!), 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; exactly invertible but badly scaled matrices are accepted and exact | 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 | 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 largest entry) | `tests/test_g20_sensitivities.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, 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` |
@@ -56,5 +56,3 @@ of `compare_methods` (arguments, refusals, first order, inputs without error, re
56
56
  - **Performance** is measured, not guaranteed: the cost of an elementary operation grows linearly with the number of
57
57
  error sources it carries.
58
58
  - R `propagate` is not part of the parity tests (G15).
59
- - Some oracles take a derivative from the library itself: the reduction of `taylor2_variance` to the formula of soerp
60
- (G14) and the ∇F·b term of the comparison with folx (G15) use `sensitivities`, itself checked independently (G20).
@@ -0,0 +1,5 @@
1
+ # Sphinx inventory version 1
2
+ # Project: NumPy
3
+ # Version: 2.5
4
+ numpy.ndarray class reference/generated/numpy.ndarray.html
5
+ numpy.random.default_rng function reference/random/generator.html
@@ -0,0 +1,3 @@
1
+ # Sphinx inventory version 1
2
+ # Project: Python
3
+ # Version: 3.15
@@ -81,5 +81,27 @@ ufuncs (`np.exp`, …, `np.arctan2`, `np.hypot`, and the arithmetic ufuncs) are
81
81
 
82
82
  ```{eval-rst}
83
83
  .. automodule:: errorcalculus.errors
84
- :members:
84
+ :no-members:
85
+
86
+ .. autoexception:: errorcalculus.ErrorCalculusError
87
+ .. autoexception:: errorcalculus.ModelError
88
+ .. autoexception:: errorcalculus.ModelMismatchError
89
+ .. autoexception:: errorcalculus.DuplicateNameError
90
+ .. autoexception:: errorcalculus.NotAnInputError
91
+ .. autoexception:: errorcalculus.OrderError
92
+ .. autoexception:: errorcalculus.FirstOrderError
93
+ .. autoexception:: errorcalculus.InputError
94
+ .. autoexception:: errorcalculus.CovarianceError
95
+ .. autoexception:: errorcalculus.MissingBiasError
96
+ .. autoexception:: errorcalculus.DomainError
97
+ .. autoexception:: errorcalculus.NonDifferentiableError
98
+ .. autoexception:: errorcalculus.NonFiniteError
99
+ .. autoexception:: errorcalculus.UnsupportedOperationError
100
+ .. autoexception:: errorcalculus.NotTrackedError
101
+ .. autoexception:: errorcalculus.NumericalDerivativeError
102
+ .. autoexception:: errorcalculus.TransportError
103
+ .. autoexception:: errorcalculus.ComparisonError
104
+ .. autoexception:: errorcalculus.UnsupportedDistributionError
105
+
106
+ .. autoclass:: errorcalculus.NumericalDerivativeWarning
85
107
  ```
@@ -32,7 +32,10 @@ The variance returned is the centred variance Var F(x̃), as in [JCGM 101](refer
32
32
  s·Γ by terms of order s² for the symmetric laws `"normal"` and `"uniform"`, and of order s^{3/2} for a law
33
33
  with a non-zero third moment. For the laws `"normal"` and `"uniform"` (on [−√3, √3]) the samples are drawn in antithetic
34
34
  pairs (z, −z); for a law supplied as a callable `(rng, shape) -> z`, they are drawn independently, so that an
35
- asymmetric law keeps its odd moments. Standard errors are computed by batches; `n_samples` is at least 400.
35
+ asymmetric law keeps its odd moments. The variance is estimated without bias: the two members of an antithetic
36
+ pair are correlated, and the estimate accounts for it (the usual Σ(v − v̄)²/(2P − 1) over the 2P samples would
37
+ overestimate the variance of a linear F by the factor 2P/(2P − 1)). Standard errors are computed by batches;
38
+ `n_samples` is at least 400.
36
39
 
37
40
  ## Second-order Taylor moments
38
41
 
@@ -42,7 +45,7 @@ variance = s Γ + s² [½ tr((HC)²) + 2 ∇FᵀCHb] + s³ bᵀHCHb, bias = s
42
45
 
43
46
  With b = 0 this is the "second-order variance" s Γ + ½ s² tr((HC)²) computed by soerp and by R `propagate`. It is not
44
47
  the s² term of the true variance, which also needs third derivatives ([GUM](references.md), 5.1.2, note). Laws other
45
- than normal raise {class}`~errorcalculus.UnsupportedDistributionError` in 0.1.0.
48
+ than normal raise {class}`~errorcalculus.UnsupportedDistributionError` in version 0.1.
46
49
 
47
50
  ## Readings
48
51
 
@@ -58,6 +61,6 @@ and `discrepancy(reference="calculus")` gives the relative gaps on Γ and A.
58
61
  | soerp | mean, second-order variance |
59
62
  | folx | Γ and A, from the Jacobian and the Laplacian |
60
63
 
61
- What these libraries do and errorcalculus 0.1.0 does not: formatting and parsing of strings (`uncertainties`);
64
+ What these libraries do and errorcalculus 0.1 does not: formatting and parsing of strings (`uncertainties`);
62
65
  degrees of freedom and complex quantities (GTC); skewness, kurtosis and non-normal inputs for the second-order
63
66
  variance (soerp); coverage intervals and copulas (R `propagate`); the adaptive Monte Carlo procedure of JCGM 101.
@@ -17,12 +17,25 @@ extensions = [
17
17
  "sphinx.ext.autodoc",
18
18
  "sphinx.ext.napoleon",
19
19
  "sphinx.ext.mathjax",
20
+ "sphinx.ext.intersphinx",
20
21
  "myst_parser",
21
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.
26
+ intersphinx_mapping = {
27
+ "python": ("https://docs.python.org/3", (None, "_inventories/python.inv")),
28
+ "numpy": ("https://numpy.org/doc/stable", (None, "_inventories/numpy.inv")),
29
+ }
30
+ intersphinx_timeout = 20
31
+ intersphinx_cache_limit = 0 # otherwise an incremental build reads the local file although the site answers
32
+ nitpicky = True
33
+ # words of NumPy-style type fields ("order : 1 or 2", "name : str, optional"), not classes
34
+ nitpick_ignore = [("py:class", "1"), ("py:class", "2"), ("py:class", "optional")]
22
35
  source_suffix = {".rst": "restructuredtext", ".md": "markdown"}
23
36
  myst_enable_extensions = ["dollarmath"]
24
37
  myst_heading_anchors = 3
25
- exclude_patterns = ["_build"]
38
+ exclude_patterns = ["_build", "_inventories"]
26
39
 
27
40
  autodoc_member_order = "bysource"
28
41
  autodoc_typehints = "signature"
@@ -117,6 +117,6 @@ method value variance std bias evaluation
117
117
  ---------------------------------------------------------------------------------
118
118
  calculus 2.71828 0.000738906 0.0271828 0.000135914 1
119
119
  sigma_points 2.71828 0.00073893 0.0271833 0.000135915 3
120
- monte_carlo 2.71828 0.000736656 0.0271414 0.000135483 1000001
120
+ monte_carlo 2.71828 0.000736655 0.0271414 0.000135483 1000001
121
121
  taylor2 2.71828 0.000738943 0.0271835 0.000135914 2
122
122
  ```
@@ -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.0 is an alpha release of the first layer of the library (finite dimension). The API of the 0.x series is
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
 
@@ -10,6 +10,6 @@ from . import compare, linalg
10
10
  from .calculus import * # noqa: F401,F403
11
11
  from .calculus import __all__ as _calculus_all
12
12
 
13
- __version__ = "0.1.0"
13
+ __version__ = "0.1.2"
14
14
 
15
15
  __all__ = [*_calculus_all, "linalg", "compare", "__version__"]
@@ -192,7 +192,7 @@ class Model:
192
192
  require_bias : bool
193
193
  Second order only: every input must declare ``bias=`` (otherwise :class:`MissingBiasError`). By default an
194
194
  undeclared bias is taken as 0 and the input's group is marked "assumed zero bias", which every result that
195
- depends on it reports (:attr:`ErrorSummary.assumed_zero_bias`).
195
+ depends on it reports (the field ``assumed_zero_bias`` of :class:`ErrorSummary`).
196
196
  bias_breakdown : bool
197
197
  Second order only: track the decomposition of A by group and by source (``contributions(kind="bias")``);
198
198
  about twice the cost.
@@ -885,7 +885,7 @@ class Quantity:
885
885
 
886
886
  @property
887
887
  def std(self) -> float:
888
- """√Γ, as a scaled norm: representable even where Γ over- or underflows."""
888
+ """The square root of Γ, computed as a scaled norm, hence representable even where Γ over- or underflows."""
889
889
  if not self._s:
890
890
  return 0.0
891
891
  M = max(abs(c) for c in self._s.values())
@@ -227,7 +227,7 @@ def _check_scale(scale) -> float:
227
227
 
228
228
  def _scalar_output(F, method: str, model: Model | None = None):
229
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)")
230
+ raise ComparisonError(f"{method}: func must return a scalar (a vector output is not supported in version 0.1)")
231
231
  if isinstance(F, Quantity):
232
232
  if model is not None and F._m is not model:
233
233
  # a quantity captured from outside the arguments: its sharp is indexed by the sources of another model
@@ -272,7 +272,7 @@ def _eval_points_raw(func, inp: _Inputs, X: np.ndarray, vectorized: bool, method
272
272
  if r.shape != (stop - start,):
273
273
  raise ComparisonError(f"{method}: with vectorized=True, func must return one value per sample (shape "
274
274
  f"({stop - start},), got {r.shape}); a vector output is not supported in "
275
- "0.1.0, or pass vectorized=False")
275
+ "version 0.1, or pass vectorized=False")
276
276
  out[start:stop] = r
277
277
  else:
278
278
  for t in range(N):
@@ -396,6 +396,25 @@ def _draw(rng, distribution, shape) -> np.ndarray:
396
396
  "(rng, shape) -> z")
397
397
 
398
398
 
399
+ def _paired_variance(Fp: np.ndarray, Fm: np.ndarray) -> float:
400
+ """Unbiased estimate of the variance of F(x̃) from P ≥ 2 antithetic pairs (Fp[i], Fm[i]).
401
+
402
+ The two members of a pair are correlated (coefficient ρ), so the usual Σ(v − v̄)²/(2P − 1) over the 2P values has
403
+ expectation σ²(2P − 1 − ρ)/(2P − 1): relative bias −ρ/(2P − 1), an overestimate by 1/(2P − 1) for a linear F
404
+ (ρ = −1). The P pair means m_i are independent, of variance Var m, and E Σ(v − v̄)² = 2Pσ² − 2 Var m, hence the
405
+ unbiased estimate Σ(v − v̄)²/(2P) + s²_m/P, with s²_m the empirical variance (ddof = 1) of the pair means.
406
+ """
407
+ allv = np.concatenate([Fp, Fm])
408
+ P = Fp.size
409
+ m = 0.5 * (Fp + Fm)
410
+ return float(np.sum((allv - np.mean(allv)) ** 2) / (2 * P) + np.var(m, ddof=1) / P)
411
+
412
+
413
+ def _sample_variance(v: np.ndarray) -> float:
414
+ """Unbiased variance of independent draws (ddof = 1)."""
415
+ return float(np.sum((v - np.mean(v)) ** 2) / (v.size - 1))
416
+
417
+
399
418
  def _monte_carlo(func, inp: _Inputs, s: float, distribution, n_samples, seed, vectorized: bool) -> MethodResult:
400
419
  n_min = 2 * _BATCHES * _MIN_PAIRS
401
420
  if isinstance(n_samples, bool) or not isinstance(n_samples, numbers.Integral) or n_samples < n_min:
@@ -428,10 +447,12 @@ def _monte_carlo(func, inp: _Inputs, s: float, distribution, n_samples, seed, ve
428
447
  Dp, Dm = D[:, :P], D[:, P:]
429
448
  Fp = _eval_points(func, inp, Dp, vectorized, "monte_carlo")
430
449
  Fm = _eval_points(func, inp, Dm, vectorized, "monte_carlo")
450
+ # variance: unbiased under the correlation of the members of a pair (antithetic pairs), or of independent draws
451
+ variance_of = _paired_variance if antithetic else (lambda a, b: _sample_variance(np.concatenate([a, b])))
431
452
  with np.errstate(all="ignore"):
432
453
  allv = np.concatenate([Fp, Fm])
433
454
  mean = float(np.mean(allv))
434
- var = float(np.sum((allv - mean) ** 2) / (allv.size - 1))
455
+ var = variance_of(Fp, Fm)
435
456
  bias = mean - F0
436
457
  # standard error of the bias: from the P pair means, which are independent (antithetic pairs), or from the
437
458
  # 2P independent draws (user law)
@@ -444,14 +465,14 @@ def _monte_carlo(func, inp: _Inputs, s: float, distribution, n_samples, seed, ve
444
465
  edges = np.linspace(0, P, B + 1).astype(int)
445
466
  bv = []
446
467
  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)))
468
+ bv.append(variance_of(Fp[lo:hi], Fm[lo:hi]))
449
469
  var_se = float(np.std(bv, ddof=1) / math.sqrt(B))
450
470
  dname = distribution if isinstance(distribution, str) else "user callable"
451
471
  kind = f"{P} antithetic pairs" if antithetic else "independent draws, no antithetic pairs (user law)"
452
472
  notes.append(f"Monte Carlo: {2 * P} samples ({kind}), distribution {dname}; standard error of the bias from the "
453
473
  f"{'pair means' if antithetic else 'draws'}, of the variance from {B} batches; centred variance "
454
- "Var F(x̃) (JCGM 101)")
474
+ "Var F(x̃) (JCGM 101), estimated without bias"
475
+ f"{' (correlation within pairs accounted for)' if antithetic else ''}")
455
476
  return _checked("monte_carlo", s, value=F0, variance=var, bias=bias, gamma_estimate=var / s,
456
477
  bias_estimate=bias / s, variance_stderr=var_se, bias_stderr=bias_se, n_eval=2 * P + 1,
457
478
  notes=notes)
@@ -554,7 +575,7 @@ def compare_methods(func, inputs, *, methods=("calculus", "sigma_points", "monte
554
575
  raise ComparisonError("a method is requested twice")
555
576
  if "taylor2" in methods and distribution != "normal":
556
577
  raise UnsupportedDistributionError("taylor2 assumes normal inputs: the terms of skewness and kurtosis need "
557
- "input moments (not in 0.1.0)")
578
+ "input moments (not in version 0.1)")
558
579
  inp = _Inputs(inputs)
559
580
  s = _check_scale(scale)
560
581
  out = {}
@@ -1,6 +1,6 @@
1
1
  """Exceptions and warnings of errorcalculus.
2
2
 
3
- Every exception derives from :class:`ErrorCalculusError` and, where it makes sense, from the standard exception that
3
+ Every exception derives from :class:`~errorcalculus.ErrorCalculusError` and, where it makes sense, from the standard exception that
4
4
  Python code already catches (``ValueError``, ``ArithmeticError``, ``TypeError``), so that ``except ValueError`` keeps
5
5
  working.
6
6
  """
@@ -109,3 +109,10 @@ class UnsupportedDistributionError(ComparisonError):
109
109
 
110
110
  class NumericalDerivativeWarning(UserWarning):
111
111
  """A numerical derivative failed its step-halving check (``check=True``)."""
112
+
113
+
114
+ # The public name of every exception is at the root of the package (``errorcalculus.DomainError``): tracebacks, the
115
+ # documentation and pickle use it. Consequence: inspect.getsource does not find their source, and raises OSError.
116
+ for _name in __all__:
117
+ globals()[_name].__module__ = "errorcalculus"
118
+ del _name
@@ -8,7 +8,7 @@
8
8
 
9
9
  **Singular matrices.** The nominal matrix is first equilibrated by powers of 2, which is exact in floating point:
10
10
  S = D₁ a D₂, with D₁ from the maxima of the rows of a, then D₂ from the maxima of the columns of D₁ a. ``solve``,
11
- ``inv`` and ``det`` raise :class:`DomainError` if a row or a column of a is zero, if S cannot be factorised, or if
11
+ ``inv`` and ``det`` raise :class:`~errorcalculus.DomainError` if a row or a column of a is zero, if S cannot be factorised, or if
12
12
  the scaled condition number ::
13
13
 
14
14
  κ_s(a) = ρ(|a⁻¹| |a|) = ρ(|S⁻¹| |S|)
@@ -24,14 +24,16 @@ factorisation with partial pivoting holds with ``|L| |U|`` in place of ``|a|``,
24
24
  threshold the decision can depend on the BLAS library (κ_s is computed in floating point). Every computation
25
25
  (value, sharp, bias) is done on S and scaled back
26
26
  (a⁻¹R = D₂ S⁻¹ D₁ R; det through the exponents): without that, a = [[1, 1e20], [1, 1]] (κ_s = 1) would be solved
27
- wrongly by a direct elimination. A non-finite result raises :class:`NonFiniteError`.
27
+ wrongly by a direct elimination. A non-finite result raises :class:`~errorcalculus.NonFiniteError`.
28
28
 
29
- For ``det``, refusing a singular matrix is a limitation of version 0.1.0 (det is C² everywhere; a cofactor version
29
+ For ``det``, refusing a singular matrix is a limitation of version 0.1 (det is C² everywhere; a cofactor version
30
30
  valid at d = 0 will come later).
31
31
  """
32
32
 
33
33
  from __future__ import annotations
34
34
 
35
+ import functools
36
+
35
37
  import numpy as np
36
38
 
37
39
  from ._array import (
@@ -121,11 +123,16 @@ class _Equilibrated:
121
123
 
122
124
  def lsolve(self, R: np.ndarray) -> np.ndarray:
123
125
  """a⁻¹ R = D₂ S⁻¹ D₁ R, R of shape (n, ...), solved on S."""
124
- n = self.n
125
- if R.size == 0:
126
- return np.zeros(R.shape)
127
- Y = np.linalg.solve(self.S, self.row(R).reshape(n, -1)).reshape(R.shape)
128
- return np.ldexp(Y, self.ec.reshape((-1,) + (1,) * (R.ndim - 1)))
126
+ return self.lsolve_rows(self.row(R))
127
+
128
+ def lsolve_rows(self, R1: np.ndarray) -> np.ndarray:
129
+ """a⁻¹ R from R1 = D₁ R already scaled by rows: D₂ S⁻¹ R1. A right-hand side built from products (a♯x,
130
+ A[a]x, …) is formed from the row-scaled factors, so that a row of a in subnormal units does not make the
131
+ products lose bits before the scaling."""
132
+ if R1.size == 0:
133
+ return np.zeros(R1.shape)
134
+ Y = np.linalg.solve(self.S, R1.reshape(self.n, -1)).reshape(R1.shape)
135
+ return np.ldexp(Y, self.ec.reshape((-1,) + (1,) * (R1.ndim - 1)))
129
136
 
130
137
  def scaled(self, M: np.ndarray) -> np.ndarray:
131
138
  """D₁ M D₂ on the first two axes of M (n, n, ...)."""
@@ -133,6 +140,18 @@ class _Equilibrated:
133
140
  return np.ldexp(M, (self.er[:, None] + self.ec[None, :]).reshape((self.n, self.n) + tail))
134
141
 
135
142
 
143
+ def _row_scaled_products(er: np.ndarray, M: np.ndarray, V: np.ndarray, spec: str, axes: tuple) -> np.ndarray:
144
+ """D₁ (Σ M ⋆ V): the products M_i… V_… of ``spec`` (an einsum that keeps every index, i first), each formed with a
145
+ single scaling by 2^(e_M + e_V + er_i) of the product of the mantissas, then summed over ``axes``. The product of
146
+ the mantissas lies in [1/4, 1), so a product is lost only if the row-scaled product itself is not representable."""
147
+ mM, eM = np.frexp(M)
148
+ mV, eV = np.frexp(V)
149
+ mant = np.einsum(spec, mM, mV)
150
+ expo = np.einsum(spec, eM, np.ones_like(eV)) + np.einsum(spec, np.ones_like(eM), eV)
151
+ expo += er.reshape((-1,) + (1,) * (expo.ndim - 1)).astype(expo.dtype)
152
+ return np.ldexp(mant, expo).sum(axis=axes)
153
+
154
+
136
155
  def solve(a, b):
137
156
  """Solution x of a x = b (a: n × n; b: n or n × p), with the rules of the module documentation."""
138
157
  a, b = _lift(a), _lift(b)
@@ -154,25 +173,30 @@ def solve(a, b):
154
173
  vec = B_.ndim == 1
155
174
  sup = _union(A_._sup, B_._sup)
156
175
  k = len(sup)
157
- Sa = _expand(A_._S, A_._sup, sup) # (n, n, k)
158
- Sb = _expand(B_._S, B_._sup, sup) # (n, [p,] k)
176
+ # Every right-hand side is D₁ R, with D₁ R = D₁ (r − Σ_j M_ij v_j): the terms of b are scaled by their row, and each
177
+ # product M_ij v_j is formed with ONE scaling (mantissas multiplied, exponents of both factors and of the row
178
+ # added), so that it cannot underflow or overflow before its row scaling, whether the row is in tiny units (the
179
+ # product of two small factors) or in huge units (a small factor times a large one).
180
+ row, lsolve1 = eq.row, eq.lsolve_rows
181
+ prod = functools.partial(_row_scaled_products, eq.er)
182
+ Sa = _expand(A_._S, A_._sup, sup) # a♯ (n, n, k)
183
+ Sb = row(_expand(B_._S, B_._sup, sup)) # D₁ b♯ (n, [p,] k)
159
184
 
160
185
  if vec:
161
- Xs = lsolve(Sb - np.einsum("ijk,j->ik", Sa, x))
186
+ Xs = lsolve1(Sb - prod(Sa, x, "ijk,j->ijk", (1,)))
162
187
  else:
163
- Xs = lsolve(Sb - np.einsum("ijk,jp->ipk", Sa, x))
188
+ Xs = lsolve1(Sb - prod(Sa, x, "ijk,jp->ijpk", (1,)))
164
189
  A = Z = B = K = None
165
190
  zg = bg = _EMPTY_IDX
166
191
  if m._order == 1:
167
192
  Z = np.zeros(x.shape + (0,), dtype=bool)
168
193
  return QuantityArray._make(m, x, Xs, sup, None, Z, zg, None, bg, None)
169
194
  Px = _partner(m, Xs, sup) # Γ[a_ij, x_j] (or the paired form)
195
+ Ab = row(B_._A) # D₁ A[b]
170
196
  if vec:
171
- g = np.einsum("ijk,jk->i", Sa, Px)
172
- Ax = lsolve(B_._A - A_._A @ x - g)
197
+ Ax = lsolve1(Ab - prod(A_._A, x, "ij,j->ij", (1,)) - prod(Sa, Px, "ijk,jk->ijk", (1, 2)))
173
198
  else:
174
- g = np.einsum("ijk,jpk->ip", Sa, Px)
175
- Ax = lsolve(B_._A - A_._A @ x - g)
199
+ Ax = lsolve1(Ab - prod(A_._A, x, "ij,jp->ijp", (1,)) - prod(Sa, Px, "ijk,jpk->ijpk", (1, 3)))
176
200
  zg = _union(A_._zg, B_._zg)
177
201
  dep = (_expand(A_._Z, A_._zg, zg, bool).reshape(A_.size, len(zg)).any(axis=0)
178
202
  | _expand(B_._Z, B_._zg, zg, bool).reshape(B_.size, len(zg)).any(axis=0))
@@ -180,15 +204,15 @@ def solve(a, b):
180
204
  if m._bb:
181
205
  bg = _union(A_._bg, B_._bg)
182
206
  Ba = _expand(A_._B, A_._bg, bg)
183
- Bb = _expand(B_._B, B_._bg, bg)
207
+ Bb = row(_expand(B_._B, B_._bg, bg))
184
208
  Ka = _expand(A_._K, A_._sup, sup)
185
- Kb = _expand(B_._K, B_._sup, sup)
209
+ Kb = row(_expand(B_._K, B_._sup, sup))
186
210
  if vec:
187
- B = lsolve(Bb - np.einsum("ijg,j->ig", Ba, x))
188
- K = lsolve(Kb - np.einsum("ijk,j->ik", Ka, x) - np.einsum("ijk,jk->ik", Sa, Xs))
211
+ B = lsolve1(Bb - prod(Ba, x, "ijg,j->ijg", (1,)))
212
+ K = lsolve1(Kb - prod(Ka, x, "ijk,j->ijk", (1,)) - prod(Sa, Xs, "ijk,jk->ijk", (1,)))
189
213
  else:
190
- B = lsolve(Bb - np.einsum("ijg,jp->ipg", Ba, x))
191
- K = lsolve(Kb - np.einsum("ijk,jp->ipk", Ka, x) - np.einsum("ijk,jpk->ipk", Sa, Xs))
214
+ B = lsolve1(Bb - prod(Ba, x, "ijg,jp->ijpg", (1,)))
215
+ K = lsolve1(Kb - prod(Ka, x, "ijk,jp->ijpk", (1,)) - prod(Sa, Xs, "ijk,jpk->ijpk", (1,)))
192
216
  return QuantityArray._make(m, x, Xs, sup, Ax, Z, zg, B, bg, K)
193
217
 
194
218
 
@@ -203,7 +227,7 @@ def inv(a):
203
227
 
204
228
 
205
229
  def det(a):
206
- """Determinant of a square matrix (a :class:`Quantity`), with the rules of the module documentation."""
230
+ """Determinant of a square matrix (a :class:`~errorcalculus.Quantity`), with the rules of the module documentation."""
207
231
  a = _lift(a)
208
232
  m = _model_of((a,))
209
233
  if m is None: