anasanchezf commited on
Commit
eef8346
1 Parent(s): 6debc34

Upload modality_gap_cloome.ipynb

Browse files
Files changed (1) hide show
  1. modality_gap_cloome.ipynb +380 -0
modality_gap_cloome.ipynb ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Exploring CLOOME with Amumo \n",
8
+ "Humer et al. 2023\n",
9
+ "\n",
10
+ "Github Repo: https://github.com/ginihumer/Amumo\n",
11
+ "\n",
12
+ "Interactive Article: https://jku-vds-lab.at/amumo"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "execution_count": null,
18
+ "metadata": {},
19
+ "outputs": [],
20
+ "source": [
21
+ "! pip install git+https://github.com/ginihumer/Amumo.git"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": 1,
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "import numpy as np\n",
31
+ "import pandas as pd\n",
32
+ "import sys\n",
33
+ "import os\n",
34
+ "import torch\n",
35
+ "sys.path.insert(0, os.path.abspath(\"src/\"))\n",
36
+ "\n",
37
+ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\""
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": 2,
43
+ "metadata": {},
44
+ "outputs": [
45
+ {
46
+ "name": "stderr",
47
+ "output_type": "stream",
48
+ "text": [
49
+ "C:\\Users\\Christina\\AppData\\Roaming\\Python\\Python39\\site-packages\\umap\\distances.py:1063: NumbaDeprecationWarning: \u001b[1mThe 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details.\u001b[0m\n",
50
+ " @numba.jit()\n",
51
+ "C:\\Users\\Christina\\AppData\\Roaming\\Python\\Python39\\site-packages\\umap\\distances.py:1071: NumbaDeprecationWarning: \u001b[1mThe 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details.\u001b[0m\n",
52
+ " @numba.jit()\n",
53
+ "C:\\Users\\Christina\\AppData\\Roaming\\Python\\Python39\\site-packages\\umap\\distances.py:1086: NumbaDeprecationWarning: \u001b[1mThe 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details.\u001b[0m\n",
54
+ " @numba.jit()\n",
55
+ "C:\\Users\\Christina\\AppData\\Roaming\\Python\\Python39\\site-packages\\umap\\umap_.py:660: NumbaDeprecationWarning: \u001b[1mThe 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details.\u001b[0m\n",
56
+ " @numba.jit()\n"
57
+ ]
58
+ }
59
+ ],
60
+ "source": [
61
+ "import amumo\n",
62
+ "from amumo import model as am_model\n",
63
+ "from amumo import data as am_data\n",
64
+ "from amumo import widgets as am_widgets\n",
65
+ "from amumo import utils as am_utils"
66
+ ]
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "execution_count": 3,
71
+ "metadata": {},
72
+ "outputs": [],
73
+ "source": [
74
+ "basepath = './'\n",
75
+ "datapath = os.path.join(basepath, \"data\")\n",
76
+ "batch_size = 100\n",
77
+ "seed = 31415"
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "execution_count": 4,
83
+ "metadata": {},
84
+ "outputs": [],
85
+ "source": [
86
+ "from PIL import Image\n",
87
+ "\n",
88
+ "# Data Helpers\n",
89
+ "def get_data_helper(dataset, filters=[], method=any):\n",
90
+ " all_images, all_prompts = dataset.get_filtered_data(filters, method=method)\n",
91
+ " print(len(all_images))\n",
92
+ "\n",
93
+ " dataset_name = dataset.name\n",
94
+ " if len(filters) > 0:\n",
95
+ " dataset_name = dataset_name + '_filter-' + method.__name__ + '_' + '-'.join(filters)\n",
96
+ " else:\n",
97
+ " dataset_name = dataset_name + '_size-%i'%len(all_images)\n",
98
+ "\n",
99
+ " return all_images, all_prompts, dataset_name\n",
100
+ "\n",
101
+ "\n",
102
+ "def reshape_image(arr):\n",
103
+ " c, h, w = arr.shape\n",
104
+ " reshaped_image = np.empty((h, w, c))\n",
105
+ "\n",
106
+ " reshaped_image[:,:,0] = arr[0]\n",
107
+ " reshaped_image[:,:,1] = arr[1]\n",
108
+ " reshaped_image[:,:,2] = arr[2]\n",
109
+ "\n",
110
+ " reshaped_pil = Image.fromarray(reshaped_image.astype(\"uint8\"))\n",
111
+ "\n",
112
+ " return reshaped_pil\n",
113
+ "\n",
114
+ "\n",
115
+ "from rdkit import Chem\n",
116
+ "from rdkit.Chem import rdFMCS\n",
117
+ "import io\n",
118
+ "class MoleculeType(am_data.TextType):\n",
119
+ " name = \"Molecule\"\n",
120
+ "\n",
121
+ " def __init__(self, data) -> None:\n",
122
+ " # data is a list of SMILES\n",
123
+ " super().__init__(data)\n",
124
+ "\n",
125
+ " def getMinSummary(self, ids):\n",
126
+ " # retrieve MCS of mols\n",
127
+ " if len(ids) == 1:\n",
128
+ " return self.data[ids[0]]\n",
129
+ "\n",
130
+ " mols = [Chem.MolFromSmiles(smiles) for smiles in self.data[ids]]\n",
131
+ " mcs = rdFMCS.FindMCS(mols)\n",
132
+ " mcs_smiles = Chem.MolToSmiles(Chem.MolFromSmarts(mcs.smartsString))\n",
133
+ " return mcs_smiles\n",
134
+ " \n",
135
+ " def getVisItem(self, idx):\n",
136
+ " output_img = io.BytesIO()\n",
137
+ " img = Chem.Draw.MolToImage(Chem.MolFromSmiles(self.data[idx]))\n",
138
+ " img.resize((300,300)).save(output_img, format='JPEG')\n",
139
+ " return output_img\n",
140
+ " \n",
141
+ "\n",
142
+ "class BioImageType(am_data.ImageType):\n",
143
+ " name = \"Bio Image\"\n",
144
+ "\n",
145
+ " def __init__(self, data) -> None:\n",
146
+ " super().__init__(data)\n",
147
+ "\n",
148
+ "\n",
149
+ "class CLOOMDataset_Dataset(am_data.DatasetInterface):\n",
150
+ " name='CLOOMDataset'\n",
151
+ "\n",
152
+ " def __init__(self, path, seed=31415, batch_size = 100):\n",
153
+ " super().__init__(path, seed, batch_size)\n",
154
+ "\n",
155
+ " self.MODE1_Type = BioImageType\n",
156
+ " self.MODE2_Type = MoleculeType\n",
157
+ "\n",
158
+ " mol_index_file = os.path.join(path, \"cellpainting-unique-molecule.csv\")\n",
159
+ " img_index_file = os.path.join(path, \"cellpainting-all-imgpermol.csv\")\n",
160
+ " images_arr = os.path.join(path, \"subset_npzs_dict_.npz\")\n",
161
+ "\n",
162
+ "\n",
163
+ " # molecule smiles\n",
164
+ " all_molecules = pd.read_csv(mol_index_file)\n",
165
+ " all_molecules.rename(columns={\"SAMPLE_KEY\": \"SAMPLE_KEY_mol\"}, inplace=True)\n",
166
+ " # microscopy images\n",
167
+ " all_microscopies = pd.read_csv(img_index_file)\n",
168
+ " all_microscopies.rename(columns={\"SAMPLE_KEY\": \"SAMPLE_KEY_img\"}, inplace=True)\n",
169
+ " # join the two dataframes\n",
170
+ " cloome_data = pd.merge(all_molecules[[\"SAMPLE_KEY_mol\", \"SMILES\"]], all_microscopies[[\"SAMPLE_KEY_img\", \"SMILES\"]], on=\"SMILES\", how=\"inner\")\n",
171
+ " \n",
172
+ " # subsample data\n",
173
+ " self.subset_idcs = self._get_random_subsample(len(cloome_data))\n",
174
+ " self.dataset = cloome_data.iloc[self.subset_idcs]\n",
175
+ " \n",
176
+ " self.all_prompts = self.dataset[\"SMILES\"].values\n",
177
+ "\n",
178
+ " # microscopy images TODO... load images on demand with a custom image loader\n",
179
+ " all_microscopies = pd.read_csv(img_index_file)\n",
180
+ " images_dict = np.load(images_arr, allow_pickle = True)\n",
181
+ " all_images = []\n",
182
+ " for img_id in self.dataset[\"SAMPLE_KEY_img\"]:\n",
183
+ " image = images_dict[f\"{img_id}.npz\"]\n",
184
+ " im = reshape_image(image)\n",
185
+ " all_images.append(im)\n",
186
+ "\n",
187
+ " self.all_images = np.array(all_images)\n",
188
+ " "
189
+ ]
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "execution_count": 5,
194
+ "metadata": {},
195
+ "outputs": [
196
+ {
197
+ "name": "stdout",
198
+ "output_type": "stream",
199
+ "text": [
200
+ "100\n"
201
+ ]
202
+ },
203
+ {
204
+ "name": "stderr",
205
+ "output_type": "stream",
206
+ "text": [
207
+ "C:\\Users\\Christina\\AppData\\Local\\Temp\\ipykernel_28556\\2905515878.py:102: FutureWarning: The input object of type 'Image' is an array-like implementing one of the corresponding protocols (`__array__`, `__array_interface__` or `__array_struct__`); but not a sequence (or 0-D). In the future, this object will be coerced as if it was first converted using `np.array(obj)`. To retain the old behaviour, you have to either modify the type 'Image', or assign to an empty array created with `np.empty(correct_shape, dtype=object)`.\n",
208
+ " self.all_images = np.array(all_images)\n",
209
+ "C:\\Users\\Christina\\AppData\\Local\\Temp\\ipykernel_28556\\2905515878.py:102: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.\n",
210
+ " self.all_images = np.array(all_images)\n"
211
+ ]
212
+ },
213
+ {
214
+ "data": {
215
+ "text/plain": [
216
+ "'CLOOMDataset_size-100'"
217
+ ]
218
+ },
219
+ "execution_count": 5,
220
+ "metadata": {},
221
+ "output_type": "execute_result"
222
+ }
223
+ ],
224
+ "source": [
225
+ "# Load Data\n",
226
+ "dataset_cloome = CLOOMDataset_Dataset(datapath,seed,batch_size)\n",
227
+ "cloome_images, cloome_molecules, cloome_dataset_name = get_data_helper(dataset_cloome, filters=[], method=any)\n",
228
+ "cloome_dataset_name\n"
229
+ ]
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "execution_count": 6,
234
+ "metadata": {},
235
+ "outputs": [
236
+ {
237
+ "data": {
238
+ "text/plain": [
239
+ "<_io.BytesIO at 0x20775295630>"
240
+ ]
241
+ },
242
+ "execution_count": 6,
243
+ "metadata": {},
244
+ "output_type": "execute_result"
245
+ }
246
+ ],
247
+ "source": [
248
+ "cloome_molecules.getVisItem(0)"
249
+ ]
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "execution_count": 7,
254
+ "metadata": {},
255
+ "outputs": [],
256
+ "source": [
257
+ "class PrecalculatedModel(am_model.CLIPModelInterface):\n",
258
+ " model_name = 'precalculated'\n",
259
+ "\n",
260
+ " def __init__(self, name, dataset_name, modality1_features, modality2_features, logit_scale=torch.tensor(0)) -> None:\n",
261
+ " # this class is a workaround for precalculated features\n",
262
+ " # it just saves the features as cached files so that the \"encode_image\" and \"encode_text\" methods are not called\n",
263
+ " self.available_models = [name]\n",
264
+ " super().__init__(name, device='cpu')\n",
265
+ " self.logit_scale = logit_scale\n",
266
+ " self.modality1_features = modality1_features\n",
267
+ " self.modality2_features = modality2_features\n",
268
+ " self.process_precalculated_features(dataset_name)\n",
269
+ "\n",
270
+ " def process_precalculated_features(self, dataset_name):\n",
271
+ " data_prefix = dataset_name + '_' + self.model_name + '_' + self.name\n",
272
+ " data_prefix = data_prefix.replace('/','-')\n",
273
+ " np.savetxt(am_utils.data_checkpoint_dir + data_prefix + '_image-embedding.csv', self.modality1_features.cpu(), delimiter = ',')\n",
274
+ " np.savetxt(am_utils.data_checkpoint_dir + data_prefix + '_text-embedding.csv', self.modality2_features.cpu(), delimiter = ',') \n",
275
+ "\n",
276
+ " def encode_image(self, images):\n",
277
+ " raise NotImplementedError(\"this cannot be done for precalculated features -> use cached features\")\n",
278
+ " \n",
279
+ " def encode_text(self, texts):\n",
280
+ " raise NotImplementedError(\"this cannot be done for precalculated features -> use cached features\")"
281
+ ]
282
+ },
283
+ {
284
+ "cell_type": "code",
285
+ "execution_count": 8,
286
+ "metadata": {},
287
+ "outputs": [],
288
+ "source": [
289
+ "molecule_features = os.path.join(datapath, \"all_molecule_cellpainting_features.pkl\")\n",
290
+ "image_features = os.path.join(datapath, \"subset_image_cellpainting_features.pkl\")\n",
291
+ "\n",
292
+ "# molecule features\n",
293
+ "mol_features_torch = torch.load(molecule_features, map_location=device)\n",
294
+ "mol_features = mol_features_torch[\"mol_features\"]\n",
295
+ "mol_ids = mol_features_torch[\"mol_ids\"]\n",
296
+ "\n",
297
+ "# microscopy features\n",
298
+ "img_features_torch = torch.load(image_features, map_location=device)\n",
299
+ "img_features = img_features_torch[\"img_features\"]\n",
300
+ "img_ids = img_features_torch[\"img_ids\"]\n",
301
+ "\n",
302
+ "# extract subsets of features\n",
303
+ "img_feature_idcs = [np.where(np.array(img_features_torch[\"img_ids\"])==i)[0][0] for i in dataset_cloome.dataset[\"SAMPLE_KEY_img\"].values]\n",
304
+ "mol_feature_idcs = [np.where(np.array(mol_features_torch[\"mol_ids\"])==i)[0][0] for i in dataset_cloome.dataset[\"SAMPLE_KEY_mol\"].values]\n",
305
+ "\n",
306
+ "mol_features_sample = mol_features_torch['mol_features'][mol_feature_idcs]\n",
307
+ "mol_features_sample = am_utils.l2_norm(mol_features_sample)\n",
308
+ "\n",
309
+ "img_features_sample = img_features_torch['img_features'][img_feature_idcs]\n",
310
+ "img_features_sample = am_utils.l2_norm(img_features_sample)\n",
311
+ "\n",
312
+ "# cache features\n",
313
+ "model = PrecalculatedModel('seed-%i'%seed, cloome_dataset_name, img_features_sample, mol_features_sample)"
314
+ ]
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "execution_count": 9,
319
+ "metadata": {},
320
+ "outputs": [
321
+ {
322
+ "name": "stdout",
323
+ "output_type": "stream",
324
+ "text": [
325
+ "found cached embeddings for CLOOMDataset_size-100_precalculated_seed-31415\n"
326
+ ]
327
+ },
328
+ {
329
+ "data": {
330
+ "application/vnd.jupyter.widget-view+json": {
331
+ "model_id": "87d1d581c2c94464bee9d98a6aea0579",
332
+ "version_major": 2,
333
+ "version_minor": 0
334
+ },
335
+ "text/plain": [
336
+ "CLIPExplorerWidget(children=(VBox(children=(HBox(children=(Dropdown(description='Model: ', options=('precalcul…"
337
+ ]
338
+ },
339
+ "execution_count": 9,
340
+ "metadata": {},
341
+ "output_type": "execute_result"
342
+ }
343
+ ],
344
+ "source": [
345
+ "cloome_widget = am_widgets.CLIPExplorerWidget(cloome_dataset_name, cloome_images, cloome_molecules, models=[model])\n",
346
+ "cloome_widget.hover_widget.width = 200\n",
347
+ "cloome_widget"
348
+ ]
349
+ },
350
+ {
351
+ "cell_type": "code",
352
+ "execution_count": null,
353
+ "metadata": {},
354
+ "outputs": [],
355
+ "source": []
356
+ }
357
+ ],
358
+ "metadata": {
359
+ "kernelspec": {
360
+ "display_name": "cloome",
361
+ "language": "python",
362
+ "name": "python3"
363
+ },
364
+ "language_info": {
365
+ "codemirror_mode": {
366
+ "name": "ipython",
367
+ "version": 3
368
+ },
369
+ "file_extension": ".py",
370
+ "mimetype": "text/x-python",
371
+ "name": "python",
372
+ "nbconvert_exporter": "python",
373
+ "pygments_lexer": "ipython3",
374
+ "version": "3.9.17"
375
+ },
376
+ "orig_nbformat": 4
377
+ },
378
+ "nbformat": 4,
379
+ "nbformat_minor": 2
380
+ }