| Total Complexity | 45 |
| Total Lines | 522 |
| Duplicated Lines | 4.6 % |
| Changes | 0 | ||
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like mandos.model.apis.pubchem_support.pubchem_models often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | from __future__ import annotations |
||
|
|
|||
| 2 | import enum |
||
| 3 | import re |
||
| 4 | import typing |
||
| 5 | from dataclasses import dataclass |
||
| 6 | from datetime import date |
||
| 7 | from typing import Union, Optional, FrozenSet, Sequence, Mapping, Set |
||
| 8 | |||
| 9 | from pocketutils.core.dot_dict import NestedDotDict |
||
| 10 | from pocketutils.tools.string_tools import StringTools |
||
| 11 | |||
| 12 | from mandos.model import MandosResources |
||
| 13 | from mandos.model.apis.pubchem_support._nav_fns import Mapx |
||
| 14 | |||
| 15 | hazards = { |
||
| 16 | d["code"]: d for d in NestedDotDict.read_toml(MandosResources.path("hazards.toml"))["signals"] |
||
| 17 | } |
||
| 18 | |||
| 19 | |||
| 20 | @dataclass(frozen=True, repr=True, eq=True, order=True) |
||
| 21 | class ComputedProperty: |
||
| 22 | key: str |
||
| 23 | value: Union[int, str, float, bool] |
||
| 24 | unit: Optional[str] |
||
| 25 | ref: str |
||
| 26 | |||
| 27 | def req_is(self, type_) -> Union[int, str, float, bool]: |
||
| 28 | if not isinstance(self.value, type_): |
||
| 29 | raise TypeError(f"{self.key}->{self.value} has {type(self.value)}, not {type_}") |
||
| 30 | return self.value |
||
| 31 | |||
| 32 | @property |
||
| 33 | def as_str(self) -> str: |
||
| 34 | return f"{self.value} {self.unit}" |
||
| 35 | |||
| 36 | |||
| 37 | class Code(str): |
||
| 38 | @property |
||
| 39 | def type_name(self) -> str: |
||
| 40 | return self.__class__.__name__.lower() |
||
| 41 | |||
| 42 | View Code Duplication | @classmethod |
|
| 43 | def of(cls, value: Union[str, int, float]): |
||
| 44 | if isinstance(value, float): |
||
| 45 | try: |
||
| 46 | value = int(value) |
||
| 47 | value = StringTools.strip_off_end(str(value).strip(), ".0") |
||
| 48 | except ArithmeticError: |
||
| 49 | value = str(value) |
||
| 50 | value = StringTools.strip_off_end(str(value).strip(), ".0") |
||
| 51 | value = str(value).strip() |
||
| 52 | return cls(value) |
||
| 53 | |||
| 54 | View Code Duplication | @classmethod |
|
| 55 | def of_nullable(cls, value: Union[None, str, int, float]): |
||
| 56 | if value is None: |
||
| 57 | return None |
||
| 58 | if isinstance(value, float): |
||
| 59 | try: |
||
| 60 | value = int(value) |
||
| 61 | value = StringTools.strip_off_end(str(value).strip(), ".0") |
||
| 62 | except ArithmeticError: |
||
| 63 | value = str(value) |
||
| 64 | value = StringTools.strip_off_end(str(value).strip(), ".0") |
||
| 65 | value = str(value).strip() |
||
| 66 | return cls(value) |
||
| 67 | |||
| 68 | |||
| 69 | class Codes: |
||
| 70 | """ |
||
| 71 | These turn out to be extremely useful for documenting return types. |
||
| 72 | For example, ``DrugbankInteraction`` might have a ``gene`` field, |
||
| 73 | which can be described as a ``GenecardSymbol`` if known. |
||
| 74 | """ |
||
| 75 | |||
| 76 | class ChemIdPlusOrganism(Code): |
||
| 77 | """ |
||
| 78 | E.g. 'women', 'frog', 'infant', or 'domestic animals - goat/sheep' |
||
| 79 | """ |
||
| 80 | |||
| 81 | @property |
||
| 82 | def is_human(self) -> bool: |
||
| 83 | return str(self) in {"women", "woman", "men", "man", "infant", "infants", "human"} |
||
| 84 | |||
| 85 | class ChemIdPlusEffect(Code): |
||
| 86 | """ |
||
| 87 | E.g. 'BEHAVIORAL: MUSCLE WEAKNESS' |
||
| 88 | """ |
||
| 89 | |||
| 90 | @property |
||
| 91 | def category(self) -> str: |
||
| 92 | return self[: self.index(":")].strip() |
||
| 93 | |||
| 94 | @property |
||
| 95 | def subcategory(self) -> str: |
||
| 96 | return self[self.index(":") + 1 :].strip() |
||
| 97 | |||
| 98 | class EcNumber(Code): |
||
| 99 | """ |
||
| 100 | e.g. 'EC:4.6.1.1' |
||
| 101 | """ |
||
| 102 | |||
| 103 | class GeneId(Code): |
||
| 104 | """ |
||
| 105 | GeneCard, UniProt gene name, etc. |
||
| 106 | e.g. 'slc1a2' |
||
| 107 | """ |
||
| 108 | |||
| 109 | class ClinicaltrialId(Code): |
||
| 110 | """ |
||
| 111 | From clinicaltrials.gov |
||
| 112 | """ |
||
| 113 | |||
| 114 | class GenericDiseaseCode(Code): |
||
| 115 | """ |
||
| 116 | From clinicaltrials.gov; pure int |
||
| 117 | """ |
||
| 118 | |||
| 119 | class GenecardSymbol(GeneId): |
||
| 120 | """ """ |
||
| 121 | |||
| 122 | class UniprotId(GeneId): |
||
| 123 | """ """ |
||
| 124 | |||
| 125 | class PubchemCompoundId(Code): |
||
| 126 | """ |
||
| 127 | e.g. 2352 |
||
| 128 | """ |
||
| 129 | |||
| 130 | @property |
||
| 131 | def value(self) -> int: |
||
| 132 | return int(self) |
||
| 133 | |||
| 134 | class AtcCode(Code): |
||
| 135 | """ """ |
||
| 136 | |||
| 137 | class PubmedId(Code): |
||
| 138 | """ """ |
||
| 139 | |||
| 140 | class Doi(Code): |
||
| 141 | """ """ |
||
| 142 | |||
| 143 | class MeshCode(Code): |
||
| 144 | """ """ |
||
| 145 | |||
| 146 | class PdbId(Code): |
||
| 147 | """ """ |
||
| 148 | |||
| 149 | class MeshHeading(Code): |
||
| 150 | """ """ |
||
| 151 | |||
| 152 | class MeshSubheading(Code): |
||
| 153 | """ """ |
||
| 154 | |||
| 155 | class DrugbankCompoundId(Code): |
||
| 156 | """ """ |
||
| 157 | |||
| 158 | class DeaSchedule(Code): |
||
| 159 | """ """ |
||
| 160 | |||
| 161 | @property |
||
| 162 | def value(self) -> int: |
||
| 163 | return Mapx.roman_to_arabic(1, 5)(self) |
||
| 164 | |||
| 165 | class GhsCode(Code): |
||
| 166 | """ """ |
||
| 167 | |||
| 168 | |||
| 169 | class CoOccurrenceType(enum.Enum): |
||
| 170 | chemical = enum.auto() |
||
| 171 | gene = enum.auto() |
||
| 172 | disease = enum.auto() |
||
| 173 | |||
| 174 | @property |
||
| 175 | def x_name(self) -> str: |
||
| 176 | if self is CoOccurrenceType.chemical: |
||
| 177 | return "ChemicalNeighbor" |
||
| 178 | elif self is CoOccurrenceType.gene: |
||
| 179 | return "ChemicalGeneSymbolNeighbor" |
||
| 180 | elif self is CoOccurrenceType.disease: |
||
| 181 | return "ChemicalDiseaseNeighbor" |
||
| 182 | raise AssertionError(f"{self} not found!!") |
||
| 183 | |||
| 184 | @property |
||
| 185 | def id_name(self) -> str: |
||
| 186 | if self is CoOccurrenceType.chemical: |
||
| 187 | return "CID" |
||
| 188 | elif self is CoOccurrenceType.gene: |
||
| 189 | return "GeneSymbol" |
||
| 190 | elif self is CoOccurrenceType.disease: |
||
| 191 | return "MeSH" |
||
| 192 | raise AssertionError(f"{self} not found!!") |
||
| 193 | |||
| 194 | |||
| 195 | class ClinicalTrialsGovUtils: |
||
| 196 | @classmethod |
||
| 197 | def phase_map(cls) -> Mapping[str, float]: |
||
| 198 | return { |
||
| 199 | "Phase 4": 4, |
||
| 200 | "Phase 3": 3, |
||
| 201 | "Phase 2": 2, |
||
| 202 | "Phase 1": 1, |
||
| 203 | "Early Phase 1": 1.5, |
||
| 204 | "Phase 2/Phase 3": 2.5, |
||
| 205 | "N/A": 0, |
||
| 206 | } |
||
| 207 | |||
| 208 | @classmethod |
||
| 209 | def known_phases(cls) -> Set[float]: |
||
| 210 | return set(cls.phase_map().values()) |
||
| 211 | |||
| 212 | @classmethod |
||
| 213 | def resolve_statuses(cls, st: str) -> Set[str]: |
||
| 214 | found = set() |
||
| 215 | for s in st.lower().split(","): |
||
| 216 | s = s.strip() |
||
| 217 | if s == "@all": |
||
| 218 | match = cls.known_statuses() |
||
| 219 | elif s in cls.known_statuses(): |
||
| 220 | match = {s} |
||
| 221 | else: |
||
| 222 | raise ValueError(s) |
||
| 223 | for m in match: |
||
| 224 | found.add(m) |
||
| 225 | return found |
||
| 226 | |||
| 227 | @classmethod |
||
| 228 | def known_statuses(cls) -> Set[str]: |
||
| 229 | return set(cls.status_map().values()) |
||
| 230 | |||
| 231 | @classmethod |
||
| 232 | def status_map(cls) -> Mapping[str, str]: |
||
| 233 | return { |
||
| 234 | "Unknown status": "unknown", |
||
| 235 | "Completed": "completed", |
||
| 236 | "Terminated": "stopped", |
||
| 237 | "Suspended": "stopped", |
||
| 238 | "Withdrawn": "stopped", |
||
| 239 | "Not yet recruiting": "ongoing", |
||
| 240 | "Recruiting": "ongoing", |
||
| 241 | "Enrolling by invitation": "ongoing", |
||
| 242 | "Active, not recruiting": "ongoing", |
||
| 243 | "Available": "completed", |
||
| 244 | "No longer available": "completed", |
||
| 245 | "Temporarily not available": "completed", |
||
| 246 | "Approved for marketing": "completed", |
||
| 247 | } |
||
| 248 | |||
| 249 | |||
| 250 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 251 | class ClinicalTrial: |
||
| 252 | ctid: Codes.ClinicaltrialId |
||
| 253 | title: str |
||
| 254 | conditions: FrozenSet[str] |
||
| 255 | disease_ids: FrozenSet[Codes.ClinicaltrialId] |
||
| 256 | phase: str |
||
| 257 | status: str |
||
| 258 | interventions: FrozenSet[str] |
||
| 259 | cids: FrozenSet[Codes.PubchemCompoundId] |
||
| 260 | source: str |
||
| 261 | |||
| 262 | @property |
||
| 263 | def mapped_phase(self) -> float: |
||
| 264 | return ClinicalTrialsGovUtils.phase_map().get(self.phase, 0) |
||
| 265 | |||
| 266 | @property |
||
| 267 | def mapped_status(self) -> str: |
||
| 268 | return ClinicalTrialsGovUtils.status_map().get(self.status, "unknown") |
||
| 269 | |||
| 270 | |||
| 271 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 272 | class GhsCode: |
||
| 273 | code: Codes.GhsCode |
||
| 274 | statement: str |
||
| 275 | clazz: str |
||
| 276 | categories: FrozenSet[str] |
||
| 277 | signal_word: str |
||
| 278 | type: str |
||
| 279 | |||
| 280 | @classmethod |
||
| 281 | def find(cls, code: str) -> GhsCode: |
||
| 282 | h = hazards[code] |
||
| 283 | cats = h["category"] # TODO |
||
| 284 | return GhsCode( |
||
| 285 | code=Codes.GhsCode(code), |
||
| 286 | statement=h["statement"], |
||
| 287 | clazz=h["class"], |
||
| 288 | categories=cats, |
||
| 289 | signal_word=h["signal_word"], |
||
| 290 | type=h["type"], |
||
| 291 | ) |
||
| 292 | |||
| 293 | @property |
||
| 294 | def level(self) -> int: |
||
| 295 | return int(self.code[1]) |
||
| 296 | |||
| 297 | |||
| 298 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 299 | class AcuteEffectEntry: |
||
| 300 | gid: int |
||
| 301 | effects: FrozenSet[Codes.ChemIdPlusEffect] |
||
| 302 | organism: Codes.ChemIdPlusOrganism |
||
| 303 | test_type: str |
||
| 304 | route: str |
||
| 305 | dose: str |
||
| 306 | |||
| 307 | @property |
||
| 308 | def mg_per_kg(self) -> float: |
||
| 309 | # TODO: Could it ever start with just a dot; e.g. '.175'? |
||
| 310 | match = re.compile(r".+?\((\d+(?:.\d+)?) *mg/kg\)").fullmatch(self.dose) |
||
| 311 | if match is None: |
||
| 312 | raise ValueError(f"Dose {self.dose} (accute effect {self.gid}) could not be parsed") |
||
| 313 | return float(match.group(1)) |
||
| 314 | |||
| 315 | |||
| 316 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 317 | class AssociatedDisorder: |
||
| 318 | gid: str |
||
| 319 | disease_id: Codes.MeshCode |
||
| 320 | disease_name: str |
||
| 321 | evidence_type: str |
||
| 322 | n_refs: int |
||
| 323 | |||
| 324 | |||
| 325 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 326 | class AtcCode: |
||
| 327 | code: str |
||
| 328 | name: str |
||
| 329 | |||
| 330 | @property |
||
| 331 | def level(self) -> int: |
||
| 332 | return len(self.parts) |
||
| 333 | |||
| 334 | @property |
||
| 335 | def parts(self) -> Sequence[str]: |
||
| 336 | pat = re.compile(r"([A-Z])([0-9]{2})?([A-Z])?([A-Z])?([A-Z])?") |
||
| 337 | match = pat.fullmatch(self.code) |
||
| 338 | return [g for g in match.groups() if g is not None] |
||
| 339 | |||
| 340 | |||
| 341 | class DrugbankTargetType(enum.Enum): |
||
| 342 | target = enum.auto() |
||
| 343 | carrier = enum.auto() |
||
| 344 | transporter = enum.auto() |
||
| 345 | enzyme = enum.auto() |
||
| 346 | |||
| 347 | |||
| 348 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 349 | class DrugbankInteraction: |
||
| 350 | record_id: Optional[str] |
||
| 351 | gene_symbol: Codes.GeneId |
||
| 352 | action: Optional[str] |
||
| 353 | protein_id: str |
||
| 354 | target_type: DrugbankTargetType |
||
| 355 | target_name: str |
||
| 356 | general_function: Optional[str] |
||
| 357 | specific_function: str |
||
| 358 | pmids: FrozenSet[Codes.PubmedId] |
||
| 359 | dois: FrozenSet[Codes.Doi] |
||
| 360 | |||
| 361 | |||
| 362 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 363 | class DrugbankDdi: |
||
| 364 | drug_drugbank_id: Codes.DrugbankCompoundId |
||
| 365 | drug_pubchem_id: Codes.PubchemCompoundId |
||
| 366 | drug_drugbank_name: str |
||
| 367 | description: str |
||
| 368 | |||
| 369 | |||
| 370 | class Activity(enum.Enum): |
||
| 371 | active = enum.auto() |
||
| 372 | inactive = enum.auto() |
||
| 373 | inconclusive = enum.auto() |
||
| 374 | unspecified = enum.auto() |
||
| 375 | |||
| 376 | |||
| 377 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 378 | class Bioactivity: |
||
| 379 | assay_id: int |
||
| 380 | assay_type: str |
||
| 381 | assay_ref: str |
||
| 382 | assay_name: str |
||
| 383 | assay_made_date: date |
||
| 384 | gene_id: Optional[Codes.GeneId] |
||
| 385 | tax_id: Optional[int] |
||
| 386 | pmid: Optional[Codes.PubmedId] |
||
| 387 | activity: Optional[Activity] |
||
| 388 | activity_name: Optional[str] |
||
| 389 | activity_value: Optional[float] |
||
| 390 | target_name: Optional[str] |
||
| 391 | compound_name: str |
||
| 392 | |||
| 393 | @property |
||
| 394 | def target_name_abbrev_species(self) -> typing.Tuple[Optional[str], str, Optional[str]]: |
||
| 395 | # first, look for a species name in parentheses |
||
| 396 | # We use \)+ at the end instead of \) |
||
| 397 | # this is to catch cases where we have parentheses inside of the species name |
||
| 398 | # this happens with some virus strains, for e.g. |
||
| 399 | match = re.compile(r"^(.+?)\(([^)]+)\)+$").fullmatch(self.target_name) |
||
| 400 | if match is None: |
||
| 401 | species = None |
||
| 402 | target = self.target_name |
||
| 403 | else: |
||
| 404 | species = match.group(2) |
||
| 405 | target = match.group(1) |
||
| 406 | # now try to get an abbreviation |
||
| 407 | match = re.compile(r"^ *([^ ]+) +- +(.+)$").fullmatch(target) |
||
| 408 | if match is None: |
||
| 409 | abbrev = None |
||
| 410 | name = target |
||
| 411 | else: |
||
| 412 | abbrev = match.group(1) |
||
| 413 | name = match.group(2) |
||
| 414 | return name, abbrev, species |
||
| 415 | |||
| 416 | |||
| 417 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 418 | class PdbEntry: |
||
| 419 | pdbid: Codes.PdbId |
||
| 420 | title: str |
||
| 421 | exp_method: str |
||
| 422 | resolution: float |
||
| 423 | lig_names: FrozenSet[str] |
||
| 424 | cids: FrozenSet[Codes.PubchemCompoundId] |
||
| 425 | uniprot_ids: FrozenSet[Codes.UniprotId] |
||
| 426 | pmids: FrozenSet[Codes.PubmedId] |
||
| 427 | dois: FrozenSet[Codes.Doi] |
||
| 428 | |||
| 429 | |||
| 430 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 431 | class PubmedEntry: |
||
| 432 | pmid: Codes.PubmedId |
||
| 433 | article_type: str |
||
| 434 | pmidsrcs: FrozenSet[str] |
||
| 435 | mesh_headings: FrozenSet[Codes.MeshHeading] |
||
| 436 | mesh_subheadings: FrozenSet[Codes.MeshSubheading] |
||
| 437 | mesh_codes: FrozenSet[Codes.MeshCode] |
||
| 438 | cids: FrozenSet[Codes.PubchemCompoundId] |
||
| 439 | article_title: str |
||
| 440 | article_abstract: str |
||
| 441 | journal_name: str |
||
| 442 | pub_date: date |
||
| 443 | |||
| 444 | |||
| 445 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 446 | class Publication: |
||
| 447 | pmid: Codes.PubmedId |
||
| 448 | pub_date: date |
||
| 449 | is_review: bool |
||
| 450 | title: str |
||
| 451 | journal: str |
||
| 452 | relevance_score: int |
||
| 453 | |||
| 454 | |||
| 455 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 456 | class CoOccurrence: |
||
| 457 | neighbor_id: str |
||
| 458 | neighbor_name: str |
||
| 459 | kind: CoOccurrenceType |
||
| 460 | # https://pubchemdocs.ncbi.nlm.nih.gov/knowledge-panels |
||
| 461 | article_count: int |
||
| 462 | query_article_count: int |
||
| 463 | neighbor_article_count: int |
||
| 464 | score: int |
||
| 465 | publications: FrozenSet[Publication] |
||
| 466 | |||
| 467 | def strip_pubs(self) -> CoOccurrence: |
||
| 468 | return CoOccurrence( |
||
| 469 | self.neighbor_id, |
||
| 470 | self.neighbor_name, |
||
| 471 | self.kind, |
||
| 472 | self.article_count, |
||
| 473 | self.query_article_count, |
||
| 474 | self.neighbor_article_count, |
||
| 475 | self.score, |
||
| 476 | frozenset({}), |
||
| 477 | ) |
||
| 478 | |||
| 479 | |||
| 480 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 481 | class DrugGeneInteraction: |
||
| 482 | """ """ |
||
| 483 | |||
| 484 | gene_name: Optional[str] |
||
| 485 | gene_claim_id: Optional[str] |
||
| 486 | source: str |
||
| 487 | interactions: FrozenSet[str] |
||
| 488 | pmids: FrozenSet[Codes.PubmedId] |
||
| 489 | dois: FrozenSet[Codes.Doi] |
||
| 490 | |||
| 491 | |||
| 492 | @dataclass(frozen=True, repr=True, eq=True) |
||
| 493 | class ChemicalGeneInteraction: |
||
| 494 | gene_name: Optional[Codes.GeneId] |
||
| 495 | interactions: FrozenSet[str] |
||
| 496 | tax_id: Optional[int] |
||
| 497 | tax_name: Optional[str] |
||
| 498 | pmids: FrozenSet[Codes.PubmedId] |
||
| 499 | |||
| 500 | |||
| 501 | __all__ = [ |
||
| 502 | "ClinicalTrial", |
||
| 503 | "AssociatedDisorder", |
||
| 504 | "AtcCode", |
||
| 505 | "DrugbankInteraction", |
||
| 506 | "DrugbankDdi", |
||
| 507 | "Bioactivity", |
||
| 508 | "Activity", |
||
| 509 | "DrugGeneInteraction", |
||
| 510 | "ChemicalGeneInteraction", |
||
| 511 | "GhsCode", |
||
| 512 | "PubmedEntry", |
||
| 513 | "Code", |
||
| 514 | "Codes", |
||
| 515 | "CoOccurrenceType", |
||
| 516 | "CoOccurrence", |
||
| 517 | "Publication", |
||
| 518 | "ComputedProperty", |
||
| 519 | "ClinicalTrialsGovUtils", |
||
| 520 | "AcuteEffectEntry", |
||
| 521 | "DrugbankTargetType", |
||
| 522 | ] |
||
| 523 |