
GC/MS deconvolution for large multi-sample batches
Source:vignettes/articles/multisample.Rmd
multisample.Rmd
Point gcmsDeco() to an experiment directory to fit
shared compound spectra and a separate log-concave elution profile for
each occurrence. It returns an area table for all injections and a
consensus spectral library. Each chromatogram keeps its own scan times,
calibration and background.
On 16 full simulated chromatograms, the blind fit recovered 1,000 of 1,000 compounds and 8,000 of 8,000 peaks, with zero false positives. Reading, fitting and exporting the batch took 29.03 seconds per sample on a 64 GB laptop with 16 logical processors, with a peak working set of 6.77 GiB.
Set up and fit an experiment
chromatograms/
standards/
alkanes.cdf
beer1/
injection001.cdf
injection002.cdf
beer2/
injection003.cdf
library(GCMSprime)
experiment <- gcmsDeco("chromatograms", output_dir="beer_results",
family=quasipoisson("identity"), precluster=32L,
batch=list(plots=TRUE))
experiment$samples
experiment$areas
coef(experiment, normalize="l1")
GIC(experiment)
plot(experiment, sample=1L, type="lines", file="sample1_traces.pdf")The standards subdirectory is reserved for calibration
chromatograms. Analytical samples are sorted using their acquisition
timestamps, including time-zone information. Group labels come from
their relative directories. Each sample uses the nearest alkane standard
in acquisition time. A single standard can calibrate the whole
experiment. Supply alkanes_file to select a particular
calibration.
For files without acquisition timestamps, supply their relative paths in the intended run order.
experiment <- gcmsDeco("chromatograms", output_dir="beer_results",
batch=list(sample_order=c("beer1/injection001.cdf",
"beer1/injection002.cdf",
"beer2/injection003.cdf")))
Aligning and fitting the samples
The initial regression uses a common set of ion groups to match peaks between injections. Each sample has its own time-varying PSF. Monotone retention maps align candidate peaks, after which the model estimates a common spectrum for each compound and a separate log-concave profile wherever it occurs. The GIC charges once for the free positive ion proportions of a shared spectrum and separately for each fitted profile. Rank-selection objective
Scan spacing and exposure
Observed matrices stay on their native scan grids. Monotone alignment changes profile coordinates and bin widths; its Jacobian preserves integrated peak areas. The model is evaluated directly at the original scan times.
By default, GCMSprime models the vendor’s exported intensities with unit exposure. Quadrupole acquisition distributes scan time across the mass range. The effective time per mass also depends on scan step size, scan averaging and acquisition settings. Agilent method documentation. ANDI files can contain arbitrary abundance units, so scan duration and the number of exported mass peaks alone do not identify physical count exposure.
If integrated counts and their durations are known, supply exposure explicitly.
experiment <- gcmsDeco("chromatograms", output_dir="count_results",
family=poisson("identity"),
batch=list(exposure=function(metadata, time) metadata$scan_duration))Here scan_duration is appropriate only when it
represents the integration duration of each reported count. A calibrated
per-mass duration can instead be returned by the function. Metadata
vectors are restricted to the fitted scans. With an identity link,
exposure multiplies the latent mean. It is incorporated into profile and
background design values during fitting.
Inspect and export the results
The output directory contains the following files.
-
samples.csv: acquisition order, group, calibration file and sample result paths. -
areas.csv: integrated compound areas, withNAfor undetected occurrences. -
consensus.msp: the common spectral library, using the shared 0.1% base-peak cutoff. -
experiment.xlsx: sample information, consensus compounds, packed spectra and areas. -
experiment.rds: the experiment object. -
samples/<sample_id>/: fitted sample RDS, NIST-compatible MSP and Excel results, plus trace and heatmap PDFs whenbatch$plots=TRUE.
Spectral text cells are unwrapped and list fragments by decreasing
intensity. Sample objects retain factor matrices and CDF paths. The
initial grouped regressions run in parallel over samples, subject to the
available RAM and the total core budget. During the joint count fit,
logconNMF keeps observations and fitted means on disk. It reads local
scan windows for profile updates and blocks of original ions for the
shared spectrum and background updates. Both operations use OpenMP. Use
batch=list(workers=4L) to cap file-import and PSF worker
counts. For this workflow, experiment$parallel$workers and
experiment$parallel$threads describe the grouped PSF
regressions. ncores sets the total thread budget for joint
refinement.
To reuse an ion grouping learned from a pooled time-binned
chromatogram or from reference spectra, pass the saved channel map
through precluster. Channel
groups
sample1 <- readRDS(experiment$paths[1L])
sample1$compounds
plot(sample1, type="profiles", file="sample1_profiles_spectra.pdf")
fitted(experiment, sample=1L)The simultaneous NMF tutorial gives the mathematical model, alignment, spectral grouping, local updates and the full 16-sample example, including the two-start GIC diagnostic and reproduction code.
Automatic rank recovery on full chromatograms
We simulated 16 full chromatograms of 10,000 scans × 550 ion channels (m/z 30–579), about 50 minutes per injection. Each of the 1,000 compounds occurred in eight randomly chosen samples, giving 8,000 peaks in total. Of these compounds, 990 had exponentially modified Gaussian (EMG) peaks and ten had shark-fin acid peaks. Both broadened with increasing concentration. The simulation included overdispersed counts, a smooth background, up to 2.93 seconds of retention drift and about 2% variation in scan spacing.
GNPS/MSHub estimated 1,414 shared components, 41.4% above the generating rank. The other five workflows report per-sample peaks or aligned feature groups. A dash indicates that the workflow reports no common factorisation rank.
| Workflow | Seconds/sample | Estimated rank (true 1,000) | TP (sensitivity) | FP | FN | Acid TP / 80 | Median absolute area error, % [P25, P75] |
|---|---|---|---|---|---|---|---|
| GCMSprime | 29.03 | 1,000 (exact) | 8,000 (100%) | 0 | 0 | 80 / 80 | 0.095 [0.041, 0.197] |
| MS-DIAL | 16.02 | — | 7,728 (96.6%) | 11,685 | 272 | 73 / 80 | 13.94 [5.86, 26.39] |
| mzmine GC-EI | 6.92 | — | 4,202 (52.5%) | 185 | 3,798 | 29 / 80 | 6.41 [2.51, 14.23] |
| eRah | 25.94 | — | 7,172 (89.7%) | 5,615 | 828 | 70 / 80 | 12.03 [5.62, 25.70] |
| AMDIS | 28.99 | — | 7,878 (98.5%) | 9,122 | 122 | 80 / 80 | 20.74 [14.34, 33.82] |
| xcms + CAMERA | 4.22 | — | 7,261 (90.8%) | 890 | 739 | 31 / 80 | 29.70 [23.15, 38.41] |
| MSHub | 15.05 | 1,414 | 7,179 (89.7%) | 12,184 | 821 | 50 / 80 | 15.42 [5.96, 35.47] |
For each correctly matched peak we calculated the absolute difference between estimated and true area as a percentage of its true area. Brackets give the 25th and 75th percentiles across those peaks.
All seven workflows received the same CDFs. The time for each is one full run divided by 16, including required input conversion and native analysis. For GCMSprime this included PSF calibration and results export. Simulation and accuracy scoring ran separately.
We calibrated the PSF against a separately generated 20-peak
standard, grouped the ions into 32 channels for initial screening and
allowed up to eight parallel sample initialisations. The benchmark
enabled local rank search with
batch = list(workers = 8L, coupling = list(penalty_search = TRUE)).
The blind fit used the observed data throughout. Its final original-ion
GIC was 32,610,830.
Stage times · Timing and peak memory
The fitted peaks followed the concentration-dependent broadening in both peak classes. Across all 8,000 occurrences the median profile cosine was 0.999994, the median absolute peak area error was 0.095% [0.041%, 0.197%] and the adjusted R² for log₁₀ peak area was 0.999982.
To compare whole elution profiles, we chose the EMG compound and the acid with the largest total simulated area in their respective classes before examining any fit. Solid curves show fitted profiles and dashed curves the simulated profiles, in total-ion intensity per scan. Colours run from low to high simulated area. Each compound occurred in eight samples and had zero true intensity in the other eight. The mean profile cosine includes all eight positive occurrences, with a missed peak scoring zero.
Seven-workflow comparison and reproduction code.
Convergence behaviour
On the 16 chromatograms the blind fit showed smooth, monotonic descent in the original-ion GIC over eight sweeps. Its final GIC differed by only 0.19% from that of a second fit started at the true elution profiles and compound identities and run for the same eight sweeps. Both fits estimated spectra, areas, elution profiles and background from the observed counts.
The curve joins 29 recorded updates. Several can occur within a sweep as the active set changes. The percentage gap is the absolute difference in final GIC divided by the magnitude of the truth-initialised fit’s GIC.
Earlier attempts at automatic NMF or NTF best rank recovery
L0glm selects candidate peaks jointly across ions by fitting a grouped L₀ regression on a time-varying PSF dictionary as a sequence of convex adaptive-ridge subproblems. With peaks aligned across samples, logconNMF updates the active set of compounds and retains deletions, residual-supported additions and fusions of neighbouring features when they lower the GIC on the original ions.
Among the published tests of conventional NMF on noisy simulated data that we reviewed, the largest rank recovered exactly was 150, which Squires et al. selected by minimum description length on a 1,000 × 2,000 matrix. Squires et al., Figs. 1–2
In chromatographic applications of MCR-ALS, PARAFAC and PARAFAC2, analysts typically specify candidate ranks and inspect the fitted spectra, elution profiles and residuals. A common practice is to divide the chromatogram into windows containing roughly one to ten components. Bro & Kiers · Johnsen et al. · van Stokkum et al.
We found no earlier published demonstration of a simultaneous chromatographic factorisation that selected 1,000 distinct compounds and verified their identities across all 8,000 occurrences. For example, the PARAFAC2-based GC–MS workflow PARADISe fits one retention window at a time. By default it evaluates models with one to eight components per window, including any components used for the baseline. The user can raise that upper limit. The rank of 1,000 recovered across the full batch is 125 times the default upper rank for a single PARADISe window. Johnsen et al. · PARADISe protocol, §12.1
Comparing a single injection with the joint fit
The multiset MCR window comparison uses the same acid-containing scans in sample 002 alone and in all 16 injections together. It includes independent rank diagnostics, fits with a supplied component count and PSF warm starts, and measures the cost of full-chromatogram windowing. Multiset MCR and tensor benchmarks
Calibrated beer example
An alkane standard supplies narrow peak shapes for both full
chromatograms. The conditional count workflow estimates a pooled
time-varying PSF and transfers it to each sample’s observed scan times.
In this example, calibration_range=c(6, Inf) excludes the
solvent and early contaminated region from PSF calibration; the
analytical samples retain their full time range and all 518 measured
mass channels.
standard <- "chromatograms/standards/alkanes.cdf"
experiment <- gcmsDeco("chromatograms", output_dir="beer_results",
alkanes_file=standard, calibration_range=c(6, Inf), precluster=32L,
ncores=8L, batch=list(workers=2L))
# Use the calibrated narrow-peak width for onset-based RI coordinates.
reference <- readRDS(experiment$paths[
grepl("54040014_a", experiment$paths)][[1L]])
cal <- calibrateRI(standard, carbon=7:23, psf=reference$psf_standard)
experiment <- annotateRI(experiment, cal, phase="DB5",
msp_file="beer_results/consensus.msp",
xlsx_file="beer_results/experiment.xlsx")A 26-column spline basis with ion-specific nonnegative coefficients allows the background spectrum to change through each chromatogram. The fit used four threads per worker and retained 642 shared identities and 1,077 occurrences.
| Sample | Occurrences | Dispersion | Sample quasi-GIC | Adjusted weighted R² |
|---|---|---|---|---|
| 502131900304_a | 549 | 631.78 | 14,331,151 | 0.98415 |
| 54040014_a | 528 | 617.21 | 15,129,017 | 0.98334 |
The joint quasi-GIC was 28,544,609, with each shared spectrum charged once. The two beer CDFs took 314.37 s from input through export. Preparation and PSF calibration took 141.05 s, grouped regression and joint refinement 166.28 s, and result construction and export 6.60 s. RI calibration added 3.01 s and RI annotation and export added 3.57 s, bringing the total to 320.95 s before plotting.
Using the Agilent NIST records, a ±30 RI window and a minimum spectral cosine of 0.85, the two beers yielded 209 and 203 distinct reciprocal identifications. There were 90 and 71 additional forward assignments to identities already called in the respective samples. These are tentative identifications in beers of unknown composition.
Diagnostic ions identify all 17 alkanes from C7 to C23. The retention coordinate is the 1%-height onset plus half the local narrow-peak width at that height. The natural cubic RI curve passes through all accepted alkane anchors exactly. MSP files contain phase-labelled DB5 indices; the consensus library uses their medians. Values outside the accepted calibration range remain unassigned.
The full beer fits still contain residual fragmentation and occasional overly broad profiles in difficult overlapping regions. Component counts are estimates under the fitted model, rather than a verified inventory of chemical compounds.
The following panels zoom into the 4.5–6 minute region of these full-chromatogram fits. They are not separately fitted cropped windows. Grey lines show observed ions after subtracting the jointly modelled background; coloured lines are the fitted compounds.


