-
Notifications
You must be signed in to change notification settings - Fork 0
/
inline_organic.py
3168 lines (2719 loc) · 108 KB
/
inline_organic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Future import
from __future__ import absolute_import, division, print_function
# Standard imports
import sys
import os
import subprocess
import re
from re import compile as _Re
import random
import csv
import dill as pickle
import gzip
import math
from math import exp, log
import random
from copy import deepcopy
from builtins import range
from collections import OrderedDict
import numpy as np
import pandas as pd
# RDKit imports
import rdkit
from rdkit import rdBase
import rdkit.Chem.AllChem as Chem
from rdkit.Chem import Crippen, MolFromSmiles, MolToSmiles, Descriptors
# PyMatGen imports
import pymatgen as mg
from pymatgen.symmetry.analyzer import PointGroupAnalyzer
#####################################################
# This built from the ORGANIC program of Aspuru-Guzik
# It has been only lightly modified by S. Ryno to
# increase generality and compatibility with more
# modern packages
#####################################################
###############
# GPU Utilities
###############
def run_command(cmd):
"""
Run terminal command and return output as string
"""
output = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]
return output.decode('ascii')
def list_available_gpus():
"""
Returns a list of the available GPU IDs and models
"""
output = run_command("nvidia-smi -L")
gpu_regex = re.compile(r"GPU (?P<gpu_id>\d+):")
result = []
for line in output.strip().split("\n"):
m = gpu_regex.match(line)
assert m, "Couldn't parse " + line
result.append(int(m.group("gpu_id")))
return result
def gpu_memory_map():
"""
Returns mapping of GPU IDs to currently allocated memory
"""
output = run_command("nvidia-smi")
gpu_output = output[output.find("GPU Memory"):]
memory_regex = re.compile(r"[|]\s+?(?P<gpu_id>\d+)\D+?(?P<pid>\d+).+[ ](?P<gpu_memory>\d+)MiB")
result = {gpu_id: 0 for gpu_id in list_available_gpus()}
for row in gpu_output.split("\n"):
m = memory_regex.search(row)
if not m:
continue
gpu_id = int(m.group("gpu_id"))
gpu_memory = int(m.group("gpu_memory"))
result[gpu_id] += gpu_memory
return result
def pick_gpu_lowest_memory():
"""
Returns the GPU ID with the current lowest allocated memory\
"""
memory_gpu_map = [(memory, gpu_id) for (gpu_id, memory) in gpu_memory_map().items()]
best_memory, best_gpu = sorted(memory_gpu_map)[0]
return best_gpu
# ML imports
# try:
# gpu_free_number = str(pick_gpu_lowest_memory())
# os.environ['CUDA_VISIBLE_DEVICES'] = '{}'.format(gpu_free_number)
# import tensorflow as tf
# config = tf.ConfigProto()
# config.gpu_options.allow_growth = True
# from keras import backend as K
# except Exception:
# import tensorflow as tf
# config = tf.ConfigProto()
# config.gpu_options.allow_growth = True
# from keras import backend as K
import tensorflow as tf
device_name = tf.test.gpu_device_name()
config = tf.ConfigProto(log_device_placement=True)
config.gpu_options.allow_growth = True
from keras import backend as K
from keras.layers import Dense, Dropout
from keras.models import Sequential, load_model
from keras.layers.normalization import BatchNormalization
from keras.callbacks import EarlyStopping
from keras_tqdm import TQDMCallback
from tensorflow.python.ops import tensor_array_ops, control_flow_ops
from tensorflow.contrib.rnn.python.ops import core_rnn_cell
from tensorflow import logging
from tqdm import tqdm
#############################################
# NN Metrics
# Class to handle Keras neural network models
#############################################
class KerasNN(object):
"""
Class for handling Keras neural network models
"""
def __init__(self, label, nBits=4096):
"""
Initializes Keras model
Arguments
--------------
- label: Identifies the property to be
predicted by the neural network.
- nBits: Refers to the number of bits in
which the Morgan fingerprints
are encoded. Defaults=4096
"""
self.label = label
self.graph = tf.Graph()
self.nBits = nBits
def predict(self, smiles, batch_size=100):
"""
Computes the predictions for a batch of molecules
Arguments
-----------
- smiles: Array or list containing the
SMILES representation of the molecules
- batch_size: Optional. Size of the batch
used for computing the properties
Returns
-----------
A list containing the predictions
"""
with self.graph.as_default():
input_x = self.computeFingerprints(smiles)
return self.model.predict(input_x, batch_size=batch_size)
def evaluate(self, train_x, train_y):
"""
Evaluates the accuracy of the method
Arguments
-----------
- train_x: Array or list containing the
SMILES representation of the molecules
- train_y: The real values of the desired
properties
Returns
-----------
Test loss
"""
with self.graph.as_default():
input_x = self.computeFingerprints(train_x)
return self.model.evaluate(input_x, train_y, verbose=0)
def load(self, file):
"""
Loads a previously trained model
Arguments
-----------
- file: A string pointing to the .h5 file
"""
with self.graph.as_default():
self.model = load_model(file)
def train(self, train_x, train_y, batch_size, nepochs, earlystopping=True, min_delta=0.001):
"""
Trains the model
The model is saved in the current directory under the name "label".h5
Arguments
-----------
- train_x: Array or list containing the
SMILES representation of the molecules
- train_y: The real values of the desired
properties
- batch_size: The size of the batch
- nepochs: The maximum number of epochs
- earlystopping: Boolean specifying whether early
stopping will be used or not. Default=True
- min_delta: If earlystopping is True, the variation
on the validation set's value which will trigger
the stopping
"""
with self.graph.as_default():
"""
Use a Sequential model with dropout rate of 0.2, 2 hidden
layers, and 1 output layer. All layers are full-connected
"""
self.model = Sequential()
self.model.add(Dropout(0.2, input_shape=(self.nBits,)))
self.model.add(BatchNormalization())
self.model.add(Dense(300, activation='relu', kernel_initializer='normal'))
self.model.add(Dense(300, activation='relu', kernel_initializer='normal'))
self.model.add(Dense(1, activation='linear', kernel_initializer='normal'))
self.model.compile(optimizer='adam', loss='mse')
input_x = self.computeFingerprints(train_x)
if earlystopping is True:
callbacks = [EarlyStopping(monitor='val_loss',
min_delta=min_delta,
patience=10,
verbose=0,
mode='auto'),
TQDMCallback()]
else:
callbacks = [TQDMCallback()]
self.model.fit(input_x, train_y,
shuffle=True,
epochs=nepochs,
batch_size=batch_size,
validation_split=0.1,
verbose=2,
callbacks=callbacks)
self.model.save('{}.h5'.format(self.label))
def computeFingerprints(self, smiles):
"""
Computes Morgan fingerprints using RDKit
Arguments
-----------
- smiles: An array or list of molecules in
the SMILES codification
Returns
-----------
A numpy array containing Morgan fingerprints
bitvectors
"""
if isinstance(smiles, str): # We need smiles as lists even if 1 smile
smiles = [smiles]
mols = [Chem.MolFromSmiles(smile) for smile in smiles]
fps = [Chem.GetMorganFingerprintAsBitVect(mol, 12, nBits=self.nBits) for mol in mols]
bitvectors = [self.fingerprintToBitVect(fp) for fp in fps]
return np.asarray(bitvectors)
def fingerprintToBitVect(self, fp):
"""
Transforms a Morgan fingerprint to a bit vector
Arguments
-----------
- fp: Morgan fingerprint
Returns
-----------
A bit vector
"""
return np.asarray([float(i) for i in fp])
#################
# Generator model
#################
class Generator(object):
"""
Class for the generative model
"""
def __init__(self, num_emb, batch_size, emb_dim, hidden_dim,
sequence_length, start_token, learning_rate=0.001,
reward_gamma=0.95, temperature=1.0, grad_clip=5.0):
"""
Sets parameters and defines the model architecture
"""
"""
Set specific parameters
"""
self.num_emb = num_emb
self.batch_size = batch_size
self.emb_dim = emb_dim
self.hidden_dim = hidden_dim
self.sequence_length = sequence_length
self.reward_gamma = reward_gamma
self.temperature = temperature
self.grad_clip = grad_clip
self.start_token = tf.constant([start_token] * self.batch_size, dtype=tf.int32)
self.learning_rate = tf.Variable(float(learning_rate), trainable=False)
"""
Set important internal variables
"""
self.g_params = [] # This list will be updated with LSTM's parameters
self.expected_reward = tf.Variable(tf.zeros([self.sequence_length]))
self.x = tf.placeholder( # true data, not including start token
tf.int32, shape=[self.batch_size, self.sequence_length])
self.rewards = tf.placeholder( # rom rollout policy and discriminator
tf.float32, shape=[self.batch_size, self.sequence_length])
"""
Define generative model
"""
with tf.variable_scope('generator'):
self.g_embeddings = tf.Variable(
self.init_matrix([self.num_emb, self.emb_dim]))
self.g_params.append(self.g_embeddings)
self.g_recurrent_unit = self.create_recurrent_unit(
self.g_params) # maps h_tm1 to h_t for generator
self.g_output_unit = self.create_output_unit(
self.g_params) # maps h_t to o_t (output token logits)
"""
Process the batches
"""
with tf.device("/cpu:0"):
# with tf.device("/device:GPU:0"):
inputs = tf.split(axis=1, num_or_size_splits=self.sequence_length,
value=tf.nn.embedding_lookup(self.g_embeddings,
self.x))
self.processed_x = tf.stack( # seq_length x batch_size x emb_dim
[tf.squeeze(input_, [1]) for input_ in inputs])
self.h0 = tf.zeros([self.batch_size, self.hidden_dim])
self.h0 = tf.stack([self.h0, self.h0])
"""
Generative process
"""
gen_o = tensor_array_ops.TensorArray(dtype=tf.float32,
size=self.sequence_length,
dynamic_size=False,
infer_shape=True)
gen_x = tensor_array_ops.TensorArray(dtype=tf.int32,
size=self.sequence_length,
dynamic_size=False,
infer_shape=True)
def _g_recurrence(i, x_t, h_tm1, gen_o, gen_x):
h_t = self.g_recurrent_unit(x_t, h_tm1) # hidden_memory_tuple
o_t = self.g_output_unit(h_t) # batch x vocab , logits not prob
log_prob = tf.log(tf.nn.softmax(o_t))
next_token = tf.cast(tf.reshape(tf.multinomial(
log_prob, 1), [self.batch_size]), tf.int32)
x_tp1 = tf.nn.embedding_lookup(
self.g_embeddings, next_token) # batch x emb_dim
gen_o = gen_o.write(i, tf.reduce_sum(tf.multiply(tf.one_hot(next_token, self.num_emb, 1.0, 0.0),
tf.nn.softmax(o_t)), 1)) # [batch_size] , prob
gen_x = gen_x.write(i, next_token) # indices, batch_size
return i + 1, x_tp1, h_t, gen_o, gen_x
_, _, _, self.gen_o, self.gen_x = control_flow_ops.while_loop(
cond=lambda i, _1, _2, _3, _4: i < self.sequence_length,
body=_g_recurrence,
loop_vars=(tf.constant(0, dtype=tf.int32),
tf.nn.embedding_lookup(self.g_embeddings, self.start_token),
self.h0, gen_o, gen_x))
self.gen_x = self.gen_x.stack() # seq_length x batch_size
self.gen_x = tf.transpose(self.gen_x, perm=[1, 0]) # batch_size x seq_length
"""
Pretraining
"""
g_predictions = tensor_array_ops.TensorArray(dtype=tf.float32, size=self.sequence_length,
dynamic_size=False, infer_shape=True)
g_logits = tensor_array_ops.TensorArray(dtype=tf.float32, size=self.sequence_length,
dynamic_size=False, infer_shape=True)
ta_emb_x = tensor_array_ops.TensorArray(dtype=tf.float32, size=self.sequence_length)
ta_emb_x = ta_emb_x.unstack(self.processed_x)
def _pretrain_recurrence(i, x_t, h_tm1, g_predictions, g_logits):
h_t = self.g_recurrent_unit(x_t, h_tm1)
o_t = self.g_output_unit(h_t)
g_predictions = g_predictions.write(
i, tf.nn.softmax(o_t)) # batch x vocab_size
g_logits = g_logits.write(i, o_t) # batch x vocab_size
x_tp1 = ta_emb_x.read(i)
return i + 1, x_tp1, h_t, g_predictions, g_logits
_, _, _, self.g_predictions, self.g_logits = control_flow_ops.while_loop(
cond=lambda i, _1, _2, _3, _4: i < self.sequence_length,
body=_pretrain_recurrence,
loop_vars=(tf.constant(0, dtype=tf.int32),tf.nn.embedding_lookup(
self.g_embeddings, self.start_token),
self.h0, g_predictions, g_logits))
self.g_predictions = tf.transpose(
self.g_predictions.stack(), perm=[1, 0, 2]) # batch_size x seq_length x vocab_size
self.g_logits = tf.transpose(
self.g_logits.stack(), perm=[1, 0, 2]) # batch_size x seq_length x vocab_size
self.pretrain_loss = -tf.reduce_sum(
tf.one_hot(tf.to_int32(tf.reshape(self.x, [-1])), self.num_emb, 1.0, 0.0) * tf.log(
tf.clip_by_value(tf.reshape(self.g_predictions, [-1, self.num_emb]), 1e-20, 1.0))) / (self.sequence_length * self.batch_size)
pretrain_opt = self.g_optimizer(self.learning_rate) # training updates
self.pretrain_grad, _ = tf.clip_by_global_norm(tf.gradients(self.pretrain_loss, self.g_params),
self.grad_clip)
self.pretrain_updates = pretrain_opt.apply_gradients(zip(self.pretrain_grad, self.g_params))
"""
Unsupervised Training
"""
self.g_loss = -tf.reduce_sum(
tf.reduce_sum(
tf.one_hot(tf.to_int32(tf.reshape(self.x, [-1])), self.num_emb, 1.0, 0.0) * tf.log(
tf.clip_by_value(tf.reshape(self.g_predictions, [-1, self.num_emb]), 1e-20, 1.0)), 1)
* tf.reshape(self.rewards, [-1]))
g_opt = self.g_optimizer(self.learning_rate)
self.g_grad, _ = tf.clip_by_global_norm(
tf.gradients(self.g_loss, self.g_params), self.grad_clip)
self.g_updates = g_opt.apply_gradients(zip(self.g_grad, self.g_params))
def generate(self, session):
"""Generates a batch of samples"""
outputs = session.run([self.gen_x])
return outputs[0]
def pretrain_step(self, session, x):
"""Performs a pretraining step on the generator"""
outputs = session.run([self.pretrain_updates, self.pretrain_loss,
self.g_predictions], feed_dict={self.x: x})
return outputs
def generator_step(self, sess, samples, rewards):
"""Performs a training step on the generator"""
feed = {self.x: samples, self.rewards: rewards}
_, g_loss = sess.run([self.g_updates, self.g_loss], feed_dict=feed)
return g_loss
def init_matrix(self, shape):
"""Returns a normally initialized matrix of a given shape"""
return tf.random_normal(shape, stddev=0.1)
def init_vector(self, shape):
"""Returns a vector of zeros of a given shape"""
return tf.zeros(shape)
def create_recurrent_unit(self, params):
"""Defines the recurrent process in the LSTM"""
# Weights and Bias for input and hidden tensor
self.Wi = tf.Variable(self.init_matrix(
[self.emb_dim, self.hidden_dim]))
self.Ui = tf.Variable(self.init_matrix(
[self.emb_dim, self.hidden_dim]))
self.bi = tf.Variable(self.init_matrix([self.hidden_dim]))
self.Wf = tf.Variable(self.init_matrix(
[self.emb_dim, self.hidden_dim]))
self.Uf = tf.Variable(self.init_matrix(
[self.hidden_dim, self.hidden_dim]))
self.bf = tf.Variable(self.init_matrix([self.hidden_dim]))
self.Wog = tf.Variable(self.init_matrix(
[self.emb_dim, self.hidden_dim]))
self.Uog = tf.Variable(self.init_matrix(
[self.hidden_dim, self.hidden_dim]))
self.bog = tf.Variable(self.init_matrix([self.hidden_dim]))
self.Wc = tf.Variable(self.init_matrix(
[self.emb_dim, self.hidden_dim]))
self.Uc = tf.Variable(self.init_matrix(
[self.hidden_dim, self.hidden_dim]))
self.bc = tf.Variable(self.init_matrix([self.hidden_dim]))
params.extend([
self.Wi, self.Ui, self.bi,
self.Wf, self.Uf, self.bf,
self.Wog, self.Uog, self.bog,
self.Wc, self.Uc, self.bc])
def unit(x, hidden_memory_tm1):
previous_hidden_state, c_prev = tf.unstack(hidden_memory_tm1)
# Input Gate
i = tf.sigmoid(
tf.matmul(x, self.Wi) +
tf.matmul(previous_hidden_state, self.Ui) + self.bi
)
# Forget Gate
f = tf.sigmoid(
tf.matmul(x, self.Wf) +
tf.matmul(previous_hidden_state, self.Uf) + self.bf
)
# Output Gate
o = tf.sigmoid(
tf.matmul(x, self.Wog) +
tf.matmul(previous_hidden_state, self.Uog) + self.bog
)
# New Memory Cell
c_ = tf.nn.tanh(
tf.matmul(x, self.Wc) +
tf.matmul(previous_hidden_state, self.Uc) + self.bc
)
# Final Memory cell
c = f * c_prev + i * c_
# Current Hidden state
current_hidden_state = o * tf.nn.tanh(c)
return tf.stack([current_hidden_state, c])
return unit
def create_output_unit(self, params):
"""Defines the output part of the LSTM."""
self.Wo = tf.Variable(self.init_matrix(
[self.hidden_dim, self.num_emb]))
self.bo = tf.Variable(self.init_matrix([self.num_emb]))
params.extend([self.Wo, self.bo])
def unit(hidden_memory_tuple):
hidden_state, c_prev = tf.unstack(hidden_memory_tuple)
# hidden_state : batch x hidden_dim
logits = tf.matmul(hidden_state, self.Wo) + self.bo
# output = tf.nn.softmax(logits)
return logits
return unit
def g_optimizer(self, *args, **kwargs):
"""Sets the optimizer."""
return tf.train.AdamOptimizer(*args, **kwargs)
#################
# Rollout model
#################
class Rollout(object):
"""
Class for the Rollout policy model
"""
def __init__(self, lstm, update_rate, pad_num):
"""
Sets parameters and defines the model architecture
"""
self.lstm = lstm
self.update_rate = update_rate
self.pad_num = pad_num
self.num_emb = self.lstm.num_emb
self.batch_size = self.lstm.batch_size
self.emb_dim = self.lstm.emb_dim
self.hidden_dim = self.lstm.hidden_dim
self.sequence_length = self.lstm.sequence_length
self.start_token = tf.identity(self.lstm.start_token)
self.learning_rate = self.lstm.learning_rate
self.g_embeddings = tf.identity(self.lstm.g_embeddings)
# maps h_tm1 to h_t for generator
self.g_recurrent_unit = self.create_recurrent_unit()
# maps h_t to o_t (output token logits)
self.g_output_unit = self.create_output_unit()
##############################
# start placeholder definition
##############################
self.x = tf.placeholder(tf.int32, shape=[self.batch_size, self.sequence_length])
self.given_num = tf.placeholder(tf.int32)
# sequence of indices of generated data generated by generator, not
# including start token
# processed for batch
with tf.device("/cpu:0"):
# with tf.device("/device:GPU:0"):
inputs = tf.split(axis=1, num_or_size_splits=self.sequence_length,
value=tf.nn.embedding_lookup(self.g_embeddings, self.x))
self.processed_x = tf.stack(
[tf.squeeze(input_, [1]) for input_ in inputs]) # seq_length x batch_size x emb_dim
ta_emb_x = tensor_array_ops.TensorArray(
dtype=tf.float32, size=self.sequence_length)
ta_emb_x = ta_emb_x.unstack(self.processed_x)
ta_x = tensor_array_ops.TensorArray(
dtype=tf.int32, size=self.sequence_length)
ta_x = ta_x.unstack(tf.transpose(self.x, perm=[1, 0]))
##############################
# end placeholder definition
##############################
self.h0 = tf.zeros([self.batch_size, self.hidden_dim])
self.h0 = tf.stack([self.h0, self.h0])
gen_x = tensor_array_ops.TensorArray(dtype=tf.int32, size=self.sequence_length,
dynamic_size=False, infer_shape=True)
def _g_recurrence_1(i, x_t, h_tm1, given_num, gen_x):
h_t = self.g_recurrent_unit(x_t, h_tm1) # hidden_memory_tuple
x_tp1 = ta_emb_x.read(i)
gen_x = gen_x.write(i, ta_x.read(i))
return i + 1, x_tp1, h_t, given_num, gen_x
def _g_recurrence_2(i, x_t, h_tm1, given_num, gen_x):
h_t = self.g_recurrent_unit(x_t, h_tm1) # hidden_memory_tuple
o_t = self.g_output_unit(h_t) # batch x vocab , logits not prob
log_prob = tf.log(tf.nn.softmax(o_t))
next_token = tf.cast(tf.reshape(tf.multinomial(
log_prob, 1), [self.batch_size]), tf.int32)
x_tp1 = tf.nn.embedding_lookup(
self.g_embeddings, next_token) # batch x emb_dim
gen_x = gen_x.write(i, next_token) # indices, batch_size
return i + 1, x_tp1, h_t, given_num, gen_x
i, x_t, h_tm1, given_num, self.gen_x = control_flow_ops.while_loop(
cond=lambda i, _1, _2, given_num, _4: i < given_num,
body=_g_recurrence_1,
loop_vars=(tf.constant(0, dtype=tf.int32),
tf.nn.embedding_lookup(self.g_embeddings, self.start_token), self.h0, self.given_num, gen_x))
_, _, _, _, self.gen_x = control_flow_ops.while_loop(
cond=lambda i, _1, _2, _3, _4: i < self.sequence_length,
body=_g_recurrence_2,
loop_vars=(i, x_t, h_tm1, given_num, self.gen_x))
self.gen_x = self.gen_x.stack() # seq_length x batch_size
# batch_size x seq_length
self.gen_x = tf.transpose(self.gen_x, perm=[1, 0])
def get_reward(self, sess, input_x, rollout_num, cnn, reward_fn=None, D_weight=1):
"""
Calculates the rewards for a list of SMILES strings
"""
reward_weight = 1 - D_weight
rewards = []
for i in range(rollout_num):
already = []
for given_num in range(1, self.sequence_length):
feed = {self.x: input_x, self.given_num: given_num}
outputs = sess.run([self.gen_x], feed)
generated_seqs = outputs[0] # batch_size x seq_length
gind = np.array(range(len(generated_seqs)))
feed = {cnn.input_x: generated_seqs,
cnn.dropout_keep_prob: 1.0}
ypred_for_auc = sess.run(cnn.ypred_for_auc, feed)
ypred = np.array([item[1] for item in ypred_for_auc])
if reward_fn:
ypred = D_weight * ypred
# Delete sequences that are already finished,
# and add their rewards
for k, r in reversed(already):
generated_seqs = np.delete(generated_seqs, k, 0)
gind = np.delete(gind, k, 0)
ypred[k] += reward_weight * r
# If there are still seqs, calculate rewards
if generated_seqs.size:
rew = reward_fn(generated_seqs)
# Add the just calculated rewards
for k, r in zip(gind, rew):
ypred[k] += reward_weight * r
# Choose the seqs finished in the last iteration
for j, k in enumerate(gind):
if input_x[k][given_num] == self.pad_num and input_x[k][given_num-1] == self.pad_num:
already.append((k, rew[j]))
already = sorted(already, key=lambda el: el[0])
if i == 0:
rewards.append(ypred)
else:
rewards[given_num - 1] += ypred
# Last char reward
feed = {cnn.input_x: input_x, cnn.dropout_keep_prob: 1.0}
ypred_for_auc = sess.run(cnn.ypred_for_auc, feed)
if reward_fn:
ypred = D_weight * np.array([item[1]
for item in ypred_for_auc])
ypred += reward_weight * reward_fn(input_x)
else:
ypred = np.array([item[1] for item in ypred_for_auc])
if i == 0:
rewards.append(ypred)
else:
rewards[-1] += ypred
rewards = np.transpose(np.array(rewards)) / \
(1.0 * rollout_num) # batch_size x seq_length
return rewards
def create_recurrent_unit(self):
"""Defines the recurrent process in the LSTM"""
# Weights and Bias for input and hidden tensor
self.Wi = tf.identity(self.lstm.Wi)
self.Ui = tf.identity(self.lstm.Ui)
self.bi = tf.identity(self.lstm.bi)
self.Wf = tf.identity(self.lstm.Wf)
self.Uf = tf.identity(self.lstm.Uf)
self.bf = tf.identity(self.lstm.bf)
self.Wog = tf.identity(self.lstm.Wog)
self.Uog = tf.identity(self.lstm.Uog)
self.bog = tf.identity(self.lstm.bog)
self.Wc = tf.identity(self.lstm.Wc)
self.Uc = tf.identity(self.lstm.Uc)
self.bc = tf.identity(self.lstm.bc)
def unit(x, hidden_memory_tm1):
previous_hidden_state, c_prev = tf.unstack(hidden_memory_tm1)
# Input Gate
i = tf.sigmoid(
tf.matmul(x, self.Wi) +
tf.matmul(previous_hidden_state, self.Ui) + self.bi
)
# Forget Gate
f = tf.sigmoid(
tf.matmul(x, self.Wf) +
tf.matmul(previous_hidden_state, self.Uf) + self.bf
)
# Output Gate
o = tf.sigmoid(
tf.matmul(x, self.Wog) +
tf.matmul(previous_hidden_state, self.Uog) + self.bog
)
# New Memory Cell
c_ = tf.nn.tanh(
tf.matmul(x, self.Wc) +
tf.matmul(previous_hidden_state, self.Uc) + self.bc
)
# Final Memory cell
c = f * c_prev + i * c_
# Current Hidden state
current_hidden_state = o * tf.nn.tanh(c)
return tf.stack([current_hidden_state, c])
return unit
def update_recurrent_unit(self):
"""
Updates the weights and biases of the rollout's LSTM
recurrent unit following the results of the training
"""
# Weights and Bias for input and hidden tensor
self.Wi = self.update_rate * self.Wi + \
(1 - self.update_rate) * tf.identity(self.lstm.Wi)
self.Ui = self.update_rate * self.Ui + \
(1 - self.update_rate) * tf.identity(self.lstm.Ui)
self.bi = self.update_rate * self.bi + \
(1 - self.update_rate) * tf.identity(self.lstm.bi)
self.Wf = self.update_rate * self.Wf + \
(1 - self.update_rate) * tf.identity(self.lstm.Wf)
self.Uf = self.update_rate * self.Uf + \
(1 - self.update_rate) * tf.identity(self.lstm.Uf)
self.bf = self.update_rate * self.bf + \
(1 - self.update_rate) * tf.identity(self.lstm.bf)
self.Wog = self.update_rate * self.Wog + \
(1 - self.update_rate) * tf.identity(self.lstm.Wog)
self.Uog = self.update_rate * self.Uog + \
(1 - self.update_rate) * tf.identity(self.lstm.Uog)
self.bog = self.update_rate * self.bog + \
(1 - self.update_rate) * tf.identity(self.lstm.bog)
self.Wc = self.update_rate * self.Wc + \
(1 - self.update_rate) * tf.identity(self.lstm.Wc)
self.Uc = self.update_rate * self.Uc + \
(1 - self.update_rate) * tf.identity(self.lstm.Uc)
self.bc = self.update_rate * self.bc + \
(1 - self.update_rate) * tf.identity(self.lstm.bc)
def unit(x, hidden_memory_tm1):
previous_hidden_state, c_prev = tf.unstack(hidden_memory_tm1)
# Input Gate
i = tf.sigmoid(
tf.matmul(x, self.Wi) +
tf.matmul(previous_hidden_state, self.Ui) + self.bi
)
# Forget Gate
f = tf.sigmoid(
tf.matmul(x, self.Wf) +
tf.matmul(previous_hidden_state, self.Uf) + self.bf
)
# Output Gate
o = tf.sigmoid(
tf.matmul(x, self.Wog) +
tf.matmul(previous_hidden_state, self.Uog) + self.bog
)
# New Memory Cell
c_ = tf.nn.tanh(
tf.matmul(x, self.Wc) +
tf.matmul(previous_hidden_state, self.Uc) + self.bc
)
# Final Memory cell
c = f * c_prev + i * c_
# Current Hidden state
current_hidden_state = o * tf.nn.tanh(c)
return tf.stack([current_hidden_state, c])
return unit
def create_output_unit(self):
"""
Defines the output process in the LSTM
"""
self.Wo = tf.identity(self.lstm.Wo)
self.bo = tf.identity(self.lstm.bo)
def unit(hidden_memory_tuple):
hidden_state, c_prev = tf.unstack(hidden_memory_tuple)
# hidden_state : batch x hidden_dim
logits = tf.matmul(hidden_state, self.Wo) + self.bo
# output = tf.nn.softmax(logits)
return logits
return unit
def update_output_unit(self):
"""
Updates the weights and biases of the rollout's LSTM
output unit following the results of the training
"""
self.Wo = self.update_rate * self.Wo + \
(1 - self.update_rate) * tf.identity(self.lstm.Wo)
self.bo = self.update_rate * self.bo + \
(1 - self.update_rate) * tf.identity(self.lstm.bo)
def unit(hidden_memory_tuple):
hidden_state, c_prev = tf.unstack(hidden_memory_tuple)
# hidden_state : batch x hidden_dim
logits = tf.matmul(hidden_state, self.Wo) + self.bo
# output = tf.nn.softmax(logits)
return logits
return unit
def update_params(self):
"""
Updates all parameters in the rollout's LSTM
"""
self.g_embeddings = tf.identity(self.lstm.g_embeddings)
self.g_recurrent_unit = self.update_recurrent_unit()
self.g_output_unit = self.update_output_unit()
################################
# Mol Methods
# Methods for SMILES parsing
# and molecular metrics handling
################################
#########
# DATA IO
#########
def read_smi(filename):
"""
Reads SMILES from a .smi file
Arguments
-----------
- filename: String pointing to the .smi file
Returns
-----------
- List of SMILES strings
"""
with open(filename) as file:
smiles = file.readlines()
smiles = [i.strip() for i in smiles]
return smiles
def read_smiles_csv(filename):
"""
Reads SMILES from a .csv file
Arguments
-----------
- filename: String pointing to the .csv file
Returns
-----------
- List of SMILES strings
Note
-----------
This function will assume that the SMILES are
in column 0.
"""
with open(filename) as file:
reader = csv.reader(file)
smiles_idx = next(reader).index("smiles")
data = [row[smiles_idx] for row in reader]
return data
def load_train_data(filename):
"""
Loads training data from a .csv or .smi file
Arguments
-----------
- filename: String pointing to the .csv or .smi file
"""
ext = filename.split(".")[-1]
if ext == 'csv':
return read_smiles_csv(filename)
if ext == 'smi':
return read_smi(filename)
else:
raise ValueError('data is not smi or csv!')
return
def save_smi(name, smiles):
"""
Saves SMILES data as a .smi file
Arguments
-----------
- filename: String pointing to the .smi file
- smiles: List of SMILES strings to be saved
"""
if not os.path.exists('epoch_data'):
os.makedirs('epoch_data')
smi_file = os.path.join('epoch_data', "{}.smi".format(name))
with open(smi_file, 'w') as afile:
afile.write('\n'.join(smiles))
return
########################
# Mathematical Utilities
########################
def checkarray(x):
"""
Checks if data is an array and not a single value
"""
if type(x) == np.ndarray or type(x) == list:
if x.size == 1:
return False
else:
return True
else:
return False
def gauss_remap(x, x_mean, x_std):
"""
Remaps a given value to a gaussian distribution
Arguments
-----------
- x: Value to be remapped
- x_mean: Mean of the distribution
- x_std: Standard deviation of the distribution
"""
return np.exp(-(x - x_mean)**2 / (x_std**2))
def remap(x, x_min, x_max):
"""
Remaps a given value to [0, 1]
Arguments
-----------
- x: Value to be remapped