minervachem 0.0.3a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- minervachem/__init__.py +1 -0
- minervachem/correction.py +41 -0
- minervachem/fingerprinters/__init__.py +21 -0
- minervachem/fingerprinters/graphletfingerprinter.py +324 -0
- minervachem/fingerprinters/morganfingerprinter.py +57 -0
- minervachem/fingerprinters/rdkitfingerprinter.py +58 -0
- minervachem/graphlet_dags.py +826 -0
- minervachem/mcts/__init__.py +11 -0
- minervachem/mcts/sa_score/LICENSE +26 -0
- minervachem/mcts/sa_score/README.md +21 -0
- minervachem/mcts/sa_score/__init__.py +5 -0
- minervachem/mcts/sa_score/fpscores.pkl.gz +0 -0
- minervachem/mcts/sa_score/sascorer.py +173 -0
- minervachem/mcts/state.py +364 -0
- minervachem/mcts/tree.py +304 -0
- minervachem/mcts/tree_viz.py +214 -0
- minervachem/networkx_utils.py +277 -0
- minervachem/padre/README.md +10 -0
- minervachem/padre/__init__.py +1 -0
- minervachem/padre/mappers.py +84 -0
- minervachem/padre/padre.py +114 -0
- minervachem/plotting.py +380 -0
- minervachem/regressors.py +349 -0
- minervachem/scoring.py +30 -0
- minervachem/sparse_eliminator.py +185 -0
- minervachem/transformers.py +363 -0
- minervachem/utils/__init__.py +0 -0
- minervachem/utils/chemistry.py +98 -0
- minervachem/utils/misc.py +118 -0
- minervachem/utils/sparse.py +104 -0
- minervachem-0.0.3a1.dist-info/METADATA +264 -0
- minervachem-0.0.3a1.dist-info/RECORD +37 -0
- minervachem-0.0.3a1.dist-info/WHEEL +5 -0
- minervachem-0.0.3a1.dist-info/licenses/AUTHORS.md +8 -0
- minervachem-0.0.3a1.dist-info/licenses/LICENSE.txt +24 -0
- minervachem-0.0.3a1.dist-info/licenses/NOTICE.md +14 -0
- minervachem-0.0.3a1.dist-info/top_level.txt +1 -0
minervachem/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.2"
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
class FragmentLinearModelCorrector:
|
|
4
|
+
|
|
5
|
+
def __init__(self, params, param_sizes):
|
|
6
|
+
"""
|
|
7
|
+
:params: a (n, ) numpy array of linear model coefficients
|
|
8
|
+
:param_sizes: a (n, ) numpy array of sizes of the substructures associated with the coefficients
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
self.params = params
|
|
12
|
+
self.param_sizes = param_sizes
|
|
13
|
+
self.unique_fragment_sizes = sorted(list(set(param_sizes)))
|
|
14
|
+
|
|
15
|
+
# take average of coefficients at different sizes
|
|
16
|
+
self.mu_by_size = {}
|
|
17
|
+
for size in self.unique_fragment_sizes:
|
|
18
|
+
self.mu_by_size[size] = self.params[param_sizes == size].mean()
|
|
19
|
+
|
|
20
|
+
def predict(self, X_seen, X_unseen, unseen_sizes):
|
|
21
|
+
"""
|
|
22
|
+
:X_seen: (m,n) array of substructure counts, to be multiplied with self.params
|
|
23
|
+
:X_unseen: (m,u) array of of unseen substructure counts
|
|
24
|
+
:unseen_sizes: (u,) array of sizes of unseen features
|
|
25
|
+
"""
|
|
26
|
+
seen_prediction = self._predict_seen(X_seen)
|
|
27
|
+
unseen_correction = self._predict_unseen(X_unseen, unseen_sizes)
|
|
28
|
+
return seen_prediction + unseen_correction
|
|
29
|
+
|
|
30
|
+
def _predict_seen(self, X):
|
|
31
|
+
|
|
32
|
+
return X @ self.params
|
|
33
|
+
|
|
34
|
+
def _predict_unseen(self, X, sizes):
|
|
35
|
+
correction = np.zeros(X.shape[0])
|
|
36
|
+
for size in self.unique_fragment_sizes:
|
|
37
|
+
counts_of_size = X[:, sizes == size].sum(1) # gives an (m, 1) matrix
|
|
38
|
+
correction_at_size = self.mu_by_size[size] * counts_of_size
|
|
39
|
+
correction += np.asarray(correction_at_size).squeeze()
|
|
40
|
+
return correction
|
|
41
|
+
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Fingerprinters: a set of callables for creating molecular fingerprints
|
|
2
|
+
|
|
3
|
+
Fingerprinters are instantiated with parameters and then called on molecules.
|
|
4
|
+
Once called they return two dictionaries, one mapping from substructures IDs to substructure counts,
|
|
5
|
+
and the other mapping from substructure IDs to a list of lists containing the atomIDs
|
|
6
|
+
of the satisfying substructures. We commonly call the first dict `fp` and the second `bi` (for bitInfo)
|
|
7
|
+
to keep with RDKit convention.
|
|
8
|
+
|
|
9
|
+
An important note is that the fingerprint bit IDs in minervachem are a tuple of the substructure's hash and its size.
|
|
10
|
+
This is convenient for DAG construction and hierarchical model fitting. The meaning of size differs across the
|
|
11
|
+
provided fingerprinters.
|
|
12
|
+
|
|
13
|
+
Available fingerprinters:
|
|
14
|
+
* GraphletFingerprinter
|
|
15
|
+
* RDKitFingerprinter (calls RDKit's rdkit fingerprint routines)
|
|
16
|
+
* MorganFingerprinter (calls RDKit's Morgan fingerprint routines)
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from .morganfingerprinter import MorganFingerprinter
|
|
20
|
+
from .rdkitfingerprinter import RDKitFingerprinter
|
|
21
|
+
from .graphletfingerprinter import GraphletFingerprinter
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
import networkx as nx
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
from buhito.depth_graphlet import (
|
|
6
|
+
HashHelper,
|
|
7
|
+
active_neighbors,
|
|
8
|
+
generate_subgraphs_depthwise,
|
|
9
|
+
generate_subgraphs_from_node,
|
|
10
|
+
search_subgraphs_from_cluster,
|
|
11
|
+
)
|
|
12
|
+
from rdkit.Chem import rdmolops, RWMol
|
|
13
|
+
from rdkit.Chem.rdchem import Mol
|
|
14
|
+
import rdkit
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# Backwards-compatible name for Minervachem callers. The graphlet enumeration
|
|
18
|
+
# and recursive hashing implementation now lives in Buhito.
|
|
19
|
+
generate_subgraphs = generate_subgraphs_depthwise
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class GraphletFingerprinter():
|
|
23
|
+
def __init__(self, max_len=3, useHs=False, elements=(), filter_in=True, terminal_pos=False):
|
|
24
|
+
"""A class to produce graphlet fingerprints
|
|
25
|
+
|
|
26
|
+
The size component of the bit ID corresponds to the number of atoms in the graphlet.
|
|
27
|
+
|
|
28
|
+
:param max_len: int, the largest number of atoms to consider for induced subgraphs
|
|
29
|
+
:param useHs: bool, whether to use explicit hydrogens
|
|
30
|
+
:param elements: tuple of str, the elements to filter for
|
|
31
|
+
:param filter_in: bool, True if substructures with filtered elements should be kept,
|
|
32
|
+
False if substructures with filtered elements should be removed
|
|
33
|
+
:param terminal_pos: bool, True if substructures with terminal atoms should be kept,
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
self.size = self.max_len = max_len
|
|
37
|
+
self.useHs = useHs
|
|
38
|
+
self.elements = elements
|
|
39
|
+
self.filter_in = filter_in
|
|
40
|
+
self.terminal_pos = terminal_pos
|
|
41
|
+
self.verbose = False
|
|
42
|
+
|
|
43
|
+
if len(self.elements)==0:
|
|
44
|
+
print('No elements to filter. Complete fingerprints are returned.') #should only appear once at the initialization
|
|
45
|
+
|
|
46
|
+
def __call__(self, mol):
|
|
47
|
+
fp, bi = ComputeGraphletFingerprint(mol,
|
|
48
|
+
self.max_len,
|
|
49
|
+
self.useHs,
|
|
50
|
+
self.elements,
|
|
51
|
+
self.filter_in,
|
|
52
|
+
self.terminal_pos,
|
|
53
|
+
self.verbose)
|
|
54
|
+
return fp, bi
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def akey_noH(atom):
|
|
59
|
+
return (atom.GetAtomicNum(),atom.GetFormalCharge(),atom.GetIsAromatic(),atom.GetNumImplicitHs())
|
|
60
|
+
|
|
61
|
+
def akey_withH(atom):
|
|
62
|
+
return (atom.GetAtomicNum(),atom.GetFormalCharge())
|
|
63
|
+
|
|
64
|
+
def mol_to_nx(mol,explicit_h=False):
|
|
65
|
+
"""
|
|
66
|
+
Modified from:
|
|
67
|
+
https://github.com/dakoner/keras-molecules/blob/dbbb790e74e406faa70b13e8be8104d9e938eba2/convert_rdkit_to_networkx.py#L17
|
|
68
|
+
"""
|
|
69
|
+
G = nx.Graph()
|
|
70
|
+
if explicit_h:
|
|
71
|
+
mol=rdmolops.AddHs(mol)
|
|
72
|
+
akey = akey_withH
|
|
73
|
+
else:
|
|
74
|
+
akey = akey_noH
|
|
75
|
+
for atom in mol.GetAtoms():
|
|
76
|
+
G.add_node(atom.GetIdx(),
|
|
77
|
+
atom_key=akey(atom))
|
|
78
|
+
for bond in mol.GetBonds():
|
|
79
|
+
G.add_edge(bond.GetBeginAtomIdx(),
|
|
80
|
+
bond.GetEndAtomIdx(),
|
|
81
|
+
bond_key = bond.GetBondType())
|
|
82
|
+
return G
|
|
83
|
+
|
|
84
|
+
def _guess_element(atom_name: str, atom_type: str | None) -> str | None:
|
|
85
|
+
elements = ('X', 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P',
|
|
86
|
+
'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn',
|
|
87
|
+
'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh',
|
|
88
|
+
'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd',
|
|
89
|
+
'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re',
|
|
90
|
+
'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th',
|
|
91
|
+
'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db',
|
|
92
|
+
'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og')
|
|
93
|
+
if atom_type:
|
|
94
|
+
t0 = atom_type.split('.')[0]
|
|
95
|
+
cand = t0[0].upper() + (t0[1:].lower() if len(t0) > 1 else "")
|
|
96
|
+
if cand in elements:
|
|
97
|
+
return cand
|
|
98
|
+
m = re.match(r"([A-Za-z]{1,2})", atom_name or "")
|
|
99
|
+
if m:
|
|
100
|
+
cand = m.group(1)[0].upper() + (m.group(1)[1:].lower() if len(m.group(1)) == 2 else "")
|
|
101
|
+
if cand in elements:
|
|
102
|
+
return cand
|
|
103
|
+
return None
|
|
104
|
+
|
|
105
|
+
def _bond_order_and_flags(bond_type: str | None):
|
|
106
|
+
if not bond_type:
|
|
107
|
+
return None, False
|
|
108
|
+
bt = bond_type.lower()
|
|
109
|
+
aromatic = (bt == "ar")
|
|
110
|
+
if bt in ("1", "single"): order = 1
|
|
111
|
+
elif bt in ("2", "double"): order = 2
|
|
112
|
+
elif bt in ("3", "triple"): order = 3
|
|
113
|
+
elif bt == "ar": order = 1.5
|
|
114
|
+
elif bt == "am": order = 1 # amide single
|
|
115
|
+
elif bt == "un": order = 0.5 # un should mostly be dative
|
|
116
|
+
else: order = None
|
|
117
|
+
return order, aromatic
|
|
118
|
+
|
|
119
|
+
def mol2_to_nx(mol2str, explicit_h=False):
|
|
120
|
+
"""mol2_to_nx
|
|
121
|
+
Take in a mol2string and return a networkx version of the molecular graph.
|
|
122
|
+
By default uses heavy elements only.
|
|
123
|
+
|
|
124
|
+
Node attrs (explicit_h=True):
|
|
125
|
+
- name, element, sybyl_type, x,y,z, charge, subst_id, subst_name
|
|
126
|
+
- atom_key = (symbol, atom_type)
|
|
127
|
+
- original_index (1-based from MOL2)
|
|
128
|
+
|
|
129
|
+
Node attrs (explicit_h=False; hydrogens collapsed):
|
|
130
|
+
- all of the above EXCEPT element/name for removed H nodes
|
|
131
|
+
- h_count (# directly bonded H)
|
|
132
|
+
- atom_key = (symbol, atom_type, h_count)
|
|
133
|
+
- original_index maps to original heavy-atom id list (1-based indices of heavy atoms)
|
|
134
|
+
|
|
135
|
+
Edge attrs (both modes):
|
|
136
|
+
- order (float|None), aromatic (bool), raw_type (str), bond_key (==raw_type)
|
|
137
|
+
- has_h (bool) # True if either endpoint in the original MOL2 bond was a hydrogen
|
|
138
|
+
- original_indices = (i1, j1) # original 1-based atom ids
|
|
139
|
+
"""
|
|
140
|
+
atoms_tmp = {} # id1 -> dict
|
|
141
|
+
bonds_tmp = [] # (i1, j1, raw_type)
|
|
142
|
+
|
|
143
|
+
s = mol2str.splitlines() # mol2 are expected to be small, can be replaced with io.StringIO(mol2str) for more efficiency
|
|
144
|
+
in_atoms = in_bonds = False
|
|
145
|
+
for line in s:
|
|
146
|
+
if not line:
|
|
147
|
+
continue
|
|
148
|
+
if line.startswith("@<TRIPOS>") or line.startswith("<TRIPOS>"):
|
|
149
|
+
tag = line.replace("@", "").upper()
|
|
150
|
+
in_atoms = (tag == "<TRIPOS>ATOM")
|
|
151
|
+
in_bonds = (tag == "<TRIPOS>BOND")
|
|
152
|
+
continue
|
|
153
|
+
if in_atoms:
|
|
154
|
+
parts = line.split()
|
|
155
|
+
if len(parts) < 8:
|
|
156
|
+
continue
|
|
157
|
+
try:
|
|
158
|
+
atom_id = int(parts[0])
|
|
159
|
+
name = parts[1]
|
|
160
|
+
x, y, z = map(float, parts[2:5])
|
|
161
|
+
sybyl_type = parts[5]
|
|
162
|
+
subst_id = int(parts[6])
|
|
163
|
+
subst_name = parts[7]
|
|
164
|
+
charge = float(parts[8]) if len(parts) >= 9 else 0.0
|
|
165
|
+
except Exception:
|
|
166
|
+
continue
|
|
167
|
+
elem = _guess_element(name, sybyl_type)
|
|
168
|
+
atoms_tmp[atom_id] = dict(
|
|
169
|
+
name=name, element=elem, sybyl_type=sybyl_type,
|
|
170
|
+
x=x, y=y, z=z, charge=charge,
|
|
171
|
+
subst_id=subst_id, subst_name=subst_name,
|
|
172
|
+
original_index=atom_id
|
|
173
|
+
)
|
|
174
|
+
elif in_bonds:
|
|
175
|
+
parts = line.split()
|
|
176
|
+
if len(parts) < 4:
|
|
177
|
+
continue
|
|
178
|
+
try:
|
|
179
|
+
i1 = int(parts[1]); j1 = int(parts[2]); btype = parts[3]
|
|
180
|
+
except Exception:
|
|
181
|
+
continue
|
|
182
|
+
bonds_tmp.append((i1, j1, btype))
|
|
183
|
+
|
|
184
|
+
is_h = {aid: (atoms_tmp[aid].get("element") == "H") for aid in atoms_tmp}
|
|
185
|
+
heavy_ids = [aid for aid in sorted(atoms_tmp) if not is_h[aid]]
|
|
186
|
+
heavy_reindex = {aid: idx for idx, aid in enumerate(heavy_ids, start=1)} # 1..N
|
|
187
|
+
|
|
188
|
+
h_count_map = {aid: 0 for aid in atoms_tmp}
|
|
189
|
+
for i1, j1, _ in bonds_tmp:
|
|
190
|
+
if is_h.get(i1, False) and not is_h.get(j1, False):
|
|
191
|
+
h_count_map[j1] += 1
|
|
192
|
+
elif is_h.get(j1, False) and not is_h.get(i1, False):
|
|
193
|
+
h_count_map[i1] += 1
|
|
194
|
+
|
|
195
|
+
G = nx.Graph()
|
|
196
|
+
|
|
197
|
+
if explicit_h:
|
|
198
|
+
# atoms with original ordering for node ids (1..N)
|
|
199
|
+
for aid in sorted(atoms_tmp):
|
|
200
|
+
a = atoms_tmp[aid]
|
|
201
|
+
atom_key = (a["element"] or "?", a["sybyl_type"])
|
|
202
|
+
G.add_node(
|
|
203
|
+
aid,
|
|
204
|
+
name=a["name"], element=a["element"], sybyl_type=a["sybyl_type"],
|
|
205
|
+
x=a["x"], y=a["y"], z=a["z"], charge=a["charge"],
|
|
206
|
+
subst_id=a["subst_id"], subst_name=a["subst_name"],
|
|
207
|
+
original_index=a["original_index"],
|
|
208
|
+
# "compat" attr
|
|
209
|
+
atom_key=atom_key
|
|
210
|
+
)
|
|
211
|
+
for i1, j1, raw in bonds_tmp:
|
|
212
|
+
order, aromatic = _bond_order_and_flags(raw)
|
|
213
|
+
G.add_edge(
|
|
214
|
+
i1, j1,
|
|
215
|
+
order=order, aromatic=aromatic,
|
|
216
|
+
raw_type=raw, bond_key=raw,
|
|
217
|
+
has_h=is_h.get(i1, False) or is_h.get(j1, False),
|
|
218
|
+
original_indices=(i1, j1)
|
|
219
|
+
)
|
|
220
|
+
else:
|
|
221
|
+
# only heavy atoms become nodes, reindexed 1..N
|
|
222
|
+
for aid in heavy_ids:
|
|
223
|
+
a = atoms_tmp[aid]
|
|
224
|
+
hc = h_count_map.get(aid, 0)
|
|
225
|
+
atom_key = (a["element"] or "?", a["sybyl_type"], hc)
|
|
226
|
+
new_id = heavy_reindex[aid]
|
|
227
|
+
G.add_node(
|
|
228
|
+
new_id,
|
|
229
|
+
name=a["name"], element=a["element"], sybyl_type=a["sybyl_type"],
|
|
230
|
+
x=a["x"], y=a["y"], z=a["z"], charge=a["charge"],
|
|
231
|
+
subst_id=a["subst_id"], subst_name=a["subst_name"],
|
|
232
|
+
h_count=hc, original_index=aid,
|
|
233
|
+
atom_key=atom_key
|
|
234
|
+
)
|
|
235
|
+
for i1, j1, raw in bonds_tmp:
|
|
236
|
+
if is_h.get(i1, False) or is_h.get(j1, False):
|
|
237
|
+
continue
|
|
238
|
+
i_new = heavy_reindex[i1]; j_new = heavy_reindex[j1]
|
|
239
|
+
order, aromatic = _bond_order_and_flags(raw)
|
|
240
|
+
G.add_edge(
|
|
241
|
+
i_new, j_new,
|
|
242
|
+
order=order, aromatic=aromatic,
|
|
243
|
+
raw_type=raw, bond_key=raw,
|
|
244
|
+
has_h=False,
|
|
245
|
+
original_indices=(i1, j1)
|
|
246
|
+
)
|
|
247
|
+
G.graph["explicit_h"] = explicit_h
|
|
248
|
+
G.graph["heavy_reindex"] = heavy_reindex if not explicit_h else None
|
|
249
|
+
return G
|
|
250
|
+
|
|
251
|
+
def flatten_list(xss):
|
|
252
|
+
return [x for xs in xss for x in xs]
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def ComputeGraphletFingerprint(rdkit_mol, maxlen, explicit_h, elements=(), filter_in=True, terminal_pos=False, verbose=False):
|
|
256
|
+
"""RDKit style wrapper to generate_subgraphs but keyed by (size, bit)"""
|
|
257
|
+
if isinstance(rdkit_mol, Mol):
|
|
258
|
+
G = mol_to_nx(rdkit_mol, explicit_h=explicit_h)
|
|
259
|
+
el_inds = [atom.GetIdx() for atom in rdkit_mol.GetAtoms() if atom.GetSymbol() in elements] if elements else None
|
|
260
|
+
elif isinstance(rdkit_mol, str):
|
|
261
|
+
if 'TRIPOS' in rdkit_mol:
|
|
262
|
+
G = mol2_to_nx(rdkit_mol, explicit_h=explicit_h)
|
|
263
|
+
el_inds = [n for n, d in G.nodes(data=True) if d.get('element') in elements] if elements else None
|
|
264
|
+
else:
|
|
265
|
+
raise ValueError('Unknown molecule type for featurizing')
|
|
266
|
+
elif isinstance(rdkit_mol, nx.classes.graph.Graph):
|
|
267
|
+
G = rdkit_mol
|
|
268
|
+
el_inds = [n for n, d in G.nodes(data=True) if d.get('element') in elements] if elements else None
|
|
269
|
+
else:
|
|
270
|
+
raise ValueError('Unknown molecule type for featurizing')
|
|
271
|
+
subsets, counter = generate_subgraphs(G, maxlen)
|
|
272
|
+
bit_info = defaultdict(lambda: [])
|
|
273
|
+
for atoms, bit in subsets:
|
|
274
|
+
subset = list(atoms)
|
|
275
|
+
size = len(subset)
|
|
276
|
+
bit_info[(size, bit + 2 ** 64)].append(subset)
|
|
277
|
+
fp = {(k[0], k[1] + 2 ** 64): v for k, v in counter.items()}
|
|
278
|
+
bit_info = dict(bit_info)
|
|
279
|
+
|
|
280
|
+
if len(elements)==0:
|
|
281
|
+
return fp, bit_info
|
|
282
|
+
else:
|
|
283
|
+
# el_inds = [atom.GetIdx() for atom in rdkit_mol.GetAtoms() if atom.GetSymbol() in elements]
|
|
284
|
+
if len(el_inds)==0:
|
|
285
|
+
if len(elements)!=0:
|
|
286
|
+
if verbose:
|
|
287
|
+
print("Elements to filter for not found OR incorrect element symbols are entered. Empty FP is returned")
|
|
288
|
+
for k in bit_info.keys():
|
|
289
|
+
bit_info[k] = []
|
|
290
|
+
fp[k] = 0
|
|
291
|
+
else:
|
|
292
|
+
for k, v in bit_info.items():
|
|
293
|
+
remove_flag = True
|
|
294
|
+
if not filter_in:
|
|
295
|
+
remove_flag = False
|
|
296
|
+
for bit_atom in flatten_list(v):
|
|
297
|
+
if bit_atom in el_inds:
|
|
298
|
+
remove_flag = not remove_flag
|
|
299
|
+
break
|
|
300
|
+
if remove_flag:
|
|
301
|
+
bit_info[k] = []
|
|
302
|
+
fp[k] = 0
|
|
303
|
+
if terminal_pos: # Not working for network x yet
|
|
304
|
+
assert filter_in, "The functionality currently works for filtering in only." # TODO make it work for filter out too
|
|
305
|
+
for k, v in bit_info.items():
|
|
306
|
+
if len(v)==0 or k[0]<=2:
|
|
307
|
+
continue
|
|
308
|
+
|
|
309
|
+
rwmol_temp = RWMol(rdkit_mol)
|
|
310
|
+
for atom in reversed(list(rwmol_temp.GetAtoms())):
|
|
311
|
+
if atom.GetIdx() not in v[0]:
|
|
312
|
+
rwmol_temp.RemoveAtom(atom.GetIdx())
|
|
313
|
+
|
|
314
|
+
non_terminal = []
|
|
315
|
+
for element in elements:
|
|
316
|
+
local_elements = [atom for atom in rwmol_temp.GetAtoms() if atom.GetSymbol()==element]
|
|
317
|
+
local_nbrs = [len(atom.GetNeighbors()) for atom in local_elements] #this should support multi metal element core
|
|
318
|
+
non_terminal.append(any(nbr_number > 1 for nbr_number in local_nbrs) if local_nbrs else True) # makes sure that if other element filtered for is not is the substructure it does not get flagged as terminal
|
|
319
|
+
|
|
320
|
+
if all(non_terminal):
|
|
321
|
+
bit_info[k] = []
|
|
322
|
+
fp[k] = 0
|
|
323
|
+
|
|
324
|
+
return fp, bit_info
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
from rdkit.Chem import AllChem
|
|
2
|
+
|
|
3
|
+
class MorganFingerprinter:
|
|
4
|
+
"""A minervachem wrapper to Morgan fingerprints from RDKit
|
|
5
|
+
|
|
6
|
+
Note that here, the size component of the bit ID corresponds to radius.
|
|
7
|
+
|
|
8
|
+
:param radius: the maximum radius used for FP construction
|
|
9
|
+
:use counts: indicator for count-based or boolean fingerprints
|
|
10
|
+
:n_bits: if None, do not hash, else hash to the given size
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, radius, use_counts=True, n_bits=None):
|
|
14
|
+
self.radius = radius
|
|
15
|
+
self.use_counts = use_counts
|
|
16
|
+
self.n_bits = n_bits
|
|
17
|
+
self.size = self.radius
|
|
18
|
+
|
|
19
|
+
def __call__(self, mol):
|
|
20
|
+
bi = {}
|
|
21
|
+
if self.n_bits:
|
|
22
|
+
fp = self._hashed_fp(mol, bi)
|
|
23
|
+
else:
|
|
24
|
+
fp = self._unhashed_fp(mol, bi)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
fp, bi = [self._append_radii(d, bi) for d in [fp, bi]]
|
|
28
|
+
return fp, bi
|
|
29
|
+
|
|
30
|
+
@staticmethod
|
|
31
|
+
def _append_radii(d, bi):
|
|
32
|
+
return {(bi[k][0][1], k): v for k, v in d.items()}
|
|
33
|
+
|
|
34
|
+
def _hashed_fp(self, mol, bi):
|
|
35
|
+
if self.use_counts:
|
|
36
|
+
fp = (AllChem.GetHashedMorganFingerprint(mol,
|
|
37
|
+
self.radius,
|
|
38
|
+
nBits=self.n_bits,
|
|
39
|
+
bitInfo=bi)
|
|
40
|
+
.GetNonzeroElements())
|
|
41
|
+
else:
|
|
42
|
+
fp = (AllChem.GetMorganFingerprintAsBitVect(mol,
|
|
43
|
+
self.radius,
|
|
44
|
+
nBits=self.n_bits,
|
|
45
|
+
bitInfo=bi)
|
|
46
|
+
.GetOnBits())
|
|
47
|
+
fp = {b: 1 for b in list(fp)}
|
|
48
|
+
|
|
49
|
+
return fp
|
|
50
|
+
|
|
51
|
+
def _unhashed_fp(self, mol, bi):
|
|
52
|
+
fp = AllChem.GetMorganFingerprint(mol,
|
|
53
|
+
self.radius,
|
|
54
|
+
bitInfo=bi,
|
|
55
|
+
useCounts=self.use_counts)
|
|
56
|
+
return fp.GetNonzeroElements()
|
|
57
|
+
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from rdkit.Chem.rdmolops import UnfoldedRDKFingerprintCountBased
|
|
2
|
+
|
|
3
|
+
class RDKitFingerprinter():
|
|
4
|
+
"""A minervachem fingerprinter for rdkit fingerprints
|
|
5
|
+
|
|
6
|
+
Currently only supports unfolded count-based fingerprints.
|
|
7
|
+
|
|
8
|
+
The arguments are passed directly to UnfoldedRDKFingerprintCountBased
|
|
9
|
+
|
|
10
|
+
Note that the size component of the bit IDs correspond to the number of bonds present in the fragment
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self,
|
|
14
|
+
minPath=1,
|
|
15
|
+
maxPath=7,
|
|
16
|
+
useHs=True,
|
|
17
|
+
branchedPaths=True,
|
|
18
|
+
useBondOrder=True,
|
|
19
|
+
atomInvariants=0,
|
|
20
|
+
fromAtoms=0,
|
|
21
|
+
atomBits=None):
|
|
22
|
+
|
|
23
|
+
self.minPath = minPath
|
|
24
|
+
self.size = self.maxPath = maxPath
|
|
25
|
+
self.useHs = useHs
|
|
26
|
+
self.branchedPaths = branchedPaths
|
|
27
|
+
self.useBondOrder = useBondOrder
|
|
28
|
+
self.atomInvariants = atomInvariants
|
|
29
|
+
self.fromAtoms = fromAtoms
|
|
30
|
+
self.atomBits = atomBits
|
|
31
|
+
|
|
32
|
+
def __call__(self, mol):
|
|
33
|
+
"""Fingerprint a molecule with rdkit fingerprints
|
|
34
|
+
|
|
35
|
+
:param mol: an RDKit Molecule
|
|
36
|
+
:return fp: a dict mapping substructure IDs to counts
|
|
37
|
+
:return bi: a dict mapping substructure IDs to a list of lists, where the inner lists are the set of bonds for a given occurence of the substructure
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
bi = {}
|
|
41
|
+
fp = UnfoldedRDKFingerprintCountBased(mol,
|
|
42
|
+
bitInfo=bi,
|
|
43
|
+
minPath=self.minPath,
|
|
44
|
+
maxPath=self.maxPath,
|
|
45
|
+
useHs=self.useHs,
|
|
46
|
+
branchedPaths=self.branchedPaths,
|
|
47
|
+
useBondOrder=self.useBondOrder,
|
|
48
|
+
atomInvariants=self.atomInvariants,
|
|
49
|
+
fromAtoms=self.fromAtoms,
|
|
50
|
+
atomBits=self.atomBits,
|
|
51
|
+
).GetNonzeroElements()
|
|
52
|
+
|
|
53
|
+
fp, bi = [self._append_lengths(d, bi) for d in [fp, bi]]
|
|
54
|
+
return fp, bi
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
def _append_lengths(d, bi):
|
|
58
|
+
return {(len(bi[k][0]), k): v for k, v in d.items()}
|