-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataloader.py
1901 lines (1760 loc) · 74.4 KB
/
dataloader.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
import numpy as np
import pandas as pd
from copy import deepcopy
from rdkit import Chem, DataStructs
from rdkit.Chem import rdFingerprintGenerator, AllChem
from sklearn.preprocessing import OneHotEncoder
from abc import ABC
import joblib
from scipy.stats.mstats import rankdata
np.random.seed(42)
def yield_to_ranking(yield_array):
"""Transforms an array of yield values to their rankings.
Currently, treat 0% yields as ties in the last place. (total # of labels)
Ties are not treated equally since label ranking algorithms, particularly ibm and ibpl
is not designed to deal with them.
Parameters
----------
yield_array : np.ndarray of shape (n_samples, n_conditions)
Array of raw yield values.
Returns
-------
ranking_array : np.ndarray of shape (n_samples, n_conditions)
Array of ranking values. Lower values correspond to higher yields.
"""
if len(yield_array.shape) == 2:
raw_rank = yield_array.shape[1] - np.argsort(
np.argsort(yield_array, axis=1), axis=1
)
for i, row in enumerate(yield_array):
raw_rank[i, np.where(row == 0)[0]] = len(row > 0)
# print("Raw rank", raw_rank)
elif len(yield_array.shape) == 1:
raw_rank = len(yield_array) - np.argsort(np.argsort(yield_array))
raw_rank[np.where(raw_rank == 0)[0]] = len(raw_rank)
return raw_rank
class Dataset(ABC):
"""
Base class for preparing datasets.
Parameters
----------
for_regressor : bool
Whether the input will be used for training a regressor.
n_rxns : int
Number of reactions that we simulate to select and conduct.
"""
def __init__(self, for_regressor, n_rxns):
self.for_regressor = for_regressor
self.n_rxns = n_rxns
@property
def X_dist(self):
"""Tanimoto distances between the substrates, used for neighbor based models."""
mfpgen = rdFingerprintGenerator.GetMorganGenerator(radius=3, fpSize=1024)
cfp_nonnp = [
mfpgen.GetCountFingerprint(Chem.MolFromSmiles(x)) for x in self.smiles_list
]
dists = np.zeros((len(cfp_nonnp), len(cfp_nonnp)))
for i in range(1, len(cfp_nonnp)):
similarities = DataStructs.BulkTanimotoSimilarity(
cfp_nonnp[i], cfp_nonnp[:i]
)
dists[i, :i] = np.array([1 - x for x in similarities])
dists += dists.T
self._X_dist = dists
# print("DISTARRAY",dists)
return self._X_dist
class NatureDataset(Dataset):
"""
Prepares arrays from the HTE paper in Nature, 2018.
Parameters
----------
for_regressor : bool
Whether the input will be used for training a regressor.
n_rxns : int
Number of reactions that we simulate to select and conduct.
component_to_rank : str {'amine', 'amide', 'sulfonamide'}
Which substrate dataset type to use.
Although 'substrate_to_rank' is a better name, using this for consistency.
"""
def __init__(self, for_regressor, component_to_rank, n_rxns=1):
super().__init__(for_regressor, n_rxns)
self.component_to_rank = component_to_rank
# Loading the raw dataset
raw_data = pd.read_excel(
"datasets/natureHTE/natureHTE.xlsx",
sheet_name="Report - Variable Conditions",
usecols=["BB SMILES", "Chemistry", "Catalyst", "Base", "Rel. % Conv."],
)
# Reagent descriptors
base_descriptors = pd.read_excel(
"datasets/natureHTE/reagent_desc.xlsx", sheet_name="Base"
)
cat_descriptors = pd.read_excel(
"datasets/natureHTE/reagent_desc.xlsx", sheet_name="Catalyst"
)
self.reagent_data = {}
for _, row in base_descriptors.iterrows():
self.reagent_data.update({row[0]: row[1:].to_numpy()})
for _, row in cat_descriptors.iterrows():
self.reagent_data.update({row[0]: row[1:].to_numpy()})
# Reaction data by substrate type
if self.component_to_rank == "amine":
self.df = raw_data[raw_data["Chemistry"] == "Amine"]
self.smiles_list = self.df["BB SMILES"].unique().tolist()
# Filtering out secondary amines - removes 35
primary_amine_smiles = []
for smiles in self.smiles_list :
mol = Chem.MolFromSmiles(smiles)
max_hydrogens = 0
for atom in mol.GetAtoms():
if atom.GetSymbol() == 'N':
num_of_h = atom.GetNumImplicitHs()
if num_of_h > max_hydrogens:
max_hydrogens = num_of_h
if max_hydrogens == 2 :
primary_amine_smiles.append(smiles)
self.smiles_to_keep = deepcopy(primary_amine_smiles)
# # Filtering out cases where the top case is a tie between condition 0 and another one. - removes 9
# inds_to_remove_from_primary_amine_smiles = []
# for i, row in enumerate(self.df[self.df["BB SMILES"].isin(primary_amine_smiles)].iloc[:, -1].to_numpy().flatten().reshape(len(primary_amine_smiles),4)) :
# if np.argmax(row) ==0 and len(np.unique(row)) != len(row) :
# inds_to_remove_from_primary_amine_smiles.append(i)
# self.smiles_to_keep = [item for i, item in enumerate(primary_amine_smiles) if i not in inds_to_remove_from_primary_amine_smiles]
# # Randomly removing 17 cases where condition 0 is top-yielding
# random_removal = [0, 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 15, 16, 17, 21, 22, 24] # the first array when you run np.random.seed(42) \n sorted(np.random.choice(27, size=17, replace=False))
# counter = 0
# inds_to_further_remove = []
# temp_y_array = self.df[self.df["BB SMILES"].isin(self.smiles_to_keep)].iloc[:, -1].to_numpy().flatten().reshape(len(self.smiles_to_keep),4)
# for i, row in enumerate(temp_y_array) :
# if np.argmax(row) == 0 :
# if counter in random_removal :
# inds_to_further_remove.append(i)
# counter += 1
# self.smiles_to_keep = [item for i, item in enumerate(self.smiles_to_keep) if i not in inds_to_further_remove]
# temp_y_array = self.df[self.df["BB SMILES"].isin(self.smiles_to_keep)].iloc[:, -1].to_numpy().flatten().reshape(len(self.smiles_to_keep),4)
self.validation_rows = [i for i, item in enumerate(self.smiles_list) if item not in self.smiles_to_keep]
elif self.component_to_rank == "sulfonamide":
self.df = raw_data[raw_data["Chemistry"] == "Sulfonamide"].reset_index()
# self.validation_rows = joblib.load(
# "datasets/natureHTE/nature_sulfon_inds_to_remove.joblib"
# )
self.validation_rows = []
elif self.component_to_rank == "amide":
self.df = raw_data[raw_data["Chemistry"] == "Amide"].reset_index()
self.smiles_list = self.df["BB SMILES"].unique().tolist()
# Filtering out secondary amides
self.smiles_to_keep = []
for smiles in self.smiles_list :
mol = Chem.MolFromSmiles(smiles)
max_hydrogens = 0
for atom in mol.GetAtoms():
if atom.GetSymbol() == 'N':
num_of_h = atom.GetNumImplicitHs()
if num_of_h > max_hydrogens:
max_hydrogens = num_of_h
if max_hydrogens == 2 :
self.smiles_to_keep.append(smiles)
self.validation_rows = [i for i, item in enumerate(self.smiles_list) if item not in self.smiles_to_keep]
elif self.component_to_rank == "thiol":
self.df = raw_data[raw_data["Chemistry"] == "Thiol"].reset_index()
self.validation_rows = []
rows_to_keep = []
# Removing rows that are all 0% yields + with multiple 100% yields
for i, row in enumerate(
raw_data[raw_data["Chemistry"] == "Thiol"]
.iloc[:, -1]
.to_numpy()
.reshape(48, 4)
):
if len(np.unique(row)) == len(row) :
rows_to_keep.append(i)
else:
self.validation_rows.append(i)
# For Table S1 - comment out four rows above and uncomment the four rows below
# if len(np.unique(row)) == 1 or np.sum(np.isnan(row)) > 0 :
# self.validation_rows.append(i)
# else :
# rows_to_keep.append(i)
self.smiles_list = self.df["BB SMILES"].unique().tolist()
self.cats = self.df["Catalyst"].unique().tolist()
self.bases = self.df["Base"].unique().tolist()
self.n_rank_component = len(self.cats) * len(self.bases)
self.train_together = False # for kNN
def _split_train_validation(self, array):
"""Splits prepared X or Y array into a training set with more balanced output.
Parameters
----------
array : np.ndarray of shape (n_rxns or n_substrates, n_features) or (n_rxns or n_substrates,)
Array to split.
"""
if self.for_regressor:
train_rows = []
val_rows = []
for i in range(len(self.df["BB SMILES"].unique())):
if i not in self.validation_rows:
train_rows.extend([4 * i, 4 * i + 1, 4 * i + 2, 4 * i + 3])
if i in self.validation_rows:
val_rows.extend([4 * i, 4 * i + 1, 4 * i + 2, 4 * i + 3])
array_train = array[train_rows]
array_val = array[val_rows]
else:
array_train = array[
[x for x in range(array.shape[0]) if x not in self.validation_rows]
]
array_val = array[self.validation_rows]
return array_train, array_val
@property
def X_fp(self, fpSize=1024, radius=3):
"""
Prepares fingerprint arrays of substrates.
For regressors, other descriptors are appended after the substrate fingerprint.
Parameters
----------
fpSize : int
Length of the Morgan FP.
radius : int
Radius of the Morgan FP.
Returns
-------
X_fp : np.ndarray of shape (n_rxns, n_features)
n_features depends on self.for_regressor
"""
mfpgen = rdFingerprintGenerator.GetMorganGenerator(radius=radius, fpSize=fpSize)
if self.for_regressor:
fp_arrays = []
for i, row in self.df.iterrows():
fp_array = mfpgen.GetCountFingerprintAsNumPy(
Chem.MolFromSmiles(row["BB SMILES"])
).reshape(1, -1)
cat_desc = self.reagent_data[row["Catalyst"]].reshape(1, -1)
base_desc = self.reagent_data[row["Base"]].reshape(1, -1)
fp_arrays.append(np.hstack((fp_array, cat_desc, base_desc)))
else:
fp_arrays = [
mfpgen.GetCountFingerprintAsNumPy(Chem.MolFromSmiles(x))
for x in self.df["BB SMILES"].unique()
]
self._X_fp, self.X_valid = self._split_train_validation(
np.vstack(tuple(fp_arrays))
)
return self._X_fp
@property
def X_desc(self):
"""
Prepares descriptor arrays.
"""
desc_array = pd.read_excel(f"datasets/natureHTE/{self.component_to_rank}_descriptors.xlsx").to_numpy()[:, 1:]
if self.for_regressor :
self._reagent_arrays = []
for i, row in self.df.iterrows():
if self.component_to_rank not in ["sulfonamide", "thiol"] and row["BB SMILES"] not in self.smiles_to_keep:
continue
cat_desc = self.reagent_data[row["Catalyst"]].reshape(1, -1)
base_desc = self.reagent_data[row["Base"]].reshape(1, -1)
self._reagent_arrays.append(np.hstack((cat_desc, base_desc)))
self._X_desc = np.hstack((
np.repeat(desc_array, 4, axis=0),
np.vstack(tuple(self._reagent_arrays))
))
else :
self._X_desc = desc_array
if self.component_to_rank in ["sulfonamide", "thiol"]:
self._X_desc, self.X_valid = self._split_train_validation(self._X_desc)
return self._X_desc
@property
def X_random(self) :
np.random.seed(42)
desc_array = pd.read_excel(f"datasets/natureHTE/{self.component_to_rank}_descriptors.xlsx").to_numpy()[:, 1:]
self._X_random = np.random.rand(desc_array.shape[0], desc_array.shape[1])
if self.for_regressor :
_ = self.X_desc
reagent_arrays = [array.astype(np.float32) for array in self._reagent_arrays]
orig_reagent_arrays = np.vstack(tuple(reagent_arrays))
uniq_rows = np.unique(orig_reagent_arrays, axis=0)
assert uniq_rows.shape[0] == 4
rand_reagent_desc = np.random.rand(
uniq_rows.shape[0],
orig_reagent_arrays.shape[1]
)
rand_reagent_array = np.vstack(tuple(
[rand_reagent_desc[np.where(np.all(uniq_rows == row, axis=1))[0][0]] for row in orig_reagent_arrays]
))
self._X_random = np.hstack((
np.repeat(self._X_random, 4, axis=0),
rand_reagent_array,
))
if self.component_to_rank in ["sulfonamide", "thiol"]:
self._X_random, _ = self._split_train_validation(self._X_random)
return self._X_random
@property
def X_onehot(self):
"""Prepares onehot arrays."""
n_subs = len(self.smiles_list)
if self.for_regressor:
n_cats = len(self.cats)
n_bases = len(self.bases)
array = np.zeros((self.df.shape[0], n_subs + n_cats + n_bases))
for i, row in self.df.iterrows():
array[
[i, i, i],
[
self.smiles_list.index(row["BB SMILES"]),
n_subs + self.cats.index(row["Catalyst"]),
n_subs + n_bases + self.bases.index(row["Base"]),
],
] = 1
else:
array = np.identity(n_subs)
self._X_onehot, self.X_valid = self._split_train_validation(array)
return self._X_onehot
@property
def X_dist(self):
"""Tanimoto distances between the substrates, used for neighbor based models."""
mfpgen = rdFingerprintGenerator.GetMorganGenerator(radius=3, fpSize=1024)
train_cfp = [
mfpgen.GetCountFingerprint(Chem.MolFromSmiles(x))
for i, x in enumerate(self.smiles_list)
if i not in self.validation_rows
]
valid_cfp = [
mfpgen.GetCountFingerprint(Chem.MolFromSmiles(x))
for i, x in enumerate(self.smiles_list)
if i in self.validation_rows
]
train_dists = np.zeros((len(train_cfp), len(train_cfp)))
valid_dists = np.zeros((len(valid_cfp), len(train_cfp)))
for i in range(1, len(train_dists)):
similarities_btw_train = DataStructs.BulkTanimotoSimilarity(
train_cfp[i], train_cfp[:i]
)
test_to_train_sim = DataStructs.BulkTanimotoSimilarity(
train_cfp[i], valid_cfp
)
train_dists[i, :i] = np.array([1 - x for x in similarities_btw_train])
valid_dists[:, i] = np.array([1 - x for x in test_to_train_sim])
train_dists += train_dists.T
self._X_dist = train_dists
self.X_valid = valid_dists
return self._X_dist
@property
def y_yield(self):
if self.for_regressor:
y = self.df["Rel. % Conv."].values.flatten()
y[np.argwhere(np.isnan(y))] = 0
self._y_yield, self.y_valid = self._split_train_validation(y)
else:
self._y_yield, self.y_valid = self._split_train_validation(
self._sort_yield_by_substrate()
)
return self._y_yield
def _sort_yield_by_substrate(self):
"""Prepares an array of yields where each row and column correspond to
a substrate and reactions conditions, respectively."""
array = np.zeros((len(self.smiles_list), len(self.cats) * len(self.bases)))
for i, row in self.df.iterrows():
y_val = row["Rel. % Conv."]
if np.isnan(y_val):
y_val = 0
array[
self.smiles_list.index(row["BB SMILES"]),
len(self.cats) * self.cats.index(row["Catalyst"])
+ self.bases.index(row["Base"]),
] = y_val
return array
@property
def y_ranking(self):
self._y_ranking, self.y_valid = self._split_train_validation(
yield_to_ranking(self._sort_yield_by_substrate())
)
return self._y_ranking
@property
def y_label(self):
self._y_label, self.y_valid = self._split_train_validation(
np.argmax(self._sort_yield_by_substrate(), axis=1)
)
return self._y_label
class InformerDataset(Dataset):
"""
Prepares arrays from the nickella-photoredox informer for downstream use.
Parameters
----------
for_regressor : bool
Whether the input will be used for training a regressor.
n_rxns : int
Number of reactions that we simulate to select and conduct.
train_together : bool
Whether the non-label reaction component should be trained altogether, or used as separate datasets.
Only considered when component_to_rank is not 'both'.
component_to_rank : str {'both', 'amine_ratio', 'catalyst_ratio'}
Which reaction component to be ranked.
Attributes
----------
X_fp :
Only fingerprint arrays are considered for substrates.
"""
def __init__(self, for_regressor, component_to_rank, train_together, n_rxns):
super().__init__(for_regressor, n_rxns)
self.component_to_rank = component_to_rank
self.train_together = train_together
# Reading in the raw dataset
informer_df = pd.read_excel("datasets/Informer.xlsx").iloc[:40, :]
desc_df = pd.read_excel(
"datasets/Informer.xlsx", sheet_name="descriptors", usecols=[0, 1, 2, 3, 4]
).iloc[:40, :]
smiles = pd.read_excel(
"datasets/Informer.xlsx", sheet_name="smiles", header=None
)
# Dropping compounds where all yields are below 20%
cols_to_erase = []
for col in informer_df.columns:
if np.all(informer_df.loc[:, col].to_numpy() < 20):
cols_to_erase.append(col)
informer_df = informer_df.loc[
:, [x for x in range(1, 19) if x not in cols_to_erase]
] # leaves 11 compounds
smiles_list = [
x[0]
for i, x in enumerate(smiles.values.tolist())
if i + 1 not in cols_to_erase
]
# Assigning the arrays
self.df = informer_df
self.desc = desc_df.to_numpy()
self.smiles_list = smiles_list
if self.component_to_rank == "amine_ratio":
self.n_rank_component = 10
self.n_non_rank_component = 4 # 4 catalyst ratio values
elif self.component_to_rank == "catalyst_ratio":
self.n_rank_component = 20
self.n_non_rank_component = 2 # 2 amine ratio values
def _split_arrays(self, substrate_array_to_process, other_array, return_X=True):
if self.for_regressor:
arrays = []
for i, (_, yield_vals) in enumerate(self.df.items()):
if return_X:
arrays.append(
np.hstack(
(
np.tile(substrate_array_to_process[i, :], (40, 1)),
other_array,
)
)
)
else:
arrays.append(yield_vals.to_numpy())
if return_X:
array = np.vstack(tuple(arrays))
else:
array = np.concatenate(tuple(arrays))
if self.train_together:
processed_array = array
else:
if self.component_to_rank == "catalyst_ratio":
processed_array = [
array[[x for x in range(array.shape[0]) if x % 8 < 4]],
array[[x for x in range(array.shape[0]) if x % 8 >= 4]],
]
elif self.component_to_rank == "amine_ratio":
processed_array = [
array[[y for y in range(array.shape[0]) if y % 4 == x]]
for x in range(4)
]
if return_X:
assert np.all(processed_array[0] == processed_array[1])
processed_array = processed_array[0]
else:
yield_array = self.df.to_numpy()
if self.component_to_rank == "amine_ratio":
if not return_X:
if not self.train_together:
processed_array = [
yield_array[
[y for y in range(yield_array.shape[0]) if y % 4 == x],
:,
].T
for x in range(4) # 11 x 10
]
else:
first_amine = []
for i, row in enumerate(yield_array.T):
first_amine.append([])
for j in range(10): # 10 chunks of 4-catalyst ratio values
first_amine[i].append(
row[4 * j : 4 * (j + 1)].reshape(-1, 1)
)
processed_array = np.vstack(
tuple(
[
np.hstack(tuple(sub_array))
for sub_array in first_amine
]
)
)
else:
if not self.train_together:
processed_array = [substrate_array_to_process] * 4
else:
processed_array = np.hstack(
(
np.repeat(substrate_array_to_process, 4, axis=0),
other_array,
)
)
elif self.component_to_rank == "catalyst_ratio":
if not return_X:
if not self.train_together:
processed_array = [
yield_array[
[x for x in range(yield_array.shape[0]) if x % 8 < 4], :
].T, # 11 x 20
yield_array[
[x for x in range(yield_array.shape[0]) if x % 8 >= 4],
:,
].T,
]
else:
if not self.train_together:
processed_array = yield_array.reshape()
else:
first_amine = []
second_amine = []
for i, row in enumerate(yield_array.T):
first_amine.append([])
second_amine.append([])
for j in range(
10
): # 10 chunks of 4-catalyst ratio values
if j % 2 == 0:
first_amine[i].append(
row[4 * j : 4 * (j + 1)].reshape(1, -1)
)
else:
second_amine[i].append(
row[4 * j : 4 * (j + 1)].reshape(1, -1)
)
subs_arrays = []
for row_first_amine, row_second_amine in zip(
first_amine, second_amine
):
subs_arrays.append(
np.vstack(
(
np.hstack(tuple(row_first_amine)),
np.hstack(tuple(row_second_amine)),
)
)
)
processed_array = np.vstack(tuple(subs_arrays))
else:
if not self.train_together:
processed_array = [substrate_array_to_process] * 2
else:
processed_array = np.hstack(
(
np.repeat(substrate_array_to_process, 2, axis=0),
other_array,
)
)
return processed_array
@property
def X_fp(self, fpSize=1024, radius=3):
"""
Prepares fingerprint arrays of substrates.
For regressors, other descriptors are appended after the substrate fingerprint.
Parameters
----------
fpSize : int
Length of the Morgan FP.
radius : int
Radius of the Morgan FP.
Returns
-------
X_fp : np.ndarray of shape (n_rxns, n_features)
n_features depends on self.for_regressor
"""
mfpgen = rdFingerprintGenerator.GetMorganGenerator(radius=radius, fpSize=fpSize)
cfp = [
mfpgen.GetCountFingerprintAsNumPy(Chem.MolFromSmiles(x))
for x in self.smiles_list
]
cfp_array = np.vstack(tuple(cfp))
if self.for_regressor:
if self.train_together:
other_array = self.desc
elif self.component_to_rank == "amine_ratio":
other_array = np.hstack(
(self.desc[:, :3], self.desc[:, -1].reshape(-1, 1))
)
elif self.component_to_rank == "catalyst_ratio":
other_array = self.desc[:, :4]
else:
if not self.train_together:
other_array = None
else:
if self.component_to_rank == "amine_ratio":
other_array = np.repeat(
self.desc[:4, :-1], 11, axis=0
) # 20 match 44
elif self.component_to_rank == "catalyst_ratio":
other_array = np.repeat(
np.vstack(
tuple(
[
row
for i, row in enumerate(
np.hstack(
(
self.desc[:8, :3],
self.desc[:8, -1].reshape(-1, 1),
)
)
)
if i % 4 == 0
]
)
),
11,
axis=0,
) # 10 match 22
self._X_fp = self._split_arrays(cfp_array, other_array)
return self._X_fp
@property
def X_desc(self):
substrate_desc = pd.read_excel("datasets/Informer.xlsx", sheet_name="substrate_descriptors").to_numpy()[:, 1:]
if self.for_regressor :
if self.component_to_rank == "amine_ratio" :
other_array = np.hstack(
(self.desc[:, :3], self.desc[:, -1].reshape(-1, 1))
)
elif self.component_to_rank == "catalyst_ratio" :
other_array = self.desc[:, :4]
else :
if self.component_to_rank == "amine_ratio" :
other_array = np.repeat(
self.desc[:4, :-1], 11, axis=0
)
elif self.component_to_rank == "catalyst_ratio":
other_array = np.repeat(
np.vstack(
tuple(
[
row
for i, row in enumerate(
np.hstack(
(
self.desc[:8, :3],
self.desc[:8, -1].reshape(-1, 1),
)
)
)
if i % 4 == 0
]
)
),
11,
axis=0,
)
self._X_desc = self._split_arrays(substrate_desc, other_array)
print("X DESC ARRAY SHAPE", self._X_desc[0].shape)
return self._X_desc
@property
def X_onehot(self):
"Prepares onehot arrays."
substrate_onehot_array = np.identity(len(self.smiles_list))
photocat_onehot_array = np.identity(5) # 5 photocatalysts
if self.for_regressor :
condition_array = np.hstack((
np.repeat(photocat_onehot_array, self.n_rank_component//5, axis=0),
np.tile(np.identity(self.n_rank_component//5), (5, 1))
))
self._X_onehot = np.hstack((
np.repeat(substrate_onehot_array, condition_array.shape[0], axis=0),
np.tile(condition_array, (substrate_onehot_array.shape[0], 1))
)) #for x in range(self.n_non_rank_component)]
else :
self._X_onehot = [substrate_onehot_array for x in range(self.n_non_rank_component)]
# if self.for_regressor :
# self._X_onehot = self._split_arrays(
# np.hstack(
# (
# substrate_onehot_array,
# photocat_onehot_array,
# # cat_ratio_onehot_array,
# amine_ratio_onehot_array,
# )
# ),
# )
# else :
# self._X_onehot = self._split_arrays(
# substrate_onehot_array
# )
return self._X_onehot
@property
def y_yield(self):
self._y_yield = self._split_arrays(None, None, return_X=False)
print(len(self._y_yield))
return self._y_yield
@property
def y_ranking(self):
if type(self.y_yield) == list:
self._y_ranking = [yield_to_ranking(x) for x in self.y_yield]
elif type(self.y_yield) == np.ndarray:
self._y_ranking = yield_to_ranking(self.y_yield)
return self._y_ranking
@property
def y_label(self):
yields = self.y_yield
if type(yields) == list:
labels = []
for i, y in enumerate(yields):
label = np.zeros_like(y)
# print(y)
nth_highest_yield = np.partition(y, -1 * self.n_rxns, axis=1)[
:, -1 * self.n_rxns
]
label[
y
>= np.hstack(tuple([nth_highest_yield.reshape(-1, 1)] * y.shape[1]))
] = 1
# print(label)
assert np.all(np.sum(label, axis=1) >= self.n_rxns)
labels.append(label)
elif type(yields) == np.ndarray:
labels = np.zeros_like(yields)
# print(yields)
nth_highest_yield = np.partition(yields, -1 * self.n_rxns, axis=1)[
:, -1 * self.n_rxns
]
labels[
yields
>= np.hstack(
tuple([nth_highest_yield.reshape(-1, 1)] * yields.shape[1])
)
] = 1
# print(labels)
# print(len(np.sum(labels, axis=1)))
assert np.all(np.sum(labels, axis=1) >= self.n_rxns)
self._y_label = labels
return self._y_label
class DeoxyDataset(Dataset):
"""
Prepares arrays from the deoxyfluorination dataset for downstream use.
Parameters
----------
for_regressor : bool
Whether the input will be used for training a regressor.
component_to_rank : str {'base', 'sulfonyl_fluoride', 'both'}
Which reaction component to be ranked.
train_together : bool
Whether the non-label reaction component should be trained altogether, or used as separate datasets.
Only considered when component_to_rank is not 'both'.
n_rxns : int
Number of reactions that we simulate to conduct.
Attributes
----------
X_fp : np.2darray of shape (n_samples, n_bits)
"""
def __init__(self, for_regressor, component_to_rank, train_together, n_rxns):
self.for_regressor = for_regressor
self.component_to_rank = component_to_rank
self.train_together = train_together
self.n_rxns = n_rxns
self.smiles_list = [
x[0]
for x in pd.read_excel(
"datasets/deoxyfluorination/substrate_smiles.xlsx", header=None
).values.tolist()
]
self.descriptors = pd.read_csv(
"datasets/deoxyfluorination/descriptor_table.csv"
).to_numpy()
self._raw_substrate_dft_desc = pd.read_csv(
"datasets/deoxyfluorination/alcohols_M062X.csv",
usecols=["name", "dipole", "electronegativity", "electronic_spatial_extent", "hardness", "homo_energy", "lumo_energy",
"C_Mulliken_charge", "C_NMR_anisotropy", "C_NMR_shift", "C_NPA_charge", "C_VBur",
"O_Mulliken_charge", "O_NMR_anisotropy", "O_NMR_shift", "O_NPA_charge", "O_VBur",
"order", "C_angle", "OC_length", "OC_L", "OC_B1", "OC_B5", "C_PVBur"
]
)
self._raw_substrate_dft_desc["order"] = self._raw_substrate_dft_desc["order"].map(
{"primary":1, "secondary":2, "tertiary":3}
)
self.reagent_desc = pd.read_csv(
"datasets/deoxyfluorination/descriptor_table.csv"
).to_numpy()[:, -4:]
self.onehot = pd.read_csv(
"datasets/deoxyfluorination/descriptor_table-OHE.csv"
).to_numpy()
self.yields = (
pd.read_csv("datasets/deoxyfluorination/observed_yields.csv", header=None)
.to_numpy()
.flatten()
)
if self.component_to_rank == "sulfonyl_fluoride":
self.n_rank_component = 5
self.n_non_rank_component = 4 # 4 bases
elif self.component_to_rank == "base":
self.n_rank_component = 4
self.n_non_rank_component = 5 # 5 sulfonyl fluorides
elif self.component_to_rank == "both":
self.n_rank_component = 20
def _combine_desc_arrays(self, substrate_array, reagent_array, n_base_bits=1):
"""
Combines feature arrays of a substrate and a reagent that first alters through
the reagent, followed by substrate.
e.g. if there are two reagents:
row1=(substrate1 + reagent1) // row2=(substrate1 + reagent2)
row3=(substrate2 + reagent1) // row4=(substrate2 + reagent2)
Parameters
---------
substrate_array : np.ndarray of shape (n_substrates, n_features)
Feature array of substrates
reagent_array : np.ndarray of shape (n_reagents, n_features)
Feature array of reagents
n_base_bits : int
Number of descriptor elements that bases take.
Returns
-------
combined_array : np.ndarray of shape (n_substrates * n_reagents, n_features_total)
Combined feature array.
"""
if (
self.component_to_rank == "sulfonyl_fluoride" and not self.for_regressor
) or (self.component_to_rank == "base" and self.for_regressor):
combined_array = np.hstack(
(
np.repeat(substrate_array, 4, axis=0),
np.tile(
reagent_array[
[5 * x for x in range(4)],
:n_base_bits,
],
(32, 1),
),
)
)
elif (self.component_to_rank == "base" and not self.for_regressor) or (
self.component_to_rank == "sulfonyl_fluoride" and self.for_regressor
):
combined_array = np.hstack(
(
np.repeat(
substrate_array,
5, # number of sulfonyl_fluoride
axis=0,
),
np.tile(
reagent_array[
[x for x in range(5)],
n_base_bits:, # adding sulfonyl fluoride features
],
(32, 1),
),
)
)
return combined_array
@property
def X_fp(self, fpSize=1024, radius=3):
"""
Prepares fingerprint arrays of substrates.
For regressors, other descriptors are appended after the substrate fingerprint.
Parameters
----------
fpSize : int
Length of the Morgan FP.
radius : int
Radius of the Morgan FP.
Returns
-------
X_fp : np.ndarray of shape (n_rxns, n_features)
n_features depends on self.for_regressor
"""
mfpgen = rdFingerprintGenerator.GetMorganGenerator(radius=radius, fpSize=fpSize)
fp_array = np.zeros((len(self.smiles_list), fpSize))
for i, smiles in enumerate(self.smiles_list):
fp_array[i] = mfpgen.GetCountFingerprintAsNumPy(Chem.MolFromSmiles(smiles))
reagent_desc = self.descriptors[:, -4:]
if self.for_regressor:
if self.component_to_rank == "both" or self.train_together:
self._X_fp = np.hstack(
(
np.repeat(fp_array, 20, axis=0),
reagent_desc,
)
)
else:
self._X_fp = self._combine_desc_arrays(fp_array, reagent_desc)
else:
if self.component_to_rank == "both":
self._X_fp = fp_array
elif self.component_to_rank in ["sulfonyl_fluoride", "base"]:
if self.train_together:
self._X_fp = self._combine_desc_arrays(fp_array, reagent_desc)
else:
self._X_fp = [fp_array] * self.n_non_rank_component
return self._X_fp
@property
def X_desc(self):
"""
Prepares descriptor arrays.
"""
import csv
with open("datasets/deoxyfluorination/descriptor_table-OHE.csv", newline="") as f :
reader = csv.reader(f)
first_row=next(reader)[:-9]
f.close()
alcohol_inds = [x[8:] for x in first_row]
subs_desc_rows = [self._raw_substrate_dft_desc[
self._raw_substrate_dft_desc["name"]==x
].to_numpy()[0, 1:] for x in alcohol_inds]
self._full_subs_desc = np.vstack(tuple(subs_desc_rows))
if self.for_regressor :
self._X_desc = self._combine_desc_arrays(
self._full_subs_desc,
self.reagent_desc
)
else :
self._X_desc = [self._full_subs_desc] * self.n_non_rank_component
return self._X_desc
@property
def X_random(self) :
np.random.seed(42)
_ = self.X_desc
orig_desc = deepcopy(self._full_subs_desc)
self._X_random = np.random.rand(orig_desc.shape[0], orig_desc.shape[1])
if self.for_regressor :
orig_reagent_desc = deepcopy(self.reagent_desc)
random_reagent_desc = np.random.rand(orig_reagent_desc.shape[0], orig_reagent_desc.shape[1])
self._X_random = self._combine_desc_arrays(
self._X_random,
random_reagent_desc
)
else :
self._X_random = [self._X_random] * self.n_non_rank_component
return self._X_random