1
|
|
|
import os |
|
|
|
|
2
|
|
|
from inspect import cleandoc |
3
|
|
|
from pathlib import Path |
4
|
|
|
from typing import ( |
5
|
|
|
AbstractSet, |
6
|
|
|
Any, |
7
|
|
|
Callable, |
8
|
|
|
Iterable, |
9
|
|
|
Mapping, |
10
|
|
|
Optional, |
11
|
|
|
Sequence, |
12
|
|
|
Set, |
13
|
|
|
Tuple, |
14
|
|
|
TypeVar, |
15
|
|
|
Union, |
16
|
|
|
) |
17
|
|
|
|
18
|
|
|
import typer |
|
|
|
|
19
|
|
|
from pocketutils.core.exceptions import PathExistsError, XTypeError, XValueError |
|
|
|
|
20
|
|
|
from regex import regex |
|
|
|
|
21
|
|
|
from typeddfs.df_errors import FilenameSuffixError |
|
|
|
|
22
|
|
|
|
23
|
|
|
from mandos.model.apis.chembl_support.chembl_targets import TargetType |
24
|
|
|
from mandos.model.apis.pubchem_support.pubchem_models import ClinicalTrialsGovUtils |
25
|
|
|
from mandos.model.settings import SETTINGS, Globals |
26
|
|
|
from mandos.model.taxonomy import Taxonomy |
27
|
|
|
from mandos.model.taxonomy_caches import TaxonomyFactories |
28
|
|
|
from mandos.model.utils.setup import logger |
29
|
|
|
|
30
|
|
|
T = TypeVar("T", covariant=True) |
|
|
|
|
31
|
|
|
|
32
|
|
|
|
33
|
|
|
class _Args: |
34
|
|
|
@staticmethod |
35
|
|
|
def _arg(doc: str, *names, default: Optional[T] = None, req: bool = False, **kwargs): |
36
|
|
|
kwargs = dict( |
37
|
|
|
help=cleandoc(doc), |
38
|
|
|
**kwargs, |
39
|
|
|
allow_dash=True, |
40
|
|
|
) |
41
|
|
|
if req: |
|
|
|
|
42
|
|
|
return typer.Argument(default, **kwargs) |
43
|
|
|
else: |
44
|
|
|
return typer.Option(default, *names, **kwargs) |
45
|
|
|
|
46
|
|
|
@staticmethod |
47
|
|
|
def _path( |
48
|
|
|
doc: str, *names, default: Optional[str], f: bool, d: bool, out: bool, req: bool, **kwargs |
|
|
|
|
49
|
|
|
): |
50
|
|
|
# if it's None, we're going to have a special default set afterward, so we'll explain it in the doc |
|
|
|
|
51
|
|
|
if out and default is None: |
52
|
|
|
kwargs = dict(show_default=False, **kwargs) |
53
|
|
|
kwargs = { |
54
|
|
|
**dict( |
55
|
|
|
exists=not out, |
56
|
|
|
dir_okay=d, |
57
|
|
|
file_okay=f, |
58
|
|
|
readable=out, |
59
|
|
|
writable=not out, |
60
|
|
|
), |
61
|
|
|
**kwargs, |
62
|
|
|
} |
63
|
|
|
return _Args._arg(doc, *names, default=default, req=req, **kwargs) |
64
|
|
|
|
65
|
|
|
|
66
|
|
|
class Arg(_Args): |
|
|
|
|
67
|
|
|
@staticmethod |
68
|
|
|
def out_file(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
69
|
|
|
return _Args._path( |
70
|
|
|
doc, *names, default=default, f=True, d=False, out=True, req=True, **kwargs |
71
|
|
|
) |
72
|
|
|
|
73
|
|
|
@staticmethod |
74
|
|
|
def out_dir(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
75
|
|
|
return _Args._path( |
76
|
|
|
doc, *names, default=default, f=True, d=True, out=True, req=True, **kwargs |
77
|
|
|
) |
78
|
|
|
|
79
|
|
|
@staticmethod |
80
|
|
|
def out_path(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
81
|
|
|
return _Args._path( |
82
|
|
|
doc, *names, default=default, f=True, d=True, out=False, req=True, **kwargs |
83
|
|
|
) |
84
|
|
|
|
85
|
|
|
@staticmethod |
86
|
|
|
def in_file(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
87
|
|
|
return _Args._path( |
88
|
|
|
doc, *names, default=default, f=True, d=False, out=False, req=True, **kwargs |
89
|
|
|
) |
90
|
|
|
|
91
|
|
|
@staticmethod |
92
|
|
|
def in_dir(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
93
|
|
|
return _Args._path( |
94
|
|
|
doc, *names, default=default, f=False, d=True, out=False, req=True, **kwargs |
95
|
|
|
) |
96
|
|
|
|
97
|
|
|
@staticmethod |
98
|
|
|
def in_path(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
99
|
|
|
return _Args._path( |
100
|
|
|
doc, *names, default=default, f=True, d=True, out=False, req=True, **kwargs |
101
|
|
|
) |
102
|
|
|
|
103
|
|
|
@staticmethod |
104
|
|
|
def val(doc: str, *names, default: Optional[T] = None, **kwargs): |
|
|
|
|
105
|
|
|
return _Args._arg(doc, *names, default=default, req=True, **kwargs) |
106
|
|
|
|
107
|
|
|
|
108
|
|
|
class Opt(_Args): |
|
|
|
|
109
|
|
|
@staticmethod |
110
|
|
|
def out_file(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
111
|
|
|
return _Args._path( |
112
|
|
|
doc, *names, default=default, f=True, d=False, out=True, req=False, **kwargs |
113
|
|
|
) |
114
|
|
|
|
115
|
|
|
@staticmethod |
116
|
|
|
def out_dir(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
117
|
|
|
return _Args._path( |
118
|
|
|
doc, *names, default=default, f=True, d=True, out=True, req=False, **kwargs |
119
|
|
|
) |
120
|
|
|
|
121
|
|
|
@staticmethod |
122
|
|
|
def out_path(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
123
|
|
|
return _Args._path( |
124
|
|
|
doc, |
125
|
|
|
*names, |
126
|
|
|
default=default, |
127
|
|
|
f=True, |
128
|
|
|
d=True, |
129
|
|
|
out=False, |
130
|
|
|
req=False, |
131
|
|
|
exists=False, |
132
|
|
|
**kwargs, |
133
|
|
|
) |
134
|
|
|
|
135
|
|
|
@staticmethod |
136
|
|
|
def in_file(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
137
|
|
|
return _Args._path( |
138
|
|
|
doc, *names, default=default, f=True, d=False, out=False, req=False, **kwargs |
139
|
|
|
) |
140
|
|
|
|
141
|
|
|
@staticmethod |
142
|
|
|
def in_dir(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
143
|
|
|
return _Args._path( |
144
|
|
|
doc, *names, default=default, f=False, d=True, out=False, req=False, **kwargs |
145
|
|
|
) |
146
|
|
|
|
147
|
|
|
@staticmethod |
148
|
|
|
def in_path(doc: str, *names, default: Optional[str] = None, **kwargs): |
|
|
|
|
149
|
|
|
return _Args._path( |
150
|
|
|
doc, |
151
|
|
|
*names, |
152
|
|
|
default=default, |
153
|
|
|
f=True, |
154
|
|
|
d=True, |
155
|
|
|
out=False, |
156
|
|
|
req=False, |
157
|
|
|
exists=False, |
158
|
|
|
**kwargs, |
159
|
|
|
) |
160
|
|
|
|
161
|
|
|
@staticmethod |
162
|
|
|
def val(doc: str, *names, default: Optional[T] = None, **kwargs): |
|
|
|
|
163
|
|
|
return _Args._arg(doc, *names, default=default, req=False, **kwargs) |
164
|
|
|
|
165
|
|
|
@staticmethod |
166
|
|
|
def flag(doc: str, *names, **kwargs): |
|
|
|
|
167
|
|
|
return _Args._arg(doc, *names, default=False, req=False, **kwargs) |
168
|
|
|
|
169
|
|
|
|
170
|
|
|
class ArgUtils: |
|
|
|
|
171
|
|
|
@classmethod |
172
|
|
|
def definition_bullets(cls, dct: Mapping[Any, Any], colon: str = ": ", indent: int = 12) -> str: |
|
|
|
|
173
|
|
|
joiner = os.linesep * 2 + " " * indent |
174
|
|
|
jesus = [f" - {k}{colon}{v}" for k, v in dct.items()] |
175
|
|
|
return joiner.join(jesus) |
176
|
|
|
|
177
|
|
|
@classmethod |
178
|
|
|
def definition_list(cls, dct: Mapping[Any, Any], colon: str = ": ", sep: str = "; ") -> str: |
|
|
|
|
179
|
|
|
jesus = [f"{k}{colon}{v}" for k, v in dct.items()] |
180
|
|
|
return sep.join(jesus) |
181
|
|
|
|
182
|
|
|
@classmethod |
183
|
|
|
def list( |
|
|
|
|
184
|
|
|
cls, |
|
|
|
|
185
|
|
|
lst: Iterable[Any], |
|
|
|
|
186
|
|
|
*, |
|
|
|
|
187
|
|
|
attr: Union[None, str, Callable[[Any], Any]] = None, |
|
|
|
|
188
|
|
|
sep: str = ", ", |
|
|
|
|
189
|
|
|
) -> str: |
190
|
|
|
x = [] |
|
|
|
|
191
|
|
|
for v in lst: |
|
|
|
|
192
|
|
|
if attr is None and hasattr(v, "name"): |
193
|
|
|
x += [v.name] |
|
|
|
|
194
|
|
|
elif attr is None: |
195
|
|
|
x += [str(v)] |
|
|
|
|
196
|
|
|
elif isinstance(attr, str): |
197
|
|
|
x += [str(getattr(v, attr))] |
|
|
|
|
198
|
|
|
else: |
199
|
|
|
x += [str(attr(v))] |
|
|
|
|
200
|
|
|
return sep.join(x) |
201
|
|
|
|
202
|
|
|
@classmethod |
203
|
|
|
def parse_taxon(cls, taxon: Union[int, str], *, id_only: bool = False) -> Union[int, str]: |
|
|
|
|
204
|
|
|
if isinstance(taxon, str) and not id_only: |
|
|
|
|
205
|
|
|
return taxon |
206
|
|
|
elif isinstance(taxon, str) and taxon.isdigit(): |
207
|
|
|
return int(taxon) |
208
|
|
|
if id_only: |
209
|
|
|
raise XTypeError(f"Taxon {taxon} must be an ID") |
210
|
|
|
raise XTypeError(f"Taxon {taxon} must be an ID or name") |
211
|
|
|
|
212
|
|
|
@classmethod |
213
|
|
|
def parse_taxa(cls, taxa: Optional[str]) -> Sequence[Union[int, str]]: |
|
|
|
|
214
|
|
|
if taxa is None or taxa == "": |
215
|
|
|
return [] |
216
|
|
|
taxa = cls._get_std_taxon(taxa) |
217
|
|
|
taxa = [t.strip() for t in taxa.split(",") if len(t.strip()) > 0] |
218
|
|
|
return [ArgUtils.parse_taxon(t, id_only=False) for t in taxa] |
219
|
|
|
|
220
|
|
|
@classmethod |
221
|
|
|
def parse_taxa_ids(cls, taxa: str) -> Sequence[int]: |
|
|
|
|
222
|
|
|
if taxa is None or taxa == "": |
223
|
|
|
return [] |
224
|
|
|
taxa = cls._get_std_taxon(taxa) |
225
|
|
|
taxa = [t.strip() for t in taxa.split(",") if len(t.strip()) > 0] |
226
|
|
|
return [ArgUtils.parse_taxon(t, id_only=True) for t in taxa] |
227
|
|
|
|
228
|
|
|
@classmethod |
229
|
|
|
def _get_std_taxon(cls, taxa: str) -> str: |
230
|
|
|
x = dict( |
|
|
|
|
231
|
|
|
vertebrata=Globals.vertebrata, |
232
|
|
|
vertebrate=Globals.vertebrata, |
233
|
|
|
vertebrates=Globals.vertebrata, |
234
|
|
|
cellular=Globals.cellular_taxon, |
235
|
|
|
cell=Globals.cellular_taxon, |
236
|
|
|
cells=Globals.cellular_taxon, |
237
|
|
|
viral=Globals.viral_taxon, |
238
|
|
|
virus=Globals.viral_taxon, |
239
|
|
|
viruses=Globals.viral_taxon, |
240
|
|
|
all=f"{Globals.cellular_taxon},{Globals.viral_taxon}", |
241
|
|
|
).get(taxa) |
242
|
|
|
return taxa if x is None else str(x) |
243
|
|
|
|
244
|
|
|
@classmethod |
245
|
|
|
def get_taxonomy( |
|
|
|
|
246
|
|
|
cls, |
|
|
|
|
247
|
|
|
taxa: Optional[str], |
|
|
|
|
248
|
|
|
forbid: Optional[str], |
|
|
|
|
249
|
|
|
ancestors: Optional[str], |
|
|
|
|
250
|
|
|
*, |
|
|
|
|
251
|
|
|
local_only: bool = False, |
|
|
|
|
252
|
|
|
) -> Optional[Taxonomy]: |
253
|
|
|
if taxa is None or len(taxa) == 0: |
254
|
|
|
return None |
255
|
|
|
return TaxonomyFactories.get_smart_taxonomy( |
256
|
|
|
allow=cls.parse_taxa(taxa), |
257
|
|
|
forbid=cls.parse_taxa(forbid), |
258
|
|
|
ancestors=cls.parse_taxa_ids(ancestors), |
259
|
|
|
local_only=local_only, |
260
|
|
|
) |
261
|
|
|
|
262
|
|
|
@staticmethod |
263
|
|
|
def get_trial_statuses(st: str) -> Set[str]: |
|
|
|
|
264
|
|
|
return ClinicalTrialsGovUtils.resolve_statuses(st) |
265
|
|
|
|
266
|
|
|
@staticmethod |
267
|
|
|
def get_target_types(st: str) -> Set[str]: |
|
|
|
|
268
|
|
|
return {s.name for s in TargetType.resolve(st)} |
269
|
|
|
|
270
|
|
|
|
271
|
|
|
class EntryUtils: |
|
|
|
|
272
|
|
|
@classmethod |
273
|
|
|
def adjust_filename( |
|
|
|
|
274
|
|
|
cls, |
|
|
|
|
275
|
|
|
to: Optional[Path], |
|
|
|
|
276
|
|
|
default: Union[str, Path], |
|
|
|
|
277
|
|
|
replace: bool, |
|
|
|
|
278
|
|
|
*, |
|
|
|
|
279
|
|
|
suffixes: Union[None, AbstractSet[str], Callable[[Union[Path, str]], Any]] = None, |
|
|
|
|
280
|
|
|
) -> Path: |
281
|
|
|
if to is None: |
282
|
|
|
path = Path(default) |
283
|
|
|
elif str(to).startswith("."): |
284
|
|
|
path = Path(default).with_suffix(str(to)) |
285
|
|
|
elif str(to).startswith("*."): |
286
|
|
|
path = Path(default).with_suffix(str(to)[1:]) |
287
|
|
|
elif to.is_dir() or to.suffix == "": |
288
|
|
|
path = to / default |
289
|
|
|
else: |
290
|
|
|
path = Path(to) |
291
|
|
|
if ( |
292
|
|
|
path.exists() |
|
|
|
|
293
|
|
|
and not path.is_file() |
|
|
|
|
294
|
|
|
and not path.is_socket() |
|
|
|
|
295
|
|
|
and not path.is_char_device() |
|
|
|
|
296
|
|
|
): |
297
|
|
|
raise PathExistsError(f"Path {path} exists and is not a file") |
298
|
|
|
if path.exists() and not replace: |
299
|
|
|
raise PathExistsError(f"File {path} already exists") |
300
|
|
|
cls._check_suffix(path.suffix, suffixes) |
301
|
|
|
if path.exists() and replace: |
302
|
|
|
logger.info(f"Overwriting existing file {path}.") |
303
|
|
|
return path |
304
|
|
|
|
305
|
|
|
@classmethod |
306
|
|
|
def adjust_dir_name( |
|
|
|
|
307
|
|
|
cls, |
|
|
|
|
308
|
|
|
to: Optional[Path], |
|
|
|
|
309
|
|
|
default: Union[str, Path], |
|
|
|
|
310
|
|
|
*, |
|
|
|
|
311
|
|
|
suffixes: Union[None, AbstractSet[str], Callable[[Union[Path, str]], Any]] = None, |
|
|
|
|
312
|
|
|
) -> Tuple[Path, str]: |
313
|
|
|
out_dir = Path(default) |
314
|
|
|
suffix = SETTINGS.table_suffix |
315
|
|
|
if to is not None: |
316
|
|
|
pat = regex.compile(r"([^\*]*)(?:\*(\..+))", flags=regex.V1) |
317
|
|
|
m: regex.Match = pat.fullmatch(to) |
|
|
|
|
318
|
|
|
out_dir = default if m.group(1) == "" else m.group(1) |
319
|
|
|
suffix = SETTINGS.table_suffix if m.group(2) == "" else m.group(2) |
320
|
|
|
if out_dir.startswith("."): |
321
|
|
|
logger.warning(f"Writing to {out_dir} - was it meant as a suffix instead?") |
322
|
|
|
out_dir = Path(out_dir) |
323
|
|
|
if out_dir.exists() and not out_dir.is_dir(): |
324
|
|
|
raise PathExistsError(f"Path {out_dir} already exists but and is not a directory") |
325
|
|
|
cls._check_suffix(suffix, suffixes) |
326
|
|
|
if out_dir.exists(): |
327
|
|
|
n_files = len(list(out_dir.iterdir())) |
328
|
|
|
if n_files > 0: |
329
|
|
|
logger.debug(f"Directory {out_dir} is non-emtpy") |
330
|
|
|
return out_dir, suffix |
331
|
|
|
|
332
|
|
|
@classmethod |
333
|
|
|
def _check_suffix(cls, suffix, suffixes): |
334
|
|
|
if suffixes is not None and callable(suffixes): |
335
|
|
|
try: |
336
|
|
|
suffixes(suffix) # make sure it's ok |
337
|
|
|
except FilenameSuffixError: |
338
|
|
|
raise XValueError(f"Unsupported file format {suffix}") |
339
|
|
|
elif suffixes is not None: |
340
|
|
|
if suffix not in suffixes: |
341
|
|
|
raise XValueError(f"Unsupported file format {suffix}") |
342
|
|
|
|
343
|
|
|
|
344
|
|
|
__all__ = ["Arg", "Opt", "ArgUtils", "EntryUtils"] |
345
|
|
|
|