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