biasda 0.1.0__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.

Potentially problematic release.


This version of biasda might be problematic. Click here for more details.

Files changed (65) hide show
  1. biasda-0.1.0/LICENSE +21 -0
  2. biasda-0.1.0/MANIFEST.in +2 -0
  3. biasda-0.1.0/PKG-INFO +182 -0
  4. biasda-0.1.0/README.md +156 -0
  5. biasda-0.1.0/biasda/__init__.py +160 -0
  6. biasda-0.1.0/biasda/base.py +727 -0
  7. biasda-0.1.0/biasda/bias/__init__.py +25 -0
  8. biasda-0.1.0/biasda/bias/bias.py +486 -0
  9. biasda-0.1.0/biasda/bias/innovation.py +592 -0
  10. biasda-0.1.0/biasda/bias/polynomial.py +565 -0
  11. biasda-0.1.0/biasda/inflation.py +175 -0
  12. biasda-0.1.0/biasda/localization.py +115 -0
  13. biasda-0.1.0/biasda/observations.py +569 -0
  14. biasda-0.1.0/biasda/sequential/__init__.py +78 -0
  15. biasda-0.1.0/biasda/sequential/ensemble.py +1643 -0
  16. biasda-0.1.0/biasda/sequential/formulations.py +224 -0
  17. biasda-0.1.0/biasda/sequential/kalman.py +457 -0
  18. biasda-0.1.0/biasda/sequential/nudging.py +207 -0
  19. biasda-0.1.0/biasda/sequential/particle.py +407 -0
  20. biasda-0.1.0/biasda/sequential/smoothers.py +478 -0
  21. biasda-0.1.0/biasda/utils.py +271 -0
  22. biasda-0.1.0/biasda/variational/__init__.py +31 -0
  23. biasda-0.1.0/biasda/variational/envar.py +363 -0
  24. biasda-0.1.0/biasda/variational/estimator.py +523 -0
  25. biasda-0.1.0/biasda/variational/var.py +540 -0
  26. biasda-0.1.0/biasda.egg-info/PKG-INFO +182 -0
  27. biasda-0.1.0/biasda.egg-info/SOURCES.txt +63 -0
  28. biasda-0.1.0/biasda.egg-info/dependency_links.txt +1 -0
  29. biasda-0.1.0/biasda.egg-info/requires.txt +10 -0
  30. biasda-0.1.0/biasda.egg-info/top_level.txt +1 -0
  31. biasda-0.1.0/pyproject.toml +60 -0
  32. biasda-0.1.0/setup.cfg +4 -0
  33. biasda-0.1.0/tests/conftest.py +205 -0
  34. biasda-0.1.0/tests/test_adjoint.py +82 -0
  35. biasda-0.1.0/tests/test_augmented.py +59 -0
  36. biasda-0.1.0/tests/test_bias.py +86 -0
  37. biasda-0.1.0/tests/test_bias_calibration.py +302 -0
  38. biasda-0.1.0/tests/test_bias_config.py +367 -0
  39. biasda-0.1.0/tests/test_bias_models.py +230 -0
  40. biasda-0.1.0/tests/test_deprecated_presets.py +86 -0
  41. biasda-0.1.0/tests/test_ekf.py +103 -0
  42. biasda-0.1.0/tests/test_ensemble.py +401 -0
  43. biasda-0.1.0/tests/test_envar.py +202 -0
  44. biasda-0.1.0/tests/test_esn_bias.py +405 -0
  45. biasda-0.1.0/tests/test_examples_construct.py +46 -0
  46. biasda-0.1.0/tests/test_formulations.py +77 -0
  47. biasda-0.1.0/tests/test_independence.py +14 -0
  48. biasda-0.1.0/tests/test_innovation_inflation.py +210 -0
  49. biasda-0.1.0/tests/test_kalman.py +290 -0
  50. biasda-0.1.0/tests/test_literature_equivalence.py +455 -0
  51. biasda-0.1.0/tests/test_localization.py +356 -0
  52. biasda-0.1.0/tests/test_monte_carlo.py +131 -0
  53. biasda-0.1.0/tests/test_nudging.py +225 -0
  54. biasda-0.1.0/tests/test_observations.py +170 -0
  55. biasda-0.1.0/tests/test_parameter_estimation.py +165 -0
  56. biasda-0.1.0/tests/test_particle.py +407 -0
  57. biasda-0.1.0/tests/test_smoother_equals_var4d.py +74 -0
  58. biasda-0.1.0/tests/test_smoothers.py +220 -0
  59. biasda-0.1.0/tests/test_time_linear_bias.py +264 -0
  60. biasda-0.1.0/tests/test_two_stage.py +273 -0
  61. biasda-0.1.0/tests/test_var_hierarchy.py +71 -0
  62. biasda-0.1.0/tests/test_variational.py +122 -0
  63. biasda-0.1.0/tests/test_variational_estimator.py +355 -0
  64. biasda-0.1.0/tests/test_variational_regularization.py +78 -0
  65. biasda-0.1.0/tests/test_zero_bias_identity.py +104 -0
