LUCIDus 3.3.1 merges two parallel lines of development from 3.2.1: the 3.3.0
correctness and parity release (all of it is kept; see the 3.3.0 section
below) and a set of fixes that make serial LUCID with useY = FALSE and its
bootstrap correct and stable. Those fixes came out of an audit of a real
analysis: 4 time points, each a 3-layer parallel sub-model, with three outcomes
fitted separately. Where the two lines disagreed, the rule that is correct for
an unsupervised model was kept.
The outcome model of a useY = FALSE fit is a regression on the posterior
cluster probabilities. New argument outcome_method = c("auto", "pip", "weighted"); "auto" means "pip" when useY = FALSE and "weighted" when
useY = TRUE. 3.2.0-3.3.0 regressed Y on the latent states with
responsibility weights. When the outcome does not inform the clusters, that
estimator is attenuated towards zero by misclassification: in a simulation
with a true contrast of 0.47 it returned 0.29. "pip" regresses Y on each
subject's non-reference posterior probabilities plus CoY, as LUCIDus 3.1.0
did, and recovers the contrast. res_Gamma$fit$coefficients keeps the 3.1.0
names LC1..LCm, so scripts written against 3.1.0 still map the terms. Binary
outcomes honour outcome_penalty = "firth". outcome_method = "weighted"
reproduces 3.3.0.
Clusters estimated without the outcome are labelled without it. 3.3.0
ordered the final serial stage by its outcome effect even when useY = FALSE.
The clusters are identical whichever outcome is attached, but their labels,
and so the sign of every coefficient, could differ between outcomes. Every
model or stage fitted without Y is now ordered by expected cluster size:
cluster 1, the reference, is the largest. Near-ties are broken by the omics
means (omics_order_index()). Outcome ordering is kept for useY = TRUE.
This also covers the upstream stages of a useY = TRUE serial model, which
never see Y: 3.3.0 ordered them by the omics means. In 3.3.1 their labels, and
so the signs of their coefficients and of the next stage's transition
coefficients, may flip. A new test fits the same serial model to three
different outcomes and requires identical posteriors and labels.
predict_lucid() no longer lets Y move the posterior of a useY = FALSE
model. Supplying Y used to switch the outcome term on in the E-step, so
predicted clusters differed from the fitted ones. Y now enters only for a model
that was fitted with it.
Warm-started replicates. New boot_init = c("reference", "default").
With "reference" (the new default) each replicate starts from the supplied
model through the new init_model argument of estimate_lucid(), so the
replicate stays in the solution being reported instead of jumping to another
local optimum.
boot_n_starts adds random starts to each replicate; a random start
replaces the warm start only if it is better by more than switch_tol
log-likelihood units, and each such mode switch is counted.boot_init = "default" restores the 3.3.0 refits.Cluster-stability report. The new element stability gives:
drop_unstable = TRUE excludes replicates whose ARI is below 0.5.Fixed resamples. boot_indices takes the exact resamples, for example
the same resamples for several outcomes. Each replicate draws its own seed
in advance, so results do not depend on the number of cores.
Parallel and reproducible. The replicate engine replaces boot::boot().
It keeps 3.3.0's parallel/ncpus/cl and adds ncores as a shorthand
for forked parallelism. Results are identical whatever the number of cores,
and the object is still of class "boot", so t0, boot_status,
min_valid and summary(fit, boot.se = ) work as in 3.3.0.
Refits match the point fit. Replicates reuse the model's n_starts,
Beta_ridge, outcome_method and outcome_penalty. Previously they used
one start and the default estimator.
New exported helper boot_lucid_table(). It gives one row per parameter
(Beta, the omics mean difference to the reference cluster, the expected
cluster size, Gamma), with the estimate, percentile CI, sign agreement,
median and bias-corrected normal CI. Serial terms are labelled with
user-supplied stage and layer names.
Alignment. 3.2.2 and 3.3.0 independently fixed the same two serial alignment bugs, with the same algebra:
The 3.3.0 implementation is kept, and alignment failures now warn for every model type.
New Beta_ridge (default 0): a ridge (weight-decay) penalty on the multinomial
G -> X coefficients and, for serial models, the stage-to-stage transition
coefficients (nnet::multinom(decay = )). Small samples with many layers can
produce (quasi-)separated assignment models; the real-data audit saw a
coefficient of -42.7 with bootstrap limits up to 153. A small value (0.01-0.1)
keeps them finite.
$likelihood stays the observed-data log-likelihood.em_control$separation (and
submodel_separation for serial fits) and warns.Beta_ridge is not applied when Rho_G > 0, whose LASSO already
regularizes these coefficients.lucid()'s unpenalized refit after selection now carries useY,
Beta_ridge and outcome_method forward. Before, useY passed through ...
was dropped, so a useY = FALSE selection was refit with useY = TRUE.init_model reuses the supplied model's geometry, so a
replicate is refit under the geometry the point estimates were produced under,
with or without init_omic.data.model = "auto".mix package is no longer listed in Suggests.
init_impute = "mix" still works when mix is installed, and otherwise
gives an informative error.tune_lucid(parallel = "snow") evaluates its data arguments before sending
the grid to socket workers. Before, a call such as tune_lucid(G = d$G, ...)
failed on every candidate with "object 'd' not found", because the workers
received d$G unevaluated. This affected the early and parallel models, and
is the backend used on Windows.summary() of a parallel or serial model fitted by lucid() with a
penalty reports the selection in the feature space that was supplied, as the
early summary and get_selected_G()/get_selected_Z() already did. Before,
it counted the refit model's own features, which are all selected after the
refit, so a fit that kept 2 of 6 exposures printed "2 / 2 (100%)". BIC and
the other fit statistics are unchanged.estimate_lucid() accepts a parallel model's K as a list of single
integers (K = list(2, 2)), the form lucid() and tune_lucid() take,
instead of failing with "invalid 'type' (list) of argument".boot_lucid(parallel = "snow") evaluates everything a replicate needs
before sending it to socket workers, the same safeguard as tune_lucid().boot_lucid() and in the full
functionality guide) are shown but not run when the package is checked, so
checking or building the vignettes never starts worker processes.useY = TRUE fits are numerically unchanged (checked
against 3.3.0 on simulated_HELIX_data, normal and binary outcomes). For a
useY = TRUE serial fit, the upstream stages may be relabelled (largest
cluster = reference); the final stage's outcome effects agree with 3.3.0 to
within the EM tolerance.useY = FALSE fits, the outcome coefficients change (no longer
attenuated) and cluster labels may flip relative to 3.3.0 (largest cluster =
reference). Pass outcome_method = "weighted" for the 3.3.0 estimator.boot_lucid() intervals change because replicates are now warm-started and
refit with the model's own settings. Pass boot_init = "default" for 3.3.0's
cold refits.init_omic.data.model now defaults to "auto", which picks the omics
covariance geometry by BIC -- per layer -- among the geometries that layer's
sample size and dimension can actually identify. The previous default was the
fixed "EEV", which estimates an orientation per cluster: 2,500 covariance
parameters for 50 features at K = 2, and 10,000 for 100. On simulated data with
six informative features among 50 and N = 600, early integration recovered
clusters at ARI 0.239 under "EEV" against 0.980 under "auto"; at 100
features it was 0.024 against 0.987. "EEV" is not uniformly bad -- a
parallel fit splitting 50 features into two 25-feature layers keeps it
estimable, and it scores 0.987 there -- it fails specifically where it is
unidentifiable, which is exactly what the new default detects.
Passing init_omic.data.model = "EEV" reproduces the previous behaviour
exactly. Every other value a caller could already supply behaves as it did: a
single model name, a per-layer vector, or NULL. Only the unspecified default
changed. The fitted object still reports a concrete geometry, never "auto",
so summary(), predict() and boot_lucid() read the same field they always
did -- and because the resolved geometry is now recorded, a bootstrap replicate
refits the geometry the point estimates were produced under instead of
re-selecting one per replicate.
"auto" is strictly better than init_omic.data.model = NULL, which it does
not replace. NULL searches all fourteen mclust geometries unfiltered;
"auto" searches the same set minus those whose parameter count exceeds what
the data can support. Across spherical, AR(1) and cluster-varying truths at
K = 2 and K = 3 and dimensions 8 to 100, the two select the same geometry in
every case, and "auto" is up to 1,923x faster (0.03 s against 55.8 s at
50 features). The geometries it skips are simultaneously the unidentifiable ones
and the most expensive to fit. A hand-picked shortlist was tried first and
rejected: on AR(1) data at K = 3 the BIC-optimal geometry is VVE, which no
short ladder contains.
The hierarchical partition that seeds EM no longer collapses onto a single
component. mclust::Mclust() starts EM from model-based agglomerative
clustering under VVV, guarded only by if (n > d). Well inside n > d --
measured at n = 800, d = 75 -- that agglomeration puts ~90% of subjects in one
cluster before EM takes a step, and EM then polishes the degenerate partition:
minimum cluster proportion was 0.101 at 75 features and 0.129 at 150, against
0.426 and 0.487 once fixed. LUCID now supplies its own EII agglomeration,
which is stable at any dimension and 2x (8 features) to 22x (100 features)
cheaper, since that agglomeration was most of the initialization cost. This is
supplied per call rather than through mclust.options(), so it changes nothing
in the caller's session, and it honours mclust.options("subset"): supplying a
starting partition bypasses mclust's own row subsampling, and agglomeration is
quadratic in N, so the cap has to be respected explicitly or large cohorts pay
for it -- 21 s at N = 5,000, 216 s at 10,000 and 1,462 s at 20,000 on the full
data, against 1.4-1.9 s on the 2,000-row subsample mclust would have used.
The collapsed start was also a severe performance bug. A parallel fit with
50 features per layer under "EEI" took 25,198 seconds -- 7.00 hours -- and
returned normally, while the same configuration under "VVV" took 2.48 s. It
was not slow arithmetic: starting from a partition with ~90% of subjects in one
cluster, the EM could not meet tol and burned restart after restart up to
max_tot.itr. With a stable starting partition the same fit converges in 2
iterations and 0.98 seconds, with no restarts -- a ~25,000x reduction, at
identical settings.
The combination removed a seed-dependence that multiple starts had been
masking. On a two-stage serial fit the stage-2 transition coefficient varied by
1.543 across four seeds with n_starts = 1; it now varies by 0.002, so
a single start delivers what four used to.
tests/testthat/test-serial-reproducibility.R asserted spread(4) <= spread(1), which was meaningful while a single start was unstable and is now a
comparison of two numbers at the noise floor; it has been restated to assert
reproducibility directly, with the measured values recorded in the file.
A vector of geometries no longer fails on the early path.
Mclust(modelNames = ) accepts several geometries and selects among them by
BIC, but estimate_lucid() stored the argument rather than the selection, so
the whole vector reached mclust::mstep() and failed with "EXPR must be a
length 1 vector". It also reached fit$init_omic.data.model, where
summary() needs a single name to count BIC parameters -- a vector silently
reverted that count to the unstructured one -- and where all four
boot_lucid() paths read it back to refit. The early path now records the
geometry mclust actually fitted, as the parallel path already did. A serial fit
likewise records the geometry each stage resolved, rather than echoing the
caller's argument.
Unknown geometry names are now rejected with a message naming the valid set,
instead of surfacing from inside mclust as "mclust failed for specified
model". "auto" cannot be combined with other names in a per-layer vector,
since it is a whole-model instruction rather than one layer's geometry.
The vignette figures change, and the HELIX example cannot adjudicate them.
Every figure in the five vignettes was re-rendered and compared against a
pre-change render. No figure broke: 21 of 23 panels are populated in both, and
the two empty ones -- the methylation block of the continuous-outcome HELIX
tutorial, shown as a heatmap and again as a bar chart -- are empty in both,
because that layer's cluster means differ by less than 0.05 either way. Five
panels changed content. The clearest is the miRNA block: before, three features
separated strongly (about +/-1.5) and five were flat; now all eight separate
moderately (about +/-0.8), which is what a more parsimonious covariance
geometry does -- it spreads the signal over features instead of concentrating
it on a few directions. simulated_HELIX_data carries no latent cluster truth,
so neither solution can be shown to be the right one on that data. On simulated
data that does carry a truth, automatic selection is equal or better. Readers
using the HELIX tutorial as a worked example should know the figures are a
different, equally defensible solution rather than a corrected one.
What this does not fix. Geometry selection is not a remedy for clusters that
are not separated. At N = 800 with 50 features and AR(1)-correlated signal, the
correlation collapses the between-cluster Mahalanobis distance and both
"auto" and NULL select EII and reach ARI 0.000. "auto" is identical to
exhaustive search there, not worse; the claim is that it finds the best
available geometry cheaply, not that it recovers clusters in any regime.
boot_lucid()'s estimate column is the supplied model's own coefficient
for parallel and serial fits, not a throwaway refit's. boot::boot() derives
t0 by calling the statistic on the unpermuted rows, which refits the model
under a fresh seed and can land on a different local optimum. Only the early
branch replaced it, so for a parallel or serial fit every CI table reported
that refit's estimates and centred every normal interval on them
(boot.ci(type = "norm") uses 2*t0 - mean(t)). On a two-stage serial fit the
transition coefficient printed as 9.5698 where the model's own estimate is
9.7627; with init_par = "random" a parallel fit's cluster-to-outcome effects
came out as -0.0856/1.0879 against the model's 0.9897/0.3401. All three
branches now take t0 from the model, and a t0 that cannot be extracted
raises an error instead of silently blanking the whole table with NAs.
Bootstrapping a lucid() fit made with a penalty no longer describes a
different model than the point estimates. lucid() refits on the surviving
features and then restores the tuned penalties on $Rho for reporting;
boot_lucid() read that same field, concluded the model was penalized, warned,
and refit at zero penalty on whatever G/Z it was handed -- the full
feature set. With Rho_G = 0.05 the fit had 4 exposures, summary(fit) printed
4, and summary(fit, boot.se = ) printed 10, with different point
estimates. The penalty a fit's estimates were actually produced under is now
recorded separately as $Rho_fit (zero after a selection refit), which is what
boot_lucid() reads, and the bootstrap data is narrowed to the fitted feature
set from $selection.
align_replicate_serial() no longer silently discards cluster alignment for
3-or-more-stage models. perms[[s]] <- NULL deletes a list element and
shortens the list, so the re-referencing loop -- which indexes perms
positionally -- read the wrong stage's permutation or ran off the end
(subscript out of bounds at n_stage >= 3). The tryCatch added in the
previous release swallowed that error, so the replicate was used completely
unaligned, re-introducing exactly the label-switching contamination the
alignment exists to remove. Fixed with perms[s] <- list(NULL); an alignment
failure now warns, naming the model type, instead of passing unnoticed.
Bootstrap replicate validity is assessed per parameter, not per replicate.
normalize_parallel_beta()/normalize_parallel_mu() deliberately NA-fill
cells they cannot resolve, and one such cell marked every replicate invalid,
yielding an all-NA CI table plus the misleading "Only 0 valid bootstrap
replicate(s) remain". Replicates whose refit failed outright are still counted
and warned about; a parameter with too few finite estimates now loses only its
own interval.
f.binary.parallel() no longer mixes two models in one table. It took the
gamma column from the model and only the bounds from the bootstrap, so the
printed estimate and the interval around it could come from different fits, and
any row whose name failed to match became an all-NA line. It now consumes the
CI table whole, as f.binary.early() and f.normal.parallel() already did.
f.normal.early() strips the "Y." prefix a serial model's final stage
adds, so a serial normal fit no longer prints Y.LC2 under boot.se = and
cluster2 without it. This is the other half of 3.2.1's f.binary.early() fix.
summary() on a one-stage serial model no longer crashes.
seq.int(2, n_submodels) with one submodel is c(2, 1), so the loop ran with
i = 2 and dereferenced submodels[[0]]: "attempt to select less than one
element in get1index build_serial_transition_labels_boot().
An omics feature with no observed value in any row is now rejected with an
error that names it. The LOD initializer deliberately leaves such a column
NA (there is no observed minimum to halve) and check_na() only warns above
50% missing, so mclust received NA and failed with "missing value where
TRUE/FALSE needed", which tune_lucid() then reported as "LUCID model fails
to converge given current tuning parameters" -- pointing the user at the
penalty grid instead of at their data. Affected all three integration
strategies. The check runs before tuning, and tune_lucid()'s
all-candidates-failed message now distinguishes a structural data problem from
non-convergence.
The "log-likelihood decreased ... this indicates a numerical problem"
warning no longer fires spuriously on every penalized parallel fit. The
parallel EM's convergence and dip checks used the unpenalized
log-likelihood while its M-step maximized the penalized one, so a
Rho_G-penalized fit emitted the warning on iteration after iteration for a
decrease that is simply what penalization does. The loop now ascends a
penalized objective (parallel_penalty_value(), which penalizes the
precision matrix as glasso does -- the dead accounting inside
Mstep_XtoZ() penalized the covariance and was never read), and
fit$likelihood and loglik_trace remain the observed-data value. Where a dip
past the tolerated slack does occur, the message now says what it means: the
imputation step is a majorization and the penalized mean/covariance updates are
approximate maximizers (est_mu() is a single coordinate sweep), so small
decreases are expected and a large one points at a penalty too strong for the
data. It is also reported once per fit with a total, rather than up to 500
identical warnings.
summary.early_lucid()'s mu slice keeps its dimensions (drop = FALSE),
and summary_lucid_auxi()'s beta slice no longer recycles a short logical
index: c(TRUE, s1) is shorter than res_Beta's 1 + dimG + dimCoG columns,
so with CoG present R recycled it and silently kept the wrong columns.
has_unselected_feature() reads a parallel layer's selectZ as a feature
mask. It is a K x M per-cluster matrix, so a feature retained overall but
with a near-zero mean in one cluster blocked the bootstrap outright.
Conversely selectG_layer was never checked, so an exposure dropped in one
layer but kept in another passed undetected. Both fixed.
align_boot_vector() matches names partially instead of falling back to
positional filling for the whole vector. One unmatched name discarded name
alignment for beta, mu and gamma together and refilled by position --
indistinguishable from a correct replicate. Matched parameters are now placed,
the rest are left NA (and lose only their own interval), and a warning names
the offenders.
estimate_lucid() rejects a negative penalty instead of treating it as
"selection requested" via != 0 and handing it to glmnet/glasso.
lucid() already rejected negatives.
Mstep_GtoX() no longer leaks layer 1's cross-validated lambda into later
layers. With penalty = NULL, assigning the CV result back to penalty
meant layers 2..n were penalized at a lambda chosen for layer 1's data. Each
layer now cross-validates its own, and the per-layer values are returned.
boot_lucid() now aligns bootstrap replicates when a serial model's
upstream stage is itself a parallel submodel. align_replicate_serial()
previously only re-referenced a downstream stage's transition coefficients
when the upstream stage was an early-integration submodel; a parallel
upstream stage's replicate-to-reference cluster permutation was silently
discarded. A serial model with any parallel stage before its last now gets
the same bootstrap-CI correction early-only serial chains already had
(cluster labels aligned to the reference fit before coefficients are
stacked across replicates) for every stage-type combination.
estimate_lucid(lucid_model = "parallel", max_itr = 0) no longer
crashes. The parallel EM loop's bound (itr < max_itr) skipped the loop
body entirely at max_itr = 0, so res_Beta/res_Mu_Sigma were never
assigned and the fit failed with "object 'res_Beta' not found" instead of
the documented max-itr-exhaustion warning the early-model branch already
gives in the same situation.
get_selected_G()/get_selected_Z()'s layer argument now accepts a
layer name, as already documented, instead of only an integer index.
tune_lucid()/lucid() no longer crash when verbose is forwarded
through .... verbose_tune already controls estimate_lucid()'s own
verbosity during tuning; a caller who also passed verbose (e.g.
lucid(..., verbose = TRUE)) previously hit R's "formal argument matched by
multiple actual arguments" error. The colliding value is now dropped (with
a warning pointing at verbose_tune) instead of crashing the call.
summary_lucid_auxi()'s parallel branch no longer discards a supplied
boot.se (previously hard-coded to NULL).
(Amended in 3.3.1: the outcome ordering described here applies when the
outcome is used to fit the clusters, useY = TRUE. Models and stages fitted
without Y are ordered by expected cluster size; see the 3.3.1 section.)
The cluster-labelling contract is now pinned for every model type and both
outcome families. A mixture model's cluster labels are arbitrary, so LUCIDus
fixes them: the clusters that feed the outcome model are relabelled in order of
increasing outcome level, and every cluster-indexed block is permuted with
them. The behaviour was already in place; what was missing was coverage, and
with it any guarantee that it held outside the early model with a continuous
outcome. It is now asserted for early, parallel and serial, for family = "normal" and "binary", with no missingness, sporadic missingness and
list-wise missingness, and through the bootstrap.
What the contract guarantees, and is now tested:
beta, mu, Sigma, the outcome parameters, the
responsibilities and (where present) the per-cluster selectZ are permuted
together. This is the part that matters and the part that is hard to eyeball,
so it is tested by recomputing the posterior from the stored parameters with
predict_lucid() and requiring it to reproduce the fit's own
inclusion.p: an inconsistently permuted block cannot survive that. Under
sporadic missingness that comparison does not apply -- predict_lucid()
marginalises over the missing values while the fit integrates an imputation,
so the two differ by design -- and the test falls back to the M-step identity,
requiring responsibility column k to be the weighting that yields mu
row k, scored against a deliberately swapped permutation.An omics block must be a dataset of at least two features, and a block with
one is now refused on input. LUCID clusters a multivariate omics profile, so
a single feature gives the model nothing to find structure in; mclust also
reports one-column data in a univariate form (model names "E"/"V", means as
a length-K vector, variances as sigmasq) that the EM does not consume.
Previously such a block was accepted and then failed deep inside the algorithm
-- "subscript out of bounds" raised inside mclustBIC at initialization, or
"incorrect number of dimensions" several EM iterations later -- both reaching
the user through the "fails to converge given current tuning parameters"
wrapper, which points at the penalty grid rather than at the shape of the data.
check_omics_estimable() now rejects it up front, naming the offending layer or
stage (by name where the block is named) and saying what is required.
A penalty that would leave fewer than two omics features is treated as a
degenerate selection rather than fitted. This is the path that made the
problem reachable from ordinary use: variable selection refits on the surviving
features, so a strong enough Rho_Z_Mu/Rho_Z_Cov produced a one-feature
block, and it broke lucid()'s own documented selection example. The existing
all-features fallback now applies at a minimum of two rather than one, warns
that the penalty is too large, and records the outcome in $selection as
degenerate. Exposures are unaffected: G is not clustered, so a single
surviving exposure is still a valid fit.
The penalized M-steps now have oracle coverage. Eqs 14-16 were previously
checked only through their consequences. Eq 14 (the G -> X lasso) and Eq 16
(the glasso covariance) are solved by external optimizers, so they are verified
against the optimality conditions the equations assert -- independent of the
algorithm that found the solution -- and Eq 15 (the soft-thresholded cluster
mean) against a derivation written from the objective, which it matches to
1.3e-15. Each oracle is mutation-tested, so it demonstrably fails on a wrong
answer rather than merely passing on a right one.
One subtlety is now encoded rather than left implicit: est_mu() performs a
single Jacobi sweep, updating each coordinate against the incoming mu, so
it is an approximate maximizer by design and a stationarity check fails against
it even at Rho_Z_Mu = 0.
The BIC counting contract is pinned, and no BIC value changes. That
Rho_Z_Cov earns no degrees-of-freedom credit is Eq 18's own definition --
D - D_G - D_Z credits deselected variables, never covariance entries -- so
crediting glasso sparsity would be an extension beyond the paper; a test now
sparsifies the precision matrix and asserts the parameter count does not move.
The geometry-aware covariance count stays opt-in, with both paths tested.
summary() now prints the basis beneath the number:
BIC : 7621.83
basis: Eq 18 (one df credited per deselected variable), unstructured
covariance count; not comparable across lucid_model
Sankey figures are tested against the layout engine they actually ship.
With V8 available (now in Suggests; the tests skip without it),
networkD3's own bundled d3.sankey runs headlessly, so the rendered column
structure, node heights and link widths can be measured rather than predicted.
This confirms the R port of the layout that four existing tests depend on, and
checks that link width stays proportional to |effect| and that nodes neither
overlap nor leave the canvas.
NaN position. d3.sankey places a node at the value-weighted mean of its
neighbours without guarding a zero denominator, and a reference cluster's
inflow is zero by construction, so it divided 0 by 0 -- and the NaN
propagated to neighbouring nodes on later relaxation passes. This was
introduced in 3.3.0 by keeping zero-magnitude links so reference clusters
retain their inflow. Exact zeros are now floored to 1e-9 of the largest
width: sub-pixel on any canvas, and enough to keep the layout finite.When a penalty retains too little to fit, the model is refit on the whole
block -- and that is now said out loud. The fallback itself is unchanged and
correct; what was missing was any way for a user to know it had happened.
$selection recorded degenerate_G/degenerate_Z, but nothing read them, so
the recorded mask -- which describes what the penalty did -- was presented as
though it described the fitted model. At Rho_G = 0.2 on sim_data,
get_selected_G() returned all-FALSE ("no exposure was selected") for a model
that had used all 10 exposures, with no warning and no mention in summary().
get_selected_G() and get_selected_Z() now warn, and set
attr(, "degenerate") on the value they return, so programmatic callers can
branch without parsing a message.summary() prints a note under the selection counts, for all three model
types.glmnet's own lambda[1] (0.132 on
sim_data), so it costs one glmnet call in the degenerate branch only and
replaces trial-and-error with a number.degenerate_Z_blocks, mirroring
selectZ's shape, so a model says which layer or stage was degenerate.
Asking for a clean layer no longer warns about a degenerate sibling. The
existing scalars are unchanged.Rho_G's mapping onto glmnet's penalty scale was checked while fixing this
and is monotone (10 -> 8 -> 7 -> 5 -> 4 -> 4 along glmnet's own path; 6 -> 5
-> 4 -> 4 -> 0 end to end, the zeros flagged degenerate), and the single-lambda
glmnet() call in the G -> X M-step agrees with a warm-started path fit to
2.6e-5, so it was left as it is. A development note in the 3.3.0 report claimed
otherwise; it has been withdrawn, and the monotonicity is now a test.
Variable selection now follows one contract for all three strategies.
lucid() previously refit on the selected features and recorded what was
dropped for "early" only -- its flag_select_G/flag_select_Z were declared
inside the early branch. A penalized "parallel" or "serial" fit returned the
penalized candidate straight from tune_lucid(), so the coefficients a user
read off it were shrunk towards zero (with Rho_Z_Mu = 40, Rho_Z_Cov = 0.4
a layer's means came back at -0.798 where the unpenalized value is -1.006, and a
second layer was zeroed entirely), with nothing on the object recording which
features had been dropped. All three now select, refit unpenalized on the
survivors, and record $selection -- in the original feature space, so
FALSE marks a dropped feature. The refit carries the tuned fit's
init_omic.data.model, init_impute, init_par, n_starts and
outcome_penalty forward, which lucid()'s early refit previously dropped
unless they happened to be routed through ....
get_selected_G()/get_selected_Z() answer in the original feature space.
They read $select, which after the refit describes the reduced dimensions
and is all TRUE -- so on a fit that dropped 6 of 10 exposures they returned 4
TRUEs and the dropped exposures simply vanished rather than appearing as
FALSE. $selection, the honest record, had no readers anywhere in the
package. They now prefer it and fall back to $select for
estimate_lucid() output, which is never refit. get_selected_Z(stage = ) is
validated the way layer = already was.
A penalty that selects nothing now warns. lucid() fell back to using every
feature and then overwrote the record with an all-TRUE mask, indistinguishable
from "the penalty dropped nothing" -- the only signal was a cat() gated on
verbose_tune. It now warns and records degenerate_G/degenerate_Z in
$selection.
tune_lucid() tunes penalties for serial models. It refused a penalty
vector outright ("Tune LUCID in serial can't tune for multiple regualrities
for now!"), so a serial model could be fit with a penalty but never tuned
over one. A serial grid now crosses the K candidates with the penalty
combinations, scored by the same per-stage BIC sum, each candidate wrapped in
try(). Rho_G applies to stage 1 only, since a later stage's "G" is the
previous stage's cluster probabilities rather than an exposure. The serial
tuning table also gains proper column names and the Rho_G/Rho_Z_Mu/
Rho_Z_Cov columns its own documentation already promised -- it was an unnamed
one-column list-matrix plus bic.
The two selectZ criteria agree. The early M-step tested whether a
feature's cluster means differ (diff(range(mu)) > 0.001) while the parallel
M-step tested whether each cluster's mean is non-zero. A feature with
identical but large means across clusters was therefore deselected by early --
and dropped from its refit -- although the penalty had not shrunk it at all.
Eq 18 defines D_Z as the variables "whose effect estimates are 0 across all
latent clusters", so the early branch now uses the zero rule too. This changes
which features an early penalized fit drops in that one case.
plot() works for parallel and serial models. Both methods raised "The
plotting function of LUCID in Parallel and Serial is still under development".
plot.lucid_parallel() now draws exposures into each layer's own clusters,
those clusters into that layer's omics features, and every layer's clusters
into the shared outcome; plot.lucid_serial() follows the chain, drawing each
stage's transition coefficients into the next stage's clusters and the final
stage's clusters into the outcome. Both share plot.early_lucid()'s visual
language and appearance options. Cluster nodes are labelled with their layer or
stage, and an omics feature name occurring in more than one block is prefixed
so the two stay distinct nodes.
Two things were needed to make those diagrams publication-ready rather than
merely drawable. A reference cluster no longer floats into the exposure
column. Its coefficients are all zero by construction, those zero-magnitude
links were being dropped, and the Sankey layout -- which takes a node's column
from the longest path into it -- then placed a cluster node at the left edge
among the exposures. Zero links are now kept (as plot.early_lucid() always
did), so a parallel fit draws every layer's clusters in one column, as the
parallel topology requires, and a serial fit reads as a clean left-to-right
chain. New link_scale argument. Link width is proportional to
|effect|, but a Sankey has one width scale and LUCID's coefficient blocks do
not share one: exposure-to-cluster links are multinomial log-odds,
cluster-to-omics links are cluster means, and a serial model's
cluster-to-cluster transitions are regressions on a posterior probability
confined to [0, 1], which makes them tens of times larger -- 53x the median
link on the package's own example data. Left raw, they crush every other link
to a hairline. The default stays "raw" (the published convention, and
plot.early_lucid()'s output is unchanged), but it now warns when one
block's magnitudes dwarf another's by more than 20-fold, and
link_scale = "within_block" divides each block by its own maximum for a
figure that can actually be read.
A serial diagram now draws the pathway alone by default. plot() on a
serial fit shows G -> X1 -> ... -> Xm -> Y and no omics features, because
that is the structure a serial model exists to express and the one a Sankey can
show unambiguously -- see the next entry for why the omics could not simply sit
alongside. The omics arm is reachable with omics = "aggregate" (one node per
stage and layer), "features" (every feature) or "per_stage" (the original
layout), and belongs properly to plot_cluster_omic_profile(), which ranks
each stage's features by how strongly they separate its clusters.
Serial figures also default to link_scale = "within_block", where the other
methods default to "raw". A serial model's cluster-to-cluster transition
coefficients regress on a posterior probability confined to [0, 1], so on one
shared width scale they run 73x the largest exposure effect on this
package's own example data (max/median width spread 72.5) and flatten the rest
of the chain to hairlines. Each block is now scaled by its own maximum (spread
1.0, and no warning); link_scale = "raw" restores the unscaled widths and the
warning that explains them. plot.early_lucid() keeps "raw", matching the
published R Journal figure, and plot.lucid_parallel() keeps it too -- its
blocks are already comparable.
A serial diagram's columns no longer mix latent clusters with omics
features (relevant to the non-default omics modes above). A Sankey takes a node's column from the longest path into it, and
networkD3 exposes no way to override that (no nodeAlign/nodeDepth
argument, and it drops any extra Nodes column). So stage s's omics features
landed in the same column as stage s+1's clusters: on a six-stage,
two-layer fit, five of the eight columns each held 6 omics leaves beside 4
cluster nodes, and no column meant one thing. plot.lucid_serial() now takes
omics, defaulting to "aggregate": one omics node per stage (per stage and
layer when the stage is a parallel sub-model), labelled with its feature count,
with all of them pushed into a terminal column. That figure drops from 68 nodes
to 44, has no mixed column, and its tallest column is 13 rather than a 37-node
wall. The link into an aggregate node carries, per cluster, that cluster's
largest mean in absolute value with the sign kept -- the strongest separation
the block offers, the notion plot_cluster_omic_profile() ranks features by,
and documented as a derived summary rather than a coefficient.
omics = "features" keeps every feature (no mixed column, tall terminal
column), "none" draws the bare chain, and "per_stage" is the original
layout, kept reachable and documented as the one that mixes columns.
Fixing that exposed a second ordering defect of the same kind as the
reference-cluster inflow bug above. Stage s's predictor is the vector of
stage s-1's non-reference cluster probabilities, so a reference cluster
has no transition coefficient and therefore no outgoing transition link; with
the omics leaves pushed right, networkD3's rule "if all my targets are sinks,
I belong near the right edge" then dragged every reference cluster out of its
own stage and piled 14 of them into one column, splitting each stage's clusters
across two columns. The fixed-at-zero contribution is now drawn as a
zero-width link, exactly as the inflow case is, so each stage's clusters stay
together.
plot.early_lucid() and plot.lucid_parallel() are untouched -- parallel has
no mixed column, and is provably identical under either alignment mode.
Worked diagrams for all three strategies are in the vignettes: the
continuous- and binary-outcome 3-model tutorials each draw early, parallel and
serial side by side; lucidus_full_functionality_guide shows the three with
their node/link counts and explains how to read each topology; and
serial_6stage_parallel_monotone_missing_tutorial draws the hardest case the
method handles -- a six-stage chain whose every stage is a two-layer parallel
submodel.
fit$Z means the same thing for every strategy. It was the fitted
(imputed) omics for early and parallel but the raw input, NAs intact, for
serial -- so strategy-agnostic code had to know which. A serial fit now stores
its per-stage fitted blocks, still also reachable at submodel[[i]]$Z.
check_na() accepts lucid_model = "serial", returning a per-stage
breakdown; previously it was an error, even though a serial fit is where a
per-stage missingness picture is most useful. Its high-missingness warning now
names the layer or stage it is about -- a parallel fit reached the unlabelled
early branch once per layer, with no way to tell which -- and carries a
condition class, so tune_lucid() reports it once for the whole grid instead
of once per candidate per start per replicate.
A parallel fit's missing_summary carries the cross-layer view that
check_na()'s own parallel branch computes but no fit ever reached: the
proportion of missing cells pooled over layers, rows_missing_any_layer,
rows_missing_all_layers, and the joint across-layer pattern counts. The joint
view is what distinguishes a subject missing one whole layer -- who still
contributes to every other layer's E-step -- from one missing all of them.
A serial fit's missing_summary carries carried_forward: per stage, how
many subjects had no observed omics value at all. From stage 2 on, a stage's
"G" is the previous stage's posterior cluster probabilities, and such a subject
enters with full weight even though its posterior there carried no omics
information. Nothing recorded this, so the limitation was invisible; it is now
reported and documented.
A fit scores its own imputation. check_imputation_quality() was exported
but never called, so a fit whose imputed values landed far from the observed
ones reported nothing. When anything was imputed, missing_summary now carries
imputation_quality (per layer for parallel) and a failing score warns. The
score is computed from the observed-cell indicator the fit already has, so no
copy of the raw data is carried through the EM loop.
A serial summary reports model_info$K and model_fit$n_parameters, which
early and parallel already did; summary(fit)$model_info$K was NULL for
serial alone, and no serial parameter count existed at all.
The residual standard deviation of a continuous outcome is printed. The BIC charges one per cluster for an early fit and one overall for a parallel fit, and neither was shown anywhere, so a reader could not see the within-cluster outcome spread the cluster means sit in.
BIC's parameter counting is documented, and a geometry-aware count is
available. The covariance contribution is charged as K*M*(M+1)/2, the
unconstrained count, regardless of the mclust geometry actually fitted
(init_omic.data.model, default "EEV", has 25 free parameters where this
charges 30 at M = 5, K = 2; "EII" has 1). That inflates BIC, biases K
selection towards smaller K, and within one penalty grid favours penalized
candidates, which really do estimate unstructured/glasso covariances. The
default is unchanged so previously reported values reproduce exactly; set
options(LUCIDus.geometry_df = TRUE) or pass summary(fit, geometry_df = TRUE)
for the geometry-aware count. ?summary_lucid now also records that
Rho_Z_Cov earns no degrees-of-freedom credit (so tuning it alone can only
raise BIC), that Eq 18 subtracts one per deselected variable rather than its
whole block, that a lucid() fit's reported BIC is computed on the refit's
reduced dimensions and so need not equal the tuning table's, and that BIC is
not comparable across lucid_model.
The sporadic-missingness likelihood convention is documented. Under
integrated imputation the missing cells are treated as parameters, so once
imputed the density is evaluated at full dimension and fit$likelihood is that
objective rather than the observed-data likelihood: it is not comparable across
datasets with different amounts of missingness, and the BIC inherits that (the
imputed cells are not counted as parameters and N is charged in full).
predict_lucid() instead marginalizes over missing coordinates, so the same
subject's posterior can differ between fit time and predict time. Neither is
wrong; they are different, deliberately, and now said so in
?estimate_lucid.
safe_impute()'s role is stated correctly. Its own documentation and the
fill_data() @seealso described it as what initializes the EM algorithm. It
is not: initialization is init_impute (fill_data_lod() or
mclust::imputeData), and nothing in the package calls safe_impute(). It is
a user-facing utility, and the docs now say so.
boot_lucid()'s @return describes what each model type actually returns.
It promised beta/mu/gamma for every type, but a serial result carries only
stage and bootstrap. The new text also records that only normal and
percentile intervals are computed (never BCa), that the normal limits are
bias-corrected and so need not bracket estimate, and the new conf and
boot_status components.
Stale claims removed. R/lucid.R's "No regularity feature for LUCID in
parallel, All Z are selected" and two "not having regularity yet, to be
added" comments in R/summary.R were all false by 3.2.0. ?lucid,
?tune_lucid, ?estimate_lucid, ?check_na, ?get_selected_G,
?get_selected_Z, ?summary_lucid and the plot methods are updated
throughout, and boot_lucid/tune_lucid gain worked parallel and serial
examples.
New: estimate_lucid() warns when a cluster's outcome coefficient shows
signs of (quasi-)complete separation from a binary Y. LUCID's whole
purpose is finding clusters that associate with Y, so at small N a
cluster can end up (quasi-)perfectly separating the outcome -- an expected
risk, not a sign the fit is wrong. In that regime the logistic MLE is
finite but numerically extreme (very large odds ratios with very wide,
unreliable confidence intervals), and empirically R's own glm()
"fitted probabilities numerically 0 or 1"/"did not converge" warnings do
not reliably fire under the soft, continuous cluster-responsibility
weights the outcome M-step uses -- so estimate_lucid() now checks
cluster-effect coefficient magnitude directly (|log-odds| > 10) and warns
once per finished fit, for both the early and parallel model types, rather
than silently swallowing glm()'s own (unreliable) signal as before.
New outcome_penalty = c("none", "firth") argument to
estimate_lucid() (and threaded through tune_lucid()/lucid()/
boot_lucid()). "firth" fits the binary outcome model with Firth's
penalized-likelihood logistic regression (via the new Suggests
dependency logistf) instead of plain glm(), which keeps every outcome
coefficient finite and well-behaved under separation instead of just
warning about it, at the cost of a small bias toward the null on every
outcome coefficient (this is Firth's global bias-variance tradeoff, not
something applied only when separation occurs). Applies to the early and
parallel model types, and to a serial model's final (outcome-bearing)
stage; rejected with a clear error for family = "normal", which has no
separation to correct for. Default ("none") behavior is unchanged.
fit_early_outcome()'s binary-outcome glm() call now uses
glm.control(maxit = 100), matching fit_parallel_outcome()'s existing
explicit value (previously relied on R's implicit default of 25), so the
two model types are not needlessly inconsistent under a very slow-to-settle
fit.
boot_lucid() can run bootstrap replicates in parallel. New parallel
("no" / "multicore" / "snow"), ncpus, and cl arguments are forwarded
to boot::boot(). Each replicate is an independent LUCID refit, so wall time
drops roughly ncpus-fold. The default stays "no" (serial, identical to
before). For reproducible parallel runs, set RNGkind("L'Ecuyer-CMRG") and a
seed before the call. The point estimate (bootstrap$t0) is unchanged.
tune_lucid() can fit its grid in parallel. Same parallel / ncpus /
cl arguments; grid points are independent fits. The tuning table, the fitted
candidate list, and the selected model are byte-for-byte identical to a serial
run -- only the interleaving of console messages can differ.
Vignette: the comprehensive-guide vignette
(lucidus_full_functionality_guide.Rmd) gains a "Running the bootstrap and
tuning on multiple cores" section with a worked parallel = "multicore"
boot_lucid() / tune_lucid() example and the RNGkind("L'Ecuyer-CMRG")
reproducibility note.
One redundant E-step removed from every EM iteration. estimate_lucid()
recomputed, at the top of each iteration, the exact E-step it had already
evaluated at the end of the previous one (same parameters, same imputed Z,
and Estep() has no iteration-dependent term). That value is now carried
forward. Converged estimates, the log-likelihood trace, and iteration counts
are unchanged; the per-iteration cost of the E-step (per-cluster Cholesky /
eigen and multivariate-normal density evaluation) is roughly halved.
New dependency: parallel (base R) is now imported.
A correctness follow-up to 3.2.0, focused on boot_lucid() and summary().
Bootstrap CIs now align cluster labels. Each bootstrap replicate is an
independent refit whose latent cluster k need not be the point estimate's
cluster k. Replicate coefficient vectors were stacked by name/position anyway,
so any coefficient whose canonical cluster ordering was weakly identified -- a
parallel layer with a near-null cluster-to-outcome effect, an upstream serial
stage ordered by a single omics feature -- could get a bimodal or sign-split
interval spanning orders of magnitude. boot_lucid() now permutes every
replicate's clusters to match the reference fit (by posterior-probability
overlap on the resampled subjects) before extracting coefficients, so each
interval brackets its own point estimate. The point estimate (bootstrap$t0)
is unchanged.
summary() bootstrap CI tables.
(3) E) and binary-outcome ((1) Y) CI tables now
carry an odds-ratio view -- OR, OR_lower, OR_upper = exp() of the
coefficient-scale estimate and interval bounds -- alongside the
coefficient-scale columns. sig is still computed on the coefficient scale
(null = 0).OR
column is shown), the CI table says the columns are coefficients on the
log-odds scale with a bootstrap interval.(3) E CI table now shows the intercept and every covariate (CoG) row,
so it has the same coefficient rows as summary(fit) without a bootstrap --
previously those rows silently vanished when boot.se was supplied. The
covariate row is also now shown in the no-CI (3) E table for the parallel
and serial models, matching the early model.f.binary.early joins the bootstrap CI to the point estimate by row name
rather than by position.Log-likelihood labeling. The "Finished LUCID ... model: penalized
log-likelihood = X" completion message printed the unpenalized observed-data
value; it now says "observed-data log-likelihood". em_control$loglik_trace is
the unpenalized observed-data log-likelihood for every model type (it was the
penalized objective for a penalized early fit), so its last value equals
$likelihood; the penalized objective still drives the internal
convergence/dip check.
This release follows directly on 3.1.0's correctness pass. It narrows the
exported API to what a user actually calls, adds four extractor functions
for a fitted model's output, marks statistically significant bootstrap CI
rows in summary(), fixes several consistency and reliability issues across
model types, and reworks the tutorial vignettes into a polished, user-facing
set built entirely on the public API.
Breaking change. Five numerical-stability helpers
(check_and_stabilize_sigma(), safe_solve(), safe_log_sum_exp(),
check_convergence(), safe_normalize()) and fill_data() are no longer
exported. They were internal EM building blocks that happened to have a
CRAN manual page; their behavior is unchanged, and they remain reachable as
LUCIDus:::fn(...) for anyone who was calling them directly. The bare
plot() S3 generic LUCIDus declared is also removed -- graphics::plot()
already provides it, and plot.early_lucid() etc. still dispatch normally.
New: model-type autodetection. predict_lucid() and boot_lucid() no
longer require lucid_model -- it is now optional and is auto-detected from
class(model). Explicitly passing it still works exactly as before
(including the existing mismatch error when it disagrees with model's
class), so no existing call site is affected; it simply becomes unnecessary
to specify.
New: extractor functions. Four new functions read directly off a fitted model and auto-detect early/parallel/serial themselves, so no branching on model type is needed at the call site:
get_selected_G() -- the selected exposures, as a named logical vector.get_selected_Z() -- the selected omics features, shaped by model type
(a vector, or a list by layer/stage).get_cluster_assignment() -- each subject's hard cluster assignment.get_top_omics_features() -- the top-n most important omics features
per layer/stage, ranked by the same criterion plot_cluster_omic_profile()
uses.New: significance markers in summary(). Every bootstrap CI table
summary() prints when boot.se/se is supplied -- the exposure-to-cluster
table, the cluster-to-outcome table, and the cluster-specific omics-mean
table -- now includes a sig column marking rows whose normal-theory
interval excludes 0 with "*".
Bug fixes. The serial model's returned object is now consistent with
early and parallel: it reports a likelihood and a select field the way
the other two model types always have, a stray unused Rho_G penalty is no
longer silently applied where it has no exposures to act on, and its console
progress messages use the same wording and level of detail the other two
model types use. Several input-validation gaps that only showed up for
specific model types or specific entry points (estimate_lucid(),
tune_lucid(), predict_lucid(), boot_lucid()) are closed, so a bad input
is now reported with a clear message regardless of which model type or
function it went through, rather than surfacing later as a confusing
downstream error.
Reliability. Convergence checking is now handled by a single, shared routine for every model type, and the optimizer's log-likelihood is checked at every iteration to confirm it is actually improving, with a warning if it ever isn't. A handful of tuning and bootstrap code paths that could previously abort an entire multi-candidate run over one bad candidate now skip that candidate and continue, matching how the other paths already behaved.
Internal. Every internal (non-user-facing) function in the package now has real documentation explaining what it does, and source files have been reorganized and renamed so that related functionality lives together and file names describe their contents -- neither change affects behavior, and both are aimed at making the package easier to review and maintain. Several long-unused, dead code paths were also removed.
Vignettes. helix_early_parallel_workflow.Rmd is replaced by two
files, lucid_3models_normal_outcome.Rmd and
lucid_3models_binary_outcome.Rmd, split by outcome family (both still
demonstrate all three model architectures). Every vignette is rewritten as a
user-facing tutorial: custom code that reimplemented feature-selection
extraction, hard cluster assignment, or omics-importance ranking is replaced
by the new extractor functions and lucid_model autodetection, sections that
walked through internal-only functions (fill_data(), the numerical-stability
helpers) are removed, and each major step gains an explanation of what it
does, why it's needed, and how to read its output.
Packaging. The README.md is no longer shipped inside the package
tarball (it remains in the source repository), and the paper-reproduction
vignette (rjournal_paper_examples.Rmd) is no longer part of the package.
Example, vignette and test runtime is trimmed so a full R CMD check
completes well within CRAN's time budget: heavy examples run on small data
subsets with capped EM iterations, vignette bootstrap sizes are reduced, and
essentially the whole model-fitting regression suite is marked
skip_on_cran() -- those tests still run in full locally and in CI; only the
fast oracle, input-validation and tightly-capped smoke tests run on CRAN.
This release is a correctness pass over the estimation, missing-data, prediction, model-selection and inference paths, validated against the statistical definitions in the two LUCID papers:
These change numbers that version 3.0.x produced. Analyses run with 3.0.x may need to be re-run.
Reported log-likelihood was wrong. summary() reported a value that was
not the observed-data log-likelihood of the fitted model. For the worked
example in the R Journal paper (fit1 on simulated_HELIX_data), 3.0.3
reported -6721.801; the correct value at 3.0.3's own maximum-likelihood
estimates is -6575.88. The BIC printed alongside it inherited the error, and
also counted K*M^2 covariance parameters rather than the K*M*(M+1)/2 of
Eq 13. Both are now correct.
Outcome coefficients were mislabelled. res_Gamma$beta held the absolute
cluster means, but summary() printed them as if reference-coded
(cluster1 = 0, cluster2 = <value>), so the second row read as a
between-cluster contrast when it was that cluster's own mean. For the paper's
fit1, the printed 0.504 was cluster 2's mean; the actual contrast between
clusters is 1.044. Outcome parameters are now stored in both forms and
printed as an intercept (cluster 1's level) plus explicit contrasts.
predict_lucid() returned 0-based cluster labels. pred.x was
0, ..., K-1 while Eq 21, summary(), inclusion.p columns and the mu /
beta row names all use 1, ..., K. It now returns 1, ..., K for early,
parallel, serial and g-computation. Code that added 1 to pred.x must drop
that adjustment.
Penalized BIC now implements Eq 18. BICp = -2 logL + (D - DG - DZ) log N
subtracts one parameter per deselected variable. The previous
implementation rebuilt the model dimension from only the selected features,
removing whole mean, covariance and regression blocks, which could select a
different penalty and therefore a different final model. Note that D counts
the multinomial-logit intercepts, making it larger than Eq 13 as printed by
K - 1; the intercepts are genuinely estimated parameters.
K >= 2 was not checked on every path that fits or tunes a model.
lucid() checked it for early, tune_lucid()'s parallel branch checked it,
and estimate_lucid()'s serial branch checked it, but est_lucid() itself
(early and parallel) and tune_lucid()'s own early branch did not, so
calling estimate_lucid()/tune_lucid() directly with K = 1 -- both are
documented as directly callable -- reached deep EM machinery before failing
with an obscure error instead of a clear one. All four paths now share the
same check.
predict_lucid() validated its two branches asymmetrically. Early
checked that model was an early_lucid object; parallel had no analogous
check. Parallel checked that Z had the right number of layers; early
never checked that Z had the right number of columns, so a wrong-width Z
failed inside Estep_early() with a linear-algebra error instead of a
clear one. Both branches now validate both things.
boot_lucid() skipped validation the fitting functions it wraps already
enforce. None of its three branches called the same G/Y/CoG/CoY
completeness check lucid()/estimate_lucid() run, so a missing value
failed confusingly inside boot::boot()'s resampling callback instead of
with the package's normal top-level error; nor did any branch check that
model's class matched the lucid_model argument. Both checks are now
applied uniformly across all three branches.
tune_lucid()'s serial branch could crash on one bad candidate, and had
an unguarded tie-break. Early and parallel wrap each grid candidate in
try(), record NA on failure, and only stop() if every candidate
failed; serial did neither, so one non-converging K (e.g. too many
clusters for the sample size) crashed the whole tuning run, and picking the
best model (which(bic == min(bic)), no tie-break) would error on a
genuine BIC tie the way early/parallel are already written to guard
against. Serial now matches early/parallel's behavior exactly.
Serial Rho_G was applied to a stage's incoming cluster probabilities as
if they were exposures. From stage 2 onward, a serial fit's "G" input is
the previous stage's posterior cluster-membership probabilities, not the
cohort's actual exposures -- there is nothing there for an exposure-selection
penalty to select among. Rho_G was only reset to 0 when that stage's
incoming pseudo-G happened to have fewer than 2 columns, so a stage with 2 or
more forwarded columns (e.g. following a stage with K >= 4) was silently
penalized on a quantity that isn't an exposure. Rho_G is now forced to 0 for
every stage after the first, unconditionally. This changes numeric output for
that specific combination (nonzero Rho_G, a later stage with K >= 4
feeding forward >= 2 non-reference columns); it does not affect the more
common case already covered by the old guard.
A serial fit's likelihood and select were commented-out dead code.
R/EM_all.R's serial results list referenced loglik_update, selectG,
selectZ and Estep_r, none of which are ever assigned in the serial
branch -- copy-paste leftovers from the early/parallel branches, left
commented out. fit$likelihood and fit$select now exist on a serial fit,
matching early and parallel: likelihood is the sum of each stage's own
log-likelihood (matching the existing, previously summary()-only
cal_loglik_serial()), and select is stage 1's own selection (the only
stage whose selectG is a real exposure-selection result, per the fix
above); the complete per-stage record remains at
fit$submodel[[i]]$select and fit$submodel[[i]]$likelihood. The dead #z = line is removed rather than resurrected: nothing in the package reads
z even where it already exists, on parallel fits.
check_convergence() was exported, documented and tested, but never
called. Early and parallel each ran their own abs(old - new) < tol
convergence check instead. Both now call the shared, tested function.
No log-likelihood trace was ever checked for monotonicity. A decrease
beyond a small, majorization/selection-aware slack now raises a warning()
naming the iteration (or serial stage) and the two values, for all three
model types -- previously nothing would have surfaced a real ascent
violation short of manually inspecting em_control$loglik_trace.
Serial's verbose output mixed "Sub Model" and "Stage" naming for the same concept, and never showed a log-likelihood. The pre-stage banner now says "Stage N/M" consistently, and both the verbose and concise per-stage finish lines report that stage's log-likelihood, matching early/parallel's own per-iteration reporting.
A second round of console-output inconsistencies, found while auditing
the rest of the package for the same pattern. lucid()'s tuned-selection
messages and tune_lucid()'s "Tuning LUCID model" banner printed
unconditionally instead of respecting verbose_tune; predict_lucid()'s
g-computation notice printed unconditionally instead of respecting
verbose, and its verbose argument otherwise did nothing for early/
parallel prediction while serial always printed regardless of it -- early
and parallel prediction now report progress under the same flag serial
already did. predict_lucid()'s serial per-stage message also still said
"Sub Model Number = N", the phrasing already replaced with "Stage N/M"
everywhere else. The three "fit completed" messages ("Success: Early Integration LUCID converges!" / "Success: LUCID in parallel converges!"
/ "Success: LUCID in Serial Model is constructed!") and estimate_lucid()'s
own two differently-worded serial "Fitting..." banners are now one
consistent pattern each.
A serial fit's inputs were not validated for completeness at the top
level. check_complete_input() (the G/Y/CoG/CoY missing-value guard) was
called from lucid() and from the early path, but not from EM_all.R's
serial orchestration -- a missing value was only caught once stage 1's
nested fit re-validated it, reporting the error as coming from inside a
sub-fit. It is now called once at the top of the serial branch.
predict_lucid() failed whenever lucid_model was not named explicitly.
The model type was resolved with match.arg() only inside the branch tests,
while the unresolved default -- the full vector
c("early", "parallel", "serial") -- was forwarded to the internal worker,
whose own choices are c("early", "parallel"). Every such call died with
'arg' must be of length 1. This is exactly how the R Journal paper documents
prediction in Section 3.5 (predict_lucid(model = fit1, G = ..., Z = ...)),
so that example had never run as printed, in this version or in 3.0.3. The
argument is now resolved once, at entry.
Prediction with sporadically missing omics. Rows containing NA were
passed to a full multivariate Gaussian density. For the early model this
returned a uniform posterior for every affected row; for the parallel model it
raised NA/NaN/Inf in foreign function call. Both now evaluate the correct
marginal density on the observed coordinates, which also makes a fully
unobserved row reduce to the list-wise partition of vbae123 Eq 11.
Parallel penalized exposure model discarded posterior mass. glmnet's
multinomial fit returns one coefficient block per class, and f_GtoX() then
prepended a further zero reference row, producing K + 1 states. The E-step
used only the first K, silently dropping roughly 33% of the probability mass
at K = 2 and 25% at K = 3. Coefficients are now rebased onto a single
reference class and stored as K - 1 rows.
Parallel penalized omics selection never deselected anything. The
indicator OR-ed in colSums(abs(Sigma)) > 0.001, which is always true for a
valid covariance. Selection is now driven by the cluster means, and parallel
penalized estimation uses the same estimator as the early model (L1-penalized
means via the graphical-lasso precision matrix).
Variable selection could abort before returning a model. When exactly one
exposure survived selection, lucid() carried the tuned Rho_G into the
refit, where the lasso requires at least two exposures, and the call failed.
The refit on selected features is now unpenalized; the tuned penalties and the
original selection are retained on the fitted object ($Rho, $selection).
init_impute = "lod" fabricated omics values. Rows with no measured omics
at all were filled with LOD/sqrt(2) and returned in fit$Z, unlike the
"mix" path which restores them. Estimation was unaffected, but the returned
data were not. All initializers now restore fully-missing rows to NA.
Bootstrap t0 was a random refit. The observed-data statistic re-estimated
the model under a random seed, so bootstrap$t0 need not equal the model
passed in and summary(fit, boot.se = ...) could print an estimate column
inconsistent with summary(fit). t0 is now taken from the supplied model.
Failed bootstrap replicates were silent. Replicates returning non-finite
estimates were dropped without notice, quietly reducing the effective R --
most likely with missing data, where a resample can contain too few rows with
complete omics. Failures are now counted and warned about. A small number of
replicates also raises a warning that the limits are unstable (Davison &
Hinkley suggest R >= 200 for normal and R >= 800 for percentile intervals).
Neither suppresses the limits: they are reported as NA only when fewer than
min_valid replicates survive, which defaults to 2 -- the point below which
a standard deviation and an order-statistic interval are undefined rather than
merely imprecise. boot_lucid() gains a min_valid argument for callers who
want a stricter rule.
Cross-layer missingness summary. check_na(..., "parallel") reported the
unweighted mean of per-layer missingness rates rather than the proportion of
missing cells; a fully-missing 1-feature layer beside a complete 9-feature
layer reported 0.50 instead of 0.10.
Bootstrap replicate failures no longer print raw error dumps. The
per-replicate refit was wrapped in capture.output(), which redirects stdout
while try() writes to stderr, so a failed replicate printed a raw
Error in est_lucid(...) trace even though the failure was handled. Two
sibling call sites already passed silent = TRUE; the third now does too.
Recovered failures no longer print raw error dumps. When the penalized
exposure model could not be fitted (for example glmnet reporting
Null probability for class 1 < 1.0e-5 on a near-degenerate cluster), the
code correctly fell back to unpenalized estimation and warned -- but the
underlying try() was not silent, so the raw C++ error text was also printed.
A single document could emit a dozen of these, each looking like a failure
when nothing had actually gone wrong. The fallback warning is unchanged; only
the spurious error text is gone. Affects Mstep_G(), the parallel
Mstep_GtoX(), and the early tuning loop.
Bootstrap confidence-interval tables no longer collapse to a vector when there
is a single exposure or K = 2.
Penalty tuning no longer performs recursive list indexing when several candidate models tie on BIC.
glasso is no longer called when Rho_Z_Cov = 0, where it reduces to the
empirical covariance but emitted a rank warning on every cluster, layer and
iteration (hundreds of identical warnings per fit).
lucid_serial fits now report whether they converged. A serial fit runs
no EM loop of its own, so its em_control carried only the stopping controls
(tol, max_itr, max_tot.itr). A stage that exhausted max_itr was
therefore invisible unless the user inspected every submodel[[i]]$em_control
by hand. em_control now also reports converged (TRUE only when every
stage converged), n_iter (the total across stages), and the per-stage
submodel_converged and submodel_n_iter.
summary() on a serial fit no longer returns duplicate components. The
returned list appended a second copy of BIC and loglik under names it
already used, so it held two entries for each. $BIC resolved to the first,
making the copies unreachable, but str() output looked malformed and
name-based iteration visited them twice. The duplicates are removed; $BIC,
$loglik and the legacy $summary.list alias are unchanged.
Missing or non-finite values outside the omics data are now rejected.
LUCID models missingness in Z; a missing value in G, Y, CoG or CoY
was handled by no code path at all. A single NA in Y did not error --
the fit ran on without converging, and where it did return, the outcome
parameters were badly wrong with nothing in the output to indicate it. These
four inputs are now checked for NA, NaN and infinite values before
fitting, with an error naming the input and the number of offending values.
Z is unaffected and may still be missing.
init_omic.data.model = NULL now works for the parallel model. The
documented automatic-selection value could not be used: R/em.R built the
per-layer geometry names with rep(init_omic.data.model, length(K)), and
rep(NULL, n) is NULL, so the names were lost between initialization and
the M-step. mclust::mstep() then received modelName = NULL and failed,
reaching the user as "LUCID model fails to converge given current tuning
parameters". The selected geometry is now read back from the mclust fit and
reported on init_omic.data.model, one entry per layer. Random
initialization, which has no fit to read, falls back to "EEV" as the early
path does. The same line also used rep() where rep_len() was meant, so a
per-layer vector of names was expanded to length(K)^2 entries.
init_impute and init_par are recorded as resolved values. A serial fit
taking the defaults stored the unevaluated c("mix", "lod") and
c("mclust", "random") -- a record of a choice that was never made, which a
bootstrap refit reading those fields would carry forward.
predict_lucid() now enforces one rule for the omics input. Z is
required for every model type; only g_computation = TRUE relaxes it, because
that mode predicts from the exposure path alone. Previously each model type
validated separately, and serial got it wrong: the check comparing
length(Z) with length(K) ran before the is.null(Z) check, and
length(NULL) is 0, so a forgotten Z was reported as
"Z and K should be two lists of the same length" -- sending the user to
inspect their stage topology rather than the argument they omitted. The
is.null branch was unreachable. All three model types now give the same
message, and it names g_computation so the error states the rule.
A single-stage serial model is now declined at prediction with an
explanation. lucid(..., lucid_model = "serial", K = list(2)) fits, but
predict_lucid() failed on it with object 'pred.y' not found: the stage
loop branches on first / middle / last, and a single stage is simultaneously
first and last, so it takes the first branch and never reaches the assignment
of pred.y. Such a model is a fully equivalent early or parallel model, so
prediction now stops with a message saying so. Known limitation: making
one-stage serial genuinely predictable requires restructuring the stage loop
so its inputs depend on being the first stage and its outputs on being the
last, independently; that is not done here.
plot_cluster_omic_profile() shows what the clusters are. plot() draws
the path structure; summary() prints the cluster means as a table. Neither
answers the question a reader asks first -- which omics features separate the
clusters, and in which direction. The new function draws that, for early,
parallel and serial fits, as a cluster-by-feature heatmap in the style used
for single-cell markers, or as bars. A parallel or serial fit returns one
plot per omics layer, named, so no figure has to hold every layer at once.
Features are ranked by an importance measure, "separation" by default: the
spread of the cluster means divided by the typical within-cluster spread. The
simpler alternatives "range" and "sd" use the means alone and so cannot
distinguish a feature that separates the clusters from one that is merely
noisy. Each returned plot carries the data it drew -- feature, cluster, mean,
within-cluster SD and score -- as the attribute "profile_data".
This adds ggplot2, scales and grDevices to Imports.
Convergence diagnostics. Fitted objects carry
em_control$converged, $n_iter, $n_restart and $loglik_trace. Reaching
max_itr without meeting the tolerance previously returned silently as though
it had converged; it now warns and records converged = FALSE.
Multiple random starts. n_starts (default 1) runs independent EM
initializations and keeps the fit with the highest observed-data
log-likelihood, with per-start values in em_control$start_loglik. EM reaches
only a local optimum: in testing at K = 3, five starts on one dataset spanned
23 log-likelihood units, and a single start returned a solution whose reported
exposure-outcome effect was five times too small.
Deterministic cluster ordering for unsupervised stages. Upstream stages of a serial model have no outcome to order by, so their cluster numbering was seed-dependent and the reported transition coefficients were not reproducible across runs on identical data. Such stages are now ordered lexicographically by their omics cluster means.
The imputation step now uses responsibilities recomputed at the updated parameters, restoring the ascent property of the E-M-I cycle.
The reference documentation was reviewed against the code function by function. The substantive corrections:
estimate_lucid() documented one return object where there are three. A
single numbered list described early, parallel and serial alike. It
listed em_control twice with contradictory contents, promised a likelihood
that serial did not yet return at the time (see the Bug fixes entry above --
it does now) and an N that early does not, and omitted missing_summary,
res_Delta and z altogether. The @return is now split into components
common to every fit and components specific to a model type.
lucid() duplicated that list rather than referring to it, and the copy
had drifted. It now cross-references estimate_lucid() and documents the
selection component, which records what the tuned penalties dropped and was
previously undocumented.
tune_lucid() now documents the tuning table's columns, its alignment
with the returned model list, and that its optimum is the penalized fit --
lucid(), not tune_lucid(), performs the unpenalized refit, so estimates
read directly from best_model are shrunk.
fill_data() described the wrong estimator. It is not an average of
per-cluster conditional means; it solves a single precision-weighted system
over the missing coordinates, which reduces to the Gaussian conditional mean
only when K = 1. The weights are also not the supplied p but p
reweighted by each cluster's density at the subject's current values.
Stub descriptions such as "List containing detailed missing data analysis"
were replaced with the actual components, conventions and edge-case behaviour
for summary_lucid(), summary.lucid_parallel(), summary.lucid_serial(),
the print methods, check_na(), analyze_missing_pattern(),
check_imputation_quality(), safe_impute() and the stability utilities.
predict_lucid() now states that pred.x runs 1, ..., K; code written
against the pre-3.1.0 0, ..., K - 1 labels must drop its adjustment.
plot() documents its appearance options and their defaults, and states that
the parallel and serial methods raise an error pending implementation.
gen_ci(), Istep_Z() and summarize_missing_stats() are internal but were
generating public help pages; they are now @noRd.
log_dmvnorm_observed() evaluates Gaussian densities on observed coordinates,
grouping rows by missingness pattern, and is shared by training and prediction.penalized_cluster_block() used by both the early and parallel M-steps.helper-oracle.R) and a
canonical data generator (helper-sim.R) rather than object-shape assertions.tests/testthat.R had test_check() commented out, so R CMD check ran none
of the suite. It is enabled; the suite runs in roughly three minutes.safe_solve() and safe_log_sum_exp() were each defined three times, and
safe_normalize() and check_and_stabilize_sigma() twice, across utils.R,
stability_utils.R and 00_stability_preload.R. The bodies agreed, so
behaviour was unaffected, but the roxygen sat on a copy that collation then
overwrote. Consolidated to one definition each in stability_utils.R.early_estep.R,
which forced a collation order. It is now a call-time wrapper, so no
load-order coupling remains.safe_solve() gains threshold and safe_normalize() gains min_val, both
always supported by the internals but dropped by the exported wrappers.reorder_z() / reorder_lucid() in R/summary.R were dead code -- never
called anywhere, and referencing field names (res_Delta$Delta,
res_Mu_Sigma) that no current class has. Removed."log-likelihood" /
"penalized log-likelihood" instead of "loglike" / "penalized loglike",
matching parallel's own wording; this is a console-output-only change, not a
numeric one.get_ref_cluster(),
reorder_Delta(), reorder_Mu_Sigma(), reorder_Beta() (R/summary.R,
the functions the already-removed reorder_z()/reorder_lucid() used to
call), print.sumlucid_auxi() and print.auxi.serial.scen1/2/3() (S3
methods registered in NAMESPACE for classes never assigned to any object,
so they could never dispatch), parallel_marginal_design(),
make_positive_definite()/is_positive_definite() (superseded by
check_and_stabilize_sigma()/safe_solve()), fill_data_help1()/
fill_data_help2(), initialize_Beta(), and early_estep() (a full
duplicate of Estep_early()) -- all confirmed to have zero call sites
anywhere in the package. check_K(), found dead in the same sweep, was kept
and wired in instead (see Bug fixes); plot.lucid_parallel()'s ~100 lines
of Sankey-plotting code after its unconditional stop() (unreachable) were
also removed, and plot.lucid_serial/plot.lucid_parallel now share the
same trimmed shape.