Jupyter Notebook

Analysis flow#

Here, we’ll track typical data transformations like subsetting that occur during analysis.

If exploring more generally, read this first: Project flow.

Setup#

# a lamindb instance containing Bionty schema
!lamin init --storage ./analysis-usecase --schema bionty
Hide code cell output
πŸ’‘ creating schemas: core==0.46.3 bionty==0.30.2 
βœ… saved: User(id='DzTjkKse', handle='testuser1', email='testuser1@lamin.ai', name='Test User1', updated_at=2023-08-31 00:33:41)
βœ… saved: Storage(id='WsU8F13L', root='/home/runner/work/lamin-usecases/lamin-usecases/docs/analysis-usecase', type='local', updated_at=2023-08-31 00:33:41, created_by_id='DzTjkKse')
βœ… loaded instance: testuser1/analysis-usecase
πŸ’‘ did not register local instance on hub (if you want, call `lamin register`)

import lamindb as ln
import lnschema_bionty as lb

lb.settings.species = "human"  # globally set species
lb.settings.auto_save_parents = False
βœ… loaded instance: testuser1/analysis-usecase (lamindb 0.51.2)
ln.track()
πŸ’‘ notebook imports: lamindb==0.51.2 lnschema_bionty==0.30.2
βœ… saved: Transform(id='eNef4Arw8nNMz8', name='Analysis flow', short_name='analysis-flow', version='0', type=notebook, updated_at=2023-08-31 00:33:42, created_by_id='DzTjkKse')
βœ… saved: Run(id='5EPLIpBKXY0XascR1949', run_at=2023-08-31 00:33:43, transform_id='eNef4Arw8nNMz8', created_by_id='DzTjkKse')

Track cell types, tissues and diseases#

We fetch an example dataset from LaminDB that has a few cell type, tissue and disease annotations:

Hide code cell content
adata = ln.dev.datasets.anndata_with_obs()
adata
AnnData object with n_obs Γ— n_vars = 40 Γ— 100
    obs: 'cell_type', 'cell_type_id', 'tissue', 'disease'
adata.var_names[:5]
Index(['ENSG00000000003', 'ENSG00000000005', 'ENSG00000000419',
       'ENSG00000000457', 'ENSG00000000460'],
      dtype='object')
adata.obs[["tissue", "cell_type", "disease"]].value_counts()
tissue  cell_type                disease                   
brain   my new cell type         Alzheimer disease             10
heart   hepatocyte               cardiac ventricle disorder    10
kidney  T cell                   chronic kidney disease        10
liver   hematopoietic stem cell  liver lymphoma                10
Name: count, dtype: int64

Processing the dataset#

To track our data transformation we create a new Transform of type β€œpipeline”:

transform = ln.Transform(
    name="Subset to T-cells and liver lymphoma", version="0.1.0", type="pipeline"
)

Set the current tracking to the new transform:

ln.track(transform)
βœ… saved: Transform(id='2ZJZdwMn1UA4TL', name='Subset to T-cells and liver lymphoma', version='0.1.0', type='pipeline', updated_at=2023-08-31 00:33:47, created_by_id='DzTjkKse')
βœ… saved: Run(id='t1mGmZgIgNeKniQmLrMh', run_at=2023-08-31 00:33:47, transform_id='2ZJZdwMn1UA4TL', created_by_id='DzTjkKse')

Get a backed AnnData object#

file = ln.File.filter(key="mini_anndata_with_obs.h5ad").one()
adata = file.backed()
adata
πŸ’‘ adding file 9v5gsYP5ULZew2Er9E8A as input for run t1mGmZgIgNeKniQmLrMh, adding parent transform eNef4Arw8nNMz8
AnnDataAccessor object with n_obs Γ— n_vars = 40 Γ— 100
  constructed for the AnnData object mini_anndata_with_obs.h5ad
    obs: ['_index', 'cell_type', 'cell_type_id', 'disease', 'tissue']
    var: ['_index']
adata.obs[["cell_type", "disease"]].value_counts()
cell_type                disease                   
T cell                   chronic kidney disease        10
hematopoietic stem cell  liver lymphoma                10
hepatocyte               cardiac ventricle disorder    10
my new cell type         Alzheimer disease             10
Name: count, dtype: int64

Subset dataset to specific cell types and diseases#

Create the subset:

subset_obs = adata.obs.cell_type.isin(["T cell", "hematopoietic stem cell"]) & (
    adata.obs.disease.isin(["liver lymphoma", "chronic kidney disease"])
)
adata_subset = adata[subset_obs]
adata_subset
AnnDataAccessorSubset object with n_obs Γ— n_vars = 20 Γ— 100
  obs: ['_index', 'cell_type', 'cell_type_id', 'disease', 'tissue']
  var: ['_index']
adata_subset.obs[["cell_type", "disease"]].value_counts()
cell_type                disease               
T cell                   chronic kidney disease    10
hematopoietic stem cell  liver lymphoma            10
Name: count, dtype: int64

This subset can now be registered:

file_subset = ln.File.from_anndata(
    adata_subset.to_memory(),
    key="subset/mini_anndata_with_obs.h5ad",
    var_ref=lb.Gene.ensembl_gene_id,
)
/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/site-packages/anndata/_core/anndata.py:1840: UserWarning: Variable names are not unique. To make them unique, call `.var_names_make_unique`.
  utils.warn_names_duplicates("var")
