Skip to contents

l0glmData() separates matrix storage from model selection. SIS/ISIS reads predictors in bounded blocks, then L0glm fits the retained working design using its ordinary or special-family engine. The original predictor count determines the GIC preset and score, and returned coefficients retain the original sparse dimensions. This works with Gaussian and other GLMs, negative binomial, multinomial and Cox models, including weights and offsets.

One interface for large matrices

library(L0glm)
set.seed(18)
X <- matrix(rnorm(100*2000),100,2000)
y <- 2*X[,1]-2*X[,2]+rnorm(100)
source <- l0glmData(X,control=list(block.cells=20000,max.cells=30000))
fit <- l0glmFit(source,y,screen='SIS',nsis=20L,lambda='gic')
coef(fit)[which(Matrix::rowSums(coef(fit)!=0)>0),,drop=FALSE]
#> 2 x 1 sparse Matrix of class "dgCMatrix"
#>           
#>   1.791184
#>  -1.913258

For a large file, replace the constructor while keeping the model call:

genotype <- l0glmData('genotypes.bed',n=4000L,p=1733480L)
fit <- l0glmFit(genotype,case_status,family=binomial(),screen='SIS',nsis=1000L)

assay <- l0glmData('cells.h5ad',dataset='counts')
fit <- l0glmFit(assay,response,family=poisson())

assay <- l0glmData('cells.h5seurat',dataset='assays/RNA/counts')
assay <- l0glmData('cells.loom')
source <- l0glmData(bigmemory::attach.big.matrix('matrix.desc'))

H5AD, h5Seurat and loom adapters put observations in rows and genes in columns. Generic HDF5 datasets retain their supplied orientation; transpose can be set explicitly. Sparse HDF5/DelayedArray assays retain sparse working blocks. The HDF5 adapters use optional HDF5Array, DelayedArray and rhdf5 packages. Native bigmemory access uses the bigmemory and BH headers when building L0glm; bigmemory is loaded only when that storage backend is requested.

Double-precision bigmemory designs are screened directly through their existing native mapping, using read-only access. Each OpenMP worker reads its assigned columns without first copying them into an R matrix. Subsets retain the original row and column indices, and screening statistics and tie handling match resident matrices. Other storage types and mean-imputed data use bounded column blocks.

Subsetting with drop=FALSE creates a view. as.matrix() makes an explicit bounded read. An unscreened working design, the retained fit matrix and requested outputs must fit the configurable max.cells guard. Full-design IRLS on an arbitrarily large tall matrix still requires a dedicated streamed solver; the current interface keeps that memory requirement explicit. For plain LASSO, the native biglasso adapter below can fit a complete double bigmemory design.

One million predictors on disk

The resident example uses 1,000 observations and 60 nonzero effects. With l0glmData() the same Gaussian construction can be extended to 10,000 observations and one million predictors, while generating and reading the design in bounded blocks. A double-precision backing file occupies 80 GB; the active fitting problem is much smaller.

Run the following from an empty working directory with enough disk space. Only a block of 256 predictor columns is generated at a time. The random number sequence matches matrix(rnorm(as.double(n)*p), n, p).

library(L0glm)
library(bigmemory)
L0glm::l0glmThreads(blas = 1L)
n <- 10000L
p <- 1000000L
backing <- filebacked.big.matrix(nrow=n,ncol=p,type="double",
  backingfile="normal.bin",descriptorfile="normal.desc",backingpath=getwd())
set.seed(123)
for(first in seq.int(1L,p,by=256L)) {
  j <- seq.int(first,min(p,first+255L))
  backing[,j] <- matrix(rnorm(as.double(n)*length(j)),n)
}
active <- sample.int(p,60L)
beta <- numeric(p)
beta[active] <- runif(60L,-.8,.8)
set.seed(1)
y <- drop(backing[,active,drop=FALSE]%*%beta[active])+rnorm(n)

# The descriptor can be reattached in a new R session.
training <- seq_len(8000L)
test <- 8001:10000
X <- l0glmData(attach.big.matrix("normal.desc"),control=list(
  block.columns=4096L,block.cells=length(training)*4096,max.cells=1e8))
system.time(fit <- l0glmFit(X[training,,drop=FALSE],y[training],
  family=gaussian(),intercept=TRUE,screen="ISIS",screen.nthreads=8L))
l0glmMetrics(fit,beta_true=beta)[
  c("gic","TP","FP","FN","TN","F1_score","MCC")]
sqrt(mean((predict(fit,X[test,,drop=FALSE])-y[test])^2))
Seconds GIC TP FP FN TN F1 MCC Test RMSE
248.72 24652 50 1 10 999939 0.901 0.904 0.993