The fitted components can be inspected sample by sample, and common
spectra can be searched against a library with each sample’s
alkane-derived retention indices. Pass library= and
search= to gcmsDeco() to include those
identifications in per-sample MSP and Excel exports.
Set coupled=FALSE to export independent fits. Set
batch=list(resume=TRUE) to reuse independently fitted
samples whose source-file metadata and fitting settings match the cache.
Simultaneous refinement is then computed from those fits.
See GCMSbatch for options and single-sample deconvolution for diagnostic plots, profile fitting and spectral recovery.
100-sample scalability benchmark
The 100 full chromatograms contained 10,000 scans and 550 channels each. Every one of the 5,000 distinct simulated compounds occurred in ten randomly chosen samples. This held the mean density at 500 peaks per sample (452–539) while reducing the proportion of samples containing each compound from 50% to 10%. The fitter received the CDFs and an independent PSF standard. The spectral library, retention-index scoring key and true profiles were reserved for simulation and validation. It used 32 initial mass-channel groups, original-ion refinement and automatic local rank search.
| Quantity | Result |
|---|---|
| True / estimated shared rank | 5,000 / 5,003 |
| True compounds with at least one reciprocal detection | 5,000 / 5,000 |
| True positive / false positive / missed occurrences | 50,000 / 1 / 0 |
| Sensitivity / precision | 100% / 99.998% |
| Shark-fin acid occurrences recovered | 500 / 500 |
| Median absolute peak area error, matched peaks (% [P25, P75]) | 0.062 [0.028, 0.119] |
| Median absolute peak area error, matched acids (% [P25, P75]) | 0.066 [0.027, 0.133] |
| Original-ion quasi-GIC | 243,809,331.9 |
| Elapsed time per sample / whole batch | 80.15 s / 133.58 min |
| Sampled peak process-tree working set | 8.095 GiB |
The run used 16 logical processors and included PSF calibration, reading the CDFs, building the dictionary, rank search and native exports. Truth scoring ran afterwards. The GCMSbenchmark scorer compared every called spectrum to all 5,000 references in each of the 100 samples and awarded one credit per reciprocal match within ±30 retention-index units at cosine ≥0.70. The shared rank counts fitted spectral factors across the batch. For 4,997 compounds, a single fitted factor accounted for all ten occurrences. The other three compounds each received two identities across their ten positive samples (9 + 1, 9 + 1 and 8 + 2). The one false-positive occurrence was a call for compound 4,886 in sample 29, where it was absent. Simulation, code and measured results


