Skip to content

Feature/null models - #126

Merged
rsenne merged 6 commits into
devfrom
feature/null-models
Aug 24, 2026
Merged

rsenne merged 6 commits into
devfrom
feature/null-models

Conversation

@harrisonritz

@harrisonritz harrisonritz commented Jul 4, 2026 •

Copy link
Copy Markdown
Collaborator

Adds latent-free baselines to score a fitted model against, and the StatsAPI
model-comparison surface built on them. Resolves #125.

Baselines

AffineNullModel{T} is one affine-Gaussian baseline whose two structural
switches (lag, input_shift) are const fields, so the four named variants
are configurations of one type rather than four implementations:

baseline model
:intercept y_t ~ N(d, R)
:inputs y_t ~ N(d + D v_{t-shift}, R)
:var y_1 ~ N(μ₀, R₀); y_t ~ N(F y_{t-1} + d, R)
:var_inputs y_1 ~ N(μ₀, R₀); y_t ~ N(F y_{t-1} + d + D v_{t-shift}, R)

input_shift matches the LDS input timing: 1 for dynamics inputs (ux, which
act on x_{t-1}), 0 for observation inputs (uy). Fit with
fit!(null, y; inputs) and score with loglikelihood(null, y; inputs) — the
plug-in log-likelihood, so passing held-out data gives a held-out score. An
optional MNPrior on the stacked matrix [F d D] and IWPriors on R / R₀
mirror the LDS M-step.

One design-matrix builder, one regression kernel and one scoring kernel serve
all four: :intercept / :var are the zero-column-D special cases of
:inputs / :var_inputs by construction. Degenerate inputs are inert rather
than fatal — an input baseline on a channel the LDS does not use collapses to
its input-free counterpart.

Model comparison on a fitted LDS

  • r2(lds, y, variant; null=:intercept, null_inputs=:ux) — all three StatsBase
    pseudo-R² variants (:CoxSnell default, :McFadden, :Nagelkerke),
    comparing the LDS marginal log-likelihood (latents integrated out) to the
    baseline's plug-in log-likelihood on the same data.
  • nullloglikelihood(lds, y) — the intercept baseline's plug-in log-likelihood.
  • nobs(lds, y) — obs_dim * sum(tsteps), the scale both log-likelihoods live
    on.

The baseline inherits the LDS's R_prior by default, so both estimate R under
the same IW prior. Gaussian LDS only: a Poisson LDS has no tractable marginal
and an SLDS is a different type, so both raise a MethodError by design.

Errors

A rank-deficient design throws a NumericalStabilityError naming the cause
rather than a bare SingularException. The case that reaches users is an input
block carrying its own constant row, which duplicates the intercept every
baseline fits.

Tests

30 test functions in test/NullModels/NullModels.jl (142 assertions), checking
against independent closed-form references rather than the implementation's own
kernels: the analytic intercept MLE and Gaussian log-density, VAR(1) parameter
recovery, held-out plug-in scoring, capacity ordering across the four baselines,
input-shift alignment, ragged and single-trial data, the IW/MN prior log-terms,
the r2 variant formulas, and the error paths.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds latent-free “null” baselines and Cox–Snell R² utilities for comparing fitted Gaussian LDS models against observation-level baselines, and introduces an inputs-aware marginal log-likelihood for Gaussian LDS to ensure fair scoring when controls are present.

Changes:

  • Introduces test_null and compute_R2 (new src/stats/null_models.jl) and exports them from the main module.
  • Adds an inputs-aware loglikelihood(lds, data::Data) for Gaussian LDS that accounts for B·ux and D·uy.
  • Adds a comprehensive null-model and R² test suite and wires it into the test runner.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/stats/null_models.jl Implements null baseline fitting/scoring and Cox–Snell R² against those baselines.
src/lds/fit_LDS.jl Adds a loglikelihood(lds, data::Data) method that incorporates dynamics/observation inputs.
src/StateSpaceDynamics.jl Includes the new null-model module and exports test_null / compute_R2.
test/NullModels/NullModels.jl Adds extensive unit tests for null-model LLs, priors, validation, and R² behavior.
test/runtests.jl Registers the new “Null Models” testset in the main test runner.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/stats/null_models.jl Resolved
Comment thread src/stats/null_models.jl Resolved
Comment thread src/lds/fit_LDS.jl Resolved
Comment thread test/NullModels/NullModels.jl Resolved
@codecov

codecov Bot commented Jul 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.92746% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.21%. Comparing base (ba1b0be) to head (0c66b02).
⚠️ Report is 39 commits behind head on dev.

Files with missing lines Patch % Lines
src/stats/null_models.jl 97.89% 4 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##              dev     #126       +/-   ##
===========================================
+ Coverage   82.68%   96.21%   +13.53%     
===========================================
  Files          17       19        +2     
  Lines        4210     3492      -718     
===========================================
- Hits         3481     3360      -121     
+ Misses        729      132      -597     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@harrisonritz

Copy link
Copy Markdown
Collaborator Author

@rsenne ready

Comment thread src/lds/fit_LDS.jl Resolved
Comment thread src/stats/null_models.jl Resolved
Comment thread src/stats/null_models.jl Resolved
Comment thread src/stats/null_models.jl Resolved
Comment thread src/stats/null_models.jl Resolved
Comment thread src/lds/fit_LDS.jl Resolved
Comment thread src/stats/null_models.jl Resolved
Comment thread src/stats/null_models.jl Resolved
Comment thread src/stats/null_models.jl Resolved
Comment thread src/stats/null_models.jl Resolved
@rsenne

