Skip to content

Address null-model review: trim docs, drop type params, add misuse guards - #177

Merged
harrisonritz merged 1 commit into
feature/null-modelsfrom
claude/gracious-noether-958i6i
Aug 23, 2026
Merged

harrisonritz merged 1 commit into
feature/null-modelsfrom
claude/gracious-noether-958i6i

Conversation

@harrisonritz

Copy link
Copy Markdown
Collaborator

Follow-up to @rsenne's review on #126. Merges into feature/null-models so #126 picks it up.

Docs and comments

  • Module header, the AffineNullModel docstring, and the loglikelihood / nobs / nullloglikelihood docstrings replaced with the shorter versions from the review, adapted where the type parameters went away.
  • Dropped the code examples. The held-out R² recipe is now one sentence of prose in r2, so there's nothing to go stale.
  • Trimmed the remaining internal block comments.

Structure

  • AffineNullModel{T,LAG,SHIFT} → AffineNullModel{T}, with lag and input_shift as fields and if null.lag control flow. These models fit once, so there was nothing worth specializing on.
  • The structural fields (obs_dim, input_dim, lag, input_shift) are const, so a fitted model can't be desynced from the shapes of F / μ₀ / R₀.
  • The normalize-y-and-inputs preamble that was repeated verbatim in fit!, loglikelihood and _null_logmap is now _null_prepare.

Misuse guards

  • The named-baseline constructor rejects lag, and rejects input_dim / input_shift on :intercept and :var, rather than letting a later keyword silently win. AffineNullModel{Float64}(:intercept, 3; lag=true) no longer returns a VAR.
  • input_shift without an input block, and R₀_prior without lag, both throw.
  • Prior shapes are checked against the regression the baseline will actually fit, instead of failing deep inside BLAS.
  • y is checked against the model's own obs_dim and element type before fitting, and empty trial lists and zero-length trials are rejected. Previously a 5-row y on a 3-dim baseline fit silently wrong, and a Float32/Float64 mix produced an opaque MethodError.
  • _null_design reports the empty-trial-list and all-trials-length-1 cases separately, so an intercept baseline no longer hits a VAR-specific error message.

Tests

  • Coverage for each new guard; removed the assertions that documented the old silently-forced input_dim.
  • test_null_var_recovers_true_F was already failing on 0d376fd (verified against that commit): null.F ≈ F_true atol=5e-2 landed at norm 0.053. Raised ntrials 8 → 24 rather than loosening the tolerance.

Full suite green: 1458/1458, including Aqua and all 116 null-model tests.

Deferred

Left out per discussion, happy to open issues: a PPCA baseline, and a Data variant for the null models.

🤖 Generated with Claude Code

https://claude.ai/code/session_0137H67bgNDdkbJ6WrLgUfUS


Generated by Claude Code

Docs and comments
- Replace the module header, the `AffineNullModel` docstring, and the
  `loglikelihood` / `nobs` / `nullloglikelihood` docstrings with the shorter
  versions from review.
- Drop the code examples from the docstrings; the held-out R2 recipe is one
  sentence of prose instead, so there is nothing to go stale.
- Trim the remaining internal block comments.

Structure
- `AffineNullModel{T,LAG,SHIFT}` becomes `AffineNullModel{T}` with `lag` and
  `input_shift` as fields and `if null.lag` control flow. These models fit once,
  so there was nothing worth specializing on.
- The structural fields (`obs_dim`, `input_dim`, `lag`, `input_shift`) are
  `const`, so a fitted model cannot be desynced from its parameter shapes.
- Fold the repeated normalize-y-and-inputs preamble in `fit!`, `loglikelihood`
  and `_null_logmap` into `_null_prepare`.

Misuse guards
- The named-baseline constructor rejects `lag`, and rejects `input_dim` /
  `input_shift` on `:intercept` and `:var`, instead of letting a later keyword
  silently win. `AffineNullModel{T}(:intercept, 3; lag=true)` no longer returns
  a VAR.
- Reject `input_shift` without an input block, and `R0_prior` without `lag`.
- Check prior shapes against the regression the baseline will actually fit.
- Check `y` against the model's own `obs_dim` and element type, and reject
  empty trial lists and zero-length trials, before fitting.
- `_null_design` reports the empty-trial-list and all-trials-length-1 cases
  separately, so an intercept baseline no longer hits a VAR-specific message.

Tests
- Cover each new guard; drop the assertions that documented the old
  silently-forced `input_dim`.
- More trials in the VAR(1) recovery test, which was failing marginally
  against its own tolerance.

Co-authored-by: Ryan Senne <50930199+rsenne@users.noreply.github.com>

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

codecov Bot commented Aug 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.92308% with 2 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (feature/null-models@0d376fd). Learn more about missing BASE report.

Files with missing lines Patch % Lines
src/stats/null_models.jl 96.92% 2 Missing ⚠️
Additional details and impacted files
@@                  Coverage Diff                   @@
##             feature/null-models     #177   +/-   ##
======================================================
  Coverage                       ?   96.21%           
======================================================
  Files                          ?       19           
  Lines                          ?     3485           
  Branches                       ?        0           
======================================================
  Hits                           ?     3353           
  Misses                         ?      132           
  Partials                       ?        0           

☔ 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
harrisonritz merged commit 127d5ea into feature/null-models Aug 23, 2026
6 checks passed
harrisonritz pushed a commit that referenced this pull request Aug 23, 2026
`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.

Co-authored-by: Ryan Senne <50930199+rsenne@users.noreply.github.com>

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0137H67bgNDdkbJ6WrLgUfUS
rsenne added a commit that referenced this pull request Aug 24, 2026
`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.
rsenne added a commit that referenced this pull request Aug 24, 2026
* Redesign null models around structs and StatsAPI methods

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>

* Address review: trim null-model docs, drop type params, add guards (#177)

* Fix degenerate input baselines, trim comments further

`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.

* Name the rank-deficient null design, add changelog entry

`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.

* Trim null-model prose

* format

---------

Co-authored-by: Ryan Senne <50930199+rsenne@users.noreply.github.com>
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.

2 participants