Standardize metadata on-the-fly#

This use cases runs on a LaminDB instance with populated CellType and Pathway registries. Make sure you run the GO Ontology notebook before executing this use case.

Here, we demonstrate how to standardize the metadata on-the-fly during cell type annotation and pathway enrichment analysis using these two registries.

For more information, see:

!lamin load use-cases-registries
πŸ’‘ connected lamindb: testuser1/use-cases-registries
import lamindb as ln
import bionty as bt
from lamin_usecases import datasets as ds
import scanpy as sc
import matplotlib.pyplot as plt
import celltypist
import gseapy as gp
πŸ’‘ connected lamindb: testuser1/use-cases-registries
sc.settings.set_figure_params(dpi=50, facecolor="white")
ln.settings.transform.stem_uid = "hsPU1OENv0LS"
ln.settings.transform.version = "0"
ln.track()
πŸ’‘ notebook imports: bionty==0.42.9 celltypist==1.6.2 gseapy==1.1.2 lamin_usecases==0.0.1 lamindb==0.71.0 matplotlib==3.8.4 scanpy==1.10.1
πŸ’‘ saved: Transform(uid='hsPU1OENv0LS6K79', name='Standardize metadata on-the-fly', key='analysis-registries', version='0', type='notebook', updated_at=2024-05-01 18:50:56 UTC, created_by_id=1)
πŸ’‘ saved: Run(uid='aNRjAufI5AwD9VAq29in', transform_id=1, created_by_id=1)

An interferon-beta treated dataset#

A small peripheral blood mononuclear cell dataset that is split into control and stimulated groups. The stimulated group was treated with interferon beta.

Let’s load the dataset and perform some preprocessing:

adata = ds.anndata_seurat_ifnb(preprocess=False, populate_registries=True)
adata


AnnData object with n_obs Γ— n_vars = 13999 Γ— 9944
    obs: 'stim'
    var: 'symbol'
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
sc.pp.highly_variable_genes(adata, n_top_genes=2000)
sc.pp.pca(adata, n_comps=20)
sc.pp.neighbors(adata, n_pcs=10)
sc.tl.umap(adata)

Analysis: cell type annotation using CellTypist#