rsenne commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

Okay sorry for the long review--but I have more to say here too lol

I think we should redesign the null models to lean on some structs and use standard StatsAPI methods. I think we could do this all in one big PR or we can break this PR down into a few smaller ones. Your call on that! Here is my design thought.

Right now the proposed API is quite similar to how many packages have null models already so i think we should redesign around StatsAPI functions to make this more in line with the current ecosystem.

Concreteky:

  1. Make each baseline a small struct (InterceptNull, VARNull, ...) with fit!(null, data) and loglikelihood(null, data) methods.
  2. Extend StatsAPI.r2(lds, data; null=:intercept) instead of exporting compute_R2.
  3. StatsAPI.nullloglikelihood(lds, data) falls out for free (it's the intercept baseline's plug-in LL)
  4. We should also be able to implement StatsAPI.nobs

Also--sorry for being such a hard ass about comments etc. just trying to keep the style uniform as possible (i have intentions of reformatting many of the current code comments soon)

LMK how all of this sounds!

@harrisonritz

Copy link
Copy Markdown
Collaborator Author

Don't apologize, this is super helpful. I'll take a pass later this week.

harrisonritz added a commit that referenced this pull request Aug 13, 2026
Replaces the `test_null` / `compute_R2` API with a single baseline struct
plus standard StatsAPI methods, per review on #126.

## Design

`AffineNullModel{T,LAG,SHIFT}` is one affine-Gaussian baseline whose two
structural switches are type parameters: `LAG` (autoregressive term
`F y_{t-1}`) and `SHIFT` (input lag). The four baselines are configurations
of that one type rather than four implementations:

  :intercept   y_t ~ N(d, R)
  :inputs      y_t ~ N(d + D v_{t-SHIFT}, R)
  :var         y_1 ~ N(μ₀, R₀);  y_t ~ N(F y_{t-1} + d, R)
  :var_inputs  y_1 ~ N(μ₀, R₀);  y_t ~ N(F y_{t-1} + d + D v_{t-SHIFT}, R)

Fit with `fit!(null, y; inputs)`, score with `loglikelihood(null, y; inputs)`.
On a fitted LDS: `r2(lds, y, variant; null=:intercept)`, `nullloglikelihood`
and `nobs`. `compute_R2` and `test_null` are gone.

## Addressing the review

- Structs + `fit!`/`loglikelihood`: as above.
- `r2` replaces `compute_R2`, and supports all three StatsAPI variants
  (`:CoxSnell` default, `:McFadden`, `:Nagelkerke`), not just Cox-Snell.
- `nullloglikelihood(lds, y)` is the intercept baseline's plug-in LL.
- `nobs(lds, y)` counts scalar observations, `obs_dim * sum(tsteps)`, which
  keeps R² on the same scale as before.
- "Delete `_null_intercept`, it's a special case of `_null_inputs`" and the
  same for `_null_var` vs `_null_var_inputs`: resolved by construction. One
  design-matrix builder, one regression kernel, one plug-in scoring kernel.
- "Doesn't `_null_trial_ll` compute this already?": yes. There is now a
  single `_null_plugin_ll` behind both `loglikelihood` and the MAP objective.
- "Isn't this the same as `_check_inputs` in fit_LDS?": both are deleted.
  `Data(lds, y; ux, uy)` is the single validation site for the LDS path;
  baselines are standalone so they keep a minimal shape check of their own.
- Degenerate/zero-column input matrices: absent inputs canonicalize to
  zero-row matrices, and input-free baselines force `input_dim = 0`, so the
  zero-column `B`/`D` case is inert rather than throwing.
- PosDefException on single-trial data: real bug. `R₀` is estimated from one
  observation per trial, so its scatter is singular whenever
  `ntrials <= obs_dim` — every single-trial dataset. Without an `R₀_prior`
  it now falls back to the innovation covariance `R`, documented and tested.
- `ux_t` vs `ux_{t-1}`: resolved per channel. `:ux` enters lagged, mirroring
  `x_t = A x_{t-1} + b + B ux_{t-1}`; `:uy` contemporaneous, mirroring
  `y_t = C x_t + d + D uy_t`. A lagged input predating the trial is zero,
  mirroring the LDS's input-free `x_1`.
- Symbols over strings: `null`, `null_inputs`, `variant` are all Symbols.
- Comment style: `#=` blocks throughout, verbose headers condensed, and the
  suggested test section comments used verbatim where the test survived.
- "All loglikelihoods should be StatsAPI overloads": done, along with the
  new `nobs` / `nullloglikelihood` / `r2` methods.

## Merge with dev

Merging dev reported no conflicts but broke two things silently:

- dev rewrote `Data` into a ragged vector-of-matrices container, while the
  null models assumed a dense 3-D array throughout. The baselines and their
  tests are rewritten against the new layout, ragged trials included.
- The `loglikelihood(lds, data::Data)` method this branch added to
  `fit_LDS.jl` is now redundant — dev's `loglikelihood(lds, y; ux, uy)`
  already applies `B·ux_{t-1}` and `D·uy_t`, and shares the covariance pass
  across trials. Deleted; `fit_LDS.jl` is identical to dev again. That also
  moots the `cholesky!` and "make this part of the existing function"
  comments on that block.

