f-galkin commited on
Commit
d851abd
1 Parent(s): 4fb1494

remove abc dependency

Browse files
Files changed (1) hide show
  1. demo/P3LIB/formula_picker.py +546 -549
demo/P3LIB/formula_picker.py CHANGED
@@ -1,549 +1,546 @@
1
- import pandas as pd
2
- import pickle
3
- from typing import List, Dict, Optional
4
- from copy import copy as cp
5
- import json
6
-
7
- from abc import ABC, abstractmethod
8
-
9
-
10
- class TCMEntity(ABC):
11
- empty_override = True
12
- desc = ''
13
- cid = -1
14
- entity = 'superclass'
15
-
16
- def __init__(self,
17
- pref_name: str, desc: str = '',
18
- synonyms: Optional[List[str]] = None,
19
- **kwargs):
20
- self.pref_name = pref_name
21
- self.desc = desc
22
- self.synonyms = [] if synonyms is None else [x for x in synonyms if str(x).strip() != 'NA']
23
-
24
- self.targets = {"known": dict(), "predicted": dict()}
25
-
26
- self.formulas = []
27
- self.herbs = []
28
- self.ingrs = []
29
-
30
- for k, v in kwargs.items():
31
- self.__dict__[k] = v
32
-
33
- def serialize(self):
34
- init_dict = dict(
35
- cid=self.cid,
36
- targets_known=self.targets['known'],
37
- targets_pred=self.targets['predicted'],
38
- pref_name=self.pref_name, desc=self.desc,
39
- synonyms=cp(self.synonyms),
40
- entity=self.entity
41
- )
42
- link_dict = self._get_link_dict()
43
- out_dict = {"init": init_dict, "links": link_dict}
44
- return out_dict
45
-
46
- @classmethod
47
- def load(cls,
48
- db: 'TCMDB', ser_dict: dict,
49
- skip_links = True):
50
- init_args = ser_dict['init']
51
-
52
- if skip_links:
53
- init_args.update({"empty_override":True})
54
- else:
55
- init_args.update({"empty_override": False})
56
-
57
- new_entity = cls(**init_args)
58
- if not skip_links:
59
- links = ser_dict['links']
60
- new_entity._set_links(db, links)
61
- return (new_entity)
62
-
63
- def _get_link_dict(self):
64
- return dict(
65
- ingrs=[x.cid for x in self.ingrs],
66
- herbs=[x.pref_name for x in self.herbs],
67
- formulas=[x.pref_name for x in self.formulas]
68
- )
69
-
70
- def _set_links(self, db: 'TCMDB', links: dict):
71
- for ent_type in links:
72
- self.__dict__[ent_type] = [db.__dict__[ent_type].get(x) for x in links[ent_type]]
73
- self.__dict__[ent_type] = [x for x in self.__dict__[ent_type] if x is not None]
74
-
75
-
76
- class Ingredient(TCMEntity):
77
- entity: str = 'ingredient'
78
-
79
- def __init__(self, cid: int,
80
- targets_pred: Optional[Dict] = None,
81
- targets_known: Optional[Dict] = None,
82
- synonyms: Optional[List[str]] = None,
83
- pref_name: str = '', desc: str = '',
84
- empty_override: bool = True, **kwargs):
85
-
86
- if not empty_override:
87
- assert targets_known is not None or targets_pred is not None, \
88
- f"Cant submit a compound with no targets at all (CID:{cid})"
89
-
90
- super().__init__(pref_name, synonyms, desc, **kwargs)
91
-
92
- self.cid = cid
93
- self.targets = {
94
- 'known': targets_known if targets_known is not None else {"symbols": [], 'entrez_ids': []},
95
- 'predicted': targets_pred if targets_pred is not None else {"symbols": [], 'entrez_ids': []}
96
- }
97
-
98
-
99
- class Herb(TCMEntity):
100
- entity: str = 'herb'
101
-
102
- def __init__(self, pref_name: str,
103
- ingrs: Optional[List[Ingredient]] = None,
104
- synonyms: Optional[List[str]] = None,
105
- desc: str = '',
106
- empty_override: bool = True, **kwargs):
107
-
108
- if ingrs is None:
109
- ingrs = []
110
-
111
- if not ingrs and not empty_override:
112
- raise ValueError(f"No ingredients provided for {pref_name}")
113
-
114
- super().__init__(pref_name, synonyms, desc, **kwargs)
115
-
116
- self.ingrs = ingrs
117
-
118
- def is_same(self, other: 'Herb') -> bool:
119
- if len(self.ingrs) != len(other.ingrs):
120
- return False
121
- this_ingrs = set(x.cid for x in self.ingrs)
122
- other_ingrs = set(x.cid for x in other.ingrs)
123
- return this_ingrs == other_ingrs
124
-
125
-
126
- class Formula(TCMEntity):
127
- entity: str = 'formula'
128
-
129
- def __init__(self, pref_name: str,
130
- herbs: Optional[List[Herb]] = None,
131
- synonyms: Optional[List[str]] = None,
132
- desc: str = '',
133
- empty_override: bool = False, **kwargs):
134
-
135
- if herbs is None:
136
- herbs = []
137
-
138
- if not herbs and not empty_override:
139
- raise ValueError(f"No herbs provided for {pref_name}")
140
-
141
- super().__init__(pref_name, synonyms, desc, **kwargs)
142
- self.herbs = herbs
143
-
144
- def is_same(self, other: 'Formula') -> bool:
145
- if len(self.herbs) != len(other.herbs):
146
- return False
147
- this_herbs = set(x.pref_name for x in self.herbs)
148
- other_herbs = set(x.pref_name for x in other.herbs)
149
- return this_herbs == other_herbs
150
-
151
-
152
- class TCMDB:
153
- hf_repo: str = "f-galkin/batman2"
154
- hf_subsets: Dict[str, str] = {'formulas': 'batman_formulas',
155
- 'herbs': 'batman_herbs',
156
- 'ingredients': 'batman_ingredients'}
157
-
158
- def __init__(self, p_batman: str):
159
- p_batman = p_batman.removesuffix("/") + "/"
160
-
161
- self.batman_files = dict(p_formulas='formula_browse.txt',
162
- p_herbs='herb_browse.txt',
163
- p_pred_by_tg='predicted_browse_by_targets.txt',
164
- p_known_by_tg='known_browse_by_targets.txt',
165
- p_pred_by_ingr='predicted_browse_by_ingredinets.txt',
166
- p_known_by_ingr='known_browse_by_ingredients.txt')
167
-
168
- self.batman_files = {x: p_batman + y for x, y in self.batman_files.items()}
169
-
170
- self.ingrs = None
171
- self.herbs = None
172
- self.formulas = None
173
-
174
- @classmethod
175
- def make_new_db(cls, p_batman: str):
176
- new_db = cls(p_batman)
177
-
178
- new_db.parse_ingredients()
179
- new_db.parse_herbs()
180
- new_db.parse_formulas()
181
-
182
- return (new_db)
183
-
184
- def parse_ingredients(self):
185
-
186
- pred_tgs = pd.read_csv(self.batman_files['p_pred_by_tg'],
187
- sep='\t', index_col=None, header=0,
188
- na_filter=False)
189
- known_tgs = pd.read_csv(self.batman_files['p_known_by_tg'],
190
- sep='\t', index_col=None, header=0,
191
- na_filter=False)
192
- entrez_to_symb = {int(pred_tgs.loc[x, 'entrez_gene_id']): pred_tgs.loc[x, 'entrez_gene_symbol'] for x in
193
- pred_tgs.index}
194
- # 9927 gene targets
195
- entrez_to_symb.update({int(known_tgs.loc[x, 'entrez_gene_id']): \
196
- known_tgs.loc[x, 'entrez_gene_symbol'] for x in known_tgs.index})
197
-
198
- known_ingreds = pd.read_csv(self.batman_files['p_known_by_ingr'],
199
- index_col=0, header=0, sep='\t',
200
- na_filter=False)
201
- # this BATMAN table is badly formatted
202
- # you cant just read it
203
- # df_pred = pd.read_csv(p_pred, index_col=0, header=0, sep='\t')
204
- pred_ingreds = dict()
205
- with open(self.batman_files['p_pred_by_ingr'], 'r') as f:
206
- # skip header
207
- f.readline()
208
- newline = f.readline()
209
- while newline != '':
210
- cid, other_line = newline.split(' ', 1)
211
- name, entrez_ids = other_line.rsplit(' ', 1)
212
- entrez_ids = [int(x.split("(")[0]) for x in entrez_ids.split("|") if not x == "\n"]
213
- pred_ingreds[int(cid)] = {"targets": entrez_ids, 'name': name}
214
- newline = f.readline()
215
-
216
- all_BATMAN_CIDs = list(set(pred_ingreds.keys()) | set(known_ingreds.index))
217
- all_BATMAN_CIDs = [int(x) for x in all_BATMAN_CIDs if str(x).strip() != 'NA']
218
-
219
- # get targets for selected cpds
220
- ingredients = dict()
221
- for cid in all_BATMAN_CIDs:
222
- known_name, pred_name, synonyms = None, None, []
223
- if cid in known_ingreds.index:
224
- known_name = known_ingreds.loc[cid, 'IUPAC_name']
225
- known_symbs = known_ingreds.loc[cid, 'known_target_proteins'].split("|")
226
- else:
227
- known_symbs = []
228
-
229
- pred_ids = pred_ingreds.get(cid, [])
230
- if pred_ids:
231
- pred_name = pred_ids.get('name')
232
- if known_name is None:
233
- cpd_name = pred_name
234
- elif known_name != pred_name:
235
- cpd_name = min([known_name, pred_name], key=lambda x: sum([x.count(y) for y in "'()-[]1234567890"]))
236
- synonyms = [x for x in [known_name, pred_name] if x != cpd_name]
237
-
238
- pred_ids = pred_ids.get('targets', [])
239
-
240
- ingredients[cid] = dict(pref_name=cpd_name,
241
- synonyms=synonyms,
242
- targets_known={"symbols": known_symbs,
243
- "entrez_ids": [int(x) for x, y in entrez_to_symb.items() if
244
- y in known_symbs]},
245
- targets_pred={"symbols": [entrez_to_symb.get(x) for x in pred_ids],
246
- "entrez_ids": pred_ids})
247
- ingredients_objs = {x: Ingredient(cid=x, **y) for x, y in ingredients.items()}
248
- self.ingrs = ingredients_objs
249
-
250
- def parse_herbs(self):
251
- if self.ingrs is None:
252
- raise ValueError("Herbs cannot be added before the ingredients")
253
- # load the herbs file
254
- name_cols = ['Pinyin.Name', 'Chinese.Name', 'English.Name', 'Latin.Name']
255
- herbs_df = pd.read_csv(self.batman_files['p_herbs'],
256
- index_col=None, header=0, sep='\t',
257
- na_filter=False)
258
- for i in herbs_df.index:
259
-
260
- herb_name = herbs_df.loc[i, 'Pinyin.Name'].strip()
261
- if herb_name == 'NA':
262
- herb_name = [x.strip() for x in herbs_df.loc[i, name_cols].tolist() if not x == 'NA']
263
- herb_name = [x for x in herb_name if x != '']
264
- if not herb_name:
265
- raise ValueError(f"LINE {i}: provided a herb with no names")
266
- else:
267
- herb_name = herb_name[-1]
268
-
269
- herb_cids = herbs_df.loc[i, 'Ingredients'].split("|")
270
-
271
- herb_cids = [x.split("(")[-1].removesuffix(")").strip() for x in herb_cids]
272
- herb_cids = [int(x) for x in herb_cids if x.isnumeric()]
273
-
274
- missed_ingrs = [x for x in herb_cids if self.ingrs.get(x) is None]
275
- for cid in missed_ingrs:
276
- self.add_ingredient(cid=int(cid), pref_name='',
277
- empty_override=True)
278
- herb_ingrs = [self.ingrs[int(x)] for x in herb_cids]
279
-
280
- self.add_herb(pref_name=herb_name,
281
- ingrs=herb_ingrs,
282
- synonyms=[x for x in herbs_df.loc[i, name_cols].tolist() if not x == "NA"],
283
- empty_override=True)
284
-
285
- def parse_formulas(self):
286
- if self.herbs is None:
287
- raise ValueError("Formulas cannot be added before the herbs")
288
- formulas_df = pd.read_csv(self.batman_files['p_formulas'], index_col=None, header=0,
289
- sep='\t', na_filter=False)
290
- for i in formulas_df.index:
291
-
292
- composition = formulas_df.loc[i, 'Pinyin.composition'].split(",")
293
- composition = [x.strip() for x in composition if not x.strip() == 'NA']
294
- if not composition:
295
- continue
296
-
297
- missed_herbs = [x.strip() for x in composition if self.herbs.get(x) is None]
298
- for herb in missed_herbs:
299
- self.add_herb(pref_name=herb,
300
- desc='Missing in the original herb catalog, but present among formula components',
301
- ingrs=[], empty_override=True)
302
-
303
- formula_herbs = [self.herbs[x] for x in composition]
304
- self.add_formula(pref_name=formulas_df.loc[i, 'Pinyin.Name'].strip(),
305
- synonyms=[formulas_df.loc[i, 'Chinese.Name']],
306
- herbs=formula_herbs)
307
-
308
- def add_ingredient(self, **kwargs):
309
- if self.ingrs is None:
310
- self.ingrs = dict()
311
-
312
- new_ingr = Ingredient(**kwargs)
313
- if not new_ingr.cid in self.ingrs:
314
- self.ingrs.update({new_ingr.cid: new_ingr})
315
-
316
- def add_herb(self, **kwargs):
317
- if self.herbs is None:
318
- self.herbs = dict()
319
-
320
- new_herb = Herb(**kwargs)
321
- old_herb = self.herbs.get(new_herb.pref_name)
322
- if not old_herb is None:
323
- if_same = new_herb.is_same(old_herb)
324
- if if_same:
325
- return
326
-
327
- same_name = new_herb.pref_name
328
- all_dupes = [self.herbs[x] for x in self.herbs if x.split('~')[0] == same_name] + [new_herb]
329
- new_names = [same_name + f"~{x + 1}" for x in range(len(all_dupes))]
330
- for i, duped in enumerate(all_dupes):
331
- duped.pref_name = new_names[i]
332
- self.herbs.pop(same_name)
333
- self.herbs.update({x.pref_name: x for x in all_dupes})
334
- else:
335
- self.herbs.update({new_herb.pref_name: new_herb})
336
-
337
- for cpd in new_herb.ingrs:
338
- cpd_herbs = [x.pref_name for x in cpd.herbs]
339
- if not new_herb.pref_name in cpd_herbs:
340
- cpd.herbs.append(new_herb)
341
-
342
- def add_formula(self, **kwargs):
343
-
344
- if self.formulas is None:
345
- self.formulas = dict()
346
-
347
- new_formula = Formula(**kwargs)
348
- old_formula = self.formulas.get(new_formula.pref_name)
349
- if not old_formula is None:
350
- is_same = new_formula.is_same(old_formula)
351
- if is_same:
352
- return
353
- same_name = new_formula.pref_name
354
- all_dupes = [self.formulas[x] for x in self.formulas if x.split('~')[0] == same_name] + [new_formula]
355
- new_names = [same_name + f"~{x + 1}" for x in range(len(all_dupes))]
356
- for i, duped in enumerate(all_dupes):
357
- duped.pref_name = new_names[i]
358
- self.formulas.pop(same_name)
359
- self.formulas.update({x.pref_name: x for x in all_dupes})
360
- else:
361
- self.formulas.update({new_formula.pref_name: new_formula})
362
-
363
- for herb in new_formula.herbs:
364
- herb_formulas = [x.pref_name for x in herb.formulas]
365
- if not new_formula.pref_name in herb_formulas:
366
- herb.formulas.append(new_formula)
367
-
368
- def link_ingredients_n_formulas(self):
369
- for h in self.herbs.values():
370
- for i in h.ingrs:
371
- fla_names = set(x.pref_name for x in i.formulas)
372
- i.formulas += [x for x in h.formulas if not x.pref_name in fla_names]
373
- for f in h.formulas:
374
- ingr_cids = set(x.cid for x in f.ingrs)
375
- f.ingrs += [x for x in h.ingrs if not x.cid in ingr_cids]
376
-
377
- def serialize(self):
378
- out_dict = dict(
379
- ingredients={cid: ingr.serialize() for cid, ingr in self.ingrs.items()},
380
- herbs={name: herb.serialize() for name, herb in self.herbs.items()},
381
- formulas={name: formula.serialize() for name, formula in self.formulas.items()}
382
- )
383
- return (out_dict)
384
-
385
- def save_to_flat_json(self, p_out: str):
386
- ser_db = db.serialize()
387
- flat_db = dict()
388
- for ent_type in ser_db:
389
- for i, obj in ser_db[ent_type].items():
390
- flat_db[f"{ent_type}:{i}"] = obj
391
- with open(p_out, "w") as f:
392
- f.write(json.dumps(flat_db))
393
-
394
- def save_to_json(self, p_out: str):
395
- with open(p_out, "w") as f:
396
- json.dump(self.serialize(), f)
397
-
398
- @classmethod
399
- def load(cls, ser_dict: dict):
400
- db = cls(p_batman="")
401
-
402
- # make sure to create all entities before you link them together
403
- db.ingrs = {int(cid): Ingredient.load(db, ingr, skip_links=True) for cid, ingr in
404
- ser_dict['ingredients'].items()}
405
- db.herbs = {name: Herb.load(db, herb, skip_links=True) for name, herb in ser_dict['herbs'].items()}
406
- db.formulas = {name: Formula.load(db, formula, skip_links=True) for name, formula in
407
- ser_dict['formulas'].items()}
408
-
409
- # now set the links
410
- for i in db.ingrs.values():
411
- # NB: somehow gotta make it work w/out relying on str-int conversion
412
- i._set_links(db, ser_dict['ingredients'][str(i.cid)]['links'])
413
- for h in db.herbs.values():
414
- h._set_links(db, ser_dict['herbs'][h.pref_name]['links'])
415
- for f in db.formulas.values():
416
- f._set_links(db, ser_dict['formulas'][f.pref_name]['links'])
417
- return (db)
418
-
419
- @classmethod
420
- def read_from_json(cls, p_file: str):
421
- with open(p_file, "r") as f:
422
- json_db = json.load(f)
423
- db = cls.load(json_db)
424
- return (db)
425
-
426
- @classmethod
427
- def download_from_hf(cls):
428
- from datasets import load_dataset
429
- dsets = {x: load_dataset(cls.hf_repo, y) for x, y in cls.hf_subsets.items()}
430
-
431
- # speed this up somehow
432
-
433
- known_tgs = {str(x['cid']): [y.split("(") for y in eval(x['targets_known'])] for x in dsets['ingredients']['train']}
434
- known_tgs = {x:{'symbols':[z[0] for z in y], "entrez_ids":[int(z[1].strip(")")) for z in y]} for x,y in known_tgs.items()}
435
- pred_tgs = {str(x['cid']): [y.split("(") for y in eval(x['targets_pred'])] for x in dsets['ingredients']['train']}
436
- pred_tgs = {x:{'symbols':[z[0] for z in y], "entrez_ids":[int(z[1].strip(")")) for z in y]} for x,y in pred_tgs.items()}
437
-
438
- json_db = dict()
439
- json_db['ingredients'] = {str(x['cid']): {'init': dict(cid=int(x['cid']),
440
- targets_known=known_tgs[str(x['cid'])],
441
- targets_pred=pred_tgs[str(x['cid'])],
442
- pref_name=x['pref_name'],
443
- synonyms=eval(x['synonyms']),
444
- desc=x['description']
445
- ),
446
-
447
- 'links': dict(
448
- herbs=eval(x['herbs']),
449
- formulas=eval(x['formulas'])
450
- )
451
- }
452
- for x in dsets['ingredients']['train']}
453
-
454
- json_db['herbs'] = {x['pref_name']: {'init': dict(pref_name=x['pref_name'],
455
- synonyms=eval(x['synonyms']),
456
- desc=x['description']),
457
- 'links': dict(ingrs=eval(x['ingredients']),
458
- formulas=eval(x['formulas']))} for x in
459
- dsets['herbs']['train']}
460
-
461
- json_db['formulas'] = {x['pref_name']: {'init': dict(pref_name=x['pref_name'],
462
- synonyms=eval(x['synonyms']),
463
- desc=x['description']),
464
- 'links': dict(ingrs=eval(x['ingredients']),
465
- herbs=eval(x['herbs']))} for x in
466
- dsets['formulas']['train']}
467
-
468
- db = cls.load(json_db)
469
- return (db)
470
-
471
- def drop_isolated(self, how='any'):
472
- match how:
473
- case 'any':
474
- self.herbs = {x: y for x, y in self.herbs.items() if (y.ingrs and y.formulas)}
475
- self.formulas = {x: y for x, y in self.formulas.items() if (y.ingrs and y.herbs)}
476
- self.ingrs = {x: y for x, y in self.ingrs.items() if (y.formulas and y.herbs)}
477
- case 'all':
478
- self.herbs = {x: y for x, y in self.herbs.items() if (y.ingrs or y.formulas)}
479
- self.formulas = {x: y for x, y in self.formulas.items() if (y.ingrs or y.herbs)}
480
- self.ingrs = {x: y for x, y in self.ingrs.items() if (y.formulas or y.herbs)}
481
- case _:
482
- raise ValueError(f'Unknown how parameter: {how}. Known parameters are "any" and "all"')
483
-
484
- def select_formula_by_cpd(self, cids: List):
485
- cids = set(x for x in cids if x in self.ingrs)
486
- if not cids:
487
- return
488
- cpd_counts = {x: len(set([z.cid for z in y.ingrs]) & cids) for x, y in self.formulas.items()}
489
- n_max = max(cpd_counts.values())
490
- if n_max == 0:
491
- return (n_max, [])
492
- selected = [x for x, y in cpd_counts.items() if y == n_max]
493
- return (n_max, selected)
494
-
495
- def pick_formula_by_cpd(self, cids: List):
496
- cids = [x for x in cids if x in self.ingrs]
497
- if not cids:
498
- return
499
- raise NotImplementedError()
500
-
501
- def select_formula_by_herb(self, herbs: List):
502
- raise NotImplementedError()
503
-
504
- def pick_formula_by_herb(self, herbs: List):
505
- raise NotImplementedError()
506
-
507
-
508
- def main(ab_initio=False,
509
- p_BATMAN="./BATMAN/",
510
- fname='BATMAN_DB.json'):
511
- p_BATMAN = p_BATMAN.removesuffix("/") + "/"
512
- # Use in case you want to recreate the TCMDB database of Chinese medicine from BATMAN files
513
- if ab_initio:
514
- db = TCMDB.make_new_db(p_BATMAN)
515
- db.link_ingredients_n_formulas()
516
- db.save_to_json(p_BATMAN + fname)
517
- # db.save_to_json('../TCM screening/BATMAN_DB.json')
518
-
519
- else:
520
- db = TCMDB.read_from_json('../TCM screening/BATMAN_DB.json')
521
- # db = TCMDB.read_from_json(p_BATMAN + fname)
522
-
523
- cids = [969516, # curcumin
524
- 445154, # resveratrol
525
- 5280343, # quercetin
526
- 6167, # colchicine
527
- 5280443, # apigening
528
- 65064, # EGCG3
529
- 5757, # estradiol
530
- 5994, # progesterone
531
- 5280863, # kaempferol
532
- 107985, # triptolide
533
- 14985, # alpha-tocopherol
534
- 1548943, # Capsaicin
535
- 64982, # Baicalin
536
- 6013, # Testosterone
537
- ]
538
-
539
- p3_formula = db.select_formula_by_cpd(cids)
540
- # somehow save file if needed ↓
541
- ser_db = db.serialize()
542
-
543
-
544
- ###
545
-
546
- if __name__ == '__main__':
547
- main(ab_initio=True, p_BATMAN="./BATMAN/", fname='BATMAN_DB.json')
548
-
549
-
 