πŸ’‘ file will be copied to default storage upon `save()` with key 'subset/mini_anndata_with_obs.h5ad'
πŸ’‘ parsing feature names of X stored in slot 'var'
❗    received 99 unique terms, 1 empty/duplicated term is ignored
❗    99 terms (100.00%) are not validated for ensembl_gene_id: ENSG00000000003, ENSG00000000005, ENSG00000000419, ENSG00000000457, ENSG00000000460, ENSG00000000938, ENSG00000000971, ENSG00000001036, ENSG00000001084, ENSG00000001167, ENSG00000001460, ENSG00000001461, ENSG00000001497, ENSG00000001561, ENSG00000001617, ENSG00000001626, ENSG00000001629, ENSG00000001630, ENSG00000001631, ENSG00000002016, ...
❗    no validated features, skip creating feature set
πŸ’‘ parsing feature names of slot 'obs'
βœ…    3 terms (75.00%) are validated for name
❗    1 term (25.00%) is not validated for name: cell_type_id
/opt/hostedtoolcache/Python/3.9.17/x64/lib/python3.9/site-packages/lamindb/_feature.py:68: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
  categoricals = {col: df[col] for col in df.columns if is_categorical_dtype(df[col])}
βœ…    loaded: FeatureSet(id='mEGmejRrf9sa3NaWbkaB', n=3, registry='core.Feature', hash='36g_ESuVhpPlZ5CANgP2', updated_at=2023-08-31 00:33:46, modality_id='xj7zYu45', created_by_id='DzTjkKse')
βœ…    linked: FeatureSet(id='mEGmejRrf9sa3NaWbkaB', n=3, registry='core.Feature', hash='36g_ESuVhpPlZ5CANgP2', updated_at=2023-08-31 00:33:46, modality_id='xj7zYu45', created_by_id='DzTjkKse')
file_subset.save()
βœ… storing file 'ky0JFHA5XOrcqdyHOqCT' at 'subset/mini_anndata_with_obs.h5ad'

Add labels to features, all of them validate:

cell_types = lb.CellType.from_values(adata.obs.cell_type, lb.CellType.name)
tissues = lb.Tissue.from_values(adata.obs.tissue, lb.Tissue.name)
diseases = lb.Disease.from_values(adata.obs.disease, lb.Disease.name)

file_subset.add_labels(cell_types, feature="cell_type")
file_subset.add_labels(tissues, feature="tissue")
file_subset.add_labels(diseases, feature="disease")
Hide code cell output
βœ… loaded 3 CellType records matching name: T cell, hematopoietic stem cell, hepatocyte
❗ did not create CellType record for 1 non-validated name: my new cell type
file_subset.describe()
πŸ’‘ File(id='ky0JFHA5XOrcqdyHOqCT', key='subset/mini_anndata_with_obs.h5ad', suffix='.h5ad', accessor='AnnData', size=38992, hash='RgGUx7ndRplZZSmalTAWiw', hash_type='md5', updated_at=2023-08-31 00:33:47)

Provenance:
    πŸ—ƒοΈ storage: Storage(id='WsU8F13L', root='/home/runner/work/lamin-usecases/lamin-usecases/docs/analysis-usecase', type='local', updated_at=2023-08-31 00:33:41, created_by_id='DzTjkKse')
    🧩 transform: Transform(id='2ZJZdwMn1UA4TL', name='Subset to T-cells and liver lymphoma', version='0.1.0', type='pipeline', updated_at=2023-08-31 00:33:47, created_by_id='DzTjkKse')
    πŸ‘£ run: Run(id='t1mGmZgIgNeKniQmLrMh', run_at=2023-08-31 00:33:47, transform_id='2ZJZdwMn1UA4TL', created_by_id='DzTjkKse')
    πŸ‘€ created_by: User(id='DzTjkKse', handle='testuser1', email='testuser1@lamin.ai', name='Test User1', updated_at=2023-08-31 00:33:41)
Features:
  obs (metadata):
    πŸ”— cell_type (3, bionty.CellType): ['hematopoietic stem cell', 'T cell', 'hepatocyte']
    πŸ”— disease (4, bionty.Disease): ['cardiac ventricle disorder', 'liver lymphoma', 'chronic kidney disease', 'Alzheimer disease']
    πŸ”— tissue (4, bionty.Tissue): ['heart', 'kidney', 'brain', 'liver']

Examine data flow#

Common questions that might arise are:

  • Which h5ad file is in the subset subfolder?

  • Which notebook ingested this file?

  • By whom?

  • And which file is its parent?

Let’s answer this using LaminDB:

Query a subsetted .h5ad file containing β€œhematopoietic stem cell” and β€œT cell” to learn which h5ad file is in the subset subfolder:

cell_types_bt_lookup = lb.CellType.lookup()
my_subset = ln.File.filter(
    suffix=".h5ad",
    key__startswith="subset",
    cell_types__in=[
        cell_types_bt_lookup.hematopoietic_stem_cell,
        cell_types_bt_lookup.t_cell,
    ],
).first()
my_subset.view_flow()
https://d33wubrfki0l68.cloudfront.net/fe5edaa00178054c716a0c10164f6091fae6864c/be0b3/_images/2c635ed856e5f7400007599fe2756bca534a7aca4fa30369d2bab75430af2571.svg
Hide code cell content
!lamin delete --force analysis-usecase
!rm -r ./analysis-usecase
πŸ’‘ deleting instance testuser1/analysis-usecase
βœ…     deleted instance settings file: /home/runner/.lamin/instance--testuser1--analysis-usecase.env
βœ…     instance cache deleted
βœ…     deleted '.lndb' sqlite file
❗     consider manually deleting your stored data: /home/runner/work/lamin-usecases/lamin-usecases/docs/analysis-usecase