Skip to content

feature / depends_on: declare, validate, and read back per-group parameters - #167

Open
harrisonritz wants to merge 7 commits into
claude/split-pr-165-incremental-t8k2s5from
claude/split-pr-165-incremental-t8k2s5-2
Open

harrisonritz wants to merge 7 commits into
claude/split-pr-165-incremental-t8k2s5from
claude/split-pr-165-incremental-t8k2s5-2

Conversation

@harrisonritz

Copy link
Copy Markdown
Collaborator

2 of 5 — splitting #165 into reviewable pieces. Stacked on #166; review that one first (the diff here is only this PR's changes). Base retargets to dev when #166 merges.

This is the declaration side of condition-dependent parameters, with no change to how any model is fitted.

The API

Every AbstractStateModel and AbstractObservationModel gains a depends_on field, default nothing. Set it to a NamedTuple of per-trial label vectors and those parameters are declared to be estimated separately per group of trials, everything else pooled:

session = vcat(fill(:day1, 20), fill(:day2, 15))   # one label per trial
obs.depends_on = (C = session, R = session)        # C, d, D and R per session

group_labels(obs, :C)              # [:day1, :day2]
group_parameter(obs, :C, :day1)    # that session's emission matrix

That is the stitching setup discussed in #98: latent dynamics shared by the animal, emissions specific to the session.

Design

Keys canonicalize to the fit_bool groups, because those parameters are fit jointly as one regression — :A/:b/:B name one group, :C/:d/:D another. So :d is an alias for :C, and naming two aliases of one group with different label vectors is an error.

A cell is a maximal set of trials sharing every parameter — one element of the common refinement of all the label vectors. (Q = condition, C = session) therefore partitions trials by (session, condition) pair. Trials in a cell are governed by a single LinearDynamicalSystem, which is what lets the follow-up run the E-step per cell completely unchanged.

variants holds one model object per parameter-group combination. A parameter that does not vary is shared by reference across every variant, so one M-step write updates all of them; a parameter that does vary gets one array per group, with slot 1 aliasing the base model so model.C keeps its original meaning. A variant's index is a fixed function of its per-group slot indices and is independent of any dataset — which is what lets a later depends_on override re-assign trials without invalidating already-fitted parameters.

Malformed declarations fail at construction. validate_LDS resolves both sub-models' depends_on, so an unknown parameter name, conflicting aliases, or label vectors of unequal length are reported when the model is built rather than at the first fit!.

The interim guard

The grouped E/M-step lands in PRs 3-5. Until then a declared depends_on must not be silently pooled, so _reject_unsupported_dependence makes fit!, smooth, elbo, loglikelihood and rand throw a clear ArgumentError. Each entry point drops that one-line call as its grouped path arrives, so the guard is fully gone by PR 5.

Tests

test/LinearDynamicalSystems/ParameterDependencies.jl — validation (bad names, disagreeing aliases, ragged label vectors, construction-time rejection), override key rules, the trial partition and its nslots/cell_trials/trial_cell, the accessors and the by-reference sharing layout, show, and the guard firing on all three model families.

Follow-ups in this series

  1. Grouped EM for the Gaussian LDS
  2. Grouped EM for the Poisson LDS
  3. Grouped EM for the SLDS

Generated by Claude Code

@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5 branch from 151d870 to d29e5b2 Compare August 13, 2026 23:04
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-2 branch 2 times, most recently from e1212f7 to d8cc83f Compare August 13, 2026 23:33
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5 branch from 63078bd to ae02dff Compare August 14, 2026 11:14
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-2 branch from d8cc83f to 1f33318 Compare August 14, 2026 11:15
claude added 3 commits August 14, 2026 11:35
`_slds_trial_elbo` was split out of `elbo!` with its `slds` argument
declared as `SLDS{T}`, dropping the `S`/`O` parameters the original
signature carried. `SLDS`'s `LDSs` field is a
`Vector{LinearDynamicalSystem{T,S,O}}`, so leaving `S` and `O` free
makes `slds.LDSs[k]` too loose to match `joint_loglikelihood!`, which
requires `S<:GaussianStateModel{T0}`. JET analyses each method against
its own declared signature, so it reported no matching method even
though every call site passes a concrete SLDS.

