|
1
|
|
|
#! /usr/bin/env python |
|
|
|
|
|
|
2
|
|
|
# |
|
3
|
|
|
# Copyright (C) 2016 Rich Lewis <[email protected]> |
|
4
|
|
|
# License: 3-clause BSD |
|
5
|
|
|
|
|
6
|
|
|
import warnings |
|
7
|
|
|
import logging |
|
8
|
|
|
import os |
|
9
|
|
|
from collections import namedtuple |
|
10
|
|
|
|
|
11
|
|
|
import numpy as np |
|
|
|
|
|
|
12
|
|
|
import pandas as pd |
|
|
|
|
|
|
13
|
|
|
import h5py |
|
|
|
|
|
|
14
|
|
|
from fuel.datasets import H5PYDataset |
|
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
from ... import forcefields |
|
17
|
|
|
from ... import filters |
|
18
|
|
|
from ... import descriptors |
|
19
|
|
|
from ... import standardizers |
|
20
|
|
|
from ... import pipeline |
|
21
|
|
|
|
|
22
|
|
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
|
23
|
|
|
|
|
24
|
|
|
|
|
25
|
|
|
def default_pipeline(): |
|
26
|
|
|
""" Return a default pipeline to be used for general datasets. """ |
|
27
|
|
|
return pipeline.Pipeline([ |
|
28
|
|
|
standardizers.ChemAxonStandardizer(keep_failed=True, warn_on_fail=False), |
|
29
|
|
|
forcefields.UFF(add_hs=True, warn_on_fail=False), |
|
30
|
|
|
filters.OrganicFilter(), |
|
31
|
|
|
filters.AtomNumberFilter(above=5, below=100, include_hydrogens=True), |
|
32
|
|
|
filters.MassFilter(below=1000) |
|
33
|
|
|
]) |
|
34
|
|
|
|
|
35
|
|
|
DEFAULT_PYTABLES_KW = { |
|
36
|
|
|
'complib': 'bzip2', |
|
37
|
|
|
'complevel': 9 |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
def contiguous_order(to_order, splits): |
|
41
|
|
|
""" Determine a contiguous order from non-overlapping splits, and put data in that order. |
|
42
|
|
|
|
|
43
|
|
|
Args: |
|
44
|
|
|
to_order (iterable<pd.Series, pd.DataFrame, pd.Panel>): |
|
45
|
|
|
The pandas objects to put in contiguous order. |
|
46
|
|
|
splits (iterable<pd.Series>): |
|
47
|
|
|
The non-overlapping splits, as boolean masks. |
|
48
|
|
|
|
|
49
|
|
|
Returns: |
|
50
|
|
|
iterable<pd.Series, pd.DataFrame, pd.Panel>: The data in contiguous order. |
|
51
|
|
|
""" |
|
52
|
|
|
|
|
53
|
|
|
member = pd.Series(0, index=splits[0].index) |
|
54
|
|
|
for i, split in enumerate(splits): |
|
55
|
|
|
member[split] = i |
|
56
|
|
|
idx = member.sort_values().index |
|
57
|
|
|
return (order.reindex(idx) for order in to_order) |
|
58
|
|
|
|
|
59
|
|
|
Feature = namedtuple('Feature', ['fper', 'key', 'axis_names']) |
|
60
|
|
|
|
|
61
|
|
|
|
|
62
|
|
|
def default_features(): |
|
|
|
|
|
|
63
|
|
|
return ( |
|
64
|
|
|
Feature(fper=descriptors.MorganFeaturizer(), |
|
65
|
|
|
key='X_morg', |
|
66
|
|
|
axis_names=['batch', 'features']), |
|
67
|
|
|
Feature(fper=descriptors.PhysicochemicalFeaturizer(), |
|
68
|
|
|
key='X_pc', |
|
69
|
|
|
axis_names=['batch', 'features']), |
|
70
|
|
|
Feature(fper=descriptors.AtomFeaturizer(max_atoms=100), |
|
71
|
|
|
key='A', |
|
72
|
|
|
axis_names=['batch', 'atom_idx', 'features']), |
|
73
|
|
|
Feature(fper=descriptors.GraphDistanceTransformer(max_atoms=100), |
|
74
|
|
|
key='G', |
|
75
|
|
|
axis_names=['batch', 'atom_idx', 'atom_idx']), |
|
76
|
|
|
Feature(fper=descriptors.SpacialDistanceTransformer(max_atoms=100), |
|
77
|
|
|
key='G_d', |
|
78
|
|
|
axis_names=['batch', 'atom_idx', 'atom_idx']), |
|
79
|
|
|
Feature(fper=descriptors.ChemAxonFeaturizer(features='all'), |
|
80
|
|
|
key='X_cx', |
|
81
|
|
|
axis_names=['batch', 'features']), |
|
82
|
|
|
Feature(fper=descriptors.ChemAxonAtomFeaturizer(features='all', max_atoms=100), |
|
83
|
|
|
key='A_cx', |
|
84
|
|
|
axis_names=['batch', 'atom_idx', 'features']) |
|
85
|
|
|
) |
|
86
|
|
|
|
|
87
|
|
|
|
|
88
|
|
|
class Split(object): |
|
|
|
|
|
|
89
|
|
|
|
|
90
|
|
|
def __init__(self, mask, name, converter): |
|
91
|
|
|
self.mask = mask |
|
92
|
|
|
self.name = name |
|
93
|
|
|
self.converter = converter |
|
94
|
|
|
|
|
95
|
|
|
@property |
|
96
|
|
|
def contiguous(self): |
|
|
|
|
|
|
97
|
|
|
diff = np.ediff1d(self.mask) |
|
98
|
|
|
if self.mask.iloc[0] != 0: |
|
99
|
|
|
diff[0] = 1 |
|
100
|
|
|
if self.mask.iloc[-1] != 0: |
|
101
|
|
|
diff[-1] = -1 |
|
102
|
|
|
return sum(diff == -1) == 1 or sum(diff == 1) == 1 |
|
103
|
|
|
|
|
104
|
|
|
@property |
|
105
|
|
|
def indices(self): |
|
|
|
|
|
|
106
|
|
|
return np.nonzero(self.mask)[0] |
|
107
|
|
|
|
|
108
|
|
|
def save(self): |
|
|
|
|
|
|
109
|
|
|
self.converter.data_file[self.name + '_indices'] = self.indices |
|
110
|
|
|
with warnings.catch_warnings(): |
|
111
|
|
|
warnings.simplefilter('ignore') |
|
112
|
|
|
self.mask.to_hdf(self.converter.data_file.filename, '/indices/' + self.name) |
|
113
|
|
|
|
|
114
|
|
|
@property |
|
115
|
|
|
def ref(self): |
|
|
|
|
|
|
116
|
|
|
return self.converter.data_file[self.name + '_indices'].ref |
|
117
|
|
|
|
|
118
|
|
|
def to_dict(self): |
|
|
|
|
|
|
119
|
|
|
idx = self.indices |
|
120
|
|
|
if self.contiguous: |
|
121
|
|
|
low, high = min(idx), max(idx) |
|
122
|
|
|
return {source: (low, high) for source in self.converter.source_names} |
|
123
|
|
|
else: |
|
124
|
|
|
return {source: (-1, -1, self.ref) for source in self.converter.source_names} |
|
125
|
|
|
|
|
126
|
|
|
|
|
127
|
|
|
class Converter(object): |
|
128
|
|
|
""" Create a fuel dataset from molecules and targets. """ |
|
129
|
|
|
|
|
130
|
|
|
def __init__(self, directory, output_directory, output_filename='default.h5'): |
|
|
|
|
|
|
131
|
|
|
raise NotImplemented |
|
|
|
|
|
|
132
|
|
|
|
|
133
|
|
|
def run(self, ms, y, output_path, splits=None, features=None, pytables_kws=DEFAULT_PYTABLES_KW): |
|
|
|
|
|
|
134
|
|
|
|
|
135
|
|
|
""" |
|
136
|
|
|
Args: |
|
137
|
|
|
ms (pd.Series): |
|
138
|
|
|
The molecules of the dataset. |
|
139
|
|
|
ys (pd.Series or pd.DataFrame): |
|
140
|
|
|
The target labels of the dataset. |
|
141
|
|
|
output_path (str): |
|
142
|
|
|
The path to which the dataset should be saved. |
|
143
|
|
|
features (list[Feature]): |
|
144
|
|
|
The features to calculate. Defaults are used if `None`. |
|
145
|
|
|
splits (iterable<(name, split)>): |
|
146
|
|
|
An iterable of name, split tuples. Splits are provided as boolean arrays of the whole data. |
|
|
|
|
|
|
147
|
|
|
""" |
|
148
|
|
|
|
|
149
|
|
|
self.pytables_kws = pytables_kws |
|
|
|
|
|
|
150
|
|
|
self.output_path = output_path |
|
|
|
|
|
|
151
|
|
|
self.features = features if features is not None else default_features() |
|
|
|
|
|
|
152
|
|
|
self.feature_names = [feat.key for feat in self.features] |
|
|
|
|
|
|
153
|
|
|
self.task_names = ['y'] |
|
|
|
|
|
|
154
|
|
|
self.splits = [Split(split, name, self) for name, split in splits] |
|
|
|
|
|
|
155
|
|
|
|
|
156
|
|
|
self.create_file(output_path) |
|
157
|
|
|
|
|
158
|
|
|
self.save_splits() |
|
159
|
|
|
self.save_molecules(ms) |
|
160
|
|
|
self.save_targets(y) |
|
161
|
|
|
self.save_features(ms) |
|
162
|
|
|
|
|
163
|
|
|
@property |
|
164
|
|
|
def source_names(self): |
|
|
|
|
|
|
165
|
|
|
return self.feature_names + self.task_names |
|
166
|
|
|
|
|
167
|
|
|
@property |
|
168
|
|
|
def split_names(self): |
|
|
|
|
|
|
169
|
|
|
return self.splits |
|
170
|
|
|
|
|
171
|
|
|
def create_file(self, path): |
|
|
|
|
|
|
172
|
|
|
logger.info('Creating h5 file at %s...', self.output_path) |
|
173
|
|
|
self.data_file = h5py.File(path, 'w') |
|
|
|
|
|
|
174
|
|
|
return self.data_file |
|
175
|
|
|
|
|
176
|
|
|
def save_molecules(self, mols): |
|
177
|
|
|
|
|
178
|
|
|
""" Save the molecules to the data file. """ |
|
179
|
|
|
|
|
180
|
|
|
logger.info('Writing molecules to file...') |
|
181
|
|
|
logger.debug('Writing %s molecules to %s', len(mols), self.data_file.filename) |
|
182
|
|
|
with warnings.catch_warnings(): |
|
183
|
|
|
warnings.simplefilter('ignore') |
|
184
|
|
|
mols.to_hdf(self.data_file.filename, 'structure', **self.pytables_kws) |
|
185
|
|
|
mols.apply(lambda m: m.to_smiles().encode('utf-8')).to_hdf(self.data_file.filename, 'smiles') |
|
|
|
|
|
|
186
|
|
|
|
|
187
|
|
|
def save_frame(self, data, name, prefix='targets'): |
|
188
|
|
|
|
|
189
|
|
|
""" Save the a frame to the data file. """ |
|
190
|
|
|
|
|
191
|
|
|
logger.info('Writing %s', name) |
|
192
|
|
|
logger.debug('Writing data of shape %s to %s', data.shape, self.data_file.filename) |
|
193
|
|
|
|
|
194
|
|
|
with warnings.catch_warnings(): |
|
195
|
|
|
warnings.simplefilter('ignore') |
|
196
|
|
|
if len(data.shape) > 2: |
|
197
|
|
|
data = data.transpose(2, 1, 0) # panel serializes backwards for some reason... |
|
198
|
|
|
data.to_hdf(self.data_file.filename, |
|
199
|
|
|
key='/{prefix}/{name}'.format(prefix=prefix, name=name), |
|
200
|
|
|
**self.pytables_kws) |
|
201
|
|
|
|
|
202
|
|
|
if isinstance(data, pd.Series): |
|
203
|
|
|
self.data_file[name] = h5py.SoftLink('/{prefix}/{name}/values'.format(prefix=prefix, name=name)) |
|
|
|
|
|
|
204
|
|
|
self.data_file[name].dims[0].label = data.index.name |
|
205
|
|
|
|
|
206
|
|
|
elif isinstance(data, pd.DataFrame): |
|
207
|
|
|
self.data_file[name] = h5py.SoftLink('/{prefix}/{name}/block0_values'.format(prefix=prefix, name=name)) |
|
|
|
|
|
|
208
|
|
|
self.data_file[name].dims[0].label = data.index.name |
|
209
|
|
|
self.data_file[name].dims[1].label = data.columns.name |
|
210
|
|
|
|
|
211
|
|
|
elif isinstance(data, pd.Panel): |
|
212
|
|
|
self.data_file[name] = h5py.SoftLink('/{prefix}/{name}/block0_values'.format(prefix=prefix, name=name)) |
|
|
|
|
|
|
213
|
|
|
self.data_file[name].dims[0].label = data.minor_axis.name # as panel serializes backwards |
|
|
|
|
|
|
214
|
|
|
self.data_file[name].dims[1].label = data.major_axis.name |
|
215
|
|
|
self.data_file[name].dims[2].label = data.items.name |
|
216
|
|
|
|
|
217
|
|
|
def save_targets(self, y): |
|
|
|
|
|
|
218
|
|
|
|
|
219
|
|
|
self.save_frame(y, name='y', prefix='targets') |
|
220
|
|
|
|
|
221
|
|
|
def save_features(self, ms): |
|
|
|
|
|
|
222
|
|
|
|
|
223
|
|
|
""" Save all features for the dataset. """ |
|
224
|
|
|
logger.debug('Saving features') |
|
225
|
|
|
for feat in self.features: |
|
226
|
|
|
self._save_feature(ms, feat) |
|
227
|
|
|
|
|
228
|
|
|
def _save_feature(self, ms, feat): |
|
|
|
|
|
|
229
|
|
|
|
|
230
|
|
|
""" Calculate and save a feature to the data file. """ |
|
231
|
|
|
logger.info('Calculating %s', feat.key) |
|
232
|
|
|
|
|
233
|
|
|
fps = feat.fper.transform(ms) |
|
234
|
|
|
self.save_frame(fps, name=feat.key, prefix='feats') |
|
235
|
|
|
|
|
236
|
|
|
def save_splits(self): |
|
237
|
|
|
|
|
238
|
|
|
""" Save the splits to the data file. """ |
|
239
|
|
|
|
|
240
|
|
|
logger.info('Producing dataset splits...') |
|
241
|
|
|
for split in self.splits: |
|
242
|
|
|
split.save() |
|
243
|
|
|
split_dict = {split.name: split.to_dict() for split in self.splits} |
|
244
|
|
|
splits = H5PYDataset.create_split_array(split_dict) |
|
245
|
|
|
logger.debug('split: %s', splits) |
|
246
|
|
|
logger.info('Saving splits...') |
|
247
|
|
|
with warnings.catch_warnings(): |
|
248
|
|
|
warnings.simplefilter('ignore') |
|
249
|
|
|
self.data_file.attrs['split'] = splits |
|
250
|
|
|
|
|
251
|
|
|
@classmethod |
|
252
|
|
|
def convert(cls, **kwargs): |
|
|
|
|
|
|
253
|
|
|
kwargs.setdefault('directory', os.getcwd()) |
|
254
|
|
|
kwargs.setdefault('output_directory', os.getcwd()) |
|
255
|
|
|
|
|
256
|
|
|
return cls(**kwargs).output_path, |
|
257
|
|
|
|
|
258
|
|
|
@classmethod |
|
259
|
|
|
def fill_subparser(cls, subparser): |
|
|
|
|
|
|
260
|
|
|
return cls.convert |
|
261
|
|
|
|
The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:
If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.