File size: 35,500 Bytes
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff63fa7
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c377fd
b1cd545
1c377fd
 
 
 
 
 
 
 
 
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fb1494
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fb1494
 
 
 
 
ad8362e
 
 
 
 
b1cd545
4fb1494
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5884c3
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad8362e
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5884c3
b1cd545
ff63fa7
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5884c3
b1cd545
a5884c3
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5884c3
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5884c3
b1cd545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "377f3d60-eddc-46aa-b21b-d30b4cf7607d",
   "metadata": {},
   "source": [
    "# Finding natural geroprotectors with Precious3GPT and BATMAN\n",
    "\n",
    "This notebook will teach you how to use P3GPT to emulate the workflow of a chemical screening projects.\n",
    "\n",
    "In particular, we will identify the compounds encountered in traditional Chinese medicine (TCM) with a geroprotective potential.\n",
    "\n",
    "In this notebook, we generate omics signatures in 8 human tissues. We will then use these signatures and an external catalog of TCM ingredients [BATMAN](http://bionet.ncpsb.org.cn/batman-tcm/#/browse) to select the compounds that target the genes in P3GPT-generated signatures.\n",
    "\n",
    "<center><img src=\"https://huggingface.co/datasets/f-galkin/batman2/resolve/main/demo/imgs/experiment_scheme.png\" width=\"800\" ></center>\n",
    "<center><i>This notebook only focuses on TCM compounds with known targets, but you may modify the code to look for geroprotectors based on the information about predicted targets as well. In this case, the identified potential geroprptectors will be more numerous and might contain novel compounds.</i></center>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05eb4e79-9040-4963-ab1f-62cfb4a9f9f3",
   "metadata": {},
   "source": [
    "> ⚠️ **Dependency:** To replicate this project, you need to download some files from [Precious3GPT's repo](https://doi.org/10.57967/hf/2699) and then move the ```mpt_7b``` directory and ```precious3_gpt_multi_modal.py``` from `p3-mm` to `~/P3LIB/`. You can remove all the other downloaded files.\n",
    "\n",
    "``` python\n",
    "from huggingface_hub import snapshot_download\n",
    "snapshot_download(repo_id=\"insilicomedicine/precious3-gpt-multi-modal\", local_dir='./p3-mm')\n",
    "```\n",
    "> In the end, your directory structure should look as follows:\n",
    "```\n",
    "└── demo\n",
    "    ├── 1Aug2024_aging_signatures.pckl [optional]\n",
    "    ├── HF_TCM+P3GPT_sceening.ipynb\n",
    "    ├── P3GPT_compound_targets.pckl\n",
    "    └── P3LIB\n",
    "        ├── mpt_7b\n",
    "        │   ├── ...\n",
    "        │   └── ...\n",
    "        ├─ endpoints.py\n",
    "        ├─ formula_picker.py\n",
    "        └─ precious3_gpt_multi_modal.py\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "27aceeaa-2db6-4df7-b9bb-3a775032b725",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Dict, List, Any\n",
    "import os\n",
    "import torch\n",
    "from transformers import AutoTokenizer, AutoModel\n",
    "import pandas as pd\n",
    "import time\n",
    "import numpy as np\n",
    "from transformers import GenerationConfig\n",
    "import pickle\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from scipy.stats import fisher_exact\n",
    "\n",
    "from P3LIB.endpoints import EndpointHandler"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe4c382e-2ef8-4cc1-a050-7cd8388519c2",
   "metadata": {},
   "source": [
    "## 1. Generate aging signatures\n",
    "\n",
    "Define the tissues and the omics domains to be screened to be inserted in the P3GPT prompt template.\n",
    "\n",
    "Since we are only intereseted in aging-related omics differences, we only need one instruction: `age_group2diff2age_group`.\n",
    "Make sure to specify the case and control age groups exactly as specified in the `p3_entities_with_type.csv` file.\n",
    "\n",
    "We can leave most other prompt fields empty but you are free to modify them and thus reproduce a different setting. E.g. you can leave `tissue` vacant and fill in the `cell` field to enable an *in vitro* setting, or you can specify the `drug` to explore how a compound affects the aging signature."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "36fac0e0-79a8-4128-9604-81b382639b84",
   "metadata": {},
   "outputs": [],
   "source": [
    "tissue_options = ['skin', 'muscle', 'whole blood', 'epithelium', 'artery', 'fat tissue', 'brain', 'liver']\n",
    "domain_options = ['methylation', 'proteomics', 'expression']\n",
    "\n",
    "prompt_config_age = {\n",
    "        \"instruction\": 'age_group2diff2age_group',\n",
    "        \"tissue\": '', #insert tissue here\n",
    "        \"age\": \"\",\n",
    "        \"cell\": \"\", #insert cell line here\n",
    "        \"efo\": \"\",\n",
    "        \"datatype\": \"\",\n",
    "        \"drug\": \"\", #insert cpd here if any\n",
    "        \"dose\": \"\",\n",
    "        \"time\": \"\",\n",
    "        \"case\": \"70.0-80.0\",\n",
    "        \"control\": \"19.95-25.0\",\n",
    "        \"dataset_type\": \"\", #insert domain here\n",
    "        \"gender\": \"\",\n",
    "        \"species\": \"human\",\n",
    "        \"up\": [],\n",
    "        \"down\": []\n",
    "    }"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "872a6b5d-4d52-46f9-839f-7378153d2f67",
   "metadata": {},
   "source": [
    "The `endpoints.py` module contains several options to invoke P3GPT.\n",
    "Unless your input prompt contains lists of up-/down-regulated genes, it is advised to use `EndpointHandler` for local inference.\n",
    "\n",
    "The only parameter you need to specify at handler initialization is the GPU device to deploy P3GPT on."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f85d0b5b-7b50-400b-82ad-bd655a137da6",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/f.galkin/.cache/huggingface/modules/transformers_modules/mosaicml/mpt-7b/039e37745f00858f0e01e988383a8c4393b1a4f5/configuration_mpt.py:114: UserWarning: alibi or rope is turned on, setting `learned_pos_emb` to `False.`\n",
      "  warnings.warn(f'alibi or rope is turned on, setting `learned_pos_emb` to `False.`')\n",
      "/home/f.galkin/.cache/huggingface/modules/transformers_modules/mosaicml/mpt-7b/039e37745f00858f0e01e988383a8c4393b1a4f5/configuration_mpt.py:141: UserWarning: If not using a Prefix Language Model, we recommend setting \"attn_impl\" to \"flash\" instead of \"triton\".\n",
      "  warnings.warn(UserWarning('If not using a Prefix Language Model, we recommend setting \"attn_impl\" to \"flash\" instead of \"triton\".'))\n"
     ]
    }
   ],
   "source": [
    "handler = EndpointHandler(device='cuda:2')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4df757f-7abd-4d50-9b3c-888b2d1208d0",
   "metadata": {},
   "source": [
    "With 8 tissues and 3 omics domains, you will generate a total of 24 aging signatures.\n",
    "\n",
    "The default mode of execution for P3GPT is prompt completion, which is inherently stocahstic. To avoid any sampling effects, we enabled a special mode of P3GPT execution in `EndpointHandler`. Instead of generating gene tokens one at a time, we access the complete output probability distribution for up- and down-regulated genes and take top-N tokens from them.\n",
    "\n",
    "We can treat a gene's output probability as a proxy for its importance in the aging process to be used later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "2a654df4-93cd-4e53-8468-99a870e427f0",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running generations for skin-methylation\n",
      "[BOS]<age_group2diff2age_group><tissue>skin </tissue><cell></cell><efo></efo><datatype></datatype><drug></drug><dose></dose><time></time><case>70.0-80.0 </case><control>19.95-25.0 </control><dataset_type>methylation </dataset_type><gender></gender><species>human </species><up>\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/f.galkin/.cache/huggingface/modules/transformers_modules/mosaicml/mpt-7b/039e37745f00858f0e01e988383a8c4393b1a4f5/attention.py:87: UserWarning: Propagating key_padding_mask to the attention module and applying it within the attention module can cause unnecessary computation/memory usage. Consider integrating into attn_bias once and passing that to each attention module instead.\n",
      "  warnings.warn('Propagating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unnecessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is token index where gene should be predicted:  1\n",
      "[BOS]<age_group2diff2age_group><tissue>skin </tissue><cell></cell><efo></efo><datatype></datatype><drug></drug><dose></dose><time></time><case>70.0-80.0 </case><control>19.95-25.0 </control><dataset_type>methylation </dataset_type><gender></gender><species>human </species>\n",
      "This is token index where gene should be predicted:  260\n",
      "Running generations for skin-proteomics\n",
      "[BOS]<age_group2diff2age_group><tissue>skin </tissue><cell></cell><efo></efo><datatype></datatype><drug></drug><dose></dose><time></time><case>70.0-80.0 </case><control>19.95-25.0 </control><dataset_type>proteomics </dataset_type><gender></gender><species>human </species><up>\n",
      "This is token index where gene should be predicted:  1\n",
      "[BOS]<age_group2diff2age_group><tissue>skin </tissue><cell></cell><efo></efo><datatype></datatype><drug></drug><dose></dose><time></time><case>70.0-80.0 </case><control>19.95-25.0 </control><dataset_type>proteomics </dataset_type><gender></gender><species>human </species>\n",
      "This is token index where gene should be predicted:  259\n",
      "Running generations for skin-expression\n",
      "...\n",
      "Running generations for liver-expression\n",
      "[BOS]<age_group2diff2age_group><tissue>liver </tissue><cell></cell><efo></efo><datatype></datatype><drug></drug><dose></dose><time></time><case>70.0-80.0 </case><control>19.95-25.0 </control><dataset_type>expression </dataset_type><gender></gender><species>human </species><up>\n",
      "This is token index where gene should be predicted:  1\n",
      "[BOS]<age_group2diff2age_group><tissue>liver </tissue><cell></cell><efo></efo><datatype></datatype><drug></drug><dose></dose><time></time><case>70.0-80.0 </case><control>19.95-25.0 </control><dataset_type>expression </dataset_type><gender></gender><species>human </species>\n",
      "[BOS]<age_group2diff2age_group><tissue>liver </tissue><cell></cell><efo></efo><datatype></datatype><drug></drug><dose></dose><time></time><case>70.0-80.0 </case><control>19.95-25.0 </control><dataset_type>expression </dataset_type><gender></gender><species>human </species>\n",
      "This is token index where gene should be predicted:  261\n"
     ]
    }
   ],
   "source": [
    "generations = {z:{x:{y:[] for y in ('up', 'down')}for x in domain_options} for z in tissue_options}\n",
    "for tis in generations:\n",
    "    prompt_config_age['tissue'] = tis\n",
    "    for dom in generations[tis]:\n",
    "        print(f\"Running generations for {tis}-{dom}\")\n",
    "        prompt_config_age['dataset_type'] = dom\n",
    "        for direct in generations[tis][dom]:\n",
    "            # uses the get_gene_probabilities method to get a list of top-k genes by their output probability\n",
    "            try:\n",
    "                generations[tis][dom][direct] = handler.get_gene_probabilities(prompt_config=prompt_config_age, top_k=100, list_type=direct,\n",
    "                                                                               random_seed = 137)\n",
    "            except ValueError:\n",
    "                # invoke P3GPT with a non-default random seed in case you encounter any errors in your generation\n",
    "                generations[tis][dom][direct] = handler.get_gene_probabilities(prompt_config=prompt_config_age, top_k=100, list_type=direct,\n",
    "                                                                               random_seed = 138)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d585e881-3057-4e7a-a609-e7982e891237",
   "metadata": {},
   "source": [
    "### ↓ This file stores the generated up-down lists for aging tissues"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4f38b543-3109-40ff-b73d-a30d152de159",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('./1Aug2024_aging_signatures.pckl', 'wb') as f:\n",
    "    pickle.dump(generations,f)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e631b582-b393-4084-b528-df5a8540272f",
   "metadata": {},
   "source": [
    "> 💡 **Note**: You may load the file above directly to skip step-1 and use P3GPT-generated aging signature in your TCM research\n",
    "```python\n",
    "with open('./1Aug2024_aging_signatures.pckl', 'rb') as f:\n",
    "    generations = pickle.load(f)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed5e17cb-0242-40be-bd24-056d3ad61bc1",
   "metadata": {},
   "source": [
    "## 2. Screen TCM compounds"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e8f2ea2-1298-4ecc-9686-e7426afd9a1b",
   "metadata": {},
   "source": [
    "The file below contains 659 TCM ingredients that are represented in the P3GPT training set.\n",
    "\n",
    "The BATMAN catalog refers to compounds by Pubchem CIDs while P3GPT uses conventional names, so we created a mapping CID→Names.\n",
    "BATMAN also specifies protein targets the compounds are known or predicted to affect. We will measure the overlap between these lists and the P3GPT-generated aging signatures to find the most promising compounds. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "4dd3cd2e-0b8c-413f-87fb-0ce9bd0464e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('./P3GPT_compound_targets.pckl', 'rb') as f:\n",
    "    TCM_cpds = pickle.load(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "fe272676-96c6-401b-af36-31896daad5a0",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(5281792,\n",
       " {'title': 'rosmarinic-acid',\n",
       "  'known_targets': {'symbols': ['C5', 'CCR3', 'CCL2', 'PREP', 'NFKB1',\n",
       "                                'IKBKB', 'CASP3', 'C3', 'OLIG2', 'CCL11', \n",
       "                                'CD86', 'AURKA', 'IL2', 'F2', 'IDO1',\n",
       "                                'IL4', 'RPS6KB1','ABAT', 'CCL3','STAT1',\n",
       "                                'CD80', 'IL5', 'IL6'],\n",
       "                    'entrez_ids': [18, 3565, 4790, 836, 3551,\n",
       "                                   3620, 6772, 718, 2147, 3558,\n",
       "                                   3569, 6347, 6356, 727, 6790,\n",
       "                                   3567, 942, 6348, 10215, 6198,\n",
       "                                   5550, 1232, 941]},\n",
       "  'predicted_targets': {'symbols': ['IFNG', 'PTGS1', 'PTGS2', 'TPMT'],\n",
       "  'entrez_ids': [3458, 5742, 5743, 7172]}})"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# See what an entry in the mapping looks like\n",
    "list(TCM_cpds.items())[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "324be182-fd49-4b5f-bc65-7c59ff56e46b",
   "metadata": {},
   "source": [
    "Next, let's count how many times each compound's targets pop up in the generated signatures. To see if the overlap between targets and important aging genes is significant, we'll apply Fisher's exact test. As the background set, we shall use the total number of genes used by P3GPT — 25,332. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "853128d9-bafb-407a-9234-7376914ab9c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "list_len = 100\n",
    "enrich_stats = pd.DataFrame(None, index = None,\n",
    "                            columns = ['compound', 'cid', 'tissue', 'domain',\n",
    "                                       'p_value', 'target_type', 'N_targets',\n",
    "                                       'hit_targets'])\n",
    "for cid in TCM_cpds:\n",
    "    tg_sets = {'known':set(TCM_cpds[cid]['known_targets']['symbols']),\n",
    "              \"predicted\":set(TCM_cpds[cid]['predicted_targets']['symbols'])}\n",
    "    tg_sets[\"both\"] = tg_sets['known'] | tg_sets['predicted']\n",
    "    for tis in generations:\n",
    "        for dom in generations[tis]:\n",
    "            p3_set = set(generations[tis][dom]['up'][:list_len] + generations[tis][dom]['down'][:list_len])\n",
    "            for tg_type, tg_set in tg_sets.items():\n",
    "                p3_hits = tg_set & p3_set\n",
    "                # cols: in targets, not in targets\n",
    "                # rows: in P3 output, not in P3 output\n",
    "                cont_table = (a := np.array([[len(p3_hits), len(tg_set - p3_hits)],\n",
    "                                                  [len(p3_hits - tg_set), 0]])) + \\\n",
    "                                  np.array([[0, 0],\n",
    "                                            [0, 25332 - a.sum().sum()]])\n",
    "\n",
    "                F_exact = fisher_exact(table=cont_table, alternative='greater')\n",
    "                #['compound', 'tissue', 'domain', 'p_value', 'target_type']\n",
    "                enrich_stats.loc[enrich_stats.shape[0],:] = [TCM_cpds[cid]['title'],\n",
    "                                                             cid,\n",
    "                                                             tis,\n",
    "                                                             dom,\n",
    "                                                             F_exact[1],\n",
    "                                                             tg_type,\n",
    "                                                             len(tg_set),\n",
    "                                                             len(p3_hits)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "9bb28a7d-b1f2-4159-b93c-3acad16d8d22",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total number of tests: 47448\n"
     ]
    }
   ],
   "source": [
    "print(f\"Total number of tests: {enrich_stats.shape[0]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "170d3779-0f09-4b93-b26c-2cf2c75bd712",
   "metadata": {},
   "source": [
    "Since we have run thousands of statistical tests, it makes sense to include a multiple comparison correction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "d087b76b-978d-4f87-81fc-97e3b8c0dad7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Remaining entries: 8866\n",
      "Compounds that passed 1+ enrichment tests: 424\n"
     ]
    }
   ],
   "source": [
    "enrich_stats[\"corr_Pv\"] = [min(1, x) for x in enrich_stats[\"p_value\"] * enrich_stats.shape[0]]\n",
    "enrich_stats = enrich_stats[enrich_stats[\"corr_Pv\"]<.001]\n",
    "print(f\"Remaining entries: {enrich_stats.shape[0]}\")\n",
    "print(f'Compounds that passed 1+ enrichment tests: {len(enrich_stats.compound.unique())}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9817c0b-51f2-4b7a-913c-9741345f1895",
   "metadata": {},
   "source": [
    "We can now zoom in on the compounds that passed the test.\n",
    "\n",
    "Out of all 659 TCM compounds, the targets of 424 of them significantly overlapped with an aging aging signature.\n",
    "Let's trim the table of significant enrichments even further by considering only the documented targets. \n",
    "\n",
    "> 💡 **Note:** You may choose a different target confirmation level. Looking for enrichment in known targets creates a bias toward well-studied compounds. Such popular anti-aging compounds as curcumin, for example, have thousands of publications covering their cellular interactions. Meanwhile, an obscure but an equally potent geroprotector may have zero known targets. Repeating this workflow with predicted targets is likely to provide more novel compounds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "3f71d393-2f67-4257-97a4-9a46b62ff334",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Remaining entries: 375\n",
      "Compounds that passed 1+ enrichment tests: 80\n"
     ]
    }
   ],
   "source": [
    "confirmation_level = 'known'\n",
    "enrich_stats = enrich_stats[enrich_stats[\"target_type\"]==confirmation_level]\n",
    "print(f\"Remaining entries: {enrich_stats.shape[0]}\")\n",
    "print(f'Compounds that passed 1+ enrichment tests: {len(enrich_stats.compound.unique())}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acf8a7b2-21c4-4394-adb1-77fba7e950f4",
   "metadata": {},
   "source": [
    "80 compounds is a much more manageable compound selection.\n",
    "\n",
    "These TCM compounds are targetting the genes involved in aging and may be considered for futher investigation *in vitro* or *in vivo*.\n",
    "But what if we we wanted to compose a cocktail of TCM ingredients that will slow down the aging processes in as many tissues as possible?\n",
    "Are there any TCM compounds that have been detected in 8/8 tissues?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "812aaa05-8ead-4cfb-b9f4-59ea7b25ead9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--- N potential geroprotectors identified in each tissue ---\n",
      "N skin-compounds = 38\n",
      "N muscle-compounds = 25\n",
      "N whole blood-compounds = 48\n",
      "N epithelium-compounds = 19\n",
      "N artery-compounds = 32\n",
      "N fat tissue-compounds = 17\n",
      "N brain-compounds = 47\n",
      "N liver-compounds = 23\n",
      "\n",
      "--- TCM ingredients targeting aging in 6 tissues (N = 4) ---\n",
      "alpha-tocopherol\n",
      "capsaicin\n",
      "baicalin\n",
      "testosterone\n",
      "\n",
      "--- TCM ingredients targeting aging in 7 tissues (N = 2) ---\n",
      "kaempferol\n",
      "triptolide\n",
      "\n",
      "--- TCM ingredients targeting aging in 8 tissues (N = 8) ---\n",
      "colchicine\n",
      "quercetin\n",
      "apigenin\n",
      "resveratrol\n",
      "curcumin\n",
      "brd-k55591206;epigallocatechin 3-gallate\n",
      "estradiol\n",
      "progesterone\n"
     ]
    }
   ],
   "source": [
    "cpd_counts = {}\n",
    "print(\"--- N potential geroprotectors identified in each tissue ---\")\n",
    "for t in tissue_options:\n",
    "    tis_df = enrich_stats[(enrich_stats.tissue == t)& \\\n",
    "                          (enrich_stats.target_type == confirmation_level)]\n",
    "    print(f'N {t}-compounds = {len(tis_df.compound.unique())}')\n",
    "    for cpd in tis_df.compound.unique():\n",
    "        if cpd not in cpd_counts:\n",
    "            cpd_counts[cpd] = 0\n",
    "        cpd_counts[cpd]+=1\n",
    "\n",
    "cpds_by_tis_count = dict()\n",
    "for i in range(1,9):\n",
    "    cpds_by_tis_count[i] = [x for x,y in cpd_counts.items() if y == i]\n",
    "\n",
    "for i in (6,7,8):\n",
    "    print(f\"\\n--- TCM ingredients targeting aging in {i} tissues (N = {len(cpds_by_tis_count[i])}) ---\")\n",
    "    print(*cpds_by_tis_count[i], sep ='\\n')\n",
    "    \n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "931bf007-843e-41b3-b0ef-be7d754b025c",
   "metadata": {},
   "source": [
    "A total of 14 compounds were detected as potential geroprotectors in 6+ tissues, while almost half of all detected ingredients affect agig only in one tissue.\n",
    "Among them, 8 were targetting the aging signatures in 8/8 tissues. \n",
    "\n",
    "<center><img src=\"https://huggingface.co/datasets/f-galkin/batman2/resolve/main/demo/imgs/cpds_affecting_tissue_aging.svg\" width=\"600\" ></center>\n",
    "\n",
    "> 💡 **Note:** The compounds we call \"potential geroprotectors\" may in fact accelerate aging. When we difined important aging genes, we did binned the up- and down-regulated genes together, although the directionality of change is extremely important in this setting. Additionally, the mechanism of action (agonist/antagonist) of a TCM ingredient needs to be taken into account. We can lean on the fact that most compounds in BATMAN are generally considered safe or even beneficial to the organism, but ultimately, the final list of TCM geroprotectors needs to be manually reviewed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16a8fec8-6587-41d0-bde7-1d1f42a69812",
   "metadata": {},
   "source": [
    "## 3. Selecting a TCM formula\n",
    "\n",
    "Now that we have a list of 14 compounds with a systemic effect on aging, we can leverage BATMAN to do either of the following:\n",
    "\n",
    "- Screen existing TCM formulas to find those that contain as many compounds from our list as possible;\n",
    "- Make a new TCM formula ourselves by selecting herbs one by one.\n",
    "\n",
    "We will demonstrate only the former option in this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "189c2367-4a63-44b5-a0be-1a9d5b65c35c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Here are the CIDs of the potential geroprotectors \n",
    "# we identified in section 2\n",
    "cids = [969516, #curcumin\n",
    "        445154, #resveratrol\n",
    "        5280343, #quercetin\n",
    "        6167, #colchicine\n",
    "        5280443, #apigening\n",
    "        65064, #EGCG3\n",
    "        5757, # estradiol\n",
    "        5994, # progesterone\n",
    "        5280863, # kaempferol\n",
    "        107985, # triptolide\n",
    "        14985, #alpha-tocopherol\n",
    "        1548943, # Capsaicin\n",
    "        64982, # Baicalin\n",
    "        6013, # Testosterone\n",
    "        ]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1969f91-d51b-4974-b1d6-fe9f834f7462",
   "metadata": {},
   "source": [
    "For the sake of brevity, we have externalized the scripts used to parse BATMAN files into linked lists of ingredients-herbs-formulas with the `formula_picker.py` mini module available at the [batman2](https://huggingface.co/datasets/f-galkin/batman2) dataset repository. \n",
    "\n",
    "Feel free reuse the scripts and files we prepared in your own TCM-related projects. If you don't need our `TCMDB` wrapper class, you can access BATMAN data tables directly by executing the following commands:\n",
    "```python\n",
    "from datasets import load_dataset\n",
    "batman_ingredients = load_dataset(\"f-galkin/batman2\", \"batman_ingredients\")\n",
    "batman_herbs = load_dataset(\"f-galkin/batman2\", \"batman_herbs\")\n",
    "batman_formulas = load_dataset(\"f-galkin/batman2\", \"batman_formulas\")\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "73c59513-f48e-4570-8c66-8bfc5cfb547d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from P3LIB.formula_picker import TCMDB\n",
    "from datasets import load_dataset\n",
    "db = TCMDB.download_from_hf()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2acc6a91-51ab-4626-993e-5689eb03858c",
   "metadata": {},
   "source": [
    "We formatted the BATMAN files (accessed on 8/1/2024) to support basic search operations, such as looking up a TCM formula that has the maximum amount of the compounds provided in a query."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "ee611008-0335-4243-824e-2c78e032c844",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "13 compounds of 14 are encountered in the following TCM formulas:\n",
      "['ZHANG ZHOU SHEN QU']\n"
     ]
    }
   ],
   "source": [
    "p3_formula = db.select_formula_by_cpd(cids)\n",
    "print(\"%s compounds of 14 are encountered in the following TCM formulas:\\n%s\"%p3_formula)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60706086-fc5f-4b10-9355-d5e1f11e3507",
   "metadata": {},
   "source": [
    "Not a single TCM formula out of the 54,832 described in BATMAN2 has all the 14 potential geroprotectors we selected.\n",
    "And only 1 formula has 13/14 compounds — ZHANG ZHOU SHEN QU. Let's take a closer look at it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "d2ddf3f9-5515-49e2-8409-0caaf5aac4cd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The contents of the ZHANG ZHOU SHEN QU (漳州神曲) TCM formula\n",
      "1. Weeping forsythia (连翘)\n",
      "2. Tsaoko (草果)\n",
      "3. Yerbadetajo (墨旱莲)\n",
      "4. Haichow elsholtzia (香薷)\n",
      "5. Common anemarrhena (知母)\n",
      "6. Medicine terminalia equivalent plant: terminalia chebula var tomentella (诃子)\n",
      "7. Slenderstyle acanthopanax root-bark equivalent plant:  acanthopanax sessiliflorus ,  acanthopanax senticosus (五加皮)\n",
      "8. Dried tangerine peel (陈皮)\n",
      "9. Bark of officinal magnolia (厚朴)\n",
      "10. Perilia fruit (紫苏子)\n",
      "11. Oriental waterplantain (泽泻)\n",
      "12. Chinese hawthorn equivalent plant: crataegus pinnatifida  var major (山楂)\n",
      "13. Common hogfennel equivalent plant:  peucedanum praeruptorum ,  peucedanum longshengens,  peucedanum rubricaule , ligusticum brachylobum (前胡)\n",
      "14. Glabrous greenbrier equivalent plant: smilax menispermoidea (土茯苓)\n",
      "15. Chinese star anise (八角茴香)\n",
      "16. White mulberry branch (桑枝)\n",
      "17.  (槟榔)\n",
      "18. Wild mint (薄荷)\n",
      "19. Pummelo peel (化橘红)\n",
      "20. Mongolian snakegourd root (天花粉)\n",
      "21. Red peony root (赤芍)\n",
      "22. Grassleaved sweetflag equivalent plant:  acorus gramineus (石菖蒲)\n",
      "23. Lesser galangal (高粱姜)\n",
      "24. Common yam equivalent plant: dioscorea japonica (山药)\n",
      "25. Fineleaf schizonepeta (荆芥)\n",
      "26. Doubleteeth pubescent angelica equivalent plant: heracleum lanatum (独活)\n",
      "27. Amur corktree equivalent plant: phellodendron chinense , phellodendron chinense  var glabriusculum,  phellodendron amurense  var wilsonii (黄柏)\n",
      "28. Barley germinating fruit (麦芽)\n",
      "29. Incised notopterygium equivalent plant:  notopterygium forbesii (羌活)\n",
      "30. Nutgrass galingale (香附)\n",
      "31. Seed of gordon euryale (芡实)\n",
      "32. Largehead atractylodes (白术)\n",
      "33. Seville orange young fruit equivalent plant: citrus wilsonii ,  poncirus trifoliata (枳实)\n",
      "34. Rangooncreeper (使君子)\n",
      "35. Baikal skullcap equivalent plant:  scutellaria amoena ,  scutellaria viscidula, scutellaria likiangensis ,  scutellaria rehderiana,  scutellaria hypericifolia (黄芩)\n",
      "36. Common nutmeg (肉豆蔻)\n",
      "37. Common burreed (三棱)\n",
      "38. Ural licorice equivalent plant: glycyrrhiza inflata, glycyrrhiza glabra, glycyrrhiza kansuensis, glycyrrhiza aspera, glycyrrhiza yunnanensis , glycyrrhiza squamulosa (甘草)\n",
      "39. Common aucklandia (costustoot) (木香)\n",
      "40. Zedoray rhizome (莪术)\n",
      "41. Medicinal rhubarb equivalent plant: rheum palmatum,  rheum tanguticum (大黄)\n",
      "42. Celery wormwood (青蒿)\n",
      "43. Common perilla leaf equivalent plant:  perilla frutescens var acuta (紫苏叶)\n",
      "44. Fruit of seville orange (枳壳)\n",
      "45. Divaricate saposhnikovia (防风)\n",
      "46. Fennel fruit (小茴香)\n",
      "47. Root - bark of chinese wolfberry (地骨皮)\n",
      "48. Cassiabarktree twig (桂枝)\n",
      "49. Swordlike atractylodes equivalent plant: atractylodes chinensis,  atractylodes japonica (苍术)\n",
      "50. Lobed kudzuvine root equivalent plant: pueraria thomsonii, pueraria edulis,  pueraria omeiensis ,  pueraria phaseoloides (葛根)\n",
      "51. Indian bread (茯苓)\n",
      "52. Rice bean (赤小豆)\n",
      "53. Dahurian angelica (白芷)\n",
      "54. Cassiabarktree (肉桂)\n",
      "55. Balloonflower (桔梗)\n",
      "56. Chinese nardostachys equivalent plant: nardostachys jatamansi (甘松)\n",
      "57. Galanga resurrectionlily (山柰)\n",
      "58. Bitter apricot seed (苦杏仁)\n",
      "59. White hyacinth bean (白扁豆)\n",
      "60. Bunge pricklyash equivalent plant: zanthoxylum schinifolium (花椒)\n",
      "61. Bugbane equivalent plant: cimicifuga dahurica,  cimicifuga heracleifolia (升麻)\n",
      "62. Chinese ephedra equivalent plant: ephedra equisetina , ephedra intermedia ,  ephedra minuta , ephedra monosperma, ephedra likiangensis,  ephedra saxatilis, ephedra gerardiana (麻黄)\n",
      "63. Jobstears seed (薏苡仁)\n",
      "64. Garden radish seed (莱菔子)\n",
      "65. Common selfheal (夏枯草)\n",
      "66. Common ginger dried rhizome (干姜)\n",
      "67. Shiny bugleweed (泽兰)\n",
      "68. Green tangerine peel (青皮)\n",
      "69. Chinese thorowax equivalent plant: bupleurum scorzonerifolium,  bupleurum smithii  var parvifolium ,  bupleurum aureum, bupleurum longiradiatum, bupleurum marginatum , bupleurum marginatum var stenophyllum, bupleurum angustissimum,  bupleurum chaishoui, bupleurum wenchuanense ,  bupleurum sibiricum,  bupleurum yinchowense (柴胡)\n",
      "70. Cape jasmine fruit (栀子)\n",
      "71. Virgate wormwood herb (茵陈)\n",
      "72. Clove tree (丁香)\n",
      "73. Combined spicebush (乌药)\n",
      "74. Cablin potchouli (广霍香)\n",
      "75. Villous amomum equivalent plant: amomum xanthioides ,  amomum longiligulare (砂仁)\n"
     ]
    }
   ],
   "source": [
    "pinyin_name = 'ZHANG ZHOU SHEN QU'\n",
    "print(f'The contents of the {pinyin_name} ({db.formulas[pinyin_name].synonyms[0]}) TCM formula')\n",
    "for i, herb in enumerate(db.formulas[pinyin_name].herbs):\n",
    "    print(f\"{i+1}. {herb.synonyms[2]} ({herb.synonyms[1]})\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "690e5223-3091-4dd0-9944-e6c4c7323abf",
   "metadata": {},
   "source": [
    "The formula we ended up with is quite complex and contains 75 herbal components, such as nutmeg, turmeric, scutellaria, citrus peels, patchouli and others.\n",
    "\n",
    "You can learn more about this composition on other [TCM databases](https://bidd.group/TCMID/tcmf.php?formula=TCMFx6833). For now, that is where we shall conclude our search"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ism311",
   "language": "python",
   "name": "myenv"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}