Declare the helper the way `elbo!` declares itself, and drop the
earlier `convert` on the log-density scratch: it pinned the element
type of `ll`, which was never the argument at fault. The body is now
identical to the loop the helper was extracted from.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
First half of condition-dependent parameters (#165): the declaration side,
with no change to how any model is fitted.

Every `AbstractStateModel` and `AbstractObservationModel` gains a `depends_on`
field (default `nothing`). Setting it to a NamedTuple of per-trial label
vectors declares that the named parameters are to be estimated separately for
each group of trials, while everything else stays pooled:

    obs.depends_on = (C = session, R = session)

That is the stitching setup for combining recording sessions that observe
different neurons in the same animal: latent dynamics shared by the animal,
emission parameters specific to the session.

Keys canonicalize to the same groups `fit_bool` uses, since those parameters
are fit jointly as one regression: :A/:b/:B name one group, :C/:d/:D another.
Labels may be Symbols, integers or strings, and different parameters may use
different label vectors — the trial partition is their common refinement, so a
*cell* is a maximal set of trials sharing every parameter.

Per-group values live in a new `variants` field holding one model object per
parameter-group combination, with non-varying parameters shared by reference
so a single M-step write covers all of them. They are read back with the newly
exported `group_labels` and `group_parameter`. `show` reports the declared
groups, and `validate_LDS` resolves both sub-models' declarations so a
malformed one is reported at construction rather than at the first `fit!`.

The grouped E/M-step that consumes the partition lands in follow-ups. Until it
does, `_reject_unsupported_dependence` makes `fit!`, `smooth`, `elbo`,
`loglikelihood` and `rand` throw on a model that declares `depends_on`, rather
than silently fitting one pooled parameter set; each entry point drops that
call as its grouped path arrives.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
`LinearDynamicalSystem` is a `@kwdef` struct, so the keyword constructor
bypasses `validate_LDS` — the positional `LinearDynamicalSystem(sm, om)` is the
one that validates. The construction test asserted the wrong path and so saw no
exception; point it at the validating constructor, and assert separately that a
keyword-built model is still rejected when `validate_LDS` runs on it. The
CHANGELOG claim is narrowed to match.

The formatter diagnostic is temporary: the package-level check returns only a
Bool, so a failure names no file. Removed once it has reported.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5 branch from ae02dff to dec54f1 Compare August 14, 2026 11:35
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-2 branch from 1f33318 to 57a9eb8 Compare August 14, 2026 11:35
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5 branch from dec54f1 to 80c06d4 Compare August 14, 2026 11:59
harrisonritz and others added 2 commits August 22, 2026 17:24
# Conflicts:
#	src/lds/fit_SLDS.jl
Runs JuliaFormatter v1.0.62 (the version test/Project.toml pins, blue style
with always_use_return) over the tree, so the "Code Formatting" test passes.
Whitespace only, no logic changes.

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

codecov Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.19355% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.00%. Comparing base (a293826) to head (7f928eb).

Files with missing lines Patch % Lines
src/lds/parameter_groups.jl 93.81% 17 Missing ⚠️
src/utils/show.jl 94.73% 1 Missing ⚠️
Additional details and impacted files
@@                            Coverage Diff                             @@
##           claude/split-pr-165-incremental-t8k2s5     #167      +/-   ##
==========================================================================
- Coverage                                   96.16%   96.00%   -0.17%     
==========================================================================
  Files                                          18       19       +1     
  Lines                                        3342     3651     +309     
==========================================================================
+ Hits                                         3214     3505     +291     
- Misses                                        128      146      +18     

☔ 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 marked this pull request as ready for review August 23, 2026 16:32
`[A b B]` and `[C d D]` are each fit as one regression, so grouping any member
groups them all. `(C = session,)` therefore made `d` and `D` session-dependent
too — which is the right behaviour but the wrong thing for that line to look
like, and nothing said so. Naming one member is now an error that lists the
group, what is missing, and the complete form:

    depends_on = (C = session,)
    ERROR: ArgumentError: depends_on: `:C` names part of `[C d]`, which is fit
    jointly as one regression — grouping one member groups them all. Say so
    explicitly by naming every member: `(C = ..., d = ...)`. Missing `:d`.

`B` and `D` are zero-column when the model takes no inputs, so there is nothing
to group and they are not required; give the model inputs and they join the
group. `:x0`, `:P0`, `:Q` and `:R` are groups of one and stand alone.

A call-site override is a `depends_on` like any other and re-labels the whole
group, so it carries the same requirement.

The canonicalization itself is unchanged — a member still resolves to its
group; the check runs first so that resolution is never reached on a partial
naming. Existing declarations move from `(C = s, R = s)` to
`(C = s, d = s, R = s)`.

Ancillary parameter dependencies 60 -> 77 assertions.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-2 branch from 56b1456 to 376f516 Compare August 23, 2026 17:11
The narrative belongs in the docstrings and the manual, not inline. The file
header drops the prose and keeps the key-to-group table and the completeness
rule; the rest lose their motivation paragraphs and keep the technical reason
they exist. The `_slot_arrays` note moves from a section banner onto the
function it describes.

87 comment lines out, 35 back.

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

This branch has not been deployed

No deployments
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