File size: 7,670 Bytes
4efcbdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
{
 "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
}