model = celltypist.models.Model.load(model="Immune_All_Low.pkl")
Hide code cell output
πŸ”Ž No available models. Downloading...
πŸ“œ Retrieving model list from server https://celltypist.cog.sanger.ac.uk/models/models.json
πŸ“š Total models in list: 47
πŸ“‚ Storing models in /home/runner/.celltypist/data/models
πŸ’Ύ Downloading model [1/47]: Immune_All_Low.pkl
πŸ’Ύ Downloading model [2/47]: Immune_All_High.pkl
πŸ’Ύ Downloading model [3/47]: Adult_CynomolgusMacaque_Hippocampus.pkl
πŸ’Ύ Downloading model [4/47]: Adult_Human_PancreaticIslet.pkl
πŸ’Ύ Downloading model [5/47]: Adult_Human_Skin.pkl
πŸ’Ύ Downloading model [6/47]: Adult_Mouse_Gut.pkl
πŸ’Ύ Downloading model [7/47]: Adult_Mouse_OlfactoryBulb.pkl
πŸ’Ύ Downloading model [8/47]: Adult_Pig_Hippocampus.pkl
πŸ’Ύ Downloading model [9/47]: Adult_RhesusMacaque_Hippocampus.pkl
πŸ’Ύ Downloading model [10/47]: Autopsy_COVID19_Lung.pkl
πŸ’Ύ Downloading model [11/47]: COVID19_HumanChallenge_Blood.pkl
πŸ’Ύ Downloading model [12/47]: COVID19_Immune_Landscape.pkl
πŸ’Ύ Downloading model [13/47]: Cells_Adult_Breast.pkl
πŸ’Ύ Downloading model [14/47]: Cells_Fetal_Lung.pkl
πŸ’Ύ Downloading model [15/47]: Cells_Human_Tonsil.pkl
πŸ’Ύ Downloading model [16/47]: Cells_Intestinal_Tract.pkl
πŸ’Ύ Downloading model [17/47]: Cells_Lung_Airway.pkl
πŸ’Ύ Downloading model [18/47]: Developing_Human_Brain.pkl
πŸ’Ύ Downloading model [19/47]: Developing_Human_Gonads.pkl
πŸ’Ύ Downloading model [20/47]: Developing_Human_Hippocampus.pkl
πŸ’Ύ Downloading model [21/47]: Developing_Human_Organs.pkl
πŸ’Ύ Downloading model [22/47]: Developing_Human_Thymus.pkl
πŸ’Ύ Downloading model [23/47]: Developing_Mouse_Brain.pkl
πŸ’Ύ Downloading model [24/47]: Developing_Mouse_Hippocampus.pkl
πŸ’Ύ Downloading model [25/47]: Fetal_Human_AdrenalGlands.pkl
πŸ’Ύ Downloading model [26/47]: Fetal_Human_Pancreas.pkl
πŸ’Ύ Downloading model [27/47]: Fetal_Human_Pituitary.pkl
πŸ’Ύ Downloading model [28/47]: Fetal_Human_Retina.pkl
πŸ’Ύ Downloading model [29/47]: Fetal_Human_Skin.pkl
πŸ’Ύ Downloading model [30/47]: Healthy_Adult_Heart.pkl
πŸ’Ύ Downloading model [31/47]: Healthy_COVID19_PBMC.pkl
πŸ’Ύ Downloading model [32/47]: Healthy_Human_Liver.pkl
πŸ’Ύ Downloading model [33/47]: Healthy_Mouse_Liver.pkl
πŸ’Ύ Downloading model [34/47]: Human_AdultAged_Hippocampus.pkl
πŸ’Ύ Downloading model [35/47]: Human_Colorectal_Cancer.pkl
πŸ’Ύ Downloading model [36/47]: Human_Developmental_Retina.pkl
πŸ’Ύ Downloading model [37/47]: Human_Embryonic_YolkSac.pkl
πŸ’Ύ Downloading model [38/47]: Human_IPF_Lung.pkl
πŸ’Ύ Downloading model [39/47]: Human_Longitudinal_Hippocampus.pkl
πŸ’Ύ Downloading model [40/47]: Human_Lung_Atlas.pkl
πŸ’Ύ Downloading model [41/47]: Human_PF_Lung.pkl
πŸ’Ύ Downloading model [42/47]: Lethal_COVID19_Lung.pkl
πŸ’Ύ Downloading model [43/47]: Mouse_Dentate_Gyrus.pkl
πŸ’Ύ Downloading model [44/47]: Mouse_Isocortex_Hippocampus.pkl
πŸ’Ύ Downloading model [45/47]: Mouse_Postnatal_DentateGyrus.pkl
πŸ’Ύ Downloading model [46/47]: Nuclei_Lung_Airway.pkl
πŸ’Ύ Downloading model [47/47]: Pan_Fetal_Human.pkl
predictions = celltypist.annotate(
    adata, model="Immune_All_Low.pkl", majority_voting=True
)
adata.obs["cell_type_celltypist"] = predictions.predicted_labels.majority_voting
πŸ”¬ Input data has 13999 cells and 9944 genes
πŸ”— Matching reference genes in the model
🧬 3704 features used for prediction
βš–οΈ Scaling input data
πŸ–‹οΈ Predicting labels
βœ… Prediction done!
πŸ‘€ Detected a neighborhood graph in the input object, will run over-clustering on the basis of it
⛓️ Over-clustering input data with resolution set to 10
πŸ—³οΈ Majority voting the predictions
βœ… Majority voting done!
adata.obs["cell_type_celltypist"] = bt.CellType.standardize(
    adata.obs["cell_type_celltypist"]
)
sc.pl.umap(
    adata,
    color=["cell_type_celltypist", "stim"],
    frameon=False,
    legend_fontsize=10,
    wspace=0.4,
)
... storing 'cell_type_celltypist' as categorical
_images/117ca05213698efc09d26e5381a4614ef6af7fcc6be6b42e0f7d1abc8fdccc76.png

