{ "cells": [ { "cell_type": "markdown", "id": "29283b5f73ff", "metadata": {}, "source": [ "# Tutorial: Creating an AnnData Object from EmeraldBay Dataset\n", "This notebook is intented for users who are familiar with the anndata format for single-cell data. We'll walk through how to parse records in the huggingface dataset format and convert between the two." ] }, { "cell_type": "markdown", "id": "ba072a78e3a4", "metadata": {}, "source": [ "## Install Required Libraries" ] }, { "cell_type": "code", "id": "b9362f7078f7", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "!pip install datasets anndata scipy pandas pubchempy" ] }, { "cell_type": "markdown", "id": "2bc895079924", "metadata": {}, "source": [ "## Import Libraries" ] }, { "cell_type": "code", "id": "e9ba03a3bd79", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "from datasets import load_dataset\n", "from scipy.sparse import csr_matrix\n", "import anndata\n", "import pandas as pd\n", "import pubchempy as pcp" ] }, { "cell_type": "markdown", "id": "c29b2fa43400", "metadata": {}, "source": [ "## Mapping records to anndata\n", "\n", "This function takes in a generator that emits records from the EmeraldBay huggingface dataset and returns an anndata object. Use the `sample_size` argument to specify the number of records you need. You can also create a new generator using the `dataset.filter` function to only emit records that match a certain filter (eg: for a specific drug/sample/cell line).\n", "\n", "If you'd like to create a DataLoader for an ML training application, it's likely best to use the data in it's native format without interfacing with anndata." ] }, { "cell_type": "code", "id": "687310bbaa90", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "\n", "def create_anndata_from_generator(generator, gene_vocab, sample_size=None):\n", " sorted_vocab_items = sorted(gene_vocab.items())\n", " token_ids, gene_names = zip(*sorted_vocab_items)\n", " token_id_to_col_idx = {token_id: idx for idx, token_id in enumerate(token_ids)}\n", "\n", " data, indices, indptr = [], [], [0]\n", " obs_data = []\n", "\n", " for i, cell in enumerate(generator):\n", " if sample_size is not None and i >= sample_size:\n", " break\n", " genes = cell['genes']\n", " expressions = cell['expressions']\n", " if expressions[0] < 0: \n", " genes = genes[1:]\n", " expressions = expressions[1:]\n", "\n", " col_indices = [token_id_to_col_idx[gene] for gene in genes if gene in token_id_to_col_idx]\n", " valid_expressions = [expr for gene, expr in zip(genes, expressions) if gene in token_id_to_col_idx]\n", "\n", " data.extend(valid_expressions)\n", " indices.extend(col_indices)\n", " indptr.append(len(data))\n", "\n", " obs_entry = {k: v for k, v in cell.items() if k not in ['genes', 'expressions']}\n", " obs_data.append(obs_entry)\n", "\n", " expr_matrix = csr_matrix((data, indices, indptr), shape=(len(indptr) - 1, len(gene_names)))\n", " obs_df = pd.DataFrame(obs_data)\n", "\n", " adata = anndata.AnnData(X=expr_matrix, obs=obs_df)\n", " adata.var.index = pd.Index(gene_names, name='ensembl_id')\n", "\n", " return adata\n" ] }, { "cell_type": "markdown", "id": "2f9b054dd5d1", "metadata": {}, "source": [ "## Load EmeraldBay Dataset" ] }, { "cell_type": "code", "id": "00fb90b58885", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "emeraldbay_ds = load_dataset('tahoebio/EmeraldBay', streaming=True, split='train')" ] }, { "cell_type": "markdown", "id": "eb4d67366482", "metadata": {}, "source": [ "## Load Gene Metadata\n", "\n", "The gene metadata contains the mapping between the integer token IDs used in the dataset and standard identifiers for genes (ensembl IDs and HGNC gene symbols)" ] }, { "cell_type": "code", "id": "f69fe5d5a0c0", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "gene_metadata = load_dataset(\"tahoebio/EmeraldBay\", name=\"gene_metadata\", split=\"train\")\n", "gene_vocab = {entry[\"token_id\"]: entry[\"ensembl_id\"] for entry in gene_metadata}" ] }, { "cell_type": "markdown", "id": "e2e508d19e5e", "metadata": {}, "source": [ "## Create AnnData Object" ] }, { "cell_type": "code", "id": "8adcb383b952", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "adata = create_anndata_from_generator(emeraldbay_ds, gene_vocab, sample_size=1000)\n", "adata" ] }, { "cell_type": "markdown", "id": "38b1fc1559fc", "metadata": {}, "source": [ "## Inspect Metadata (`adata.obs`)" ] }, { "cell_type": "code", "id": "2403918666e7", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "adata.obs.head()" ] }, { "cell_type": "markdown", "id": "d7fcc00b9b45", "metadata": {}, "source": "## Add Drug Metadata\n\nThe drug metadata contains additional information for the compounds used in EmeraldBay. See the dataset card for more information about how this information was generated." }, { "cell_type": "code", "id": "188820081704", "metadata": {}, "execution_count": null, "outputs": [], "source": "drug_metadata = load_dataset(\"tahoebio/EmeraldBay\",\"drug_metadata\", split=\"train\").to_pandas()\nadata.obs = pd.merge(adata.obs, drug_metadata, on=\"drug\", how=\"left\")\nadata.obs.head()" }, { "cell_type": "markdown", "id": "8ab3abb59bbf", "metadata": {}, "source": [ "## Drug Info from PubChem\n", "\n", "We also provide the pubchem IDs for the compounds in EmeraldBay, this can be used to querry additional information as needed." ] }, { "cell_type": "code", "id": "1550c8343527", "metadata": {}, "execution_count": null, "outputs": [], "source": "drug_name = adata.obs[\"drug\"].values[0]\ncid = int(float(adata.obs[\"pubchem-cid\"].values[0]))\ncompound = pcp.Compound.from_cid(cid)\n\nprint(f\"Name: {drug_name}\")\nprint(f\"Synonyms: {compound.synonyms[:10]}\")\nprint(f\"Formula: {compound.molecular_formula}\")\nprint(f\"SMILES: {compound.isomeric_smiles}\")\nprint(f\"Mass: {compound.exact_mass}\")" }, { "cell_type": "markdown", "id": "6eb51c1c4b78", "metadata": {}, "source": [ "## Load Cell Line Metadata\n", "The cell-line metadata contains additional identifiers for the cell-lines used in EmeraldBay (eg: Depmap-IDs) as well as a curated list of driver mutations for each cell line. This information can be used for instance to train genotype aware models on the EmeraldBay data." ] }, { "cell_type": "code", "id": "c102249f7cc9", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "cell_line_metadata = load_dataset(\"tahoebio/EmeraldBay\",\"cell_line_metadata\", split=\"train\").to_pandas()\n", "cell_line_metadata.head()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }