-
Notifications
You must be signed in to change notification settings - Fork 2
/
qDrug_generator_benchmark_parallel_v13.py
1306 lines (1157 loc) · 43.8 KB
/
qDrug_generator_benchmark_parallel_v13.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
from inspect import signature
import os, json, time,sys
from datetime import datetime
from pathlib import Path
from functools import partial
from argparse import ArgumentParser
from typing import Literal, NamedTuple
import wandb
import torch
from torch import nn
import tqdm
import numpy as np
import matplotlib.pyplot as plt
from rdkit import Chem, RDLogger
from rdkit.Chem import Draw
import optuna
from optuna.trial import TrialState
import cloudpickle
import pandas as pd
from orquestra.qml.api import TrainCache
from orquestra.qml.models.rbm.th import RBM, TrainingParameters as RBMParams
from orquestra.qml.models.samplers.th import RandomChoiceSampler
from orquestra.qml.data_loaders import new_data_loader
from orquestra.qml.trainers import SimpleTrainer
# QCBM imports
from orquestra.qml.models.qcbm.layer_builders import LineEntanglingLayerBuilder
from orquestra.qml.models.qcbm.ansatze.alternating_entangling_layers import (
EntanglingLayerAnsatz,
)
from orquestra.qml.models.qcbm import WavefunctionQCBM
from orquestra.integrations.qulacs.simulator import QulacsSimulator
from orquestra.opt.optimizers.scipy_optimizer import ScipyOptimizer
# multi bases
from orquestra.qml.models.qcbm import MultiBasisWavefunctionQCBM
from orquestra.qml.models.qcbm import MultiBasisWavefunctionQCBM, RotationLayer
from orquestra.quantum.circuits import X, create_layer_of_gates
from utils import (
SmilesEncoding,
SelfiesEncoding,
generate_bulk_samples,
truncate_smiles,
LegacyExperiment,
lipinski_filter,
lipinski_hard_filter,
compute_compound_stats,
)
from utils.lipinski_utils import (
compute_qed,
compute_lipinski,
compute_logp,
draw_compounds,
)
from models.recurrent import NoisyLSTMv3
from utils.docking import compute_array_value
from utils.data import compund_to_csv
from utils.filter import (
apply_filters,
filter_phosphorus,
substructure_violations,
maximum_ring_size,
# lipinski_filter,
get_diversity,
passes_wehi_mcf,
pains_filt,
legacy_apply_filters,
)
# qiskit version
from orquestra.integrations.qiskit.conversions import (
export_to_qiskit,
import_from_qiskit,
)
from qiskit import QuantumCircuit, Aer, transpile, execute
from qiskit.providers.aer.noise import NoiseModel
from qiskit import IBMQ
from qiskit.providers.fake_provider import FakeGuadalupe, FakeHanoi
# from models.priors.qcbm_qiskit import QCBMGenerator
from qiskit.tools.monitor import job_monitor
# LOAD IBMQ account
from models.priors.loss import ExactNLLTorch
from orquestra.integrations.qiskit.runner import QiskitRunner
from orquestra.qml.models.qcbm import ShotQCBM
from orquestra.qml.models.qcbm import MultiBasisShotQCBM
sys.path.insert(0,'/home/mghazi/workspace/Tartarus')
from benchmark_models import docking_tartarus as trt
from tartarus.filter_ import process_molecule
IBMQ.load_account()
# SYBA
from syba.syba import SybaClassifier
from utils.api import RewardAPI
syba = SybaClassifier()
syba.fitDefaultScore()
RDLogger.DisableLog("rdApp.*")
diversity_fn = get_diversity
BATCHSIZE_GENERETATION = 100000
ACTIVE_FILTER = False
DISABLE_PROGRESS_BAR_PRIOR = False
traking = False
class TrainingArgs(NamedTuple):
lstm_n_epochs: int
prior_n_epochs: int
n_compound_generation: int
n_generation_steps: int
prior_model: Literal[
"QCBM", "mQCBM", "mrQCBM", "RBM", "classical", "ibm_hub_simulator"
]
filter_constraint: Literal["soft", "hard"]
n_lstm_layers: int
embedding_dim: int
hidden_dim: int
prior_size: int
n_qcbm_layers: int
data_set_id: int
file_path: str
device: Literal["cpu", "cuda", "auto"] = "auto"
gpu_count: int = 1
n_test_samples: int = 20_000
batch_size: int = 128
dataset_frac: float = 1.0
n_samples_chemistry42: int = 30
n_test_samples_chemistry42: int = 300
backend_name: str = "ibmq_qasm_simulator"
n_shots: int = 20000
optimizer_name: str = "COBYLA"
train_backend:str ="sw",
sampeling_backend:str="sw"
do_greedy_sampling: bool = False
temprature:float = 0.5
experiment_root:str = "/project/mghazi/experiment_results"
traking_wandb:bool = True
protein:str = "1syh"
@classmethod
def from_file(cls, path: str) -> "TrainingArgs":
assert os.path.exists(path), f"File {path} does not exist"
assert path.endswith(".json"), f"File {path} is not a json file"
with open(path, "r") as f:
args = json.load(f)
return cls(**args)
@classmethod
def from_namespace(cls, namespace) -> "TrainingArgs":
namespace_dict = vars(namespace)
namespace_dict.pop("config_file", None)
return cls(**namespace_dict)
def wma(arr: np.ndarray, window_size: int) -> np.ndarray:
"""Returns Weighted Moving Average.
Args:
arr (np.ndarray): data array.
window_size (int): window_size for computing average.
"""
weights = np.arange(window_size)
return np.convolve(arr, weights, "valid") / np.sum(weights)
def compute_stats_encode(data):
new_data = []
for data_ in data:
try:
reward_1 = compute_array_value(data_)
lip = compute_lipinski(data_, mol_weight_ref=600)
reward = np.append(lip[2], reward_1)
new_data.append(reward)
except:
reward = np.asarray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
new_data.append(reward)
return torch.Tensor(new_data).sum(dim=1)
def filter_legacy(smiles_compound, max_mol_weight: float = 800):
pass_all = []
for smile_ in smiles_compound:
try:
if apply_filters(smile_, max_mol_weight=max_mol_weight):
pass_all.append(smiles_compound)
except:
pass
return pass_all
def reward_fc_legacy(data):
new_data = []
for data_ in data:
try:
if validity_fn(data_):
reward_1 = compute_array_value(data_)
lip = compute_lipinski(data_, mol_weight_ref=600)
reward = np.append(lip[2], reward_1)
new_data.append(reward)
else:
reward = np.asarray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
new_data.append(reward)
except:
reward = np.asarray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
new_data.append(reward)
return torch.Tensor(new_data).sum(dim=1)
def benchmark_filter(smiles_compound, max_mol_weight: float = 800):
pass_all = []
for smile_ in smiles_compound:
try:
mol_cal = process_molecule(smile_)
if mol_cal[1]=="PASS":
pass_all.append(smile_)
except:
pass
return pass_all
def combine_filter(
smiles_compound, max_mol_weight: float = 800, filter_fc=apply_filters
):
# syba imports take a while move them here to only import when needed
pass_all = []
i = 0
with tqdm.tqdm(total=len(smiles_compound)) as pbar:
for smile_ in smiles_compound:
pbar.set_description(
f"Filtered {i} / {len(smiles_compound)}. passed={len(pass_all)},frac={len(pass_all)/len(smiles_compound)}"
)
try:
if (
filter_fc(smile_, max_mol_weight)
and smile_ not in pass_all
and (syba.predict(smile_) > 0)
and passes_wehi_mcf(smile_)
and (len(pains_filt(Chem.MolFromSmiles(smile_))) == 0)
):
pass_all.append(smile_)
except Exception as e:
print(
f"The following error occurred during the `combine_filter` step: {e}"
)
i += 1
pbar.update()
return pass_all
def reward_fc(smiles_ls, max_mol_weight: float = 800, filter_fc=legacy_apply_filters):
rewards = []
for smiles_compound in smiles_ls:
#: TODO: add wieghts for filter
try:
reward = 1
if filter_fc(smiles_compound, max_mol_weight=max_mol_weight):
reward += 15
if passes_wehi_mcf(smiles_compound):
reward += 5
if len(pains_filt(Chem.MolFromSmiles(smiles_compound))) == 0:
reward += 5
if syba.predict(smiles_compound) > 0:
reward += 30
rewards.append(reward)
except:
rewards.append(0)
return torch.Tensor(rewards)
def reward_fc_benchmark(smiles_ls, max_mol_weight: float = 800, filter_fc=legacy_apply_filters):
rewards = []
for smiles_compound in smiles_ls:
#: TODO: add wieghts for filter
try:
reward = 1
mol_cal = process_molecule(smiles_compound)
if mol_cal[1]=="PASS":
reward += 15
rewards.append(reward)
except:
rewards.append(0)
return torch.Tensor(rewards)
def rew_chemistry(
smiles_list: list, api: RewardAPI, custom_w_name: str = "training_loop"
):
workflow_ids = []
not_submitted = []
submitted = {}
rewards = []
smiles_dict = {}
step_size = 10
if len(smiles_list) > 10:
for i in range(0, len(smiles_list), 10):
smiles_ls = [smiles_["smiles"] for smiles_ in smiles_list[i : i + 10]]
try:
workflow_uuid = api.post_smiles(
name=f"{custom_w_name}_{i}_{i+10}",
mpo_score_definition_id=0,
smiles_list=smiles_ls,
)
submitted[workflow_uuid] = smiles_ls
print(i, i + 10)
submited_flag = True
except:
not_submitted.append(smiles_ls)
rewards.append(step_size * [-1.6])
submited_flag = False
if submited_flag:
try:
status = api.get_workflow_status(workflow_uuid)
while status != "success":
time.sleep(10)
status = api.get_workflow_status(workflow_uuid)
results = api.get_workflow_results(workflow_uuid)
for reward_, key_ in zip(results, list(range(i, i + 10))):
if reward_["filters_passed"]:
rewards.append(4 * (reward_["main_reward"] + 1))
else:
rewards.append(-1.6)
smiles_dict[key_] = {
"filters_passed": reward_["filters_passed"],
"ROMol_was_valid": reward_["ROMol_was_valid"],
"smiles": reward_["smiles"],
"reward": reward_["main_reward"],
}
except:
print(f"{workflow_uuid} pulling results is faled!")
rewards.append(step_size * [-1.6])
else:
smiles_ls = [smiles_["smiles"] for smiles_ in smiles_list]
api.post_smiles(
name="training_loop",
mpo_score_definition_id=0,
smiles_list=smiles_ls,
)
try:
status = api.get_workflow_status(workflow_uuid)
while status != "success":
time.sleep(5)
status = api.get_workflow_status(workflow_uuid)
results = api.get_workflow_results(workflow_uuid)
for reward_, key_ in zip(results, list(range(i, len(results)))):
if reward_["filters_passed"]:
rewards.append(4 * (reward_["main_reward"] + 1))
else:
rewards.append(-1.6)
smiles_dict[key_] = {
"filters_passed": reward_["filters_passed"],
"ROMol_was_valid": reward_["ROMol_was_valid"],
"smiles": reward_["smiles"],
"reward": reward_["main_reward"],
}
except:
print(f"{workflow_uuid} pulling results is faled!")
rewards.append(step_size * [-1.6])
print(rewards)
return smiles_dict, rewards
# save in file:
def save_obj(obj, file_path):
with open(file_path, "wb") as f:
r = cloudpickle.dump(obj, f)
return r
def load_obj(file_path):
with open(file_path, "rb") as f:
obj = cloudpickle.load(f)
return obj
def generate_samples(file_path,n_samples,protein):
saved_object = load_obj(file_path)
selfies_ = saved_object['selfies']
model_ = saved_object['model']
prior_ = saved_object['prior']
# model_.generate(prior_.generate(n_samples))
prior_samples_current = torch.tensor(prior_.generate(n_samples)).float()
encoded_compounds = model_.generate(prior_samples_current)
# prior_samples_current = torch.tensor(prior.generate(4000)).float()
# encoded_compounds = model.generate(prior_samples_current)
smiles_benchamrk = selfies_.decode_fn(encoded_compounds)
passed_filter_benchmark = benchmark_filter(smiles_benchamrk)
data = {
"smiles":list(set(passed_filter_benchmark))
}
epoch_plot_dir = file_path.split("mode")[0]
smiles_path = epoch_plot_dir + f"smiles_benchamrk_{protein}.csv"
df_ = pd.DataFrame(data)
df_.to_csv(smiles_path)
# inputs
argparser = ArgumentParser()
argparser.add_argument(
"--config_file",
type=str,
help="Path to config file for training. Manual configuration will take priority over values in config file.",
default="setting_benchmark_ibm_hub_simulator_qcbm_ch42_16_qubits_v12_1syh.json",
)
argparser.add_argument(
"--lstm_n_epochs", type=int, help="Number of epochs to train LSTM for"
)
argparser.add_argument(
"--prior_n_epochs", type=int, help="Number of epochs to train prior for"
)
argparser.add_argument(
"--n_compound_generation", type=int, help="Number of compounds to generate"
)
argparser.add_argument(
"--n_generation_steps", type=int, help="Number of generation steps to take"
)
argparser.add_argument(
"--prior_model",
type=str,
help="Name of prior model to use.",
choices=["QCBM", "mQCBM", "mrQCBM", "RBM", "classical", "ibm_hub_simulator"],
default=None,
)
argparser.add_argument(
"--filter_constraint",
type=str,
help="Name of filter constraint to use.",
choices=["hard", "soft"],
)
argparser.add_argument("--n_lstm_layers", type=int, help="Number of layers in LSTM")
argparser.add_argument("--embedding_dim", type=int, help="Embedding dimension")
argparser.add_argument("--hidden_dim", type=int, help="Hidden dimension")
argparser.add_argument(
"--prior_size", type=int, help="Dimension of samples generated by prior."
)
argparser.add_argument("--n_qcbm_layers", type=int, help="Number of layers in the QCBM")
argparser.add_argument(
"--data_set_id", type=int, help="ID of data set to use.", default=0
)
argparser.add_argument(
"--device",
type=str,
help="Device to use for training.",
choices=["cpu", "cuda", "auto"],
default="auto",
)
argparser.add_argument(
"--gpu_count", type=int, help="Number of GPUs to use, if available.", default=1
)
argparser.add_argument(
"--n_test_samples",
type=int,
help="Number of test samples to generate",
default=20_000,
)
argparser.add_argument(
"--batch_size",
type=int,
help="Number of samples per batch (per GPU if multiple available).",
default=128,
)
argparser.add_argument(
"--dataset_frac",
type=float,
help="Fraction of full dataset to train on.",
default=1.0,
)
argparser.add_argument(
"--n_samples_chemistry42",
type=int,
help="Number of test samples to generate",
default=50,
)
argparser.add_argument(
"--n_test_samples_chemistry42",
type=int,
help="Number of test samples to generate",
default=300,
)
argparser.add_argument(
"--n_shots",
type=int,
help="Number of shots on the quantum HW/SIM",
default=20000,
)
argparser.add_argument(
"--backend_name",
type=str,
help="backend_name name",
default="ibmq_qasm_simulator",
)
argparser.add_argument(
"--optimizer_name",
type=str,
help="optimizer_name name",
default="COBYLA",
)
argparser.add_argument(
"--train_backend",
type=str,
help="train_backend name [sw,hw]",
default="sw",
)
argparser.add_argument(
"--sampeling_backend",
type=str,
help="sampeling_backend [sw,hw]",
default="sw",
)
argparser.add_argument(
"--do_greedy_sampling",
type=str,
help="do_greedy_sampling [True,False]",
default=False,
)
argparser.add_argument(
"--temprature",
type=float,
help="temprature [0.0,...,1.0]",
default=1.0,
)
argparser.add_argument(
"--experiment_root",
type=str,
help="experiment_root [/project/mghazi/experiment_results]",
default= "/project/mghazi/experiment_results",
)
argparser.add_argument(
"--traking_wandb",
type=str,
help="traking_wandb [true or false]",
default= True,
)
argparser.add_argument(
"--file_path",
type=str,
help="file_path str",
default= "/project/mghazi/good_latest_results/benchmark-lstm-QCBM-2023_05_09T23_04_51.429333/mode_prior_150.pkl",
)
argparser.add_argument(
"--protein",
type=str,
help="protein str",
default= "1syh",
)
namespace, _ = argparser.parse_known_args()
if namespace.config_file is not None:
args = TrainingArgs.from_file(namespace.config_file)
else:
args = TrainingArgs.from_namespace(namespace)
# get values from args
max_mol_weight = 800
prior_hidden_layer = 10
device = args.device
if device == "auto":
if torch.cuda.is_available():
device = "cuda"
else:
device = "cpu"
prior_sample_size = args.prior_size
lstm_n_batch_size = args.batch_size
data_set = args.data_set_id
filter_constraint = args.filter_constraint
prior_model = args.prior_model
n_qcbm_layers = args.n_qcbm_layers
hidden_dim = args.hidden_dim
embedding_dim = args.embedding_dim
n_lstm_layers = args.n_lstm_layers
lstm_n_epochs = args.lstm_n_epochs
prior_n_epochs = args.prior_n_epochs
n_test_samples = args.n_test_samples
n_compound_generation = args.n_compound_generation
n_generation_steps = args.n_generation_steps
dataset_frac = args.dataset_frac
N_SAMPLES_CHEMISTRY42 = args.n_samples_chemistry42
N_TEST_SAMPLES_CHEMISTRY42 = args.n_test_samples_chemistry42
backend_name = args.backend_name
n_shots = args.n_shots
optimizer_name = args.optimizer_name
train_backend = args.train_backend
sampeling_backend = args.sampeling_backend
do_greedy_sampling = args.do_greedy_sampling
temprature = args.temprature
experiment_root = args.experiment_root
traking_wandb = args.traking_wandb
file_path = args.file_path
protein = args.protein
print(f"\n**TRAINING CONFIGURATION**: {args}\n")
# path_to_dataset = "data/KRAS_G12D/KRAS_G12D_inhibitors_update2023.csv"
dataset_by_id = {
0: "data/KRAS_G12D/KRAS_G12D_inhibitors_update2023.csv",
1: "data/KRAS_G12D/initial_dataset.csv",
2: "data/KRAS_G12D/initial_data_with_chemistry42_syba_merged_v2.csv",
3: "data/KRAS_G12D/initial_data_set_with_100k_hits.csv",
4: "data/merged_dataset/1Mstoned_vsc_initial_dataset_insilico_chemistry42_filtered.csv",
5: "/home/mghazi/workspace/Tartarus/datasets/docking.csv"
}
path_to_dataset = dataset_by_id.get(data_set, None)
if path_to_dataset is None:
raise ValueError(f"Invalid data set id: {data_set}")
path_to_model_weights = None
if filter_constraint == "hard":
filter_fc = partial(combine_filter, max_mol_weight=max_mol_weight)
rew_fc = reward_fc
elif filter_constraint == "soft":
filter_fc = partial(
combine_filter,
max_mol_weight=max_mol_weight,
filter_fc=legacy_apply_filters,
)
rew_fc = partial(
reward_fc, max_mol_weight=max_mol_weight, filter_fc=legacy_apply_filters
)
else:
raise ValueError("Invalid filter constraint.")
run_date_time = datetime.today().strftime("%Y_%d_%mT%H_%M_%S.%f")
trials_no = int(sys.argv[3])
experiment = LegacyExperiment(run_id=f"benchmark-lstm-{prior_model}-{trials_no}-{run_date_time}",root_dir= Path(experiment_root).resolve())
print(f"Experiment ID: {experiment.run_id}")
if data_set == 2:
object_loaded = load_obj("data/initial_data.pkl")
selfies = object_loaded[1]
elif data_set == 4:
object_loaded = load_obj(
"data/merged_dataset/1Mstoned_vsc_initial_dataset_insilico_chemistry42_filtered.pkl"
)
selfies = object_loaded[1]
else:
selfies = SelfiesEncoding(path_to_dataset, dataset_identifier="benchmark")
print(f"Using file: {selfies._filepath}.")
print(f"Dataset identifier: {selfies.dataset_identifier}")
optimizer = ScipyOptimizer(method=optimizer_name, options={"maxiter": 1})
ibm_hub_simulator = False
prior_train = True
if prior_model == "QCBM":
# QCBM
noisy_sim_backend = QulacsSimulator() # QiskitRunner(sampeling_backend) #
sampeling_backend_orq = QulacsSimulator()
entangling_layer_builder = LineEntanglingLayerBuilder(n_qubits=prior_sample_size)
qcbm_ansatz = EntanglingLayerAnsatz(
n_qubits=prior_sample_size,
n_layers=n_qcbm_layers,
entangling_layer_builder=entangling_layer_builder,
)
prior = WavefunctionQCBM(
ansatz=qcbm_ansatz,
optimizer=optimizer,
backend=QulacsSimulator(),
choices=(0, 1),
use_efficient_training=False,
distance_measure=ExactNLLTorch()
) #
elif prior_model == "mQCBM":
noisy_sim_backend = QulacsSimulator() # QiskitRunner(sampeling_backend) #
sampeling_backend_orq = QulacsSimulator()
# multi bases QCBM
entangling_layer_builder = LineEntanglingLayerBuilder(
n_qubits=prior_sample_size // 2
)
multiqcbm_ansatz = EntanglingLayerAnsatz(
n_qubits=prior_sample_size // 2,
n_layers=n_qcbm_layers,
entangling_layer_builder=entangling_layer_builder,
)
rotate_basis_circuit = RotationLayer(n_qubits=prior_sample_size//2)
prior = MultiBasisWavefunctionQCBM(
ansatz=multiqcbm_ansatz,
optimizer=optimizer,
backend=QulacsSimulator(),
choices=(0, 1),
use_efficient_training=False,
# train_basis=False,
basis_rotations=rotate_basis_circuit,
distance_measure=ExactNLLTorch()
)
elif prior_model == "mrQCBM":
# multi bases QCBM
noisy_sim_backend = QulacsSimulator() # QiskitRunner(sampeling_backend) #
sampeling_backend_orq = QulacsSimulator()
entangling_layer_builder = LineEntanglingLayerBuilder(
n_qubits=prior_sample_size // 2
)
multiqcbm_ansatz = EntanglingLayerAnsatz(
n_qubits=prior_sample_size // 2,
n_layers=n_qcbm_layers,
entangling_layer_builder=entangling_layer_builder,
)
# We create a circuit that rotates the basis of the qubits at the end of the circuit
rotate_basis_circuit = create_layer_of_gates(
number_of_qubits=prior_sample_size // 2, gate_factory=X
)
prior = MultiBasisWavefunctionQCBM(
ansatz=multiqcbm_ansatz,
optimizer=optimizer,
backend=QulacsSimulator(),
choices=(0, 1),
use_efficient_training=False,
train_basis=False,
basis_rotations=rotate_basis_circuit,
distance_measure=ExactNLLTorch()
)
prior_train = False
elif prior_model == "RBM":
prior = RBM(
n_visible_units=prior_sample_size,
n_hidden_units=prior_hidden_layer,
training_parameters=RBMParams(),
)
elif prior_model == "classical":
prior = RandomChoiceSampler(prior_sample_size, [0.0, 1.0])
prior_train = False
elif prior_model =="ibmq_guadalupe_qcbm":
backend_name = "ibmq_guadalupe"
provider = IBMQ.get_provider(hub='ibm-q-startup', group='zapata', project='reservations')
sampeling_backend = provider.get_backend(backend_name)
noisy_sim_backend = QulacsSimulator() # QiskitRunner(sampeling_backend) #
sampeling_backend_orq = QiskitRunner(sampeling_backend)
entangling_layer_builder = LineEntanglingLayerBuilder(n_qubits=prior_sample_size)
qcbm_ansatz = EntanglingLayerAnsatz(
n_qubits=prior_sample_size,
n_layers=n_qcbm_layers,
entangling_layer_builder=entangling_layer_builder,
)
prior = ShotQCBM(ansatz=qcbm_ansatz, optimizer=optimizer,distance_measure=ExactNLLTorch(), backend=sampeling_backend_orq, choices=(0, 1), use_efficient_training=True)
ibm_hub_simulator = True
else:
raise ValueError(f"Prior model {prior_model} not implemented.")
print(f"Prior identifier: {prior.__str__()}")
###
base_url = "https://rip.chemistry42.com"
username = "m.ghazivakili"
password = "hJEV0jm5bgqX"
reward_api = RewardAPI(username=username, password=password, base_url=base_url)
###
# TODO: optuna for
# hidden_dim=8, # next: 64
# embedding_dim=256
# hidden_dim=128, # next: 64 # best resulst is with hidden_dim 128
trials_no = int(sys.argv[3])
path_to_dataset = f"hill_climming/stoned/0{trials_no}_initial_dataset_50k_stoned_sim_0.8_qvina_{protein}_n.txt"
print(path_to_dataset)
selfies = SelfiesEncoding(path_to_dataset, dataset_identifier=f"benchmark_{protein}")
model = NoisyLSTMv3(
vocab_size=selfies.num_emd,
seq_len=selfies.max_length,
sos_token_index=selfies.start_char_index,
prior_sample_dim=prior_sample_size,
padding_token_index=selfies.pad_char_index,
hidden_dim=hidden_dim,
embedding_dim=embedding_dim,
n_layers=n_lstm_layers,
do_greedy_sampling=do_greedy_sampling,
sampling_temperature=temprature
)
# save_object = load_obj(file_path)
# model = save_object["model"]
# experiment.model_configurations.append(model.config.as_dict())
# selfies = save_object["selfies"]
# prior = save_object["prior"]
# if path_to_model_weights is not None:
# print(f"Loading model weights from {path_to_model_weights}")
# model.load_weights(path_to_model_weights)
if device == "cuda":
if torch.cuda.device_count() > 1 and args.gpu_count > 1:
print("Using", torch.cuda.device_count(), "GPUs!")
model._model = nn.DataParallel(model._model)
lstm_n_batch_size = lstm_n_batch_size * torch.cuda.device_count()
model.to_device(device)
training_parameters = {
"n_epochs": lstm_n_epochs,
"batch_size": lstm_n_batch_size,
}
n_epochs = training_parameters["n_epochs"]
# x1 = torch.tensor(prior.generate(1300)).float()
# y1 = model.generate(x1)
# decoder_fn = selfies.decode_fn
# truncate_fn = truncate_smiles
# validity_fn = filter_fc
# train_compounds = selfies.train_samples
encoded_samples_th = torch.tensor(selfies.encoded_samples)
data = encoded_samples_th.float()
decoder_fn = selfies.decode_fn
truncate_fn = truncate_smiles
train_compounds = selfies.train_samples
validity_fn = filter_fc
training_parameters.update(
dict(
n_test_samples=n_test_samples,
decoder_fn_signature=str(signature(decoder_fn)),
truncate_fn_signature=str(signature(truncate_fn)),
validity_fn_signature=str(signature(validity_fn)),
)
)
epoch_plot_dir = Path(experiment_root) / "epoch_plots" / experiment.run_id
epoch_plot_dir = epoch_plot_dir.resolve()
# all_samples = decoder_fn(y1)
# passed_filter_benchmark = benchmark_filter(all_samples)
# initial_data = {
# "smiles":passed_filter_benchmark,
# # "qvina":len(passed_filter_benchmark)*None,
# # "smina":len(passed_filter_benchmark)*None,
# }
# df_initial_data = pd.DataFrame(initial_data)
# df_initial_data.to_csv("hill_climming/initial_data.csv")
# sr_fraction = float(len(passed_filter_benchmark)/len(all_samples)*100)
# print(sr_fraction)
# qvina_docking = []
# smina_docking = []
# for ligand in passed_filter_benchmark:
# qvina_docking.append(trt.perform_calc_single(ligand,protein , docking_program='qvina'))
# smina_docking.append(trt.perform_calc_single(ligand,protein , docking_program='smina'))
# initial_data = {
# "smiles":passed_filter_benchmark,
# "qvina_docking":qvina_docking,
# "smina_docking":smina_docking,
# }
# df_initial_data = pd.DataFrame(initial_data)
# ndf = df_initial_data.sort_values(by="qvina_docking")
# new_data = df_initial_data.nsmallest(int(len(df_initial_data) * 0.1), 'qvina_docking').smiles.to_list()
if epoch_plot_dir.exists() is False:
os.makedirs(str(epoch_plot_dir))
dataloader = (
new_data_loader(
data=data, batch_size=training_parameters["batch_size"], drop_last=True
)
.shuffle(12345)
.truncate(fraction=dataset_frac)
)
train_cache = TrainCache()
if prior_model == "QCBM" or prior_model == "mQCBM" or prior_model == "mrQCBM" or prior_model == "ibmq_guadalupe_qcbm":
batch_size_prior = -1
else:
batch_size_prior = training_parameters["batch_size"]
n_samples = data.shape[0]
# start training
# if torch.cuda.is_available():
# torch.cuda.empty_cache()
# wandb
if traking_wandb:
wandb.login()
run = wandb.init(
# Set the project where this run will be logged
project=experiment.run_id,
name=f"1-{protein}-{prior_model}",
# Track hyperparameters and run metadata
config={
"args": args,
"epoch_plot_dir": epoch_plot_dir
}
)
wandb.watch(model._model, log_freq=100)
generated_compunds = {}
live_model_loss = []
all_chem_42_computed = []
valid_smiles_ = []
all_compound = []
for epoch in range(1, n_epochs + 1):
with tqdm.tqdm(total=dataloader.n_batches) as pbar:
pbar.set_description(f"Epoch {epoch} / {n_epochs}.")
concat_prior_samples = []
if ibm_hub_simulator:
if epoch ==1:
prior._backend = noisy_sim_backend
else:
prior._backend = sampeling_backend_orq
all_batch_prior_samples = prior.generate(n_samples)
i = 0
for batch_idx, batch in enumerate(dataloader):
if ibm_hub_simulator:
prior_samples = torch.tensor(
all_batch_prior_samples[i : i + training_parameters["batch_size"]]
).float()
i += training_parameters["batch_size"]
else:
prior_samples = torch.tensor(prior.generate(batch.batch_size)).float()
batch.targets = prior_samples
batch_result = model.train_on_batch(batch)
train_cache.update_history(batch_result)
concat_prior_samples = concat_prior_samples + prior_samples.tolist()
pbar.set_postfix(dict(Loss=batch_result["loss"]))
pbar.update()
# if torch.cuda.is_available():
# torch.cuda.empty_cache()
th_prior_samples = torch.tensor(concat_prior_samples)
# put model in evaluation mode such that layers like Dropout, Batchnorm don't affect results
model.set_eval_state()
# prior training
if epoch == 1:
prior_samples_current = torch.tensor(prior.generate(n_test_samples)).float()
encoded_compounds = model.generate(prior_samples_current)
compound_stats = compute_compound_stats(
encoded_compounds,
decoder_fn,
diversity_fn,
validity_fn,
train_compounds,
)
datanew = rew_fc(list(compound_stats.all_compounds)).cpu()
soft = torch.nn.Softmax(dim=0)
probs = soft(datanew)
print(probs)
prior_train_data = new_data_loader(
data=prior_samples_current,
probs=probs,
batch_size=batch_size_prior,
)
# TODO track prior training cache
prior_x = prior_samples_current
prior_y = probs
if prior_model == "ibm_hub_simulator" or prior_model == "ibmq_guadalupe":
prior_train_cache = prior.train(
prior_n_epochs, prior_samples_current, probs
)
elif prior_train:
prior._backend = noisy_sim_backend
prior_train_cache = SimpleTrainer().train(
prior,
prior_train_data,