To handle batch effects before running cNMF, use the Preprocess class. This implements an adaptation of Harmony that corrects the underlying count matrix rather than principal components.
Workflow
- Initialize
Preprocess. - Use
preprocess_for_cnmf on an AnnData object, specifying harmony_vars (column names in adata.obs to correct). - Pass the resulting corrected files into the
cNMF.prepare() method.
from cnmf import cNMF, Preprocess
# 1. Initialize Preprocess
p = Preprocess(random_seed=14)
# 2. Batch correct and save outputs
# This produces corrected counts (adata_c), TPM normalized data (adata_tpm), and high-variance genes (hvgs)
(adata_c, adata_tpm, hvgs) = p.preprocess_for_cnmf(
adata,
harmony_vars=['Sex', 'Sample'],
n_top_rna_genes=2000,
librarysize_targetsum=1e6,
save_output_base='./example_islets/batchcorrect_example_sex'
)
# 3. Run cNMF using the corrected files
cnmf_obj_corrected = cNMF(output_dir='./example_islets', name='BatchCorrected')
cnmf_obj_corrected.prepare(
counts_fn='./example_islets/batchcorrect_example.Corrected.HVG.Varnorm.h5ad',
tpm_fn='./example_islets/batchcorrect_example.TP10K.h5ad',
genes_file='./example_islets/batchcorrect_example.Corrected.HVGs.txt',
components=[15],
n_iter=20,
seed=14,
num_highvar_genes=2000
)
from cnmf import cNMF, Preprocess
p = Preprocess(random_seed=14)
(adata_c, adata_tpm, hvgs) = p.preprocess_for_cnmf(adata, harmony_vars=['Sex', 'Sample'], n_top_rna_genes = 2000, librarysize_targetsum= 1e6,
save_output_base='./example_islets/batchcorrect_example_sex')
cnmf_obj_corrected = cNMF(output_dir='./example_islets', name='BatchCorrected')
cnmf_obj_corrected.prepare(counts_fn='./example_islets/batchcorrect_example.Corrected.HVG.Varnorm.h5ad',
tpm_fn='./example_islets/batchcorrect_example.TP10K.h5ad',
genes_file='./example_islets/batchcorrect_example.Corrected.HVGs.txt',
components=[15], n_iter=20, seed=14, num_highvar_genes=2000)