Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .JuliaFormatter.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
style = "blue"
always_use_return = true
ignore = ["benchmark/comparison", "benchmark/profiling", "deps", "docs", "notebooks", "paper"]
ignore = ["benchmark/comparison", "benchmark/somata", "benchmark/profiling", "deps", "docs", "notebooks", "paper"]
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
.vscode/
.idea/
.DS_Store
scratch/

# Jupyter notebooks
/tests/ssm_testing_notebook.ipynb
Expand Down Expand Up @@ -40,6 +41,9 @@ benchmark/comparison/benchmark.jl.claude/worktrees/
/.claude
/benchmark/comparison/results
CLAUDE.md
benchmark/somata/.CondaPkg/
benchmark/somata/__pycache__/
benchmark/somata/results

# Local profiling sandbox (never committed)
/dev/
Expand Down
4 changes: 3 additions & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
name = "StateSpaceDynamics"
uuid = "19cf8126-1d00-4ad8-bf17-4e76d7bc0f6d"
version = "0.4.1"
version = "0.5.0"
authors = ["Ryan Senne rsenne@bu.edu"]

[deps]
DSP = "717857b8-e6f2-59f4-9121-6e50c889abd2"
Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
HiddenMarkovModels = "84ca31d5-effc-45e0-bfda-5a68cd981f47"
LineSearches = "d3d80556-e9d4-5f37-9878-2ab0fcc64255"
Expand All @@ -19,6 +20,7 @@ Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
StatsAPI = "82ae8749-77ed-4fe6-ae5f-f523153014b0"

[compat]
DSP = "0.8.6"
Distributions = "0.25.109"
HiddenMarkovModels = "0.7.0"
LineSearches = "7"
Expand Down
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

StateSpaceDynamics.jl is a fast, self-contained Julia package for linear dynamical systems (LDS) and related latent state-space models. It covers Gaussian and Poisson LDS, Switching LDS (SLDS), and Probabilistic PCA, taking inspiration from [ssm](https://github.com/lindermanlab/ssm) (Linderman Lab) and [Dynamax](https://probml.github.io/dynamax/). It leverages Julia's speed and expressiveness to give researchers and data scientists a powerful, efficient toolkit for latent state-space modeling.

An opt-in [`Somata`](#oscillator-and-autoregressive-models-somata) submodule adds *structured* state models — banks of Matsuda oscillators and autoregressive processes, along with the Decomposed Oscillator Search — ported from [somata](https://github.com/mh105/somata) (Purdon lab).

This package is geared towards applications in neuroscience, so the models incorporate a certain neuroscience flavor (e.g., many of our models are trialized, as is common in experimental paradigms). However, the models are general enough to be used in other fields such as finance, robotics, and many other domains involving sequential data analysis.

We are continuously working to expand our model offerings. If you have suggestions for additional models or features, please open an issue on our GitHub repository.
Expand Down Expand Up @@ -92,6 +94,56 @@ This procedure begins by maximizing the joint log-probability of the latent stat

This approximation allows us to perform tractable, efficient inference in otherwise intractable models while still capturing uncertainty about the latent states. In the case of Gaussian observations and latents, this is equivalent to the canonical RTS smoothing algorithm.

## Oscillator and autoregressive models (`Somata`)

The `Somata` submodule adds two **structured** Gaussian state models, ported from [somata](https://github.com/mh105/somata), the Python state-space toolbox from the Purdon lab:

- `OscillatorStateModel` — a bank of independent Matsuda oscillators, each contributing a damped rotation `aᵢ · R(ωᵢ)` to `A` and an isotropic `σ²ᵢ · I₂` to `Q`.
- `AutoRegressiveStateModel` — univariate AR(p) processes in companion form.

Both subtype `AbstractLinearGaussianStateModel`, so they reuse the package's block-tridiagonal smoother, sufficient statistics, ELBO and `fit!` unchanged. What they add is a **constrained M-step**: closed-form updates that keep `A` and `Q` inside the model's structural family rather than letting EM move them freely. A fitted oscillator bank is therefore still an oscillator bank, with damping factors, frequencies and per-component noise variances you can read off and interpret directly.

Also included is **Decomposed Oscillator Search** (`dosc`), which chooses the number of oscillators for you: it proposes candidates from the eigenmodes of a high-order autoregressive fit, fits banks of increasing size by EM, and selects a size from the knee of the log-likelihood curve (or by eBIC). `diagnose_residuals` then tests whether the selected bank left structure behind in the one-step prediction residuals.

The submodule is opt-in: `using StateSpaceDynamics` exports only the name `Somata`, so names like `ncomps` and `theoretical_spectrum` stay out of the namespace of users who never touch these models.

```julia
using StateSpaceDynamics
using StateSpaceDynamics.Somata # opt-in; or reach the names qualified, as `Somata.dosc`
using StableRNGs

fs = 100.0 # sampling rate, Hz

# simulate three Matsuda oscillators (2, 10 and 22 Hz) observed in white noise
osc = OscillatorStateModel(;
a=[0.98, 0.99, 0.96], freq=[2.0, 10.0, 22.0], σ²=[1.0, 3.0, 0.5], fs=fs
)
lds_true = LinearDynamicalSystem(osc; R=1.5)
_, y = rand(StableRNG(1), lds_true, [3000])

# Decomposed Oscillator Search: how many oscillators, and at what frequencies?
dom = dosc(y[1]; fs=fs, osc_range=7)
ncomps(dom) # 3 oscillators selected
oscillator_frequencies(selected_model(dom).state_model) # [2.09, 9.99, 22.15] Hz

diagnose_residuals(dom).ljung_box # residual whiteness test
```

Or, when the number of components is already known, fit a bank of that size directly and let the constrained EM keep it structured:

```julia
osc_init = OscillatorStateModel(;
a=[0.9, 0.9, 0.9], freq=[3.0, 11.0, 20.0], σ²=[1.0, 1.0, 1.0], fs=fs
)
lds = LinearDynamicalSystem(osc_init; R=1.0)
elbos = fit!(lds, y[1]; max_iter=100)

oscillator_frequencies(lds.state_model) # [2.09, 9.99, 22.17] Hz
lds.state_model.a # [0.982, 0.990, 0.950]
```

These models are benchmarked directly against the Python package they were ported from, at a median **9.0× speedup** over 30 EM configurations (the gap is widest at small latent dimension and narrows toward the BLAS floor as the state grows). See [`benchmark/somata/README.md`](benchmark/somata/README.md) for the methodology, the full results, and the handful of documented numerical differences between the two implementations.

## Community Guidelines

- Maintain professional, respectful discourse
Expand All @@ -110,6 +162,10 @@ Help us maintain a welcoming environment for researchers and developers.
- [x] Switching Linear Dynamical Systems (SLDS)
- [ ] Recurrent Switching Linear Dynamical Systems (rSLDS)
- [x] Probabilistic PCA (PPCA)
- [x] Structured state models (`Somata` submodule)
- [x] Matsuda oscillator banks (`OscillatorStateModel`)
- [x] Autoregressive processes in companion form (`AutoRegressiveStateModel`)
- [x] Decomposed Oscillator Search (`dosc`)

## Related Packages

Expand All @@ -123,6 +179,8 @@ Help us maintain a welcoming environment for researchers and developers.

- [StateSpaceAnalysis.jl](https://github.com/harrisonritz/StateSpaceAnalysis.jl): A highly performant Julia package for fitting Gaussian LDS models. Currently being absorbed into this package.

- [somata](https://github.com/mh105/somata): A python package for state-space oscillator modeling of neural time series, from the Purdon lab. The source of our `Somata` submodule.

## Contributing

If you would like to contribute, report a bug, request a new feature, or simply give feedback, please feel free to [open an issue](https://github.com/depasquale-lab/StateSpaceDynamics.jl/issues) and we will get back to you in a timely manner.
Expand Down Expand Up @@ -189,3 +247,5 @@ This project follows the [all-contributors](https://github.com/all-contributors/
4. Paninski, L. et al. (2010). A new look at state-space models for neural data. Journal of computational neuroscience, 29(1-2), 107-126.

5. Macke, J. H. et al. (2011). Empirical models of spiking in neural populations. Advances in neural information processing systems, 24, 1350-1358.

6. Matsuda, T., Komaki, F. (2017). Time series decomposition into oscillation components and phase estimation. Neural Computation, 29(2), 332-367. [doi:10.1162/NECO_a_00916](https://doi.org/10.1162/NECO_a_00916)
23 changes: 23 additions & 0 deletions benchmark/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ All benchmarking lives under this directory. There are three distinct pieces:
|------|---------|------|
| `benchmarks.jl` + `Project.toml` | **Regression tracking** — the `SUITE` run by [AirspeedVelocity.jl](https://github.com/MilesCranmer/AirspeedVelocity.jl) to compare a PR against its base branch. | lightweight (BenchmarkTools, StableRNGs) |
| `comparison/` | **Cross-library comparison** — benchmarks StateSpaceDynamics against Python libraries (pykalman, Dynamax). | heavy (PythonCall/CondaPkg, Plots, CSV) |
| `somata/` | **SOMATA port comparison** — benchmarks `StateSpaceDynamics.Somata` against [somata](https://github.com/mh105/somata), the Python package it was ported from. | own env (PythonCall/CondaPkg, Plots, CSV) |
| `profiling/` | **Ad-hoc profiling** scripts for chasing allocations / hot loops during development. | uses `comparison/`'s env |

`somata/` keeps its own environment rather than joining `comparison/`: that one pins
`jax <= 0.5.0` for Dynamax, which somata's dependencies have no reason to resolve
against.

## Regression tracking (AirspeedVelocity)

`benchmark/benchmarks.jl` defines `const SUITE::BenchmarkGroup` (Gaussian + Poisson
Expand Down Expand Up @@ -45,6 +50,24 @@ julia --project=benchmark/comparison benchmark/comparison/plotting.jl # -

Curated comparison artifacts live in `comparison/results/`.

## SOMATA port comparison (somata)

The `somata/` harness fits the same oscillator and AR(p) models in
`StateSpaceDynamics.Somata` and in the reference Python package, from identical starting
parameters on identical data, for a fixed EM iteration count. It also writes a parity
table comparing the two fits, since a speed comparison between libraries that disagree
on the answer is not worth much. Needs a `somata` checkout at `../somata` (or
`SOMATA_PATH`).

```bash
julia --project=benchmark/somata benchmark/somata/setup.jl # once
julia --project=benchmark/somata benchmark/somata/run_benchmark.jl # -> results/*.csv
julia --project=benchmark/somata benchmark/somata/plotting.jl # -> results/*.svg/png
```

See [`somata/README.md`](somata/README.md) for what is held equal between the two and the
known implementation differences.

## Profiling

```bash
Expand Down
10 changes: 10 additions & 0 deletions benchmark/somata/CondaPkg.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
channels = ["conda-forge"]

[deps]
numpy = ""
pip = ""
tqdm = ""
joblib = ""
pytorch = ""
python = "3.12.*"
scipy = ""
19 changes: 19 additions & 0 deletions benchmark/somata/Project.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[deps]
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
CondaPkg = "992eb4ea-22a4-4c89-a5bb-47a3300528ab"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
JSON3 = "0f8b85d8-7281-11e9-16c2-39a750bddbf1"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Measures = "442fdcdd-2543-5da2-b0f3-8c86c306513e"
NPZ = "15e1cf62-19b3-5cfa-8e77-841668bca605"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
PythonCall = "6099a3de-0909-46bc-b1f4-468b9a2dfc0d"
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
StableRNGs = "860ef19b-820b-49d6-a774-d7a799459cd3"
StateSpaceDynamics = "19cf8126-1d00-4ad8-bf17-4e76d7bc0f6d"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"

[sources]
StateSpaceDynamics = {path = "../.."}
Loading
Loading