Incidental: `show.jl` had a local `nobs` shadowing the newly exported name,
renamed to `obs_dim`.

## Still unsure

- Not run. Julia could not be installed in this environment (the network
  policy blocks the download host), so the test suite, JuliaFormatter, JET,
  Aqua and the docs build are all unverified. Formatting and the docs build
  are the likeliest breakages: `checkdocs = :exports` means the new exports
  must resolve, and the api.md entries use explicit method signatures that
  Documenter may or may not match.
- `compute_R2(lds, train, test)` is dropped. Held-out R² is now the two-call
  recipe (fit on train, score test), documented and tested, but that is a
  convenience removal. Easy to restore as a `fit_on=` kwarg if wanted.
- The prior-augmented objective (data LL + IW/MN terms, the old `train_ll`
  that lines up with `elbo!` at the EM fixed point) is internal
  `_null_logmap`, still tested. `loglikelihood` is the plug-in LL only, since
  that is what the name means in StatsAPI. Could be made public.
- PPCA baseline not added — flagged in review as optional.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LoWGorJvqR8yBLouSao7VV

---------

Co-authored-by: Ryan Senne <50930199+rsenne@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: CompatHelper Julia <compathelper_noreply@julialang.org>
Co-authored-by: Claude <noreply@anthropic.com>
@rsenne

rsenne commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

i'm going to rebase/squash the branch because the diff history is corrupted

@rsenne

rsenne commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

i'll also be reviewing your other pr today sorry for the delay!

@harrisonritz

Copy link
Copy Markdown
Collaborator Author

Shit, sorry about the got history.

Not urgent, I'm "on vacation", but appreciate whenever you can take a look at it.

Lmk if it's too sloppy and I'll work through it before your full review.

@github-actions

github-actions Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark Results (Julia v1)