1
+ import pandas as pd
2
+ import pickle
3
+ from typing import List, Dict, Optional
4
+ from copy import copy as cp
5
+ import json
6
+
7
+ class TCMEntity():
8
+ empty_override = True
9
+ desc = ''
10
+ cid = -1
11
+ entity = 'superclass'
12
+
13
+ def __init__(self,
14
+ pref_name: str, desc: str = '',
15
+ synonyms: Optional[List[str]] = None,
16
+ **kwargs):
17
+ self.pref_name = pref_name
18
+ self.desc = desc
19
+ self.synonyms = [] if synonyms is None else [x for x in synonyms if str(x).strip() != 'NA']
20
+
21
+ self.targets = {"known": dict(), "predicted": dict()}
22
+
23
+ self.formulas = []
24
+ self.herbs = []
25
+ self.ingrs = []
26
+
27
+ for k, v in kwargs.items():
28
+ self.__dict__[k] = v
29
+
30
+ def serialize(self):
31
+ init_dict = dict(
32
+ cid=self.cid,
33
+ targets_known=self.targets['known'],
34
+ targets_pred=self.targets['predicted'],
35
+ pref_name=self.pref_name, desc=self.desc,
36
+ synonyms=cp(self.synonyms),
37
+ entity=self.entity
38
+ )
39
+ link_dict = self._get_link_dict()
40
+ out_dict = {"init": init_dict, "links": link_dict}
41
+ return out_dict
42
+
43
+ @classmethod
44
+ def load(cls,
45
+ db: 'TCMDB', ser_dict: dict,
46
+ skip_links = True):
47
+ init_args = ser_dict['init']
48
+
49
+ if skip_links:
50
+ init_args.update({"empty_override":True})
51
+ else:
52
+ init_args.update({"empty_override": False})
53
+
54
+ new_entity = cls(**init_args)
55
+ if not skip_links:
56
+ links = ser_dict['links']
57
+ new_entity._set_links(db, links)
58
+ return (new_entity)
59
+
60
+ def _get_link_dict(self):
61
+ return dict(
62
+ ingrs=[x.cid for x in self.ingrs],
63
+ herbs=[x.pref_name for x in self.herbs],
64
+ formulas=[x.pref_name for x in self.formulas]
65
+ )
66
+
67
+ def _set_links(self, db: 'TCMDB', links: dict):
68
+ for ent_type in links:
69
+ self.__dict__[ent_type] = [db.__dict__[ent_type].get(x) for x in links[ent_type]]
70
+ self.__dict__[ent_type] = [x for x in self.__dict__[ent_type] if x is not None]
71
+
72
+
73
+ class Ingredient(TCMEntity):
74
+ entity: str = 'ingredient'
75
+
76
+ def __init__(self, cid: int,
77
+ targets_pred: Optional[Dict] = None,
78
+ targets_known: Optional[Dict] = None,
79
+ synonyms: Optional[List[str]] = None,
80
+ pref_name: str = '', desc: str = '',
81
+ empty_override: bool = True, **kwargs):
82
+
83
+ if not empty_override:
84
+ assert targets_known is not None or targets_pred is not None, \
85
+ f"Cant submit a compound with no targets at all (CID:{cid})"
86
+
87
+ super().__init__(pref_name, synonyms, desc, **kwargs)
88
+
89
+ self.cid = cid
90
+ self.targets = {
91
+ 'known': targets_known if targets_known is not None else {"symbols": [], 'entrez_ids': []},
92
+ 'predicted': targets_pred if targets_pred is not None else {"symbols": [], 'entrez_ids': []}
93
+ }
94
+
95
+
96
+ class Herb(TCMEntity):
97
+ entity: str = 'herb'
98
+
99
+ def __init__(self, pref_name: str,
100
+ ingrs: Optional[List[Ingredient]] = None,
101
+ synonyms: Optional[List[str]] = None,
102
+ desc: str = '',
103
+ empty_override: bool = True, **kwargs):
104
+
105
+ if ingrs is None:
106
+ ingrs = []
107
+
108
+ if not ingrs and not empty_override:
109
+ raise ValueError(f"No ingredients provided for {pref_name}")
110
+
111
+ super().__init__(pref_name, synonyms, desc, **kwargs)
112
+
113
+ self.ingrs = ingrs
114
+
115
+ def is_same(self, other: 'Herb') -> bool:
116
+ if len(self.ingrs) != len(other.ingrs):
117
+ return False
118
+ this_ingrs = set(x.cid for x in self.ingrs)
119
+ other_ingrs = set(x.cid for x in other.ingrs)
120
+ return this_ingrs == other_ingrs
121
+
122
+
123
+ class Formula(TCMEntity):
124
+ entity: str = 'formula'
125
+
126
+ def __init__(self, pref_name: str,
127
+ herbs: Optional[List[Herb]] = None,
128
+ synonyms: Optional[List[str]] = None,
129
+ desc: str = '',
130
+ empty_override: bool = False, **kwargs):
131
+
132
+ if herbs is None:
133
+ herbs = []
134
+
135
+ if not herbs and not empty_override:
136
+ raise ValueError(f"No herbs provided for {pref_name}")
137
+
138
+ super().__init__(pref_name, synonyms, desc, **kwargs)
139
+ self.herbs = herbs
140
+
141
+ def is_same(self, other: 'Formula') -> bool:
142
+ if len(self.herbs) != len(other.herbs):
143
+ return False
144
+ this_herbs = set(x.pref_name for x in self.herbs)
145
+ other_herbs = set(x.pref_name for x in other.herbs)
146
+ return this_herbs == other_herbs
147
+
148
+
149
+ class TCMDB:
150
+ hf_repo: str = "f-galkin/batman2"
151
+ hf_subsets: Dict[str, str] = {'formulas': 'batman_formulas',
152
+ 'herbs': 'batman_herbs',
153
+ 'ingredients': 'batman_ingredients'}
154
+
155
+ def __init__(self, p_batman: str):
156
+ p_batman = p_batman.removesuffix("/") + "/"
157
+
158
+ self.batman_files = dict(p_formulas='formula_browse.txt',
159
+ p_herbs='herb_browse.txt',
160
+ p_pred_by_tg='predicted_browse_by_targets.txt',
161
+ p_known_by_tg='known_browse_by_targets.txt',
162
+ p_pred_by_ingr='predicted_browse_by_ingredinets.txt',
163
+ p_known_by_ingr='known_browse_by_ingredients.txt')
164
+
165
+ self.batman_files = {x: p_batman + y for x, y in self.batman_files.items()}
166
+
167
+ self.ingrs = None
168
+ self.herbs = None
169
+ self.formulas = None
170
+
171
+ @classmethod
172
+ def make_new_db(cls, p_batman: str):
173
+ new_db = cls(p_batman)
174
+
175
+ new_db.parse_ingredients()
176
+ new_db.parse_herbs()
177
+ new_db.parse_formulas()
178
+
179
+ return (new_db)
180
+
181
+ def parse_ingredients(self):
182
+
183
+ pred_tgs = pd.read_csv(self.batman_files['p_pred_by_tg'],
184
+ sep='\t', index_col=None, header=0,
185
+ na_filter=False)
186
+ known_tgs = pd.read_csv(self.batman_files['p_known_by_tg'],
187
+ sep='\t', index_col=None, header=0,
188
+ na_filter=False)
189
+ entrez_to_symb = {int(pred_tgs.loc[x, 'entrez_gene_id']): pred_tgs.loc[x, 'entrez_gene_symbol'] for x in
190
+ pred_tgs.index}
191
+ # 9927 gene targets
192
+ entrez_to_symb.update({int(known_tgs.loc[x, 'entrez_gene_id']): \
193
+ known_tgs.loc[x, 'entrez_gene_symbol'] for x in known_tgs.index})
194
+
195
+ known_ingreds = pd.read_csv(self.batman_files['p_known_by_ingr'],
196
+ index_col=0, header=0, sep='\t',
197
+ na_filter=False)
198
+ # this BATMAN table is badly formatted
199
+ # you cant just read it
200
+ # df_pred = pd.read_csv(p_pred, index_col=0, header=0, sep='\t')
201
+ pred_ingreds = dict()
202
+ with open(self.batman_files['p_pred_by_ingr'], 'r') as f:
203
+ # skip header
204
+ f.readline()
205
+ newline = f.readline()
206
+ while newline != '':
207
+ cid, other_line = newline.split(' ', 1)
208
+ name, entrez_ids = other_line.rsplit(' ', 1)
209
+ entrez_ids = [int(x.split("(")[0]) for x in entrez_ids.split("|") if not x == "\n"]
210
+ pred_ingreds[int(cid)] = {"targets": entrez_ids, 'name': name}
211
+ newline = f.readline()
212
+
213
+ all_BATMAN_CIDs = list(set(pred_ingreds.keys()) | set(known_ingreds.index))
214
+ all_BATMAN_CIDs = [int(x) for x in all_BATMAN_CIDs if str(x).strip() != 'NA']
215
+
216
+ # get targets for selected cpds
217
+ ingredients = dict()
218
+ for cid in all_BATMAN_CIDs:
219
+ known_name, pred_name, synonyms = None, None, []
220
+ if cid in known_ingreds.index:
221
+ known_name = known_ingreds.loc[cid, 'IUPAC_name']
222
+ known_symbs = known_ingreds.loc[cid, 'known_target_proteins'].split("|")
223
+ else:
224
+ known_symbs = []
225
+
226
+ pred_ids = pred_ingreds.get(cid, [])
227
+ if pred_ids:
228
+ pred_name = pred_ids.get('name')
229
+ if known_name is None:
230
+ cpd_name = pred_name
231
+ elif known_name != pred_name:
232
+ cpd_name = min([known_name, pred_name], key=lambda x: sum([x.count(y) for y in "'()-[]1234567890"]))
233
+ synonyms = [x for x in [known_name, pred_name] if x != cpd_name]
234
+
235
+ pred_ids = pred_ids.get('targets', [])
236
+
237
+ ingredients[cid] = dict(pref_name=cpd_name,
238
+ synonyms=synonyms,
239
+ targets_known={"symbols": known_symbs,
240
+ "entrez_ids": [int(x) for x, y in entrez_to_symb.items() if
241
+ y in known_symbs]},
242
+ targets_pred={"symbols": [entrez_to_symb.get(x) for x in pred_ids],
243
+ "entrez_ids": pred_ids})
244
+ ingredients_objs = {x: Ingredient(cid=x, **y) for x, y in ingredients.items()}
245
+ self.ingrs = ingredients_objs
246
+
247
+ def parse_herbs(self):
248
+ if self.ingrs is None:
249
+ raise ValueError("Herbs cannot be added before the ingredients")
250
+ # load the herbs file
251
+ name_cols = ['Pinyin.Name', 'Chinese.Name', 'English.Name', 'Latin.Name']
252
+ herbs_df = pd.read_csv(self.batman_files['p_herbs'],
253
+ index_col=None, header=0, sep='\t',
254
+ na_filter=False)
255
+ for i in herbs_df.index:
256
+
257
+ herb_name = herbs_df.loc[i, 'Pinyin.Name'].strip()
258
+ if herb_name == 'NA':
259
+ herb_name = [x.strip() for x in herbs_df.loc[i, name_cols].tolist() if not x == 'NA']
260
+ herb_name = [x for x in herb_name if x != '']
261
+ if not herb_name:
262
+ raise ValueError(f"LINE {i}: provided a herb with no names")
263
+ else:
264
+ herb_name = herb_name[-1]
265
+
266
+ herb_cids = herbs_df.loc[i, 'Ingredients'].split("|")
267
+
268
+ herb_cids = [x.split("(")[-1].removesuffix(")").strip() for x in herb_cids]
269
+ herb_cids = [int(x) for x in herb_cids if x.isnumeric()]
270
+
271
+ missed_ingrs = [x for x in herb_cids if self.ingrs.get(x) is None]
272
+ for cid in missed_ingrs:
273
+ self.add_ingredient(cid=int(cid), pref_name='',
274
+ empty_override=True)
275
+ herb_ingrs = [self.ingrs[int(x)] for x in herb_cids]
276
+
277
+ self.add_herb(pref_name=herb_name,
278
+ ingrs=herb_ingrs,
279
+ synonyms=[x for x in herbs_df.loc[i, name_cols].tolist() if not x == "NA"],
280
+ empty_override=True)
281
+
282
+ def parse_formulas(self):
283
+ if self.herbs is None:
284
+ raise ValueError("Formulas cannot be added before the herbs")
285
+ formulas_df = pd.read_csv(self.batman_files['p_formulas'], index_col=None, header=0,
286
+ sep='\t', na_filter=False)
287
+ for i in formulas_df.index:
288
+
289
+ composition = formulas_df.loc[i, 'Pinyin.composition'].split(",")
290
+ composition = [x.strip() for x in composition if not x.strip() == 'NA']
291
+ if not composition:
292
+ continue
293
+
294
+ missed_herbs = [x.strip() for x in composition if self.herbs.get(x) is None]
295
+ for herb in missed_herbs:
296
+ self.add_herb(pref_name=herb,
297
+ desc='Missing in the original herb catalog, but present among formula components',
298
+ ingrs=[], empty_override=True)
299
+
300
+ formula_herbs = [self.herbs[x] for x in composition]
301
+ self.add_formula(pref_name=formulas_df.loc[i, 'Pinyin.Name'].strip(),
302
+ synonyms=[formulas_df.loc[i, 'Chinese.Name']],
303
+ herbs=formula_herbs)
304
+
305
+ def add_ingredient(self, **kwargs):
306
+ if self.ingrs is None:
307
+ self.ingrs = dict()
308
+
309
+ new_ingr = Ingredient(**kwargs)
310
+ if not new_ingr.cid in self.ingrs:
311
+ self.ingrs.update({new_ingr.cid: new_ingr})
312
+
313
+ def add_herb(self, **kwargs):
314
+ if self.herbs is None:
315
+ self.herbs = dict()
316
+
317
+ new_herb = Herb(**kwargs)
318
+ old_herb = self.herbs.get(new_herb.pref_name)
319
+ if not old_herb is None:
320
+ if_same = new_herb.is_same(old_herb)
321
+ if if_same:
322
+ return
323
+
324
+ same_name = new_herb.pref_name
325
+ all_dupes = [self.herbs[x] for x in self.herbs if x.split('~')[0] == same_name] + [new_herb]
326
+ new_names = [same_name + f"~{x + 1}" for x in range(len(all_dupes))]
327
+ for i, duped in enumerate(all_dupes):
328
+ duped.pref_name = new_names[i]
329
+ self.herbs.pop(same_name)
330
+ self.herbs.update({x.pref_name: x for x in all_dupes})
331
+ else:
332
+ self.herbs.update({new_herb.pref_name: new_herb})
333
+
334
+ for cpd in new_herb.ingrs:
335
+ cpd_herbs = [x.pref_name for x in cpd.herbs]
336
+ if not new_herb.pref_name in cpd_herbs:
337
+ cpd.herbs.append(new_herb)
338
+
339
+ def add_formula(self, **kwargs):
340
+
341
+ if self.formulas is None:
342
+ self.formulas = dict()
343
+
344
+ new_formula = Formula(**kwargs)
345
+ old_formula = self.formulas.get(new_formula.pref_name)
346
+ if not old_formula is None:
347
+ is_same = new_formula.is_same(old_formula)
348
+ if is_same:
349
+ return
350
+ same_name = new_formula.pref_name
351
+ all_dupes = [self.formulas[x] for x in self.formulas if x.split('~')[0] == same_name] + [new_formula]
352
+ new_names = [same_name + f"~{x + 1}" for x in range(len(all_dupes))]
353
+ for i, duped in enumerate(all_dupes):
354
+ duped.pref_name = new_names[i]
355
+ self.formulas.pop(same_name)
356
+ self.formulas.update({x.pref_name: x for x in all_dupes})
357
+ else:
358
+ self.formulas.update({new_formula.pref_name: new_formula})
359
+
360
+ for herb in new_formula.herbs:
361
+ herb_formulas = [x.pref_name for x in herb.formulas]
362
+ if not new_formula.pref_name in herb_formulas:
363
+ herb.formulas.append(new_formula)
364
+
365
+ def link_ingredients_n_formulas(self):
366
+ for h in self.herbs.values():
367
+ for i in h.ingrs:
368
+ fla_names = set(x.pref_name for x in i.formulas)
369
+ i.formulas += [x for x in h.formulas if not x.pref_name in fla_names]
370
+ for f in h.formulas:
371
+ ingr_cids = set(x.cid for x in f.ingrs)
372
+ f.ingrs += [x for x in h.ingrs if not x.cid in ingr_cids]
373
+
374
+ def serialize(self):
375
+ out_dict = dict(
376
+ ingredients={cid: ingr.serialize() for cid, ingr in self.ingrs.items()},
377
+ herbs={name: herb.serialize() for name, herb in self.herbs.items()},
378
+ formulas={name: formula.serialize() for name, formula in self.formulas.items()}
379
+ )
380
+ return (out_dict)
381
+
382
+ def save_to_flat_json(self, p_out: str):
383
+ ser_db = db.serialize()
384
+ flat_db = dict()
385
+ for ent_type in ser_db:
386
+ for i, obj in ser_db[ent_type].items():
387
+ flat_db[f"{ent_type}:{i}"] = obj
388
+ with open(p_out, "w") as f:
389
+ f.write(json.dumps(flat_db))
390
+
391
+ def save_to_json(self, p_out: str):
392
+ with open(p_out, "w") as f:
393
+ json.dump(self.serialize(), f)
394
+
395
+ @classmethod
396
+ def load(cls, ser_dict: dict):
397
+ db = cls(p_batman="")
398
+
399
+ # make sure to create all entities before you link them together
400
+ db.ingrs = {int(cid): Ingredient.load(db, ingr, skip_links=True) for cid, ingr in
401
+ ser_dict['ingredients'].items()}
402
+ db.herbs = {name: Herb.load(db, herb, skip_links=True) for name, herb in ser_dict['herbs'].items()}
403
+ db.formulas = {name: Formula.load(db, formula, skip_links=True) for name, formula in
404
+ ser_dict['formulas'].items()}
405
+
406
+ # now set the links
407
+ for i in db.ingrs.values():
408
+ # NB: somehow gotta make it work w/out relying on str-int conversion
409
+ i._set_links(db, ser_dict['ingredients'][str(i.cid)]['links'])
410
+ for h in db.herbs.values():
411
+ h._set_links(db, ser_dict['herbs'][h.pref_name]['links'])
412
+ for f in db.formulas.values():
413
+ f._set_links(db, ser_dict['formulas'][f.pref_name]['links'])
414
+ return (db)
415
+
416
+ @classmethod
417
+ def read_from_json(cls, p_file: str):
418
+ with open(p_file, "r") as f:
419
+ json_db = json.load(f)
420
+ db = cls.load(json_db)
421
+ return (db)
422
+
423
+ @classmethod
424
+ def download_from_hf(cls):
425
+ from datasets import load_dataset
426
+ dsets = {x: load_dataset(cls.hf_repo, y) for x, y in cls.hf_subsets.items()}
427
+
428
+ # speed this up somehow
429
+
430
+ known_tgs = {str(x['cid']): [y.split("(") for y in eval(x['targets_known'])] for x in dsets['ingredients']['train']}
431
+ known_tgs = {x:{'symbols':[z[0] for z in y], "entrez_ids":[int(z[1].strip(")")) for z in y]} for x,y in known_tgs.items()}
432
+ pred_tgs = {str(x['cid']): [y.split("(") for y in eval(x['targets_pred'])] for x in dsets['ingredients']['train']}
433
+ pred_tgs = {x:{'symbols':[z[0] for z in y], "entrez_ids":[int(z[1].strip(")")) for z in y]} for x,y in pred_tgs.items()}
434
+
435
+ json_db = dict()
436
+ json_db['ingredients'] = {str(x['cid']): {'init': dict(cid=int(x['cid']),
437
+ targets_known=known_tgs[str(x['cid'])],
438
+ targets_pred=pred_tgs[str(x['cid'])],
439
+ pref_name=x['pref_name'],
440
+ synonyms=eval(x['synonyms']),
441
+ desc=x['description']
442
+ ),
443
+
444
+ 'links': dict(
445
+ herbs=eval(x['herbs']),
446
+ formulas=eval(x['formulas'])
447
+ )
448
+ }
449
+ for x in dsets['ingredients']['train']}
450
+
451
+ json_db['herbs'] = {x['pref_name']: {'init': dict(pref_name=x['pref_name'],
452
+ synonyms=eval(x['synonyms']),
453
+ desc=x['description']),
454
+ 'links': dict(ingrs=eval(x['ingredients']),
455
+ formulas=eval(x['formulas']))} for x in
456
+ dsets['herbs']['train']}
457
+
458
+ json_db['formulas'] = {x['pref_name']: {'init': dict(pref_name=x['pref_name'],
459
+ synonyms=eval(x['synonyms']),
460
+ desc=x['description']),
461
+ 'links': dict(ingrs=eval(x['ingredients']),
462
+ herbs=eval(x['herbs']))} for x in
463
+ dsets['formulas']['train']}
464
+
465
+ db = cls.load(json_db)
466
+ return (db)
467
+
468
+ def drop_isolated(self, how='any'):
469
+ match how:
470
+ case 'any':
471
+ self.herbs = {x: y for x, y in self.herbs.items() if (y.ingrs and y.formulas)}
472
+ self.formulas = {x: y for x, y in self.formulas.items() if (y.ingrs and y.herbs)}
473
+ self.ingrs = {x: y for x, y in self.ingrs.items() if (y.formulas and y.herbs)}
474
+ case 'all':
475
+ self.herbs = {x: y for x, y in self.herbs.items() if (y.ingrs or y.formulas)}
476
+ self.formulas = {x: y for x, y in self.formulas.items() if (y.ingrs or y.herbs)}
477
+ self.ingrs = {x: y for x, y in self.ingrs.items() if (y.formulas or y.herbs)}
478
+ case _:
479
+ raise ValueError(f'Unknown how parameter: {how}. Known parameters are "any" and "all"')
480
+
481
+ def select_formula_by_cpd(self, cids: List):
482
+ cids = set(x for x in cids if x in self.ingrs)
483
+ if not cids:
484
+ return
485
+ cpd_counts = {x: len(set([z.cid for z in y.ingrs]) & cids) for x, y in self.formulas.items()}
486
+ n_max = max(cpd_counts.values())
487
+ if n_max == 0:
488
+ return (n_max, [])
489
+ selected = [x for x, y in cpd_counts.items() if y == n_max]
490
+ return (n_max, selected)
491
+
492
+ def pick_formula_by_cpd(self, cids: List):
493
+ cids = [x for x in cids if x in self.ingrs]
494
+ if not cids:
495
+ return
496
+ raise NotImplementedError()
497
+
498
+ def select_formula_by_herb(self, herbs: List):
499
+ raise NotImplementedError()
500
+
501
+ def pick_formula_by_herb(self, herbs: List):
502
+ raise NotImplementedError()
503
+
504
+
505
+ def main(ab_initio=False,
506
+ p_BATMAN="./BATMAN/",
507
+ fname='BATMAN_DB.json'):
508
+ p_BATMAN = p_BATMAN.removesuffix("/") + "/"
509
+ # Use in case you want to recreate the TCMDB database of Chinese medicine from BATMAN files
510
+ if ab_initio:
511
+ db = TCMDB.make_new_db(p_BATMAN)
512
+ db.link_ingredients_n_formulas()
513
+ db.save_to_json(p_BATMAN + fname)
514
+ # db.save_to_json('../TCM screening/BATMAN_DB.json')
515
+
516
+ else:
517
+ db = TCMDB.read_from_json('../TCM screening/BATMAN_DB.json')
518
+ # db = TCMDB.read_from_json(p_BATMAN + fname)
519
+
520
+ cids = [969516, # curcumin
521
+ 445154, # resveratrol
522
+ 5280343, # quercetin
523
+ 6167, # colchicine
524
+ 5280443, # apigening
525
+ 65064, # EGCG3
526
+ 5757, # estradiol
527
+ 5994, # progesterone
528
+ 5280863, # kaempferol
529
+ 107985, # triptolide
530
+ 14985, # alpha-tocopherol
531
+ 1548943, # Capsaicin
532
+ 64982, # Baicalin
533
+ 6013, # Testosterone
534
+ ]
535
+
536
+ p3_formula = db.select_formula_by_cpd(cids)
537
+ # somehow save file if needed ↓
538
+ ser_db = db.serialize()
539
+
540
+
541
+ ###
542
+
543
+ if __name__ == '__main__':
544
+ main(ab_initio=True, p_BATMAN="./BATMAN/", fname='BATMAN_DB.json')
545
+
546
+