Repository navigation
Feature/null models - #126
Conversation
There was a problem hiding this comment.
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_nullandcompute_R2(newsrc/stats/null_models.jl) and exports them from the main module. - Adds an inputs-aware
loglikelihood(lds, data::Data)for Gaussian LDS that accounts forB·uxandD·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.
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
|
@rsenne ready |
|
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:
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! |
|
Don't apologize, this is super helpful. I'll take a pass later this week. |
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>
|
i'm going to rebase/squash the branch because the diff history is corrupted |
|
i'll also be reviewing your other pr today sorry for the delay! |
|
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. |
Benchmark Results (Julia v1)Time benchmarks
Memory benchmarks
|
|
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>
5bcbe5a to
0d376fd
Compare
|
@harrisonritz you'll need to run (or upstream if not origin) before pullin/pushing |
|
I'll do that for next push. FWIW I think this looks reviewable as is (but no rush) |
rsenne
left a comment
There was a problem hiding this comment.
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
| 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)") |
| function AffineNullModel{T}( | ||
| baseline::Symbol, obs_dim::Int; input_dim::Int=0, kwargs... | ||
| ) where {T<:Real} |
There was a problem hiding this comment.
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
| end | ||
|
|
||
| isempty(responses) && | ||
| throw(ArgumentError("a VAR baseline needs at least one trial with tsteps ≥ 2")) |
There was a problem hiding this comment.
this could throw on an intercept only model so we need some more control flow here
| #============================================================================= | ||
| 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₀`. | ||
| =============================================================================# |
There was a problem hiding this comment.
| #============================================================================= | |
| 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₀`. | |
| =============================================================================# |
There was a problem hiding this comment.
this read a little too claude to me
| # 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). |
There was a problem hiding this comment.
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?
| """ | ||
| 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. | ||
| """ |
There was a problem hiding this comment.
| """ | |
| 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. | |
| """ |
| """ | ||
| 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)`. | ||
| """ |
There was a problem hiding this comment.
| """ | |
| 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. | |
| """ |
| """ | ||
| 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. | ||
| """ |
There was a problem hiding this comment.
| """ | |
| 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. | |
| """ |
|
|
||
| See also [`r2`](@ref), [`nullloglikelihood`](@ref). | ||
| """ | ||
| mutable struct AffineNullModel{T<:Real,LAG,SHIFT} |
There was a problem hiding this comment.
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
| trials = _null_trials(y) | ||
| tsteps = Int[size(yn, 2) for yn in trials] | ||
| v = _null_input_trials(T, inputs, tsteps, null.input_dim) |
There was a problem hiding this comment.
nit but these three lines are copied verbatim in fit! and _null_logmap could make this a helper func
|
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 |
| baseline, | ||
| obs_dim; | ||
| input_dim=size(first(v), 1), | ||
| input_shift=shift, |
There was a problem hiding this comment.
input_shift = size(first(v),1) > 0 ? shift : 0
this is needed to prevent a degenerate case
There was a problem hiding this comment.
we also need to add tests where input_dim=0
|
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) |
`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.
0d4ab1a to
3b3fe09
Compare
`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>
`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.
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 structuralswitches (
lag,input_shift) areconstfields, so the four named variantsare configurations of one type rather than four implementations:
:intercepty_t ~ N(d, R):inputsy_t ~ N(d + D v_{t-shift}, R):vary_1 ~ N(μ₀, R₀);y_t ~ N(F y_{t-1} + d, R):var_inputsy_1 ~ N(μ₀, R₀);y_t ~ N(F y_{t-1} + d + D v_{t-shift}, R)input_shiftmatches the LDS input timing:1for dynamics inputs (ux, whichact on
x_{t-1}),0for observation inputs (uy). Fit withfit!(null, y; inputs)and score withloglikelihood(null, y; inputs)— theplug-in log-likelihood, so passing held-out data gives a held-out score. An
optional
MNPrioron the stacked matrix[F d D]andIWPriors onR/R₀mirror the LDS M-step.
One design-matrix builder, one regression kernel and one scoring kernel serve
all four:
:intercept/:varare the zero-column-Dspecial cases of:inputs/:var_inputsby construction. Degenerate inputs are inert ratherthan 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 StatsBasepseudo-R² variants (
:CoxSnelldefault,: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 liveon.
The baseline inherits the LDS's
R_priorby default, so both estimateRunderthe same IW prior. Gaussian LDS only: a Poisson LDS has no tractable marginal
and an
SLDSis a different type, so both raise aMethodErrorby design.Errors
A rank-deficient design throws a
NumericalStabilityErrornaming the causerather than a bare
SingularException. The case that reaches users is an inputblock carrying its own constant row, which duplicates the intercept every
baseline fits.
Tests
30 test functions in
test/NullModels/NullModels.jl(142 assertions), checkingagainst 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
r2variant formulas, and the error paths.