1
|
|
|
""" |
2
|
|
|
Model of ChEMBL targets and a hierarchy between them as a directed acyclic graph (DAG). |
3
|
|
|
""" |
4
|
|
|
from __future__ import annotations |
5
|
|
|
|
6
|
|
|
import abc |
7
|
|
|
import enum |
8
|
|
|
import logging |
9
|
|
|
import re |
10
|
|
|
from dataclasses import dataclass |
11
|
|
|
from typing import Optional, Sequence, Set |
12
|
|
|
from typing import Tuple as Tup |
13
|
|
|
|
14
|
|
|
from urllib3.util.retry import MaxRetryError |
|
|
|
|
15
|
|
|
from pocketutils.core.dot_dict import NestedDotDict |
|
|
|
|
16
|
|
|
|
17
|
|
|
from mandos.model.chembl_api import ChemblApi |
18
|
|
|
|
19
|
|
|
logger = logging.getLogger(__package__) |
20
|
|
|
|
21
|
|
|
|
22
|
|
|
class TargetNotFoundError(ValueError): |
|
|
|
|
23
|
|
|
"""""" |
24
|
|
|
|
25
|
|
|
|
26
|
|
|
class TargetType(enum.Enum): |
27
|
|
|
""" |
28
|
|
|
Enum corresponding to the ChEMBL API field ``target.target_type``. |
29
|
|
|
""" |
30
|
|
|
|
31
|
|
|
single_protein = enum.auto() |
32
|
|
|
protein_family = enum.auto() |
33
|
|
|
protein_complex = enum.auto() |
34
|
|
|
protein_complex_group = enum.auto() |
35
|
|
|
selectivity_group = enum.auto() |
36
|
|
|
protein_protein_interaction = enum.auto() |
37
|
|
|
nucleic_acid = enum.auto() |
38
|
|
|
chimeric_protein = enum.auto() |
39
|
|
|
protein_nucleic_acid_complex = enum.auto() |
40
|
|
|
metal = enum.auto() |
41
|
|
|
small_molecule = enum.auto() |
42
|
|
|
subcellular = enum.auto() |
43
|
|
|
unknown = enum.auto() |
44
|
|
|
|
45
|
|
|
@classmethod |
46
|
|
|
def of(cls, s: str) -> TargetType: |
|
|
|
|
47
|
|
|
key = s.replace(" ", "_").replace("-", "_").lower() |
48
|
|
|
try: |
49
|
|
|
return TargetType[key] |
50
|
|
|
except KeyError: |
51
|
|
|
logger.error(f"Target type {key} not found. Using TargetType.unknown.") |
|
|
|
|
52
|
|
|
return TargetType.unknown |
53
|
|
|
|
54
|
|
|
@classmethod |
55
|
|
|
def protein_types(cls) -> Set[TargetType]: |
|
|
|
|
56
|
|
|
return {s for s in cls if s.is_protein} |
57
|
|
|
|
58
|
|
|
@classmethod |
59
|
|
|
def all_types(cls) -> Set[TargetType]: |
|
|
|
|
60
|
|
|
return set(TargetType) # here for symmetry |
61
|
|
|
|
62
|
|
|
@property |
63
|
|
|
def is_traversable(self) -> bool: |
|
|
|
|
64
|
|
|
return self in { |
65
|
|
|
TargetType.single_protein, |
66
|
|
|
TargetType.protein_family, |
67
|
|
|
TargetType.protein_complex, |
68
|
|
|
TargetType.protein_complex_group, |
69
|
|
|
TargetType.selectivity_group, |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
@property |
73
|
|
|
def is_protein(self) -> bool: |
|
|
|
|
74
|
|
|
return self in { |
75
|
|
|
TargetType.single_protein, |
76
|
|
|
TargetType.protein_family, |
77
|
|
|
TargetType.protein_complex, |
78
|
|
|
TargetType.protein_complex_group, |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
@property |
82
|
|
|
def is_unknown(self) -> bool: |
|
|
|
|
83
|
|
|
return self == TargetType.unknown |
84
|
|
|
|
85
|
|
|
|
86
|
|
|
class TargetRelationshipType(enum.Enum): |
|
|
|
|
87
|
|
|
subset_of = enum.auto() |
88
|
|
|
superset_of = enum.auto() |
89
|
|
|
overlaps_with = enum.auto() |
90
|
|
|
equivalent_to = enum.auto() |
91
|
|
|
|
92
|
|
|
@classmethod |
93
|
|
|
def of(cls, s: str) -> TargetRelationshipType: |
|
|
|
|
94
|
|
|
return TargetRelationshipType[s.replace(" ", "_").replace("-", "_").lower()] |
95
|
|
|
|
96
|
|
|
|
97
|
|
|
@dataclass(frozen=True, order=True, repr=True) |
|
|
|
|
98
|
|
|
class DagTargetLinkType: |
99
|
|
|
source_type: TargetType |
100
|
|
|
rel_type: TargetRelationshipType |
101
|
|
|
dest_type: TargetType |
102
|
|
|
words: Optional[Set[str]] |
103
|
|
|
|
104
|
|
|
@classmethod |
105
|
|
|
def cross( |
|
|
|
|
106
|
|
|
cls, |
|
|
|
|
107
|
|
|
source_types: Set[TargetType], |
|
|
|
|
108
|
|
|
rel_types: Set[TargetRelationshipType], |
|
|
|
|
109
|
|
|
dest_types: Set[TargetType], |
|
|
|
|
110
|
|
|
) -> Set[DagTargetLinkType]: |
111
|
|
|
st = set() |
|
|
|
|
112
|
|
|
for source in source_types: |
113
|
|
|
for rel in rel_types: |
114
|
|
|
for dest in dest_types: |
115
|
|
|
st.add(DagTargetLinkType(source, rel, dest, None)) |
116
|
|
|
return st |
117
|
|
|
|
118
|
|
|
def matches( |
|
|
|
|
119
|
|
|
self, |
|
|
|
|
120
|
|
|
source: TargetType, |
|
|
|
|
121
|
|
|
rel: TargetRelationshipType, |
|
|
|
|
122
|
|
|
target: TargetType, |
|
|
|
|
123
|
|
|
target_name: Optional[str], |
|
|
|
|
124
|
|
|
) -> bool: |
125
|
|
|
if self.words is None: |
126
|
|
|
words_match = True |
127
|
|
|
else: |
128
|
|
|
words_match = False |
129
|
|
|
for choice in self.words: |
130
|
|
|
if any((word == choice for word in re.compile(r"[ \-_]+").split(target_name))): |
|
|
|
|
131
|
|
|
words_match = True |
132
|
|
|
break |
133
|
|
|
return ( |
134
|
|
|
self.source_type == source |
135
|
|
|
and self.rel_type == rel |
136
|
|
|
and self.dest_type == target |
137
|
|
|
and words_match |
138
|
|
|
) |
139
|
|
|
|
140
|
|
|
|
141
|
|
|
@dataclass(frozen=True, order=True, repr=True) |
|
|
|
|
142
|
|
|
class DagTarget: |
143
|
|
|
depth: int |
144
|
|
|
is_end: bool |
145
|
|
|
target: ChemblTarget |
146
|
|
|
link_type: Optional[DagTargetLinkType] |
147
|
|
|
|
148
|
|
|
|
149
|
|
|
@dataclass(frozen=True, order=True, repr=True) |
150
|
|
|
class ChemblTarget(metaclass=abc.ABCMeta): |
151
|
|
|
""" |
152
|
|
|
A target from ChEMBL, from the ``target`` table. |
153
|
|
|
ChEMBL targets form a DAG via the ``target_relation`` table using links of type "SUPERSET OF" and "SUBSET OF". |
|
|
|
|
154
|
|
|
(There are additional link types ("OVERLAPS WITH", for ex), which we are ignoring.) |
155
|
|
|
For some receptors the DAG happens to be a tree. This is not true in general. See the GABAA receptor, for example. |
|
|
|
|
156
|
|
|
To fetch a target, use the ``find`` factory method. |
157
|
|
|
|
158
|
|
|
Attributes: |
159
|
|
|
chembl: The CHEMBL ID, starting with 'CHEMBL' |
160
|
|
|
name: The preferred name (``pref_target_name``) |
161
|
|
|
type: From the ``target_type`` ChEMBL field |
162
|
|
|
""" |
163
|
|
|
|
164
|
|
|
chembl: str |
165
|
|
|
name: Optional[str] |
166
|
|
|
type: TargetType |
167
|
|
|
|
168
|
|
|
@classmethod |
169
|
|
|
def api(cls) -> ChemblApi: |
170
|
|
|
""" |
171
|
|
|
|
172
|
|
|
Returns: |
173
|
|
|
|
174
|
|
|
""" |
175
|
|
|
raise NotImplementedError() |
176
|
|
|
|
177
|
|
|
@classmethod |
178
|
|
|
def find(cls, chembl: str) -> ChemblTarget: |
179
|
|
|
""" |
180
|
|
|
|
181
|
|
|
Args: |
182
|
|
|
chembl: |
183
|
|
|
|
184
|
|
|
Returns: |
185
|
|
|
|
186
|
|
|
""" |
187
|
|
|
try: |
188
|
|
|
targets = cls.api().target.filter(target_chembl_id=chembl) |
189
|
|
|
except MaxRetryError: |
190
|
|
|
raise TargetNotFoundError(f"Failed to find target {chembl}") |
191
|
|
|
assert len(targets) == 1, f"Found {len(targets)} targets for {chembl}" |
192
|
|
|
target = NestedDotDict(targets[0]) |
193
|
|
|
return cls( |
194
|
|
|
chembl=target["target_chembl_id"], |
195
|
|
|
name=target.get("pref_name"), |
196
|
|
|
type=TargetType.of(target["target_type"]), |
197
|
|
|
) |
198
|
|
|
|
199
|
|
|
def links( |
200
|
|
|
self, rel_types: Set[TargetRelationshipType] |
|
|
|
|
201
|
|
|
) -> Sequence[Tup[ChemblTarget, TargetRelationshipType]]: |
202
|
|
|
""" |
203
|
|
|
Gets adjacent targets in the DAG. |
204
|
|
|
|
205
|
|
|
Args: |
206
|
|
|
rel_types: |
207
|
|
|
|
208
|
|
|
Returns: |
209
|
|
|
""" |
210
|
|
|
relations = self.__class__.api().target_relation.filter(target_chembl_id=self.chembl) |
211
|
|
|
links = [] |
212
|
|
|
# "subset" means "up" (it's reversed from what's on the website) |
213
|
|
|
for superset in relations: |
214
|
|
|
linked_id = superset["related_target_chembl_id"] |
215
|
|
|
rel_type = TargetRelationshipType.of(superset["relationship"]) |
216
|
|
|
if rel_type in rel_types: |
217
|
|
|
linked_target = self.find(linked_id) |
218
|
|
|
links.append((linked_target, rel_type)) |
219
|
|
|
return sorted(links) |
220
|
|
|
|
221
|
|
|
def traverse(self, permitting: Set[DagTargetLinkType]) -> Set[DagTarget]: |
222
|
|
|
""" |
223
|
|
|
Traverses the DAG from this node, hopping only to targets with type in the given set. |
224
|
|
|
|
225
|
|
|
Args: |
226
|
|
|
permitting: The set of target types we're allowed to follow links onto |
227
|
|
|
|
228
|
|
|
Returns: |
229
|
|
|
The targets in the set, in a breadth-first order (then sorted by CHEMBL ID) |
230
|
|
|
The int is the depth, starting at 0 (this protein), going to +inf for the highest ancestors |
|
|
|
|
231
|
|
|
""" |
232
|
|
|
results = set() |
233
|
|
|
# purposely use the invalid value None for is_root |
234
|
|
|
self._traverse(DagTarget(0, None, self, None), permitting, results) |
235
|
|
|
assert not any((x.is_end is None for x in results)) |
|
|
|
|
236
|
|
|
return results |
237
|
|
|
|
238
|
|
|
@classmethod |
239
|
|
|
def _traverse( |
240
|
|
|
cls, source: DagTarget, permitting: Set[DagTargetLinkType], results: Set[DagTarget] |
|
|
|
|
241
|
|
|
) -> None: |
242
|
|
|
# recursive method called from traverse |
243
|
|
|
# this got really complex |
244
|
|
|
# basically, we just want to: |
245
|
|
|
# for each link (relationship) to another target: |
246
|
|
|
# for every allowed link type (DagTargetLinkType), try: |
247
|
|
|
# if the link type is acceptable, add the found target and associated link type, and break |
248
|
|
|
# all good if we've already traversed this |
249
|
|
|
if source.target.chembl in {s.target.chembl for s in results}: |
250
|
|
|
return |
251
|
|
|
# find all links from ChEMBL, then filter to only the valid links |
252
|
|
|
# do not traverse yet -- we just want to find these links |
253
|
|
|
link_candidates = source.target.links({q.rel_type for q in permitting}) |
254
|
|
|
links = [] |
255
|
|
|
for linked_target, rel_type in link_candidates: |
256
|
|
|
# try out all of the link types that could match |
257
|
|
|
# getting to the link_target by way of any of them is fine |
258
|
|
|
# although the DagTarget takes the link_type, we'll just go ahead and break if we find one acceptable link |
|
|
|
|
259
|
|
|
# the links are already sorted, so that should be fine |
260
|
|
|
# (otherwise, we just end up with redundant targets) |
261
|
|
|
for permitted in permitting: |
262
|
|
|
if permitted.matches( |
263
|
|
|
source.target.type, rel_type, linked_target.type, linked_target.name |
|
|
|
|
264
|
|
|
): |
265
|
|
|
link_type = DagTargetLinkType( |
266
|
|
|
source.target.type, rel_type, linked_target.type, permitted.words |
267
|
|
|
) |
268
|
|
|
# purposely use the invalid value None for is_root |
269
|
|
|
linked = DagTarget(source.depth + 1, None, linked_target, link_type) |
270
|
|
|
links.append(linked) |
271
|
|
|
break |
272
|
|
|
# now, we'll add our own (breadth-first, remember) |
273
|
|
|
# we know whether we're at an "end" node by whether we found any links |
274
|
|
|
# note that this is an invariant of the node (and permitted link types): it doesn't depend on traversal order |
|
|
|
|
275
|
|
|
is_at_end = len(links) == 0 |
276
|
|
|
results.add(DagTarget(source.depth, is_at_end, source.target, source.link_type)) |
277
|
|
|
# alright! now traverse on the links |
278
|
|
|
for link in links: |
279
|
|
|
# this check is needed |
280
|
|
|
# otherwise we can go superset --- subset --- superset --- |
281
|
|
|
# or just --- overlaps with --- overlaps with --- |
282
|
|
|
if link not in results: |
283
|
|
|
cls._traverse(link, permitting, results) |
284
|
|
|
|
285
|
|
|
|
286
|
|
|
class TargetFactory: |
287
|
|
|
""" |
288
|
|
|
Factory for ``Target`` that injects a ``ChemblApi``. |
289
|
|
|
""" |
290
|
|
|
|
291
|
|
|
@classmethod |
292
|
|
|
def find(cls, chembl: str, api: ChemblApi) -> ChemblTarget: |
293
|
|
|
""" |
294
|
|
|
|
295
|
|
|
Args: |
296
|
|
|
chembl: |
297
|
|
|
api: |
298
|
|
|
|
299
|
|
|
Returns: |
300
|
|
|
A ``Target`` instance from a newly created subclass of that class |
301
|
|
|
""" |
302
|
|
|
|
303
|
|
|
@dataclass(frozen=True, order=True, repr=True) |
304
|
|
|
class _Target(ChemblTarget): |
305
|
|
|
@classmethod |
306
|
|
|
def api(cls) -> ChemblApi: |
307
|
|
|
return api |
308
|
|
|
|
309
|
|
|
_Target.__name__ = "Target:" + chembl |
310
|
|
|
return _Target.find(chembl) |
311
|
|
|
|
312
|
|
|
|
313
|
|
|
__all__ = [ |
314
|
|
|
"TargetType", |
315
|
|
|
"TargetRelationshipType", |
316
|
|
|
"ChemblTarget", |
317
|
|
|
"DagTarget", |
318
|
|
|
"TargetFactory", |
319
|
|
|
"DagTargetLinkType", |
320
|
|
|
"TargetNotFoundError", |
321
|
|
|
] |
322
|
|
|
|