File size: 22,667 Bytes
d851abd |
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 |
import pandas as pd
import pickle
from typing import List, Dict, Optional
from copy import copy as cp
import json
class TCMEntity():
empty_override = True
desc = ''
cid = -1
entity = 'superclass'
def __init__(self,
pref_name: str, desc: str = '',
synonyms: Optional[List[str]] = None,
**kwargs):
self.pref_name = pref_name
self.desc = desc
self.synonyms = [] if synonyms is None else [x for x in synonyms if str(x).strip() != 'NA']
self.targets = {"known": dict(), "predicted": dict()}
self.formulas = []
self.herbs = []
self.ingrs = []
for k, v in kwargs.items():
self.__dict__[k] = v
def serialize(self):
init_dict = dict(
cid=self.cid,
targets_known=self.targets['known'],
targets_pred=self.targets['predicted'],
pref_name=self.pref_name, desc=self.desc,
synonyms=cp(self.synonyms),
entity=self.entity
)
link_dict = self._get_link_dict()
out_dict = {"init": init_dict, "links": link_dict}
return out_dict
@classmethod
def load(cls,
db: 'TCMDB', ser_dict: dict,
skip_links = True):
init_args = ser_dict['init']
if skip_links:
init_args.update({"empty_override":True})
else:
init_args.update({"empty_override": False})
new_entity = cls(**init_args)
if not skip_links:
links = ser_dict['links']
new_entity._set_links(db, links)
return (new_entity)
def _get_link_dict(self):
return dict(
ingrs=[x.cid for x in self.ingrs],
herbs=[x.pref_name for x in self.herbs],
formulas=[x.pref_name for x in self.formulas]
)
def _set_links(self, db: 'TCMDB', links: dict):
for ent_type in links:
self.__dict__[ent_type] = [db.__dict__[ent_type].get(x) for x in links[ent_type]]
self.__dict__[ent_type] = [x for x in self.__dict__[ent_type] if x is not None]
class Ingredient(TCMEntity):
entity: str = 'ingredient'
def __init__(self, cid: int,
targets_pred: Optional[Dict] = None,
targets_known: Optional[Dict] = None,
synonyms: Optional[List[str]] = None,
pref_name: str = '', desc: str = '',
empty_override: bool = True, **kwargs):
if not empty_override:
assert targets_known is not None or targets_pred is not None, \
f"Cant submit a compound with no targets at all (CID:{cid})"
super().__init__(pref_name, synonyms, desc, **kwargs)
self.cid = cid
self.targets = {
'known': targets_known if targets_known is not None else {"symbols": [], 'entrez_ids': []},
'predicted': targets_pred if targets_pred is not None else {"symbols": [], 'entrez_ids': []}
}
class Herb(TCMEntity):
entity: str = 'herb'
def __init__(self, pref_name: str,
ingrs: Optional[List[Ingredient]] = None,
synonyms: Optional[List[str]] = None,
desc: str = '',
empty_override: bool = True, **kwargs):
if ingrs is None:
ingrs = []
if not ingrs and not empty_override:
raise ValueError(f"No ingredients provided for {pref_name}")
super().__init__(pref_name, synonyms, desc, **kwargs)
self.ingrs = ingrs
def is_same(self, other: 'Herb') -> bool:
if len(self.ingrs) != len(other.ingrs):
return False
this_ingrs = set(x.cid for x in self.ingrs)
other_ingrs = set(x.cid for x in other.ingrs)
return this_ingrs == other_ingrs
class Formula(TCMEntity):
entity: str = 'formula'
def __init__(self, pref_name: str,
herbs: Optional[List[Herb]] = None,
synonyms: Optional[List[str]] = None,
desc: str = '',
empty_override: bool = False, **kwargs):
if herbs is None:
herbs = []
if not herbs and not empty_override:
raise ValueError(f"No herbs provided for {pref_name}")
super().__init__(pref_name, synonyms, desc, **kwargs)
self.herbs = herbs
def is_same(self, other: 'Formula') -> bool:
if len(self.herbs) != len(other.herbs):
return False
this_herbs = set(x.pref_name for x in self.herbs)
other_herbs = set(x.pref_name for x in other.herbs)
return this_herbs == other_herbs
class TCMDB:
hf_repo: str = "f-galkin/batman2"
hf_subsets: Dict[str, str] = {'formulas': 'batman_formulas',
'herbs': 'batman_herbs',
'ingredients': 'batman_ingredients'}
def __init__(self, p_batman: str):
p_batman = p_batman.removesuffix("/") + "/"
self.batman_files = dict(p_formulas='formula_browse.txt',
p_herbs='herb_browse.txt',
p_pred_by_tg='predicted_browse_by_targets.txt',
p_known_by_tg='known_browse_by_targets.txt',
p_pred_by_ingr='predicted_browse_by_ingredinets.txt',
p_known_by_ingr='known_browse_by_ingredients.txt')
self.batman_files = {x: p_batman + y for x, y in self.batman_files.items()}
self.ingrs = None
self.herbs = None
self.formulas = None
@classmethod
def make_new_db(cls, p_batman: str):
new_db = cls(p_batman)
new_db.parse_ingredients()
new_db.parse_herbs()
new_db.parse_formulas()
return (new_db)
def parse_ingredients(self):
pred_tgs = pd.read_csv(self.batman_files['p_pred_by_tg'],
sep='\t', index_col=None, header=0,
na_filter=False)
known_tgs = pd.read_csv(self.batman_files['p_known_by_tg'],
sep='\t', index_col=None, header=0,
na_filter=False)
entrez_to_symb = {int(pred_tgs.loc[x, 'entrez_gene_id']): pred_tgs.loc[x, 'entrez_gene_symbol'] for x in
pred_tgs.index}
# 9927 gene targets
entrez_to_symb.update({int(known_tgs.loc[x, 'entrez_gene_id']): \
known_tgs.loc[x, 'entrez_gene_symbol'] for x in known_tgs.index})
known_ingreds = pd.read_csv(self.batman_files['p_known_by_ingr'],
index_col=0, header=0, sep='\t',
na_filter=False)
# this BATMAN table is badly formatted
# you cant just read it
# df_pred = pd.read_csv(p_pred, index_col=0, header=0, sep='\t')
pred_ingreds = dict()
with open(self.batman_files['p_pred_by_ingr'], 'r') as f:
# skip header
f.readline()
newline = f.readline()
while newline != '':
cid, other_line = newline.split(' ', 1)
name, entrez_ids = other_line.rsplit(' ', 1)
entrez_ids = [int(x.split("(")[0]) for x in entrez_ids.split("|") if not x == "\n"]
pred_ingreds[int(cid)] = {"targets": entrez_ids, 'name': name}
newline = f.readline()
all_BATMAN_CIDs = list(set(pred_ingreds.keys()) | set(known_ingreds.index))
all_BATMAN_CIDs = [int(x) for x in all_BATMAN_CIDs if str(x).strip() != 'NA']
# get targets for selected cpds
ingredients = dict()
for cid in all_BATMAN_CIDs:
known_name, pred_name, synonyms = None, None, []
if cid in known_ingreds.index:
known_name = known_ingreds.loc[cid, 'IUPAC_name']
known_symbs = known_ingreds.loc[cid, 'known_target_proteins'].split("|")
else:
known_symbs = []
pred_ids = pred_ingreds.get(cid, [])
if pred_ids:
pred_name = pred_ids.get('name')
if known_name is None:
cpd_name = pred_name
elif known_name != pred_name:
cpd_name = min([known_name, pred_name], key=lambda x: sum([x.count(y) for y in "'()-[]1234567890"]))
synonyms = [x for x in [known_name, pred_name] if x != cpd_name]
pred_ids = pred_ids.get('targets', [])
ingredients[cid] = dict(pref_name=cpd_name,
synonyms=synonyms,
targets_known={"symbols": known_symbs,
"entrez_ids": [int(x) for x, y in entrez_to_symb.items() if
y in known_symbs]},
targets_pred={"symbols": [entrez_to_symb.get(x) for x in pred_ids],
"entrez_ids": pred_ids})
ingredients_objs = {x: Ingredient(cid=x, **y) for x, y in ingredients.items()}
self.ingrs = ingredients_objs
def parse_herbs(self):
if self.ingrs is None:
raise ValueError("Herbs cannot be added before the ingredients")
# load the herbs file
name_cols = ['Pinyin.Name', 'Chinese.Name', 'English.Name', 'Latin.Name']
herbs_df = pd.read_csv(self.batman_files['p_herbs'],
index_col=None, header=0, sep='\t',
na_filter=False)
for i in herbs_df.index:
herb_name = herbs_df.loc[i, 'Pinyin.Name'].strip()
if herb_name == 'NA':
herb_name = [x.strip() for x in herbs_df.loc[i, name_cols].tolist() if not x == 'NA']
herb_name = [x for x in herb_name if x != '']
if not herb_name:
raise ValueError(f"LINE {i}: provided a herb with no names")
else:
herb_name = herb_name[-1]
herb_cids = herbs_df.loc[i, 'Ingredients'].split("|")
herb_cids = [x.split("(")[-1].removesuffix(")").strip() for x in herb_cids]
herb_cids = [int(x) for x in herb_cids if x.isnumeric()]
missed_ingrs = [x for x in herb_cids if self.ingrs.get(x) is None]
for cid in missed_ingrs:
self.add_ingredient(cid=int(cid), pref_name='',
empty_override=True)
herb_ingrs = [self.ingrs[int(x)] for x in herb_cids]
self.add_herb(pref_name=herb_name,
ingrs=herb_ingrs,
synonyms=[x for x in herbs_df.loc[i, name_cols].tolist() if not x == "NA"],
empty_override=True)
def parse_formulas(self):
if self.herbs is None:
raise ValueError("Formulas cannot be added before the herbs")
formulas_df = pd.read_csv(self.batman_files['p_formulas'], index_col=None, header=0,
sep='\t', na_filter=False)
for i in formulas_df.index:
composition = formulas_df.loc[i, 'Pinyin.composition'].split(",")
composition = [x.strip() for x in composition if not x.strip() == 'NA']
if not composition:
continue
missed_herbs = [x.strip() for x in composition if self.herbs.get(x) is None]
for herb in missed_herbs:
self.add_herb(pref_name=herb,
desc='Missing in the original herb catalog, but present among formula components',
ingrs=[], empty_override=True)
formula_herbs = [self.herbs[x] for x in composition]
self.add_formula(pref_name=formulas_df.loc[i, 'Pinyin.Name'].strip(),
synonyms=[formulas_df.loc[i, 'Chinese.Name']],
herbs=formula_herbs)
def add_ingredient(self, **kwargs):
if self.ingrs is None:
self.ingrs = dict()
new_ingr = Ingredient(**kwargs)
if not new_ingr.cid in self.ingrs:
self.ingrs.update({new_ingr.cid: new_ingr})
def add_herb(self, **kwargs):
if self.herbs is None:
self.herbs = dict()
new_herb = Herb(**kwargs)
old_herb = self.herbs.get(new_herb.pref_name)
if not old_herb is None:
if_same = new_herb.is_same(old_herb)
if if_same:
return
same_name = new_herb.pref_name
all_dupes = [self.herbs[x] for x in self.herbs if x.split('~')[0] == same_name] + [new_herb]
new_names = [same_name + f"~{x + 1}" for x in range(len(all_dupes))]
for i, duped in enumerate(all_dupes):
duped.pref_name = new_names[i]
self.herbs.pop(same_name)
self.herbs.update({x.pref_name: x for x in all_dupes})
else:
self.herbs.update({new_herb.pref_name: new_herb})
for cpd in new_herb.ingrs:
cpd_herbs = [x.pref_name for x in cpd.herbs]
if not new_herb.pref_name in cpd_herbs:
cpd.herbs.append(new_herb)
def add_formula(self, **kwargs):
if self.formulas is None:
self.formulas = dict()
new_formula = Formula(**kwargs)
old_formula = self.formulas.get(new_formula.pref_name)
if not old_formula is None:
is_same = new_formula.is_same(old_formula)
if is_same:
return
same_name = new_formula.pref_name
all_dupes = [self.formulas[x] for x in self.formulas if x.split('~')[0] == same_name] + [new_formula]
new_names = [same_name + f"~{x + 1}" for x in range(len(all_dupes))]
for i, duped in enumerate(all_dupes):
duped.pref_name = new_names[i]
self.formulas.pop(same_name)
self.formulas.update({x.pref_name: x for x in all_dupes})
else:
self.formulas.update({new_formula.pref_name: new_formula})
for herb in new_formula.herbs:
herb_formulas = [x.pref_name for x in herb.formulas]
if not new_formula.pref_name in herb_formulas:
herb.formulas.append(new_formula)
def link_ingredients_n_formulas(self):
for h in self.herbs.values():
for i in h.ingrs:
fla_names = set(x.pref_name for x in i.formulas)
i.formulas += [x for x in h.formulas if not x.pref_name in fla_names]
for f in h.formulas:
ingr_cids = set(x.cid for x in f.ingrs)
f.ingrs += [x for x in h.ingrs if not x.cid in ingr_cids]
def serialize(self):
out_dict = dict(
ingredients={cid: ingr.serialize() for cid, ingr in self.ingrs.items()},
herbs={name: herb.serialize() for name, herb in self.herbs.items()},
formulas={name: formula.serialize() for name, formula in self.formulas.items()}
)
return (out_dict)
def save_to_flat_json(self, p_out: str):
ser_db = db.serialize()
flat_db = dict()
for ent_type in ser_db:
for i, obj in ser_db[ent_type].items():
flat_db[f"{ent_type}:{i}"] = obj
with open(p_out, "w") as f:
f.write(json.dumps(flat_db))
def save_to_json(self, p_out: str):
with open(p_out, "w") as f:
json.dump(self.serialize(), f)
@classmethod
def load(cls, ser_dict: dict):
db = cls(p_batman="")
# make sure to create all entities before you link them together
db.ingrs = {int(cid): Ingredient.load(db, ingr, skip_links=True) for cid, ingr in
ser_dict['ingredients'].items()}
db.herbs = {name: Herb.load(db, herb, skip_links=True) for name, herb in ser_dict['herbs'].items()}
db.formulas = {name: Formula.load(db, formula, skip_links=True) for name, formula in
ser_dict['formulas'].items()}
# now set the links
for i in db.ingrs.values():
# NB: somehow gotta make it work w/out relying on str-int conversion
i._set_links(db, ser_dict['ingredients'][str(i.cid)]['links'])
for h in db.herbs.values():
h._set_links(db, ser_dict['herbs'][h.pref_name]['links'])
for f in db.formulas.values():
f._set_links(db, ser_dict['formulas'][f.pref_name]['links'])
return (db)
@classmethod
def read_from_json(cls, p_file: str):
with open(p_file, "r") as f:
json_db = json.load(f)
db = cls.load(json_db)
return (db)
@classmethod
def download_from_hf(cls):
from datasets import load_dataset
dsets = {x: load_dataset(cls.hf_repo, y) for x, y in cls.hf_subsets.items()}
# speed this up somehow
known_tgs = {str(x['cid']): [y.split("(") for y in eval(x['targets_known'])] for x in dsets['ingredients']['train']}
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()}
pred_tgs = {str(x['cid']): [y.split("(") for y in eval(x['targets_pred'])] for x in dsets['ingredients']['train']}
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()}
json_db = dict()
json_db['ingredients'] = {str(x['cid']): {'init': dict(cid=int(x['cid']),
targets_known=known_tgs[str(x['cid'])],
targets_pred=pred_tgs[str(x['cid'])],
pref_name=x['pref_name'],
synonyms=eval(x['synonyms']),
desc=x['description']
),
'links': dict(
herbs=eval(x['herbs']),
formulas=eval(x['formulas'])
)
}
for x in dsets['ingredients']['train']}
json_db['herbs'] = {x['pref_name']: {'init': dict(pref_name=x['pref_name'],
synonyms=eval(x['synonyms']),
desc=x['description']),
'links': dict(ingrs=eval(x['ingredients']),
formulas=eval(x['formulas']))} for x in
dsets['herbs']['train']}
json_db['formulas'] = {x['pref_name']: {'init': dict(pref_name=x['pref_name'],
synonyms=eval(x['synonyms']),
desc=x['description']),
'links': dict(ingrs=eval(x['ingredients']),
herbs=eval(x['herbs']))} for x in
dsets['formulas']['train']}
db = cls.load(json_db)
return (db)
def drop_isolated(self, how='any'):
match how:
case 'any':
self.herbs = {x: y for x, y in self.herbs.items() if (y.ingrs and y.formulas)}
self.formulas = {x: y for x, y in self.formulas.items() if (y.ingrs and y.herbs)}
self.ingrs = {x: y for x, y in self.ingrs.items() if (y.formulas and y.herbs)}
case 'all':
self.herbs = {x: y for x, y in self.herbs.items() if (y.ingrs or y.formulas)}
self.formulas = {x: y for x, y in self.formulas.items() if (y.ingrs or y.herbs)}
self.ingrs = {x: y for x, y in self.ingrs.items() if (y.formulas or y.herbs)}
case _:
raise ValueError(f'Unknown how parameter: {how}. Known parameters are "any" and "all"')
def select_formula_by_cpd(self, cids: List):
cids = set(x for x in cids if x in self.ingrs)
if not cids:
return
cpd_counts = {x: len(set([z.cid for z in y.ingrs]) & cids) for x, y in self.formulas.items()}
n_max = max(cpd_counts.values())
if n_max == 0:
return (n_max, [])
selected = [x for x, y in cpd_counts.items() if y == n_max]
return (n_max, selected)
def pick_formula_by_cpd(self, cids: List):
cids = [x for x in cids if x in self.ingrs]
if not cids:
return
raise NotImplementedError()
def select_formula_by_herb(self, herbs: List):
raise NotImplementedError()
def pick_formula_by_herb(self, herbs: List):
raise NotImplementedError()
def main(ab_initio=False,
p_BATMAN="./BATMAN/",
fname='BATMAN_DB.json'):
p_BATMAN = p_BATMAN.removesuffix("/") + "/"
# Use in case you want to recreate the TCMDB database of Chinese medicine from BATMAN files
if ab_initio:
db = TCMDB.make_new_db(p_BATMAN)
db.link_ingredients_n_formulas()
db.save_to_json(p_BATMAN + fname)
# db.save_to_json('../TCM screening/BATMAN_DB.json')
else:
db = TCMDB.read_from_json('../TCM screening/BATMAN_DB.json')
# db = TCMDB.read_from_json(p_BATMAN + fname)
cids = [969516, # curcumin
445154, # resveratrol
5280343, # quercetin
6167, # colchicine
5280443, # apigening
65064, # EGCG3
5757, # estradiol
5994, # progesterone
5280863, # kaempferol
107985, # triptolide
14985, # alpha-tocopherol
1548943, # Capsaicin
64982, # Baicalin
6013, # Testosterone
]
p3_formula = db.select_formula_by_cpd(cids)
# somehow save file if needed ↓
ser_db = db.serialize()
###
if __name__ == '__main__':
main(ab_initio=True, p_BATMAN="./BATMAN/", fname='BATMAN_DB.json')
|