Analysis: Pathway enrichment analysis using Enrichr#

This analysis is based on the GSEApy scRNA-seq Example.

First, we compute differentially expressed genes using a Wilcoxon test between stimulated and control cells.

# compute differentially expressed genes
sc.tl.rank_genes_groups(
    adata,
    groupby="stim",
    use_raw=False,
    method="wilcoxon",
    groups=["STIM"],
    reference="CTRL",
)

rank_genes_groups_df = sc.get.rank_genes_groups_df(adata, "STIM")
rank_genes_groups_df.head()
names scores logfoldchanges pvals pvals_adj
0 ISG15 99.456406 7.132497 0.0 0.0
1 ISG20 96.736259 5.074062 0.0 0.0
2 IFI6 94.973038 5.828577 0.0 0.0
3 IFIT3 92.482315 7.432163 0.0 0.0
4 IFIT1 90.698952 8.053299 0.0 0.0

Next, we filter out up/down-regulated differentially expressed gene sets:

degs_up = rank_genes_groups_df[
    (rank_genes_groups_df["logfoldchanges"] > 0)
    & (rank_genes_groups_df["pvals_adj"] < 0.05)
]
degs_dw = rank_genes_groups_df[
    (rank_genes_groups_df["logfoldchanges"] < 0)
    & (rank_genes_groups_df["pvals_adj"] < 0.05)
]

degs_up.shape, degs_dw.shape
((542, 5), (937, 5))

Run pathway enrichment analysis on DEGs and plot top 10 pathways:

enr_up = gp.enrichr(degs_up.names, gene_sets="GO_Biological_Process_2023").res2d
gp.dotplot(enr_up, figsize=(2, 3), title="Up", cmap=plt.cm.autumn_r);
_images/3a26b696e6111cabf14e9bd245b8d8ea4d22a44a12359e7ff7ba8245017c0ce9.png
enr_dw = gp.enrichr(degs_dw.names, gene_sets="GO_Biological_Process_2023").res2d
gp.dotplot(enr_dw, figsize=(2, 3), title="Down", cmap=plt.cm.winter_r);
_images/e6ad4f33d51f38b46a6925021611af53dcf3ef21b8d8b6ddf4b2a77a69d875ac.png

Register analyzed dataset and annotate with metadata#

Register new features and labels (check out more details here):

new_features = ln.Feature.from_df(adata.obs)
ln.save(new_features)
new_labels = [ln.ULabel(name=i) for i in adata.obs["stim"].unique()]
ln.save(new_labels)
features = ln.Feature.lookup()

Register dataset using a Artifact object:

artifact = ln.Artifact.from_anndata(
    adata,
    description="seurat_ifnb_activated_Bcells",
)
artifact.save()
Artifact(uid='BRZ7WlJ0cxCctgb9OwHu', suffix='.h5ad', accessor='AnnData', description='seurat_ifnb_activated_Bcells', size=215138790, hash='60gDH_vTLvljceBN6JUBFd', hash_type='sha1-fl', visibility=1, key_is_virtual=True, updated_at=2024-05-01 18:54:11 UTC, storage_id=1, transform_id=1, run_id=1, created_by_id=1)
artifact.features.add_from_anndata(
    var_field=bt.Gene.symbol,
    organism="human", # optionally, globally set organism via bt.settings.organism = "human"
)

Querying metadata#

artifact.describe()
Artifact(uid='BRZ7WlJ0cxCctgb9OwHu', suffix='.h5ad', accessor='AnnData', description='seurat_ifnb_activated_Bcells', size=215138790, hash='60gDH_vTLvljceBN6JUBFd', hash_type='sha1-fl', visibility=1, key_is_virtual=True, updated_at=2024-05-01 18:54:12 UTC)

Provenance:
  πŸ“Ž storage: Storage(uid='oODpbLp1qFXI', root='/home/runner/work/lamin-usecases/lamin-usecases/docs/use-cases-registries', type='local', instance_uid='6l8lZsT2TN6X')
  πŸ“Ž transform: Transform(uid='hsPU1OENv0LS6K79', name='Standardize metadata on-the-fly', key='analysis-registries', version='0', type='notebook')
  πŸ“Ž run: Run(uid='aNRjAufI5AwD9VAq29in', started_at=2024-05-01 18:50:56 UTC, is_consecutive=True)
  πŸ“Ž created_by: User(uid='DzTjkKse', handle='testuser1', name='Test User1')
Features:
  var: FeatureSet(uid='AQXrjiw0NCPRPTT9IfN9', n=11286, type='number', registry='bionty.Gene')
    'IL10RB', 'ATP1B3', 'TAL2', 'AQP10', 'KLC2', 'RPS7', 'SYS1', 'MEAK7', 'PRKAR2B', 'RBM5', 'UBE2R2', 'FUT4', 'NOP10', 'IPO5', 'MAEA', 'TMX2', 'ZNF487', 'TXNIP', 'FBXO28', 'FNTB', ...
  obs: FeatureSet(uid='Oz8XEdF66qZdMlYjWfdp', n=2, registry='core.Feature')
    πŸ”— stim (2, core.ULabel): 'CTRL', 'STIM'
    πŸ”— cell_type_celltypist (13, bionty.CellType): 'B cell', 'plasmacytoid dendritic cell', 'natural killer cell', 'central memory CD8-positive, alpha-beta T cell', 'mast cell', 'macrophage', 'effector memory CD4-positive, alpha-beta T cell', 'classical monocyte', 'non-classical monocyte', 'central memory CD4-positive, alpha-beta T cell', ...
  STIM-up-DEGs: FeatureSet(uid='cGp7dWUzme5VeQOx5aNZ', name='Up-regulated DEGs STIM vs CTRL', n=661, type='category', registry='bionty.Gene')
    'PSMG2', 'TIA1', 'MASTL', 'GBP2', 'SPPL2A', 'IRF7', 'TMSB10', 'GBP1', 'TENT5A', 'IL17D', 'CAPN2', 'FCN1', 'SUB1', 'NAGK', 'PRDX4', 'SSB', 'TXNIP', 'FYB1', 'SERPING1', 'ISG20', ...
  STIM-down-DEGs: FeatureSet(uid='pZT68VJAaz35vfnG0fAh', name='Down-regulated DEGs STIM vs CTRL', n=1094, type='category', registry='bionty.Gene')
    'IL10RB', 'COX6B1', 'SNRPD3', 'HLA-DQA1', 'ATP1B3', 'COTL1', 'PLA2G7', 'SLC25A6', 'PKM', 'MED8', 'EIF3I', 'PCBP2', 'SEC62', 'RPS7', 'COPS5', 'PARVG', 'CD3E', 'NOP10', 'CHMP1B', 'MRPL41', ...
Labels:
  πŸ“Ž cell_types (13, bionty.CellType): 'B cell', 'plasmacytoid dendritic cell', 'natural killer cell', 'central memory CD8-positive, alpha-beta T cell', 'mast cell', 'macrophage', 'effector memory CD4-positive, alpha-beta T cell', 'classical monocyte', 'non-classical monocyte', 'central memory CD4-positive, alpha-beta T cell', ...
  πŸ“Ž ulabels (2, core.ULabel): 'CTRL', 'STIM'

Querying cell types#

Querying for cell types contains β€œB cell” in the name:

bt.CellType.filter(name__contains="B cell").df().head()
uid name ontology_id abbr synonyms description public_source_id created_at updated_at created_by_id
id
1 ryEtgi1y B cell CL:0000236 None B-lymphocyte|Cycling B cells|B lymphocyte|B ce... A Lymphocyte Of B Lineage That Is Capable Of B... 21 2024-05-01 18:50:18.215572+00:00 2024-05-01 18:50:48.115443+00:00 1
2 2EhFTUoZ follicular B cell CL:0000843 None Follicular B cells|follicular B-lymphocyte|Fo ... A Resting Mature B Cell That Has The Phenotype... 21 2024-05-01 18:50:18.215683+00:00 2024-05-01 18:50:47.819752+00:00 1
3 4IowPafD germinal center B cell CL:0000844 None GC B lymphocyte|Proliferative germinal center ... A Rapidly Cycling Mature B Cell That Has Disti... 21 2024-05-01 18:50:18.215772+00:00 2024-05-01 18:50:47.848957+00:00 1
4 2cUPBtY8 memory B cell CL:0000787 None memory B-cell|memory B-lymphocyte|Age-associat... A Memory B Cell Is A Mature B Cell That Is Lon... 21 2024-05-01 18:50:18.215860+00:00 2024-05-01 18:50:48.008025+00:00 1
5 3jdCg7zi naive B cell CL:0000788 None Naive B cells|naive B-cell|naive B lymphocyte|... A Naive B Cell Is A Mature B Cell That Has The... 21 2024-05-01 18:50:18.215946+00:00 2024-05-01 18:50:48.023815+00:00 1

Querying for all artifacts annotated with a cell type:

celltypes = bt.CellType.lookup()
celltypes.plasmacytoid_dendritic_cell
CellType(uid='3JO0EdVd', name='plasmacytoid dendritic cell', ontology_id='CL:0000784', synonyms='type 2 DC|pDC|interferon-producing cell|IPC|T-associated plasma cell|plasmacytoid T cell|DC2|plasmacytoid monocyte|lymphoid dendritic cell', description='A Dendritic Cell Type Of Distinct Morphology, Localization, And Surface Marker Expression (Cd123-Positive) From Other Dendritic Cell Types And Associated With Early Stage Immune Responses, Particularly The Release Of Physiologically Abundant Amounts Of Type I Interferons In Response To Infection.', updated_at=2024-05-01 18:50:42 UTC, public_source_id=21, created_by_id=1)
ln.Artifact.filter(cell_types=celltypes.plasmacytoid_dendritic_cell).df()
uid storage_id key suffix accessor description version size hash hash_type n_objects n_observations transform_id run_id visibility key_is_virtual created_at updated_at created_by_id
id
1 BRZ7WlJ0cxCctgb9OwHu 1 None .h5ad AnnData seurat_ifnb_activated_Bcells None 215138790 60gDH_vTLvljceBN6JUBFd sha1-fl None None 1 1 1 True 2024-05-01 18:54:11.429514+00:00 2024-05-01 18:54:12.930026+00:00 1

Querying pathways#

Querying for pathways contains β€œinterferon-beta” in the name:

bt.Pathway.filter(name__contains="interferon-beta").df()
uid name ontology_id abbr synonyms description public_source_id created_at updated_at created_by_id
id
684 1l4z0v8W cellular response to interferon-beta GO:0035458 None cellular response to fibroblast interferon|cel... Any Process That Results In A Change In State ... 48 2024-05-01 18:49:30.760261+00:00 2024-05-01 18:49:30.760270+00:00 1
2130 1NzHDJDi negative regulation of interferon-beta production GO:0032688 None down regulation of interferon-beta production|... Any Process That Stops, Prevents, Or Reduces T... 48 2024-05-01 18:49:30.905876+00:00 2024-05-01 18:49:30.905887+00:00 1
3127 3x0xmK1y positive regulation of interferon-beta production GO:0032728 None positive regulation of IFN-beta production|up-... Any Process That Activates Or Increases The Fr... 48 2024-05-01 18:49:31.008738+00:00 2024-05-01 18:49:31.008757+00:00 1
4334 54R2a0el regulation of interferon-beta production GO:0032648 None regulation of IFN-beta production Any Process That Modulates The Frequency, Rate... 48 2024-05-01 18:49:31.133243+00:00 2024-05-01 18:49:31.133252+00:00 1
4953 3VZq4dMe response to interferon-beta GO:0035456 None response to fiblaferon|response to fibroblast ... Any Process That Results In A Change In State ... 48 2024-05-01 18:49:31.198749+00:00 2024-05-01 18:49:31.198760+00:00 1

Query pathways from a gene:

bt.Pathway.filter(genes__symbol="KIR2DL1").df()
uid name ontology_id abbr synonyms description public_source_id created_at updated_at created_by_id
id
1346 7S7qlEkG immune response-inhibiting cell surface recept... GO:0002767 None immune response-inhibiting cell surface recept... The Series Of Molecular Signals Initiated By A... 48 2024-05-01 18:49:30.827339+00:00 2024-05-01 18:49:30.827348+00:00 1

Query artifacts from a pathway:

ln.Artifact.filter(feature_sets__pathways__name__icontains="interferon-beta").first()
Artifact(uid='BRZ7WlJ0cxCctgb9OwHu', suffix='.h5ad', accessor='AnnData', description='seurat_ifnb_activated_Bcells', size=215138790, hash='60gDH_vTLvljceBN6JUBFd', hash_type='sha1-fl', visibility=1, key_is_virtual=True, updated_at=2024-05-01 18:54:12 UTC, storage_id=1, transform_id=1, run_id=1, created_by_id=1)

Query featuresets from a pathway to learn from which geneset this pathway was computed:

pathway = bt.Pathway.filter(ontology_id="GO:0035456").one()
pathway
Pathway(uid='3VZq4dMe', name='response to interferon-beta', ontology_id='GO:0035456', synonyms='response to fiblaferon|response to fibroblast interferon|response to interferon beta', description='Any Process That Results In A Change In State Or Activity Of A Cell Or An Organism (In Terms Of Movement, Secretion, Enzyme Production, Gene Expression, Etc.) As A Result Of An Interferon-Beta Stimulus. Interferon-Beta Is A Type I Interferon.', updated_at=2024-05-01 18:49:31 UTC, public_source_id=48, created_by_id=1)
degs = ln.FeatureSet.filter(pathways__ontology_id=pathway.ontology_id).one()

Now we can get the list of genes that are differentially expressed and belong to this pathway:

contributing_genes = pathway.genes.all() & degs.genes.all()
contributing_genes.list("symbol")
['STAT1',
 'OAS1',
 'SHFL',
 'IFITM1',
 'IFI16',
 'MNDA',
 'IRF1',
 'IFITM3',
 'PLSCR1',
 'PNPT1',
 'CALM1',
 'AIM2',
 'XAF1',
 'IFITM2',
 'BST2']
# clean up test instance
!lamin delete --force use-cases-registries
!rm -r ./use-cases-registries
Hide code cell output
Traceback (most recent call last):
  File "/opt/hostedtoolcache/Python/3.10.14/x64/bin/lamin", line 8, in <module>
    sys.exit(main())
  File "/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/rich_click/rich_command.py", line 360, in __call__
    return super().__call__(*args, **kwargs)
  File "/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/click/core.py", line 1157, in __call__
    return self.main(*args, **kwargs)
  File "/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/rich_click/rich_command.py", line 152, in main
    rv = self.invoke(ctx)
  File "/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/click/core.py", line 1688, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/click/core.py", line 1434, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/click/core.py", line 783, in invoke
    return __callback(*args, **kwargs)
  File "/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/lamin_cli/__main__.py", line 103, in delete
    return delete(instance, force=force)
  File "/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/lamindb_setup/_delete.py", line 140, in delete
    n_objects = check_storage_is_empty(
  File "/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/lamindb_setup/core/upath.py", line 814, in check_storage_is_empty
    raise InstanceNotEmpty(message)
lamindb_setup.core.upath.InstanceNotEmpty: Storage /home/runner/work/lamin-usecases/lamin-usecases/docs/use-cases-registries/.lamindb contains 2 objects ('./lamindb/_is_initialized'  ignored) - delete them prior to deleting the instance
['/home/runner/work/lamin-usecases/lamin-usecases/docs/use-cases-registries/.lamindb/BRZ7WlJ0cxCctgb9OwHu.h5ad', '/home/runner/work/lamin-usecases/lamin-usecases/docs/use-cases-registries/.lamindb/_is_initialized']