Generating the 80 GB file took 488.31 seconds, excluded from the fitting time.

The first 8,000 rows are used for screening and fitting, and the remaining 2,000 rows assess prediction. The model includes a free intercept. Screening reads the native mapping with eight threads; repeated candidate fits also use a resident pool of 10,000 screened predictors, occupying 640 MB. Four global screening scans are sufficient here. The GIC preset and every support score use the original one million predictors. Generation and fitting times are recorded separately. The complete reproduction script creates a reusable descriptor and response cache and reports the screening history. The response, truth and descriptor should be saved together when continuing in a new session.

For large complete double-precision bigmemory designs, Gaussian ISIS can cache up to control$working.columns columns (default 10,000), bounded by control$max.cells. The ordinary global ISIS trajectory is retained, and a cached candidate replaces its best fit only when the original-data GIC improves. Identical consecutive Gaussian coefficients avoid another redundant full-file scan. Set working.columns=0L to use the ordinary global path without a resident candidate pool. Weights, offsets and compulsory terms retain their specified meaning; other families and fitting options use the regular screening path.

On this dataset, screen.maxit=2L gives the same support, GIC and test RMSE in 123.96 seconds, with coefficients agreeing to numerical precision. This explicit two-round budget is useful when disk scans dominate; the default retains further global convergence checks.

Compare with native file-backed LASSO

The optional biglasso solver fits plain LASSO directly on the same backing file. Its native row-index interface also reuses the file across cross-validation folds. screen="none" keeps all predictors available; biglasso still uses its own screening rules to accelerate the convex LASSO path. The shared sparseGLM() interface selects lambda using the same likelihood and information-criterion code as the other methods.

install.packages("biglasso") # once
comparison <- sparseGLM(X[training,,drop=FALSE],y[training],family=gaussian(),
  method="biglasso",screen="none",intercept=TRUE,tune="bic",nlambda=10L,
  options=list(ncores=8L,lambda.min=.05),beta_true=beta)
l0glmMetrics(comparison)[c("method","seconds","gic","TP","FP","F1_score","MCC")]
sqrt(mean((predict(comparison,X[test,,drop=FALSE])[[1]]-y[test])^2))

# The same file supports training-row cross-validation without dense copies.
cv <- sparseGLM(X[training,,drop=FALSE],y[training],family=gaussian(),
  method="biglasso",screen="none",intercept=TRUE,tune="cv",nfolds=5L,
  nlambda=10L,options=list(ncores=8L,lambda.min=.05))

Biglasso includes a free Gaussian/logistic intercept. For a matched comparison, give both methods a free intercept. The reproduction script uses a GIC preset and ISIS for L0glm, while LASSO selects from ten native lambda values using BIC. Both models train on 8,000 rows and predict the same held-out 2,000 rows. Both methods read the backing matrix directly, and neither copies the full design into an R matrix.

Method Selection Seconds GIC TP FP FN F1 MCC Test RMSE
L0glm GIC preset 248.72 24652 50 1 10 0.901 0.904 0.993
biglasso LASSO BIC path 792.32 25933 51 3 9 0.895 0.896 1.074

L0glm’s ISIS fit takes 4.15 minutes, compared with 13.2 minutes for the full-predictor biglasso LASSO path: 3.2 times faster, with lower GIC, fewer false positives and lower held-out RMSE. Biglasso’s BIC minimum is the ninth of ten grid points (lambda=0.05690), so the lower endpoint does not determine the result. The complete BIC path retains every candidate’s support size and score. These single-run timings include disk access; file caching and storage speed affect them substantially.

The comparison script records fitting and selection time, including common path scoring, separately from final recovery metrics and test predictions. CV is available through the same interface; the table reports BIC selection. Gaussian offsets and zero-weight row exclusions are supported. Biglasso requires unrestricted coefficients; non-unit positive weights and non-Gaussian offsets are excluded explicitly. SIS/ISIS can also be applied to biglasso and the other sparseGLM() methods.

Packed genotypes and logistic GWAS

PLINK 1 variant-major BED stores four hardcalls per byte. The native screening kernel computes the same family-specific scores directly from these two-bit calls, with deterministic OpenMP reduction across predictors. The selected genotypes are decoded only for the smaller fitting problem.

This reproducible logistic example has 4,000 observations, one million independent variants, six main effects and one pairwise interaction. Minor-allele frequencies range from 0.1 to 0.5, and diploid genotypes are generated in Hardy-Weinberg equilibrium. The BED file occupies 1 GB, versus 32 GB for the decoded double-precision matrix. The simulator writes matching BIM and FAM files, so the dataset can also be opened with PLINK. The FAM file encodes controls as 1 and cases as 2; the saved R response uses 0/1.

