|
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} |
|
|
|
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) |
|
|
|
|
|
|
|
pred_ingreds = dict() |
|
with open(self.batman_files['p_pred_by_ingr'], 'r') as f: |
|
|
|
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'] |
|
|
|
|
|
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") |
|
|
|
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="") |
|
|
|
|
|
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()} |
|
|
|
|
|
for i in db.ingrs.values(): |
|
|
|
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()} |
|
|
|
|
|
|
|
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("/") + "/" |
|
|
|
if ab_initio: |
|
db = TCMDB.make_new_db(p_BATMAN) |
|
db.link_ingredients_n_formulas() |
|
db.save_to_json(p_BATMAN + fname) |
|
|
|
|
|
else: |
|
db = TCMDB.read_from_json('../TCM screening/BATMAN_DB.json') |
|
|
|
|
|
cids = [969516, |
|
445154, |
|
5280343, |
|
6167, |
|
5280443, |
|
65064, |
|
5757, |
|
5994, |
|
5280863, |
|
107985, |
|
14985, |
|
1548943, |
|
64982, |
|
6013, |
|
] |
|
|
|
p3_formula = db.select_formula_by_cpd(cids) |
|
|
|
ser_db = db.serialize() |
|
|
|
|
|
|
|
|
|
if __name__ == '__main__': |
|
main(ab_initio=True, p_BATMAN="./BATMAN/", fname='BATMAN_DB.json') |
|
|
|
|
|
|