Time benchmarks
main 0c66b02... main / 0c66b02...
GaussianLDS/("smooth", "latent=2", "obs=10", "T=100") 0.22 ± 0.02 ms 0.223 ± 0.03 ms 0.987 ± 0.16
GaussianLDS/("smooth", "latent=2", "obs=10", "T=500") 0.979 ± 0.0075 ms 0.983 ± 0.059 ms 0.996 ± 0.061
GaussianLDS/("smooth", "latent=2", "obs=20", "T=100") 0.237 ± 0.028 ms 0.213 ± 0.028 ms 1.11 ± 0.2
GaussianLDS/("smooth", "latent=2", "obs=20", "T=500") 0.993 ± 0.0057 ms 1 ± 0.066 ms 0.993 ± 0.066
GaussianLDS/("smooth", "latent=2", "obs=5", "T=100") 0.215 ± 0.026 ms 0.213 ± 0.018 ms 1.01 ± 0.15
GaussianLDS/("smooth", "latent=2", "obs=5", "T=500") 0.98 ± 0.037 ms 0.983 ± 0.056 ms 0.997 ± 0.068
GaussianLDS/("smooth", "latent=4", "obs=10", "T=100") 0.408 ± 0.022 ms 0.398 ± 0.017 ms 1.03 ± 0.07
GaussianLDS/("smooth", "latent=4", "obs=10", "T=500") 1.89 ± 0.014 ms 1.9 ± 0.038 ms 0.995 ± 0.021
GaussianLDS/("smooth", "latent=4", "obs=20", "T=100") 0.415 ± 0.027 ms 0.413 ± 0.017 ms 1.01 ± 0.077
GaussianLDS/("smooth", "latent=4", "obs=20", "T=500") 1.96 ± 0.36 ms 1.91 ± 0.17 ms 1.03 ± 0.21
GaussianLDS/("smooth", "latent=4", "obs=5", "T=100") 0.409 ± 0.017 ms 0.403 ± 0.026 ms 1.02 ± 0.078
GaussianLDS/("smooth", "latent=4", "obs=5", "T=500") 1.89 ± 0.016 ms 1.9 ± 0.045 ms 0.996 ± 0.025
GaussianLDS/("smooth", "latent=8", "obs=10", "T=100") 0.937 ± 0.024 ms 0.957 ± 0.0082 ms 0.979 ± 0.026
GaussianLDS/("smooth", "latent=8", "obs=10", "T=500") 6.47 ± 3.1 ms 7.45 ± 2.3 ms 0.869 ± 0.49
GaussianLDS/("smooth", "latent=8", "obs=20", "T=100") 0.963 ± 0.034 ms 1 ± 0.03 ms 0.961 ± 0.045
GaussianLDS/("smooth", "latent=8", "obs=20", "T=500") 5.43 ± 3.3 ms 7.47 ± 1.3 ms 0.727 ± 0.45
PoissonLDS/("smooth", "latent=2", "obs=10", "T=100") 1.14 ± 0.02 ms 0.933 ± 0.0059 ms 1.22 ± 0.023
PoissonLDS/("smooth", "latent=2", "obs=10", "T=500") 5.72 ± 0.023 ms 4.71 ± 0.028 ms 1.21 ± 0.0087
PoissonLDS/("smooth", "latent=2", "obs=5", "T=100") 1.21 ± 0.029 ms 0.967 ± 0.0098 ms 1.25 ± 0.033
PoissonLDS/("smooth", "latent=2", "obs=5", "T=500") 6.63 ± 0.048 ms 5.28 ± 0.052 ms 1.26 ± 0.015
PoissonLDS/("smooth", "latent=4", "obs=10", "T=100") 1.98 ± 0.041 ms 1.67 ± 0.014 ms 1.18 ± 0.026
PoissonLDS/("smooth", "latent=4", "obs=10", "T=500") 10.7 ± 0.08 ms 9.29 ± 0.31 ms 1.15 ± 0.039
PoissonLDS/("smooth", "latent=4", "obs=5", "T=100") 1.57 ± 0.043 ms 1.31 ± 0.015 ms 1.2 ± 0.036
PoissonLDS/("smooth", "latent=4", "obs=5", "T=500") 9.89 ± 0.024 ms 8.31 ± 0.045 ms 1.19 ± 0.0071
time_to_load 0.832 ± 0.0063 s 0.847 ± 0.0064 s 0.982 ± 0.011
Memory benchmarks
main 0c66b02... main / 0c66b02...
GaussianLDS/("smooth", "latent=2", "obs=10", "T=100") 2.08 k allocs: 0.265 MB 2.05 k allocs: 0.235 MB 1.13
GaussianLDS/("smooth", "latent=2", "obs=10", "T=500") 9.3 k allocs: 1.24 MB 9.27 k allocs: 1.09 MB 1.14
GaussianLDS/("smooth", "latent=2", "obs=20", "T=100") 2.09 k allocs: 0.298 MB 2.06 k allocs: 0.259 MB 1.15
GaussianLDS/("smooth", "latent=2", "obs=20", "T=500") 9.31 k allocs: 1.31 MB 9.28 k allocs: 1.11 MB 1.17
GaussianLDS/("smooth", "latent=2", "obs=5", "T=100") 2.08 k allocs: 0.254 MB 2.05 k allocs: 0.227 MB 1.12
GaussianLDS/("smooth", "latent=2", "obs=5", "T=500") 9.3 k allocs: 1.22 MB 9.27 k allocs: 1.08 MB 1.12
GaussianLDS/("smooth", "latent=4", "obs=10", "T=100") 2.09 k allocs: 0.716 MB 2.06 k allocs: 0.626 MB 1.14
GaussianLDS/("smooth", "latent=4", "obs=10", "T=500") 9.3 k allocs: 3.48 MB 9.27 k allocs: 3.03 MB 1.15
GaussianLDS/("smooth", "latent=4", "obs=20", "T=100") 2.1 k allocs: 0.75 MB 2.07 k allocs: 0.652 MB 1.15
GaussianLDS/("smooth", "latent=4", "obs=20", "T=500") 9.31 k allocs: 3.55 MB 9.28 k allocs: 3.06 MB 1.16
GaussianLDS/("smooth", "latent=4", "obs=5", "T=100") 2.09 k allocs: 0.704 MB 2.06 k allocs: 0.618 MB 1.14
GaussianLDS/("smooth", "latent=4", "obs=5", "T=500") 9.3 k allocs: 3.45 MB 9.27 k allocs: 3.02 MB 1.14
GaussianLDS/("smooth", "latent=8", "obs=10", "T=100") 2.09 k allocs: 2.48 MB 2.06 k allocs: 2.16 MB 1.15
GaussianLDS/("smooth", "latent=8", "obs=10", "T=500") 9.3 k allocs: 12.3 MB 9.27 k allocs: 10.7 MB 1.15
GaussianLDS/("smooth", "latent=8", "obs=20", "T=100") 2.1 k allocs: 2.52 MB 2.07 k allocs: 2.19 MB 1.15
GaussianLDS/("smooth", "latent=8", "obs=20", "T=500") 9.31 k allocs: 12.3 MB 9.28 k allocs: 10.7 MB 1.15
PoissonLDS/("smooth", "latent=2", "obs=10", "T=100") 3.32 k allocs: 0.283 MB 2.05 k allocs: 0.234 MB 1.21
PoissonLDS/("smooth", "latent=2", "obs=10", "T=500") 15.3 k allocs: 1.33 MB 9.27 k allocs: 1.09 MB 1.22
PoissonLDS/("smooth", "latent=2", "obs=5", "T=100") 3.53 k allocs: 0.276 MB 2.05 k allocs: 0.228 MB 1.21
PoissonLDS/("smooth", "latent=2", "obs=5", "T=500") 17.4 k allocs: 1.34 MB 9.27 k allocs: 1.09 MB 1.23
PoissonLDS/("smooth", "latent=4", "obs=10", "T=100") 3.54 k allocs: 0.738 MB 2.06 k allocs: 0.626 MB 1.18
PoissonLDS/("smooth", "latent=4", "obs=10", "T=500") 17.4 k allocs: 3.6 MB 9.27 k allocs: 3.03 MB 1.19
PoissonLDS/("smooth", "latent=4", "obs=5", "T=100") 3.33 k allocs: 0.723 MB 2.06 k allocs: 0.618 MB 1.17
PoissonLDS/("smooth", "latent=4", "obs=5", "T=500") 17.4 k allocs: 3.58 MB 9.27 k allocs: 3.03 MB 1.18
time_to_load 0.149 k allocs: 11.2 kB 0.149 k allocs: 11.2 kB 1

@harrisonritz

Copy link
Copy Markdown
Collaborator Author

See how it looks after the rebase -- if it still has way too many irrelevant changes, lmk and I'll just make another PR.