From the checkout root, run:

source("benchmarks/benchmark_filebacked_gwas.R")
results <- benchmark_filebacked_gwas(n=4000L,p=1000000L,
  cache="codex_sandbox/filebacked_gwas")
results[c("method","seconds","gic","TP","FP","FN","F1_score","MCC",
  "interaction_recovered","test_AUC","test_logloss")]

The R script and its small C++ simulator contain the full simulation, including the random seeds. Packed calls are written directly to disk, without constructing a dense genotype matrix. For an existing BED file the fitting calls are:

prefix <- "codex_sandbox/filebacked_gwas/gwas-4000-1000000"
simulation <- readRDS(paste0(prefix,".rds"))
y <- simulation$response$y
offset <- simulation$response$offset
X <- l0glmData(paste0(prefix,".bed"),n=4000L,p=1000000L)
training <- seq_len(3200L)
fit <- l0glmFit(X[training,,drop=FALSE],y[training],family=binomial(),
  intercept=TRUE,offset=offset[training],screen="ISIS",screen.nthreads=8L,
  interactions=1L)
fit$interactions$history
GIC(fit)
coef(fit)[which(Matrix::rowSums(coef(fit)!=0)>0),,drop=FALSE]
predict(fit,X[3201:4000,,drop=FALSE],offset=offset[3201:4000])

Set screen="SIS" for one marginal screen and interactions=0L for main effects alone. Pairwise products are generated among selected main effects; they are stored in the model recipe and constructed only when needed. The example deliberately includes main effects for both interacting variants.

Method Seconds GIC TP FP FN F1 MCC Interaction recovered Test AUC Test log loss
SIS 3.28 2971 6 0 1 0.923 0.926 No 0.830 0.437
ISIS 7.94 2971 6 0 1 0.923 0.926 No 0.830 0.437
ISIS + interactions 10.62 2906 6 0 1 0.923 0.926 Yes 0.833 0.431

The main-effect models recover all six main effects. The interaction model retains five main effects and the true interaction, with lower GIC and held-out log loss. Parent main effects are eligible for removal after their products have been generated.

The first 3,200 observations train the models; 800 are held out. Recovery includes the six main effects and the true interaction, so an omitted interaction counts as a false negative. All rows use the same evaluation universe: original predictors plus the union of generated interactions and the true interaction. Simulation truth is used only for evaluation. These independent variants provide a reproducible computational example; real GWAS also require appropriate population-structure and relatedness adjustment.

Timings exclude generation and final metric reporting. They were measured on an HP ZBook Fury G8 with an Intel i9-11950H, eight physical cores, 16 logical processors and one BLAS thread. Windows may cache file reads.

PGEN uses the official pgenlibr reader, retaining continuous ALT dosages. BED coefficients count BIM allele 1; PGEN coefficients count ALT dosage, combining ALT alleles for multiallelic records.

source <- l0glmData('variants.pgen')
source <- l0glmData('variants.vcf.gz',control=list(
  plink='C:/tools/plink2.exe',cache='C:/analysis/cache/genotypes',dosage='DS'))

VCF conversion uses PLINK 2 and an explicit output prefix. A provenance record identifies the input used by a reusable cache. dosage='DS' preserves expected dosages; omitting it imports GT hardcalls.

Imputation, prediction and resampling

BED/PGEN use training-mean imputation by default; other formats require an explicit missing='mean'. Only nonmissing training rows with positive weight in at least one channel enter each mean. An all-missing column becomes zero. Cross-validation relearns these means in each training fold. Prediction reuses the fitted training means, including when predictor columns are reordered by name. Bootstrap row views repeat the fitting pipeline with replicate-specific training means.

tuned <- l0glmTune(source,response,family=binomial(),tune='cv',nfolds=5L,
  nlambda=10L,screen='SIS',nsis=1000L)
predict(tuned$fit_best,source[test_rows,,drop=FALSE])

Keep the source files at their saved paths. File-backed intercepts can be added with intercept=TRUE; existing constant columns should be named or declared with always.include. Numeric starts, compulsory terms, predictor groups and interaction terms retain their usual eligibility and screening rules.

Streamed outcome clustering

Ward distances and cut losses add over observation blocks, so glmCluster() can cluster file-backed responses without making a full dense outcome copy:

channels <- l0glmData('chromatogram.h5',dataset='intensity')
clustered <- glmCluster(channels,family=poisson(identity),linkage='ward',k.max=32L)

The pairwise channel distances and returned centres/aggregates must satisfy the memory guard. Size factors use whole-channel totals, computed in a streamed pass when omitted. Bregman agglomeration retains its bounded-matrix route.