Passed
Push — main ( 9ff912...d08a4e )
by Douglas
03:54
created

mandos.search.entries._EntryChemblGo.run()   B

Complexity

Conditions 4

Size

Total Lines 52
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 38
nop 12
dl 0
loc 52
rs 8.968
c 0
b 0
f 0

How to fix   Long Method    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
"""
2
Run searches and write files.
3
"""
4
5
from __future__ import annotations
6
7
import abc
8
import logging
9
from inspect import cleandoc as doc
10
from pathlib import Path
11
from typing import Optional, TypeVar, Generic, Union, Mapping, Set, Sequence, Type
0 ignored issues
show
Unused Code introduced by
Unused Optional imported from typing
Loading history...
12
13
import typer
0 ignored issues
show
introduced by
Unable to import 'typer'
Loading history...
14
15
from mandos.model import ReflectionUtils, InjectionError, MandosResources
0 ignored issues
show
Unused Code introduced by
Unused MandosResources imported from mandos.model
Loading history...
16
from mandos.model.chembl_api import ChemblApi
17
from mandos.model.chembl_support import DataValidityComment
18
from mandos.model.chembl_support.chembl_targets import TargetType, ConfidenceLevel
19
from mandos.model.pubchem_support.pubchem_models import ClinicalTrialsGovUtils, CoOccurrenceType
20
from mandos.model.searches import Search
21
from mandos.model.settings import MANDOS_SETTINGS
22
from mandos.model.taxonomy import Taxonomy
23
from mandos.model.taxonomy_caches import TaxonomyFactories
24
from mandos.search.api_singletons import Apis
25
from mandos.search.chembl.target_traversal import TargetTraversalStrategies
26
from mandos.search.pubchem.dgidb_search import DgiSearch, CgiSearch
27
from mandos.search.searcher import Searcher
28
29
Chembl, Pubchem = Apis.Chembl, Apis.Pubchem
30
from mandos.search.chembl.binding_search import BindingSearch
0 ignored issues
show
introduced by
Import "from mandos.search.chembl.binding_search import BindingSearch" should be placed at the top of the module
Loading history...
31
from mandos.search.chembl.atc_search import AtcSearch
0 ignored issues
show
introduced by
Import "from mandos.search.chembl.atc_search import AtcSearch" should be placed at the top of the module
Loading history...
32
from mandos.search.chembl.go_search import GoType, GoSearch
0 ignored issues
show
introduced by
Import "from mandos.search.chembl.go_search import GoType, GoSearch" should be placed at the top of the module
Loading history...
33
from mandos.search.chembl.indication_search import IndicationSearch
0 ignored issues
show
introduced by
Import "from mandos.search.chembl.indication_search import IndicationSearch" should be placed at the top of the module
Loading history...
34
from mandos.search.chembl.mechanism_search import MechanismSearch
0 ignored issues
show
introduced by
Import "from mandos.search.chembl.mechanism_search import MechanismSearch" should be placed at the top of the module
Loading history...
35
from mandos.search.pubchem.cooccurrence_search import (
0 ignored issues
show
introduced by
Import "from mandos.search.pubchem.cooccurrence_search import GeneCoOccurrenceSearch, ChemicalCoOccurrenceSearch, CoOccurrenceSearch" should be placed at the top of the module
Loading history...
36
    GeneCoOccurrenceSearch,
37
    ChemicalCoOccurrenceSearch,
38
    CoOccurrenceSearch,
39
)
40
from mandos.search.pubchem.disease_search import DiseaseSearch
0 ignored issues
show
introduced by
Import "from mandos.search.pubchem.disease_search import DiseaseSearch" should be placed at the top of the module
Loading history...
41
42
logger = logging.getLogger(__package__)
43
44
S = TypeVar("S", bound=Search, covariant=True)
0 ignored issues
show
Coding Style Naming introduced by
Class name "S" doesn't conform to PascalCase naming style ('[^\\W\\da-z][^\\W_]+$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
45
46
47
class Utils:
0 ignored issues
show
Documentation introduced by
Empty class docstring
Loading history...
48
    """"""
49
50
    @staticmethod
51
    def split(st: str) -> Set[str]:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
Coding Style Naming introduced by
Argument name "st" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
52
        return {s.strip() for s in st.split(",")}
53
54
    @staticmethod
55
    def get_taxa(taxa: str) -> Sequence[Taxonomy]:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
56
        return [
57
            TaxonomyFactories.from_uniprot(MANDOS_SETTINGS.taxonomy_cache_path).load(int(taxon))
58
            for taxon in taxa.split(",")
59
        ]
60
61
    @staticmethod
62
    def get_trial_statuses(st: str) -> Set[str]:
0 ignored issues
show
Coding Style Naming introduced by
Argument name "st" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
introduced by
Missing function or method docstring
Loading history...
63
        return ClinicalTrialsGovUtils.resolve_statuses(st)
64
65
    @staticmethod
66
    def get_target_types(st: str) -> Set[str]:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
Coding Style Naming introduced by
Argument name "st" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
67
        return {s.name for s in TargetType.resolve(st)}
68
69
    @staticmethod
70
    def get_flags(st: str) -> Set[str]:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
Coding Style Naming introduced by
Argument name "st" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
71
        return {s.name for s in DataValidityComment.resolve(st)}
72
73
74
class _Typer:
75
76
    path = typer.Argument(
77
        None,
78
        exists=True,
79
        file_okay=True,
80
        dir_okay=False,
81
        help=doc(
82
            """
83
            The path to the input file.
84
            One of:
85
86
              (A) *.txt or *.lines with one InChI Key per line;
87
88
              (B) A *.csv, *.tsv, *.tab file (or .gzip variant) with a column called 'inchikey'; OR
89
90
              (C) An Apache Arrow *.feather file with a column called 'inchikey'
91
        """
92
        ),
93
    )
94
95
    @staticmethod
96
    def key(name: str) -> typer.Option:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
97
        return typer.Option(
98
            name,
99
            min=1,
100
            max=120,
101
            help="""
102
            A free-text unique key for the search.
103
            Should be a short, <60-character name that describes the search and any parameters.
104
            The output file will be named according to a 'sanitized' variant of this value.
105
            """,
106
        )
107
108
    taxa = typer.Option(
109
        "7742",
110
        show_default=False,
111
        help=doc(
112
            """
113
        The IDs or names of UniProt taxa, comma-separated.
114
        Taxon names and common names can be used for vertebrate species (where available).
115
116
        This can have a significant effect on the search. See the docs fore more info.
117
118
        [default: 7742] (Euteleostomi)
119
        """
120
        ),
121
    )
122
123
    traversal_strategy = typer.Option(
124
        "@null",
125
        show_default=False,
126
        help=doc(
127
            """
128
        Target traversal strategy name, file, or class.
129
        Dictates the way the network of ChEMBL targets is traversed (from the annotated target as a source).
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (108/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
130
        Specifies the network links that are followed and which targets are 'accepted' for final annotations.
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (109/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
131
        This option has a dramatic effect on the search. See the docs for more info.
132
133
        Can be one of:
134
        (A) A standard strategy name, starting with @;
135
        (B) The path to a ``*.strat`` file; OR
136
        (C) The fully qualified name of a ``TargetTraversal``
137
138
        The standard traversal strategies are: {}
139
140
        [default: @null] (No traversal; targets as-is)
141
        """.format(
142
                "; ".join(TargetTraversalStrategies.standard_strategies())
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation (remove 4 spaces).
Loading history...
143
            )
144
        ),
145
    )
146
147
    target_types = typer.Option(
148
        "@molecular",
149
        show_default=False,
150
        help=doc(
151
            """
152
        The accepted target types, comma-separated.
153
154
        NOTE: This affects only the types are are accepted after traversal,
155
        and the types must be included in the traversal.
156
        This means that this must be AT LEAST as restrictive as the traversal strategy.
157
158
        The ChEMBL-defined types are:
159
160
          {}
161
162
        These special names are also accepted:
163
164
          - {}
165
166
        [default: @molecular]
167
        """.format(
168
                "; ".join([s.name for s in TargetType.all_types()]),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation (remove 4 spaces).
Loading history...
169
                "\n\n          - ".join(
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation (remove 4 spaces).
Loading history...
170
                    [f"{k} ({v})" for k, v in TargetType.special_type_names().items()]
171
                ),
172
            )
173
        ),
174
    )