Adds `AffineNullModel{T,LAG,SHIFT}`, a single affine-Gaussian baseline
whose two structural switches are type parameters: `LAG` (autoregressive
term `F y_{t-1}`) and `SHIFT` (input lag). Four baseline variants are
configurations of that one type rather than four implementations:

  :intercept   y_t ~ N(d, R)
  :inputs      y_t ~ N(d + D v_{t-SHIFT}, R)
  :var         y_1 ~ N(μ₀, R₀);  y_t ~ N(F y_{t-1} + d, R)
  :var_inputs  y_1 ~ N(μ₀, R₀);  y_t ~ N(F y_{t-1} + d + D v_{t-SHIFT}, R)

Fit with `fit!(null, y; inputs)`, score with `loglikelihood(null, y; inputs)`.
On a fitted LDS: `r2(lds, y, variant; null=:intercept)`, `nullloglikelihood`,
and `nobs`.

## Design

- `r2` supports all three StatsAPI variants (`:CoxSnell` default, `:McFadden`,
  `:Nagelkerke`), not just Cox-Snell.
- `nullloglikelihood(lds, y)` is the intercept baseline's plug-in LL.
- `nobs(lds, y)` counts scalar observations, `obs_dim * sum(tsteps)`, keeping
  R² on the same scale as before.
- One design-matrix builder, one regression kernel, one plug-in scoring
  kernel (`_null_plugin_ll`) behind both `loglikelihood` and the MAP
  objective — `:intercept`/`:var` are special cases of `:inputs`/`:var_inputs`
  by construction rather than separate implementations.
- Degenerate/zero-column input matrices are inert rather than throwing:
  absent inputs canonicalize to zero-row matrices, and input-free baselines
  force `input_dim = 0`.
- Single-trial data: `R₀` is estimated from one observation per trial, so its
  scatter is singular whenever `ntrials <= obs_dim` (every single-trial
  dataset). Without an `R₀_prior` it falls back to the innovation covariance
  `R`.
- `ux` enters lagged (mirroring `x_t = A x_{t-1} + b + B ux_{t-1}`); `uy`
  contemporaneous (mirroring `y_t = C x_t + d + D uy_t`). A lagged input
  predating the trial is zero, mirroring the LDS's input-free `x_1`.

## Known follow-ups

- `compute_R2(lds, train, test)` is not carried over; held-out R² is the
  two-call recipe (fit on train, score test), documented and tested. Easy to
  restore as a `fit_on=` kwarg if wanted.
- The prior-augmented objective (data LL + IW/MN terms) is internal
  `_null_logmap`, still tested; `loglikelihood` is the plug-in LL only, since
  that's what the name means under StatsAPI. Could be made public.
- PPCA baseline not added.

Co-authored-by: Ryan Senne <50930199+rsenne@users.noreply.github.com>
@rsenne
rsenne force-pushed the feature/null-models branch from 5bcbe5a to 0d376fd Compare August 13, 2026 14:21
@rsenne

rsenne commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

@harrisonritz you'll need to run

git fetch origin
git checkout feature/null-models
git reset --hard origin/feature/null-models

(or upstream if not origin) before pullin/pushing

@harrisonritz

Copy link
Copy Markdown
Collaborator Author

I'll do that for next push. FWIW I think this looks reviewable as is (but no rush)

@rsenne
rsenne self-requested a review August 13, 2026 20:33

@rsenne rsenne left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

overall, loogs, good. A few nits and suggestions. Mostly just suggestions to de-claude speak this. in general i don't like how claude documents things. Has a tendency to bloat the code and also imo it can be somewhat hard to read

Comment thread src/utils/show.jl
if nobs > 4 || nstate > 4
println(io, gap, " size(C) = ($nobs, $nstate)")
if obs_dim > 4 || nstate > 4
println(io, gap, " size(C) = ($obs_dim, $nstate)")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

Comment thread src/stats/null_models.jl
Comment on lines +111 to +113
function AffineNullModel{T}(
baseline::Symbol, obs_dim::Int; input_dim::Int=0, kwargs...
) where {T<:Real}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fdor this covnenience wrapper--we need some logic preventing someone from doing something dumb by mistake. Right now, a user can pass lag in the kwargs. In Julia the later var wins, so if someone did, say:

null = AffineNullModel{Float64}(:intercept, 3; lag=true)
size(null.F) # =(3 , 3)

so basically they'll get a VAR despite requesting an intercept

Comment thread src/stats/null_models.jl
end

isempty(responses) &&
throw(ArgumentError("a VAR baseline needs at least one trial with tsteps ≥ 2"))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this could throw on an intercept only model so we need some more control flow here

Comment thread src/stats/null_models.jl Outdated
Comment on lines +1 to +27
#=============================================================================
Latent-free baseline ("null") models for LDS model comparison.

`AffineNullModel` is one affine-Gaussian baseline whose two structural switches
are type parameters — `LAG`, whether an autoregressive term `F y_{t-1}` is
present, and `SHIFT`, how far the input is lagged — so the four baselines worth
having are configurations of a single type rather than four implementations:

:intercept y_t ~ N(d, R)
:inputs y_t ~ N(d + D v_{t-SHIFT}, R)
:var y_1 ~ N(μ₀, R₀); y_t ~ N(F y_{t-1} + d, R) (t ≥ 2)
:var_inputs y_1 ~ N(μ₀, R₀); y_t ~ N(F y_{t-1} + d + D v_{t-SHIFT}, R) (t ≥ 2)

