File size: 53,434 Bytes
6b76845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# look data_example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle, h5py\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "with open('./LINCS2020/idx2smi.pickle', 'rb') as f:\n",
    "    idx2smi = pickle.load(f)\\\n",
    "        \n",
    "smiles_list = list(idx2smi.values())  # 假设idx2smi是一个字典,其值为SMILES字符串\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8316 BrC1C(Br)C(Br)C(Br)C(Br)C1Br\n"
     ]
    }
   ],
   "source": [
    "print(len(idx2smi), idx2smi[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'BrC1C(Br)C(Br)C(Br)C(Br)C1Br'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "idx2smi[0]  # to path_to_input_smiles.csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SMILES已成功保存到LINCS2020_smiles.csv文件中。\n"
     ]
    }
   ],
   "source": [
    "import pickle\n",
    "import csv\n",
    "\n",
    "# 将SMILES字符串写入CSV文件\n",
    "with open('./LINCS2020/LINCS2020_smiles.csv', 'w', newline='') as csvfile:\n",
    "    writer = csv.writer(csvfile)\n",
    "    # 写入标题行(可选)\n",
    "    writer.writerow(['SMILES'])\n",
    "    # 遍历字典,写入SMILES\n",
    "    for idx, smi in idx2smi.items():\n",
    "        writer.writerow([smi])\n",
    "\n",
    "print(\"SMILES已成功保存到LINCS2020_smiles.csv文件中。\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generate ECFP4 embedding for all smiles\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from rdkit import Chem\n",
    "from rdkit.Chem import AllChem\n",
    "import numpy as np\n",
    "import pickle\n",
    "\n",
    "def smiles_to_ecfp4(smiles_list, radius=2, n_bits=2048):\n",
    "    \"\"\"\n",
    "    将SMILES列表转换为ECFP4特征向量。\n",
    "\n",
    "    参数:\n",
    "    smiles_list (list): SMILES字符串列表。\n",
    "    radius (int): ECFP的半径,默认为2(即ECFP4)。\n",
    "    n_bits (int): 特征向量的长度,默认为2048。\n",
    "\n",
    "    返回:\n",
    "    dict: 一个字典,键为SMILES字符串,值为对应的ECFP4特征向量。\n",
    "    \"\"\"\n",
    "    ecfp4_dict = {}\n",
    "    \n",
    "    for smiles in smiles_list:\n",
    "        mol = Chem.MolFromSmiles(smiles)\n",
    "        if mol is not None:\n",
    "            # 替换编码器\n",
    "            ecfp4 = AllChem.GetMorganFingerprintAsBitVect(mol, radius=radius, nBits=n_bits)\n",
    "            ecfp4_dict[smiles] = np.array(ecfp4, dtype=np.float32)\n",
    "        else:\n",
    "            print(\"Error in \", smiles)\n",
    "            # 如果SMILES无法解析为分子,则填充一个全零的向量\n",
    "            ecfp4_dict[smiles] = np.zeros(n_bits, dtype=np.float32)\n",
    "    \n",
    "    return ecfp4_dict\n",
    "\n",
    "# 从字典中提取SMILES列表\n",
    "smiles_list = list(idx2smi.values())  # 假设idx2smi是一个字典,其值为SMILES字符串\n",
    "\n",
    "# 计算ECFP4特征\n",
    "ecfp4_features_dict = smiles_to_ecfp4(smiles_list)\n",
    "\n",
    "# ecfp4_features_dict\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8316 8316\n"
     ]
    }
   ],
   "source": [
    "print(len(smiles_list), len(ecfp4_features_dict))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ecfp4_features_dict\n",
    "\n",
    "# np.str_('BrC1C(Br)C(Br)C(Br)C(Br)C1Br'): array([0., 0., 0., ..., 0., 0., 0.], dtype=float32),"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 保存为 pickle 文件\n",
    "with open('./LINCS2020/ECFP4_emb2048.pickle', 'wb') as f:\n",
    "    pickle.dump(ecfp4_features_dict, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(2048,)"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ecfp4_features_dict['CN1CCN(CCCN2c3ccccc3Sc3ccc(cc23)C(F)(F)F)CC1'].shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import pickle, h5py\n",
    "# import numpy as np\n",
    "# import pandas as pd\n",
    "\n",
    "# with open('./embeddings/ChemBERTa2_emb384.pickle', 'rb') as f:\n",
    "#     KPGT_emb2304 = pickle.load(f)\n",
    "# KPGT_emb2304"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(300,)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# KPGT_emb2304['BrC1C(Br)C(Br)C(Br)C(Br)C1Br'].shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generate KGPT embedding for all smiles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle, h5py\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "with open('./embeddings/KPGT_emb2304.pickle', 'rb') as f:\n",
    "    KPGT_emb2304 = pickle.load(f)\n",
    "KPGT_emb2304"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预训练权重总参数量: 111,755,936\n",
      "111.8 M\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/KPGT/base.pth', map_location='cpu')\n",
    "total = sum(v.numel() for v in state_dict.values())\n",
    "print(f'预训练权重总参数量: {total:,}')\n",
    "print(f'{total/1e6:.1f} M')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generate InfoAlign embedding for all smiles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# pip install infoalign\n",
    "\n",
    "# infoalign_predict --input LINCS2020/LINCS2020_smiles.csv \\\n",
    "#                   --output InfoAlign_output.npy \\\n",
    "#                   --output-to-input-column  # Adds the representation as an additional column in the input CSV\n",
    "\n",
    "# 是否存在数据泄露,因为这个是基于表征学习的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预训练权重总参数量: 13,808,553\n",
      "13.8 M\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_1948954/1463163983.py:2: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/infoalign_model/pretrain.pt', map_location='cpu')\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/infoalign_model/pretrain.pt', map_location='cpu')\n",
    "total = sum(v.numel() for v in state_dict.values())\n",
    "print(f'预训练权重总参数量: {total:,}')\n",
    "print(f'{total/1e6:.1f} M')      # → 21.2 M"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv\n",
    "import numpy as np\n",
    "import pickle\n",
    "\n",
    "# CSV文件路径\n",
    "csv_path = 'infoalign_model/LINCS2020_smiles.csv'\n",
    "# NPY文件路径\n",
    "npy_path = 'infoalign_model/InfoAlign_output.npy'\n",
    "\n",
    "# 初始化一个空字典来存储SMILES和对应的表征\n",
    "smiles_to_representation = {}\n",
    "\n",
    "# 读取NPY文件\n",
    "info_align_output = np.load(npy_path)\n",
    "\n",
    "# 读取CSV文件并同时替换字典中的值\n",
    "with open(csv_path, mode='r', newline='', encoding='utf-8') as csvfile:\n",
    "    reader = csv.DictReader(csvfile)\n",
    "    for idx, row in enumerate(reader):\n",
    "        smiles = row['SMILES']\n",
    "        # 直接从info_align_output中获取对应的数值\n",
    "        representation = info_align_output[idx]\n",
    "        smiles_to_representation[smiles] = representation\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "8316"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(smiles_to_representation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "字典已成功保存到 embeddings/InfoAlign_emb300.pickle\n"
     ]
    }
   ],
   "source": [
    "# 保存字典为pickle文件\n",
    "pickle_path = 'embeddings/InfoAlign_emb300.pickle'\n",
    "with open(pickle_path, 'wb') as pickle_file:\n",
    "    pickle.dump(smiles_to_representation, pickle_file)\n",
    "\n",
    "print(f\"字典已成功保存到 {pickle_path}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generate ChemBERTa-2 embedding for all smiles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Some weights of RobertaModel were not initialized from the model checkpoint at DeepChem/ChemBERTa-77M-MLM and are newly initialized: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n",
      "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
     ]
    }
   ],
   "source": [
    "from transformers import AutoModel, AutoTokenizer\n",
    "model = AutoModel.from_pretrained(\"DeepChem/ChemBERTa-77M-MLM\")   # 77M SMILES(完整PubChem数据集)\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"DeepChem/ChemBERTa-77M-MLM\")\n",
    "inputs = tokenizer(\"CCO\", return_tensors=\"pt\")\n",
    "outputs = model(**inputs)  # 嵌入位于 outputs.last_hidden_state"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([1, 5, 384])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "outputs.last_hidden_state.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Some weights of RobertaModel were not initialized from the model checkpoint at DeepChem/ChemBERTa-77M-MLM and are newly initialized: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n",
      "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ChemBERTa-77M 可训练参数量: 3,427,440\n",
      "3.4 M\n"
     ]
    }
   ],
   "source": [
    "# from transformers import AutoModel\n",
    "\n",
    "# model = AutoModel.from_pretrained(\"DeepChem/ChemBERTa-77M-MLM\")\n",
    "\n",
    "# trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
    "# print(f\"ChemBERTa-77M 可训练参数量: {trainable:,}\")\n",
    "# print(f\"{trainable/1e6:.1f} M\")   # → 85.7 M"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Some weights of RobertaModel were not initialized from the model checkpoint at DeepChem/ChemBERTa-77M-MLM and are newly initialized: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n",
      "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
     ]
    }
   ],
   "source": [
    "# from transformers import AutoModel, AutoTokenizer\n",
    "# import torch, os, shutil\n",
    "\n",
    "# repo_id = \"DeepChem/ChemBERTa-77M-MLM\"\n",
    "\n",
    "# # 1. 磁盘大小:下载后统计整个 snapshot 目录\n",
    "# tmp_dir = \"./tmp_snapshot\"          # 临时目录,用完即删\n",
    "# model = AutoModel.from_pretrained(repo_id, cache_dir=tmp_dir)\n",
    "# tokenizer = AutoTokenizer.from_pretrained(repo_id, cache_dir=tmp_dir)\n",
    "\n",
    "# disk_mb = sum(\n",
    "#     os.path.getsize(os.path.join(root, f))\n",
    "#     for root, _, files in os.walk(tmp_dir)\n",
    "#     for f in files\n",
    "# ) / 1024 ** 2\n",
    "\n",
    "# print(f\"权重文件磁盘占用:{disk_mb:.1f} MB\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Some weights of RobertaModel were not initialized from the model checkpoint at DeepChem/ChemBERTa-77M-MLM and are newly initialized: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n",
      "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n",
      "100%|██████████| 260/260 [00:01<00:00, 168.25it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "总分子数 : 8316\n",
      "总耗时   : 2.82 s\n",
      "平均推理 : 0.34 ms / molecule\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import pickle\n",
    "import time\n",
    "from transformers import AutoModel, AutoTokenizer\n",
    "import torch\n",
    "import numpy as np\n",
    "from rdkit import Chem\n",
    "from tqdm import tqdm  # 可选:用于进度条\n",
    "\n",
    "def smiles_to_chemberta2(smiles_list, model_name=\"DeepChem/ChemBERTa-77M-MLM\", batch_size=32):\n",
    "    \"\"\"\n",
    "    将SMILES列表转换为ChemBERTa-2的嵌入向量(CLS token的隐藏状态)。\n",
    "    \n",
    "    参数:\n",
    "        smiles_list (list): SMILES字符串列表\n",
    "        model_name (str): Hugging Face模型ID,默认为ChemBERTa-2的MLM版本\n",
    "        batch_size (int): 批处理大小,根据GPU内存调整\n",
    "        \n",
    "    返回:\n",
    "        dict: 键为SMILES,值为768维嵌入向量(numpy数组)\n",
    "    \"\"\"\n",
    "    # 加载模型和tokenizer\n",
    "    tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
    "    model = AutoModel.from_pretrained(model_name)\n",
    "    model.eval()  # 切换到推理模式\n",
    "    \n",
    "    # 检查CUDA可用性\n",
    "    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "    model.to(device)\n",
    "    \n",
    "    chemberta2_dict = {}\n",
    "    \n",
    "    # 分批处理SMILES\n",
    "    for i in tqdm(range(0, len(smiles_list), batch_size)):\n",
    "        batch_smiles = smiles_list[i:i+batch_size]\n",
    "        valid_indices = []\n",
    "        batch_inputs = []\n",
    "        \n",
    "        # 过滤无效SMILES并生成输入\n",
    "        for idx, smiles in enumerate(batch_smiles):\n",
    "            mol = Chem.MolFromSmiles(smiles)\n",
    "            if mol is not None:\n",
    "                valid_indices.append(idx)\n",
    "                batch_inputs.append(smiles)\n",
    "            else:\n",
    "                print(f\"Invalid SMILES: {smiles}\")\n",
    "        \n",
    "        if not batch_inputs:\n",
    "            continue\n",
    "            \n",
    "        # Tokenize并移动到设备\n",
    "        inputs = tokenizer(\n",
    "            batch_inputs, \n",
    "            return_tensors=\"pt\", \n",
    "            padding=True, \n",
    "            truncation=True, \n",
    "            max_length=512\n",
    "        ).to(device)\n",
    "        \n",
    "        # 生成嵌入\n",
    "        with torch.no_grad():\n",
    "            outputs = model(**inputs)\n",
    "            embeddings = outputs.last_hidden_state[:, 0, :]  # 取CLS token的嵌入\n",
    "        \n",
    "        # 将有效结果存入字典\n",
    "        for j, idx in enumerate(valid_indices):\n",
    "            chemberta2_dict[batch_smiles[idx]] = embeddings[j].cpu().numpy()\n",
    "        \n",
    "        # 处理无效SMILES(填充零向量)\n",
    "        for idx, smiles in enumerate(batch_smiles):\n",
    "            if idx not in valid_indices:\n",
    "                chemberta2_dict[smiles] = np.zeros(768, dtype=np.float32)\n",
    "    \n",
    "    return chemberta2_dict\n",
    "\n",
    "# 使用示例\n",
    "import time\n",
    "# ----- 计时开始 -----\n",
    "t0 = time.perf_counter()\n",
    "smiles_list = list(idx2smi.values())  # 假设idx2smi是SMILES字典\n",
    "chemberta2_features_dict = smiles_to_chemberta2(smiles_list)\n",
    "\n",
    "t1 = time.perf_counter()\n",
    "# ----- 计时结束 -----\n",
    "\n",
    "# 基本统计\n",
    "total_mols = len(chemberta2_features_dict)\n",
    "avg_time_ms = (t1 - t0) / total_mols * 1000\n",
    "\n",
    "print(f\"总分子数 : {total_mols}\")\n",
    "print(f\"总耗时   : {t1 - t0:.2f} s\")\n",
    "print(f\"平均推理 : {avg_time_ms:.2f} ms / molecule\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8316 384\n"
     ]
    }
   ],
   "source": [
    "print(len(chemberta2_features_dict), len(chemberta2_features_dict['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "chemberta2_features_dict['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "字典已成功保存到 embeddings/ChemBERTa2_emb384.pickle\n"
     ]
    }
   ],
   "source": [
    "# 保存字典为pickle文件\n",
    "pickle_path = 'embeddings/ChemBERTa2_emb384.pickle'\n",
    "with open(pickle_path, 'wb') as pickle_file:\n",
    "    pickle.dump(chemberta2_features_dict, pickle_file)\n",
    "\n",
    "print(f\"字典已成功保存到 {pickle_path}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generate MolT5 embedding for all smiles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([1, 768])\n"
     ]
    }
   ],
   "source": [
    "from transformers import T5ForConditionalGeneration, AutoTokenizer\n",
    "model = T5ForConditionalGeneration.from_pretrained(\"laituan245/molt5-base\")\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"laituan245/molt5-base\")\n",
    "inputs = tokenizer(\"CCO\", return_tensors=\"pt\")\n",
    "embeddings = model.encoder(**inputs).last_hidden_state.mean(dim=1)  # 平均池化\n",
    "print(embeddings.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MolT5-base 可训练参数量: 247.6 M\n"
     ]
    }
   ],
   "source": [
    "trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
    "print(f'MolT5-base 可训练参数量: {trainable/1e6:.1f} M')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "已缓存权重磁盘占用:3784.1 MB\n"
     ]
    }
   ],
   "source": [
    "# molt5_disk_usage.py\n",
    "from transformers import AutoModel, AutoTokenizer\n",
    "import os, pathlib\n",
    "\n",
    "repo_id = \"laituan245/molt5-base\"\n",
    "\n",
    "# 让 transformers 只走本地缓存,不会触发下载\n",
    "model = AutoModel.from_pretrained(repo_id, local_files_only=True)\n",
    "tokenizer = AutoTokenizer.from_pretrained(repo_id, local_files_only=True)\n",
    "\n",
    "# 找到缓存目录\n",
    "cache_root = pathlib.Path.home() / \".cache/huggingface/hub\"\n",
    "# 仓库目录名格式:models--{user}--{repo}\n",
    "repo_dir = cache_root / f\"models--{repo_id.replace('/', '--')}\"\n",
    "\n",
    "disk_bytes = sum(f.stat().st_size for f in repo_dir.rglob(\"*\") if f.is_file())\n",
    "disk_mb = disk_bytes / 1024 ** 2\n",
    "\n",
    "print(f\"已缓存权重磁盘占用:{disk_mb:.1f} MB\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 130/130 [00:09<00:00, 13.90it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "总分子数 : 8316\n",
      "总耗时   : 11.55 s\n",
      "平均推理 : 1.39 ms / molecule\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import pickle\n",
    "from transformers import T5ForConditionalGeneration, AutoTokenizer\n",
    "import torch\n",
    "import numpy as np\n",
    "from rdkit import Chem\n",
    "from tqdm import tqdm\n",
    "\n",
    "def smiles_to_molt5(smiles_list, model_name=\"laituan245/molt5-base\", batch_size=32, pooling=\"mean\"):\n",
    "    \"\"\"\n",
    "    使用 MolT5 生成 SMILES 的嵌入向量(基于 encoder 的隐藏状态)\n",
    "    \n",
    "    参数:\n",
    "        smiles_list (list): SMILES 字符串列表\n",
    "        model_name (str): Hugging Face 模型 ID,默认为 MolT5-base\n",
    "        batch_size (int): 批处理大小,根据 GPU 内存调整\n",
    "        pooling (str): 池化方法,可选 \"mean\"(平均池化)或 \"cls\"(取 CLS token)\n",
    "        \n",
    "    返回:\n",
    "        dict: 键为 SMILES,值为嵌入向量(numpy 数组)\n",
    "    \"\"\"\n",
    "    # 加载 MolT5 的 tokenizer 和模型\n",
    "    model = T5ForConditionalGeneration.from_pretrained(model_name)\n",
    "    tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
    "    model.eval()\n",
    "    \n",
    "    # 设备设置\n",
    "    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "    model.to(device)\n",
    "    \n",
    "    molt5_dict = {}\n",
    "    \n",
    "    # 分批处理\n",
    "    for i in tqdm(range(0, len(smiles_list), batch_size)):\n",
    "        batch_smiles = smiles_list[i:i+batch_size]\n",
    "        valid_indices = []\n",
    "        batch_inputs = []\n",
    "        \n",
    "        # 过滤无效 SMILES\n",
    "        for idx, smiles in enumerate(batch_smiles):\n",
    "            mol = Chem.MolFromSmiles(smiles)\n",
    "            if mol is not None:\n",
    "                valid_indices.append(idx)\n",
    "                batch_inputs.append(smiles)\n",
    "            else:\n",
    "                print(f\"Invalid SMILES: {smiles}\")\n",
    "                molt5_dict[smiles] = np.zeros(model.config.d_model, dtype=np.float32)  # 填充零向量\n",
    "        \n",
    "        if not batch_inputs:\n",
    "            continue\n",
    "            \n",
    "        # Tokenize 并生成嵌入\n",
    "        inputs = tokenizer(\n",
    "            batch_inputs,\n",
    "            return_tensors=\"pt\",\n",
    "            padding=True,\n",
    "            truncation=True,\n",
    "            max_length=512\n",
    "        ).to(device)\n",
    "        \n",
    "        with torch.no_grad():\n",
    "            # 获取 encoder 的隐藏状态(形状: [batch_size, seq_len, hidden_dim])\n",
    "            encoder_outputs = model.encoder(**inputs)\n",
    "            hidden_states = encoder_outputs.last_hidden_state\n",
    "            \n",
    "            # 池化策略\n",
    "            if pooling == \"mean\":\n",
    "                embeddings = hidden_states.mean(dim=1)  # 平均池化\n",
    "            elif pooling == \"cls\":\n",
    "                embeddings = hidden_states[:, 0, :]     # CLS token\n",
    "            else:\n",
    "                raise ValueError(\"pooling 必须是 'mean' 或 'cls'\")\n",
    "        \n",
    "        # 存储结果\n",
    "        for j, idx in enumerate(valid_indices):\n",
    "            molt5_dict[batch_smiles[idx]] = embeddings[j].cpu().numpy()\n",
    "    \n",
    "    return molt5_dict\n",
    "\n",
    "\n",
    "import time\n",
    "# ----- 计时开始 -----\n",
    "smiles_list = list(idx2smi.values())  # 假设 idx2smi 是 SMILES 字典\n",
    "\n",
    "t0 = time.perf_counter()\n",
    "molt5_embeddings = smiles_to_molt5(smiles_list, batch_size=64, pooling=\"mean\")\n",
    "\n",
    "t1 = time.perf_counter()\n",
    "# ----- 计时结束 -----\n",
    "\n",
    "# 基本统计\n",
    "total_mols = len(molt5_embeddings)\n",
    "avg_time_ms = (t1 - t0) / total_mols * 1000\n",
    "\n",
    "print(f\"总分子数 : {total_mols}\")\n",
    "print(f\"总耗时   : {t1 - t0:.2f} s\")\n",
    "print(f\"平均推理 : {avg_time_ms:.2f} ms / molecule\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8316 768\n"
     ]
    }
   ],
   "source": [
    "print(len(molt5_embeddings), len(molt5_embeddings['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "molt5_embeddings['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "字典已成功保存到 embeddings/molt5_emb768.pickle\n"
     ]
    }
   ],
   "source": [
    "# 保存字典为pickle文件\n",
    "pickle_path = 'embeddings/molt5_emb768.pickle'\n",
    "with open(pickle_path, 'wb') as pickle_file:\n",
    "    pickle.dump(molt5_embeddings, pickle_file)\n",
    "\n",
    "print(f\"字典已成功保存到 {pickle_path}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generate Chemprop embedding for all smiles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# git clone https://github.com/chemprop/chemprop.git\n",
    "# https://chemprop.readthedocs.io/en/main/installation.html\n",
    "# https://chemprop.readthedocs.io/en/main/tutorial/cli/fingerprint.html#fingerprint \n",
    "\n",
    "# chemprop fingerprint --test-path ./embeddings/LINCS2020_smiles.csv --model-path chemprop/tests/data/example_model_v2_regression_mol.ckpt --output embeddings/fps.csv --ffn-block-index -2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预训练权重总参数量: 319,505\n",
      "0.3 M\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_1948954/3140832406.py:3: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  ckpt = torch.load('/home/bob/boom/VCBench/Molecule_encoder/chemprop/tests/data/example_model_v2_regression_mol.ckpt',\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "ckpt = torch.load('/home/bob/boom/VCBench/Molecule_encoder/chemprop/tests/data/example_model_v2_regression_mol.ckpt',\n",
    "                  map_location='cpu')\n",
    "\n",
    "# 取出模型参数部分\n",
    "model_state = ckpt['state_dict']\n",
    "\n",
    "total = sum(v.numel() for v in model_state.values() if isinstance(v, torch.Tensor))\n",
    "print(f'预训练权重总参数量: {total:,}')\n",
    "print(f'{total/1e6:.1f} M')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "8316"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import csv\n",
    "import numpy as np\n",
    "\n",
    "# CSV文件路径\n",
    "csv1_path = 'infoalign_model/LINCS2020_smiles.csv'\n",
    "csv2_path = 'embeddings/fps_0.csv'\n",
    "\n",
    "# 初始化一个空字典来存储SMILES和对应的表征\n",
    "smiles_to_representation = {}\n",
    "\n",
    "# 读取第一个CSV文件(SMILES信息)\n",
    "smiles_list = []\n",
    "with open(csv1_path, mode='r', newline='', encoding='utf-8') as csvfile:\n",
    "    reader = csv.DictReader(csvfile)\n",
    "    for row in reader:\n",
    "        smiles = row['SMILES']  # 假设CSV文件中列名为'SMILES'\n",
    "        smiles_list.append(smiles)\n",
    "\n",
    "# 读取第二个CSV文件(表征信息),跳过第一行\n",
    "representation_list = []\n",
    "with open(csv2_path, mode='r', newline='', encoding='utf-8') as csvfile:\n",
    "    reader = csv.reader(csvfile)\n",
    "    next(reader)  # 跳过第一行\n",
    "    for row in reader:\n",
    "        # 将字符串转换为浮点数\n",
    "        representation = [np.float32(x)  for x in row]  # 假设表征信息是整行数据\n",
    "        representation_list.append(representation)\n",
    "\n",
    "# 将列表转换为numpy数组\n",
    "representation_array = np.array(representation_list)\n",
    "\n",
    "# 将SMILES和对应的表征合并到字典中\n",
    "for smiles, representation in zip(smiles_list, representation_array):\n",
    "    smiles_to_representation[smiles] = representation\n",
    "\n",
    "len(smiles_to_representation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "300 <class 'numpy.ndarray'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "dtype('float32')"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(len(smiles_to_representation['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']), type(smiles_to_representation['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']))\n",
    "\n",
    "smiles_to_representation['BrC1C(Br)C(Br)C(Br)C(Br)C1Br'].dtype"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "300\n",
      "字典已成功保存到 embeddings/Chemprop_emb300.pickle\n"
     ]
    }
   ],
   "source": [
    "print(len(smiles_to_representation['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']))\n",
    "\n",
    "import pickle\n",
    "# 保存字典为pickle文件\n",
    "pickle_path = 'embeddings/Chemprop_emb300.pickle'\n",
    "with open(pickle_path, 'wb') as pickle_file:\n",
    "    pickle.dump(smiles_to_representation, pickle_file)\n",
    "\n",
    "print(f\"字典已成功保存到 {pickle_path}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generate MolCLR embedding for all smiles\n",
    "\n",
    "## see /home/bob/boom/DrugIM/TranSiGen/data/MolCLR/Get_emd.ipynb\n",
    "\n",
    "### We use GIN model, which has a better performance in their paper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预训练权重总参数量: 2,407,201\n",
      "2.4 M\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_1948954/3871607093.py:2: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/MolCLR/ckpt/pretrained_gin/checkpoints/model.pth', map_location='cpu')\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/MolCLR/ckpt/pretrained_gin/checkpoints/model.pth', map_location='cpu')\n",
    "total = sum(v.numel() for v in state_dict.values())\n",
    "print(f'预训练权重总参数量: {total:,}')\n",
    "print(f'{total/1e6:.1f} M')      # → 21.2 M"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Generate Mole-BERT embedding for all smiles\n",
    "\n",
    "## see /home/bob/boom/DrugIM/TranSiGen/data/Mole-BERT/Get_emd.ipynb\n",
    "\n",
    "### We use GNN_graphpred model, which has a better performance in their paper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预训练权重总参数量: 1,860,905\n",
      "1.9 M\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_1948954/2103728332.py:2: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/Mole-BERT/model_gin/Mole-BERT.pth', map_location='cpu')\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "state_dict = torch.load('/home/bob/boom/VCBench/Molecule_encoder/Mole-BERT/model_gin/Mole-BERT.pth', map_location='cpu')\n",
    "total = sum(v.numel() for v in state_dict.values())\n",
    "print(f'预训练权重总参数量: {total:,}')\n",
    "print(f'{total/1e6:.1f} M')      # → 21.2 M"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3D  UniMol"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "8316"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pickle, h5py\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "with open('./LINCS2020/idx2smi.pickle', 'rb') as f:\n",
    "    idx2smi = pickle.load(f)\\\n",
    "\n",
    "unique_smiles = list(idx2smi.values())  # 假设idx2smi是一个字典,其值为SMILES字符串\n",
    "len(unique_smiles)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-09-15 11:17:31 | unimol_tools/models/unimolv2.py | 161 | INFO | Uni-Mol Tools | Loading pretrained weights from /home/bob/anaconda3/envs/boom/lib/python3.11/site-packages/unimol_tools/weights/modelzoo/310M/checkpoint.pt\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始生成32个SMILES的嵌入表示...\n",
      "开始\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "处理批次:   0%|          | 0/1 [00:00<?, ?it/s]2025-09-15 11:17:32 | unimol_tools/data/conformer.py | 437 | INFO | Uni-Mol Tools | Start generating conformers...\n",
      "32it [00:00, 82.76it/s]\n",
      "2025-09-15 11:17:33 | unimol_tools/data/conformer.py | 452 | INFO | Uni-Mol Tools | Succeeded in generating conformers for 100.00% of molecules.\n",
      "2025-09-15 11:17:33 | unimol_tools/data/conformer.py | 469 | INFO | Uni-Mol Tools | Succeeded in generating 3d conformers for 100.00% of molecules.\n",
      "2025-09-15 11:17:33 | unimol_tools/tasks/trainer.py | 78 | INFO | Uni-Mol Tools | Number of GPUs available: 1\n",
      "2025-09-15 11:17:33 | unimol_tools/tasks/trainer.py | 98 | INFO | Uni-Mol Tools | Using single GPU.\n",
      "100%|██████████| 1/1 [00:00<00:00,  2.32it/s]\n",
      "处理批次: 100%|██████████| 1/1 [00:01<00:00,  1.25s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "嵌入生成完成!共处理 32 个SMILES,32 个成功,0 个失败。\n",
      "嵌入结果已保存至 embeddings/UniMolV2_emb1024.pkl\n",
      "总分子数 : 32\n",
      "总耗时   : 3.50 s\n",
      "平均推理 : 109.37 ms / molecule\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import pickle\n",
    "import numpy as np\n",
    "from tqdm import tqdm\n",
    "from unimol_tools import UniMolRepr\n",
    "import os, sys, contextlib\n",
    "\n",
    "@contextlib.contextmanager\n",
    "def suppress_stdout_stderr():\n",
    "    \"\"\"with 块内所有 print / tqdm / warning 都不会显示\"\"\"\n",
    "    with open(os.devnull, 'w') as devnull:\n",
    "        old_out, old_err = sys.stdout, sys.stderr\n",
    "        sys.stdout, sys.stderr = devnull, devnull\n",
    "        try:\n",
    "            yield\n",
    "        finally:\n",
    "            sys.stdout, sys.stderr = old_out, old_err\n",
    "\n",
    "def get_unimol_embeddings(smiles_list, output_file=\"UniMol_emb512.pkl\", \n",
    "                         model_name='unimolv1', model_size='84m', \n",
    "                         remove_hs=False, batch_size=32):\n",
    "    \"\"\"\n",
    "    使用Uni-Mol模型为SMILES列表生成分子嵌入,并保存为pickle文件\n",
    "    \n",
    "    参数:\n",
    "    smiles_list (list): SMILES字符串列表\n",
    "    output_file (str): 输出pickle文件路径\n",
    "    model_name (str): 模型名称,可选'unimolv1'或'unimolv2'\n",
    "    model_size (str): 模型大小,仅在使用unimolv2时有效\n",
    "    remove_hs (bool): 是否移除氢原子\n",
    "    batch_size (int): 批处理大小\n",
    "    \n",
    "    返回:\n",
    "    dict: 包含SMILES及其对应嵌入的字典\n",
    "    \"\"\"\n",
    "    # 初始化模型\n",
    "    clf = UniMolRepr(\n",
    "        data_type='molecule',\n",
    "        remove_hs=remove_hs,\n",
    "        model_name=model_name,\n",
    "        model_size=model_size\n",
    "    )\n",
    "    \n",
    "    # 用于存储结果的字典\n",
    "    embeddings_dict = {}\n",
    "    error_smiles = []\n",
    "    \n",
    "    # 批处理SMILES\n",
    "    total_batches = (len(smiles_list) + batch_size - 1) // batch_size\n",
    "    \n",
    "    print(f\"开始生成{len(smiles_list)}个SMILES的嵌入表示...\")\n",
    "    \n",
    "    print(\"开始\")\n",
    "    # with suppress_stdout_stderr():\n",
    "    for i in tqdm(range(total_batches), desc=\"处理批次\"):\n",
    "        batch = smiles_list[i*batch_size : (i+1)*batch_size]\n",
    "        \n",
    "        try:\n",
    "            # 获取嵌入表示\n",
    "            batch_repr = clf.get_repr(batch, return_atomic_reprs=False)\n",
    "            \n",
    "            # 将结果存入字典 (使用CLS token作为分子表示)\n",
    "            for idx, smiles in enumerate(batch):\n",
    "                embeddings_dict[smiles] = batch_repr['cls_repr'][idx]\n",
    "                \n",
    "        except Exception as e:\n",
    "            print(f\"处理批次 {i+1}/{total_batches} 时发生错误: {str(e)}\")\n",
    "            # 记录处理失败的SMILES\n",
    "            error_smiles.extend(batch)\n",
    "        \n",
    "    # 保存嵌入结果\n",
    "    with open(output_file, 'wb') as f:\n",
    "        pickle.dump(embeddings_dict, f)\n",
    "    \n",
    "    print(f\"嵌入生成完成!共处理 {len(smiles_list)} 个SMILES,\"\n",
    "          f\"{len(smiles_list) - len(error_smiles)} 个成功,\"\n",
    "          f\"{len(error_smiles)} 个失败。\")\n",
    "    print(f\"嵌入结果已保存至 {output_file}\")\n",
    "    \n",
    "    if error_smiles:\n",
    "        print(f\"处理失败的SMILES已记录。\")\n",
    "    \n",
    "    return embeddings_dict\n",
    "\n",
    "# 使用示例\n",
    "if __name__ == \"__main__\":\n",
    "    \n",
    "    # 假设unique_smiles是你的SMILES列表\n",
    "    unique_smiles = [\n",
    "    \"CC(=O)OC1=CC=CC=C1C(=O)O\",  # Aspirin\n",
    "    \"CN1C=NC2=C1C(=O)N(C(=O)N2C)C\" # Caffeine\n",
    "    ]  # 示例SMILES列表\n",
    "    unique_smiles = pd.read_csv('./LINCS2020/LINCS2020_smiles.csv')['SMILES'].tolist()\n",
    "\n",
    "    # UniMol V1\n",
    "    # embeddings = get_unimol_embeddings(\n",
    "    #     smiles_list=unique_smiles,\n",
    "    #     output_file=\"embeddings/UniMol_emb512.pkl\",\n",
    "    #     model_name='unimolv1',\n",
    "    #     model_size='84m',\n",
    "    #     remove_hs=False,\n",
    "    #     batch_size=32\n",
    "    # )\n",
    "    \n",
    "    # UniMol V2\n",
    "    embeddings = get_unimol_embeddings(\n",
    "    smiles_list=unique_smiles,\n",
    "    output_file=\"embeddings/UniMolV2_emb1024.pkl\", # save path\n",
    "    model_name='unimolv2',      # 修改为 v2 版本\n",
    "    model_size='310m',          # 指定 v2 模型大小(根据需要选择)\n",
    "    remove_hs=False,\n",
    "    batch_size=32\n",
    "    )\n",
    "\n",
    "    # 打印样例嵌入\n",
    "    sample_smiles = unique_smiles[0]\n",
    "    print(f\"SMILES: {sample_smiles}\")\n",
    "    print(f\"嵌入向量: {embeddings[sample_smiles]}\")\n",
    "    print(f\"嵌入维度: {len(embeddings[sample_smiles])}\")\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-10-16 21:29:18 | unimol_tools/models/unimol.py | 136 | INFO | Uni-Mol Tools | Loading pretrained weights from /home/bob/anaconda3/envs/boom/lib/python3.11/site-packages/unimol_tools/weights/mol_pre_all_h_220816.pt\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "UniMol-unimolv1-84m 可训练参数量: 47.3 M\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-10-16 21:29:20 | unimol_tools/models/unimolv2.py | 161 | INFO | Uni-Mol Tools | Loading pretrained weights from /home/bob/anaconda3/envs/boom/lib/python3.11/site-packages/unimol_tools/weights/modelzoo/310M/checkpoint.pt\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "UniMol-unimolv2-310m 可训练参数量: 308.9 M\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import pickle\n",
    "import numpy as np\n",
    "from tqdm import tqdm\n",
    "from unimol_tools import UniMolRepr\n",
    "import os, sys, contextlib\n",
    "\n",
    "def get_unimol_embeddings(smiles_list, output_file=\"UniMol_emb512.pkl\", \n",
    "                         model_name='unimolv1', model_size='84m', \n",
    "                         remove_hs=False, batch_size=32):\n",
    "    \"\"\"\n",
    "    使用Uni-Mol模型为SMILES列表生成分子嵌入,并保存为pickle文件\n",
    "    \n",
    "    参数:\n",
    "    smiles_list (list): SMILES字符串列表\n",
    "    output_file (str): 输出pickle文件路径\n",
    "    model_name (str): 模型名称,可选'unimolv1'或'unimolv2'\n",
    "    model_size (str): 模型大小,仅在使用unimolv2时有效\n",
    "    remove_hs (bool): 是否移除氢原子\n",
    "    batch_size (int): 批处理大小\n",
    "    \n",
    "    返回:\n",
    "    dict: 包含SMILES及其对应嵌入的字典\n",
    "    \"\"\"\n",
    "    # 初始化模型\n",
    "    # ===== 在 clf 初始化完成后立即统计 =====\n",
    "    clf = UniMolRepr(\n",
    "            data_type='molecule',\n",
    "            remove_hs=remove_hs,\n",
    "            model_name=model_name,\n",
    "            model_size=model_size)\n",
    "\n",
    "    # 取出真正的网络\n",
    "    real_model = clf.model          # <== 关键属性\n",
    "\n",
    "    total = sum(p.numel() for p in real_model.parameters() if p.requires_grad)\n",
    "    print(f'UniMol-{model_name}-{model_size} 可训练参数量: {total/1e6:.1f} M')\n",
    "  \n",
    "        \n",
    "# 使用示例\n",
    "if __name__ == \"__main__\":\n",
    "    # 假设unique_smiles是你的SMILES列表\n",
    "    # 生成并保存嵌入\n",
    "    import time\n",
    "    # ----- 计时开始 -----\n",
    "    unique_smiles = list(idx2smi.values())  # 假设 idx2smi 是 SMILES 字典\n",
    "\n",
    "    t0 = time.perf_counter()\n",
    "    \n",
    "    embeddings = get_unimol_embeddings(\n",
    "        smiles_list=unique_smiles[:32],\n",
    "        output_file=\"embeddings/UniMol_emb512.pkl\",\n",
    "        model_name='unimolv1',\n",
    "        model_size='84m',\n",
    "        remove_hs=False,\n",
    "        batch_size=32\n",
    "    )\n",
    "    # UniMol 2\n",
    "    embeddings = get_unimol_embeddings(\n",
    "    smiles_list=unique_smiles[:32],\n",
    "    output_file=\"embeddings/UniMolV2_emb1024.pkl\",\n",
    "    model_name='unimolv2',      # 修改为 v2 版本\n",
    "    model_size='310m',          # 指定 v2 模型大小(根据需要选择)\n",
    "    remove_hs=False,\n",
    "    batch_size=32\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# output_file=\"embeddings/UniMolV2_emb1024.pkl\"\n",
    "# with open(output_file, 'wb') as f:\n",
    "#     pickle.dump(embeddings, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "path = './embeddings/UniMolV2_emb1024.pkl'\n",
    "import pickle\n",
    "with open(path, 'rb') as f:\n",
    "    unimol_feat = pickle.load(f)\n",
    "\n",
    "unimol_feat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8316 512\n"
     ]
    }
   ],
   "source": [
    "print(len(unimol_feat), len(unimol_feat['BrC1C(Br)C(Br)C(Br)C(Br)C1Br']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "处理前维度: (1, 512)\n",
      "处理后维度: (512,)\n"
     ]
    }
   ],
   "source": [
    "# import pickle\n",
    "# import numpy as np\n",
    "\n",
    "# # 加载原始特征\n",
    "# path = './embeddings/UniMol_emb512.pkl'\n",
    "# with open(path, 'rb') as f:\n",
    "#     unimol_feat = pickle.load(f)\n",
    "\n",
    "# # 处理特征维度:从(1,512)变为(512,)\n",
    "# unimol_feat_processed = {k: v.squeeze() for k, v in unimol_feat.items()}\n",
    "\n",
    "# # 验证处理结果\n",
    "# test_molecule = 'BrC1C(Br)C(Br)C(Br)C(Br)C1Br'\n",
    "# if test_molecule in unimol_feat_processed:\n",
    "#     print(f\"处理前维度: {unimol_feat[test_molecule].shape}\")\n",
    "#     print(f\"处理后维度: {unimol_feat_processed[test_molecule].shape}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # 保存处理后的特征\n",
    "# # 选项1:覆盖原始文件\n",
    "# with open(path, 'wb') as f:\n",
    "#     pickle.dump(unimol_feat_processed, f)\n",
    "\n",
    "# 选项2:保存到新文件(推荐,避免覆盖原始数据)\n",
    "# processed_path = './embeddings/UniMol_emb512_processed.pkl'\n",
    "# with open(processed_path, 'wb') as f:\n",
    "#     pickle.dump(unimol_feat_processed, f)\n",
    "\n",
    "# print(f\"处理后的特征已保存至: {processed_path}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "boom",
   "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.11.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}