175
176
    min_confidence = typer.Option(
177
        3,
178
        min=0,
179
        max=9,
180
        show_default=False,
181
        help=doc(
182
            """
183
        Minimum target confidence score, inclusive.
184
        This is useful to modify in only some cases. More important options are min_pchembl and taxa.
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (101/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
185
186
        Values are: {}
187
188
        [default: 3]
189
        """.format(
190
                "; ".join([f"{s.value} ({s.name})" for s in ConfidenceLevel])
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation (remove 4 spaces).
Loading history...
191
            )
192
        ),
193
    )
194
195
    relations = typer.Option(
196
        "<,<=,=",
197
        show_default=False,
198
        help=doc(
199
            """
200
        Assay activity relations allowed, comma-separated.
201
        If post-processing yourself, consider including all.
202
        Values are: <, <=, =, >, >=, ~.
203
        [default: <,<=,=]
204
        """
205
        ),
206
    )
207
208
    min_pchembl = typer.Option(
209
        6.0,
210
        min=0.0,
211
        show_default=False,
212
        help=doc(
213
            """
214
        Minimum pCHEMBL value, inclusive.
215
        If post-processing yourself, consider setting to 0.0.
216
        [default: 6.0]
217
        """
218
        ),
219
    )
220
221
    banned_flags = typer.Option(
222
        "@negative",
223
        show_default=False,
224
        help=doc(
225
            """
226
        Exclude activity annotations with data validity flags, comma-separated.
227
        It is rare to need to change this.
228
229
        Values are: {}.
230
231
        Special sets are:
232
233
          - @all (all flags are banned)
234
235
          - @negative ({})
236
237
          - @positive ({})
238
239
        [default: @negative]
240
        """.format(
241
                "; ".join([s.name for s in DataValidityComment]),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation (remove 4 spaces).
Loading history...
242
                ", ".join([s.name for s in DataValidityComment.negative_comments()]),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation (remove 4 spaces).
Loading history...
243
                ", ".join([s.name for s in DataValidityComment.positive_comments()]),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation (remove 4 spaces).
Loading history...
244
            ),
245
        ),
246
    )
247
248
    test = typer.Option(False, help="Do not run searches; just check that the parameters are ok.")
249
250
    chembl_trial = typer.Option(
251
        3,
252
        show_default=False,
253
        help=doc(
254
            """
255
        Minimum phase of a clinical trial, inclusive.
256
        Values are: 0, 1, 2, 3.
257
        [default: 3]
258
        """
259
        ),
260
        min=0,
261
        max=3,
262
    )
263
264
265
class Entry(Generic[S], metaclass=abc.ABCMeta):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
266
    @classmethod
267
    def cmd(cls) -> str:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
268
        key = cls._get_default_key()
269
        if isinstance(key, typer.models.OptionInfo):
270
            key = key.default
271
        if key is None or not isinstance(key, str):
272
            raise AssertionError(f"Key for {cls.__name__} is {key}")
273
        return key
274
275
    @classmethod
276
    def run(cls, path: Path, **params) -> None:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
277
        raise NotImplementedError()
278
279
    @classmethod
280
    def get_search_type(cls) -> Type[S]:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
281
        # noinspection PyTypeChecker
282
        return ReflectionUtils.get_generic_arg(cls, Search)
283
284
    @classmethod
285
    def test(cls, path: Path, **params) -> None:
0 ignored issues
show
Unused Code introduced by
The argument path seems to be unused.
Loading history...
introduced by
Missing function or method docstring
Loading history...
286
        params = dict(params)
287
        params["test"] = True
288
        cls.run(**params)
289
290
    @classmethod
291
    def _run(cls, built: S, path: Path, test: bool):
292
        searcher = Searcher([built], path)
293
        if not test:
294
            searcher.search()
295
        return searcher
296
297
    # @classmethod
298
    # def build(cls, path: Path, **params: Mapping[str, Union[int, float, str]]) -> Search:
299
    #    raise NotImplementedError()
300
301
    @classmethod
302
    def default_param_values(cls) -> Mapping[str, Union[str, float, int]]:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
303
        return {
304
            param: value
305
            for param, value in ReflectionUtils.default_arg_values(cls.run).items()
306
            if param not in {"key", "path"}
307
        }
308
309
    @classmethod
310
    def _get_default_key(cls) -> str:
311
        vals = ReflectionUtils.default_arg_values(cls.run)
312
        try:
313
            return vals["key"]
314
        except KeyError:
315
            logger.error(f"key not in {vals.keys()} for {cls.__name__}")