`SHIFT` follows whichever LDS input channel the baseline stands in for: the
dynamics input enters lagged (`x_t = A x_{t-1} + b + B ux_{t-1}`), the
observation input contemporaneously (`y_t = C x_t + d + D uy_t`). A lagged input
that predates the trial is zero, mirroring the LDS's input-free `x_1`.

The `μ₀`/`R₀` step of the VAR baselines mirrors the LDS's `(x0, P0)` layer, so
every timestep is scored and the baseline stays comparable to the LDS marginal
likelihood term for term.

Baselines are fit with `fit!` and scored with `loglikelihood`; `r2`,
`nullloglikelihood` and `nobs` build on those to score a fitted LDS against a
baseline. Priors are optional and mirror the LDS M-step: an `MNPrior` on the
stacked regression matrix, `IWPrior`s on `R` and `R₀`.
=============================================================================#

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
#=============================================================================
Latent-free baseline ("null") models for LDS model comparison.
`AffineNullModel` is one affine-Gaussian baseline whose two structural switches
are type parameters — `LAG`, whether an autoregressive term `F y_{t-1}` is
present, and `SHIFT`, how far the input is lagged — so the four baselines worth
having are configurations of a single type rather than four implementations:
:intercept y_t ~ N(d, R)
:inputs y_t ~ N(d + D v_{t-SHIFT}, R)
:var y_1 ~ N(μ₀, R₀); y_t ~ N(F y_{t-1} + d, R) (t ≥ 2)
:var_inputs y_1 ~ N(μ₀, R₀); y_t ~ N(F y_{t-1} + d + D v_{t-SHIFT}, R) (t ≥ 2)
`SHIFT` follows whichever LDS input channel the baseline stands in for: the
dynamics input enters lagged (`x_t = A x_{t-1} + b + B ux_{t-1}`), the
observation input contemporaneously (`y_t = C x_t + d + D uy_t`). A lagged input
that predates the trial is zero, mirroring the LDS's input-free `x_1`.
The `μ₀`/`R₀` step of the VAR baselines mirrors the LDS's `(x0, P0)` layer, so
every timestep is scored and the baseline stays comparable to the LDS marginal
likelihood term for term.
Baselines are fit with `fit!` and scored with `loglikelihood`; `r2`,
`nullloglikelihood` and `nobs` build on those to score a fitted LDS against a
baseline. Priors are optional and mirror the LDS M-step: an `MNPrior` on the
stacked regression matrix, `IWPrior`s on `R` and `R₀`.
=============================================================================#
#=============================================================================
Latent-free affine-Gaussian baselines for LDS comparison.
`AffineNullModel{LAG,SHIFT}` covers four configurations:
:intercept y_t ~ N(d, R)
:inputs y_t ~ N(d + D v_{t-SHIFT}, R)
:var y_1 ~ N(μ₀, R₀); y_t ~ N(F y_{t-1} + d, R)
:var_inputs y_1 ~ N(μ₀, R₀); y_t ~ N(F y_{t-1} + d + D v_{t-SHIFT}, R)
Here `LAG` enables the autoregressive term and `SHIFT` matches the corresponding
LDS input timing: lagged for dynamics inputs and contemporaneous for observation
inputs. Pretrial inputs are zero. For VAR models, `(μ₀, R₀)` scores the first
observation analogously to the LDS initial-state layer.
Use `fit!` and `loglikelihood`; `r2`, `nullloglikelihood`, and `nobs` compare a
fitted LDS against a baseline. Optional priors are an `MNPrior` on the stacked
regression matrix and `IWPrior`s on `R` and `R₀`.
=============================================================================#

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this read a little too claude to me

Comment thread src/stats/null_models.jl Outdated
Comment on lines +515 to +527
# Examples
Held-out R² comes from fitting a baseline on one split and scoring another,
which is the same two calls `r2` makes internally:

```julia
null = AffineNullModel{Float64}(:intercept, obs_dim)
fit!(null, y_train)
ll = loglikelihood(lds, y_test)
ll₀ = loglikelihood(null, y_test)
r2_heldout = 1 - exp(2 * (ll₀ - ll) / nobs(lds, y_test))
```

See also [`nullloglikelihood`](@ref), [`nobs`](@ref), [`AffineNullModel`](@ref).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't add examples. I'm not a fan of the doctest interface in Julia and without that we are liable for these to go stale. Can you remove?

Comment thread src/stats/null_models.jl
Comment on lines +350 to +356
"""
loglikelihood(null::AffineNullModel, y; inputs=nothing)

Plug-in log-likelihood of `y` under the fitted baseline — no prior terms, so it
is directly comparable to the LDS marginal `loglikelihood(lds, y)`. Scoring data
other than the fit data gives the held-out log-likelihood.
"""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"""
loglikelihood(null::AffineNullModel, y; inputs=nothing)
Plug-in log-likelihood of `y` under the fitted baseline — no prior terms, so it
is directly comparable to the LDS marginal `loglikelihood(lds, y)`. Scoring data
other than the fit data gives the held-out log-likelihood.
"""
"""
loglikelihood(null::AffineNullModel, y; inputs=nothing)
Plug-in log-likelihood of `y` under the fitted baseline. This excludes prior
terms and is directly comparable to the LDS marginal `loglikelihood(lds, y)`.
Pass held-out data to compute held-out log-likelihood.
"""

