-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathuncertainty_guided_optimization.py
180 lines (162 loc) · 14.7 KB
/
uncertainty_guided_optimization.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
import os,sys
import numpy as np
import pandas as pd
import json
import pickle as pkl
import argparse
import time
from rdkit import RDLogger
import torch
from JTVAE.fast_jtnn import *
from utils import optimization_utils as ou
lg = RDLogger.logger()
lg.setLevel(RDLogger.CRITICAL)
path = os.path.abspath(__file__)
dir_path = os.path.dirname(path)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if __name__=="__main__":
parser = argparse.ArgumentParser(description='Agument parser')
parser.add_argument('--experiment_name', default="20210101", type=str, help='Name of experiment log file')
parser.add_argument('--target_property', default='final_logP', type=str, help='Black box objective to optimize (eg., final_logP)')
parser.add_argument('--model_type', default='JTVAE', type=str, help='CharVAE|JTVAE')
parser.add_argument('--optimization_method', default=None, type=str, help='Method to optimize objects: [gradient_ascent|bayesian_optimization]')
parser.add_argument('--batch_size', default=128, type=int, help='Batch size')
parser.add_argument('--mode_generation_starting_points', default="random", type=str, help='Method to generate starting points [random|low_property_objects]')
parser.add_argument('--starting_property_upper_bound', default=None, type=float, help='Property upper bound when selecting starting positions [low_property_objects]')
parser.add_argument('--num_starting_points', default=1000, type=int, help='Number of starting points for search')
parser.add_argument('--GA_number_optimization_steps', default=None, type=int, help='Number of gradient steps during optimization')
parser.add_argument('--GA_alpha', default=None, type=float, help='Coefficient scaling gradient step during gradient ascent')
parser.add_argument('--GA_uncertainty_threshold', default=None, type=str, help='Uncertainty upper bound (passed as percentile of train values) [No_constraint|max|P99|P95|P90]')
parser.add_argument('--GA_keep_all_generated', default=False, action='store_true', help='Whether to do stats on all generated objects Vs just last set obtained (GA)')
parser.add_argument('--BO_number_objects_generated', default=None, type=int, help='Number of objects generated by Bayesian optimization')
parser.add_argument('--BO_uncertainty_mode', default=None, type=str, help='Mode to include uncertainty in BO [Uncertainty_censoring|Penalized_objective]')
parser.add_argument('--BO_uncertainty_threshold', default=None, type=str, help='Uncertainty upper bound (passed as percentile of train values) [No_constraint|max|P99|P95|P90]')
parser.add_argument('--BO_uncertainty_coeff', default=None, type=float, help='Uncertainty penalty coeff in surrogate model')
parser.add_argument('--BO_abs_bound', default=None, type=float, help='Bounds of space to search for new points')
parser.add_argument('--BO_acquisition_function', default=None, type=str, help='Type of acquisition function')
parser.add_argument('--BO_default_value_invalid', default=None, type=float, help='Imputation in BO when generating an invalid molecule')
parser.add_argument('--decoder_uncertainty_method', default="MI_Importance_Sampling", type=str, help='Method to estimate uncertainty [MI_Importance_sampling, NLL_prior]')
parser.add_argument('--decoder_num_sampled_models', default=10, type=int, help='Number of samples from model parameters')
parser.add_argument('--decoder_num_sampled_outcomes', default=40, type=int, help='Number of sequences sampled to estimate decooder uncertainty')
parser.add_argument('--model_checkpoint', default=None, type=str, help='Checkpoint of PVAE to be used')
parser.add_argument('--vocab_path', default=None, type=str, help='Path to vocab to be used')
parser.add_argument('--model_decoding_mode', default=None, type=str, help='Method to decode from latent [topk|max|sample]')
parser.add_argument('--model_decoding_topk_value', default=None, type=int, help='Number of elements considered in topk decoding approach')
parser.add_argument('--seed', default=0, type=int, help='Random seed for reproducibility')
args = parser.parse_args()
torch.manual_seed(args.seed)
model_path = os.path.dirname(args.model_checkpoint)
if args.model_type=='JTVAE':
vocab = [x.strip("\r\n ") for x in open(args.vocab_path)]
vocab = Vocab(vocab)
params = json.load(open(model_path+os.sep+"parameters.json","r"))
if 'prop' not in params.keys():
model = JTNNVAE(vocab=vocab, **params)
else:
model = JTNNVAE_prop(vocab=vocab, **params)
dict_buffer = torch.load(args.model_checkpoint)
model.load_state_dict(dict_buffer)
model = model.to(device)
with open(dir_path+os.sep+'JTVAE/data/zinc/train.txt') as f:
train_dataset = [line.strip("\r\n ").split()[0] for line in f]
with open(dir_path+os.sep+'JTVAE/data/zinc/test.txt') as f:
test_dataset = [line.strip("\r\n ").split()[0] for line in f]
hidden_dim = model.latent_size*2
elif args.model_type=='CharVAE':
pass
result_folder = dir_path+os.sep+'results/optimization'
file_name = str(args.model_type) +'_'+ args.mode_generation_starting_points +"_"+ args.optimization_method + "_" + args.decoder_uncertainty_method + "_" + args.experiment_name + '_zdim_'+ str(hidden_dim)
if args.optimization_method == "bayesian_optimization":
run_parameters = '_acq_' + str(args.BO_acquisition_function) + '_Bound_'+str(args.BO_abs_bound)+ '_UncCo_' + str(args.BO_uncertainty_threshold)
elif args.optimization_method == "gradient_ascent":
run_parameters = '_steps_' + str(args.GA_number_optimization_steps) + '_alpha_' + str(args.GA_alpha) + '_UB_' + str(args.GA_uncertainty_threshold)
file_name = result_folder+os.sep+file_name+run_parameters
ou.log_stats(file_name=file_name, stats=str(args), log_entry="Passed in arguments")
print("Sample starting positions")
starting_objects_latent_embeddings, starting_objects_properties, starting_objects_smiles = ou.starting_objects_latent_embeddings(
model=model,
data=train_dataset,
mode=args.mode_generation_starting_points,
num_objects_to_select=args.num_starting_points,
batch_size=args.batch_size,
property_upper_bound=args.starting_property_upper_bound,
model_type=args.model_type)
print("Shape of starting_objects_latent_embeddings: "+ str(starting_objects_latent_embeddings.shape))
print("Perform optimization in latent space")
start_time=time.time()
if args.optimization_method == "gradient_ascent":
generated_objects_list = ou.gradient_ascent_optimization(
model=model,
starting_objects_latent_embeddings=starting_objects_latent_embeddings,
number_gradient_steps=args.GA_number_optimization_steps,
uncertainty_decoder_method=args.decoder_uncertainty_method,
num_sampled_models=args.decoder_num_sampled_models,
num_sampled_outcomes=args.decoder_num_sampled_outcomes,
model_decoding_mode=args.model_decoding_mode,
model_decoding_topk_value=args.model_decoding_topk_value,
alpha=args.GA_alpha,
normalize_gradients=True,
batch_size=args.batch_size,
uncertainty_threshold=args.GA_uncertainty_threshold,
keep_all_generated=args.GA_keep_all_generated,
model_type=args.model_type
)
elif args.optimization_method == "bayesian_optimization":
generated_objects_list, _ = ou.bayesian_optimization(model,
starting_objects_latent_embeddings=starting_objects_latent_embeddings,
starting_objects_properties=starting_objects_properties,
number_BO_steps=args.BO_number_objects_generated,
BO_uncertainty_mode=args.BO_uncertainty_mode,
BO_uncertainty_threshold=args.BO_uncertainty_threshold,
BO_uncertainty_coeff=args.BO_uncertainty_coeff,
BO_acquisition_function=args.BO_acquisition_function,
BO_default_value_invalid=args.BO_default_value_invalid,
model_decoding_mode=args.model_decoding_mode,
model_decoding_topk_value=args.model_decoding_topk_value,
uncertainty_decoder_method=args.decoder_uncertainty_method,
num_sampled_models=args.decoder_num_sampled_models,
num_sampled_outcomes = args.decoder_num_sampled_outcomes,
min_bound=-args.BO_abs_bound, max_bound = args.BO_abs_bound,
batch_size=args.batch_size,
generation_timout_seconds=600,
model_type=args.model_type
)
end_time=time.time()
duration=end_time-start_time
print("Log statistics optimization")
with open(file_name, "a+") as logs_file:
logs_file.write("#"*150+"\n")
logs_file.write("Stats for starting molecules\n")
logs_file.write("#"*150+"\n")
logs_file.write("\n")
train_data_smiles = ou.convert_tensors_to_smiles(train_dataset, model.params.indices_char) if args.model_type=="CharVAE" else train_dataset
starting_objects_stats = ou.assessment_generated_objects(starting_objects_smiles, model_training_data=train_data_smiles, prop=args.target_property)
starting_objects_stats.log_all_stats_generated_objects(file_name)
with open(file_name, "a+") as logs_file:
logs_file.write("\n\n")
logs_file.write("#"*150+"\n")
logs_file.write("Stats for generated molecules\n")
logs_file.write("#"*150+"\n")
logs_file.write("\n\n")
logs_file.write("Number of new objects generated: "+str(len(generated_objects_list))+"\n")
ou.log_stats(file_name=file_name, stats=str(generated_objects_list[:10]), log_entry="First 10 objects generated:")
generated_objects_stats = ou.assessment_generated_objects(generated_objects_list, model_training_data=train_data_smiles, prop=args.target_property)
final_results = generated_objects_stats.log_all_stats_generated_objects(file_name)
db_filename = result_folder+os.sep+'All_optimization_results.txt'
with open(db_filename, "a+") as f:
if not os.path.isfile(db_filename) or os.stat(db_filename).st_size == 0:
header = "checkpoint_name,experiment_name,seed,optimization_method,subset,decoder_uncertainty_method,decoder_num_sampled_models,decoder_num_sampled_outcomes,BO_abs_bound,BO_uncertainty_threshold,BO_uncertainty_coeff,BO_number_objects_generated,z_dim,run_parameters,\
uncertainty_decoder_upper_bound,number_optimization_steps,alpha,top1_prop,top2_prop,top3_prop,top4_prop,top5_prop,prop_all,validity_all,unicity_all,novelty_all,quality_all,qed_all,prop_top10,unicity_top10,novelty_top10,quality_top10,qed_top10,\
prop_top50,property_all_qual,property_top1_qual,property_top2_qual,property_top3_qual,property_top4_qual,property_top5_qual,property_top6_qual,property_top7_qual,property_top8_qual,property_top9_qual,property_top10_qual,property_top5avg_qual,\
property_top10avg_qual,property_top50avg_qual,qed_all_qual,qed_top10_qual,duration"
f.write(header+"\n")
res = ','.join([str(x) for x in [args.model_checkpoint, args.experiment_name, args.seed, args.optimization_method, "all", args.decoder_uncertainty_method, args.decoder_num_sampled_models, args.decoder_num_sampled_outcomes, args.BO_abs_bound, args.BO_uncertainty_threshold, args.BO_uncertainty_coeff, args.BO_number_objects_generated, hidden_dim,\
run_parameters, args.GA_uncertainty_threshold, args.GA_number_optimization_steps, args.GA_alpha, final_results['top1'],final_results['top2'],final_results['top3'],\
final_results['top4'],final_results['top5'],final_results['target_property_all'],final_results['validity_all'], final_results['unicity_all'], final_results['novelty_all'], final_results['quality_all'], final_results['qed_all'],\
final_results['target_property_top10'], final_results['unicity_top10'], final_results['novelty_top10'], final_results['quality_top10'], final_results['qed_top10'],final_results['target_property_top50'],\
final_results['property_all_qual'], final_results['property_top1_qual'], final_results['property_top2_qual'], final_results['property_top3_qual'], final_results['property_top4_qual'], final_results['property_top5_qual'], final_results['property_top6_qual'], final_results['property_top7_qual'],\
final_results['property_top8_qual'], final_results['property_top9_qual'], final_results['property_top10_qual'], final_results['property_top5avg_qual'], final_results['property_top10avg_qual'],\
final_results['property_top50avg_qual'],final_results['qed_all_qual'], final_results['qed_top10_qual'],duration
]
])
f.write(res+"\n")