biasda-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrea Nóvoa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ # The tests of the sdist import their fixtures from conftest.py.
2
+ include tests/conftest.py
biasda-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.4
2
+ Name: biasda
3
+ Version: 0.1.0
4
+ Summary: Bias-aware data assimilation for any forecast model: variational and sequential state, parameter and bias estimation
5
+ Author-email: Andrea Nóvoa <a.novoa@imperial.ac.uk>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/andreanovoa/biasda
8
+ Project-URL: Repository, https://github.com/andreanovoa/biasda
9
+ Project-URL: Issues, https://github.com/andreanovoa/biasda/issues
10
+ Keywords: data-assimilation,ensemble-kalman-filter,state-estimation,parameter-estimation,bias-aware
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: matplotlib<4.0,>=3.9
18
+ Requires-Dist: numpy<3.0,>=2.0
19
+ Requires-Dist: scipy<2.0,>=1.13
20
+ Provides-Extra: esn
21
+ Requires-Dist: echostatenetwork>=0.1.4; extra == "esn"
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=9.0.3; extra == "dev"
24
+ Requires-Dist: ruff>=0.11.5; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # biasda
28
+
29
+ [![PyPI](https://img.shields.io/pypi/v/biasda)](https://pypi.org/project/biasda/)
30
+ [![Docs](https://img.shields.io/badge/docs-latest-blue)](https://andreanovoa.github.io/biasda/)
31
+
32
+ Bias-aware data assimilation for any forecast model: sequential and variational estimation of the state, the model parameters and the model bias, in numpy and scipy.
33
+
34
+ An estimator is classified by two choices. **What it estimates** is a configuration of the augmented state, not a class: the state $\boldsymbol{\phi}$ always; the model parameters $\boldsymbol{\alpha}$ when they are named in `est_alpha`; and the bias $\boldsymbol{b}$ when a `Bias` estimator is attached. **How it assimilates** is the class, and each class is configured by its `type`.
35
+
36
+ ![The class hierarchy of biasda](https://raw.githubusercontent.com/andreanovoa/biasda/dev-an/diagrams/tree_full.png)
37
+
38
+ *The class hierarchy of `biasda`. Each box is a class; the darker boxes are the parent classes, which are not called directly. Each class lists its keywords, in plain monospace, and its methods, written `name()`. The rounded frames labelled `type` are the values of the `type` of a class, with the default in a dark border; the grey frames are the values of the other keywords, on the class that introduces them. Not every subclass implements every value: the table below gives where each keyword applies. A `Bias` instance, attached with `parent_bias=` (ensemble and particle filters) or `bias=` (the other estimators), makes any estimator bias-aware.*
39
+
40
+ The modules:
41
+
42
+ ```
43
+ biasda
44
+ ├── sequential
45
+ │ ├── kalman KalmanFilter (type = linear | extended | unscented)
46
+ │ ├── ensemble EnsembleFilter (type = stochastic | deterministic | sqrt | sqrt-random | sqrt-serial | sqrt-half)
47
+ │ ├── particle ParticleFilter (type = classic | flow): bootstrap resampling, or the exact Daum-Huang flow
48
+ │ ├── nudging Nudging (continuous relaxation; its optimal gain is the Kalman gain)
49
+ │ └── smoothers Smoother (type = rts | ks), wrapping an ensemble, particle or Kalman filter
50
+ ├── variational one minimization per window of a record: Var3D (cycled 3D-Var, or 3D-FGAT),
51
+ │ Var4D (type = cost gradient), EnVar (type = 3d | 4d); the cost functions var3d, var4d, en4dvar
52
+ ├── bias InnovationBias (type = constant | drift | esn): ConstantBias, NoBias, DriftLinearBias, ESNBias
53
+ │ PolynomialBias (order = 1 | 2, variable = observables | time, shared):
54
+ │ LinearBias, QuadraticBias, TimeLinearBias
55
+ ├── inflation multiplicative, adaptive and innovation covariance inflation
56
+ ├── localization Gaspari-Cohn covariance localization
57
+ └── observations twin-experiment truths and observations
58
+ ```
59
+
60
+ Each method is a family class with its keywords: the EnSRKF is `EnsembleFilter(type='sqrt')`, the dual EnKF `EnsembleFilter(parameter_estimation='dual')`, the unscented Kalman filter `KalmanFilter(type='unscented')`. The named entry points of earlier versions (`EnKF`, `EnSRKF`, `DualEnKF`, `rEnKF`, ...) are deprecated, and the API reference lists the class and keywords of each. The bias is a configuration of the same classes: the regularized bias-aware analysis of Nóvoa, Racca and Magri (2023) is `EnsembleFilter` with a bias (`parent_bias`), `bias_estimation` and `bias_regularization`.
61
+
62
+ Documentation: [andreanovoa.github.io/biasda](https://andreanovoa.github.io/biasda/), with the theory pages, the API reference and executed tutorial notebooks (in [`tutorials/`](https://github.com/andreanovoa/biasda/tree/dev-an/tutorials), grouped into `sequential/`, `variational/` and `topics/`).
63
+
64
+ ## Installation
65
+
66
+ ```bash
67
+ pip install biasda
68
+ ```
69
+
70
+ The echo state network bias (`ESNBias`) needs the optional `echostatenetwork` package: `pip install "biasda[esn]"`.
71
+
72
+ ## Configuration
73
+
74
+ The keywords have one spelling per option. Not every estimator takes every value; a combination that is not implemented raises an error at construction, so that no option is ignored silently:
75
+
76
+ | Keyword | Values | Applies to | Effect |
77
+ |---|---|---|---|
78
+ | `type` | depends on the family (see the tree above) | every class | the analysis update; case, hyphens and underscores are ignored |
79
+ | `parameter_estimation` | `None`, `'joint'`, `'dual'` | `'joint'`: all but `Nudging`; `'dual'`: Kalman and ensemble filters | `None` without `est_alpha`; `'joint'` (the default with `est_alpha`) analyses state and parameters together; `'dual'` analyses the parameters, re-forecasts the window, then analyses the state |
80
+ | `inflation` | a factor, `'adaptive'` or `'innovation'` | a factor: every estimator; `'adaptive'`: `EnsembleFilter`; `'innovation'`: `EnsembleFilter` | multiplicative inflation of the analysis; for the ensemble filters, the factor estimated at every analysis from its sampling error (`'adaptive'`, Evensen 2009, Sect. 15.3); for `EnsembleFilter`, the inflation of the forecast estimated from the bias-corrected innovation (`'innovation'`, Li, Kalnay & Miyoshi 2009), averaged with the weight `inflation_rate`, with the deviation factor $\sqrt{\lambda}$ bounded by `inflation_max` |
81
+ | `obs_error_adaptation` | `True`, `False` | `EnsembleFilter` | scales the observation-error covariance at every analysis by a factor estimated from the residuals of the forecast and analysis means (Desroziers et al. 2005), averaged with the weight `obs_error_rate` and bounded to `obs_error_bounds`; with `inflation='innovation'`, the inflation and the observation error adapt together |
82
+ | `localization` | the Gaspari-Cohn half-radius | every estimator except `type='sqrt-serial'` | covariance localization for the gain-form updates; one transform per row (LETKF) for `'sqrt'` and `'sqrt-half'`, and one shared random rotation (LSEIK) for `'sqrt-random'`; `loc_period`, `state_positions` and `obs_positions` set the geometry |
83
+ | `bias_regularization` | $\gamma \ge 0$ | every estimator, with a bias | the weight of the bias norm in the regularized bias-aware cost; requires a bias. With the bias estimated (`'joint-…'`), $\gamma$ shrinks the estimate of a correct bias $b$ to $b / [1 + \gamma(1 + P/R)]$, with $P$ and $R$ the forecast and observation-error variances of the observable, so $\gamma = 0$ is unbiased for a form that the data identify |
84
+ | `bias_estimation` | `None`, `'two-stage-analysis'`, `'two-stage-forecast'`, `'lms'`, `'joint-state'`, `'joint-parameters'`, `'joint-all'`, or a pair | `EnsembleFilter`; `ParticleFilter`: the `'joint-…'` routes; `Var3D`, `Var4D`, `EnVar`: `'joint-state'`, the bias in the control vector (variational bias correction, VarBC), with `bias_covariance` | how the analysis updates the bias: reset to the analysis innovation (`None`), the exact two-stage filters, a least-mean-squares step on the bias parameters, or the bias carried in the augmented ensemble |
85
+ | `window` | observations per window, or `None` for the whole record | `Var3D` (default 1), `Var4D` and `EnVar(type='4d')` (required) | the batch window of one minimization |
86
+ | `bias_covariance` | $\boldsymbol{\mathsf{C}}_{\beta\beta}$ | `Var3D`, `Var4D`, `EnVar`, with `bias_estimation='joint-state'` | the background covariance of the bias in the control vector (VarBC) |
87
+
88
+ The bias is attached as `parent_bias=` on the ensemble and particle filters and as `bias=` on the other estimators.
89
+
90
+ ## Usage
91
+
92
+ The ensemble estimators forecast with any model that satisfies a duck-typed protocol, documented in `biasda.base`. [dynamodels](https://github.com/andreanovoa/dynamodels) is the reference implementation, and `tests/conftest.py` holds a minimal one. The Kalman filters and the variational estimators also run without a model, from a linear transition matrix `F` or a nonlinear one-step map `f`, and `Nudging` takes the right-hand side of the model equations.
93
+
94
+ A sequential filter alternates a forecast to the time of each observation with an analysis. The ensemble transform Kalman filter, `EnsembleFilter(type='sqrt')`, on the Lorenz-63 system, with the inflation estimated from the innovations at every analysis:
95
+
96
+ ```python
97
+ import numpy as np
98
+ from biasda import EnsembleFilter, LinearBias, Observations, observation_covariance
99
+ from dynamodels.physical import Lorenz63
100
+
101
+
102
+ def main():
103
+ truth = Observations(model=Lorenz63, t_start=10.0, t_stop=40.0, Nt_obs=10,
104
+ add_noise=True, noise_level=0.01, seed=0)
105
+ Cdd = observation_covariance(truth, std_obs=0.01)
106
+
107
+ est = EnsembleFilter(type='sqrt', parent_model=Lorenz63, m=20, std_phi=0.3, dt=truth.dt,
108
+ inflation='innovation')
109
+ for d, t_d in zip(truth.y_obs, truth.t_obs):
110
+ est.forecast_step(t_end=t_d)
111
+ est.analysis_step(d=d, Cdd=Cdd)
112
+ est.close()
113
+
114
+
115
+ if __name__ == '__main__':
116
+ main()
117
+ ```
118
+
119
+ The `if __name__ == '__main__'` guard is needed because dynamodels integrates the ensemble members in a multiprocessing pool, which Python 3.14 starts with the forkserver method.
120
+
121
+ The bias is a configuration of the same class. Below, the sensor is biased, $\boldsymbol{d} = \boldsymbol{q} + \boldsymbol{\beta}_0 + 0.3\,\boldsymbol{q} + \boldsymbol{\epsilon}$ with $\boldsymbol{\beta}_0 = (1, 1, 2)$, and the filter carries the linear form $\boldsymbol{b} = \boldsymbol{\beta}_0 + \boldsymbol{\mathsf{A}}\boldsymbol{q}$, whose coefficients every member carries and the analysis infers with the state (`bias_estimation='joint-parameters'`). The inflation of the state keeps the ensemble spread at the forecast error; without it, the coefficient ensemble absorbs the forecast error that the state ensemble does not represent:
122
+
123
+ ```python
124
+ # inside main(), after the first example
125
+ d_biased = truth.y_obs + np.array([1.0, 1.0, 2.0]) + 0.3 * truth.y_obs
126
+ bias = LinearBias(innovation=np.zeros(3), t=0.0, dt=truth.dt)
127
+ est = EnsembleFilter(type='stochastic', parent_model=Lorenz63, parent_bias=bias, m=40, std_phi=0.3,
128
+ dt=truth.dt, bias_estimation='joint-parameters', inflation='innovation')
129
+ for d, t_d in zip(d_biased, truth.t_obs):
130
+ est.forecast_step(t_end=t_d)
131
+ est.analysis_step(d=d, Cdd=Cdd)
132
+ print(est.bias.c, np.diag(est.bias.A)) # close to (1, 1, 2) and 0.3
133
+ est.close()
134
+ ```
135
+
136
+ `bias_regularization` $= \gamma > 0$ adds the regularization of Nóvoa, Racca and Magri (2023), which weights the norm of a bias whose form may be wrong; it also shrinks an estimated bias toward zero (see the table above), so the example, whose linear form is correct, leaves it at zero. `bias_estimation` selects how the analysis updates the bias.
137
+
138
+ The variational estimators are batch methods: `assimilate` analyses a record of observations, with one minimization per `window` observations, and returns the analysed trajectory. They need no model, only a one-step map `f` or a matrix `F`. Strong-constraint 4D-Var on Lorenz-63, with $x$ and $z$ observed every ten steps:
139
+
140
+ ```python
141
+ import numpy as np
142
+ from biasda import Var4D
143
+
144
+
145
+ def step(x, dt=0.01):
146
+ """One fourth-order Runge-Kutta step of the Lorenz-63 equations."""
147
+ def rhs(x):
148
+ return np.array([10 * (x[1] - x[0]), x[0] * (28 - x[2]) - x[1], x[0] * x[1] - 8 / 3 * x[2]])
149
+ k1 = rhs(x)
150
+ k2 = rhs(x + dt / 2 * k1)
151
+ k3 = rhs(x + dt / 2 * k2)
152
+ k4 = rhs(x + dt * k3)
153
+ return x + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
154
+
155
+
156
+ M = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) # x and z observed
157
+ rng, x, d = np.random.default_rng(0), np.array([-5.9, -5.5, 24.6]), []
158
+ for _ in range(40): # 40 observations, every 10 steps
159
+ for _ in range(10):
160
+ x = step(x)
161
+ d.append(M @ x + 0.5 * rng.standard_normal(2))
162
+
163
+ est = Var4D(psi0=[-5.0, -5.0, 25.0], B=np.eye(3), M=M, Cdd=0.25 * np.eye(2), f=step, window=4)
164
+ X = est.assimilate(np.array(d), obs_steps=10 * np.arange(1, 41)) # the analysed trajectory, (401, 3)
165
+ ```
166
+
167
+ `Var3D` (cycled 3D-Var, or 3D-FGAT with `window` > 1) and `EnVar(type='3d' | '4d')` take the same arguments. The `type` of `Var4D` selects the cost gradient; with a nonlinear `f` and no adjoint, `'auto'` takes finite differences.
168
+
169
+ ## Validation
170
+
171
+ The implementations follow Evensen, Vossepoel and van Leeuwen (2022), *Data Assimilation Fundamentals* (Springer, open access), and the test suite checks the linear-Gaussian identities of the book: the 3D-Var minimizer equals the Kalman-filter analysis, the unscented Kalman filter reproduces the Kalman filter on a linear system, the ensemble filters converge to the Kalman-filter update as the ensemble grows, and the smoothed trajectory ends at the filter analysis. The square-root types share the analysis mean and covariance, and the localized filters reduce to the global ones for an infinite radius. For the bias, the suite checks that every bias-aware analysis reduces exactly to its bias-blind counterpart when the bias and its Jacobian vanish, and that the regularized square-root, Kalman and variational analyses equal the precision form of the regularized cost.
172
+
173
+ ```bash
174
+ python -m pytest tests/
175
+ ```
176
+
177
+ The tests that build the tutorial models import dynamodels.
178
+
179
+
180
+ ## License
181
+
182
+ MIT.
biasda-0.1.0/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # biasda
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/biasda)](https://pypi.org/project/biasda/)
4
+ [![Docs](https://img.shields.io/badge/docs-latest-blue)](https://andreanovoa.github.io/biasda/)
5
+
6
+ Bias-aware data assimilation for any forecast model: sequential and variational estimation of the state, the model parameters and the model bias, in numpy and scipy.
7
+
8
+ An estimator is classified by two choices. **What it estimates** is a configuration of the augmented state, not a class: the state $\boldsymbol{\phi}$ always; the model parameters $\boldsymbol{\alpha}$ when they are named in `est_alpha`; and the bias $\boldsymbol{b}$ when a `Bias` estimator is attached. **How it assimilates** is the class, and each class is configured by its `type`.
9
+
10
+ ![The class hierarchy of biasda](https://raw.githubusercontent.com/andreanovoa/biasda/dev-an/diagrams/tree_full.png)
11
+
12
+ *The class hierarchy of `biasda`. Each box is a class; the darker boxes are the parent classes, which are not called directly. Each class lists its keywords, in plain monospace, and its methods, written `name()`. The rounded frames labelled `type` are the values of the `type` of a class, with the default in a dark border; the grey frames are the values of the other keywords, on the class that introduces them. Not every subclass implements every value: the table below gives where each keyword applies. A `Bias` instance, attached with `parent_bias=` (ensemble and particle filters) or `bias=` (the other estimators), makes any estimator bias-aware.*
13
+
14
+ The modules:
15
+
16
+ ```
17
+ biasda
18
+ ├── sequential
19
+ │ ├── kalman KalmanFilter (type = linear | extended | unscented)
20
+ │ ├── ensemble EnsembleFilter (type = stochastic | deterministic | sqrt | sqrt-random | sqrt-serial | sqrt-half)
21
+ │ ├── particle ParticleFilter (type = classic | flow): bootstrap resampling, or the exact Daum-Huang flow
22
+ │ ├── nudging Nudging (continuous relaxation; its optimal gain is the Kalman gain)
23
+ │ └── smoothers Smoother (type = rts | ks), wrapping an ensemble, particle or Kalman filter
24
+ ├── variational one minimization per window of a record: Var3D (cycled 3D-Var, or 3D-FGAT),
25
+ │ Var4D (type = cost gradient), EnVar (type = 3d | 4d); the cost functions var3d, var4d, en4dvar
26
+ ├── bias InnovationBias (type = constant | drift | esn): ConstantBias, NoBias, DriftLinearBias, ESNBias
27
+ │ PolynomialBias (order = 1 | 2, variable = observables | time, shared):
28
+ │ LinearBias, QuadraticBias, TimeLinearBias
29
+ ├── inflation multiplicative, adaptive and innovation covariance inflation
30
+ ├── localization Gaspari-Cohn covariance localization
31
+ └── observations twin-experiment truths and observations
32
+ ```
33
+
34
+ Each method is a family class with its keywords: the EnSRKF is `EnsembleFilter(type='sqrt')`, the dual EnKF `EnsembleFilter(parameter_estimation='dual')`, the unscented Kalman filter `KalmanFilter(type='unscented')`. The named entry points of earlier versions (`EnKF`, `EnSRKF`, `DualEnKF`, `rEnKF`, ...) are deprecated, and the API reference lists the class and keywords of each. The bias is a configuration of the same classes: the regularized bias-aware analysis of Nóvoa, Racca and Magri (2023) is `EnsembleFilter` with a bias (`parent_bias`), `bias_estimation` and `bias_regularization`.
35
+
36
+ Documentation: [andreanovoa.github.io/biasda](https://andreanovoa.github.io/biasda/), with the theory pages, the API reference and executed tutorial notebooks (in [`tutorials/`](https://github.com/andreanovoa/biasda/tree/dev-an/tutorials), grouped into `sequential/`, `variational/` and `topics/`).
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install biasda
42
+ ```
43
+
44
+ The echo state network bias (`ESNBias`) needs the optional `echostatenetwork` package: `pip install "biasda[esn]"`.
45
+
46
+ ## Configuration
47
+
48
+ The keywords have one spelling per option. Not every estimator takes every value; a combination that is not implemented raises an error at construction, so that no option is ignored silently:
49
+
50
+ | Keyword | Values | Applies to | Effect |
51
+ |---|---|---|---|
52
+ | `type` | depends on the family (see the tree above) | every class | the analysis update; case, hyphens and underscores are ignored |
53
+ | `parameter_estimation` | `None`, `'joint'`, `'dual'` | `'joint'`: all but `Nudging`; `'dual'`: Kalman and ensemble filters | `None` without `est_alpha`; `'joint'` (the default with `est_alpha`) analyses state and parameters together; `'dual'` analyses the parameters, re-forecasts the window, then analyses the state |
54
+ | `inflation` | a factor, `'adaptive'` or `'innovation'` | a factor: every estimator; `'adaptive'`: `EnsembleFilter`; `'innovation'`: `EnsembleFilter` | multiplicative inflation of the analysis; for the ensemble filters, the factor estimated at every analysis from its sampling error (`'adaptive'`, Evensen 2009, Sect. 15.3); for `EnsembleFilter`, the inflation of the forecast estimated from the bias-corrected innovation (`'innovation'`, Li, Kalnay & Miyoshi 2009), averaged with the weight `inflation_rate`, with the deviation factor $\sqrt{\lambda}$ bounded by `inflation_max` |
55
+ | `obs_error_adaptation` | `True`, `False` | `EnsembleFilter` | scales the observation-error covariance at every analysis by a factor estimated from the residuals of the forecast and analysis means (Desroziers et al. 2005), averaged with the weight `obs_error_rate` and bounded to `obs_error_bounds`; with `inflation='innovation'`, the inflation and the observation error adapt together |
56
+ | `localization` | the Gaspari-Cohn half-radius | every estimator except `type='sqrt-serial'` | covariance localization for the gain-form updates; one transform per row (LETKF) for `'sqrt'` and `'sqrt-half'`, and one shared random rotation (LSEIK) for `'sqrt-random'`; `loc_period`, `state_positions` and `obs_positions` set the geometry |
57
+ | `bias_regularization` | $\gamma \ge 0$ | every estimator, with a bias | the weight of the bias norm in the regularized bias-aware cost; requires a bias. With the bias estimated (`'joint-…'`), $\gamma$ shrinks the estimate of a correct bias $b$ to $b / [1 + \gamma(1 + P/R)]$, with $P$ and $R$ the forecast and observation-error variances of the observable, so $\gamma = 0$ is unbiased for a form that the data identify |
58
+ | `bias_estimation` | `None`, `'two-stage-analysis'`, `'two-stage-forecast'`, `'lms'`, `'joint-state'`, `'joint-parameters'`, `'joint-all'`, or a pair | `EnsembleFilter`; `ParticleFilter`: the `'joint-…'` routes; `Var3D`, `Var4D`, `EnVar`: `'joint-state'`, the bias in the control vector (variational bias correction, VarBC), with `bias_covariance` | how the analysis updates the bias: reset to the analysis innovation (`None`), the exact two-stage filters, a least-mean-squares step on the bias parameters, or the bias carried in the augmented ensemble |
59
+ | `window` | observations per window, or `None` for the whole record | `Var3D` (default 1), `Var4D` and `EnVar(type='4d')` (required) | the batch window of one minimization |
60
+ | `bias_covariance` | $\boldsymbol{\mathsf{C}}_{\beta\beta}$ | `Var3D`, `Var4D`, `EnVar`, with `bias_estimation='joint-state'` | the background covariance of the bias in the control vector (VarBC) |
61
+
62
+ The bias is attached as `parent_bias=` on the ensemble and particle filters and as `bias=` on the other estimators.
63
+
64
+ ## Usage
65
+
66
+ The ensemble estimators forecast with any model that satisfies a duck-typed protocol, documented in `biasda.base`. [dynamodels](https://github.com/andreanovoa/dynamodels) is the reference implementation, and `tests/conftest.py` holds a minimal one. The Kalman filters and the variational estimators also run without a model, from a linear transition matrix `F` or a nonlinear one-step map `f`, and `Nudging` takes the right-hand side of the model equations.
67
+
68
+ A sequential filter alternates a forecast to the time of each observation with an analysis. The ensemble transform Kalman filter, `EnsembleFilter(type='sqrt')`, on the Lorenz-63 system, with the inflation estimated from the innovations at every analysis:
69
+
70
+ ```python
71
+ import numpy as np
72
+ from biasda import EnsembleFilter, LinearBias, Observations, observation_covariance
73
+ from dynamodels.physical import Lorenz63
74
+
75
+
76
+ def main():
77
+ truth = Observations(model=Lorenz63, t_start=10.0, t_stop=40.0, Nt_obs=10,
78
+ add_noise=True, noise_level=0.01, seed=0)
79
+ Cdd = observation_covariance(truth, std_obs=0.01)
80
+
81
+ est = EnsembleFilter(type='sqrt', parent_model=Lorenz63, m=20, std_phi=0.3, dt=truth.dt,
82
+ inflation='innovation')
83
+ for d, t_d in zip(truth.y_obs, truth.t_obs):
84
+ est.forecast_step(t_end=t_d)
85
+ est.analysis_step(d=d, Cdd=Cdd)
86
+ est.close()
87
+
88
+
89
+ if __name__ == '__main__':
90
+ main()
91
+ ```
92
+
93
+ The `if __name__ == '__main__'` guard is needed because dynamodels integrates the ensemble members in a multiprocessing pool, which Python 3.14 starts with the forkserver method.
94
+
95
+ The bias is a configuration of the same class. Below, the sensor is biased, $\boldsymbol{d} = \boldsymbol{q} + \boldsymbol{\beta}_0 + 0.3\,\boldsymbol{q} + \boldsymbol{\epsilon}$ with $\boldsymbol{\beta}_0 = (1, 1, 2)$, and the filter carries the linear form $\boldsymbol{b} = \boldsymbol{\beta}_0 + \boldsymbol{\mathsf{A}}\boldsymbol{q}$, whose coefficients every member carries and the analysis infers with the state (`bias_estimation='joint-parameters'`). The inflation of the state keeps the ensemble spread at the forecast error; without it, the coefficient ensemble absorbs the forecast error that the state ensemble does not represent:
96
+
97
+ ```python
98
+ # inside main(), after the first example
99
+ d_biased = truth.y_obs + np.array([1.0, 1.0, 2.0]) + 0.3 * truth.y_obs
100
+ bias = LinearBias(innovation=np.zeros(3), t=0.0, dt=truth.dt)
101
+ est = EnsembleFilter(type='stochastic', parent_model=Lorenz63, parent_bias=bias, m=40, std_phi=0.3,
102
+ dt=truth.dt, bias_estimation='joint-parameters', inflation='innovation')
103
+ for d, t_d in zip(d_biased, truth.t_obs):
104
+ est.forecast_step(t_end=t_d)
105
+ est.analysis_step(d=d, Cdd=Cdd)
106
+ print(est.bias.c, np.diag(est.bias.A)) # close to (1, 1, 2) and 0.3
107
+ est.close()
108
+ ```
109
+
110
+ `bias_regularization` $= \gamma > 0$ adds the regularization of Nóvoa, Racca and Magri (2023), which weights the norm of a bias whose form may be wrong; it also shrinks an estimated bias toward zero (see the table above), so the example, whose linear form is correct, leaves it at zero. `bias_estimation` selects how the analysis updates the bias.
111
+
112
+ The variational estimators are batch methods: `assimilate` analyses a record of observations, with one minimization per `window` observations, and returns the analysed trajectory. They need no model, only a one-step map `f` or a matrix `F`. Strong-constraint 4D-Var on Lorenz-63, with $x$ and $z$ observed every ten steps:
113
+
114
+ ```python
115
+ import numpy as np
116
+ from biasda import Var4D
117
+
118
+
119
+ def step(x, dt=0.01):
120
+ """One fourth-order Runge-Kutta step of the Lorenz-63 equations."""
121
+ def rhs(x):
122
+ return np.array([10 * (x[1] - x[0]), x[0] * (28 - x[2]) - x[1], x[0] * x[1] - 8 / 3 * x[2]])
123
+ k1 = rhs(x)
124
+ k2 = rhs(x + dt / 2 * k1)
125
+ k3 = rhs(x + dt / 2 * k2)
126
+ k4 = rhs(x + dt * k3)
127
+ return x + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
128
+
129
+
130
+ M = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) # x and z observed
131
+ rng, x, d = np.random.default_rng(0), np.array([-5.9, -5.5, 24.6]), []
132
+ for _ in range(40): # 40 observations, every 10 steps
133
+ for _ in range(10):
134
+ x = step(x)
135
+ d.append(M @ x + 0.5 * rng.standard_normal(2))
136
+
137
+ est = Var4D(psi0=[-5.0, -5.0, 25.0], B=np.eye(3), M=M, Cdd=0.25 * np.eye(2), f=step, window=4)
138
+ X = est.assimilate(np.array(d), obs_steps=10 * np.arange(1, 41)) # the analysed trajectory, (401, 3)
139
+ ```
140
+
141
+ `Var3D` (cycled 3D-Var, or 3D-FGAT with `window` > 1) and `EnVar(type='3d' | '4d')` take the same arguments. The `type` of `Var4D` selects the cost gradient; with a nonlinear `f` and no adjoint, `'auto'` takes finite differences.
142
+
143
+ ## Validation
144
+
145
+ The implementations follow Evensen, Vossepoel and van Leeuwen (2022), *Data Assimilation Fundamentals* (Springer, open access), and the test suite checks the linear-Gaussian identities of the book: the 3D-Var minimizer equals the Kalman-filter analysis, the unscented Kalman filter reproduces the Kalman filter on a linear system, the ensemble filters converge to the Kalman-filter update as the ensemble grows, and the smoothed trajectory ends at the filter analysis. The square-root types share the analysis mean and covariance, and the localized filters reduce to the global ones for an infinite radius. For the bias, the suite checks that every bias-aware analysis reduces exactly to its bias-blind counterpart when the bias and its Jacobian vanish, and that the regularized square-root, Kalman and variational analyses equal the precision form of the regularized cost.
146
+
147
+ ```bash
148
+ python -m pytest tests/
149
+ ```
150
+
151
+ The tests that build the tutorial models import dynamodels.
152
+
153
+
154
+ ## License
155
+
156
+ MIT.
@@ -0,0 +1,160 @@
1
+ r"""biasda — data assimilation for any forecast model.
2
+
3
+ Taxonomy
4
+ --------
5
+ From the top down, an estimator is classified by **what it estimates** and by
6
+ **how it assimilates**.
7
+
8
+ What is estimated (a configuration of the augmented state, not a class tree):
9
+
10
+ - state ($\vect{\phi}$) — the default;
11
+ - state + parameters ($\vect{\alpha}$) — name the parameters in
12
+ ``est_alpha``; they are appended to the state and updated by the same analysis;
13
+ - state + parameters + bias ($\vect{b}$) — attach a `Bias` estimator
14
+ (`biasda.bias`) to any estimator: the analysis then corrects the forecast
15
+ observables with the current bias estimate (the un-regularized,
16
+ $\gamma = 0$ bias-aware update). Like localization and inflation, this is
17
+ a configuration, not a class per filter; the $\gamma > 0$ bias-norm
18
+ regularization is a configuration too (``bias_regularization`` on the
19
+ estimators, ``gamma`` on the variational functions), and ``bias_estimation``
20
+ selects how the analysis updates the bias.
21
+
22
+ How it assimilates, in three families that derive from `Estimator` (the root, which holds the
23
+ configuration and the bias machinery they share):
24
+
25
+ - **sequential** (`SequentialEstimator`, `biasda.sequential`): filters in a forecast/analysis cycle,
26
+ - Kalman-type, deterministic: `KalmanFilter` (``type`` = linear, extended or unscented;
27
+ ``parameter_estimation`` = None, joint or dual);
28
+ - continuous: `Nudging` (Newtonian relaxation; the optimal gain is the
29
+ Kalman gain);
30
+ - Kalman-type, ensemble: `EnsembleFilter` (``type`` = stochastic, deterministic or
31
+ square-root; ``parameter_estimation`` = None, joint or dual; ``localization``);
32
+ - particle: `ParticleFilter` (``type`` = classic, i.e., bootstrap resampling with
33
+ optional kernel rejuvenation, or flow, i.e., the exact Daum-Huang Gaussian flow);
34
+ - **smoothers** (`Smoother`, ``type`` = rts or ks): around an `EnsembleFilter` or a `ParticleFilter`,
35
+ the ensemble RTS smoother or the EnKS; around a `KalmanFilter`, the Rauch-Tung-Striebel smoother;
36
+ - **variational** (`VariationalEstimator`, `biasda.variational`): `Var3D`, `Var4D` and `EnVar`, batch
37
+ analyses of a record (`assimilate`), one minimization per window (cycled 3D-Var by default; 4D-Var and
38
+ 4DEnVar need a window); `Var4D` with ``type`` = the cost gradient (auto, finite-difference, linear,
39
+ jacobian, user), and `EnVar` with ``type`` = 3d or 4d (3DEnVar, 4DEnVar: the ensemble subspace, no
40
+ adjoint, iterable on chaotic windows);
41
+ the cost functions are also plain functions on arrays, `var3d`, `var4d` and `en4dvar`.
42
+ A bias covariance estimates a bias constant over the window in the control vector (the
43
+ weak-constraint formulation).
44
+
45
+ Auxiliaries: `biasda.inflation` (multiplicative, adaptive and innovation covariance
46
+ inflation), `biasda.localization` (Gaspari-Cohn covariance localization),
47
+ `biasda.observations` (twin-experiment truths and observations).
48
+
49
+ Forecast models are duck-typed: any object satisfying the protocol documented in
50
+ `biasda.base` works (``dynamodels.Model`` is the reference implementation), and
51
+ the deterministic estimators also run from a matrix ``F`` or a one-step map ``f``.
52
+
53
+ Reference
54
+ ---------
55
+ Evensen, Vossepoel & van Leeuwen (2022). *Data Assimilation Fundamentals: A
56
+ Unified Formulation of the State and Parameter Estimation Problem.* Springer
57
+ (open access). The implementations are validated against the linear-Gaussian
58
+ identities of the book (see ``tests/``).
59
+ """
60
+
61
+ from .base import Estimator, SequentialEstimator
62
+ from .bias import (
63
+ Bias,
64
+ ConstantBias,
65
+ DriftLinearBias,
66
+ ESNBias,
67
+ InnovationBias,
68
+ LinearBias,
69
+ NoBias,
70
+ PolynomialBias,
71
+ QuadraticBias,
72
+ TimeLinearBias,
73
+ )
74
+ from .inflation import adaptive_inflation_factor, innovation_inflation_factor, multiplicative_inflation
75
+ from .localization import distance_matrix, gaspari_cohn, localization_matrix
76
+ from .observations import (
77
+ Observations,
78
+ measured_idx,
79
+ observation_covariance,
80
+ std_fraction_covariance,
81
+ variance_fraction_covariance,
82
+ )
83
+ from .sequential import (
84
+ DualEnKF,
85
+ EnKF,
86
+ EnKS,
87
+ EnRTS,
88
+ EnsembleEstimator,
89
+ EnsembleFilter,
90
+ EnSRKF,
91
+ ExtendedKalmanFilter,
92
+ KalmanFilter,
93
+ KalmanSmoother,
94
+ LocalizedEnKF,
95
+ Nudging,
96
+ ParticleFilter,
97
+ ParticleFlowFilter,
98
+ Smoother,
99
+ UnscentedKalmanFilter,
100
+ enks_smooth,
101
+ enrts_smooth,
102
+ rEnKF,
103
+ rts_smooth,
104
+ )
105
+ from .variational import EnVar, Var3D, Var4D, VariationalEstimator, en4dvar, var3d, var4d
106
+
107
+ __version__ = "0.1.0"
108
+
109
+ __all__ = [
110
+ 'Bias',
111
+ 'ConstantBias',
112
+ 'DriftLinearBias',
113
+ 'ESNBias',
114
+ 'InnovationBias',
115
+ 'DualEnKF',
116
+ 'EnKF',
117
+ 'EnKS',
118
+ 'EnRTS',
119
+ 'EnSRKF',
120
+ 'EnsembleEstimator',
121
+ 'EnsembleFilter',
122
+ 'Estimator',
123
+ 'ExtendedKalmanFilter',
124
+ 'KalmanFilter',
125
+ 'KalmanSmoother',
126
+ 'LinearBias',
127
+ 'LocalizedEnKF',
128
+ 'Nudging',
129
+ 'NoBias',
130
+ 'PolynomialBias',
131
+ 'Observations',
132
+ 'ParticleFilter',
133
+ 'ParticleFlowFilter',
134
+ 'QuadraticBias',
135
+ 'SequentialEstimator',
136
+ 'Smoother',
137
+ 'TimeLinearBias',
138
+ 'UnscentedKalmanFilter',
139
+ 'adaptive_inflation_factor',
140
+ 'innovation_inflation_factor',
141
+ 'distance_matrix',
142
+ 'enks_smooth',
143
+ 'enrts_smooth',
144
+ 'rts_smooth',
145
+ 'gaspari_cohn',
146
+ 'localization_matrix',
147
+ 'measured_idx',
148
+ 'multiplicative_inflation',
149
+ 'observation_covariance',
150
+ 'std_fraction_covariance',
151
+ 'variance_fraction_covariance',
152
+ 'rEnKF',
153
+ 'EnVar',
154
+ 'Var3D',
155
+ 'Var4D',
156
+ 'VariationalEstimator',
157
+ 'en4dvar',
158
+ 'var3d',
159
+ 'var4d',
160
+ ]