File size: 77,093 Bytes
f2d6c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "import time\n",
    "import subprocess\n",
    "import logging\n",
    "import warnings\n",
    "import gc\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.patches as mpatches\n",
    "from concurrent.futures import ProcessPoolExecutor, as_completed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from rdkit import Chem\n",
    "from rdkit.Chem import AllChem, DataStructs, Draw\n",
    "from rdkit import RDConfig\n",
    "from rdkit.Chem import Descriptors, rdMolDescriptors, Lipinski, rdDistGeom, rdPartialCharges\n",
    "from rdkit.Chem.AllChem import GetMorganGenerator\n",
    "from rdkit.DataStructs.cDataStructs import ConvertToNumpyArray\n",
    "from rdkit.Avalon.pyAvalonTools import GetAvalonFP"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow import keras\n",
    "from tensorflow.keras import layers\n",
    "from tensorflow.keras.models import Sequential\n",
    "from tensorflow.keras.layers import Dense, Dropout, Activation\n",
    "from tensorflow.keras.regularizers import l2\n",
    "from tensorflow.keras.optimizers import Adam\n",
    "from tensorflow.keras import regularizers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.linear_model import Ridge\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.neural_network import MLPRegressor\n",
    "from sklearn.svm import SVR\n",
    "from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error, root_mean_squared_error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "import optuna\n",
    "from optuna.trial import TrialState"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "tf.keras.backend.clear_session()\n",
    "gpus = tf.config.experimental.list_physical_devices('GPU')\n",
    "if gpus:\n",
    "    try:\n",
    "        for gpu in gpus:\n",
    "            tf.config.experimental.set_memory_growth(gpu, True)\n",
    "    except RuntimeError as e:\n",
    "        print(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "target_path = \"result/5_ANO_structure\"\n",
    "os.makedirs(target_path, exist_ok=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_ws = pd.read_csv('./data/ws496_logS.csv', dtype={'SMILES': 'string'})\n",
    "smiles_ws = data_ws['SMILES']\n",
    "y_ws = data_ws.iloc[:, 2]\n",
    "\n",
    "data_delaney = pd.read_csv('./data/delaney-processed.csv', dtype={'smiles': 'string'})\n",
    "smiles_de = data_delaney['smiles']\n",
    "y_de = data_delaney.iloc[:, 1]\n",
    "\n",
    "data_lovric2020 = pd.read_csv('./data/Lovric2020_logS0.csv', dtype={'isomeric_smiles': 'string'})\n",
    "smiles_lo = data_lovric2020['isomeric_smiles']\n",
    "y_lo = data_lovric2020.iloc[:, 1]\n",
    "\n",
    "data_huuskonen = pd.read_csv('./data/huusk.csv', dtype={'SMILES': 'string'})\n",
    "smiles_hu = data_huuskonen['SMILES']\n",
    "y_hu = data_huuskonen.iloc[:, -1].astype('float')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mol3d(mol):\n",
    "    mol = Chem.AddHs(mol)\n",
    "    optimization_methods = [\n",
    "        (AllChem.EmbedMolecule, (mol, AllChem.ETKDGv3()), {}),\n",
    "        (AllChem.UFFOptimizeMolecule, (mol,), {'maxIters': 200}),\n",
    "        (AllChem.MMFFOptimizeMolecule, (mol,), {'maxIters': 200})\n",
    "    ]\n",
    "\n",
    "    for method, args, kwargs in optimization_methods:\n",
    "        try:\n",
    "            method(*args, **kwargs)\n",
    "            if mol.GetNumConformers() > 0:\n",
    "                return mol\n",
    "        except ValueError as e:\n",
    "            print(f\"Error: {e} - Trying next optimization method [{method}]\")\n",
    "\n",
    "    print(f\"Invalid mol for 3d {'\\033[94m'}{Chem.MolToSmiles(mol)}{'\\033[0m'} - No conformer generated\")\n",
    "    return None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "def convert_smiles_to_mol(smiles, fail_folder=None, index=None, yvalue=None):\n",
    "    mol = Chem.MolFromSmiles(smiles)\n",
    "    if mol is None:\n",
    "        print(f\"[convert_smiles_to_mol] Cannot convert {smiles} to Mols\")\n",
    "        return None, {\"smiles\": smiles, \"y_value\": yvalue, \"error\": \"Invalid SMILES\"}\n",
    "\n",
    "    try:\n",
    "        Chem.Kekulize(mol, clearAromaticFlags=True)\n",
    "        isomeric_smiles = Chem.MolToSmiles(mol, isomericSmiles=True)\n",
    "        mol = Chem.MolFromSmiles(isomeric_smiles)\n",
    "    except Exception as e:\n",
    "        print(f\"[convert_smiles_to_mol] failed {smiles} isomeric_smiles by {e}\")\n",
    "        if fail_folder and index is not None:\n",
    "            img_path = os.path.join(fail_folder, f\"mol_{index}.png\")\n",
    "            img = Draw.MolToImage(mol)\n",
    "            img.save(img_path)\n",
    "        return None, {\"smiles\": smiles, \"y_value\": yvalue, \"error\": f\"Isomeric SMILES error: {e}\"}\n",
    "\n",
    "    try:\n",
    "        Chem.SanitizeMol(mol)\n",
    "    except Exception as e:\n",
    "        print(f\"[convert_smiles_to_mol] failed {smiles} SanitizeMol by {e}\")\n",
    "        if fail_folder and index is not None:\n",
    "            img_path = os.path.join(fail_folder, f\"mol_{index}.png\")\n",
    "            img = Draw.MolToImage(mol)\n",
    "            img.save(img_path)\n",
    "        return None, {\"smiles\": smiles, \"y_value\": yvalue, \"error\": f\"SanitizeMol error: {e}\"}\n",
    "\n",
    "    return mol, None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_smiles(smiles, yvalue, fail_folder, index):\n",
    "    mol, error = convert_smiles_to_mol(smiles, fail_folder, index, yvalue)\n",
    "    if error:\n",
    "        return None, None, error\n",
    "\n",
    "    mol_3d = mol3d(mol)\n",
    "    if mol_3d:\n",
    "        return smiles, yvalue, None\n",
    "    else:\n",
    "        img_path = os.path.join(fail_folder, f\"mol_{index}.png\")\n",
    "        img = Draw.MolToImage(mol)\n",
    "        img.save(img_path)\n",
    "        return None, None, {\"smiles\": smiles, \"y_value\": yvalue}\n",
    "\n",
    "def process_dataset(smiles_list, y_values, dataset_name, target_path=\"result\", max_workers=None):\n",
    "    start = time.time()\n",
    "    valid_smiles, valid_y = [], []\n",
    "    error_smiles_list = []\n",
    "    fail_folder = f\"{target_path}/failed/{dataset_name}\"\n",
    "    os.makedirs(fail_folder, exist_ok=True)\n",
    "\n",
    "    with ProcessPoolExecutor(max_workers=max_workers) as executor:\n",
    "        futures = [\n",
    "            executor.submit(process_smiles, smiles, yvalue, fail_folder, i)\n",
    "            for i, (smiles, yvalue) in enumerate(zip(smiles_list, y_values))\n",
    "        ]\n",
    "        for future in as_completed(futures):\n",
    "            smiles, yvalue, error = future.result()\n",
    "            if error:\n",
    "                error_smiles_list.append(error)\n",
    "            elif smiles is not None and yvalue is not None:\n",
    "                valid_smiles.append(smiles)\n",
    "                valid_y.append(yvalue)\n",
    "\n",
    "    if error_smiles_list:\n",
    "        error_df = pd.DataFrame(error_smiles_list)\n",
    "        error_df.to_csv(os.path.join(fail_folder, \"failed_smiles.csv\"), index=False)\n",
    "    print(f\" [{dataset_name:<10}] : {time.time()-start:.4f} sec\")\n",
    "    return valid_smiles, valid_y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " [ws496     ] : 0.8649 sec\n",
      " [delaney   ] : 1.3527 sec\n",
      "Error: Bad Conformer Id - Trying next optimization method [<Boost.Python.function object at 0x560fe30ad760>]\n",
      "Error: Bad Conformer Id - Trying next optimization method [<Boost.Python.function object at 0x560fe30ae5f0>]\n",
      "Invalid mol for 3d \u001b[94m[H]O[C@@]([H])(c1c([H])c([H])nc2c([H])c([H])c(OC([H])([H])[H])c([H])c12)[C@]1([H])[N@]2C([H])([H])C([H])([H])[C@@]([H])(C1([H])[H])[C@@]([H])(C([H])=C([H])[H])C2([H])[H]\u001b[0m - No conformer generated\n",
      "Error: Bad Conformer Id - Trying next optimization method [<Boost.Python.function object at 0x560fe30ad760>]\n",
      "Error: Bad Conformer Id - Trying next optimization method [<Boost.Python.function object at 0x560fe30ae5f0>]\n",
      "Invalid mol for 3d \u001b[94m[H]O[C@]([H])(c1c([H])c([H])nc2c([H])c([H])c(OC([H])([H])[H])c([H])c12)[C@@]1([H])[N@]2C([H])([H])C([H])([H])[C@@]([H])(C1([H])[H])[C@@]([H])(C([H])=C([H])[H])C2([H])[H]\u001b[0m - No conformer generated\n",
      " [Lovric2020_logS0] : 8.3057 sec\n",
      " [huusk     ] : 1.5089 sec\n"
     ]
    }
   ],
   "source": [
    "smiles_ws, y_ws = process_dataset(smiles_ws, y_ws, \"ws496\", target_path)\n",
    "smiles_de, y_de = process_dataset(smiles_de, y_de, \"delaney\", target_path)\n",
    "smiles_lo, y_lo = process_dataset(smiles_lo, y_lo, \"Lovric2020_logS0\", target_path)\n",
    "smiles_hu, y_hu = process_dataset(smiles_hu, y_hu, \"huusk\", target_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "LEN_OF_FF = 2048\n",
    "LEN_OF_MA = 167\n",
    "LEN_OF_AV = 512"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_fingerprints(mol):\n",
    "    if mol is None:\n",
    "        return None, None, None\n",
    "    \n",
    "    morgan_generator = GetMorganGenerator(radius=2, fpSize=LEN_OF_FF)\n",
    "    ecfp = morgan_generator.GetFingerprint(mol)\n",
    "    ecfp_array = np.zeros((LEN_OF_FF,),dtype=int)\n",
    "    DataStructs.ConvertToNumpyArray(ecfp, ecfp_array)\n",
    "    \n",
    "    maccs = Chem.rdMolDescriptors.GetMACCSKeysFingerprint(mol)\n",
    "\n",
    "    avalon_fp = GetAvalonFP(mol)\n",
    "    avalon_array = np.zeros((LEN_OF_AV,),dtype=int)\n",
    "    DataStructs.ConvertToNumpyArray(avalon_fp, avalon_array)\n",
    "    \n",
    "    return ecfp_array, maccs, avalon_array\n",
    "\n",
    "def fp_converter(data, use_parallel=True):\n",
    "    mols = [Chem.MolFromSmiles(smi) for smi in data]\n",
    "    \n",
    "    if use_parallel:\n",
    "        try:            \n",
    "            with ProcessPoolExecutor() as executor:\n",
    "                results = list(executor.map(get_fingerprints, mols))\n",
    "        except Exception as e:\n",
    "            print(f\"Parallel processing failed due to: {e}. Falling back to sequential processing.\")\n",
    "            use_parallel = False\n",
    "    \n",
    "    if not use_parallel:\n",
    "        results = [get_fingerprints(mol) for mol in mols]\n",
    "    \n",
    "    ECFP, MACCS, AvalonFP = zip(*results)\n",
    "    \n",
    "    ECFP_container = np.vstack([arr for arr in ECFP if arr is not None])\n",
    "    MACCS_container = np.zeros((len(MACCS), LEN_OF_MA), dtype=int)\n",
    "    AvalonFP_container = np.vstack([arr for arr in AvalonFP if arr is not None])\n",
    "\n",
    "    for i, fp in enumerate(MACCS):\n",
    "        if fp is not None:\n",
    "            DataStructs.ConvertToNumpyArray(fp, MACCS_container[i])\n",
    "    \n",
    "    return mols, ECFP_container, MACCS_container, AvalonFP_container"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "mol_ws, x_ws, MACCS_ws, AvalonFP_ws = fp_converter(smiles_ws,target_path)\n",
    "mol_de, x_de, MACCS_de, AvalonFP_de = fp_converter(smiles_de,target_path)\n",
    "mol_lo, x_lo, MACCS_lo, AvalonFP_lo = fp_converter(smiles_lo,target_path)\n",
    "mol_hu, x_hu, MACCS_hu, AvalonFP_hu = fp_converter(smiles_hu,target_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "def concatenate_to_numpy(*dataframes):\n",
    "    numpy_arrays = [df.to_numpy() if isinstance(df, pd.DataFrame) else df for df in dataframes]\n",
    "    if not all(isinstance(arr, np.ndarray) for arr in numpy_arrays):\n",
    "        raise ValueError(\"All inputs must be either pandas DataFrame or numpy array\")\n",
    "    return np.concatenate(numpy_arrays, axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "group_nws = concatenate_to_numpy(x_ws, MACCS_ws, AvalonFP_ws)\n",
    "group_nde = concatenate_to_numpy(x_de, MACCS_de, AvalonFP_de)\n",
    "group_nlo = concatenate_to_numpy(x_lo, MACCS_lo, AvalonFP_lo)\n",
    "group_nhu = concatenate_to_numpy(x_hu, MACCS_hu, AvalonFP_hu)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "BATCHSIZE = 32\n",
    "EPOCHS = 1000\n",
    "lr = 0.0001\n",
    "decay = 1e-4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [],
   "source": [
    "def search_model(trial, input_dim):\n",
    "    n_layers = trial.suggest_int(\"n_layers\", 1, 3)\n",
    "    model = tf.keras.Sequential()\n",
    "    model.add(tf.keras.layers.Input(shape=(input_dim,)))\n",
    "    layer_dropout = trial.suggest_int(\"layer_dropout\", 0, 1)\n",
    "    \n",
    "    for i in range(n_layers):\n",
    "        num_hidden = trial.suggest_int(f\"n_units_l_{i}\", 2, 10000)\n",
    "        num_decay = trial.suggest_categorical(f\"n_decay_l_{i}\", [1e-3, 1e-4, 1e-5])\n",
    "        model.add(\n",
    "            tf.keras.layers.Dense(\n",
    "                num_hidden,\n",
    "                activation=\"relu\",\n",
    "                kernel_initializer='glorot_uniform',\n",
    "                kernel_regularizer=tf.keras.regularizers.l2(num_decay),\n",
    "            )\n",
    "        )\n",
    "        if layer_dropout == 1:\n",
    "            fdropout1 = trial.suggest_categorical(f\"F_dropout_{i}\", [0.1, 0.2, 0.3])\n",
    "            model.add(tf.keras.layers.Dropout(rate=fdropout1))\n",
    "            \n",
    "    if layer_dropout == 0:\n",
    "        fdropout2 = trial.suggest_categorical(\"last_dropout\", [0.1, 0.2, 0.3])\n",
    "        model.add(tf.keras.layers.Dropout(rate=fdropout2))\n",
    "    \n",
    "    model.add(tf.keras.layers.Dense(units=1))\n",
    "    # # Colab\n",
    "    # learningr = trial.suggest_categorical(\"Learning_rate\",[0.01,0.001,0.0001])\n",
    "    # model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=learningr),\n",
    "    #                 loss=tf.keras.losses.MeanSquaredError(),\n",
    "    #                 metrics=[tf.keras.losses.MeanSquaredError(),\n",
    "    #                         tf.keras.losses.MeanAbsoluteError(),\n",
    "    #                         tf.keras.metrics.RootMeanSquaredError()])\n",
    "    return model\n",
    "\n",
    "def save_model(trial, x_data):\n",
    "    model_path = \"save_model/full_model.keras\"\n",
    "    if not os.path.exists(model_path):\n",
    "        try:\n",
    "            model = search_model(trial, x_data.shape[1])\n",
    "            os.makedirs(\"save_model\", exist_ok=True)\n",
    "            model.save(model_path)\n",
    "            print(f\"Model successfully saved to {model_path}\")\n",
    "        except Exception as e:\n",
    "            print(f\"Error saving model: {e}\")\n",
    "    else:\n",
    "        print(f\"Model already exists at {model_path}\")\n",
    "        os.remove(model_path)\n",
    "        save_model(trial, x_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import warnings\n",
    "\n",
    "os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n",
    "os.environ['TF_GPU_ALLOCATOR'] = 'cuda_malloc_async'\n",
    "os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n",
    "os.environ['TF_XLA_FLAGS'] = '--tf_xla_auto_jit=2 --tf_xla_enable_xla_devices'\n",
    "os.environ['XLA_FLAGS'] = '--xla_gpu_cuda_data_dir=/usr/local/cuda --xla_gpu_force_compilation_parallelism=1'\n",
    "os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\n",
    "os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'\n",
    "os.environ['TF_NUMA_NODES'] = '1'\n",
    "\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "warnings.simplefilter(action='ignore', category=FutureWarning)\n",
    "\n",
    "logging.getLogger('tensorflow').setLevel(logging.ERROR)\n",
    "\n",
    "tf.get_logger().setLevel('ERROR')\n",
    "tf.autograph.set_verbosity(0)\n",
    "\n",
    "def suppress_warnings(condition=True):\n",
    "    if condition:\n",
    "        logging.getLogger('tensorflow').setLevel(logging.ERROR)\n",
    "        os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n",
    "    else:\n",
    "        logging.getLogger('tensorflow').setLevel(logging.WARNING)\n",
    "        os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'\n",
    "\n",
    "suppress_warnings(condition=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "def objective_ws_struct(trial):\n",
    "    try:\n",
    "        y_true = np.asarray(y_ws).astype('float')\n",
    "        np.save('new_fps.npy', group_nws)\n",
    "        np.save('y_true.npy', y_true)\n",
    "        \n",
    "        save_model(trial, group_nws)\n",
    "\n",
    "        lr = trial.suggest_categorical(f\"lr\", [1e-3, 1e-4, 1e-5])\n",
    "\n",
    "        result = subprocess.run(['python3', './extra_code/learning_process.py', \n",
    "                                str(BATCHSIZE), str(EPOCHS), \n",
    "                                str(lr), \n",
    "                                'new_fps.npy', 'y_true.npy'],\n",
    "                                stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\n",
    "\n",
    "        if result.stderr:\n",
    "            filtered_stderr = '\\n'.join([line for line in result.stderr.split('\\n') if \"could not open file to read NUMA node\" not in line and \"Your kernel may have been built without NUMA support\" not in line])\n",
    "            if filtered_stderr:\n",
    "                print(f\"Error in subprocess: {filtered_stderr}\", file=sys.stderr)\n",
    "\n",
    "        for line in result.stdout.splitlines():\n",
    "            if \"R2\" in line:\n",
    "                if \"(prune)\" in line:\n",
    "                    print(f\"Pruning trial due to poor R2: {line}\")\n",
    "                    r2_result = 0.0\n",
    "                    trial.report(r2_result, step=0)\n",
    "                    raise optuna.exceptions.TrialPruned()\n",
    "                else:\n",
    "                    r2_result = float(line.split(\":\")[1].strip())\n",
    "                    print(f\"R2 score: {r2_result}\")\n",
    "                    trial.report(r2_result, step=0)\n",
    "\n",
    "                    if trial.should_prune():\n",
    "                        raise optuna.exceptions.TrialPruned()\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"Exception occurred: {e}\", file=sys.stderr)\n",
    "        r2_result = 0.0\n",
    "\n",
    "    gc.collect()\n",
    "\n",
    "    return r2_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "def objective_de_struct(trial):\n",
    "    try:\n",
    "        y_true = np.asarray(y_de).astype('float')\n",
    "        np.save('new_fps.npy', group_nde)\n",
    "        np.save('y_true.npy', y_true)\n",
    "        \n",
    "        save_model(trial, group_nde)\n",
    "\n",
    "        lr = trial.suggest_categorical(f\"lr\", [1e-3, 1e-4, 1e-5])\n",
    "\n",
    "        result = subprocess.run(['python3', './extra_code/learning_process.py', \n",
    "                                str(BATCHSIZE), str(EPOCHS), \n",
    "                                str(lr), \n",
    "                                'new_fps.npy', 'y_true.npy'],\n",
    "                                stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\n",
    "\n",
    "        if result.stderr:\n",
    "            filtered_stderr = '\\n'.join([line for line in result.stderr.split('\\n') if \"could not open file to read NUMA node\" not in line and \"Your kernel may have been built without NUMA support\" not in line])\n",
    "            if filtered_stderr:\n",
    "                print(f\"Error in subprocess: {filtered_stderr}\", file=sys.stderr)\n",
    "\n",
    "        for line in result.stdout.splitlines():\n",
    "            if \"R2\" in line:\n",
    "                if \"(prune)\" in line:\n",
    "                    print(f\"Pruning trial due to poor R2: {line}\")\n",
    "                    r2_result = 0.0\n",
    "                    trial.report(r2_result, step=0)\n",
    "                    raise optuna.exceptions.TrialPruned()\n",
    "                else:\n",
    "                    r2_result = float(line.split(\":\")[1].strip())\n",
    "                    print(f\"R2 score: {r2_result}\")\n",
    "                    trial.report(r2_result, step=0)\n",
    "\n",
    "                    if trial.should_prune():\n",
    "                        raise optuna.exceptions.TrialPruned()\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"Exception occurred: {e}\", file=sys.stderr)\n",
    "        r2_result = 0.0\n",
    "\n",
    "    gc.collect()\n",
    "\n",
    "    return r2_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "def objective_lo_struct(trial):\n",
    "    try:\n",
    "        y_true = np.asarray(y_lo).astype('float')\n",
    "        np.save('new_fps.npy', group_nlo)\n",
    "        np.save('y_true.npy', y_true)\n",
    "        \n",
    "        save_model(trial, group_nlo)\n",
    "\n",
    "        lr = trial.suggest_categorical(f\"lr\", [1e-3, 1e-4, 1e-5])\n",
    "\n",
    "        result = subprocess.run(['python3', './extra_code/learning_process.py', \n",
    "                                str(BATCHSIZE), str(EPOCHS), \n",
    "                                str(lr), \n",
    "                                'new_fps.npy', 'y_true.npy'],\n",
    "                                stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\n",
    "\n",
    "        if result.stderr:\n",
    "            filtered_stderr = '\\n'.join([line for line in result.stderr.split('\\n') if \"could not open file to read NUMA node\" not in line and \"Your kernel may have been built without NUMA support\" not in line])\n",
    "            if filtered_stderr:\n",
    "                print(f\"Error in subprocess: {filtered_stderr}\", file=sys.stderr)\n",
    "\n",
    "        for line in result.stdout.splitlines():\n",
    "            if \"R2\" in line:\n",
    "                if \"(prune)\" in line:\n",
    "                    print(f\"Pruning trial due to poor R2: {line}\")\n",
    "                    r2_result = 0.0\n",
    "                    trial.report(r2_result, step=0)\n",
    "                    raise optuna.exceptions.TrialPruned()\n",
    "                else:\n",
    "                    r2_result = float(line.split(\":\")[1].strip())\n",
    "                    print(f\"R2 score: {r2_result}\")\n",
    "                    trial.report(r2_result, step=0)\n",
    "\n",
    "                    if trial.should_prune():\n",
    "                        raise optuna.exceptions.TrialPruned()\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"Exception occurred: {e}\", file=sys.stderr)\n",
    "        r2_result = 0.0\n",
    "\n",
    "    gc.collect()\n",
    "\n",
    "    return r2_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "def objective_hu_struct(trial):\n",
    "    try:\n",
    "        y_true = np.asarray(y_hu).astype('float')\n",
    "        np.save('new_fps.npy', group_nhu)\n",
    "        np.save('y_true.npy', y_true)\n",
    "        \n",
    "        save_model(trial, group_nhu)\n",
    "\n",
    "        lr = trial.suggest_categorical(f\"lr\", [1e-3, 1e-4, 1e-5])\n",
    "\n",
    "        result = subprocess.run(['python3', './extra_code/learning_process.py', \n",
    "                                str(BATCHSIZE), str(EPOCHS), \n",
    "                                str(lr), \n",
    "                                'new_fps.npy', 'y_true.npy'],\n",
    "                                stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)\n",
    "\n",
    "        if result.stderr:\n",
    "            filtered_stderr = '\\n'.join([line for line in result.stderr.split('\\n') if \"could not open file to read NUMA node\" not in line and \"Your kernel may have been built without NUMA support\" not in line])\n",
    "            if filtered_stderr:\n",
    "                print(f\"Error in subprocess: {filtered_stderr}\", file=sys.stderr)\n",
    "\n",
    "        for line in result.stdout.splitlines():\n",
    "            if \"R2\" in line:\n",
    "                if \"(prune)\" in line:\n",
    "                    print(f\"Pruning trial due to poor R2: {line}\")\n",
    "                    r2_result = 0.0\n",
    "                    trial.report(r2_result, step=0)\n",
    "                    raise optuna.exceptions.TrialPruned()\n",
    "                else:\n",
    "                    r2_result = float(line.split(\":\")[1].strip())\n",
    "                    print(f\"R2 score: {r2_result}\")\n",
    "                    trial.report(r2_result, step=0)\n",
    "\n",
    "                    if trial.should_prune():\n",
    "                        raise optuna.exceptions.TrialPruned()\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"Exception occurred: {e}\", file=sys.stderr)\n",
    "        r2_result = 0.0\n",
    "\n",
    "    gc.collect()\n",
    "\n",
    "    return r2_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [],
   "source": [
    "storage = optuna.storages.RDBStorage(url=\"sqlite:///ano_analysis.db\", engine_kwargs={\"connect_args\": {\"timeout\": 10000}})\n",
    "# storage_urls = \"postgresql+psycopg2://postgres:{pwd}}@localhost:{num}}\"\n",
    "# storage = optuna.storages.RDBStorage(url=storage_urls)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    optuna.delete_study(study_name=\"ANO_ws_struct\", storage=storage)\n",
    "    optuna.delete_study(study_name=\"ANO_de_struct\", storage=storage)\n",
    "    optuna.delete_study(study_name=\"ANO_lo_struct\", storage=storage)\n",
    "    optuna.delete_study(study_name=\"ANO_hu_struct\", storage=storage)\n",
    "except:\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "TRIALS = 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:27:16,193] A new study created in RDB with name: ANO_ws_struct\n",
      "I0000 00:00:1729823236.262387  712386 cuda_executor.cc:1001] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node\n",
      "Your kernel may have been built without NUMA support.\n",
      "I0000 00:00:1729823236.262494  712386 cuda_executor.cc:1001] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node\n",
      "Your kernel may have been built without NUMA support.\n",
      "I0000 00:00:1729823236.262547  712386 cuda_executor.cc:1001] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node\n",
      "Your kernel may have been built without NUMA support.\n",
      "I0000 00:00:1729823236.414390  712386 cuda_executor.cc:1001] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node\n",
      "Your kernel may have been built without NUMA support.\n",
      "I0000 00:00:1729823236.414547  712386 cuda_executor.cc:1001] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node\n",
      "Your kernel may have been built without NUMA support.\n",
      "2024-10-25 11:27:16.414564: I tensorflow/core/common_runtime/gpu/gpu_device.cc:2112] Could not identify NUMA node of platform GPU id 0, defaulting to 0.  Your kernel may not have been built with NUMA support.\n",
      "2024-10-25 11:27:16.414596: I tensorflow/core/common_runtime/gpu/gpu_process_state.cc:198] Using CUDA malloc Async allocator for GPU: 0\n",
      "I0000 00:00:1729823236.414877  712386 cuda_executor.cc:1001] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node\n",
      "Your kernel may have been built without NUMA support.\n",
      "2024-10-25 11:27:16.414914: I tensorflow/core/common_runtime/gpu/gpu_device.cc:2021] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 3586 MB memory:  -> device: 0, name: NVIDIA GeForce RTX 3060 Laptop GPU, pci bus id: 0000:01:00.0, compute capability: 8.6\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823240.072256  713235 service.cc:146] XLA service 0x558b4abf8ec0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823240.072318  713235 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823240.199007  713235 service.cc:146] XLA service 0x558b4b330cb0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823240.199045  713235 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823242.903035  713344 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.72685\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:27:28,379] Trial 0 finished with value: 0.72685 and parameters: {'n_layers': 1, 'layer_dropout': 0, 'n_units_l_0': 9922, 'n_decay_l_0': 1e-05, 'last_dropout': 0.1, 'lr': 0.001}. Best is trial 0 with value: 0.72685.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823251.215260  714082 service.cc:146] XLA service 0x55a8ec6b6500 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823251.215311  714082 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823251.333433  714082 service.cc:146] XLA service 0x55a8ec5cd290 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823251.333463  714082 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823263.351498  714193 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.707063\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:28:11,955] Trial 1 finished with value: 0.707063 and parameters: {'n_layers': 2, 'layer_dropout': 0, 'n_units_l_0': 6572, 'n_decay_l_0': 1e-05, 'n_units_l_1': 1332, 'n_decay_l_1': 0.0001, 'last_dropout': 0.3, 'lr': 1e-05}. Best is trial 0 with value: 0.72685.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823294.853158  716419 service.cc:146] XLA service 0x55b5e46a62f0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823294.853225  716419 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823295.002577  716419 service.cc:146] XLA service 0x55b5e46e5fb0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823295.002610  716419 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823297.511032  716525 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.705862\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:28:23,131] Trial 2 finished with value: 0.705862 and parameters: {'n_layers': 1, 'layer_dropout': 1, 'n_units_l_0': 3241, 'n_decay_l_0': 1e-05, 'F_dropout_0': 0.2, 'lr': 0.0001}. Best is trial 0 with value: 0.72685.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-10-25 11:28:23.378722: W external/local_tsl/tsl/framework/cpu_allocator_impl.cc:83] Allocation of 286627920 exceeds 10% of free system memory.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823306.834696  718042 service.cc:146] XLA service 0x55ff6bc60e10 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823306.834744  718042 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823306.978987  718042 service.cc:146] XLA service 0x55ff6bc7c930 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823306.979019  718042 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823333.708484  718154 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.741337\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:30:53,672] Trial 3 finished with value: 0.741337 and parameters: {'n_layers': 3, 'layer_dropout': 0, 'n_units_l_0': 787, 'n_decay_l_0': 0.0001, 'n_units_l_1': 9082, 'n_decay_l_1': 0.001, 'n_units_l_2': 7890, 'n_decay_l_2': 0.001, 'last_dropout': 0.1, 'lr': 0.0001}. Best is trial 3 with value: 0.741337.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823456.995677  725244 service.cc:146] XLA service 0x56214db0e060 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823456.995725  725244 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823457.136743  725244 service.cc:146] XLA service 0x56214da498b0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823457.136787  725244 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823459.392929  725349 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.68373\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:31:13,484] Trial 4 finished with value: 0.68373 and parameters: {'n_layers': 1, 'layer_dropout': 0, 'n_units_l_0': 1253, 'n_decay_l_0': 0.0001, 'last_dropout': 0.2, 'lr': 1e-05}. Best is trial 3 with value: 0.741337.\n"
     ]
    }
   ],
   "source": [
    "study_ws_struct = optuna.create_study(study_name='ANO_ws_struct', storage=storage, direction=\"maximize\", pruner=optuna.pruners.SuccessiveHalvingPruner(reduction_factor=64, min_early_stopping_rate=10),load_if_exists=True)     \n",
    "# study_ws_fea = optuna.create_study(study_name='ANO_ws_struct', storage=storage, direction=\"maximize\", pruner=optuna.pruners.HyperbandPruner(min_resource=100,max_resource=1000,reduction_factor=3), load_if_exists=True)\n",
    "study_ws_struct.optimize(objective_ws_struct, n_trials=TRIALS)\n",
    "pruned_trials_ws_struct = study_ws_struct.get_trials(deepcopy=False, states=[TrialState.PRUNED])\n",
    "complete_trials_ws_struct = study_ws_struct.get_trials(deepcopy=False, states=[TrialState.COMPLETE])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:31:13,504] A new study created in RDB with name: ANO_de_struct\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823476.380438  735317 service.cc:146] XLA service 0x564b5beee4b0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823476.380497  735317 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823476.549364  735317 service.cc:146] XLA service 0x564b5be2ad00 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823476.549448  735317 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823490.704246  735426 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.803869\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:32:02,303] Trial 0 finished with value: 0.803869 and parameters: {'n_layers': 2, 'layer_dropout': 0, 'n_units_l_0': 1737, 'n_decay_l_0': 1e-05, 'n_units_l_1': 6702, 'n_decay_l_1': 1e-05, 'last_dropout': 0.2, 'lr': 0.001}. Best is trial 0 with value: 0.803869.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823525.878834  736385 service.cc:146] XLA service 0x55bad3cb21e0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823525.878873  736385 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823526.015032  736385 service.cc:146] XLA service 0x55bad3c304f0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823526.015066  736385 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823529.879054  736488 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.826782\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:32:39,308] Trial 1 finished with value: 0.826782 and parameters: {'n_layers': 2, 'layer_dropout': 1, 'n_units_l_0': 9935, 'n_decay_l_0': 1e-05, 'F_dropout_0': 0.2, 'n_units_l_1': 3544, 'n_decay_l_1': 1e-05, 'F_dropout_1': 0.3, 'lr': 0.0001}. Best is trial 1 with value: 0.826782.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823562.604376  737355 service.cc:146] XLA service 0x55eaf2377f20 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823562.604431  737355 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823562.742863  737355 service.cc:146] XLA service 0x55eaf23d2e30 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823562.742895  737355 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823566.592650  737461 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.823751\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:33:33,879] Trial 2 finished with value: 0.823751 and parameters: {'n_layers': 2, 'layer_dropout': 1, 'n_units_l_0': 7233, 'n_decay_l_0': 1e-05, 'F_dropout_0': 0.2, 'n_units_l_1': 4859, 'n_decay_l_1': 0.0001, 'F_dropout_1': 0.3, 'lr': 0.001}. Best is trial 1 with value: 0.826782.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823616.856357  739058 service.cc:146] XLA service 0x55d8efa212a0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823616.856406  739058 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823616.997938  739058 service.cc:146] XLA service 0x55d8ef979320 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823616.997975  739058 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823621.412038  739168 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.796098\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:34:39,639] Trial 3 finished with value: 0.796098 and parameters: {'n_layers': 3, 'layer_dropout': 1, 'n_units_l_0': 809, 'n_decay_l_0': 1e-05, 'F_dropout_0': 0.3, 'n_units_l_1': 3939, 'n_decay_l_1': 0.0001, 'F_dropout_1': 0.2, 'n_units_l_2': 6198, 'n_decay_l_2': 0.0001, 'F_dropout_2': 0.1, 'lr': 0.001}. Best is trial 1 with value: 0.826782.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823682.926391  740686 service.cc:146] XLA service 0x5579d09bb100 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823682.926465  740686 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823683.068876  740686 service.cc:146] XLA service 0x5579d09fa810 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823683.068912  740686 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823696.228323  740798 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.84961\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:37:05,301] Trial 4 finished with value: 0.84961 and parameters: {'n_layers': 2, 'layer_dropout': 0, 'n_units_l_0': 7109, 'n_decay_l_0': 0.001, 'n_units_l_1': 3436, 'n_decay_l_1': 1e-05, 'last_dropout': 0.3, 'lr': 1e-05}. Best is trial 4 with value: 0.84961.\n"
     ]
    }
   ],
   "source": [
    "study_de_struct = optuna.create_study(study_name='ANO_de_struct', storage=storage, direction=\"maximize\", pruner=optuna.pruners.SuccessiveHalvingPruner(reduction_factor=64, min_early_stopping_rate=10),load_if_exists=True)     \n",
    "# study_de_fea = optuna.create_study(study_name='ANO_de_struct', storage=storage, direction=\"maximize\", pruner=optuna.pruners.HyperbandPruner(min_resource=100,max_resource=1000,reduction_factor=3), load_if_exists=True)\n",
    "study_de_struct.optimize(objective_de_struct, n_trials=TRIALS)\n",
    "pruned_trials_de_struct = study_de_struct.get_trials(deepcopy=False, states=[TrialState.PRUNED])\n",
    "complete_trials_de_struct = study_de_struct.get_trials(deepcopy=False, states=[TrialState.COMPLETE])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:37:05,323] A new study created in RDB with name: ANO_lo_struct\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823828.951072  753530 service.cc:146] XLA service 0x560175567120 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823828.951145  753530 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823829.108219  753530 service.cc:146] XLA service 0x56017553de50 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823829.108251  753530 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823833.863752  753634 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.679332\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:39:42,324] Trial 0 finished with value: 0.679332 and parameters: {'n_layers': 2, 'layer_dropout': 1, 'n_units_l_0': 7114, 'n_decay_l_0': 0.001, 'F_dropout_0': 0.1, 'n_units_l_1': 7475, 'n_decay_l_1': 0.0001, 'F_dropout_1': 0.3, 'lr': 1e-05}. Best is trial 0 with value: 0.679332.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729823985.424040  762359 service.cc:146] XLA service 0x55d75759be40 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823985.424082  762359 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729823985.555550  762359 service.cc:146] XLA service 0x55d75744c2d0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729823985.555588  762359 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729823989.791130  762463 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.668488\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:40:50,103] Trial 1 finished with value: 0.668488 and parameters: {'n_layers': 3, 'layer_dropout': 1, 'n_units_l_0': 2152, 'n_decay_l_0': 0.001, 'F_dropout_0': 0.1, 'n_units_l_1': 1830, 'n_decay_l_1': 0.0001, 'F_dropout_1': 0.1, 'n_units_l_2': 4427, 'n_decay_l_2': 0.0001, 'F_dropout_2': 0.3, 'lr': 0.0001}. Best is trial 0 with value: 0.679332.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729824052.960321  765604 service.cc:146] XLA service 0x55cc5280bdf0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824052.960390  765604 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729824053.116021  765604 service.cc:146] XLA service 0x55cc50253a30 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824053.116054  765604 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729824055.695706  765714 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.662751\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:41:01,389] Trial 2 finished with value: 0.662751 and parameters: {'n_layers': 1, 'layer_dropout': 0, 'n_units_l_0': 2892, 'n_decay_l_0': 0.001, 'last_dropout': 0.1, 'lr': 0.001}. Best is trial 0 with value: 0.679332.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729824064.281415  766911 service.cc:146] XLA service 0x55b827b832f0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824064.281454  766911 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729824064.424930  766911 service.cc:146] XLA service 0x55b827b5a3c0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824064.424972  766911 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729824067.087899  767014 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.644237\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:41:12,311] Trial 3 finished with value: 0.644237 and parameters: {'n_layers': 1, 'layer_dropout': 0, 'n_units_l_0': 6028, 'n_decay_l_0': 0.0001, 'last_dropout': 0.2, 'lr': 0.001}. Best is trial 0 with value: 0.679332.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729824075.529341  767599 service.cc:146] XLA service 0x563c07a27f10 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824075.529392  767599 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729824075.650832  767599 service.cc:146] XLA service 0x563c07a82e20 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824075.650868  767599 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729824078.421404  767708 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.619821\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:41:23,815] Trial 4 finished with value: 0.619821 and parameters: {'n_layers': 1, 'layer_dropout': 1, 'n_units_l_0': 8402, 'n_decay_l_0': 1e-05, 'F_dropout_0': 0.2, 'lr': 0.001}. Best is trial 0 with value: 0.679332.\n"
     ]
    }
   ],
   "source": [
    "study_lo_struct = optuna.create_study(study_name='ANO_lo_struct', storage=storage, direction=\"maximize\", pruner=optuna.pruners.SuccessiveHalvingPruner(reduction_factor=64, min_early_stopping_rate=10),load_if_exists=True)     \n",
    "# study_lo_fea = optuna.create_study(study_name='ANO_lo_struct', storage=storage, direction=\"maximize\", pruner=optuna.pruners.HyperbandPruner(min_resource=100,max_resource=1000,reduction_factor=3), load_if_exists=True)\n",
    "study_lo_struct.optimize(objective_lo_struct, n_trials=TRIALS)\n",
    "pruned_trials_lo_struct = study_lo_struct.get_trials(deepcopy=False, states=[TrialState.PRUNED])\n",
    "complete_trials_lo_struct = study_lo_struct.get_trials(deepcopy=False, states=[TrialState.COMPLETE])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:41:23,834] A new study created in RDB with name: ANO_hu_struct\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729824086.884600  768220 service.cc:146] XLA service 0x5626a2e78390 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824086.884652  768220 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729824087.003367  768220 service.cc:146] XLA service 0x5626a2e4fce0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824087.003400  768220 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729824105.963199  768323 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.856321\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:42:47,320] Trial 0 finished with value: 0.856321 and parameters: {'n_layers': 2, 'layer_dropout': 0, 'n_units_l_0': 6594, 'n_decay_l_0': 0.0001, 'n_units_l_1': 301, 'n_decay_l_1': 0.001, 'last_dropout': 0.3, 'lr': 1e-05}. Best is trial 0 with value: 0.856321.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729824170.843053  772954 service.cc:146] XLA service 0x558ed359fba0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824170.843094  772954 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729824170.980423  772954 service.cc:146] XLA service 0x558ed34d34b0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824170.980455  772954 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729824174.981970  773059 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.852474\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:46:37,297] Trial 1 finished with value: 0.852474 and parameters: {'n_layers': 2, 'layer_dropout': 1, 'n_units_l_0': 6712, 'n_decay_l_0': 0.0001, 'F_dropout_0': 0.1, 'n_units_l_1': 6556, 'n_decay_l_1': 0.001, 'F_dropout_1': 0.1, 'lr': 1e-05}. Best is trial 0 with value: 0.856321.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729824400.201392  788855 service.cc:146] XLA service 0x55a8a31a00b0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824400.201453  788855 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729824400.333349  788855 service.cc:146] XLA service 0x55a8a3176de0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824400.333383  788855 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729824402.770049  788964 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.839939\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:46:47,755] Trial 2 finished with value: 0.839939 and parameters: {'n_layers': 1, 'layer_dropout': 0, 'n_units_l_0': 4994, 'n_decay_l_0': 0.0001, 'last_dropout': 0.1, 'lr': 0.001}. Best is trial 0 with value: 0.856321.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729824410.699218  789515 service.cc:146] XLA service 0x55ac8eda5d40 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824410.699260  789515 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729824410.834295  789515 service.cc:146] XLA service 0x55ac8ece7750 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824410.834333  789515 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729824435.249758  789626 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.845373\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:48:32,252] Trial 3 finished with value: 0.845373 and parameters: {'n_layers': 3, 'layer_dropout': 0, 'n_units_l_0': 4463, 'n_decay_l_0': 0.0001, 'n_units_l_1': 1966, 'n_decay_l_1': 0.001, 'n_units_l_2': 924, 'n_decay_l_2': 0.0001, 'last_dropout': 0.1, 'lr': 0.0001}. Best is trial 0 with value: 0.856321.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model already exists at save_model/full_model.keras\n",
      "Model successfully saved to save_model/full_model.keras\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error in subprocess: WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
      "I0000 00:00:1729824515.181650  795905 service.cc:146] XLA service 0x55dbccb5d560 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824515.181691  795905 service.cc:154]   StreamExecutor device (0): Host, Default Version\n",
      "I0000 00:00:1729824515.312754  795905 service.cc:146] XLA service 0x55dbccb71e90 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "I0000 00:00:1729824515.312792  795905 service.cc:154]   StreamExecutor device (0): NVIDIA GeForce RTX 3060 Laptop GPU, Compute Capability 8.6\n",
      "I0000 00:00:1729824518.617949  796015 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R2 score: 0.812906\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[I 2024-10-25 11:49:05,409] Trial 4 finished with value: 0.812906 and parameters: {'n_layers': 2, 'layer_dropout': 1, 'n_units_l_0': 1477, 'n_decay_l_0': 0.0001, 'F_dropout_0': 0.3, 'n_units_l_1': 5762, 'n_decay_l_1': 1e-05, 'F_dropout_1': 0.2, 'lr': 0.001}. Best is trial 0 with value: 0.856321.\n"
     ]
    }
   ],
   "source": [
    "study_hu_struct = optuna.create_study(study_name='ANO_hu_struct', storage=storage, direction=\"maximize\", pruner=optuna.pruners.SuccessiveHalvingPruner(reduction_factor=64, min_early_stopping_rate=10),load_if_exists=True)     \n",
    "# study_hu_fea = optuna.create_study(study_name='ANO_hu_struct', storage=storage, direction=\"maximize\", pruner=optuna.pruners.HyperbandPruner(min_resource=100,max_resource=1000,reduction_factor=3), load_if_exists=True)\n",
    "study_hu_struct.optimize(objective_hu_struct, n_trials=TRIALS)\n",
    "pruned_trials_hu_struct = study_hu_struct.get_trials(deepcopy=False, states=[TrialState.PRUNED])\n",
    "complete_trials_hu_struct = study_hu_struct.get_trials(deepcopy=False, states=[TrialState.COMPLETE])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Study statistics: [ws_structure] \n",
      "  Number of finished trials:  5\n",
      "  Number of pruned trials:  0\n",
      "  Number of complete trials:  5\n",
      "Best trial:\n",
      "  Value:  0.741337\n",
      "  Params: \n",
      "    n_layers: 3\n",
      "    layer_dropout: 0\n",
      "    n_units_l_0: 787\n",
      "    n_decay_l_0: 0.0001\n",
      "    n_units_l_1: 9082\n",
      "    n_decay_l_1: 0.001\n",
      "    n_units_l_2: 7890\n",
      "    n_decay_l_2: 0.001\n",
      "    last_dropout: 0.1\n",
      "    lr: 0.0001\n"
     ]
    }
   ],
   "source": [
    "print(\"Study statistics: [ws_structure] \")\n",
    "print(\"  Number of finished trials: \", len(study_ws_struct.trials))\n",
    "print(\"  Number of pruned trials: \", len(pruned_trials_ws_struct))\n",
    "print(\"  Number of complete trials: \", len(complete_trials_ws_struct))\n",
    "print(\"Best trial:\")\n",
    "trials_tmp = study_ws_struct.best_trial\n",
    "print(\"  Value: \", trials_tmp.value)\n",
    "print(\"  Params: \")\n",
    "for key, value in trials_tmp.params.items():\n",
    "    print(\"    {}: {}\".format(key, value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Study statistics: [de_structure] \n",
      "  Number of finished trials:  5\n",
      "  Number of pruned trials:  0\n",
      "  Number of complete trials:  5\n",
      "Best trial:\n",
      "  Value:  0.84961\n",
      "  Params: \n",
      "    n_layers: 2\n",
      "    layer_dropout: 0\n",
      "    n_units_l_0: 7109\n",
      "    n_decay_l_0: 0.001\n",
      "    n_units_l_1: 3436\n",
      "    n_decay_l_1: 1e-05\n",
      "    last_dropout: 0.3\n",
      "    lr: 1e-05\n"
     ]
    }
   ],
   "source": [
    "print(\"Study statistics: [de_structure] \")\n",
    "print(\"  Number of finished trials: \", len(study_de_struct.trials))\n",
    "print(\"  Number of pruned trials: \", len(pruned_trials_de_struct))\n",
    "print(\"  Number of complete trials: \", len(complete_trials_de_struct))\n",
    "print(\"Best trial:\")\n",
    "trials_tmp = study_de_struct.best_trial\n",
    "print(\"  Value: \", trials_tmp.value)\n",
    "print(\"  Params: \")\n",
    "for key, value in trials_tmp.params.items():\n",
    "    print(\"    {}: {}\".format(key, value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Study statistics: [lo_structure] \n",
      "  Number of finished trials:  5\n",
      "  Number of pruned trials:  0\n",
      "  Number of complete trials:  5\n",
      "Best trial:\n",
      "  Value:  0.679332\n",
      "  Params: \n",
      "    n_layers: 2\n",
      "    layer_dropout: 1\n",
      "    n_units_l_0: 7114\n",
      "    n_decay_l_0: 0.001\n",
      "    F_dropout_0: 0.1\n",
      "    n_units_l_1: 7475\n",
      "    n_decay_l_1: 0.0001\n",
      "    F_dropout_1: 0.3\n",
      "    lr: 1e-05\n"
     ]
    }
   ],
   "source": [
    "print(\"Study statistics: [lo_structure] \")\n",
    "print(\"  Number of finished trials: \", len(study_lo_struct.trials))\n",
    "print(\"  Number of pruned trials: \", len(pruned_trials_lo_struct))\n",
    "print(\"  Number of complete trials: \", len(complete_trials_lo_struct))\n",
    "print(\"Best trial:\")\n",
    "trials_tmp = study_lo_struct.best_trial\n",
    "print(\"  Value: \", trials_tmp.value)\n",
    "print(\"  Params: \")\n",
    "for key, value in trials_tmp.params.items():\n",
    "    print(\"    {}: {}\".format(key, value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Study statistics: [hu_structure] \n",
      "  Number of finished trials:  5\n",
      "  Number of pruned trials:  0\n",
      "  Number of complete trials:  5\n",
      "Best trial:\n",
      "  Value:  0.856321\n",
      "  Params: \n",
      "    n_layers: 2\n",
      "    layer_dropout: 0\n",
      "    n_units_l_0: 6594\n",
      "    n_decay_l_0: 0.0001\n",
      "    n_units_l_1: 301\n",
      "    n_decay_l_1: 0.001\n",
      "    last_dropout: 0.3\n",
      "    lr: 1e-05\n"
     ]
    }
   ],
   "source": [
    "print(\"Study statistics: [hu_structure] \")\n",
    "print(\"  Number of finished trials: \", len(study_hu_struct.trials))\n",
    "print(\"  Number of pruned trials: \", len(pruned_trials_hu_struct))\n",
    "print(\"  Number of complete trials: \", len(complete_trials_hu_struct))\n",
    "print(\"Best trial:\")\n",
    "trials_tmp = study_hu_struct.best_trial\n",
    "print(\"  Value: \", trials_tmp.value)\n",
    "print(\"  Params: \")\n",
    "for key, value in trials_tmp.params.items():\n",
    "    print(\"    {}: {}\".format(key, value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ai",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}