diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c144913..aa3ebce6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- Ancillary parameter dependencies, declaration side: every + `AbstractStateModel` and `AbstractObservationModel` now carries a + `depends_on` field (default `nothing`). Setting it to a `NamedTuple` of + per-trial label vectors — e.g. `obs_model.depends_on = (C = session, d = + session, R = session)` — declares that those parameters are to be estimated separately for + each group of trials, while everything else stays pooled. This is the + "stitching" setup for combining recording sessions that observe different + neurons in the same animal: shared latent dynamics, session-specific + emissions + * Keys are grouped the same way `fit_bool` groups them, since those + parameters are fit jointly as one regression — `[A b B]` is one group and + `[C d D]` another. Grouping any member groups them all, so a declaration + has to name **every** member of a group it touches: `(C = s, d = s)`, not + `(C = s,)`. `B` and `D` are zero-column when the model takes no inputs and + are then not part of the group; give the model inputs and they must be + named too. `:x0`, `:P0`, `:Q` and `:R` are groups of one. Labels may be + `Symbol`s, integers or strings. Different groups may use different label + vectors; the trial partition is their common refinement + * A malformed declaration (unknown parameter name, a group named only in + part, members of one group carrying different labels, label vectors of + unequal length) is rejected by + `validate_LDS` — so by the positional `LinearDynamicalSystem(state_model, + obs_model)` constructor, not at the first `fit!` + * 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 new exported `group_labels(model, name)` and + `group_parameter(model, name, label)` + * `show` reports the declared groups for a model that has any + * **Not yet honoured by fitting.** The grouped E/M-step lands in a follow-up; + until it does, `fit!`, `smooth`, `elbo`, `loglikelihood` and `rand` throw + an `ArgumentError` on a model that declares `depends_on` rather than + silently fitting one pooled parameter set - Public allocating `elbo(model, y; ...)` for all three models (Gaussian LDS with `ux`/`uy` keywords, Poisson LDS with Newton-smoother keywords, SLDS with an `rng` keyword since its E-step consumes a posterior sample). Runs diff --git a/docs/src/api.md b/docs/src/api.md index 9c296a91..940e802d 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -39,6 +39,13 @@ MNPrior x0_mean_prior ``` +## Ancillary parameter dependencies + +```@docs +group_labels +group_parameter +``` + ## Sampling ```@docs; canonical = false diff --git a/src/StateSpaceDynamics.jl b/src/StateSpaceDynamics.jl index 592f7b48..1ef607b5 100644 --- a/src/StateSpaceDynamics.jl +++ b/src/StateSpaceDynamics.jl @@ -33,6 +33,7 @@ include("stats/priors.jl") # Model definitions + inference-state containers. include("lds/types.jl") # abstract types, model structs, SLDS include("lds/workspaces.jl") # FilterSmooth / SufficientStatistics / workspaces +include("lds/parameter_groups.jl") # `depends_on` -> per-group parameter variants include("utils/show.jl") include("utils/validation.jl") @@ -65,6 +66,9 @@ export GaussianStateModel, GaussianObservationModel, PoissonObservationModel export IWPrior, MNPrior, x0_mean_prior export CovUpdateCache +# Ancillary parameter dependencies (`depends_on`) +export group_labels, group_parameter + # Utilities export block_tridgm export valid_Σ, gaussian_entropy diff --git a/src/lds/fit_LDS.jl b/src/lds/fit_LDS.jl index d7ccb1df..3133169b 100644 --- a/src/lds/fit_LDS.jl +++ b/src/lds/fit_LDS.jl @@ -123,6 +123,7 @@ function smooth( ux=nothing, uy=nothing, ) where {T<:Real,S<:GaussianStateModel{T},O<:GaussianObservationModel{T}} + _reject_unsupported_dependence(lds) data = Data(lds, y; ux=ux, uy=uy) tfs = _smooth_data(lds, data) return _collect_smooth_output(tfs, y) @@ -773,6 +774,7 @@ function elbo( ux=nothing, uy=nothing, ) where {T<:Real,S<:GaussianStateModel{T},O<:GaussianObservationModel{T}} + _reject_unsupported_dependence(lds) data = Data(lds, y; ux=ux, uy=uy) tfs = initialize_FilterSmooth(lds, data.tsteps)::TrialFilterSmooth{T} npool = min(Threads.maxthreadid(), length(data.y)) @@ -849,6 +851,7 @@ function fit!( ux=nothing, uy=nothing, ) where {T<:Real,S<:GaussianStateModel{T},O<:GaussianObservationModel{T}} + _reject_unsupported_dependence(lds) data = Data(lds, y; ux=ux, uy=uy) return _fit_tridiag!(lds, data; max_iter=max_iter, tol=tol, progress=progress) end @@ -1098,6 +1101,7 @@ function StatsAPI.loglikelihood( ux=nothing, uy=nothing, ) where {T<:Real,SM<:GaussianStateModel{T},OM<:GaussianObservationModel{T}} + _reject_unsupported_dependence(lds) data = Data(lds, y; ux=ux, uy=uy) S_chol, K = _filter_cov_pass(lds, maximum(data.tsteps)) diff --git a/src/lds/fit_PLDS.jl b/src/lds/fit_PLDS.jl index 6f952371..eb5bc424 100644 --- a/src/lds/fit_PLDS.jl +++ b/src/lds/fit_PLDS.jl @@ -760,6 +760,7 @@ function elbo( newton_max_iter::Int=20, newton_tol::Float64=1e-6, ) where {T<:Real,S<:GaussianStateModel{T},O<:PoissonObservationModel{T}} + _reject_unsupported_dependence(plds) data = Data(plds, y; ux=ux, uy=uy) tfs = initialize_FilterSmooth(plds, data.tsteps)::TrialFilterSmooth{T} npool = min(Threads.maxthreadid(), length(data.y)) @@ -806,6 +807,7 @@ function smooth( ux=nothing, uy=nothing, ) where {T<:Real,S<:GaussianStateModel{T},O<:PoissonObservationModel{T}} + _reject_unsupported_dependence(plds) data = Data(plds, y; ux=ux, uy=uy) tfs = initialize_FilterSmooth(plds, data.tsteps)::TrialFilterSmooth{T} # Cap the pool at the trial count — workspaces beyond ntrials are never @@ -862,6 +864,7 @@ function fit!( newton_max_iter::Int=20, newton_tol::Float64=1e-6, ) where {T<:Real,S<:GaussianStateModel{T},O<:PoissonObservationModel{T}} + _reject_unsupported_dependence(plds) data = Data(plds, y; ux=ux, uy=uy) T_max = maximum(data.tsteps) diff --git a/src/lds/fit_SLDS.jl b/src/lds/fit_SLDS.jl index ecd740cc..7813a7ce 100644 --- a/src/lds/fit_SLDS.jl +++ b/src/lds/fit_SLDS.jl @@ -71,6 +71,7 @@ function Random.rand( ux::Union{Nothing,AbstractMatrix{T}}=nothing, uy::Union{Nothing,AbstractMatrix{T}}=nothing, ) where {T<:Real,S<:AbstractStateModel,O<:AbstractObservationModel} + _reject_unsupported_dependence(slds) lds1 = slds.LDSs[1] latent_dim = lds1.latent_dim obs_dim = lds1.obs_dim @@ -110,6 +111,7 @@ function Random.rand( ux::Union{Nothing,AbstractVector{<:AbstractMatrix{T}}}=nothing, uy::Union{Nothing,AbstractVector{<:AbstractMatrix{T}}}=nothing, ) where {T<:Real,S<:AbstractStateModel,O<:AbstractObservationModel} + _reject_unsupported_dependence(slds) lds1 = slds.LDSs[1] latent_dim = lds1.latent_dim obs_dim = lds1.obs_dim @@ -895,9 +897,11 @@ function _slds_trial_elbo( trial_elbo = zero(T) x_smooth_trial = fs.x_smooth + # Per-regime log-density scratch, built once rather than per regime. + ll = view(slds_ws.ll_tmp, 1:Tsteps)::AbstractVector{T} + # E_q[log p(y, x | z)], plug-in at the posterior mean, weighted by γ. for k in 1:K - ll = view(slds_ws.ll_tmp, 1:Tsteps)::AbstractVector{T} joint_loglikelihood!( ll, slds_ws, @@ -1062,6 +1066,7 @@ function elbo( uy=nothing, rng::AbstractRNG=Random.default_rng(), ) where {T<:Real,S<:AbstractStateModel,O<:AbstractObservationModel} + _reject_unsupported_dependence(slds) # `Data` centralizes shape validation and canonicalizes the three # observation/input forms (regime dims are uniform, so validating against # LDSs[1] covers all regimes). Absent ux/uy become zero-row matrices. @@ -1284,6 +1289,7 @@ function fit!( progress::Bool=true, rng::AbstractRNG=Random.default_rng(), ) where {T<:Real,S<:AbstractStateModel,O<:AbstractObservationModel} + _reject_unsupported_dependence(slds) #= `Data` centralizes shape validation and canonicalizes the three observation/input forms (regime dims are uniform, so validating against diff --git a/src/lds/parameter_groups.jl b/src/lds/parameter_groups.jl new file mode 100644 index 00000000..6b33edeb --- /dev/null +++ b/src/lds/parameter_groups.jl @@ -0,0 +1,714 @@ +#============================================================================= +Ancillary parameter dependencies (`depends_on`) + +A `NamedTuple` of per-trial label vectors declares that the named parameters +are estimated separately for each group of trials. Keys map to the groups +`fit_bool` uses, since those parameters are fit jointly as one regression: + + :x0 -> initial state mean (fit_bool[1]) + :P0 -> initial state cov (fit_bool[2]) + :A, :b, :B -> dynamics [A b B] (fit_bool[3]) + :Q -> process noise (fit_bool[4]) + :C, :d, :D -> emission [C d D] (fit_bool[5]) + :R -> observation noise (fit_bool[6], Gaussian only) + +Grouping one member of a group groups them all, so a `depends_on` must name +every member the model carries. `B`/`D` are zero-column, and not part of the +group, when the model takes no inputs. + +A *cell* is a maximal set of trials sharing every parameter — one element of +the common refinement of the label vectors — and is governed by a single +`LinearDynamicalSystem`, so the E-step runs on it unchanged. + +This file is the declaration side: validation, resolution into per-parameter +versions, `variants` storage, and the trial partition. +=============================================================================# + +#= +Any model carrying a `depends_on` field. Named rather than untyped so inference +union-splits over the three concrete model types. +=# +const DependentModel = Union{AbstractStateModel,AbstractObservationModel} + +# Parameter-group ordinals; identical to the `fit_bool` layout, and the index +# into a `ParameterGrouping`'s `nslots` / `cell_slot`. +const _G_X0 = 1 +const _G_P0 = 2 +const _G_AB = 3 +const _G_Q = 4 +const _G_CD = 5 +const _G_R = 6 + +# Canonical group names, ordered to match `fit_bool`. State-model groups occupy +# `fit_bool` slots 1:4 and observation-model groups slots 5:6 (5:5 for Poisson). +_group_names(::GaussianStateModel) = (:x0, :P0, :A, :Q) +_group_names(::GaussianObservationModel) = (:C, :R) +_group_names(::PoissonObservationModel) = (:C,) + +#= +Map a member to its group; completeness is checked by +`_check_group_naming_complete`. `_try_canonical_param` returns `nothing` for a +name the model does not own, since one `depends_on` is resolved against both +sub-models and each must ignore the other's keys. +=# +function _try_canonical_param(::GaussianStateModel, name::Symbol) + name in (:A, :b, :B) && return :A + name in (:x0, :P0, :Q) && return name + return nothing +end + +function _try_canonical_param(::GaussianObservationModel, name::Symbol) + name in (:C, :d, :D) && return :C + name === :R && return :R + return nothing +end + +function _try_canonical_param(::PoissonObservationModel, name::Symbol) + name in (:C, :d, :D) && return :C + return nothing +end + +_valid_param_names(::GaussianStateModel) = ":x0, :P0, :A, :b, :B, :Q" +_valid_param_names(::GaussianObservationModel) = ":C, :d, :D, :R" +function _valid_param_names(::PoissonObservationModel) + return ":C, :d, :D (a Poisson emission has no noise covariance)" +end + +""" + _group_members(model, canonical) -> Tuple{Vararg{Symbol}} + +The parameters the group `canonical` covers, restricted to the ones this model +actually carries. `B` and `D` default to zero-column matrices when the model +takes no inputs; there is nothing to group there, so they are left out. +""" +_group_members(m::GaussianStateModel, c::Symbol) = + c === :A ? (size(m.B, 2) > 0 ? (:A, :b, :B) : (:A, :b)) : (c,) +function _group_members(m::GaussianObservationModel, c::Symbol) + return c === :C ? (size(m.D, 2) > 0 ? (:C, :d, :D) : (:C, :d)) : (c,) +end +function _group_members(m::PoissonObservationModel, c::Symbol) + return c === :C ? (size(m.D, 2) > 0 ? (:C, :d, :D) : (:C, :d)) : (c,) +end + +""" + _check_group_naming_complete(model, spec, what) + +`[A b B]` and `[C d D]` are each fit as one regression, so grouping any member +groups them all. Naming one and leaving the others out reads as though only +that one varies, which is the opposite of what happens — so it is rejected +rather than quietly widened. Name every member the model carries. + +Keys this model does not own are skipped: one `depends_on` is resolved against +both sub-models, so each has to ignore the other's. +""" +function _check_group_naming_complete( + model::DependentModel, spec::NamedTuple, what::AbstractString +) + named = Dict{Symbol,Vector{Symbol}}() + for key in keys(spec) + canonical = _try_canonical_param(model, key) + canonical === nothing && continue + push!(get!(named, canonical, Symbol[]), key) + end + for canonical in sort!(collect(keys(named))) + used = named[canonical] + members = _group_members(model, canonical) + absent = [m for m in members if !(m in used)] + isempty(absent) && continue + given = join(("`:$k`" for k in used), ", ") + want = join(("$m = ..." for m in members), ", ") + throw( + ArgumentError( + "$what: $given names part of `[$(join(members, " "))]`, which is fit " * + "jointly as one regression — grouping one member groups them all. " * + "Say so explicitly by naming every member: `($want)`. " * + "Missing $(join(("`:$m`" for m in absent), ", ")).", + ), + ) + end + return nothing +end + +function _canonical_param(model::DependentModel, name::Symbol) + canonical = _try_canonical_param(model, name) + canonical === nothing && throw( + ArgumentError( + "depends_on: `:$name` is not a parameter of a $(nameof(typeof(model))); " * + "valid names are $(_valid_param_names(model))", + ), + ) + return canonical +end + +""" + ParameterDependence + +**Internal.** Resolved, model-intrinsic form of a model's `depends_on`: for each +of the model's parameter groups, whether it varies, the ordered list of distinct +labels, and the per-trial labels as supplied. + +`nslots[g]` is `length(labels[g])` for a varying group and `1` otherwise, so a +model's `variants` vector always has `prod(nslots)` entries and a variant's index +is a fixed function of its per-group slot indices — independent of any dataset, +which is what lets a `depends_on` override re-assign trials without invalidating +already-fitted parameters. +""" +struct ParameterDependence + names::Vector{Symbol} + varies::Vector{Bool} + labels::Vector{Vector{Any}} + trial_labels::Vector{Vector{Any}} + nslots::Vector{Int} +end + +_any_varies(dep::ParameterDependence) = any(dep.varies) + +function _same_labels(a::Vector{Any}, b::Vector{Any}) + return length(a) == length(b) && all(isequal(a[i], b[i]) for i in eachindex(a)) +end + +""" + _resolve_dependence(model) -> ParameterDependence + +Validate `model.depends_on` and resolve it against the model's parameter groups. +Throws `ArgumentError` on unknown parameter names or on aliases of one group +carrying different label vectors, and `DimensionMismatchError` on label vectors +of unequal length. +""" +function _resolve_dependence(model::DependentModel) + names = collect(Symbol, _group_names(model)) + ngroups = length(names) + varies = fill(false, ngroups) + labels = [Any[] for _ in 1:ngroups] + trial_labels = [Any[] for _ in 1:ngroups] + nslots = fill(1, ngroups) + dep = ParameterDependence(names, varies, labels, trial_labels, nslots) + + spec = model.depends_on + spec === nothing && return dep + _check_group_naming_complete(model, spec, "depends_on") + + # First key to claim each group, so a conflicting alias can name both. + claimed = Vector{Symbol}(undef, ngroups) + for key in keys(spec) + canonical = _canonical_param(model, key) + g = findfirst(isequal(canonical), names)::Int + supplied = getproperty(spec, key) + supplied isa AbstractVector || throw( + ArgumentError( + "depends_on[:$key] must be a vector with one label per trial, " * + "got a $(typeof(supplied))", + ), + ) + isempty(supplied) && + throw(ArgumentError("depends_on[:$key] is empty; expected one label per trial")) + current = collect(Any, supplied) + if varies[g] + _same_labels(current, trial_labels[g]) || throw( + ArgumentError( + "depends_on: `:$key` and `:$(claimed[g])` name the same parameter " * + "group (`:$canonical`, fit jointly as one regression) but were " * + "given different label vectors; supply one label vector per group", + ), + ) + continue + end + varies[g] = true + claimed[g] = key + trial_labels[g] = current + labels[g] = collect(Any, unique(current)) + nslots[g] = length(labels[g]) + end + + ntrials = 0 + for g in 1:ngroups + varies[g] || continue + if ntrials == 0 + ntrials = length(trial_labels[g]) + elseif length(trial_labels[g]) != ntrials + throw( + DimensionMismatchError( + "depends_on[:$(names[g])] length", ntrials, length(trial_labels[g]) + ), + ) + end + end + + return dep +end + +#= +Mixed-radix (column-major) variant index from per-group slots, and its inverse. +Written out so `nslots` never has to be splatted into a tuple. +=# +function _variant_index(nslots::AbstractVector{Int}, slots::AbstractVector{Int}) + idx = 0 + for g in length(nslots):-1:1 + idx = idx * nslots[g] + (slots[g] - 1) + end + return idx + 1 +end + +function _variant_slots(nslots::AbstractVector{Int}, index::Int) + slots = Vector{Int}(undef, length(nslots)) + rest = index - 1 + for g in eachindex(nslots) + slots[g] = rest % nslots[g] + 1 + rest = rest ÷ nslots[g] + end + return slots +end + +""" + _slot_of(dep, g, label) -> Int + +Slot index of `label` within parameter group `g`. Throws when the label was not +present in the label vector the model was built with — an override may +re-assign trials to known groups but not introduce new parameter sets. +""" +function _slot_of(dep::ParameterDependence, g::Int, label) + dep.varies[g] || return 1 + slot = findfirst(isequal(label), dep.labels[g]) + slot === nothing && throw( + ArgumentError( + "depends_on: label $(repr(label)) is not a known group of parameter " * + "`:$(dep.names[g])` (known: $(join(map(repr, dep.labels[g]), ", "))). " * + "An override may only re-assign trials to existing groups.", + ), + ) + return slot::Int +end + +""" + _trial_labels_for(dep, g, model, override) -> Vector{Any} + +Per-trial labels for group `g`, taken from `override` when it names the group +(under any alias) and from the model's own `depends_on` otherwise. +""" +function _trial_labels_for( + dep::ParameterDependence, g::Int, model::DependentModel, override +) + if override !== nothing + for key in keys(override) + _try_canonical_param(model, key) === dep.names[g] || continue + supplied = getproperty(override, key) + supplied isa AbstractVector || throw( + ArgumentError( + "depends_on override for `:$key` must be a vector with one label " * + "per trial, got a $(typeof(supplied))", + ), + ) + return collect(Any, supplied) + end + end + return dep.trial_labels[g] +end + +# ============================================================================ +# Variant construction +# ============================================================================ + +# Slot 1 aliases `base`, so `model.C` keeps its meaning; other slots get a copy. +# A non-varying parameter has one slot, shared by every variant, so a single +# M-step write updates all of them. +_slot_arrays(base, nslots::Int) = [i == 1 ? base : copy(base) for i in 1:nslots] + +function _build_variants!( + sm::GaussianStateModel{T,M,V}, dep::ParameterDependence +) where {T<:Real,M<:AbstractMatrix{T},V<:AbstractVector{T}} + ncells = prod(dep.nslots) + existing = sm.variants + if existing !== nothing && length(existing) == ncells + return existing + end + + x0s = _slot_arrays(sm.x0, dep.nslots[1]) + P0s = _slot_arrays(sm.P0, dep.nslots[2]) + As = _slot_arrays(sm.A, dep.nslots[3]) + bs = _slot_arrays(sm.b, dep.nslots[3]) + Bs = _slot_arrays(sm.B, dep.nslots[3]) + Qs = _slot_arrays(sm.Q, dep.nslots[4]) + + variants = Vector{GaussianStateModel{T,M,V}}(undef, ncells) + for cell in 1:ncells + s = _variant_slots(dep.nslots, cell) + variants[cell] = GaussianStateModel{T,M,V}(; + A=As[s[3]], + Q=Qs[s[4]], + b=bs[s[3]], + x0=x0s[s[1]], + P0=P0s[s[2]], + B=Bs[s[3]], + Q_prior=sm.Q_prior, + P0_prior=sm.P0_prior, + AB_prior=sm.AB_prior, + x0_prior=sm.x0_prior, + ) + end + sm.variants = variants + return variants +end + +function _build_variants!( + om::GaussianObservationModel{T,M,V}, dep::ParameterDependence +) where {T<:Real,M<:AbstractMatrix{T},V<:AbstractVector{T}} + ncells = prod(dep.nslots) + existing = om.variants + if existing !== nothing && length(existing) == ncells + return existing + end + + Cs = _slot_arrays(om.C, dep.nslots[1]) + ds = _slot_arrays(om.d, dep.nslots[1]) + Ds = _slot_arrays(om.D, dep.nslots[1]) + Rs = _slot_arrays(om.R, dep.nslots[2]) + + variants = Vector{GaussianObservationModel{T,M,V}}(undef, ncells) + for cell in 1:ncells + s = _variant_slots(dep.nslots, cell) + variants[cell] = GaussianObservationModel{T,M,V}(; + C=Cs[s[1]], + R=Rs[s[2]], + d=ds[s[1]], + D=Ds[s[1]], + R_prior=om.R_prior, + CD_prior=om.CD_prior, + ) + end + om.variants = variants + return variants +end + +function _build_variants!( + om::PoissonObservationModel{T,M,V}, dep::ParameterDependence +) where {T<:Real,M<:AbstractMatrix{T},V<:AbstractVector{T}} + ncells = prod(dep.nslots) + existing = om.variants + if existing !== nothing && length(existing) == ncells + return existing + end + + Cs = _slot_arrays(om.C, dep.nslots[1]) + ds = _slot_arrays(om.d, dep.nslots[1]) + Ds = _slot_arrays(om.D, dep.nslots[1]) + + variants = Vector{PoissonObservationModel{T,M,V}}(undef, ncells) + for cell in 1:ncells + s = _variant_slots(dep.nslots, cell) + variants[cell] = PoissonObservationModel{T,M,V}(; + C=Cs[s[1]], d=ds[s[1]], D=Ds[s[1]], CD_prior=om.CD_prior + ) + end + om.variants = variants + return variants +end + +# ============================================================================ +# Trial partition +# ============================================================================ + +""" + ParameterGrouping + +**Internal.** The trial partition induced by a model's `depends_on`, together +with the per-cell parameter lookups the grouped E/M-steps need. + +# Fields +- `names`: canonical parameter-group names, ordered as `fit_bool` +- `ncells`: number of occupied cells +- `trial_cell`: cell index of each trial +- `cell_trials`: trial indices of each cell +- `cell_state` / `cell_obs`: index into the state / observation model's + `variants` vector for each cell +- `nslots[g]`: number of distinct versions of parameter group `g` +- `cell_slot[g][cell]`: which version of group `g` a cell uses +- `slot_labels[g][slot]`: the user's label for that version (`nothing` when the + group does not vary) +""" +struct ParameterGrouping + names::Vector{Symbol} + ncells::Int + trial_cell::Vector{Int} + cell_trials::Vector{Vector{Int}} + cell_state::Vector{Int} + cell_obs::Vector{Int} + nslots::Vector{Int} + cell_slot::Vector{Vector{Int}} + slot_labels::Vector{Vector{Any}} +end + +""" + _validate_override_keys(sm, om, dep_s, dep_o, override) + +Reject a call-site `depends_on` that names something neither sub-model owns (a +typo), or a parameter the model does not declare as varying. An override +re-assigns trials to existing groups; it cannot introduce a parameter set that +was never fitted. +""" +function _validate_override_keys( + sm::DependentModel, + om::DependentModel, + dep_s::ParameterDependence, + dep_o::ParameterDependence, + override::Union{Nothing,NamedTuple}, +) + override === nothing && return nothing + for key in keys(override) + cs = _try_canonical_param(sm, key) + co = _try_canonical_param(om, key) + cs === nothing && + co === nothing && + throw( + ArgumentError( + "depends_on override: `:$key` is not a parameter of either sub-model " * + "(state: $(_valid_param_names(sm)); " * + "observation: $(_valid_param_names(om)))", + ), + ) + declared = + (cs !== nothing && dep_s.varies[findfirst(isequal(cs), dep_s.names)::Int]) || + (co !== nothing && dep_o.varies[findfirst(isequal(co), dep_o.names)::Int]) + declared || throw( + ArgumentError( + "depends_on override: `:$key` is not declared as depending on an " * + "ancillary variable by the model; an override may only re-assign " * + "trials to groups the model already declares", + ), + ) + end + # An override re-labels the whole group, so it must name it as completely. + _check_group_naming_complete(sm, override, "depends_on override") + _check_group_naming_complete(om, override, "depends_on override") + return nothing +end + +""" + parameter_grouping(lds, ntrials; depends_on=nothing) + +Build the trial partition for `lds` over `ntrials` trials, or return `nothing` +when no parameter of either sub-model depends on an ancillary variable. + +`depends_on` optionally overrides the label vectors stored on the models, for +scoring a dataset whose trial count differs from the fitted one. +""" +function parameter_grouping( + lds::LinearDynamicalSystem, ntrials::Int; depends_on::Union{Nothing,NamedTuple}=nothing +) + sm = lds.state_model + om = lds.obs_model + dep_s = _resolve_dependence(sm) + dep_o = _resolve_dependence(om) + + # An override only re-assigns trials to existing groups; a model with no + # `depends_on` stays ungrouped. + if !_any_varies(dep_s) && !_any_varies(dep_o) + depends_on === nothing || throw( + ArgumentError( + "a `depends_on` override was supplied but neither sub-model declares " * + "`depends_on`; set it on the model before fitting", + ), + ) + return nothing + end + + _validate_override_keys(sm, om, dep_s, dep_o, depends_on) + + _build_variants!(sm, dep_s) + _build_variants!(om, dep_o) + + ngroups_s = length(dep_s.names) + ngroups_o = length(dep_o.names) + ngroups = ngroups_s + ngroups_o + names = vcat(dep_s.names, dep_o.names) + varies = vcat(dep_s.varies, dep_o.varies) + + # Per-trial labels for every group (state groups first, matching fit_bool). + trial_labels = Vector{Vector{Any}}(undef, ngroups) + for g in 1:ngroups_s + trial_labels[g] = _trial_labels_for(dep_s, g, sm, depends_on) + end + for g in 1:ngroups_o + trial_labels[ngroups_s + g] = _trial_labels_for(dep_o, g, om, depends_on) + end + + for g in 1:ngroups + varies[g] || continue + length(trial_labels[g]) == ntrials || throw( + DimensionMismatchError( + "depends_on labels for :$(names[g])", ntrials, length(trial_labels[g]) + ), + ) + end + + # Per-trial slot indices, then the per-trial variant index of each sub-model. + state_idx = Vector{Int}(undef, ntrials) + obs_idx = Vector{Int}(undef, ntrials) + s_slots = Vector{Int}(undef, ngroups_s) + o_slots = Vector{Int}(undef, ngroups_o) + for n in 1:ntrials + for g in 1:ngroups_s + s_slots[g] = dep_s.varies[g] ? _slot_of(dep_s, g, trial_labels[g][n]) : 1 + end + for g in 1:ngroups_o + gg = ngroups_s + g + o_slots[g] = dep_o.varies[g] ? _slot_of(dep_o, g, trial_labels[gg][n]) : 1 + end + state_idx[n] = _variant_index(dep_s.nslots, s_slots) + obs_idx[n] = _variant_index(dep_o.nslots, o_slots) + end + + # Occupied cells, in order of first appearance. + trial_cell = Vector{Int}(undef, ntrials) + cell_state = Int[] + cell_obs = Int[] + cell_trials = Vector{Int}[] + for n in 1:ntrials + cell = 0 + for c in eachindex(cell_state) + if cell_state[c] == state_idx[n] && cell_obs[c] == obs_idx[n] + cell = c + break + end + end + if cell == 0 + push!(cell_state, state_idx[n]) + push!(cell_obs, obs_idx[n]) + push!(cell_trials, Int[]) + cell = length(cell_state) + end + trial_cell[n] = cell + push!(cell_trials[cell], n) + end + + ncells = length(cell_state) + cell_slot = [Vector{Int}(undef, ncells) for _ in 1:ngroups] + for c in 1:ncells + cs = _variant_slots(dep_s.nslots, cell_state[c]) + co = _variant_slots(dep_o.nslots, cell_obs[c]) + for g in 1:ngroups_s + cell_slot[g][c] = cs[g] + end + for g in 1:ngroups_o + cell_slot[ngroups_s + g][c] = co[g] + end + end + + slot_labels = Vector{Vector{Any}}(undef, ngroups) + for g in 1:ngroups_s + slot_labels[g] = dep_s.varies[g] ? dep_s.labels[g] : Any[nothing] + end + for g in 1:ngroups_o + gg = ngroups_s + g + slot_labels[gg] = dep_o.varies[g] ? dep_o.labels[g] : Any[nothing] + end + + return ParameterGrouping( + names, + ncells, + trial_cell, + cell_trials, + cell_state, + cell_obs, + vcat(dep_s.nslots, dep_o.nslots), + cell_slot, + slot_labels, + ) +end + +""" + _has_parameter_dependence(model) -> Bool + +Whether a model (or either sub-model of a `LinearDynamicalSystem`) declares a +`depends_on` that actually varies a parameter. +""" +function _has_parameter_dependence(model::DependentModel) + model.depends_on === nothing && return false + return _any_varies(_resolve_dependence(model)) +end + +function _has_parameter_dependence(lds::LinearDynamicalSystem) + return _has_parameter_dependence(lds.state_model) || + _has_parameter_dependence(lds.obs_model) +end + +""" + _reject_unsupported_dependence(model) + +**Internal, temporary.** Refuse to run an entry point that does not yet honour +`depends_on`. The field, its validation and its accessors land ahead of the +grouped E/M-step machinery, so in the interim a declared dependence must be an +error rather than a silently pooled fit. Each entry point drops this call as +its grouped path lands. +""" +function _reject_unsupported_dependence(lds::LinearDynamicalSystem) + _has_parameter_dependence(lds) || return nothing + return throw( + ArgumentError( + "this model declares `depends_on`, but fitting and inference with " * + "condition-dependent parameters are not implemented yet — the grouped " * + "E/M-step lands in a follow-up. Unset `depends_on` to fit the model " * + "with one parameter set shared by every trial.", + ), + ) +end + +function _reject_unsupported_dependence(slds::SLDS) + for lds in slds.LDSs + _reject_unsupported_dependence(lds) + end + return nothing +end + +# ============================================================================ +# Public accessors +# ============================================================================ + +""" + group_labels(model, name) -> Vector + +Distinct labels of the parameter group `name` on a state or observation model, +in the order their parameter versions are stored. Returns an empty vector when +that parameter does not depend on an ancillary variable. + +```julia +group_labels(obs_model, :C) # [:session_a, :session_b] +``` + +Members of a jointly-fitted group are aliases, so `group_labels(m, :d)` is the +same as `group_labels(m, :C)`. +""" +function group_labels(model::DependentModel, name::Symbol) + dep = _resolve_dependence(model) + canonical = _canonical_param(model, name) + g = findfirst(isequal(canonical), dep.names)::Int + return dep.varies[g] ? copy(dep.labels[g]) : Any[] +end + +""" + group_parameter(model, name, label) + +The version of parameter `name` fitted from the trials labelled `label`. + +```julia +group_parameter(obs_model, :C, :session_a) # that session's emission matrix +group_parameter(obs_model, :d, :session_a) # its emission bias +``` + +Throws when the model declares no dependence for that parameter (read the field +directly in that case) or when `label` is not one of its groups. +""" +function group_parameter(model::DependentModel, name::Symbol, label) + dep = _resolve_dependence(model) + canonical = _canonical_param(model, name) + g = findfirst(isequal(canonical), dep.names)::Int + dep.varies[g] || throw( + ArgumentError( + "parameter `:$name` of this $(nameof(typeof(model))) does not depend on an " * + "ancillary variable; read `model.$name` directly", + ), + ) + slots = fill(1, length(dep.nslots)) + slots[g] = _slot_of(dep, g, label) + variants = _build_variants!(model, dep) + return getproperty(variants[_variant_index(dep.nslots, slots)], name) +end diff --git a/src/lds/types.jl b/src/lds/types.jl index 7ea43026..78ac3f19 100644 --- a/src/lds/types.jl +++ b/src/lds/types.jl @@ -4,6 +4,11 @@ Abstract supertype for latent-state models of a [`LinearDynamicalSystem`](@ref) (e.g. [`GaussianStateModel`](@ref)). A state model defines how the latent state evolves from one timestep to the next. + +Every concrete subtype carries a `depends_on` field declaring which of its +parameters are estimated separately per group of trials, and a companion +`variants` field holding one model object per parameter-group combination. +See `src/lds/parameter_groups.jl` for the full description. """ abstract type AbstractStateModel{T<:Real} end @@ -14,6 +19,11 @@ Abstract supertype for observation (emission) models of a [`LinearDynamicalSystem`](@ref) (e.g. [`GaussianObservationModel`](@ref) or [`PoissonObservationModel`](@ref)). An observation model defines how observed data are generated from the latent state. + +Every concrete subtype carries a `depends_on` field declaring which of its +parameters are estimated separately per group of trials, and a companion +`variants` field holding one model object per parameter-group combination. +See `src/lds/parameter_groups.jl` for the full description. """ abstract type AbstractObservationModel{T<:Real} end @@ -74,6 +84,14 @@ where `B·ux_t` is present only when `B` is supplied (i.e., has nonzero columns) they match the internal workspaces regardless of how `A` is stored. - `x0_prior::Union{Nothing,MNPrior{T,Matrix{T}}} = nothing`: Optional matrix-normal prior on the initial mean `x0`. +- `depends_on::Union{Nothing,NamedTuple} = nothing`: Optional declaration that some + parameters are estimated separately per group of trials. Keys are parameter names + (`:x0`, `:P0`, `:A`/`:b`/`:B`, `:Q`), values are per-trial label vectors; `nothing` + (the default) means one parameter set shared by every trial. +- `variants::Union{Nothing,Vector{GaussianStateModel{T,M,V}}} = nothing`: Derived storage + for the per-group parameter sets; populated from `depends_on` by the fitting entry + points. Parameters that do not vary are shared **by reference** across variants, so + an M-step write through any variant is visible from all of them. """ Base.@kwdef mutable struct GaussianStateModel{ T<:Real,M<:AbstractMatrix{T},V<:AbstractVector{T} @@ -88,6 +106,8 @@ Base.@kwdef mutable struct GaussianStateModel{ P0_prior::Union{Nothing,IWPrior{T}} = nothing AB_prior::Union{Nothing,MNPrior{T,Matrix{T}}} = nothing x0_prior::Union{Nothing,MNPrior{T,Matrix{T}}} = nothing + depends_on::Union{Nothing,NamedTuple} = nothing + variants::Union{Nothing,Vector{GaussianStateModel{T,M,V}}} = nothing end """ @@ -105,6 +125,13 @@ Represents the observation model of a Linear Dynamical System with Gaussian nois the stacked emission matrix `[C D]`. Pair with `R_prior` for a full MNIW prior on `(CD, R)`. Prior matrices are stored as plain `Matrix{T}` (decoupled from `C`'s storage type `M`) so they match the internal workspaces regardless of how `C` is stored. +- `depends_on::Union{Nothing,NamedTuple} = nothing`: Optional declaration that some + parameters are estimated separately per group of trials. Keys are parameter names + (`:C`/`:d`/`:D`, `:R`), values are per-trial label vectors; `nothing` (the default) + means one parameter set shared by every trial. +- `variants::Union{Nothing,Vector{GaussianObservationModel{T,M,V}}} = nothing`: Derived + storage for the per-group parameter sets; populated from `depends_on` by the fitting + entry points. Parameters that do not vary are shared **by reference** across variants. """ Base.@kwdef mutable struct GaussianObservationModel{ T<:Real,M<:AbstractMatrix{T},V<:AbstractVector{T} @@ -115,6 +142,8 @@ Base.@kwdef mutable struct GaussianObservationModel{ D::M = zeros(eltype(C), size(C, 1), 0) # eltype-preserving default R_prior::Union{Nothing,IWPrior{T}} = nothing CD_prior::Union{Nothing,MNPrior{T,Matrix{T}}} = nothing + depends_on::Union{Nothing,NamedTuple} = nothing + variants::Union{Nothing,Vector{GaussianObservationModel{T,M,V}}} = nothing end # Convenience constructors (State) @@ -197,6 +226,13 @@ model reduces to the canonical `λ_t = exp(C x_t + d)`. `(latent_dim+1+uy_dim, latent_dim+1+uy_dim)` respectively. Unlike the Gaussian path there is no IW counterpart since Poisson has no observation-noise covariance — this is an MN-only prior contributing `½ tr(([C d D] - M₀) Λ ([C d D] - M₀)')` to the LBFGS objective. +- `depends_on::Union{Nothing,NamedTuple} = nothing`: Optional declaration that `[C d D]` + is estimated separately per group of trials. Keys are parameter names (`:C`/`:d`/`:D`), + values are per-trial label vectors; `nothing` (the default) means one parameter set + shared by every trial. +- `variants::Union{Nothing,Vector{PoissonObservationModel{T,M,V}}} = nothing`: Derived + storage for the per-group parameter sets; populated from `depends_on` by the fitting + entry points. """ Base.@kwdef mutable struct PoissonObservationModel{ T<:Real,M<:AbstractMatrix{T},V<:AbstractVector{T} @@ -205,6 +241,8 @@ Base.@kwdef mutable struct PoissonObservationModel{ d::V D::M = zeros(eltype(C), size(C, 1), 0) # eltype-preserving default (no obs inputs) CD_prior::Union{Nothing,MNPrior{T,Matrix{T}}} = nothing + depends_on::Union{Nothing,NamedTuple} = nothing + variants::Union{Nothing,Vector{PoissonObservationModel{T,M,V}}} = nothing end # 2-arg convenience constructor; matches the Gaussian path's positional form diff --git a/src/stats/simulate.jl b/src/stats/simulate.jl index a663cd84..a68ffdcd 100644 --- a/src/stats/simulate.jl +++ b/src/stats/simulate.jl @@ -124,6 +124,7 @@ function Random.rand( ux::Union{Nothing,AbstractMatrix{T}}=nothing, uy::Union{Nothing,AbstractMatrix{T}}=nothing, ) where {T<:Real,S<:GaussianStateModel{T},O<:AbstractObservationModel{T}} + _reject_unsupported_dependence(lds) state_params = _extract_state_params(lds.state_model) obs_params = _extract_obs_params(lds.obs_model) Ti = Int(tsteps) @@ -144,6 +145,7 @@ function Random.rand( ux::Union{Nothing,AbstractVector{<:AbstractMatrix{T}}}=nothing, uy::Union{Nothing,AbstractVector{<:AbstractMatrix{T}}}=nothing, ) where {T<:Real,S<:GaussianStateModel{T},O<:AbstractObservationModel{T}} + _reject_unsupported_dependence(lds) state_params = _extract_state_params(lds.state_model) obs_params = _extract_obs_params(lds.obs_model) diff --git a/src/utils/show.jl b/src/utils/show.jl index d8f097db..ae42096b 100644 --- a/src/utils/show.jl +++ b/src/utils/show.jl @@ -20,6 +20,32 @@ end print_full(obj) = print_full(stdout, obj) +#= +One line per group that depends on an ancillary variable, e.g. +`C, d, D -> 2 groups (:session_a, :session_b)`. Prints nothing when +`depends_on` is unset. +=# +function _show_depends_on(io::IO, model::DependentModel; gap="") + model.depends_on === nothing && return nothing + dep = _resolve_dependence(model) + any(dep.varies) || return nothing + + println(io, gap, " Depends on:") + for g in eachindex(dep.names) + dep.varies[g] || continue + members = if dep.names[g] === :A + "A, b, B" + elseif dep.names[g] === :C + "C, d, D" + else + String(dep.names[g]) + end + labels = join(map(repr, dep.labels[g]), ", ") + println(io, gap, " $members -> $(dep.nslots[g]) groups ($labels)") + end + return nothing +end + function Base.show(io::IO, gsm::GaussianStateModel; gap="") println(io, gap, "Gaussian State Model:") println(io, gap, "---------------------") @@ -45,6 +71,8 @@ function Base.show(io::IO, gsm::GaussianStateModel; gap="") println(io, gap, " Dynamics input:") println(io, gap, " size(B) = ($(size(gsm.B,1)), $(size(gsm.B,2)))") + _show_depends_on(io, gsm; gap=gap) + return nothing end @@ -64,6 +92,8 @@ function Base.show(io::IO, gom::GaussianObservationModel; gap="") println(io, gap, " D = $(round.(gom.D, digits=2))") end + _show_depends_on(io, gom; gap=gap) + return nothing end @@ -86,6 +116,8 @@ function Base.show(io::IO, pom::PoissonObservationModel; gap="") ) end + _show_depends_on(io, pom; gap=gap) + return nothing end diff --git a/src/utils/validation.jl b/src/utils/validation.jl index b38a0c9f..fd6077b8 100644 --- a/src/utils/validation.jl +++ b/src/utils/validation.jl @@ -321,6 +321,12 @@ function validate_LDS(lds::LinearDynamicalSystem{T,S,O}) where {T,S,O} # Check observation model dimensions and properties _validate_obs_model(lds.obs_model, lds.obs_dim, lds.latent_dim) + # Resolve `depends_on` so a malformed declaration is reported here rather + # than at the first `fit!`. The result is discarded; the fitting entry + # points re-resolve against the actual trial count. + _resolve_dependence(lds.state_model) + _resolve_dependence(lds.obs_model) + #= Check fit_bool length. The Gaussian path uses length 6 — the regression M-step fits A&b&B and C&d&D jointly. diff --git a/test/LinearDynamicalSystems/ParameterDependencies.jl b/test/LinearDynamicalSystems/ParameterDependencies.jl new file mode 100644 index 00000000..114970d0 --- /dev/null +++ b/test/LinearDynamicalSystems/ParameterDependencies.jl @@ -0,0 +1,366 @@ +# Ancillary parameter dependencies (`depends_on`): declaring that some +# parameters are estimated separately per group of trials. +# +# This file covers the declaration side — validation, the resolved trial +# partition, and the accessors that read a fitted version back. The grouped +# E/M-step that consumes the partition lands in a follow-up; until it does, +# every entry point refuses a model that declares `depends_on` rather than +# silently pooling it (`test_depends_on_rejected_until_supported`). + +const PD_LATENT_DIM = 2 +const PD_OBS_DIM = 2 + +function pd_state_model(::Type{T}=Float64) where {T<:Real} + return GaussianStateModel(; + A=T[0.92 0.10; -0.10 0.92], + Q=Matrix{T}(0.01 * I(PD_LATENT_DIM)), + b=zeros(T, PD_LATENT_DIM), + x0=zeros(T, PD_LATENT_DIM), + P0=Matrix{T}(0.10 * I(PD_LATENT_DIM)), + ) +end + +function pd_obs_model(::Type{T}=Float64) where {T<:Real} + return GaussianObservationModel(; + C=T[1.0 0.2; -0.3 1.0], d=zeros(T, PD_OBS_DIM), R=Matrix{T}(0.20 * I(PD_OBS_DIM)) + ) +end + +function pd_lds(sm, om; fit_bool::Vector{Bool}=fill(true, 6)) + return LinearDynamicalSystem(; + state_model=sm, + obs_model=om, + latent_dim=PD_LATENT_DIM, + obs_dim=PD_OBS_DIM, + fit_bool=fit_bool, + ) +end + +pd_fresh_lds() = pd_lds(pd_state_model(), pd_obs_model()) + +# ============================================================================ +# Validation +# ============================================================================ + +function test_depends_on_validation() + om = pd_obs_model() + + om.depends_on = (Z=[:a, :b],) + @test_throws ArgumentError SSD._resolve_dependence(om) + + # `:d` is an alias of `:C` — they must carry the same labels. + om.depends_on = (C=[:a, :b], d=[:a, :a]) + @test_throws ArgumentError SSD._resolve_dependence(om) + + om.depends_on = (C=[:a, :b], d=[:a, :b], R=[:a, :b, :b]) + @test_throws SSD.DimensionMismatchError SSD._resolve_dependence(om) + + om.depends_on = (C=Symbol[], d=Symbol[]) + @test_throws ArgumentError SSD._resolve_dependence(om) + + # A Poisson emission has no `R`. + pom = PoissonObservationModel(zeros(2, 2), zeros(2)) + pom.depends_on = (R=[:a, :b],) + @test_throws ArgumentError SSD._resolve_dependence(pom) + + # A state model has no `C`. + sm = pd_state_model() + sm.depends_on = (C=[:a, :b], d=[:a, :b]) + @test_throws ArgumentError SSD._resolve_dependence(sm) + + return nothing +end + +""" +`validate_LDS` resolves both sub-models' `depends_on`, so a malformed +declaration is reported by the validating positional constructor rather than at +the first `fit!`. (`LinearDynamicalSystem` is a `@kwdef` struct, so the keyword +constructor bypasses `validate_LDS` — for `depends_on` exactly as for every +other field.) +""" +function test_depends_on_validated_at_construction() + bad_obs = pd_obs_model() + bad_obs.depends_on = (nope=[:a, :b],) + @test_throws ArgumentError LinearDynamicalSystem(pd_state_model(), bad_obs) + + bad_state = pd_state_model() + bad_state.depends_on = (A=[:a, :b], b=[:b, :a]) # aliases disagreeing + @test_throws ArgumentError LinearDynamicalSystem(bad_state, pd_obs_model()) + + ok_obs = pd_obs_model() + ok_obs.depends_on = (C=[:a, :b], d=[:a, :b]) + @test LinearDynamicalSystem(pd_state_model(), ok_obs) isa LinearDynamicalSystem + + # A model built through the keyword constructor is still rejected when + # `validate_LDS` is run on it. + @test_throws ArgumentError validate_LDS(pd_lds(pd_state_model(), bad_obs)) + + return nothing +end + +# ============================================================================ +# Accessors and storage layout +# ============================================================================ + +function test_group_accessors_and_aliasing() + labels = [:s1, :s1, :s2, :s2] + om = pd_obs_model() + om.depends_on = (C=labels, d=labels) + lds = pd_lds(pd_state_model(), om) + + @test group_labels(om, :C) == [:s1, :s2] + @test group_labels(om, :d) == [:s1, :s2] # alias of the same group + @test group_labels(om, :D) == [:s1, :s2] + @test isempty(group_labels(om, :R)) # R does not vary + + @test_throws ArgumentError group_parameter(om, :R, :s1) + @test_throws ArgumentError group_parameter(om, :C, :nope) + + grp = SSD.parameter_grouping(lds, length(labels)) + @test grp !== nothing + @test grp.ncells == 2 + @test grp.trial_cell == [1, 1, 2, 2] + @test grp.cell_trials == [[1, 2], [3, 4]] + + variants = om.variants + @test variants !== nothing + @test length(variants) == 2 + # Slot 1 aliases the base model, so `om.C` keeps its original meaning. + @test variants[1].C === om.C + @test group_parameter(om, :C, :s1) === om.C + # A varying parameter gets one array per group ... + @test variants[1].C !== variants[2].C + @test variants[1].d !== variants[2].d + # ... a fixed one is shared by reference, so a single M-step write covers all. + @test variants[1].R === variants[2].R + @test variants[1].R === om.R + + return nothing +end + +""" +A trial's cell is its position in the common refinement of every label vector, +so parameters may be grouped along different ancillary variables at once. +""" +function test_grouping_is_the_join_of_label_vectors() + session = [:s1, :s1, :s2, :s2] + condition = [:c1, :c2, :c1, :c2] + sm = pd_state_model() + sm.depends_on = (Q=condition,) + om = pd_obs_model() + om.depends_on = (C=session, d=session) + lds = pd_lds(sm, om) + + grp = SSD.parameter_grouping(lds, 4) + # Q varies by condition and C by session, so a cell is one (session, + # condition) pair: four singleton cells. + @test grp.ncells == 4 + @test sort(grp.trial_cell) == [1, 2, 3, 4] + @test grp.nslots[SSD._G_Q] == 2 + @test grp.nslots[SSD._G_CD] == 2 + @test grp.nslots[SSD._G_AB] == 1 + + # The trial count must match the label vectors the model was built with. + @test_throws SSD.DimensionMismatchError SSD.parameter_grouping(lds, 3) + + return nothing +end + +""" +An override may re-assign trials to groups the model already declares, but it +cannot invent a parameter set that was never fitted, and it is meaningless on a +model that declares nothing. +""" +function test_override_key_validation() + om = pd_obs_model() + om.depends_on = (C=[:a, :a, :b], d=[:a, :a, :b]) + lds = pd_lds(pd_state_model(), om) + + @test SSD.parameter_grouping(lds, 2; depends_on=(C=[:a, :b], d=[:a, :b])) !== nothing + @test_throws ArgumentError SSD.parameter_grouping( + lds, 3; depends_on=(C=[:a, :a, :x], d=[:a, :a, :x]) + ) + @test_throws ArgumentError SSD.parameter_grouping(lds, 3; depends_on=(nope=[:a],)) + # `:R` is a real parameter name, but this model does not group by it. + @test_throws ArgumentError SSD.parameter_grouping(lds, 3; depends_on=(R=[:a, :b],)) + + plain = pd_fresh_lds() + @test_throws ArgumentError SSD.parameter_grouping( + plain, 2; depends_on=(C=[:a, :b], d=[:a, :b]) + ) + @test SSD.parameter_grouping(plain, 2) === nothing + + return nothing +end + +# ============================================================================ +# Interim guard (removed as each model family's grouped fit lands) +# ============================================================================ + +function test_depends_on_rejected_until_supported() + rng = StableRNG(101) + labels = [:a, :a, :b] + y = [randn(rng, PD_OBS_DIM, 20) for _ in 1:3] + + om = pd_obs_model() + om.depends_on = (C=labels, d=labels) + lds = pd_lds(pd_state_model(), om) + + @test_throws ArgumentError fit!(lds, y; max_iter=1, progress=false) + @test_throws ArgumentError smooth(lds, y) + @test_throws ArgumentError elbo(lds, y) + @test_throws ArgumentError loglikelihood(lds, y) + @test_throws ArgumentError rand(rng, lds, 20) + @test_throws ArgumentError rand(rng, lds, fill(20, 3)) + + # A model that declares nothing is untouched by any of this. + plain = pd_fresh_lds() + @test fit!(plain, y; max_iter=1, progress=false) isa Vector + + pom = PoissonObservationModel([0.6 0.1; -0.2 0.5], [1.0, 0.8]) + pom.depends_on = (C=labels, d=labels) + plds = LinearDynamicalSystem(; + state_model=pd_state_model(), + obs_model=pom, + latent_dim=PD_LATENT_DIM, + obs_dim=PD_OBS_DIM, + fit_bool=fill(true, 5), + ) + counts = [Float64.(rand(rng, 0:3, PD_OBS_DIM, 20)) for _ in 1:3] + @test_throws ArgumentError fit!(plds, counts; max_iter=1, progress=false) + @test_throws ArgumentError smooth(plds, counts) + @test_throws ArgumentError elbo(plds, counts) + + slds = SLDS(; + A=[0.9 0.1; 0.1 0.9], + πₖ=[0.5, 0.5], + LDSs=[pd_fresh_lds(), pd_lds(pd_state_model(), om)], + ) + @test_throws ArgumentError fit!(slds, y; max_iter=1, progress=false) + @test_throws ArgumentError elbo(slds, y) + @test_throws ArgumentError rand(rng, slds, 20) + + return nothing +end + +# ============================================================================ +# Display +# ============================================================================ + +function test_grouped_show() + labels = [:s1, :s1, :s2] + om = pd_obs_model() + om.depends_on = (C=labels, d=labels, R=labels) + out = sprint(show, om) + @test occursin("Depends on:", out) + @test occursin("C, d, D", out) + @test occursin(":s2", out) + + plain = sprint(show, pd_obs_model()) + @test !occursin("Depends on:", plain) + + return nothing +end + +#= +`[A b B]` and `[C d D]` are each fit as one regression, so grouping any member +groups them all. Naming one and leaving the rest out reads as though only that +one varies — the opposite of what happens — so it is rejected rather than +quietly widened. +=# +function test_depends_on_requires_the_whole_group() + labels = [:a, :a, :b, :b] + + # Naming part of a regression group is an error, whichever part. + for spec in ((C=labels,), (d=labels,)) + om = pd_obs_model() + om.depends_on = spec + @test_throws ArgumentError SSD._resolve_dependence(om) + end + for spec in ((A=labels,), (b=labels,)) + sm = pd_state_model() + sm.depends_on = spec + @test_throws ArgumentError SSD._resolve_dependence(sm) + end + + # The message names what is missing and shows the complete form. + om = pd_obs_model() + om.depends_on = (C=labels,) + msg = try + SSD._resolve_dependence(om) + "" + catch e + sprint(showerror, e) + end + @test occursin("[C d]", msg) + @test occursin(":d", msg) + + # Naming the whole group is accepted. + om2 = pd_obs_model() + om2.depends_on = (C=labels, d=labels) + @test SSD._resolve_dependence(om2).varies[1] + sm2 = pd_state_model() + sm2.depends_on = (A=labels, b=labels) + @test SSD._resolve_dependence(sm2) isa SSD.ParameterDependence + + # A group of one is complete on its own. + for (model, spec) in ( + (pd_obs_model(), (R=labels,)), + (pd_state_model(), (Q=labels,)), + (pd_state_model(), (x0=labels, P0=labels)), + ) + model.depends_on = spec + @test SSD._resolve_dependence(model) isa SSD.ParameterDependence + end + return nothing +end + +#= +`B` and `D` are zero-column when the model takes no inputs, so there is nothing +to group and naming them is not required. Give the emission an input and `:D` +joins the group. +=# +function test_depends_on_group_membership_follows_inputs() + labels = [:a, :a, :b, :b] + + # No observation inputs: `(C, d)` is the whole group. + om = pd_obs_model() + @test size(om.D, 2) == 0 + om.depends_on = (C=labels, d=labels) + @test SSD._resolve_dependence(om) isa SSD.ParameterDependence + + # With an observation input, `:D` is part of it too. + om2 = pd_obs_model() + om2.D = zeros(PD_OBS_DIM, 1) + om2.depends_on = (C=labels, d=labels) + @test_throws ArgumentError SSD._resolve_dependence(om2) + om2.depends_on = (C=labels, d=labels, D=labels) + @test SSD._resolve_dependence(om2) isa SSD.ParameterDependence + + # Same on the state side, via `B`. + sm = pd_state_model() + sm.B = zeros(PD_LATENT_DIM, 1) + sm.depends_on = (A=labels, b=labels) + @test_throws ArgumentError SSD._resolve_dependence(sm) + sm.depends_on = (A=labels, b=labels, B=labels) + @test SSD._resolve_dependence(sm) isa SSD.ParameterDependence + return nothing +end + +#= +A call-site override is a `depends_on` like any other and re-labels the whole +regression group, so it has to name the group as completely as the declaration +did. +=# +function test_depends_on_override_requires_the_whole_group() + labels = [:a, :a, :b, :b] + om = pd_obs_model() + om.depends_on = (C=labels, d=labels) + lds = pd_lds(pd_state_model(), om) + + swapped = [:b, :b, :a, :a] + @test_throws ArgumentError SSD.parameter_grouping(lds, 4; depends_on=(C=swapped,)) + @test_throws ArgumentError SSD.parameter_grouping(lds, 4; depends_on=(d=swapped,)) + @test SSD.parameter_grouping(lds, 4; depends_on=(C=swapped, d=swapped)) !== nothing + return nothing +end diff --git a/test/runtests.jl b/test/runtests.jl index d6b61a31..a104bc77 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -252,6 +252,28 @@ using SSDTest test_poisson_gradient_shape_and_finiteness() end end + + include("LinearDynamicalSystems/ParameterDependencies.jl") + @testset "Ancillary parameter dependencies" begin + @testset "Validation" begin + test_depends_on_validation() + test_depends_on_validated_at_construction() + test_override_key_validation() + test_depends_on_requires_the_whole_group() + test_depends_on_group_membership_follows_inputs() + test_depends_on_override_requires_the_whole_group() + end + + @testset "Accessors and partition" begin + test_group_accessors_and_aliasing() + test_grouping_is_the_join_of_label_vectors() + test_grouped_show() + end + + @testset "Not yet honoured by fitting" begin + test_depends_on_rejected_until_supported() + end + end end # Optimization primitives (line search + Newton)