scrna1/6 Jupyter Notebook lamindata Binder

scRNA-seq#

You’ll learn how to manage a growing number of scRNA-seq data batches as a single queryable dataset.

Along the way, you’ll see how to create reports, leverage data lineage, and query individual data batches stored as files.

Specifically, you will:

  1. read a single .h5ad file as an AnnData object and seed a growing dataset with it (scrna1/6, current page)

  2. append a new data batch (a new .h5ad file) and create a new version of this dataset (scrna2/6)

  3. query & inspect files by metadata individually (scrna3/6)

  4. load the dataset into memory and save analytical results (scrna4/6)

  5. iterate over the dataset, train a model, store a derived representation (scrna5/6)

  6. discuss converting a number of files to a single TileDB SOMA store of the same data (scrna6/6)

Setup#

!lamin init --storage ./test-scrna --schema bionty
Hide code cell output
✅ saved: User(uid='DzTjkKse', handle='testuser1', name='Test User1', updated_at=2023-10-27 14:08:02)
✅ saved: Storage(uid='u254wjlq', root='/home/runner/work/lamin-usecases/lamin-usecases/docs/test-scrna', type='local', updated_at=2023-10-27 14:08:02, created_by_id=1)
💡 loaded instance: testuser1/test-scrna
💡 did not register local instance on hub

import lamindb as ln
import lnschema_bionty as lb
import pandas as pd

ln.track()
💡 loaded instance: testuser1/test-scrna (lamindb 0.59.0)
💡 notebook imports: lamindb==0.59.0 lnschema_bionty==0.34.0 pandas==1.5.3
💡 Transform(uid='Nv48yAceNSh8z8', name='scRNA-seq', short_name='scrna', version='0', type=notebook, updated_at=2023-10-27 14:08:07, created_by_id=1)
💡 Run(uid='T5xPTY12UVw6rOOjgE7H', run_at=2023-10-27 14:08:07, transform_id=1, created_by_id=1)

Access #

Let us look at the data of Conde et al., Science (2022).

These data are available in standardized form from the CellxGene data portal.

Here, we’ll use it to seed a growing in-house store of scRNA-seq data managed with the corresponding metadata in LaminDB registries.

Note

If you’re not interested in managing large collections of in-house data and you’d just like to query public data, please take a look at CellxGene census, which exposes all datasets hosted in the data portal as a concatenated TileDB SOMA store.

lb.settings.organism = "human"

By calling ln.dev.datasets.anndata_human_immune_cells below, we download the dataset from the CellxGene portal here and pre-populate some LaminDB registries.

adata = ln.dev.datasets.anndata_human_immune_cells(
    populate_registries=True  # this pre-populates registries
)
adata
AnnData object with n_obs × n_vars = 1648 × 36503
    obs: 'donor', 'tissue', 'cell_type', 'assay'
    var: 'feature_is_filtered', 'feature_reference', 'feature_biotype'
    uns: 'default_embedding'
    obsm: 'X_umap'

This AnnData is already standardized using the same public ontologies underlying lnschema-bionty, hence, we expect validation to be simple.

Nonetheless, LaminDB focuses on building clean in-house registries

Note

In the next notebook, we’ll look at the more difficult case of a non-standardized dataset that requires curation.

Validate #

This following represents a manual metadata curation process that often occur in notebooks. See custom validator for bulk validation.

Validate genes in .var#

lb.Gene.validate(adata.var.index, lb.Gene.ensembl_gene_id);
148 terms (0.40%) are not validated for ensembl_gene_id: ENSG00000269933, ENSG00000261737, ENSG00000259834, ENSG00000256374, ENSG00000263464, ENSG00000203812, ENSG00000272196, ENSG00000272880, ENSG00000270188, ENSG00000287116, ENSG00000237133, ENSG00000224739, ENSG00000227902, ENSG00000239467, ENSG00000272551, ENSG00000280374, ENSG00000236886, ENSG00000229352, ENSG00000286601, ENSG00000227021, ...

148 gene identifiers can’t be validated (not currently in the Gene registry). Let’s inspect them to see what to do:

inspector = lb.Gene.inspect(adata.var.index, lb.Gene.ensembl_gene_id)
148 terms (0.40%) are not validated for ensembl_gene_id: ENSG00000269933, ENSG00000261737, ENSG00000259834, ENSG00000256374, ENSG00000263464, ENSG00000203812, ENSG00000272196, ENSG00000272880, ENSG00000270188, ENSG00000287116, ENSG00000237133, ENSG00000224739, ENSG00000227902, ENSG00000239467, ENSG00000272551, ENSG00000280374, ENSG00000236886, ENSG00000229352, ENSG00000286601, ENSG00000227021, ...
   detected 35 Gene terms in Bionty for ensembl_gene_id: 'ENSG00000212907', 'ENSG00000198727', 'ENSG00000275249', 'ENSG00000278633', 'ENSG00000268674', 'ENSG00000198712', 'ENSG00000278817', 'ENSG00000198886', 'ENSG00000278704', 'ENSG00000198786', 'ENSG00000277400', 'ENSG00000273554', 'ENSG00000276760', 'ENSG00000198938', 'ENSG00000277196', 'ENSG00000273748', 'ENSG00000198840', 'ENSG00000276017', 'ENSG00000278384', 'ENSG00000277856', ...
→  add records from Bionty to your Gene registry via .from_values()
   couldn't validate 113 terms: 'ENSG00000273496', 'ENSG00000272196', 'ENSG00000287388', 'ENSG00000239446', 'ENSG00000225932', 'ENSG00000272370', 'ENSG00000256892', 'ENSG00000273370', 'ENSG00000237548', 'ENSG00000232196', 'ENSG00000269933', 'ENSG00000254561', 'ENSG00000263464', 'ENSG00000280374', 'ENSG00000273888', 'ENSG00000261773', 'ENSG00000236740', 'ENSG00000278198', 'ENSG00000272040', 'ENSG00000227021', ...
→  if you are sure, create new records via ln.Gene() and save to your registry

Logging says 35 of the non-validated ids can be found in the Bionty reference. Let’s register them:

records = lb.Gene.from_values(inspector.non_validated, lb.Gene.ensembl_gene_id)
ln.save(records)
did not create Gene records for 113 non-validated ensembl_gene_ids: 'ENSG00000112096', 'ENSG00000182230', 'ENSG00000203812', 'ENSG00000204092', 'ENSG00000215271', 'ENSG00000221995', 'ENSG00000224739', 'ENSG00000224745', 'ENSG00000225932', 'ENSG00000226377', 'ENSG00000226380', 'ENSG00000226403', 'ENSG00000227021', 'ENSG00000227220', 'ENSG00000227902', 'ENSG00000228139', 'ENSG00000228906', 'ENSG00000229352', 'ENSG00000231575', 'ENSG00000232196', ...

The remaining 113 are legacy IDs, not present in the current Ensembl assembly (e.g. ENSG00000112096).

We’d still like to register them, but won’t dive into the details of converting them from an old Ensembl version to the current one.

validated = lb.Gene.validate(adata.var.index, lb.Gene.ensembl_gene_id)
records = [lb.Gene(ensembl_gene_id=id) for id in adata.var.index[~validated]]
ln.save(records)
113 terms (0.30%) are not validated for ensembl_gene_id: ENSG00000269933, ENSG00000261737, ENSG00000259834, ENSG00000256374, ENSG00000263464, ENSG00000203812, ENSG00000272196, ENSG00000272880, ENSG00000270188, ENSG00000287116, ENSG00000237133, ENSG00000224739, ENSG00000227902, ENSG00000239467, ENSG00000272551, ENSG00000280374, ENSG00000236886, ENSG00000229352, ENSG00000286601, ENSG00000227021, ...

Now all genes pass validation:

lb.Gene.validate(adata.var.index, lb.Gene.ensembl_gene_id);

Our in-house Gene registry provides rich metadata for each gene measured in the AnnData:

lb.Gene.filter().df().head(10)
uid symbol stable_id ensembl_gene_id ncbi_gene_ids biotype description synonyms organism_id bionty_source_id updated_at created_by_id
id
1 nG5QMZBh5VxD MIR1302-2HG None ENSG00000243485 lncRNA MIR1302-2 host gene [Source:HGNC Symbol;Acc:HG... 1 9.0 2023-10-27 14:08:19 1
2 A7BOVXA3f7IS FAM138A None ENSG00000237613 645520|124906933 lncRNA family with sequence similarity 138 member A [... F379 1 9.0 2023-10-27 14:08:19 1
3 fXkFfHvbJRDx OR4F5 None ENSG00000186092 79501 protein_coding olfactory receptor family 4 subfamily F member... 1 9.0 2023-10-27 14:08:19 1
4 On07aEStsWXn None None ENSG00000238009 lncRNA novel transcript 1 9.0 2023-10-27 14:08:19 1
5 JNhwMkpEuypB None None ENSG00000239945 lncRNA novel transcript 1 9.0 2023-10-27 14:08:19 1
6 tr0ZVFDfxqAP None None ENSG00000239906 lncRNA novel transcript 1 9.0 2023-10-27 14:08:19 1
7 9Pp5Np9wxTs0 None None ENSG00000241860 lncRNA novel transcript 1 9.0 2023-10-27 14:08:19 1
8 EF9CRfhfg5HM None None ENSG00000241599 lncRNA novel transcript 1 9.0 2023-10-27 14:08:19 1
9 SFS4UJ0eZaE0 None None ENSG00000286448 lncRNA novel transcript 1 9.0 2023-10-27 14:08:19 1
10 1mHgOtxqz5jx None None ENSG00000236601 lncRNA novel transcript 1 9.0 2023-10-27 14:08:19 1

There are about 36k genes in the registry, all for organism “human”.

lb.Gene.filter().df().shape
(36503, 12)

Validate metadata in .obs#

adata.obs.columns
Index(['donor', 'tissue', 'cell_type', 'assay'], dtype='object')
ln.Feature.validate(adata.obs.columns)
1 term (25.00%) is not validated for name: donor
array([False,  True,  True,  True])

1 feature is not validated: "donor". Let’s register it:

feature = ln.Feature(name="donor", type="category", registries=[ln.ULabel])
feature.save()

Tip

You can also use features = ln.Feature.from_df(df) to bulk create features with types.

All metadata columns are now validated:

ln.Feature.validate(adata.obs.columns)
array([ True,  True,  True,  True])

Next, let’s validate the corresponding labels of each feature.

Some of the metadata labels can be typed using dedicated registries like CellType:

validated = lb.CellType.validate(adata.obs.cell_type)
❗ received 32 unique terms, 1616 empty/duplicated terms are ignored
2 terms (6.20%) are not validated for name: germinal center B cell, megakaryocyte

Register non-validated cell types - they can all be loaded from a public ontology through Bionty:

records = lb.CellType.from_values(adata.obs.cell_type[~validated], "name")
ln.save(records)
❗ now recursing through parents: this only happens once, but is much slower than bulk saving
lb.ExperimentalFactor.validate(adata.obs.assay)
lb.Tissue.validate(adata.obs.tissue);

Because we didn’t mount a custom schema that contains a Donor registry, we use the ULabel registry to track donor ids:

ln.ULabel.validate(adata.obs.donor);
❗ received 12 unique terms, 1636 empty/duplicated terms are ignored
12 terms (100.00%) are not validated for name: D496, 621B, A29, A36, A35, 637C, A52, A37, D503, 640C, A31, 582C

Donor labels are not validated, so let’s register them:

donors = [ln.ULabel(name=name) for name in adata.obs.donor.unique()]
ln.save(donors)
ln.ULabel.validate(adata.obs.donor);

Register #

modalities = ln.Modality.lookup()
experimental_factors = lb.ExperimentalFactor.lookup()
organism = lb.Organism.lookup()
features = ln.Feature.lookup()

Register data#

When we create a File object from an AnnData, we’ll automatically link its feature sets and get information about unmapped categories:

file = ln.File.from_anndata(
    adata, description="Conde22", field=lb.Gene.ensembl_gene_id, modality=modalities.rna
)
file.save()

The file has the following 2 linked feature sets:

file.features
Features:
  var: FeatureSet(uid='6qRKjbpfuxhgYAbbyN5d', n=36503, type='number', registry='bionty.Gene', hash='dnRexHCtxtmOU81_EpoJ', updated_at=2023-10-27 14:08:52, modality_id=1, created_by_id=1)
    'MIR1302-2HG', 'FAM138A', 'OR4F5', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'OR4F29', 'None', 'OR4F16', 'None', 'LINC01409', 'FAM87B', 'LINC01128', 'LINC00115', 'FAM41C', 'None', ...
  obs: FeatureSet(uid='BCo5J2bFOheDRHdwQ4Zd', n=4, registry='core.Feature', hash='JsxufswT1GUhRPy_OR3-', updated_at=2023-10-27 14:08:53, modality_id=2, created_by_id=1)
    🔗 cell_type (0, bionty.CellType): 
    🔗 assay (0, bionty.ExperimentalFactor): 
    🔗 tissue (0, bionty.Tissue): 
    🔗 donor (0, core.ULabel): 

Create a dataset#

dataset = ln.Dataset(file, name="My versioned scRNA-seq dataset", version="1")

dataset
Dataset(uid='OmLkMWSbDuMAxFj7BqyV', name='My versioned scRNA-seq dataset', version='1', hash='9sXda5E7BYiVoDOQkTC0KB', visibility=0, transform_id=1, run_id=1, file_id=1, created_by_id=1)

Let’s inspect the features measured in this dataset which were inherited from the file:

dataset.features
Features:
  var: FeatureSet(uid='6qRKjbpfuxhgYAbbyN5d', n=36503, type='number', registry='bionty.Gene', hash='dnRexHCtxtmOU81_EpoJ', updated_at=2023-10-27 14:08:52, modality_id=1, created_by_id=1)
    'MIR1302-2HG', 'FAM138A', 'OR4F5', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'OR4F29', 'None', 'OR4F16', 'None', 'LINC01409', 'FAM87B', 'LINC01128', 'LINC00115', 'FAM41C', 'None', ...
  obs: FeatureSet(uid='BCo5J2bFOheDRHdwQ4Zd', n=4, registry='core.Feature', hash='JsxufswT1GUhRPy_OR3-', updated_at=2023-10-27 14:08:53, modality_id=2, created_by_id=1)
    🔗 cell_type (0, bionty.CellType): 
    🔗 assay (0, bionty.ExperimentalFactor): 
    🔗 tissue (0, bionty.Tissue): 
    🔗 donor (0, core.ULabel): 
  external: FeatureSet(uid='O1oXV6kF6vDYn7g6FC76', n=1, registry='core.Feature', hash='QsvUUCL8Ea4Az1u2v4I-', updated_at=2023-10-27 14:08:54, modality_id=2, created_by_id=1)
    🔗 organism (0, bionty.Organism): 

This looks all good, hence, let’s save it:

dataset.save()

Annotate by linking labels:

dataset.labels.add(experimental_factors.single_cell_rna_sequencing, features.assay)
dataset.labels.add(organism.human, features.organism)
dataset.labels.add(adata.obs.cell_type, feature=features.cell_type)
dataset.labels.add(adata.obs.assay, feature=features.assay)
dataset.labels.add(adata.obs.tissue, feature=features.tissue)
dataset.labels.add(adata.obs.donor, feature=features.donor)

For this version 1 of the dataset, dataset and file match each other. But they’re independently tracked and queryable through their registries.

dataset.describe()
Dataset(uid='OmLkMWSbDuMAxFj7BqyV', name='My versioned scRNA-seq dataset', version='1', hash='9sXda5E7BYiVoDOQkTC0KB', visibility=0, updated_at=2023-10-27 14:08:58)

Provenance:
  💫 transform: Transform(uid='Nv48yAceNSh8z8', name='scRNA-seq', short_name='scrna', version='0', type=notebook, updated_at=2023-10-27 14:08:07, created_by_id=1)
  👣 run: Run(uid='T5xPTY12UVw6rOOjgE7H', run_at=2023-10-27 14:08:07, transform_id=1, created_by_id=1)
  📄 file: File(uid='OmLkMWSbDuMAxFj7BqyV', suffix='.h5ad', accessor='AnnData', description='Conde22', size=57612943, hash='9sXda5E7BYiVoDOQkTC0KB', hash_type='sha1-fl', visibility=0, key_is_virtual=True, updated_at=2023-10-27 14:08:58, storage_id=1, transform_id=1, run_id=1, created_by_id=1)
  👤 created_by: User(uid='DzTjkKse', handle='testuser1', name='Test User1', updated_at=2023-10-27 14:08:02)
Features:
  var: FeatureSet(uid='6qRKjbpfuxhgYAbbyN5d', n=36503, type='number', registry='bionty.Gene', hash='dnRexHCtxtmOU81_EpoJ', updated_at=2023-10-27 14:08:52, modality_id=1, created_by_id=1)
    'MIR1302-2HG', 'FAM138A', 'OR4F5', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'OR4F29', 'None', 'OR4F16', 'None', 'LINC01409', 'FAM87B', 'LINC01128', 'LINC00115', 'FAM41C', 'None', ...
  obs: FeatureSet(uid='BCo5J2bFOheDRHdwQ4Zd', n=4, registry='core.Feature', hash='JsxufswT1GUhRPy_OR3-', updated_at=2023-10-27 14:08:53, modality_id=2, created_by_id=1)
    🔗 cell_type (32, bionty.CellType): 'classical monocyte', 'T follicular helper cell', 'memory B cell', 'alveolar macrophage', 'naive thymus-derived CD4-positive, alpha-beta T cell', 'effector memory CD8-positive, alpha-beta T cell, terminally differentiated', 'alpha-beta T cell', 'CD4-positive helper T cell', 'naive thymus-derived CD8-positive, alpha-beta T cell', 'macrophage', ...
    🔗 assay (4, bionty.ExperimentalFactor): 'single-cell RNA sequencing', '10x 3' v3', '10x 5' v2', '10x 5' v1'
    🔗 tissue (17, bionty.Tissue): 'blood', 'thoracic lymph node', 'spleen', 'lung', 'mesenteric lymph node', 'lamina propria', 'liver', 'jejunal epithelium', 'omentum', 'bone marrow', ...
    🔗 donor (12, core.ULabel): 'D496', '621B', 'A29', 'A36', 'A35', '637C', 'A52', 'A37', 'D503', '640C', ...
  external: FeatureSet(uid='O1oXV6kF6vDYn7g6FC76', n=1, registry='core.Feature', hash='QsvUUCL8Ea4Az1u2v4I-', updated_at=2023-10-27 14:08:54, modality_id=2, created_by_id=1)
    🔗 organism (1, bionty.Organism): 'human'
Labels:
  🏷️ organism (1, bionty.Organism): 'human'
  🏷️ tissues (17, bionty.Tissue): 'blood', 'thoracic lymph node', 'spleen', 'lung', 'mesenteric lymph node', 'lamina propria', 'liver', 'jejunal epithelium', 'omentum', 'bone marrow', ...
  🏷️ cell_types (32, bionty.CellType): 'classical monocyte', 'T follicular helper cell', 'memory B cell', 'alveolar macrophage', 'naive thymus-derived CD4-positive, alpha-beta T cell', 'effector memory CD8-positive, alpha-beta T cell, terminally differentiated', 'alpha-beta T cell', 'CD4-positive helper T cell', 'naive thymus-derived CD8-positive, alpha-beta T cell', 'macrophage', ...
  🏷️ experimental_factors (4, bionty.ExperimentalFactor): 'single-cell RNA sequencing', '10x 3' v3', '10x 5' v2', '10x 5' v1'
  🏷️ ulabels (12, core.ULabel): 'D496', '621B', 'A29', 'A36', 'A35', '637C', 'A52', 'A37', 'D503', '640C', ...

And we can access the file like so:

dataset.file
File(uid='OmLkMWSbDuMAxFj7BqyV', suffix='.h5ad', accessor='AnnData', description='Conde22', size=57612943, hash='9sXda5E7BYiVoDOQkTC0KB', hash_type='sha1-fl', visibility=0, key_is_virtual=True, updated_at=2023-10-27 14:08:58, storage_id=1, transform_id=1, run_id=1, created_by_id=1)
dataset.view_flow()
_images/666236b024a0bc44fad5cfd9e741f6419dacc32b0246f59d97ed4a7eb56ea3c3.svg