0 ignored issues
show
introduced by
Use lazy % formatting in logging functions
Loading history...
316
            raise
317
318
319
class EntryChemblBinding(Entry[BindingSearch]):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
introduced by
Value 'Entry' is unsubscriptable
Loading history...
320
    @classmethod
321
    def run(
0 ignored issues
show
best-practice introduced by
Too many arguments (11/5)
Loading history...
322
        cls,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
323
        path=_Typer.path,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
324
        key=_Typer.key("chembl:binding"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
325
        taxa=_Typer.taxa,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
326
        traversal=_Typer.traversal_strategy,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
327
        target_types=_Typer.target_types,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
328
        confidence=_Typer.min_confidence,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
329
        relations=_Typer.relations,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
330
        min_pchembl=_Typer.min_pchembl,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
331
        banned_flags=_Typer.banned_flags,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
332
        test=_Typer.test,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
333
    ) -> Searcher:
334
        """
335
        Fetch binding data from ChEMBL.
336
        These are 'activity' annotations of the type 'B' that have a pCHEMBL value.
337
        There is extended documentation on this search; see:
338
339
        https://mandos-chem.readthedocs.io/en/latest/binding.html
340
        """
341
        built = BindingSearch(
342
            key=key,
343
            api=Chembl,
344
            taxa=Utils.get_taxa(taxa),
345
            traversal_strategy=traversal,
346
            allowed_target_types=Utils.get_target_types(target_types),
347
            min_confidence_score=confidence,
348
            allowed_relations=Utils.split(relations),
349
            min_pchembl=min_pchembl,
350
            banned_flags=Utils.get_flags(banned_flags),
351
        )
352
        return cls._run(built, path, test)
353
354
355
class EntryChemblMechanism(Entry[MechanismSearch]):
0 ignored issues
show
introduced by
Value 'Entry' is unsubscriptable
Loading history...
introduced by
Missing class docstring
Loading history...
356
    @classmethod
357
    def run(
0 ignored issues
show
best-practice introduced by
Too many arguments (8/5)
Loading history...
358
        cls,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
359
        path=_Typer.path,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
360
        key=_Typer.key("chembl:mechanism"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
361
        taxa=_Typer.taxa,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
362
        traversal=_Typer.traversal_strategy,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
363
        target_types=_Typer.target_types,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
364
        min_confidence=_Typer.min_confidence,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
365
        test=_Typer.test,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
366
    ) -> Searcher:
367
        """
368
        Fetch mechanism of action (MoA) data from ChEMBL.
369
        """
370
        built = MechanismSearch(
371
            key=key,
372
            api=Chembl,
373
            taxa=Utils.get_taxa(taxa),
374
            traversal_strategy=traversal,
375
            allowed_target_types=Utils.get_target_types(target_types),
376
            min_confidence_score=min_confidence,
377
        )
378
        return cls._run(built, path, test)
379
380
381
class EntryChemblTrials(Entry[IndicationSearch]):
0 ignored issues
show
introduced by
Value 'Entry' is unsubscriptable
Loading history...
introduced by
Missing class docstring
Loading history...
382
    @classmethod
383
    def run(
384
        cls,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
385
        path=_Typer.path,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
386
        key=_Typer.key("chembl.trials"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
387
        min_phase=_Typer.chembl_trial,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
388
        test=_Typer.test,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
389
    ) -> Searcher:
390
        """
391
        Fetch clinical trials recorded in ChEMBL.
392
        """
393
        built = IndicationSearch(key=key, api=Chembl, min_phase=min_phase)
394
        return cls._run(built, path, test)
395
396
397
class EntryChemblAtc(Entry[AtcSearch]):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
introduced by
Value 'Entry' is unsubscriptable
Loading history...
398
    @classmethod
399
    def run(
400
        cls,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
401
        path=_Typer.path,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
402
        key=_Typer.key("chembl.atc"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
403
        levels=typer.Option(
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
404
            "1,2,3,4,5", min=1, max=5, help="""List of ATC levels, comma-separated."""
405
        ),
406
        test=_Typer.test,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
407
    ) -> Searcher:
408
        """
409
        Fetch ATC codes from ChEMBL.
410
        """
411
        built = AtcSearch(key=key, api=Chembl, levels={int(x.strip()) for x in levels.split(",")})
412
        return cls._run(built, path, test)
413
414
415
class _EntryChemblGo(Entry[GoSearch], metaclass=abc.ABCMeta):
416
    @classmethod
417
    def go_type(cls) -> GoType:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
418
        raise NotImplementedError()
419
420
    @classmethod
421
    def cmd(cls) -> str:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
422
        return f"chembl:go.{cls.go_type().name.lower()}"
423
424
    @classmethod
425
    def run(
0 ignored issues
show
best-practice introduced by
Too many arguments (12/5)
Loading history...
426
        cls,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
427
        path=_Typer.path,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
428
        key=_Typer.key("<see above>"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
429
        taxa=_Typer.taxa,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
430
        traversal_strategy=_Typer.traversal_strategy,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
431
        target_types=_Typer.target_types,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
432
        confidence=_Typer.min_confidence,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
433
        relations=_Typer.relations,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
434
        min_pchembl=_Typer.min_pchembl,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
435
        banned_flags=_Typer.banned_flags,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
436
        binding_search=typer.Option(
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
437
            None,
438
            help="""
439
            The fully qualified name of a class inheriting ``BindingSearch``.
440
            If specified, all parameters above are passed to its constructor.
441
            """,
442
        ),
443
        test=_Typer.test,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
444
    ) -> Searcher:
445
        """
446
        Process data.
447
448
        Note:
449
450
            By default, the key is the "chembl:go.function", "chembl:go.process", or "chembl:go.component".
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (107/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
451
        """
452
        if key is None:
453
            key = cls.cmd()
454
        api = ChemblApi.wrap(Chembl)
455
        if binding_search is None:
456
            binding_clazz = BindingSearch
457
        else:
458
            binding_clazz = ReflectionUtils.injection(binding_search, BindingSearch)
459
            logger.info(f"NOTICE: Passing parameters to {binding_clazz.__qualname__}")
0 ignored issues
show
introduced by
Use lazy % formatting in logging functions
Loading history...
460
        try:
461
            binding_search = binding_clazz(
462
                key=key,
463
                api=Chembl,
464
                taxa=Utils.get_taxa(taxa),
465
                traversal_strategy=traversal_strategy,
466
                allowed_target_types=Utils.get_target_types(target_types),
467
                min_confidence_score=confidence,
468
                allowed_relations=Utils.split(relations),
469
                min_pchembl=min_pchembl,
470
                banned_flags=Utils.get_flags(banned_flags),
471
            )
472
        except (TypeError, ValueError):
473
            raise InjectionError(f"Failed to build {binding_clazz.__qualname__}")
474
        built = GoSearch(key, api, cls.go_type(), binding_search)
475
        return cls._run(built, path, test)
476
477
478
class EntryGoFunction(_EntryChemblGo):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
479
    @classmethod
480
    def go_type(cls) -> GoType:
481
        return GoType.function
482
483
484
class EntryGoProcess(_EntryChemblGo):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
485
    @classmethod
486
    def go_type(cls) -> GoType:
487
        return GoType.process
488
489
490
class EntryGoComponent(_EntryChemblGo):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
491
    @classmethod
492
    def go_type(cls) -> GoType:
493
        return GoType.component
494
495
496
class EntryPubchemDisease(Entry[DiseaseSearch]):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
introduced by
Value 'Entry' is unsubscriptable
Loading history...
497
    @classmethod
498
    def run(
0 ignored issues
show
best-practice introduced by
Too many arguments (6/5)
Loading history...
499
        cls,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
500
        path=_Typer.path,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
501
        key=_Typer.key("disease.ctd:mesh"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
502
        therapeutic=typer.Option(True, help="Include annotations of type 'therapeutic'"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
503
        marker=typer.Option(True, help="Include annotations of type 'marker/mechanism'"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
504
        test=_Typer.test,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
505
    ) -> Searcher:
506
        """
507
        Fetch MeSH codes of diseases and disorders in the Comparative Toxicogenomics Database (CTD).
508
        """
509
        built = DiseaseSearch(key, Pubchem, therapeutic=therapeutic, marker=marker)
510
        return cls._run(built, path, test)
511
512
513
class EntryPubchemDgi(Entry[DgiSearch]):
0 ignored issues
show
introduced by
Value 'Entry' is unsubscriptable
Loading history...
introduced by
Missing class docstring
Loading history...
514
    @classmethod
515
    def run(
516
        cls,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
517
        path=_Typer.path,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
518
        key=_Typer.key("disease.dgidb:dgis"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
519
        test=_Typer.test,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
520
    ) -> Searcher:
521
        """
522
        Fetch DRUG/gene interactions in the Drug Gene Interaction Database (DGIDB).
523
        Also see ``disease.dgidb:cgis``.
524
        """
525
        built = DgiSearch(key, Pubchem)
526
        return cls._run(built, path, test)
527
528
529
class EntryPubchemCgi(Entry[CgiSearch]):
0 ignored issues
show
introduced by
Value 'Entry' is unsubscriptable
Loading history...
introduced by
Missing class docstring
Loading history...
530
    @classmethod
531
    def run(
532
        cls,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
533
        path=_Typer.path,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
534
        key=_Typer.key("disease.dgidb:cgis"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
535
        test=_Typer.test,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
536
    ) -> Searcher:
537
        """
538
        Fetch COMPOUND/gene interactions in the Drug Gene Interaction Database (DGIDB).
539
        Also see ``disease.dgidb:dgis``.
540
        """
541
        built = CgiSearch(key, Pubchem)
542
        return cls._run(built, path, test)
543
544
545
U = TypeVar("U", covariant=True, bound=CoOccurrenceSearch)
0 ignored issues
show
Coding Style Naming introduced by
Class name "U" doesn't conform to PascalCase naming style ('[^\\W\\da-z][^\\W_]+$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
546
547
548
class _EntryPubchemCoOccurrence(Entry[U], metaclass=abc.ABCMeta):
549
    @classmethod
550
    def cmd(cls) -> str:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
551
        return f"lit.pubchem:{cls.get_cooccurrence_type().name.lower()}"
552
553
    @classmethod
554
    def get_cooccurrence_type(cls) -> CoOccurrenceType:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
555
        s: CoOccurrenceSearch = cls.get_search_type()
0 ignored issues
show
Coding Style Naming introduced by
Variable name "s" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
556
        return s.cooccurrence_type()
557
558
    @classmethod
559
    def run(
0 ignored issues
show
best-practice introduced by
Too many arguments (6/5)
Loading history...
560
        cls,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
561
        path=_Typer.path,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
562
        key=_Typer.key("<see above>"),
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
563
        min_score=typer.Option(
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
564
            0.0,
565
            help="Minimum enrichment score, inclusive. See docs for more info.",
566
            min=0.0,
567
        ),
568
        min_articles=typer.Option(
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
569
            0,
570
            help="Minimum number of articles for both the compound and object, inclusive.",
571
            min=0,
572
        ),
573
        test=_Typer.test,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
574
    ) -> Searcher:
575
        """
576
        Fetch co-occurrences from PubMed articles.
577
        There is extended documentation on this search.
578
        Also refer to https://pubchemdocs.ncbi.nlm.nih.gov/knowledge-panels
579
        """
580
        if key is None:
581
            key = cls.cmd()
582
        clazz = cls.get_search_type()
583
        built = clazz(key, Pubchem, min_score=min_score, min_articles=min_articles)
584
        return cls._run(built, path, test)
585
586
587
class EntryPubchemGeneCoOccurrence(_EntryPubchemCoOccurrence[GeneCoOccurrenceSearch]):
0 ignored issues
show
Documentation introduced by
Empty class docstring
Loading history...
588
    """"""
589
590
591
class EntryPubchemDiseaseCoOccurrence(_EntryPubchemCoOccurrence[GeneCoOccurrenceSearch]):
0 ignored issues
show
Documentation introduced by
Empty class docstring
Loading history...
592
    """"""
593
594
595
class EntryPubchemChemicalCoOccurrence(_EntryPubchemCoOccurrence[ChemicalCoOccurrenceSearch]):
0 ignored issues
show
Documentation introduced by
Empty class docstring
Loading history...
596
    """"""
597
598
599
Entries = [
600
    EntryChemblBinding,
601
    EntryChemblMechanism,
602
    EntryChemblAtc,
603
    EntryChemblTrials,
604
    EntryGoFunction,
605
    EntryGoProcess,
606
    EntryGoComponent,
607
    EntryPubchemDisease,
608
    EntryPubchemGeneCoOccurrence,
609
    EntryPubchemDiseaseCoOccurrence,
610
    EntryPubchemChemicalCoOccurrence,
611
]
612