Comment thread src/stats/null_models.jl
Comment on lines +439 to +445
"""
nobs(lds::LinearDynamicalSystem, y; ux=nothing, uy=nothing)

Number of scalar observations in `y` — `obs_dim * sum(tsteps)`, summed over
trials. This is the denominator [`r2`](@ref) uses for the Cox–Snell and
Nagelkerke variants, so it is on the same scale as `loglikelihood(lds, y)`.
"""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"""
nobs(lds::LinearDynamicalSystem, y; ux=nothing, uy=nothing)
Number of scalar observations in `y` — `obs_dim * sum(tsteps)`, summed over
trials. This is the denominator [`r2`](@ref) uses for the Cox–Snell and
Nagelkerke variants, so it is on the same scale as `loglikelihood(lds, y)`.
"""
"""
nobs(lds::LinearDynamicalSystem, y; ux=nothing, uy=nothing)
Number of scalar observations in `y`: `obs_dim * sum(tsteps)` across trials.
r2 uses this count in the Cox–Snell and Nagelkerke variants.
"""

Comment thread src/stats/null_models.jl
Comment on lines +454 to +462
"""
nullloglikelihood(lds, y; ux=nothing, uy=nothing, R_prior=lds.obs_model.R_prior)

Plug-in log-likelihood of the intercept baseline `y_t ~ N(d, R)` fit on the same
data — the reference point [`r2`](@ref) measures `lds` against by default.

`R_prior` defaults to the LDS's own observation-noise prior so the baseline's `R`
is regularized exactly as the LDS's is.
"""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"""
nullloglikelihood(lds, y; ux=nothing, uy=nothing, R_prior=lds.obs_model.R_prior)
Plug-in log-likelihood of the intercept baseline `y_t ~ N(d, R)` fit on the same
data — the reference point [`r2`](@ref) measures `lds` against by default.
`R_prior` defaults to the LDS's own observation-noise prior so the baseline's `R`
is regularized exactly as the LDS's is.
"""
"""
nullloglikelihood(lds, y; ux=nothing, uy=nothing, R_prior=lds.obs_model.R_prior)
Plug-in log-likelihood of the intercept baseline `y_t ~ N(d, R)`, fit to the
same data. This is the default reference model for `r2`.
`R_prior` defaults to the LDS observation-noise prior.
"""

Comment thread src/stats/null_models.jl Outdated

