remove abc dependency
Browse files- 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 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
self.
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
self.
|
| 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 |
-
return (
|
| 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 |
-
if ingrs
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
self.ingrs
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
if herbs
|
| 136 |
-
herbs
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
self.herbs
|
| 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 |
-
self.
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
new_db
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
new_db
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
entrez_to_symb
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
cid
|
| 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 |
-
self.ingrs
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
herb_cids =
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
for
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
if
|
| 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 |
-
for
|
| 331 |
-
|
| 332 |
-
self.herbs.
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
if
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
for
|
| 357 |
-
|
| 358 |
-
self.formulas.
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
for
|
| 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 |
-
db =
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
db.
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
for
|
| 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 |
-
self.
|
| 476 |
-
self.
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
raise NotImplementedError()
|
| 500 |
-
|
| 501 |
-
def
|
| 502 |
-
raise NotImplementedError()
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
db
|
| 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 |
-
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 |
+
|
|
|
|
|
|
|
|
|