
Fit a log-concave factorization with automatic rank selection
Source:R/logconNMF.R, R/conditional_counts.R, R/simultaneousNMF.R
logconNMF.RdEstimate ordered, nonnegative log-concave profiles and channel loadings from one signal or several related samples. The information criterion selects the number of components. Simultaneous fits share spectra while retaining the original scan grids and estimating a separate profile and area for each occurrence.
Usage
logconNMF(
y,
X = NULL,
family = poisson("identity"),
lambda = "gic",
background = NULL,
dispersion = NULL,
theta = NULL,
precluster = "auto",
weights = NULL,
offset = NULL,
correlation = NULL,
ncores = NULL,
control = list(),
start = NULL,
path = NULL,
align = TRUE,
method = c("cosine", "hellinger"),
verbose = FALSE,
time = NULL,
objective.trace = FALSE,
truth.profiles = NULL
)
conditionalSolverAvailable()
# S3 method for class 'logconNMF_fit'
coef(object, sample = NULL, normalize = c("none", "l1"), ...)
# S3 method for class 'logconNMF_fit'
fitted(object, sample = 1L, ...)
# S3 method for class 'simultaneousNMF'
plot(
x,
type = c("areas", "spectra", "profiles"),
sample = NULL,
compounds = seq_len(min(6L, nrow(x$P))),
...
)
sampleNMF(object, sample = 1L)Arguments
- y
A numeric scans-by-channels matrix or vector for one sample, or a list of at least two sample descriptions for a simultaneous fit. Each description contains
yand increasingtime, with optionalX,background,fit,weights,offset,exposure,dispersion,theta,sample_id,group,small_widthandedges. Supply observations, weights, offsets or initial fits as RDS paths to read them from disk. Samples share channel names and order. List names supply sample IDs when the descriptions omitsample_id.- X
Candidate profile matrix for a single sample, such as the sparse design from
estimatePSF(). In a simultaneous fit, supply it in each sample description or let the simultaneous initializer estimate it.- family
Identity-link noise family:
gaussian,poisson,quasipoisson,mgcv::nb,Gamma,nb1(),gammaScale()orgammaCensored(). The corresponding names, including"nb","nb1"and"Gamma_scale", are also accepted. Count likelihoods require integer counts; quasipoisson accepts nonnegative intensities. Gaussian observations may be negative; their fitted latent signals remain nonnegative.- lambda
An information criterion (
"gic","aic","bic","ebic"or"mbic") or a nonnegative numeric penalty per selection degree of freedom, before any temporal information adjustment. With the general solver and \(m\) channels, a single component incurs \(m\lambda\); in a simultaneous fit a shared spectrum incurs \((m-1)\lambda\) and an occurrence incurs \(\lambda\).- background
Optional nonnegative scans-by-basis matrix, for example
splines::bs(time, df=6, intercept=TRUE). Coefficients are nonnegative and unpenalized.NULLfits without a background.- dispersion
Known common Gaussian variance, quasipoisson scale, Gamma dispersion, NB1 variance-to-mean ratio or common Gamma scale.
NULLestimates a pooled value from temporal differences and freezes it. Parameters supplied in a signal_families object are used when this argument is omitted. Poisson and NB2 use unit dispersion.- theta
NB2 shape, shared by all original channels.
NULLestimates and freezes a temporal moment estimate; a positive value fixes it; a negative value initializes at its absolute value and enables pooled likelihood updates. A fixed shape in the supplied NB family is respected.- precluster
Maximum channel groups or a saved
channelGroups()map."auto"uses the original channels for a single sample and up to 32 common groups for a simultaneous fit.FALSEorNULLdisables aggregation. Final fits use every original channel.- weights
Nonnegative likelihood weights: a scalar, row vector or matrix matching
y.NULLuses one. Zero weights omit observations.- offset
Known nonnegative mean contribution, in the same supported formats as
weights.NULLuses zero. It is included on the response scale because the link is identity.- correlation
Lag-one working information adjustment.
NULLuses the fitter's default ("auto"for one sample and"none"for simultaneous fits), orcontrol$correlationif supplied for a simultaneous fit.- ncores
Total core budget.
NULLuses physical cores for one sample and logical cores for simultaneous fits. Grouped PSF regressions divide this budget between samples and native threads. The conditional count solver then reuses it for sample-specific profile and background updates and disjoint ion columns of the shared spectra, with one BLAS thread per worker. Setncores=1Lfor a serial fit.- control
Named controls. In both fitting modes,
refinement_sweeps(default 0) requests extra alternating updates. Withselective=TRUE, long refinements revisit every component on the first, every tenth and the final sweep. Between these audits they update components whose relative profiles or spectra changed by at least 0.0001 on the last audit. The local search also schedules initial and post-matching sweeps this way. Setselective=TRUEexplicitly for early scheduling with other controls. Partial sweeps hold the background fixed. Native count fits check apparent convergence with a full update.selective=FALSEuses full alternating sweeps throughout.penalty_search=TRUEproposes deletions at four times the fitted penalty and refits at the original penalty. The count solver also tests occurrence re-entry. The retained model must improve the original-channel criterion. This additional search defaults to FALSE. With zero extra sweeps and a single PSF dictionary, count fits first try removing a weak occurrence and refitting up to two overlapping log-concave profiles. If a shared spectrum still qualifies for removal at the higher penalty, the solver refines the connected profiles with the remaining compounds in the offset. Across samples it also tests one shared spectrum for similar identities with overlapping aligned half-height intervals, refitting their neighbours.fit$refinementrecords the before and after criteria and search work.alternative_Xenables a second blind PSF initialization. Supply a PSF design, one design per sample in input order, or TRUE for blind estimation. Joint conditional count fits pool total signal on a common time grid, estimate a time-varying PSF and transfer it to each native grid. Other fits estimate the alternate PSF per sample. Both runs use the primary noise specification, original data and price. The general solver keeps the better complete fit. The conditional count solver also exchanges overlapping groups of factors between fits, across all samples, when the original criterion decreases.fit$restartrecords both scores and the final score. The default NULL incurs no second fit. Disk-backed fits share one store of observations. SeesplogconNMF()for one matrix. The conditional count solver uses up to 12 initial sweeps, stopping at a relative improvement of 0.001. For a general simultaneous fit,cycles=10Landinitial_cycles=5Lset refinement limits,rounds=3Lsets the number of grouping rounds, andq=64Lsets the initial profile update resolution. After a cross-sample match, each local profile is refined on all original channels using the hard shape constraint offitLogConcaveProfile(). Its window extends two local PSF full widths at half maximum on either side of the initial support. The defaultrt_tolerance=NULLandalignment_window=NULLderive matching windows from the narrow-peak widths.ridge=TRUEchecks the profile ridge across samples. The remaining defaults arecensor=0.5,correlation="none",workers=NULLandcache=FALSE.initialpasses controls to the independent initial fits and defaults tolist(initial_relaxed=FALSE); single-sample fits default to a relaxed grouped-support initialization.workerslimits concurrent samples withinncores. Conditional grouped regressions use a memory-aware worker cap. Both batch solvers store original observations on disk. The general solver can optionally cache aggregated observations withcache=TRUE. Supplyingcache=FALSEexplicitly selects general likelihood updates for count data.workers=1Lprocesses one initialization at a time. Setinitial=list(initial_solver=list(solver="eigen", method=3L, precond=1L))to request iterative component selection for every sample. The solver'smax.memorybudget covers Gram/factor workspace, not total process RAM.- start
Optional list
H,Sandalpha, with original dimensions.Hhas scans in rows and compounds in columns;Shas compounds in rows and all original channels in columns.alphacontains background coefficients and defaults to zero. Profiles are normalized with the inverse change applied to spectra. A restart bypasses initial screening and preclustering; nonnegative spectral entries can reopen during refitting.- path
New directory for the sample store and fitted factors in a simultaneous fit.
NULLuses a temporary directory.- align
Estimate monotone time warps for a simultaneous fit.
- method
Spectral distance for matching simultaneous samples, either
"cosine"or"hellinger".- verbose
Print stage timings, objective changes and compound counts.
- time
Increasing scan coordinates for a single sample. Defaults to scan index. Supply native time in each descriptor for a simultaneous fit.
- objective.trace
Record the penalized quasi-deviance after each conditional block. The default avoids the cost of those measurements.
- truth.profiles
Optional simulation diagnostic for the conditional Poisson and quasi-Poisson solver. For one sample supply a scan-by-compound matrix or a simulation record with
H, compoundidand optionaltime. For multiple samples supply one such entry per sample, in input order or named by sample ID. Match compounds across samples with column names orid. Unnamed matrices must have the same columns in the same order. AsimulateGCMSSamples()result can be passed directly. Zero columns indicate absence. Each positive column is normalized to unit area. To satisfy the same constraint as the fit, the reference uses the least concave majorant of its log heights on the native scan grid and normalizes the result. This preserves log-concave input shapes. Areas, spectra and backgrounds are estimated from the observations. Both fits record their block traces. An active reference receives at least as many full profile and spectrum sweeps as the blind fit. Retrieve the empirical optimality gap in GIC relative to the truth-initialised fit and plot both trajectories withfit$gic_gapandplot(fit$gic_gap). SeegicGap().- object
A fitted model returned by
logconNMF().sampleNMF()takes a simultaneous model.- sample
Sample index or ID. For a single matrix use
1Lor"sample1". Incoef(),NULLreturns the common spectra for a simultaneous fit. Inplot(),NULLdisplays all samples.- normalize
"none"returns amplitude-scaled loadings."l1"returns unit-sum rows.- ...
Further arguments passed to the underlying extractor.
- x
A fitted simultaneous model for plotting.
- type
Plot sample areas, common spectra or aligned compound profiles.
- compounds
Compound indices to display in a simultaneous plot.
Value
A fitted object with estimated rank, the number of single-sample
components or shared components. Use coef(), fitted() and GIC() in
either mode. fitted() returns one sample on its original grid. A
simultaneous fit includes consensus spectra P, sample-by-compound areas,
compounds, alignment, paths, store, channel_groups and
parallel thread allocation.
Details
Rank-selection objective. The fit approximately minimizes
$$-2\sum_s \ell_{\nu_s}(M_s;Y_s) + \kappa\lambda d.$$
The weighted log-likelihood \(\ell_{\nu_s}\) uses the fitted mean
\(M_s\) on the original channels of sample \(s\). For quasipoisson
it is the Poisson log score divided by the sample's estimated or supplied
dispersion. The optional working temporal adjustment is \(\kappa\),
equal to one under independence. A numeric lambda sets the penalty per
selection degree of freedom. The GIC preset uses \(\log(p)\log\log(n)\),
with the PSF dictionary width and number of scans for a single matrix.
For a sample list the preset uses \(p=n=\sum_s n_s\).
For the conditional count solver the complexity is the sum of the number of
positive ions minus one per normalized spectrum and the dimension of every
positive log-profile face (two endpoints plus interior slope changes).
fit$conditional_objective reports quasi-deviance and both dimensions.
An absent occurrence has zero cost. Finite support proposals and alternating
conditional updates give a local optimum candidate. For the general solver,
for one matrix with \(m\) channels and \(K\) components,
\(d=mK\). For a simultaneous model, \(d=(m-1)G+L\), where \(G\) is
the number of shared unit-sum spectra and \(L\) counts the detected
sample-specific component occurrences. Each spectrum contributes \(m-1\)
coordinates and each occurrence contributes one amplitude. Setting
\(G=L=K\) gives the single-sample count. Profiles have contiguous
support and a concave logarithm on the positive interval. Profile shapes
and smooth backgrounds carry no additional rank charge.
The simultaneous objective and reported information criteria such as GIC()
also count estimated noise parameters. The single-sample objective
drops that constant charge for a fixed noise specification. Local
refinement and fusion, deletion or addition of candidate components
provide the approximate rank search.
Final single-sample refinement also tries broader local starts for nearly
coincident profiles. Compatible Poisson/quasipoisson fits use their existing
channel groups for preliminary screening; completed candidates and controls
are always refined and checked on every original channel. Other cases retain
full-channel screening. This is enabled
by default. For one matrix, control=list(profile_restarts=FALSE) disables
the pass; simultaneous fits pass this option through control$initial.
For a simultaneous fit, put background, weights, offset and any initial
fit in the sample descriptions. path = NULL uses a new temporary
sample store. Supply a persistent path when saving a simultaneous fit for later
use, and retain the store with the fitted object.
Numeric penalties in logconNMF() have the same scale in both modes.
To reproduce a single-sample splogconNMF() call using a numeric compound
penalty, divide that penalty by the number of channels.
Simultaneous models
Ignoring backgrounds, exposures and offsets, the sample means have the shared-factor form \(M_s = Q_s P\), with one common spectral factor \(P\) and sample-specific profile/area factors \(Q_s\). This follows the simultaneous-NMF terminology of Cichocki et al. (2009) and Lee et al. (2012).
Samples can supply separate background bases, known exposures and noise
parameters. With a time warp \(u=w_s(t)\), binwise Jacobian \(J\),
and exposure \(e\), the fitted mean on the original grid is
$$\mu_{sij}=e_{si}\{J_{si}\sum_g a_{sg}h_{sg}(u_{si})p_{gj}
+(B_sA_s)_{ij}\}+o_{sij}.$$
Spectra sum to one and the profiles integrate to one on the aligned grid.
Unit exposure models the supplied intensities. Use known integration
durations as exposures for integrated counts. Scan spacing and
small_width use the same time units.
Reciprocal spectral matches provide leading-edge alignment anchors.
Compatible occurrences share spectra after checking overlap and profile
shape in area order. At most one occurrence of a compound enters each
sample. Local profile, spectral and background updates compare the
full original-channel likelihood. Undetected occurrences have NA
areas. Noise scales are held fixed when comparing groupings. A negative
NB2 theta allows bounded, likelihood-improving shape updates.
The common channel map is learned from samples aggregated on common time
bins. For conditional Poisson and quasi-Poisson updates, each injection's
counts, background and fitted means occupy temporary tiled files. Profiles
store their active scan intervals. Registration loads one candidate spectrum
table alongside the reference, and rank search reads local original-ion
windows. Spectral coefficients are shared across samples and updated in ion
blocks. options(logconNMF.scratch=...) selects the scratch parent directory.
Two optional workspace budgets, logconNMF.profile_MiB (1536) and
logconNMF.stripe_MiB (768), control sweep blocking. A single sample
or ion column sets the minimum block size. Process memory also includes
initialization workers, shared factors and export objects.
The general identity-link solver retains its family-specific likelihood and
streams original-channel blocks in multisample models. A general-family fit
called with a single matrix uses that matrix in memory. An individual PSF
initialisation can load one sample per active worker. Absolute likelihoods retain their normalizers.
Keep the store with the saved fitted object for reconstruction and plots.
Extract one sample
sampleNMF(object, sample) returns a single-sample factorization view.
The view contains unit-sum original-grid profiles in H, matching
amplitude-scaled spectra in S, its fitted background, integrated areas
in integrated_area, and consensus IDs in compound_id. Alignment and
exposure are included in the profiles and spectra. Use coef(),
fitted() and GIC() on the returned view. The view carries no observed
matrix.
Automatic solver selection
Poisson and quasi-Poisson fits with unit weights and exposure and zero
observation offset use conditional updates of profiles, spectra and background.
Other noise families, weighted or offset models, and joint fits requesting
control = list(cache = FALSE) use the general identity-link solver.
Examples
X <- convMatrix(convKernel("gaussian", 9L), 50L)
signal <- cbind(700 * X[, 16L] + 350 * X[, 35L],
150 * X[, 16L] + 500 * X[, 35L])
set.seed(12)
Y <- matrix(rpois(length(signal), signal), nrow(signal))
fit <- logconNMF(Y, X = X, ncores = 1L)
fit$rank
#> [1] 2
coef(fit, normalize = "l1")
#> [,1] [,2]
#> compound1 0.8090323 0.1909677
#> compound2 0.4328358 0.5671642
second <- matrix(rpois(length(signal), 1.4 * signal), nrow(signal))
samples <- list(first = list(y = Y, time = seq_len(nrow(Y)), X = X),
second = list(y = second, time = seq_len(nrow(Y)), X = X))
joint <- logconNMF(samples, ncores = 1L)
joint$rank
#> [1] 2
joint$areas
#> compound1 compound2
#> first 775 871
#> second 1163 1202
fitted(joint, sample = "second")[1:3, ]
#> 1 2
#> [1,] 1e-08 1e-08
#> [2,] 1e-08 1e-08
#> [3,] 1e-08 1e-08
second_fit <- sampleNMF(joint, sample = "second")
second_fit$compound_id
#> [1] 1 2
coef(second_fit)
#> 1 2
#> compound1 948.1631 214.8369
#> compound2 515.4742 686.5258