See also [`r2`](@ref), [`nullloglikelihood`](@ref).
"""
mutable struct AffineNullModel{T<:Real,LAG,SHIFT}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure this needs three type params. These models in theory have their function run once so not much for the compiler to specialzie on. Soemthing like:

if null.lag control flow would have same effect and no measurable performance hit imo

Comment thread src/stats/null_models.jl Outdated
Comment on lines +358 to +360
trials = _null_trials(y)
tsteps = Int[size(yn, 2) for yn in trials]
v = _null_input_trials(T, inputs, tsteps, null.input_dim)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit but these three lines are copied verbatim in fit! and _null_logmap could make this a helper func

@rsenne

rsenne commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

overall looks good. Some nits and suggestions. Biggest thing is reducing some claude-speak. I tend to find its docs hard to read so i'm on the side of using it less for that

Comment thread src/stats/null_models.jl Outdated
baseline,
obs_dim;
input_dim=size(first(v), 1),
input_shift=shift,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

input_shift = size(first(v),1) > 0 ? shift : 0

this is needed to prevent a degenerate case

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we also need to add tests where input_dim=0

@rsenne

rsenne commented Aug 23, 2026

Copy link
Copy Markdown
Collaborator

Can we also go through again de-claude further? i still think there is a good bit of verbosity here (i do think codex can be good at fixing this if you have access)

rsenne added 2 commits August 23, 2026 20:51
`r2(lds, y; null=:inputs)` threw on an LDS with no inputs on the requested
channel. The baseline got `input_dim=0` but still `input_shift=1`, which the
guard added in #177 rejects. Drop the shift when there is no input block, so an
input baseline on an unused channel collapses to its input-free counterpart
(`:inputs` to `:intercept`, `:var_inputs` to `:var`) instead of throwing.

Tests cover `input_dim=0` on both paths: through `r2` for an LDS with neither
channel populated and for one where only `ux` is, and directly on the baselines,
where the collapse matches the input-free fit parameter for parameter. Both new
tests fail without the fix.

Also another pass over the comments, cutting the design rationale and the
restatements: the constructor and `const` paragraphs in the `AffineNullModel`
docstring, the `fit!` trial-format list that repeats the one above
`_null_trials`, and the blocks on `_null_fit_regression`, `_null_init_cov`,
`_null_logmap` and `r2`.

Formatted with JuliaFormatter 1.0.62 to match the pinned version in
test/Project.toml.
`fit!(null, y; inputs)` threw a bare `SingularException` from `mn_map` whenever
the design's Gram matrix was singular. The case that reaches users is an input
block carrying its own constant row — the documented way to get a bias since the
`B0` removal — which duplicates the intercept every baseline fits. With
`input_shift=0` the two rows are exactly collinear and the fit dies; with
`input_shift=1` the shift zeroes the first column and it survives, so the
failure looks arbitrary from the outside. Too few timesteps for the coefficient
count does the same thing.

`_null_check_design` now factors the matrix `mn_map` is about to invert
(`X X' + Λ` when there is an `MNPrior`, `X X'` otherwise) and throws a
`NumericalStabilityError` naming the coefficient/observation counts, the
constant-row cause, and the three ways out: drop the row, add timesteps, or set
a `W_prior`. The Gram matrix is now formed once and passed to `mn_map` rather
than rebuilt inside the call.

Tests cover the collinear-input block on `:inputs` and `:var_inputs`, the
`input_shift=1` case that stays full rank, an `MNPrior` regularizing the same
design back to full rank, and the fewer-observations-than-coefficients path.
All four throw `SingularException` without the guard.

Also adds the `CHANGELOG.md` entry the repo keeps for every feature: the
`AffineNullModel` baselines and the `r2` / `nullloglikelihood` / `nobs`
StatsAPI surface, both tagged #126.
@rsenne
rsenne force-pushed the feature/null-models branch from 0d4ab1a to 3b3fe09 Compare August 24, 2026 02:24
@rsenne
rsenne merged commit 629f0c4 into dev Aug 24, 2026
5 checks passed
@rsenne
rsenne deleted the feature/null-models branch August 24, 2026 03:19
@rsenne rsenne mentioned this pull request Aug 24, 2026
rsenne added a commit that referenced this pull request Aug 24, 2026
`dev` had two commits we lacked: the null models (#126), which are genuinely
new, and the SLDS input addition (#158). CCN2026 already carries #158's content
via a *different* commit (eca88b6, merged as #160), so the same patch existed
twice under two SHAs — that duplicate is what made the PR conflict.

Resolution:

- src/lds/fit_SLDS.jl, src/utils/validation.jl,
  test/LinearDynamicalSystems/SLDS.jl -> ours. Verified first that dev's delta
  in these three files comes only from #158 (the null-models commit does not
  touch them), and that every function dev adds is already present on our side:
  the 9 input-handling test functions and helpers, `Random.rand`/`smooth`
  methods, and the ux_dim/uy_dim checks in validate_SLDS. Ours is a strict
  superset, being the same content plus #175 and the work on top.
- src/StateSpaceDynamics.jl, test/runtests.jl -> both sides. Git auto-merged
  these correctly, keeping dev's null-model import/include/exports alongside
  our export line and SLDS test entries.
- src/stats/null_models.jl, test/NullModels/NullModels.jl and the CHANGELOG /
  docs/api / show.jl edits -> dev's, unchanged.

One fix on top of the auto-merge: it produced a duplicate "Control inputs
(ux/uy)" testset in runtests.jl, because git could not tell dev's #158 block was
the same one we already had from #160. Removed the copy. Checked that no other
testset or test call was duplicated by the merge — the repeated names that
remain (test_EM, test_smooth, ...) are the pre-existing per-model pattern and
are identical to the pre-merge file.

Verified on the merged tree: SLDS suites 559 passed / 0 failed / 1 broken (the
pre-existing @test_broken on ELBO monotonicity), null models 142/142, and
JuliaFormatter 1.0.62 clean across src/ and test/. The format check was run
against `git archive` of the merged index rather than the working tree, because
core.autocrlf=true makes the local checkout report
src/stats/sufficient_statistics.jl as unformatted on line endings alone; the LF
blob CI sees is clean, and that file is untouched by this merge.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
rsenne added a commit that referenced this pull request Aug 24, 2026
`dev` had two commits we lacked: the null models (#126), which are genuinely
new, and the SLDS input addition (#158). CCN2026 already carries #158's content
via a *different* commit (eca88b6, merged as #160), so the same patch existed
twice under two SHAs — that duplicate is what made the PR conflict.

Resolution:

- src/lds/fit_SLDS.jl, src/utils/validation.jl,
  test/LinearDynamicalSystems/SLDS.jl -> ours. Verified first that dev's delta
  in these three files comes only from #158 (the null-models commit does not
  touch them), and that every function dev adds is already present on our side:
  the 9 input-handling test functions and helpers, `Random.rand`/`smooth`
  methods, and the ux_dim/uy_dim checks in validate_SLDS. Ours is a strict
  superset, being the same content plus #175 and the work on top.
- src/StateSpaceDynamics.jl, test/runtests.jl -> both sides. Git auto-merged
  these correctly, keeping dev's null-model import/include/exports alongside
  our export line and SLDS test entries.
- src/stats/null_models.jl, test/NullModels/NullModels.jl and the CHANGELOG /
  docs/api / show.jl edits -> dev's, unchanged.

One fix on top of the auto-merge: it produced a duplicate "Control inputs
(ux/uy)" testset in runtests.jl, because git could not tell dev's #158 block was
the same one we already had from #160. Removed the copy. Checked that no other
testset or test call was duplicated by the merge — the repeated names that
remain (test_EM, test_smooth, ...) are the pre-existing per-model pattern and
are identical to the pre-merge file.

Verified on the merged tree: SLDS suites 559 passed / 0 failed / 1 broken (the
pre-existing @test_broken on ELBO monotonicity), null models 142/142, and
JuliaFormatter 1.0.62 clean across src/ and test/. The format check was run
against `git archive` of the merged index rather than the working tree, because
core.autocrlf=true makes the local checkout report
src/stats/sufficient_statistics.jl as unformatted on line endings alone; the LF
blob CI sees is clean, and that file is untouched by this merge.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants