cuthbert 0.0.0__tar.gz → 0.0.1__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.
cuthbert-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: cuthbert
3
+ Version: 0.0.1
4
+ Summary: State-space model inference with JAX
5
+ Author-email: Sam Duffield <s@mduffield.com>, Sahel Iqbal <sahel13miqbal@proton.me>, Adrien Corenflos <adrien.corenflos.stats@gmail.com>
6
+ License: Apache-2.0
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: jax>=0.4.35
11
+ Requires-Dist: numba>=0.60.0
12
+ Provides-Extra: tests
13
+ Requires-Dist: chex; extra == "tests"
14
+ Requires-Dist: pre-commit; extra == "tests"
15
+ Requires-Dist: ruff; extra == "tests"
16
+ Requires-Dist: pyright; extra == "tests"
17
+ Requires-Dist: pytest; extra == "tests"
18
+ Requires-Dist: pytest-xdist; extra == "tests"
19
+ Requires-Dist: entangled-cli; python_version >= "3.12" and extra == "tests"
20
+ Provides-Extra: docs
21
+ Requires-Dist: mkdocs-material; extra == "docs"
22
+ Requires-Dist: mkdocs-include-markdown-plugin; extra == "docs"
23
+ Requires-Dist: mkdocstrings-python; extra == "docs"
24
+ Provides-Extra: examples
25
+ Requires-Dist: matplotlib; extra == "examples"
26
+ Requires-Dist: pandas; extra == "examples"
27
+ Requires-Dist: pandas-stubs; extra == "examples"
28
+ Requires-Dist: yfinance; extra == "examples"
29
+ Requires-Dist: dynamax; extra == "examples"
30
+ Requires-Dist: ipython; extra == "examples"
31
+ Requires-Dist: tfp-nightly[jax]; extra == "examples"
32
+ Dynamic: license-file
33
+
34
+ <!--intro-start-->
35
+ <div align="center">
36
+ <img src="docs/assets/cuthbert.png" alt="logo"></img>
37
+ </div>
38
+
39
+ A JAX library for state-space model inference
40
+ (filtering, smoothing, static parameter estimation).
41
+
42
+ > Disclaimer: The name `cuthbert` was chosen as a playful nod to the well-known
43
+ > caterpillar cake rivalry between Aldi and M&S in the UK, as the classic state-space
44
+ > model diagram looks vaguely like a caterpillar. However, this software project
45
+ > has no formal connection to Aldi, M&S, or any food products (notwithstanding the coffee drunk during its writeup).
46
+ > `cuthbert` is simply a fun name for this state-space model library and should not be interpreted as an
47
+ > endorsement, association, or affiliation with any brand or animal themed baked goods.
48
+
49
+ [![Discord](https://img.shields.io/badge/Discord-5865F2?logo=discord&logoColor=white&style=for-the-badge)](https://discord.gg/sBnr6JhT)
50
+ [![GitHub](https://img.shields.io/badge/GitHub-181717?logo=github&logoColor=white&style=for-the-badge)](https://github.com/state-space-models/cuthbert)
51
+ [![PyPI](https://img.shields.io/pypi/v/cuthbert?style=for-the-badge)](https://pypi.org/project/cuthbert/)
52
+ [![Docs](https://img.shields.io/badge/Docs-b6d7a8?logo=materialformkdocs&logoColor=black&style=for-the-badge)](https://state-space-models.github.io/cuthbert/)
53
+ <!--intro-end-->
54
+
55
+ <!--goals-start-->
56
+ ### Goals
57
+ - Simple, flexible and performant interface for state-space model inference.
58
+ - Decoupling of model specification and inference. `cuthbert` is built to swap between
59
+ different **inference** methods without be tied to a specific model specification.
60
+ - Compose with the [JAX ecosystem](#ecosystem) for extensive external tools.
61
+ - Functional API: The only classes in `cuthbert` are `NamedTuple`s and `Protocol`s.
62
+ All functions are pure and work seamlessly with `jax.grad`, `jax.jit`, `jax.vmap` etc.
63
+ - Methods for filtering: $p(x_t \mid y_{0:t}, \theta)$.
64
+ - Methods for smoothing: $p(x_{0:T} \mid y_{0:T}, \theta)$ or $p(x_{t} \mid y_{0:T}, \theta)$.
65
+ - Methods for static parameter estimation: $p(\theta \mid y_{0:T})$
66
+ or $\text{argmax} p(y_{0:T} \mid \theta)$.
67
+ - This includes support for forward-backward/Baum-Welch, particle filtering/sequential Monte Carlo,
68
+ Kalman filtering (+ extended/unscented/ensemble), expectation-maximization and more!
69
+
70
+ ### Non-goals
71
+ - Tools for defining models and distributions. `cuthbert` is not a probabilistic programming language (PPL).
72
+ But can easily compose with [`dynamax`](https://github.com/probml/dynamax), [`distrax`](https://github.com/google-deepmind/distrax), [`numpyro`](https://github.com/pyro-ppl/numpyro) and [`pymc`](https://github.com/pymc-devs/pymc) in a similar way to how [`blackjax` does](https://blackjax-devs.github.io/blackjax/).
73
+ - ["SMC Samplers"](https://www.stats.ox.ac.uk/~doucet/delmoral_doucet_jasra_sequentialmontecarlosamplersJRSSB.pdf) which sample from a posterior
74
+ distribution which is not (necessarily) a state-space model - [`blackjax` is great for this](https://github.com/blackjax-devs/blackjax/tree/main/blackjax/smc).
75
+ <!--goals-end-->
76
+
77
+ <!--codebase-structure-start-->
78
+ ### Codebase structure
79
+
80
+ The codebase is structured as follows:
81
+
82
+ - `cuthbert`: The main package with unified interface for filtering and smoothing.
83
+ - `cuthbertlib`: A collection of atomic, smaller-scoped tools useful for state-space model inference,
84
+ that represent the building blocks that power the main `cuthbert` package.
85
+ <!--codebase-structure-end-->
86
+ - `docs`: Source code for the documentation for `cuthbert` and `cuthbertlib`.
87
+ - `tests`: Tests for the `cuthbert` and `cuthbertlib` packages.
88
+
89
+
90
+ <!--installation-start-->
91
+ ## Installation
92
+
93
+ `cuthbert` depends on JAX, so you'll need to [install JAX](https://docs.jax.dev/en/latest/installation.html) for the available hardware (CPU, GPU, or TPU).
94
+ For example, on computers with NVIDIA GPUs:
95
+
96
+ ```bash
97
+ pip install -U "jax[cuda13]"
98
+ ```
99
+
100
+ Now install `cuthbert` from PyPI:
101
+
102
+ ```bash
103
+ pip install -U cuthbert
104
+ ```
105
+
106
+ Installing `cuthbert` will also install `cuthbertlib`.
107
+
108
+ <!--installation-end-->
109
+
110
+ <!--ecosystem-start-->
111
+ ## Ecosystem
112
+ - `cuthbert` is built on top of [`jax`](https://github.com/google/jax) and composes
113
+ easily with other JAX packages, e.g. [`optax`](https://github.com/google-deepmind/optax)
114
+ for optimization, [`flax`](https://github.com/google/flax) for neural networks, and
115
+ [`blackjax`](https://github.com/blackjax-devs/blackjax) for (SG)MCMC as well as the PPLs
116
+ mentioned [above](#non-goals).
117
+ - What about [`dynamax`](https://github.com/probml/dynamax)?
118
+ - `dynamax` is a great library for state-space model specification and inference with
119
+ discrete or Gaussian state-space models. `cuthbert` is focused on inference
120
+ with arbitrary state-space models via e.g. SMC that is not supported in `dynamax`.
121
+ However as they are both built on [`jax`](https://github.com/google/jax)
122
+ they can be used together! A `dynamax`
123
+ model can be passed to `cuthbert` for inference.
124
+ - And [`particles`](https://github.com/nchopin/particles)?
125
+ - [`particles`](https://github.com/nchopin/particles) and the accompanying book
126
+ [Sequential Monte Carlo Methods in Practice](https://link.springer.com/book/10.1007/978-3-030-47845-2)
127
+ are wonderful learning materials for state-space models and SMC.
128
+ `cuthbert` is more focused on performance and composability with the JAX ecosystem.
129
+ - Much of the code in `cuthbert` is built on work from [`sqrt-parallel-smoothers`](https://github.com/EEA-sensors/sqrt-parallel-smoothers), [`mocat`](https://github.com/SamDuffield/mocat) and [`abile`](https://github.com/SamDuffield/abile).
130
+ <!--ecosystem-end-->
131
+
132
+ ## Contributing
133
+
134
+ We're always looking for contributions!
135
+ Check out the [contributing guide](CONTRIBUTING.md) for more information.
136
+
@@ -0,0 +1,103 @@
1
+ <!--intro-start-->
2
+ <div align="center">
3
+ <img src="docs/assets/cuthbert.png" alt="logo"></img>
4
+ </div>
5
+
6
+ A JAX library for state-space model inference
7
+ (filtering, smoothing, static parameter estimation).
8
+
9
+ > Disclaimer: The name `cuthbert` was chosen as a playful nod to the well-known
10
+ > caterpillar cake rivalry between Aldi and M&S in the UK, as the classic state-space
11
+ > model diagram looks vaguely like a caterpillar. However, this software project
12
+ > has no formal connection to Aldi, M&S, or any food products (notwithstanding the coffee drunk during its writeup).
13
+ > `cuthbert` is simply a fun name for this state-space model library and should not be interpreted as an
14
+ > endorsement, association, or affiliation with any brand or animal themed baked goods.
15
+
16
+ [![Discord](https://img.shields.io/badge/Discord-5865F2?logo=discord&logoColor=white&style=for-the-badge)](https://discord.gg/sBnr6JhT)
17
+ [![GitHub](https://img.shields.io/badge/GitHub-181717?logo=github&logoColor=white&style=for-the-badge)](https://github.com/state-space-models/cuthbert)
18
+ [![PyPI](https://img.shields.io/pypi/v/cuthbert?style=for-the-badge)](https://pypi.org/project/cuthbert/)
19
+ [![Docs](https://img.shields.io/badge/Docs-b6d7a8?logo=materialformkdocs&logoColor=black&style=for-the-badge)](https://state-space-models.github.io/cuthbert/)
20
+ <!--intro-end-->
21
+
22
+ <!--goals-start-->
23
+ ### Goals
24
+ - Simple, flexible and performant interface for state-space model inference.
25
+ - Decoupling of model specification and inference. `cuthbert` is built to swap between
26
+ different **inference** methods without be tied to a specific model specification.
27
+ - Compose with the [JAX ecosystem](#ecosystem) for extensive external tools.
28
+ - Functional API: The only classes in `cuthbert` are `NamedTuple`s and `Protocol`s.
29
+ All functions are pure and work seamlessly with `jax.grad`, `jax.jit`, `jax.vmap` etc.
30
+ - Methods for filtering: $p(x_t \mid y_{0:t}, \theta)$.
31
+ - Methods for smoothing: $p(x_{0:T} \mid y_{0:T}, \theta)$ or $p(x_{t} \mid y_{0:T}, \theta)$.
32
+ - Methods for static parameter estimation: $p(\theta \mid y_{0:T})$
33
+ or $\text{argmax} p(y_{0:T} \mid \theta)$.
34
+ - This includes support for forward-backward/Baum-Welch, particle filtering/sequential Monte Carlo,
35
+ Kalman filtering (+ extended/unscented/ensemble), expectation-maximization and more!
36
+
37
+ ### Non-goals
38
+ - Tools for defining models and distributions. `cuthbert` is not a probabilistic programming language (PPL).
39
+ But can easily compose with [`dynamax`](https://github.com/probml/dynamax), [`distrax`](https://github.com/google-deepmind/distrax), [`numpyro`](https://github.com/pyro-ppl/numpyro) and [`pymc`](https://github.com/pymc-devs/pymc) in a similar way to how [`blackjax` does](https://blackjax-devs.github.io/blackjax/).
40
+ - ["SMC Samplers"](https://www.stats.ox.ac.uk/~doucet/delmoral_doucet_jasra_sequentialmontecarlosamplersJRSSB.pdf) which sample from a posterior
41
+ distribution which is not (necessarily) a state-space model - [`blackjax` is great for this](https://github.com/blackjax-devs/blackjax/tree/main/blackjax/smc).
42
+ <!--goals-end-->
43
+
44
+ <!--codebase-structure-start-->
45
+ ### Codebase structure
46
+
47
+ The codebase is structured as follows:
48
+
49
+ - `cuthbert`: The main package with unified interface for filtering and smoothing.
50
+ - `cuthbertlib`: A collection of atomic, smaller-scoped tools useful for state-space model inference,
51
+ that represent the building blocks that power the main `cuthbert` package.
52
+ <!--codebase-structure-end-->
53
+ - `docs`: Source code for the documentation for `cuthbert` and `cuthbertlib`.
54
+ - `tests`: Tests for the `cuthbert` and `cuthbertlib` packages.
55
+
56
+
57
+ <!--installation-start-->
58
+ ## Installation
59
+
60
+ `cuthbert` depends on JAX, so you'll need to [install JAX](https://docs.jax.dev/en/latest/installation.html) for the available hardware (CPU, GPU, or TPU).
61
+ For example, on computers with NVIDIA GPUs:
62
+
63
+ ```bash
64
+ pip install -U "jax[cuda13]"
65
+ ```
66
+
67
+ Now install `cuthbert` from PyPI:
68
+
69
+ ```bash
70
+ pip install -U cuthbert
71
+ ```
72
+
73
+ Installing `cuthbert` will also install `cuthbertlib`.
74
+
75
+ <!--installation-end-->
76
+
77
+ <!--ecosystem-start-->
78
+ ## Ecosystem
79
+ - `cuthbert` is built on top of [`jax`](https://github.com/google/jax) and composes
80
+ easily with other JAX packages, e.g. [`optax`](https://github.com/google-deepmind/optax)
81
+ for optimization, [`flax`](https://github.com/google/flax) for neural networks, and
82
+ [`blackjax`](https://github.com/blackjax-devs/blackjax) for (SG)MCMC as well as the PPLs
83
+ mentioned [above](#non-goals).
84
+ - What about [`dynamax`](https://github.com/probml/dynamax)?
85
+ - `dynamax` is a great library for state-space model specification and inference with
86
+ discrete or Gaussian state-space models. `cuthbert` is focused on inference
87
+ with arbitrary state-space models via e.g. SMC that is not supported in `dynamax`.
88
+ However as they are both built on [`jax`](https://github.com/google/jax)
89
+ they can be used together! A `dynamax`
90
+ model can be passed to `cuthbert` for inference.
91
+ - And [`particles`](https://github.com/nchopin/particles)?
92
+ - [`particles`](https://github.com/nchopin/particles) and the accompanying book
93
+ [Sequential Monte Carlo Methods in Practice](https://link.springer.com/book/10.1007/978-3-030-47845-2)
94
+ are wonderful learning materials for state-space models and SMC.
95
+ `cuthbert` is more focused on performance and composability with the JAX ecosystem.
96
+ - Much of the code in `cuthbert` is built on work from [`sqrt-parallel-smoothers`](https://github.com/EEA-sensors/sqrt-parallel-smoothers), [`mocat`](https://github.com/SamDuffield/mocat) and [`abile`](https://github.com/SamDuffield/abile).
97
+ <!--ecosystem-end-->
98
+
99
+ ## Contributing
100
+
101
+ We're always looking for contributions!
102
+ Check out the [contributing guide](CONTRIBUTING.md) for more information.
103
+
@@ -0,0 +1,12 @@
1
+ from cuthbert import discrete, gaussian, smc
2
+ from cuthbert.filtering import filter
3
+ from cuthbert.inference import (
4
+ Filter,
5
+ FilterCombine,
6
+ FilterPrepare,
7
+ InitPrepare,
8
+ Smoother,
9
+ SmootherCombine,
10
+ SmootherPrepare,
11
+ )
12
+ from cuthbert.smoothing import smoother
@@ -0,0 +1,81 @@
1
+ """Unified cuthbert filtering interface."""
2
+
3
+ import warnings
4
+
5
+ from jax import numpy as jnp
6
+ from jax import random, tree, vmap
7
+ from jax.lax import associative_scan, scan
8
+
9
+ from cuthbert.inference import Filter
10
+ from cuthbertlib.types import ArrayTree, ArrayTreeLike, KeyArray
11
+
12
+
13
+ def filter(
14
+ filter_obj: Filter,
15
+ model_inputs: ArrayTreeLike,
16
+ parallel: bool = False,
17
+ key: KeyArray | None = None,
18
+ ) -> ArrayTree:
19
+ """Applies offline filtering given a filter object and model inputs.
20
+
21
+ `model_inputs` should have leading temporal dimension of length T + 1,
22
+ where T is the number of time steps excluding the initial state.
23
+
24
+ Args:
25
+ filter_obj: The filter inference object.
26
+ model_inputs: The model inputs (with leading temporal dimension of length T + 1).
27
+ parallel: Whether to run the filter in parallel.
28
+ Requires `filter.associative_filter` to be `True`.
29
+ key: The key for the random number generator.
30
+
31
+ Returns:
32
+ The filtered states (NamedTuple with leading temporal dimension of length T + 1).
33
+ """
34
+ if parallel and not filter_obj.associative:
35
+ warnings.warn(
36
+ f"Parallel filtering attempted but filter.associative is False for {filter_obj}"
37
+ )
38
+
39
+ T = tree.leaves(model_inputs)[0].shape[0] - 1
40
+
41
+ if key is None:
42
+ # This will throw error if used as a key, which is desired behavior
43
+ # (albeit not a useful error, we could improve this)
44
+ prepare_keys = jnp.empty(T + 1)
45
+ else:
46
+ prepare_keys = random.split(key, T + 1)
47
+
48
+ init_model_input = tree.map(lambda x: x[0], model_inputs)
49
+ init_state = filter_obj.init_prepare(init_model_input, key=prepare_keys[0])
50
+
51
+ prep_model_inputs = tree.map(lambda x: x[1:], model_inputs)
52
+
53
+ if parallel:
54
+ other_prep_states = vmap(lambda inp, k: filter_obj.filter_prepare(inp, key=k))(
55
+ prep_model_inputs, prepare_keys[1:]
56
+ )
57
+ prep_states = tree.map(
58
+ lambda x, y: jnp.concatenate([x[None], y]), init_state, other_prep_states
59
+ )
60
+ states = associative_scan(
61
+ vmap(filter_obj.filter_combine),
62
+ prep_states,
63
+ )
64
+ else:
65
+
66
+ def body(prev_state, prep_inp_and_k):
67
+ prep_inp, k = prep_inp_and_k
68
+ prep_state = filter_obj.filter_prepare(prep_inp, key=k)
69
+ state = filter_obj.filter_combine(prev_state, prep_state)
70
+ return state, state
71
+
72
+ _, states = scan(
73
+ body,
74
+ init_state,
75
+ (prep_model_inputs, prepare_keys[1:]),
76
+ )
77
+ states = tree.map(
78
+ lambda x, y: jnp.concatenate([x[None], y]), init_state, states
79
+ )
80
+
81
+ return states
@@ -0,0 +1,220 @@
1
+ """Provides protocols and types for representing unified inference objects."""
2
+
3
+ from typing import NamedTuple, Protocol
4
+
5
+ from cuthbertlib.types import ArrayTree, ArrayTreeLike, KeyArray
6
+
7
+
8
+ class InitPrepare(Protocol):
9
+ """Protocol for preparing the initial state for the inference."""
10
+
11
+ def __call__(
12
+ self,
13
+ model_inputs: ArrayTreeLike,
14
+ key: KeyArray | None = None,
15
+ ) -> ArrayTree:
16
+ """Prepare the initial state for the inference.
17
+
18
+ The state at the first time point, prior to any observations.
19
+
20
+ Args:
21
+ model_inputs: The model inputs at the first time point.
22
+ key: The key for the random number generator.
23
+ Optional, as only used for stochastic inference methods
24
+
25
+ Returns:
26
+ The initial state, a NamedTuple with inference-specific fields.
27
+ """
28
+ ...
29
+
30
+
31
+ class FilterPrepare(Protocol):
32
+ """Protocol for preparing the state for the filter at the next time point."""
33
+
34
+ def __call__(
35
+ self,
36
+ model_inputs: ArrayTreeLike,
37
+ key: KeyArray | None = None,
38
+ ) -> ArrayTree:
39
+ """Prepare the state for the filter at the next time point.
40
+
41
+ Converts the model inputs (and any stochasticity) into a unified state
42
+ object which can be combined with a state (of the same form) from the
43
+ previous time point with FilterCombine.
44
+
45
+ state = FilterCombine(prev_state, FilterPrepare(model_inputs, key))
46
+
47
+ Args:
48
+ model_inputs: The model inputs at the next time point.
49
+ key: The key for the random number generator.
50
+ Optional, as only used for stochastic inference methods
51
+
52
+ Returns:
53
+ The state prepared for FilterCombine,
54
+ a NamedTuple with inference-specific fields.
55
+ """
56
+ ...
57
+
58
+
59
+ class FilterCombine(Protocol):
60
+ """Protocol for combining the previous state with the state from FilterPrepare."""
61
+
62
+ def __call__(
63
+ self,
64
+ state_1: ArrayTreeLike,
65
+ state_2: ArrayTreeLike,
66
+ ) -> ArrayTree:
67
+ """Combine state from previous time point with state from FilterPrepare.
68
+
69
+ ```python
70
+ state = FilterCombine(prev_state, FilterPrepare(model_inputs, key))
71
+ ```
72
+
73
+ Args:
74
+ state_1: The state from the previous time point.
75
+ state_2: The state from FilterPrepare for the current time point.
76
+
77
+ Returns:
78
+ The combined filter state, a NamedTuple with inference-specific fields.
79
+ """
80
+ ...
81
+
82
+
83
+ class SmootherPrepare(Protocol):
84
+ """Protocol for preparing the state for the smoother."""
85
+
86
+ def __call__(
87
+ self,
88
+ filter_state: ArrayTreeLike,
89
+ model_inputs: ArrayTreeLike,
90
+ key: KeyArray | None = None,
91
+ ) -> ArrayTree:
92
+ """Prepare the state for the smoother at the next time point.
93
+
94
+ Converts `filter_state` with `model_inputs` (and any stochasticity) into a
95
+ unified state object which can be combined with a state (of the same form)
96
+ from the next time point with `SmootherCombine`.
97
+
98
+ Remember smoothing iterates backwards in time.
99
+
100
+ ```python
101
+ state = SmootherCombine(
102
+ SmootherPrepare(filter_state, model_inputs, key), next_smoother_state
103
+ )
104
+ ```
105
+
106
+ Note that the `model_inputs` here are different to `filter_state.model_inputs`.
107
+ The `model_inputs` required here are for the transition from t to t+1.
108
+ `filter_state.model_inputs` represents the transition from t-1 to t.
109
+
110
+ Args:
111
+ filter_state: The state from the filter at the previous time point.
112
+ model_inputs: Model inputs for the transition from t to t+1.
113
+ key: The key for the random number generator.
114
+ Optional, as only used for stochastic inference methods
115
+
116
+ Returns:
117
+ The state prepared for `SmootherCombine`,
118
+ a NamedTuple with inference-specific fields.
119
+ """
120
+ ...
121
+
122
+
123
+ class SmootherCombine(Protocol):
124
+ """Protocol for combining the next smoother state with the state prepared with latest model inputs."""
125
+
126
+ def __call__(
127
+ self,
128
+ state_1: ArrayTreeLike,
129
+ state_2: ArrayTreeLike,
130
+ ) -> ArrayTree:
131
+ """Combine the state from the next time point with the state from `SmootherPrepare`.
132
+
133
+ Remember smoothing iterates backwards in time.
134
+
135
+ ```python
136
+ state = SmootherCombine(
137
+ SmootherPrepare(filter_state, model_inputs, key), next_smoother_state
138
+ )
139
+ ```
140
+
141
+ Args:
142
+ state_1: The state from `SmootherPrepare` for the current time point.
143
+ state_2: The state from the next time point.
144
+
145
+ Returns:
146
+ The combined smoother state, a NamedTuple with inference-specific fields.
147
+ """
148
+ ...
149
+
150
+
151
+ class ConvertFilterToSmootherState(Protocol):
152
+ """Protocol for converting a filter state to a smoother state."""
153
+
154
+ def __call__(
155
+ self,
156
+ filter_state: ArrayTreeLike,
157
+ model_inputs: ArrayTreeLike | None = None,
158
+ key: KeyArray | None = None,
159
+ ) -> ArrayTree:
160
+ """Convert the filter state to a smoother state.
161
+
162
+ Useful for offline smoothing where the final filter state is statistically
163
+ equivalent to the final smoother state.
164
+ This function converts the filter state to the smoother state data structure.
165
+
166
+ Args:
167
+ filter_state: The filter state.
168
+ model_inputs: Only used to create an empty `model_inputs` tree
169
+ (the values are ignored).
170
+ Useful so that the final smoother state has the same structure as the rest.
171
+ By default, `filter_state.model_inputs` is used. So this
172
+ is only needed if the smoother `model_inputs` have a different tree
173
+ structure to `filter_state.model_inputs`.
174
+ key: The key for the random number generator.
175
+ Optional, as only used for stochastic inference methods
176
+
177
+ Returns:
178
+ The smoother state.
179
+ """
180
+ ...
181
+
182
+
183
+ class Filter(NamedTuple):
184
+ """Filter object.
185
+
186
+ Typically passed to [cuthbert.filtering.filter][].
187
+
188
+ Attributes:
189
+ init_prepare: Function to prepare the initial state for the filter.
190
+ filter_prepare: Function to prepare intermediate states for the filter.
191
+ filter_combine: Function that combines two filter states to produce another.
192
+ associative: Whether `filter_combine` is an associative operator. Temporally
193
+ parallelized filters are guaranteed to produce correct results only if
194
+ `associative=True`.
195
+ """
196
+
197
+ init_prepare: InitPrepare
198
+ filter_prepare: FilterPrepare
199
+ filter_combine: FilterCombine
200
+ associative: bool = False
201
+
202
+
203
+ class Smoother(NamedTuple):
204
+ """Smoother object.
205
+
206
+ Typically passed to [cuthbert.smoothing.smoother][].
207
+
208
+ Attributes:
209
+ convert_filter_to_smoother_state: Function to convert the final filter state to a smoother state.
210
+ smoother_prepare: Function to prepare intermediate states for the smoother.
211
+ smoother_combine: Function that combines two smoother states to produce another.
212
+ associative: Whether `smoother_combine` is an associative operator. Temporally
213
+ parallelized smoothers are guaranteed to produce correct results only if
214
+ `associative=True`.
215
+ """
216
+
217
+ convert_filter_to_smoother_state: ConvertFilterToSmootherState
218
+ smoother_prepare: SmootherPrepare
219
+ smoother_combine: SmootherCombine
220
+ associative: bool = False
@@ -0,0 +1,128 @@
1
+ """Unified cuthbert smoothing interface."""
2
+
3
+ import warnings
4
+
5
+ from jax import numpy as jnp
6
+ from jax import random, tree, vmap
7
+ from jax.lax import associative_scan, scan
8
+
9
+ from cuthbert.inference import Smoother
10
+ from cuthbert.utils import dummy_tree_like
11
+ from cuthbertlib.types import ArrayTree, ArrayTreeLike, KeyArray
12
+
13
+
14
+ def smoother(
15
+ smoother_obj: Smoother,
16
+ filter_states: ArrayTreeLike,
17
+ model_inputs: ArrayTreeLike | None = None,
18
+ parallel: bool = False,
19
+ key: KeyArray | None = None,
20
+ ) -> ArrayTree:
21
+ """Applies offline smoothing given a smoother object, output from filter, and model inputs.
22
+
23
+ `filter_states` should have leading temporal dimension of length T + 1, where
24
+ T is the number of time steps excluding the initial state.
25
+
26
+ Each element of `model_inputs` refers to the transition from t to t+1, except for the
27
+ first element which refers to the initial state. The initial state `model_inputs`
28
+ are not used for smoothing. Thus the `model_inputs` used here have length T.
29
+ By default, `filter_states.model_inputs[1:]` are used (i.e. the `model_inputs`
30
+ used for the initial state is ignored).
31
+
32
+ Args:
33
+ smoother_obj: The smoother inference object.
34
+ filter_states: The filtered states (with leading temporal dimension of length T + 1).
35
+ model_inputs: The model inputs (with leading temporal dimension of length T).
36
+ Optional, if None then `filter_states.model_inputs[1:]` are used.
37
+ parallel: Whether to run the smoother in parallel.
38
+ Requires `smoother_obj.associative_smoother` to be `True`.
39
+ key: The key for the random number generator.
40
+
41
+ Returns:
42
+ The smoothed states (NamedTuple with leading temporal dimension of length T + 1).
43
+ """
44
+ if parallel and not smoother_obj.associative:
45
+ warnings.warn(
46
+ "Parallel smoothing attempted but smoother.associative is False "
47
+ f"for {smoother}"
48
+ )
49
+
50
+ if model_inputs is None:
51
+ model_inputs = filter_states.model_inputs
52
+
53
+ T = tree.leaves(filter_states)[0].shape[0] - 1
54
+
55
+ # model_inputs for the dynamics distribution from t-1 to t is stored
56
+ # in model_inputs[t] thus we need model_inputs[1:]
57
+ # model_inputs[0] is only used for init_prepare and not for smoothing.
58
+ # Therefore, we allow model_inputs to be either of length T + 1 or T
59
+ # where if length is T + 1 then we simply discard model_inputs[0]
60
+ model_inputs_length = tree.leaves(model_inputs)[0].shape[0]
61
+ if model_inputs_length == T + 1:
62
+ model_inputs = tree.map(lambda x: x[1:], model_inputs)
63
+ elif model_inputs_length != T:
64
+ raise ValueError(
65
+ "model_inputs must have length T + 1 or T, got length "
66
+ f"{model_inputs_length}"
67
+ )
68
+
69
+ if key is None:
70
+ # This will throw error if used as a key, which is desired
71
+ # (albeit not a useful error, we could improve this)
72
+ prepare_keys = jnp.empty(T + 1)
73
+ else:
74
+ prepare_keys = random.split(key, T + 1)
75
+
76
+ final_filter_state = tree.map(lambda x: x[-1], filter_states)
77
+ other_filter_states = tree.map(lambda x: x[:-1], filter_states)
78
+
79
+ # Final smoother state doesn't need model inputs, so we create a dummy one
80
+ # with the same structure as model_inputs but with all values set to dummy values.
81
+ dummy_single_model_inputs = dummy_tree_like(tree.map(lambda x: x[0], model_inputs))
82
+
83
+ final_smoother_state = smoother_obj.convert_filter_to_smoother_state(
84
+ final_filter_state, model_inputs=dummy_single_model_inputs, key=prepare_keys[0]
85
+ )
86
+
87
+ if parallel:
88
+ prep_states = vmap(
89
+ lambda fs, inp, k: smoother_obj.smoother_prepare(
90
+ fs, model_inputs=inp, key=k
91
+ )
92
+ )(other_filter_states, model_inputs, prepare_keys[1:])
93
+ prep_states = tree.map(
94
+ lambda x, y: jnp.concatenate([x, y[None]]),
95
+ prep_states,
96
+ final_smoother_state,
97
+ )
98
+
99
+ states = associative_scan(
100
+ vmap(lambda current, next: smoother_obj.smoother_combine(next, current)),
101
+ # TODO: Maybe change cuthbertlib direction so that this lambda isn't needed
102
+ prep_states,
103
+ reverse=True,
104
+ )
105
+ else:
106
+
107
+ def body(next_state, filt_state_and_prep_inp_and_k):
108
+ filt_state, prep_inp, k = filt_state_and_prep_inp_and_k
109
+ prep_state = smoother_obj.smoother_prepare(
110
+ filt_state, model_inputs=prep_inp, key=k
111
+ )
112
+ state = smoother_obj.smoother_combine(prep_state, next_state)
113
+ return state, state
114
+
115
+ _, states = scan(
116
+ body,
117
+ final_smoother_state,
118
+ (other_filter_states, model_inputs, prepare_keys[1:]),
119
+ reverse=True,
120
+ )
121
+
122
+ states = tree.map(
123
+ lambda x, y: jnp.concatenate([x, y[None]]),
124
+ states,
125
+ final_smoother_state,
126
+ )
127
+
128
+ return states
@@ -0,0 +1,32 @@
1
+ """Utility functions (filling dummy arrays and trees) for cuthbert."""
2
+
3
+ import jax
4
+ import jax.numpy as jnp
5
+
6
+ from cuthbertlib.types import Array, ArrayLike, ArrayTree, ArrayTreeLike
7
+
8
+
9
+ def _dummy_array(leaf: ArrayLike | jax.ShapeDtypeStruct) -> Array:
10
+ """Returns an array of the same shape and dtype filled with dummy values."""
11
+ if isinstance(leaf, jax.ShapeDtypeStruct):
12
+ leaf = jnp.empty_like(leaf)
13
+
14
+ leaf = jnp.asarray(leaf)
15
+ dtype = leaf.dtype
16
+ shape = leaf.shape
17
+
18
+ if jnp.issubdtype(dtype, jnp.integer):
19
+ min_val = jnp.iinfo(dtype).min
20
+ elif jnp.issubdtype(dtype, jnp.floating):
21
+ min_val = jnp.finfo(dtype).min
22
+ elif jnp.issubdtype(dtype, jnp.bool_):
23
+ min_val = False
24
+ else:
25
+ raise ValueError(f"Unsupported dtype: {dtype}")
26
+
27
+ return jnp.full(shape, min_val, dtype=dtype)
28
+
29
+
30
+ def dummy_tree_like(pytree: ArrayTreeLike) -> ArrayTree:
31
+ """Returns a pytree with the same structure filled with dummy values."""
32
+ return jax.tree.map(_dummy_array, pytree)
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: cuthbert
3
+ Version: 0.0.1
4
+ Summary: State-space model inference with JAX
5
+ Author-email: Sam Duffield <s@mduffield.com>, Sahel Iqbal <sahel13miqbal@proton.me>, Adrien Corenflos <adrien.corenflos.stats@gmail.com>
6
+ License: Apache-2.0
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: jax>=0.4.35
11
+ Requires-Dist: numba>=0.60.0
12
+ Provides-Extra: tests
13
+ Requires-Dist: chex; extra == "tests"
14
+ Requires-Dist: pre-commit; extra == "tests"
15
+ Requires-Dist: ruff; extra == "tests"
16
+ Requires-Dist: pyright; extra == "tests"
17
+ Requires-Dist: pytest; extra == "tests"
18
+ Requires-Dist: pytest-xdist; extra == "tests"
19
+ Requires-Dist: entangled-cli; python_version >= "3.12" and extra == "tests"
20
+ Provides-Extra: docs
21
+ Requires-Dist: mkdocs-material; extra == "docs"
22
+ Requires-Dist: mkdocs-include-markdown-plugin; extra == "docs"
23
+ Requires-Dist: mkdocstrings-python; extra == "docs"
24
+ Provides-Extra: examples
25
+ Requires-Dist: matplotlib; extra == "examples"
26
+ Requires-Dist: pandas; extra == "examples"
27
+ Requires-Dist: pandas-stubs; extra == "examples"
28
+ Requires-Dist: yfinance; extra == "examples"
29
+ Requires-Dist: dynamax; extra == "examples"
30
+ Requires-Dist: ipython; extra == "examples"
31
+ Requires-Dist: tfp-nightly[jax]; extra == "examples"
32
+ Dynamic: license-file
33
+
34
+ <!--intro-start-->
35
+ <div align="center">
36
+ <img src="docs/assets/cuthbert.png" alt="logo"></img>
37
+ </div>
38
+
39
+ A JAX library for state-space model inference
40
+ (filtering, smoothing, static parameter estimation).
41
+
42
+ > Disclaimer: The name `cuthbert` was chosen as a playful nod to the well-known
43
+ > caterpillar cake rivalry between Aldi and M&S in the UK, as the classic state-space
44
+ > model diagram looks vaguely like a caterpillar. However, this software project
45
+ > has no formal connection to Aldi, M&S, or any food products (notwithstanding the coffee drunk during its writeup).
46
+ > `cuthbert` is simply a fun name for this state-space model library and should not be interpreted as an
47
+ > endorsement, association, or affiliation with any brand or animal themed baked goods.
48
+
49
+ [![Discord](https://img.shields.io/badge/Discord-5865F2?logo=discord&logoColor=white&style=for-the-badge)](https://discord.gg/sBnr6JhT)
50
+ [![GitHub](https://img.shields.io/badge/GitHub-181717?logo=github&logoColor=white&style=for-the-badge)](https://github.com/state-space-models/cuthbert)
51
+ [![PyPI](https://img.shields.io/pypi/v/cuthbert?style=for-the-badge)](https://pypi.org/project/cuthbert/)
52
+ [![Docs](https://img.shields.io/badge/Docs-b6d7a8?logo=materialformkdocs&logoColor=black&style=for-the-badge)](https://state-space-models.github.io/cuthbert/)
53
+ <!--intro-end-->
54
+
55
+ <!--goals-start-->
56
+ ### Goals
57
+ - Simple, flexible and performant interface for state-space model inference.
58
+ - Decoupling of model specification and inference. `cuthbert` is built to swap between
59
+ different **inference** methods without be tied to a specific model specification.
60
+ - Compose with the [JAX ecosystem](#ecosystem) for extensive external tools.
61
+ - Functional API: The only classes in `cuthbert` are `NamedTuple`s and `Protocol`s.
62
+ All functions are pure and work seamlessly with `jax.grad`, `jax.jit`, `jax.vmap` etc.
63
+ - Methods for filtering: $p(x_t \mid y_{0:t}, \theta)$.
64
+ - Methods for smoothing: $p(x_{0:T} \mid y_{0:T}, \theta)$ or $p(x_{t} \mid y_{0:T}, \theta)$.
65
+ - Methods for static parameter estimation: $p(\theta \mid y_{0:T})$
66
+ or $\text{argmax} p(y_{0:T} \mid \theta)$.
67
+ - This includes support for forward-backward/Baum-Welch, particle filtering/sequential Monte Carlo,
68
+ Kalman filtering (+ extended/unscented/ensemble), expectation-maximization and more!
69
+
70
+ ### Non-goals
71
+ - Tools for defining models and distributions. `cuthbert` is not a probabilistic programming language (PPL).
72
+ But can easily compose with [`dynamax`](https://github.com/probml/dynamax), [`distrax`](https://github.com/google-deepmind/distrax), [`numpyro`](https://github.com/pyro-ppl/numpyro) and [`pymc`](https://github.com/pymc-devs/pymc) in a similar way to how [`blackjax` does](https://blackjax-devs.github.io/blackjax/).
73
+ - ["SMC Samplers"](https://www.stats.ox.ac.uk/~doucet/delmoral_doucet_jasra_sequentialmontecarlosamplersJRSSB.pdf) which sample from a posterior
74
+ distribution which is not (necessarily) a state-space model - [`blackjax` is great for this](https://github.com/blackjax-devs/blackjax/tree/main/blackjax/smc).
75
+ <!--goals-end-->
76
+
77
+ <!--codebase-structure-start-->
78
+ ### Codebase structure
79
+
80
+ The codebase is structured as follows:
81
+
82
+ - `cuthbert`: The main package with unified interface for filtering and smoothing.
83
+ - `cuthbertlib`: A collection of atomic, smaller-scoped tools useful for state-space model inference,
84
+ that represent the building blocks that power the main `cuthbert` package.
85
+ <!--codebase-structure-end-->
86
+ - `docs`: Source code for the documentation for `cuthbert` and `cuthbertlib`.
87
+ - `tests`: Tests for the `cuthbert` and `cuthbertlib` packages.
88
+
89
+
90
+ <!--installation-start-->
91
+ ## Installation
92
+
93
+ `cuthbert` depends on JAX, so you'll need to [install JAX](https://docs.jax.dev/en/latest/installation.html) for the available hardware (CPU, GPU, or TPU).
94
+ For example, on computers with NVIDIA GPUs:
95
+
96
+ ```bash
97
+ pip install -U "jax[cuda13]"
98
+ ```
99
+
100
+ Now install `cuthbert` from PyPI:
101
+
102
+ ```bash
103
+ pip install -U cuthbert
104
+ ```
105
+
106
+ Installing `cuthbert` will also install `cuthbertlib`.
107
+
108
+ <!--installation-end-->
109
+
110
+ <!--ecosystem-start-->
111
+ ## Ecosystem
112
+ - `cuthbert` is built on top of [`jax`](https://github.com/google/jax) and composes
113
+ easily with other JAX packages, e.g. [`optax`](https://github.com/google-deepmind/optax)
114
+ for optimization, [`flax`](https://github.com/google/flax) for neural networks, and
115
+ [`blackjax`](https://github.com/blackjax-devs/blackjax) for (SG)MCMC as well as the PPLs
116
+ mentioned [above](#non-goals).
117
+ - What about [`dynamax`](https://github.com/probml/dynamax)?
118
+ - `dynamax` is a great library for state-space model specification and inference with
119
+ discrete or Gaussian state-space models. `cuthbert` is focused on inference
120
+ with arbitrary state-space models via e.g. SMC that is not supported in `dynamax`.
121
+ However as they are both built on [`jax`](https://github.com/google/jax)
122
+ they can be used together! A `dynamax`
123
+ model can be passed to `cuthbert` for inference.
124
+ - And [`particles`](https://github.com/nchopin/particles)?
125
+ - [`particles`](https://github.com/nchopin/particles) and the accompanying book
126
+ [Sequential Monte Carlo Methods in Practice](https://link.springer.com/book/10.1007/978-3-030-47845-2)
127
+ are wonderful learning materials for state-space models and SMC.
128
+ `cuthbert` is more focused on performance and composability with the JAX ecosystem.
129
+ - Much of the code in `cuthbert` is built on work from [`sqrt-parallel-smoothers`](https://github.com/EEA-sensors/sqrt-parallel-smoothers), [`mocat`](https://github.com/SamDuffield/mocat) and [`abile`](https://github.com/SamDuffield/abile).
130
+ <!--ecosystem-end-->
131
+
132
+ ## Contributing
133
+
134
+ We're always looking for contributions!
135
+ Check out the [contributing guide](CONTRIBUTING.md) for more information.
136
+
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ cuthbert/__init__.py
5
+ cuthbert/filtering.py
6
+ cuthbert/inference.py
7
+ cuthbert/smoothing.py
8
+ cuthbert/utils.py
9
+ cuthbert.egg-info/PKG-INFO
10
+ cuthbert.egg-info/SOURCES.txt
11
+ cuthbert.egg-info/dependency_links.txt
12
+ cuthbert.egg-info/requires.txt
13
+ cuthbert.egg-info/top_level.txt
14
+ cuthbertlib/__init__.py
15
+ cuthbertlib/types.py
16
+ tests/test_examples_scripts.py
@@ -0,0 +1,27 @@
1
+ jax>=0.4.35
2
+ numba>=0.60.0
3
+
4
+ [docs]
5
+ mkdocs-material
6
+ mkdocs-include-markdown-plugin
7
+ mkdocstrings-python
8
+
9
+ [examples]
10
+ matplotlib
11
+ pandas
12
+ pandas-stubs
13
+ yfinance
14
+ dynamax
15
+ ipython
16
+ tfp-nightly[jax]
17
+
18
+ [tests]
19
+ chex
20
+ pre-commit
21
+ ruff
22
+ pyright
23
+ pytest
24
+ pytest-xdist
25
+
26
+ [tests:python_version >= "3.12"]
27
+ entangled-cli
@@ -0,0 +1,2 @@
1
+ cuthbert
2
+ cuthbertlib
@@ -0,0 +1,20 @@
1
+ """Type aliases for common types used in the library."""
2
+
3
+ from typing import Any, Callable, TypeAlias
4
+
5
+ from jax import Array
6
+ from jax.typing import ArrayLike
7
+
8
+ KeyArray: TypeAlias = Array # No native JAX type annotation for keys https://jax.readthedocs.io/en/latest/changelog.html#jax-0-4-16-sept-18-2023
9
+ ArrayTree: TypeAlias = Any # No native JAX type annotation for PyTrees https://github.com/google/jax/issues/3340
10
+ ArrayTreeLike: TypeAlias = Any # Tree with all leaves castable to jax.Array https://jax.readthedocs.io/en/latest/jax.typing.html#module-jax.typing
11
+ ScalarArray: TypeAlias = (
12
+ Array # jax.Array with just a single float element, i.e. shape ()
13
+ )
14
+ ScalarArrayLike: TypeAlias = ArrayLike # Object that will be cast to a ScalarArray
15
+
16
+ LogDensity: TypeAlias = Callable[[ArrayTreeLike], ScalarArray]
17
+ LogConditionalDensity: TypeAlias = Callable[[ArrayTreeLike, ArrayTreeLike], ScalarArray]
18
+ LogConditionalDensityAux: TypeAlias = Callable[
19
+ [ArrayTreeLike, ArrayTreeLike], tuple[ScalarArray, ArrayTree]
20
+ ]
@@ -0,0 +1,64 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cuthbert"
7
+ version = "0.0.1"
8
+ description = "State-space model inference with JAX"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [
13
+ { name = "Sam Duffield", email = "s@mduffield.com" },
14
+ { name = "Sahel Iqbal", email = "sahel13miqbal@proton.me" },
15
+ { name = "Adrien Corenflos", email = "adrien.corenflos.stats@gmail.com" },
16
+ ]
17
+
18
+ dependencies = [
19
+ "jax>=0.4.35",
20
+ "numba>=0.60.0",
21
+ ]
22
+
23
+ [tool.uv]
24
+ # The tensorflow-probability override forces installation on undefined platforms only
25
+ # effectively disabling it for all normal platforms
26
+ override-dependencies = [
27
+ "tensorflow-probability ; sys_platform == 'undefined'",
28
+ ]
29
+
30
+ [tool.setuptools.packages.find]
31
+ include = ["cuthbert", "cuthbertlib"]
32
+
33
+ [project.optional-dependencies]
34
+ tests = [
35
+ "chex", # test additional dependencies
36
+ "pre-commit", "ruff", "pyright", # linting etc
37
+ "pytest", "pytest-xdist", # testing
38
+ "entangled-cli; python_version >= '3.12'", # convert .md examples to .py, requires Python 3.12+
39
+ ]
40
+ docs = ["mkdocs-material", "mkdocs-include-markdown-plugin", "mkdocstrings-python"]
41
+ examples = [
42
+ "matplotlib", "pandas", "pandas-stubs", "yfinance",
43
+ "dynamax", "ipython", "tfp-nightly[jax]",
44
+ ]
45
+ # ipython just required for dynamax, can be removed when they do a new release
46
+ # tfp-nightly[jax] provides tensorflow_probability module that dynamax needs
47
+
48
+ [tool.ruff]
49
+ [tool.ruff.lint.per-file-ignores]
50
+ "__init__.py" = ["F401", "F821", "E402", "D104"]
51
+ "tests/**/*.py" = ["D"] # no docstring checking for tests
52
+ "cuthbertlib/resampling/**/*.py" = ["D103"] # resampling uses decorator for docstrings
53
+ [tool.ruff.lint]
54
+ select = ["D"]
55
+ [tool.ruff.lint.pydocstyle]
56
+ convention = "google"
57
+
58
+ [tool.pytest]
59
+ [tool.pytest.ini_options]
60
+ markers = "examples: Run tangled example scripts as tests"
61
+
62
+ [tool.entangled]
63
+ version = "2.3.0"
64
+ ignore_list = ["CONTRIBUTING.md"]
@@ -0,0 +1,13 @@
1
+ import glob
2
+ import runpy
3
+
4
+ import pytest
5
+
6
+ EXAMPLES_DIR = "examples_scripts"
7
+
8
+
9
+ @pytest.mark.examples
10
+ @pytest.mark.parametrize("script", glob.glob(f"{EXAMPLES_DIR}/*.py"))
11
+ def test_example_scripts(script):
12
+ """Run each tangled example script to ensure it runs without error."""
13
+ runpy.run_path(script)
cuthbert-0.0.0/PKG-INFO DELETED
@@ -1,5 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: cuthbert
3
- Version: 0.0.0
4
- Summary: Coming soon
5
- Author-email: Sam Duffield <s@mduffield.com>
@@ -1,5 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: cuthbert
3
- Version: 0.0.0
4
- Summary: Coming soon
5
- Author-email: Sam Duffield <s@mduffield.com>
@@ -1,6 +0,0 @@
1
- pyproject.toml
2
- cuthbert/__init__.py
3
- cuthbert.egg-info/PKG-INFO
4
- cuthbert.egg-info/SOURCES.txt
5
- cuthbert.egg-info/dependency_links.txt
6
- cuthbert.egg-info/top_level.txt
@@ -1 +0,0 @@
1
- cuthbert
@@ -1,7 +0,0 @@
1
- [project]
2
- name = "cuthbert"
3
- authors = [
4
- {name = "Sam Duffield", email = "s@mduffield.com"},
5
- ]
6
- version = "0.0.0"
7
- description = "Coming soon"
File without changes