1
|
|
|
from __future__ import annotations |
|
|
|
|
2
|
|
|
|
3
|
|
|
import os |
4
|
|
|
from dataclasses import dataclass |
5
|
|
|
from pathlib import Path |
6
|
|
|
from typing import ( |
7
|
|
|
AbstractSet, |
8
|
|
|
Any, |
9
|
|
|
Callable, |
10
|
|
|
Iterable, |
11
|
|
|
Mapping, |
12
|
|
|
Optional, |
13
|
|
|
Sequence, |
14
|
|
|
Set, |
15
|
|
|
Tuple, |
16
|
|
|
TypeVar, |
17
|
|
|
Union, |
18
|
|
|
) |
19
|
|
|
|
20
|
|
|
from pocketutils.core.exceptions import PathExistsError, XTypeError, XValueError |
|
|
|
|
21
|
|
|
from pocketutils.misc.typer_utils import Arg, Opt |
|
|
|
|
22
|
|
|
from pocketutils.tools.path_tools import PathTools |
|
|
|
|
23
|
|
|
from regex import regex |
|
|
|
|
24
|
|
|
from typeddfs.df_errors import FilenameSuffixError |
|
|
|
|
25
|
|
|
|
26
|
|
|
from mandos import logger |
27
|
|
|
from mandos.model.apis.chembl_support.chembl_targets import TargetType |
28
|
|
|
from mandos.model.apis.pubchem_support.pubchem_models import ClinicalTrialsGovUtils |
29
|
|
|
from mandos.model.settings import SETTINGS, Globals |
30
|
|
|
from mandos.model.taxonomy import Taxonomy |
31
|
|
|
from mandos.model.taxonomy_caches import TaxonomyFactories |
32
|
|
|
|
33
|
|
|
T = TypeVar("T", covariant=True) |
|
|
|
|
34
|
|
|
|
35
|
|
|
|
36
|
|
|
@dataclass(frozen=True, repr=True, order=True) |
|
|
|
|
37
|
|
|
class ParsedTaxa: |
38
|
|
|
source: str |
39
|
|
|
allow: Sequence[Union[int, str]] |
40
|
|
|
forbid: Sequence[Union[int, str]] |
41
|
|
|
ancestors: Sequence[Union[int, str]] |
42
|
|
|
|
43
|
|
|
@classmethod |
44
|
|
|
def empty(cls) -> ParsedTaxa: |
|
|
|
|
45
|
|
|
return ParsedTaxa("", [], [], []) |
46
|
|
|
|
47
|
|
|
|
48
|
|
|
class ArgUtils: |
|
|
|
|
49
|
|
|
@classmethod |
50
|
|
|
def definition_bullets(cls, dct: Mapping[Any, Any], colon: str = ": ", indent: int = 12) -> str: |
|
|
|
|
51
|
|
|
joiner = os.linesep * 2 + " " * indent |
52
|
|
|
jesus = [f" - {k}{colon}{v}" for k, v in dct.items()] |
53
|
|
|
return joiner.join(jesus) |
54
|
|
|
|
55
|
|
|
@classmethod |
56
|
|
|
def definition_list(cls, dct: Mapping[Any, Any], colon: str = ": ", sep: str = "; ") -> str: |
|
|
|
|
57
|
|
|
jesus = [f"{k}{colon}{v}" for k, v in dct.items()] |
58
|
|
|
return sep.join(jesus) |
59
|
|
|
|
60
|
|
|
@classmethod |
61
|
|
|
def list( |
|
|
|
|
62
|
|
|
cls, |
|
|
|
|
63
|
|
|
lst: Iterable[Any], |
|
|
|
|
64
|
|
|
*, |
|
|
|
|
65
|
|
|
attr: Union[None, str, Callable[[Any], Any]] = None, |
|
|
|
|
66
|
|
|
sep: str = ", ", |
|
|
|
|
67
|
|
|
) -> str: |
68
|
|
|
x = [] |
|
|
|
|
69
|
|
|
for v in lst: |
|
|
|
|
70
|
|
|
if attr is None and hasattr(v, "name"): |
71
|
|
|
x += [v.name] |
|
|
|
|
72
|
|
|
elif attr is None: |
73
|
|
|
x += [str(v)] |
|
|
|
|
74
|
|
|
elif isinstance(attr, str): |
75
|
|
|
x += [str(getattr(v, attr))] |
|
|
|
|
76
|
|
|
else: |
77
|
|
|
x += [str(attr(v))] |
|
|
|
|
78
|
|
|
return sep.join(x) |
79
|
|
|
|
80
|
|
|
@classmethod |
81
|
|
|
def get_taxonomy( |
|
|
|
|
82
|
|
|
cls, |
|
|
|
|
83
|
|
|
taxa: Optional[str], |
|
|
|
|
84
|
|
|
*, |
|
|
|
|
85
|
|
|
local_only: bool = False, |
|
|
|
|
86
|
|
|
allow_forbid: bool = True, |
|
|
|
|
87
|
|
|
) -> Optional[Taxonomy]: |
88
|
|
|
if taxa is None or len(taxa) == 0: |
89
|
|
|
return None |
90
|
|
|
parsed = cls.parse_taxa(taxa, allow_forbid=allow_forbid) |
91
|
|
|
return TaxonomyFactories.get_smart_taxonomy( |
92
|
|
|
allow=parsed.allow, |
93
|
|
|
forbid=parsed.forbid, |
94
|
|
|
ancestors=parsed.ancestors, |
95
|
|
|
local_only=local_only, |
96
|
|
|
) |
97
|
|
|
|
98
|
|
|
@classmethod |
99
|
|
|
def parse_taxa( |
|
|
|
|
100
|
|
|
cls, |
|
|
|
|
101
|
|
|
taxa: Optional[str], |
|
|
|
|
102
|
|
|
*, |
|
|
|
|
103
|
|
|
allow_forbid: bool = True, |
|
|
|
|
104
|
|
|
) -> ParsedTaxa: |
105
|
|
|
if taxa is None or taxa == "": |
106
|
|
|
return ParsedTaxa.empty() |
107
|
|
|
ancestors = f"{Globals.cellular_taxon},{Globals.viral_taxon}" |
108
|
|
|
if ":" in taxa: |
109
|
|
|
ancestors = taxa.split(":", 1)[1] |
110
|
|
|
taxa = taxa.split(":", 1)[0] |
111
|
|
|
taxa_objs = [t.strip() for t in taxa.split(",") if len(t.strip()) > 0] |
112
|
|
|
allow = [t.strip().lstrip("+") for t in taxa_objs if not t.startswith("-")] |
113
|
|
|
forbid = [t.strip().lstrip("-") for t in taxa_objs if t.startswith("-")] |
114
|
|
|
ancestors = [t.strip() for t in ancestors.split(",")] |
115
|
|
|
if not allow_forbid and len(forbid) > 0: |
116
|
|
|
raise XValueError(f"Cannot use '-' in {taxa}") |
117
|
|
|
return ParsedTaxa( |
118
|
|
|
source=taxa, |
119
|
|
|
allow=[ArgUtils.parse_taxon(t, id_only=False) for t in allow], |
120
|
|
|
forbid=[ArgUtils.parse_taxon(t, id_only=False) for t in forbid], |
121
|
|
|
ancestors=[ArgUtils.parse_taxon(t, id_only=True) for t in ancestors], |
122
|
|
|
) |
123
|
|
|
|
124
|
|
|
@classmethod |
125
|
|
|
def parse_taxa_ids(cls, taxa: str) -> Sequence[int]: |
126
|
|
|
""" |
127
|
|
|
Does not allow negatives. |
128
|
|
|
""" |
129
|
|
|
if taxa is None or taxa == "": |
130
|
|
|
return [] |
131
|
|
|
taxa = [t.strip() for t in taxa.split(",") if len(t.strip()) > 0] |
132
|
|
|
return [ArgUtils.parse_taxon(t, id_only=True) for t in taxa] |
133
|
|
|
|
134
|
|
|
@classmethod |
135
|
|
|
def parse_taxon(cls, taxon: Union[int, str], *, id_only: bool = False) -> Union[int, str]: |
|
|
|
|
136
|
|
|
std = cls._get_std_taxon(taxon) |
137
|
|
|
if isinstance(taxon, str) and taxon in std: |
138
|
|
|
return std |
139
|
|
|
if isinstance(taxon, str) and not id_only: |
|
|
|
|
140
|
|
|
return taxon |
141
|
|
|
elif isinstance(taxon, str) and taxon.isdigit(): |
142
|
|
|
return int(taxon) |
143
|
|
|
if id_only: |
144
|
|
|
raise XTypeError(f"Taxon {taxon} must be an ID") |
145
|
|
|
raise XTypeError(f"Taxon {taxon} must be an ID or name") |
146
|
|
|
|
147
|
|
|
@classmethod |
148
|
|
|
def _get_std_taxon(cls, taxa: str) -> str: |
149
|
|
|
x = dict( |
|
|
|
|
150
|
|
|
vertebrata=Globals.vertebrata, |
151
|
|
|
vertebrate=Globals.vertebrata, |
152
|
|
|
vertebrates=Globals.vertebrata, |
153
|
|
|
cellular=Globals.cellular_taxon, |
154
|
|
|
cell=Globals.cellular_taxon, |
155
|
|
|
cells=Globals.cellular_taxon, |
156
|
|
|
viral=Globals.viral_taxon, |
157
|
|
|
virus=Globals.viral_taxon, |
158
|
|
|
viruses=Globals.viral_taxon, |
159
|
|
|
all=f"{Globals.cellular_taxon},{Globals.viral_taxon}", |
160
|
|
|
).get(taxa) |
161
|
|
|
return taxa if x is None else str(x) |
162
|
|
|
|
163
|
|
|
@staticmethod |
164
|
|
|
def get_trial_statuses(st: str) -> Set[str]: |
|
|
|
|
165
|
|
|
return ClinicalTrialsGovUtils.resolve_statuses(st) |
166
|
|
|
|
167
|
|
|
@staticmethod |
168
|
|
|
def get_target_types(st: str) -> Set[str]: |
|
|
|
|
169
|
|
|
return {s.name for s in TargetType.resolve(st)} |
170
|
|
|
|
171
|
|
|
|
172
|
|
|
class EntryUtils: |
|
|
|
|
173
|
|
|
@classmethod |
174
|
|
|
def adjust_filename( |
|
|
|
|
175
|
|
|
cls, |
|
|
|
|
176
|
|
|
to: Optional[Path], |
|
|
|
|
177
|
|
|
default: Union[str, Path], |
|
|
|
|
178
|
|
|
replace: bool, |
|
|
|
|
179
|
|
|
*, |
|
|
|
|
180
|
|
|
suffixes: Union[None, AbstractSet[str], Callable[[Union[Path, str]], Any]] = None, |
|
|
|
|
181
|
|
|
) -> Path: |
182
|
|
|
if to is None: |
183
|
|
|
path = Path(default) |
184
|
|
|
elif str(to).startswith("."): |
185
|
|
|
path = Path(default).with_suffix(str(to)) |
186
|
|
|
elif str(to).startswith("*."): |
187
|
|
|
path = Path(default).with_suffix(str(to)[1:]) |
188
|
|
|
elif to.is_dir() or to.suffix == "": |
189
|
|
|
path = to / default |
190
|
|
|
else: |
191
|
|
|
path = Path(to) |
192
|
|
|
path = Path(path) |
193
|
|
|
if os.name == "nt" and SETTINGS.sanitize_paths: |
194
|
|
|
new_path = Path(*PathTools.sanitize_nodes(path._parts, is_file=True)) |
|
|
|
|
195
|
|
|
if new_path.resolve() != path.resolve(): |
196
|
|
|
logger.warning(f"Sanitized filename {path} → {new_path}") |
197
|
|
|
path = new_path |
198
|
|
|
if ( |
199
|
|
|
path.exists() |
|
|
|
|
200
|
|
|
and not path.is_file() |
|
|
|
|
201
|
|
|
and not path.is_socket() |
|
|
|
|
202
|
|
|
and not path.is_char_device() |
|
|
|
|
203
|
|
|
): |
204
|
|
|
raise PathExistsError(f"Path {path} exists and is not a file") |
205
|
|
|
if path.exists() and not replace: |
206
|
|
|
raise PathExistsError(f"File {path} already exists") |
207
|
|
|
cls._check_suffix(path.suffix, suffixes) |
208
|
|
|
if path.exists() and replace: |
209
|
|
|
logger.info(f"Overwriting existing file {path}") |
210
|
|
|
return path |
211
|
|
|
|
212
|
|
|
@classmethod |
213
|
|
|
def adjust_dir_name( |
|
|
|
|
214
|
|
|
cls, |
|
|
|
|
215
|
|
|
to: Optional[Path], |
|
|
|
|
216
|
|
|
default: Union[str, Path], |
|
|
|
|
217
|
|
|
*, |
|
|
|
|
218
|
|
|
suffixes: Union[None, AbstractSet[str], Callable[[Union[Path, str]], Any]] = None, |
|
|
|
|
219
|
|
|
) -> Tuple[Path, str]: |
220
|
|
|
out_dir = Path(default) |
221
|
|
|
suffix = SETTINGS.table_suffix |
222
|
|
|
if to is not None: |
223
|
|
|
pat = regex.compile(r"([^\*]*)(?:\*(\..+))", flags=regex.V1) |
224
|
|
|
m: regex.Match = pat.fullmatch(to) |
|
|
|
|
225
|
|
|
out_dir = default if m.group(1) == "" else m.group(1) |
226
|
|
|
suffix = SETTINGS.table_suffix if m.group(2) == "" else m.group(2) |
227
|
|
|
if out_dir.startswith("."): |
228
|
|
|
logger.warning(f"Writing to {out_dir} — was it meant as a suffix instead?") |
229
|
|
|
out_dir = Path(out_dir) |
230
|
|
|
if os.name == "nt" and SETTINGS.sanitize_paths: |
231
|
|
|
new_dir = Path(*PathTools.sanitize_nodes(out_dir._parts, is_file=True)) |
|
|
|
|
232
|
|
|
if new_dir.resolve() != out_dir.resolve(): |
233
|
|
|
logger.warning(f"Sanitized directory {out_dir} → {new_dir}") |
234
|
|
|
out_dir = new_dir |
235
|
|
|
if out_dir.exists() and not out_dir.is_dir(): |
236
|
|
|
raise PathExistsError(f"Path {out_dir} already exists but and is not a directory") |
237
|
|
|
cls._check_suffix(suffix, suffixes) |
238
|
|
|
if out_dir.exists(): |
239
|
|
|
n_files = len(list(out_dir.iterdir())) |
240
|
|
|
if n_files > 0: |
241
|
|
|
logger.debug(f"Directory {out_dir} is non-emtpy") |
242
|
|
|
return out_dir, suffix |
243
|
|
|
|
244
|
|
|
@classmethod |
245
|
|
|
def _check_suffix(cls, suffix, suffixes): |
246
|
|
|
if suffixes is not None and callable(suffixes): |
247
|
|
|
try: |
248
|
|
|
suffixes(suffix) # make sure it's ok |
249
|
|
|
except FilenameSuffixError: |
250
|
|
|
raise XValueError(f"Unsupported file format {suffix}") |
251
|
|
|
elif suffixes is not None: |
252
|
|
|
if suffix not in suffixes: |
253
|
|
|
raise XValueError(f"Unsupported file format {suffix}") |
254
|
|
|
|
255
|
|
|
|
256
|
|
|
__all__ = ["Arg", "Opt", "ArgUtils", "EntryUtils"] |
257
|
|
|
|