File size: 47,483 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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 数据聚合:「输入药物 SMILES,输出基因表达 + 细胞形态」的多模态虚拟细胞模型,配对不齐,训练集不均衡。\n",
    "\n",
    "## 策略有3种:\n",
    "\n",
    "### 1 是按 SMILES 聚合,对每个 SMILES 在每个模态上 取平均或中位数(或更复杂的 embedding 聚合)。\n",
    "\n",
    "### 2 是多实例学习(Multiple Instance Learning, MIL):思路:把一个 SMILES 的所有 replicate 当作一个 bag,模型学习 bag-level 对齐。\n",
    "\n",
    "### 3 是不对齐 replicate,随机采样:思路:训练时,每个 batch 从两个模态中随机采样该 SMILES 的一个 replicate,逐步逼近两个分布。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "import os\n",
    "import h5py\n",
    "\n",
    "def load_from_HDF(fname):\n",
    "    \"\"\"Load data from a HDF5 file to a dictionary.\"\"\"\n",
    "    data = dict()\n",
    "    with h5py.File(fname, 'r') as f:\n",
    "        for key in f:\n",
    "            data[key] = np.asarray(f[key])\n",
    "            if isinstance(data[key][0], np.bytes_):\n",
    "                data[key] = data[key].astype(str)\n",
    "    return data\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "CP_path =  './Processed_Paired_CP_KeepRep.h5'\n",
    "GE_path = './Processed_Paired_GE_KeepRep.h5'\n",
    "\n",
    "CP_CSV = load_from_HDF(CP_path)\n",
    "GE_CSV = load_from_HDF(GE_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'canonical_smiles': array(['CCCOc1cc(N)ccc1C(=O)OCCN(CC)CC',\n",
       "        'C=C(C)[C@@H]1CCC(C)=C[C@H]1c1c(OC)cc(C)cc1OC',\n",
       "        'COc1cc(O)cc(/C=C/c2ccccc2)c1', ...,\n",
       "        'C[C@@H]1CN([C@@H](C)CO)C(=O)CCCn2cc(nn2)CO[C@H]1CN(C)C(=O)c1ccncc1',\n",
       "        'C[C@H](CO)N1C[C@H](C)[C@@H](CN(C)C(=O)c2ccncc2)OCc2cn(nn2)CCCC1=O',\n",
       "        'C[C@@H]1CN([C@@H](C)CO)C(=O)CCCn2nncc2CO[C@H]1CN(C)Cc1ccc2c(c1)OCCN2C'],\n",
       "       dtype='<U227'),\n",
       " 'control': array([[-0.15425342,  0.20473444,  0.04847282, ...,  0.22247523,\n",
       "          0.41372228,  0.09528223],\n",
       "        [-0.15425342,  0.20473444,  0.04847282, ...,  0.22247523,\n",
       "          0.41372228,  0.09528223],\n",
       "        [-0.15425342,  0.20473444,  0.04847282, ...,  0.22247523,\n",
       "          0.41372228,  0.09528223],\n",
       "        ...,\n",
       "        [ 0.08794986,  0.04630309,  0.0316207 , ..., -0.18811361,\n",
       "         -0.08507317, -0.19418037],\n",
       "        [ 0.08794986,  0.04630309,  0.0316207 , ..., -0.18811361,\n",
       "         -0.08507317, -0.19418037],\n",
       "        [ 0.08794986,  0.04630309,  0.0316207 , ..., -0.18811361,\n",
       "         -0.08507317, -0.19418037]], dtype=float32),\n",
       " 'dose': array([ 6.05, 10.  , 10.  , ..., 10.41, 10.14, 10.22], dtype=float32),\n",
       " 'target': array([[ 1.7987275 , -1.0678272 , -1.3908694 , ..., -2.2844946 ,\n",
       "         -1.4380481 , -0.4035441 ],\n",
       "        [ 0.3030874 ,  0.57465357, -0.18462732, ..., -1.4371198 ,\n",
       "         -0.8579998 ,  0.20614216],\n",
       "        [-0.7811053 ,  0.5069796 ,  0.9922175 , ...,  0.3974406 ,\n",
       "         -0.13609461,  0.42841423],\n",
       "        ...,\n",
       "        [ 1.466404  , -1.2910391 , -0.19340979, ..., -2.0167367 ,\n",
       "         -1.2818346 , -1.4399147 ],\n",
       "        [ 1.0264087 , -0.42999583, -1.681699  , ..., -1.4709337 ,\n",
       "         -0.9747103 , -1.4030336 ],\n",
       "        [ 1.4138446 , -0.93786097, -1.3868744 , ..., -1.2337868 ,\n",
       "         -0.58811694, -0.94757   ]], dtype=float32)}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "CP_CSV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'canonical_smiles': array(['CC(C)[C@H](CO)Nc1nc(Nc2cc(N)cc(Cl)c2)c2ncn(C(C)C)c2n1',\n",
       "        'Ic1cccc(CSc2nnc(-c3ccncc3)o2)c1',\n",
       "        'O=C(Nc1ccncc1)Nc1c(Cl)cc(Cl)cc1Cl', ...,\n",
       "        'O=C(O)c1ccc(-c2ccc(/C=c3\\\\sc4nc5ccccc5n4c3=O)o2)cc1',\n",
       "        'O=S(=O)(c1cccc2cncc(C(F)F)c12)N1CCCNCC1',\n",
       "        'COc1ccc(S(=O)(=O)N(C)C[C@@H]2Oc3c(NC(=O)Nc4cccc5ccccc45)cccc3C(=O)N([C@@H](C)CO)C[C@H]2C)cc1'],\n",
       "       dtype='<U227'),\n",
       " 'control': array([[ 0.305876  , -0.59514517, -0.21795662, ...,  0.20644613,\n",
       "         -0.07786681,  0.14617148],\n",
       "        [ 0.305876  , -0.59514517, -0.21795662, ...,  0.20644613,\n",
       "         -0.07786681,  0.14617148],\n",
       "        [ 0.305876  , -0.59514517, -0.21795662, ...,  0.20644613,\n",
       "         -0.07786681,  0.14617148],\n",
       "        ...,\n",
       "        [ 0.        ,  0.        ,  0.        , ...,  0.        ,\n",
       "          0.        ,  0.        ],\n",
       "        [ 0.        ,  0.        ,  0.        , ...,  0.        ,\n",
       "          0.        ,  0.        ],\n",
       "        [ 0.        ,  0.        ,  0.        , ...,  0.        ,\n",
       "          0.        ,  0.        ]], dtype=float32),\n",
       " 'dose': array([50. , 12.7, 50. , ..., 20. , 40. , 20. ], dtype=float32),\n",
       " 'target': array([[-0.7184085 , -1.4126618 , -1.7777987 , ...,  1.1767539 ,\n",
       "          2.0003324 ,  2.4972866 ],\n",
       "        [ 0.25343022, -1.2717106 , -0.0366732 , ...,  1.8126812 ,\n",
       "         -0.6341776 , -1.2102923 ],\n",
       "        [-0.43184918,  1.0067521 , -0.00558909, ..., -0.26218557,\n",
       "         -0.8643179 ,  1.4752281 ],\n",
       "        ...,\n",
       "        [-0.67632276,  0.7587029 ,  0.3990235 , ...,  2.8850307 ,\n",
       "         -0.92035365, -1.8870968 ],\n",
       "        [-2.1307466 ,  2.1573339 , -1.6117429 , ...,  0.566304  ,\n",
       "         -1.1584423 , -2.332463  ],\n",
       "        [ 2.0216608 ,  1.4105401 , -1.0605472 , ..., -0.1974064 ,\n",
       "         -0.30219036, -1.2475965 ]], dtype=float32)}"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "GE_CSV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((86844, 741), (57835, 977))"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "CP_CSV['target'].shape, GE_CSV['target'].shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 按照第一种方式直接 mean"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ 聚合后的数据已保存到 ./Aggregated_CP_GE.h5\n"
     ]
    }
   ],
   "source": [
    "import h5py\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "def aggregate_modalities(CP, GE, out_path):\n",
    "    # 转成 DataFrame 方便聚合\n",
    "    CP_df = pd.DataFrame({\n",
    "        \"SMILES\": CP[\"canonical_smiles\"],\n",
    "        \"control\": list(CP[\"control\"]),\n",
    "        \"target\": list(CP[\"target\"])\n",
    "    })\n",
    "    GE_df = pd.DataFrame({\n",
    "        \"SMILES\": GE[\"canonical_smiles\"],\n",
    "        \"control\": list(GE[\"control\"]),\n",
    "        \"target\": list(GE[\"target\"])\n",
    "    })\n",
    "\n",
    "    # groupby + mean pooling\n",
    "    CP_grouped = CP_df.groupby(\"SMILES\").agg(lambda x: np.nanmean(np.stack(x), axis=0)).reset_index()\n",
    "    GE_grouped = GE_df.groupby(\"SMILES\").agg(lambda x: np.nanmean(np.stack(x), axis=0)).reset_index()\n",
    "\n",
    "    # merge 保证对齐\n",
    "    merged = pd.merge(CP_grouped, GE_grouped, on=\"SMILES\", how=\"inner\", suffixes=(\"_CP\", \"_GE\"))\n",
    "\n",
    "    # 转 numpy array 并替换剩余 NaN\n",
    "    def clean_array(arr_list):\n",
    "        arr = np.stack(arr_list.to_numpy())\n",
    "        arr = np.nan_to_num(arr, nan=0.0, posinf=0.0, neginf=0.0)  # 替换 NaN/Inf\n",
    "        return arr.astype(np.float32)\n",
    "\n",
    "    smiles_array     = merged[\"SMILES\"].to_numpy(dtype=\"S\")\n",
    "    control_CP_array = clean_array(merged[\"control_CP\"])\n",
    "    target_CP_array  = clean_array(merged[\"target_CP\"])\n",
    "    control_GE_array = clean_array(merged[\"control_GE\"])\n",
    "    target_GE_array  = clean_array(merged[\"target_GE\"])\n",
    "\n",
    "    # 存 HDF5\n",
    "    with h5py.File(out_path, \"w\") as f:\n",
    "        f.create_dataset(\"canonical_smiles\", data=smiles_array)\n",
    "        f.create_dataset(\"control_CP\", data=control_CP_array)\n",
    "        f.create_dataset(\"target_CP\", data=target_CP_array)\n",
    "        f.create_dataset(\"control_GE\", data=control_GE_array)\n",
    "        f.create_dataset(\"target_GE\", data=target_GE_array)\n",
    "\n",
    "    print(f\"✅ 聚合后的数据已保存到 {out_path}\")\n",
    "\n",
    "# 用法\n",
    "# root = '/home/bob/boom/VCBench/data/MVC/CDRP-BBBC047-Bray/'\n",
    "CP_path = './Processed_Paired_CP.h5'\n",
    "GE_path = './Processed_Paired_GE.h5'\n",
    "\n",
    "CP_CSV = load_from_HDF(CP_path)\n",
    "GE_CSV = load_from_HDF(GE_path)\n",
    "\n",
    "out_path = './Aggregated_CP_GE.h5'\n",
    "aggregate_modalities(CP_CSV, GE_CSV, out_path)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'canonical_smiles': array(['Brc1c(CSc2nc3ccccc3s2)nc2ncccn12', 'Brc1c(NC2=NCCN2)ccc2nccnc12',\n",
       "        'Brc1ccc(CSc2nnc(-c3ccccn3)n2Cc2ccco2)cc1', ...,\n",
       "        'c1nc(CC2CCNCC2)c[nH]1', 'c1nc(CCCC2CCNCC2)c[nH]1',\n",
       "        'c1ncn(CCOCCOc2ccc3c(c2)CCC3)n1'], dtype='<U227'),\n",
       " 'control_CP': array([[-0.15487705,  0.11688805, -0.06308393, ...,  0.24665973,\n",
       "          0.18521263,  0.24594025],\n",
       "        [-0.1634329 ,  0.15811297, -0.03295023, ...,  0.2232287 ,\n",
       "          0.18645084,  0.20041683],\n",
       "        [-0.13265091,  0.11912386, -0.04087081, ...,  0.23031679,\n",
       "          0.15957166,  0.2795726 ],\n",
       "        ...,\n",
       "        [-0.16390067,  0.1292826 , -0.02731108, ...,  0.2356141 ,\n",
       "          0.20089747,  0.22413647],\n",
       "        [-0.1634329 ,  0.15811297, -0.03295023, ...,  0.2232287 ,\n",
       "          0.18645084,  0.20041683],\n",
       "        [-0.1903376 ,  0.16364928, -0.02507655, ...,  0.2462861 ,\n",
       "          0.21280092,  0.2474828 ]], dtype=float32),\n",
       " 'control_GE': array([[-0.11589041,  0.09791137, -0.10001642, ..., -0.04151818,\n",
       "          0.00727702, -0.21572095],\n",
       "        [ 0.01338525, -0.02699645,  0.0147262 , ..., -0.01713243,\n",
       "         -0.02412532,  0.08308113],\n",
       "        [ 0.02007259,  0.03755556, -0.02430556, ..., -0.18552697,\n",
       "         -0.0794616 , -0.020855  ],\n",
       "        ...,\n",
       "        [ 0.02062   , -0.00183125, -0.13683268, ..., -0.17978694,\n",
       "          0.21799538,  0.17114288],\n",
       "        [ 0.01338525, -0.02699645,  0.0147262 , ..., -0.01713243,\n",
       "         -0.02412532,  0.08308113],\n",
       "        [-0.06893609, -0.02563992,  0.06738283, ...,  0.07980002,\n",
       "         -0.11235818, -0.03411045]], dtype=float32),\n",
       " 'target_CP': array([[ 0.38674092, -0.62070274, -0.62418985, ...,  0.44180262,\n",
       "          0.42434335, -1.2392346 ],\n",
       "        [ 0.31655684, -0.23943731,  0.18836854, ..., -0.05182697,\n",
       "          0.2953927 ,  1.5328658 ],\n",
       "        [-1.4637322 ,  1.873155  ,  2.345407  , ...,  2.3001804 ,\n",
       "          2.5974057 , -0.5258522 ],\n",
       "        ...,\n",
       "        [-0.22405519,  0.21074149, -0.0310891 , ..., -0.20554903,\n",
       "         -0.28407168, -0.17878559],\n",
       "        [ 0.36180133, -0.36012647,  0.18524444, ..., -0.5896245 ,\n",
       "         -0.28982347, -0.09377167],\n",
       "        [-0.11151703,  0.40477425,  0.04721215, ...,  1.3899186 ,\n",
       "          0.70356005,  0.23341325]], dtype=float32),\n",
       " 'target_GE': array([[ 0.09065   ,  0.0786    , -0.06155001, ..., -0.1333    ,\n",
       "          0.097875  ,  0.15165001],\n",
       "        [-0.07302775,  0.0460825 , -0.02222175, ...,  0.17655626,\n",
       "         -0.154201  ,  0.033125  ],\n",
       "        [-0.03446667, -0.01266666,  0.04358333, ...,  0.27253333,\n",
       "         -0.06081   ,  0.28026667],\n",
       "        ...,\n",
       "        [ 0.22472501,  0.20904249, -0.2872    , ..., -0.22035149,\n",
       "          0.5861085 ,  0.278331  ],\n",
       "        [ 0.01292225,  0.07139751, -0.13613375, ..., -0.16344374,\n",
       "          0.053449  , -0.200645  ],\n",
       "        [ 0.14866668, -0.054     ,  0.04613333, ...,  0.22286667,\n",
       "         -0.09675   , -0.01868333]], dtype=float32)}"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "out_path = './Aggregated_CP_GE.h5'\n",
    "\n",
    "agg_data = load_from_HDF(out_path)\n",
    "agg_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((20341, 775), (20341, 775), (20341, 977), (20341, 977))"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agg_data['control_CP'].shape, agg_data['target_CP'].shape, agg_data['control_GE'].shape, agg_data['target_GE'].shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'O=C(C[C@@H]1CC[C@@H]2[C@H](COC[C@H](O)CN2Cc2cc(F)cc(F)c2)O1)Nc1nccs1' in agg_data['canonical_smiles']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 复杂点,样本级别的配对"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "加载源数据...\n",
      "开始创建多模态配对数据集...\n",
      "Cell Painting 唯一化合物数: 20341\n",
      "Gene Expression 唯一化合物数: 20341\n",
      "多模态共有化合物数 (Intersection): 20341\n",
      "生成配对样本总数: 223805\n",
      "正在组装最终矩阵...\n",
      "✅ 最终数据集已保存至: ./Paired_CP_GE_Dataset.h5\n",
      "------------------------------\n",
      "Dataset Shapes:\n",
      "canonical_smiles: (223805,)\n",
      "control_CP: (223805, 741)\n",
      "target_CP: (223805, 741)\n",
      "control_GE: (223805, 977)\n",
      "target_GE: (223805, 977)\n",
      "CP_dose: (223805,)\n",
      "GE_dose: (223805,)\n"
     ]
    }
   ],
   "source": [
    "import h5py\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from collections import defaultdict\n",
    "\n",
    "# ==========================================\n",
    "# 0. 辅助函数:读取 HDF5\n",
    "# ==========================================\n",
    "def load_from_HDF(fname):\n",
    "    data = dict()\n",
    "    with h5py.File(fname, 'r') as f:\n",
    "        for key in f:\n",
    "            data[key] = np.asarray(f[key])\n",
    "            # 处理字符串解码\n",
    "            if data[key].dtype.kind == 'S':\n",
    "                data[key] = data[key].astype(str)\n",
    "    return data\n",
    "\n",
    "# ==========================================\n",
    "# 1. 核心逻辑:创建稳健配对数据集\n",
    "# ==========================================\n",
    "def create_robust_paired_dataset(CP_data, GE_data, out_path, max_samples_per_smiles=5, seed=42):\n",
    "    \"\"\"\n",
    "    CP_data, GE_data: 包含 'canonical_smiles', 'control', 'target', 'dose' 的字典\n",
    "    max_samples_per_smiles: 每个模态最多采样的重复数\n",
    "    seed: 随机种子,保证配对结果可复现\n",
    "    \"\"\"\n",
    "    print(\"开始创建多模态配对数据集...\")\n",
    "    \n",
    "    # [新增] 检查输入数据是否包含 dose\n",
    "    if 'dose' not in CP_data or 'dose' not in GE_data:\n",
    "        raise ValueError(\"输入数据缺少 'dose' 字段,请检查上一步是否正确保存了剂量信息。\")\n",
    "\n",
    "    # [新增] 设置随机种子\n",
    "    np.random.seed(seed)\n",
    "    \n",
    "    # --- A. 构建索引映射 ---\n",
    "    cp_smiles_to_indices = defaultdict(list)\n",
    "    ge_smiles_to_indices = defaultdict(list)\n",
    "    \n",
    "    for idx, smiles in enumerate(CP_data['canonical_smiles']):\n",
    "        cp_smiles_to_indices[smiles].append(idx)\n",
    "    \n",
    "    for idx, smiles in enumerate(GE_data['canonical_smiles']):\n",
    "        ge_smiles_to_indices[smiles].append(idx)\n",
    "    \n",
    "    # --- B. 找交集 ---\n",
    "    common_smiles = set(cp_smiles_to_indices.keys()) & set(ge_smiles_to_indices.keys())\n",
    "    print(f\"Cell Painting 唯一化合物数: {len(cp_smiles_to_indices)}\")\n",
    "    print(f\"Gene Expression 唯一化合物数: {len(ge_smiles_to_indices)}\")\n",
    "    print(f\"多模态共有化合物数 (Intersection): {len(common_smiles)}\")\n",
    "    \n",
    "    # --- C. 生成配对索引 ---\n",
    "    paired_indices = []\n",
    "    \n",
    "    for i, smiles in enumerate(common_smiles):\n",
    "        # 获取该 SMILES 的所有索引\n",
    "        cp_indices = cp_smiles_to_indices[smiles]\n",
    "        ge_indices = ge_smiles_to_indices[smiles]\n",
    "        \n",
    "        # 限制采样数量\n",
    "        n_cp = min(max_samples_per_smiles, len(cp_indices))\n",
    "        n_ge = min(max_samples_per_smiles, len(ge_indices))\n",
    "        \n",
    "        # 无放回随机采样\n",
    "        sampled_cp_indices = np.random.choice(cp_indices, n_cp, replace=False)\n",
    "        sampled_ge_indices = np.random.choice(ge_indices, n_ge, replace=False)\n",
    "        \n",
    "        # 笛卡尔积配对\n",
    "        for cp_idx in sampled_cp_indices:\n",
    "            for ge_idx in sampled_ge_indices:\n",
    "                paired_indices.append({\n",
    "                    'smiles': smiles,\n",
    "                    'cp_idx': cp_idx,\n",
    "                    'ge_idx': ge_idx\n",
    "                })\n",
    "                \n",
    "    print(f\"生成配对样本总数: {len(paired_indices)}\")\n",
    "\n",
    "    # --- D. 组装数据 ---\n",
    "    n_samples = len(paired_indices)\n",
    "    \n",
    "    # 获取特征维度\n",
    "    cp_feat_dim = CP_data['target'].shape[1]\n",
    "    ge_feat_dim = GE_data['target'].shape[1]\n",
    "    \n",
    "    # 预分配内存\n",
    "    final_data = {\n",
    "        'canonical_smiles': np.empty(n_samples, dtype='S200'),\n",
    "        'control_CP': np.empty((n_samples, cp_feat_dim), dtype=np.float32),\n",
    "        'target_CP':  np.empty((n_samples, cp_feat_dim), dtype=np.float32),\n",
    "        'control_GE': np.empty((n_samples, ge_feat_dim), dtype=np.float32),\n",
    "        'target_GE':  np.empty((n_samples, ge_feat_dim), dtype=np.float32),\n",
    "        # [新增] 两个模态的剂量\n",
    "        'CP_dose':    np.empty(n_samples, dtype=np.float32), \n",
    "        'GE_dose':    np.empty(n_samples, dtype=np.float32)\n",
    "    }\n",
    "    \n",
    "    print(\"正在组装最终矩阵...\")\n",
    "    for i, item in enumerate(paired_indices):\n",
    "        cp_idx = item['cp_idx']\n",
    "        ge_idx = item['ge_idx']\n",
    "        \n",
    "        final_data['canonical_smiles'][i] = item['smiles'].encode('utf-8')\n",
    "        \n",
    "        # 填入 CP 数据\n",
    "        final_data['control_CP'][i]       = CP_data['control'][cp_idx]\n",
    "        final_data['target_CP'][i]        = CP_data['target'][cp_idx]\n",
    "        final_data['CP_dose'][i]          = CP_data['dose'][cp_idx] # [新增]\n",
    "        \n",
    "        # 填入 GE 数据\n",
    "        final_data['control_GE'][i]       = GE_data['control'][ge_idx]\n",
    "        final_data['target_GE'][i]        = GE_data['target'][ge_idx]\n",
    "        final_data['GE_dose'][i]          = GE_data['dose'][ge_idx] # [新增]\n",
    "        \n",
    "    # --- E. 数据清洗与保存 ---\n",
    "    # 检查并处理 NaN/Inf (Dose 通常不需要处理,但如果有 NaN 也顺便处理一下安全)\n",
    "    check_cols = ['control_CP', 'target_CP', 'control_GE', 'target_GE', 'CP_dose', 'GE_dose']\n",
    "    \n",
    "    for key in check_cols:\n",
    "        if np.isnan(final_data[key]).any() or np.isinf(final_data[key]).any():\n",
    "            print(f\"警告: {key} 包含 NaN 或 Inf,正在填充 0...\")\n",
    "            final_data[key] = np.nan_to_num(final_data[key], nan=0.0, posinf=0.0, neginf=0.0)\n",
    "\n",
    "    # 保存\n",
    "    with h5py.File(out_path, 'w') as f:\n",
    "        for key, val in final_data.items():\n",
    "            f.create_dataset(key, data=val)\n",
    "            \n",
    "    print(f\"✅ 最终数据集已保存至: {out_path}\")\n",
    "    print(\"-\" * 30)\n",
    "    print(f\"Dataset Shapes:\")\n",
    "    for k, v in final_data.items():\n",
    "        print(f\"{k}: {v.shape}\")\n",
    "\n",
    "# ==========================================\n",
    "# 2. 执行流程\n",
    "# ==========================================\n",
    "# 定义输入输出路径\n",
    "cp_input = './Processed_Paired_CP_KeepRep.h5'\n",
    "ge_input = './Processed_Paired_GE_KeepRep.h5'\n",
    "final_output = './Paired_CP_GE_Dataset.h5'\n",
    "\n",
    "# 加载数据\n",
    "print(\"加载源数据...\")\n",
    "cp_data = load_from_HDF(cp_input)\n",
    "ge_data = load_from_HDF(ge_input)\n",
    "\n",
    "# 执行配对\n",
    "create_robust_paired_dataset(cp_data, ge_data, final_output, max_samples_per_smiles=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'CP_dose': array([10.65, 10.65, 10.65, ..., 10.  , 10.  , 10.  ], dtype=float32),\n",
       " 'GE_dose': array([10.6501, 10.6501, 10.6501, ..., 10.    , 10.    , 10.    ],\n",
       "       dtype=float32),\n",
       " 'canonical_smiles': array(['C[C@H](CO)N1C[C@H](C)[C@H](CN(C)Cc2ccncc2)Oc2ccc(NS(C)(=O)=O)cc2CC1=O',\n",
       "        'C[C@H](CO)N1C[C@H](C)[C@H](CN(C)Cc2ccncc2)Oc2ccc(NS(C)(=O)=O)cc2CC1=O',\n",
       "        'C[C@H](CO)N1C[C@H](C)[C@H](CN(C)Cc2ccncc2)Oc2ccc(NS(C)(=O)=O)cc2CC1=O',\n",
       "        ..., 'CN(C)C(=O)n1nnnc1Cc1ccc(-c2ccccc2)cc1',\n",
       "        'CN(C)C(=O)n1nnnc1Cc1ccc(-c2ccccc2)cc1',\n",
       "        'CN(C)C(=O)n1nnnc1Cc1ccc(-c2ccccc2)cc1'], dtype='<U200'),\n",
       " 'control_CP': array([[-0.13953187,  0.06501261, -0.00263713, ...,  0.08332227,\n",
       "          0.12313318, -0.02047802],\n",
       "        [-0.13953187,  0.06501261, -0.00263713, ...,  0.08332227,\n",
       "          0.12313318, -0.02047802],\n",
       "        [-0.13953187,  0.06501261, -0.00263713, ...,  0.08332227,\n",
       "          0.12313318, -0.02047802],\n",
       "        ...,\n",
       "        [ 0.07532343,  0.01590352,  0.11149302, ...,  0.09762042,\n",
       "         -0.0291416 ,  0.18638068],\n",
       "        [ 0.06642057, -0.06762539,  0.07449123, ..., -0.2643804 ,\n",
       "         -0.08335885, -0.47207668],\n",
       "        [ 0.06642057, -0.06762539,  0.07449123, ..., -0.2643804 ,\n",
       "         -0.08335885, -0.47207668]], dtype=float32),\n",
       " 'control_GE': array([[ 0.24454208,  0.60980904,  0.60357696, ...,  0.18017063,\n",
       "         -0.88657326,  0.01677261],\n",
       "        [-0.56268126,  0.15758337, -0.13244417, ..., -0.6394515 ,\n",
       "          1.1245222 ,  1.1233364 ],\n",
       "        [ 0.44537392,  0.6973298 , -1.5441636 , ..., -0.425022  ,\n",
       "         -0.23347344,  0.57313305],\n",
       "        ...,\n",
       "        [ 0.65565985,  0.11522385,  0.9597033 , ...,  0.43092778,\n",
       "         -0.15957022,  0.03049997],\n",
       "        [ 0.7688196 ,  0.9452282 , -0.80648696, ..., -0.3607209 ,\n",
       "          0.51043606, -1.139512  ],\n",
       "        [ 0.65565985,  0.11522385,  0.9597033 , ...,  0.43092778,\n",
       "         -0.15957022,  0.03049997]], dtype=float32),\n",
       " 'target_CP': array([[-0.7322785 , -0.1324034 , -0.92490584, ...,  0.0871982 ,\n",
       "          0.19238813, -0.2730067 ],\n",
       "        [-0.7322785 , -0.1324034 , -0.92490584, ...,  0.0871982 ,\n",
       "          0.19238813, -0.2730067 ],\n",
       "        [-0.7322785 , -0.1324034 , -0.92490584, ...,  0.0871982 ,\n",
       "          0.19238813, -0.2730067 ],\n",
       "        ...,\n",
       "        [-6.900763  , 10.        , 10.        , ...,  8.523304  ,\n",
       "          8.528054  ,  9.481978  ],\n",
       "        [-6.2097163 ,  9.116677  , 10.        , ...,  5.122239  ,\n",
       "          5.808592  ,  1.9759494 ],\n",
       "        [-6.2097163 ,  9.116677  , 10.        , ...,  5.122239  ,\n",
       "          5.808592  ,  1.9759494 ]], dtype=float32),\n",
       " 'target_GE': array([[-0.13318162, -2.3996215 , -0.60478145, ..., -1.7717572 ,\n",
       "         -0.7603032 ,  1.6145478 ],\n",
       "        [ 0.71842533, -2.600954  ,  0.4446499 , ..., -0.6659924 ,\n",
       "         -1.0708426 , -0.40832376],\n",
       "        [-1.034582  ,  1.0713423 , -4.108202  , ...,  0.01961743,\n",
       "          1.2580668 ,  0.00507223],\n",
       "        ...,\n",
       "        [ 0.11101682,  1.4468411 ,  0.9668232 , ...,  0.43233392,\n",
       "         -0.3482708 , -1.8351849 ],\n",
       "        [-0.41256198, -0.05275529, -3.0842478 , ..., -0.2453646 ,\n",
       "          1.7232248 ,  3.0262802 ],\n",
       "        [ 0.11101682,  1.4468411 ,  0.9668232 , ...,  0.43233392,\n",
       "         -0.3482708 , -1.8351849 ]], dtype=float32)}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "ename": "",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m在当前单元格或上一个单元格中执行代码时 Kernel 崩溃。\n",
      "\u001b[1;31m请查看单元格中的代码,以确定故障的可能原因。\n",
      "\u001b[1;31m单击<a href='https://aka.ms/vscodeJupyterKernelCrash'>此处</a>了解详细信息。\n",
      "\u001b[1;31m有关更多详细信息,请查看 Jupyter <a href='command:jupyter.viewOutput'>log</a>。"
     ]
    }
   ],
   "source": [
    "out_path = './Paired_CP_GE_Dataset.h5'\n",
    "\n",
    "agg_data = load_from_HDF(out_path)\n",
    "agg_data"
   ]
  },
  {
   "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": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "共有化合物: 20341\n",
      "总配对样本数: 242192\n",
      "数据集形状:\n",
      "  control_CP: (242192, 775)\n",
      "  target_CP: (242192, 775)\n",
      "  control_GE: (242192, 977)\n",
      "  target_GE: (242192, 977)\n",
      "✅ 配对数据集已保存到: ./Paired_CP_GE_Dataset.h5\n"
     ]
    }
   ],
   "source": [
    "# import h5py\n",
    "# import numpy as np\n",
    "# import pandas as pd\n",
    "# from collections import defaultdict\n",
    "\n",
    "# def create_paired_dataset(CP_data, GE_data, out_path):\n",
    "#     \"\"\"\n",
    "#     创建样本级配对的多模态数据集\n",
    "#     保持原始样本的完整性,只配对真正对应的样本\n",
    "#     \"\"\"\n",
    "    \n",
    "#     # 构建SMILES到索引列表的映射\n",
    "#     cp_smiles_to_indices = defaultdict(list)\n",
    "#     ge_smiles_to_indices = defaultdict(list)\n",
    "    \n",
    "#     for idx, smiles in enumerate(CP_data['canonical_smiles']):\n",
    "#         cp_smiles_to_indices[smiles].append(idx)\n",
    "    \n",
    "#     for idx, smiles in enumerate(GE_data['canonical_smiles']):\n",
    "#         ge_smiles_to_indices[smiles].append(idx)\n",
    "    \n",
    "#     # 找到共有的SMILES\n",
    "#     common_smiles = set(cp_smiles_to_indices.keys()) & set(ge_smiles_to_indices.keys())\n",
    "#     print(f\"共有化合物: {len(common_smiles)}\")\n",
    "    \n",
    "#     # 收集所有有效配对\n",
    "#     paired_samples = []\n",
    "    \n",
    "#     for smiles in common_smiles:\n",
    "#         cp_indices = cp_smiles_to_indices[smiles]\n",
    "#         ge_indices = ge_smiles_to_indices[smiles]\n",
    "        \n",
    "#         # 为每个SMILES创建所有可能的CP-GE配对\n",
    "#         for cp_idx in cp_indices:\n",
    "#             for ge_idx in ge_indices:\n",
    "#                 paired_samples.append({\n",
    "#                     'canonical_smiles': smiles,\n",
    "#                     'cp_index': cp_idx,\n",
    "#                     'ge_index': ge_idx\n",
    "#                 })\n",
    "    \n",
    "#     print(f\"总配对样本数: {len(paired_samples)}\")\n",
    "    \n",
    "#     # 创建最终的字典形数据集\n",
    "#     dataset_dict = {\n",
    "#         'canonical_smiles': [],\n",
    "#         'control_CP': [],\n",
    "#         'target_CP': [], \n",
    "#         'control_GE': [],\n",
    "#         'target_GE': []\n",
    "#     }\n",
    "    \n",
    "#     for sample in paired_samples:\n",
    "#         dataset_dict['canonical_smiles'].append(sample['canonical_smiles'])\n",
    "#         dataset_dict['control_CP'].append(CP_data['control'][sample['cp_index']])\n",
    "#         dataset_dict['target_CP'].append(CP_data['target'][sample['cp_index']])\n",
    "#         dataset_dict['control_GE'].append(GE_data['control'][sample['ge_index']]) \n",
    "#         dataset_dict['target_GE'].append(GE_data['target'][sample['ge_index']])\n",
    "    \n",
    "#     # 转换为numpy数组\n",
    "#     final_dataset = {}\n",
    "#     final_dataset['canonical_smiles'] = np.array(dataset_dict['canonical_smiles'], dtype='S')\n",
    "#     final_dataset['control_CP'] = np.array(dataset_dict['control_CP'], dtype=np.float32)\n",
    "#     final_dataset['target_CP'] = np.array(dataset_dict['target_CP'], dtype=np.float32)\n",
    "#     final_dataset['control_GE'] = np.array(dataset_dict['control_GE'], dtype=np.float32)\n",
    "#     final_dataset['target_GE'] = np.array(dataset_dict['target_GE'], dtype=np.float32)\n",
    "    \n",
    "#     print(f\"数据集形状:\")\n",
    "#     print(f\"  control_CP: {final_dataset['control_CP'].shape}\")\n",
    "#     print(f\"  target_CP: {final_dataset['target_CP'].shape}\")\n",
    "#     print(f\"  control_GE: {final_dataset['control_GE'].shape}\")\n",
    "#     print(f\"  target_GE: {final_dataset['target_GE'].shape}\")\n",
    "    \n",
    "#     # 保存为HDF5\n",
    "#     with h5py.File(out_path, 'w') as f:\n",
    "#         for key, value in final_dataset.items():\n",
    "#             f.create_dataset(key, data=value)\n",
    "    \n",
    "#     print(f\"✅ 配对数据集已保存到: {out_path}\")\n",
    "#     return final_dataset\n",
    "\n",
    "# # 使用方案\n",
    "# out_path = './Paired_CP_GE_Dataset.h5'\n",
    "# paired_dataset = create_paired_dataset(CP_CSV, GE_CSV, out_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'canonical_smiles': array(['C[C@@H]1CCCCO[C@@H](CN(C)C(=O)c2ccccc2)[C@@H](C)CN([C@H](C)CO)C(=O)c2cc(N(C)C)ccc2O1',\n",
       "        'C[C@@H]1CCCCO[C@@H](CN(C)C(=O)c2ccccc2)[C@@H](C)CN([C@H](C)CO)C(=O)c2cc(N(C)C)ccc2O1',\n",
       "        'C[C@@H]1CCCCO[C@@H](CN(C)C(=O)c2ccccc2)[C@@H](C)CN([C@H](C)CO)C(=O)c2cc(N(C)C)ccc2O1',\n",
       "        ...,\n",
       "        'C/C=C/c1ccc2n(c1=O)C[C@H]1[C@H](CO)[C@@H](C(=O)N3CCCCC3)[C@@H]2N1C(=O)C1CCC1.C/C=C\\\\c1ccc2n(c1=O)C[C@H]1[C@H](CO)[C@@H](C(=O)N3CCCCC3)[C@@H]2N1C(=O)C1CCC1',\n",
       "        'C/C=C/c1ccc2n(c1=O)C[C@H]1[C@H](CO)[C@@H](C(=O)N3CCCCC3)[C@@H]2N1C(=O)C1CCC1.C/C=C\\\\c1ccc2n(c1=O)C[C@H]1[C@H](CO)[C@@H](C(=O)N3CCCCC3)[C@@H]2N1C(=O)C1CCC1',\n",
       "        'C/C=C/c1ccc2n(c1=O)C[C@H]1[C@H](CO)[C@@H](C(=O)N3CCCCC3)[C@@H]2N1C(=O)C1CCC1.C/C=C\\\\c1ccc2n(c1=O)C[C@H]1[C@H](CO)[C@@H](C(=O)N3CCCCC3)[C@@H]2N1C(=O)C1CCC1'],\n",
       "       dtype='<U227'),\n",
       " 'control_CP': array([[-0.08486467,  0.1714288 , -0.05182531, ...,  0.12218629,\n",
       "          0.21159805,  0.24014652],\n",
       "        [-0.08486467,  0.1714288 , -0.05182531, ...,  0.12218629,\n",
       "          0.21159805,  0.24014652],\n",
       "        [-0.08486467,  0.1714288 , -0.05182531, ...,  0.12218629,\n",
       "          0.21159805,  0.24014652],\n",
       "        ...,\n",
       "        [-0.2378668 ,  0.23262355, -0.0475704 , ...,  0.21625724,\n",
       "          0.23215774,  0.23364826],\n",
       "        [-0.2378668 ,  0.23262355, -0.0475704 , ...,  0.21625724,\n",
       "          0.23215774,  0.23364826],\n",
       "        [-0.2378668 ,  0.23262355, -0.0475704 , ...,  0.21625724,\n",
       "          0.23215774,  0.23364826]], dtype=float32),\n",
       " 'control_GE': array([[-0.0330701 ,  0.01753275, -0.05136025, ...,  0.06250588,\n",
       "         -0.0405625 , -0.19137537],\n",
       "        [ 0.01287525,  0.03997513,  0.035275  , ..., -0.04473713,\n",
       "         -0.1068325 ,  0.03364687],\n",
       "        [ 0.04092   , -0.0524448 , -0.0302184 , ..., -0.045687  ,\n",
       "          0.018924  , -0.026421  ],\n",
       "        ...,\n",
       "        [ 0.1941795 , -0.00547   , -0.2204975 , ..., -0.05459375,\n",
       "          0.10817   ,  0.011832  ],\n",
       "        [ 0.03131568,  0.1014732 , -0.214663  , ...,  0.111306  ,\n",
       "         -0.0012838 ,  0.143236  ],\n",
       "        [-0.0118007 , -0.124132  ,  0.111037  , ...,  0.1051161 ,\n",
       "         -0.275516  , -0.05782   ]], dtype=float32),\n",
       " 'target_CP': array([[ 1.1871912 , -0.0034563 ,  0.52810115, ..., -1.6746186 ,\n",
       "         -0.9638308 ,  0.73771006],\n",
       "        [ 1.1871912 , -0.0034563 ,  0.52810115, ..., -1.6746186 ,\n",
       "         -0.9638308 ,  0.73771006],\n",
       "        [ 1.1871912 , -0.0034563 ,  0.52810115, ..., -1.6746186 ,\n",
       "         -0.9638308 ,  0.73771006],\n",
       "        ...,\n",
       "        [-0.45244193, -0.05774116, -0.9494869 , ..., -0.27629495,\n",
       "         -0.4013643 , -0.337052  ],\n",
       "        [-0.45244193, -0.05774116, -0.9494869 , ..., -0.27629495,\n",
       "         -0.4013643 , -0.337052  ],\n",
       "        [-0.45244193, -0.05774116, -0.9494869 , ..., -0.27629495,\n",
       "         -0.4013643 , -0.337052  ]], dtype=float32),\n",
       " 'target_GE': array([[ 0.10045115,  0.0189385 , -0.136369  , ..., -0.115892  ,\n",
       "          0.021835  , -0.240325  ],\n",
       "        [ 0.105046  , -0.199388  ,  0.0151    , ..., -0.36268   ,\n",
       "          0.01984   ,  0.060748  ],\n",
       "        [ 0.17609   ,  0.012886  , -0.05032   , ...,  0.045372  ,\n",
       "          0.37968   ,  0.180597  ],\n",
       "        ...,\n",
       "        [-0.120883  ,  0.42693624, -0.11864   , ...,  0.14749   ,\n",
       "         -0.361165  , -0.1950255 ],\n",
       "        [ 0.013835  , -0.42966   ,  0.396749  , ...,  0.25792   ,\n",
       "         -0.1543    ,  0.03015   ],\n",
       "        [ 0.1609315 , -0.40984   ,  0.028058  , ...,  0.31154   ,\n",
       "         -0.104255  , -0.16908   ]], dtype=float32)}"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "out_path = './Paired_CP_GE_Dataset.h5'\n",
    "\n",
    "agg_data = load_from_HDF(out_path)\n",
    "agg_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((223689, 775), (223689, 775), (223689, 977), (223689, 977))"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agg_data['control_CP'].shape, agg_data['target_CP'].shape, agg_data['control_GE'].shape, agg_data['target_GE'].shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 限制配对的数量,更好收敛。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始创建稳健配对数据集...\n",
      "共有化合物: 20341\n",
      "处理进度: 0/20341\n",
      "处理进度: 1000/20341\n",
      "处理进度: 2000/20341\n",
      "处理进度: 3000/20341\n",
      "处理进度: 4000/20341\n",
      "处理进度: 5000/20341\n",
      "处理进度: 6000/20341\n",
      "处理进度: 7000/20341\n",
      "处理进度: 8000/20341\n",
      "处理进度: 9000/20341\n",
      "处理进度: 10000/20341\n",
      "处理进度: 11000/20341\n",
      "处理进度: 12000/20341\n",
      "处理进度: 13000/20341\n",
      "处理进度: 14000/20341\n",
      "处理进度: 15000/20341\n",
      "处理进度: 16000/20341\n",
      "处理进度: 17000/20341\n",
      "处理进度: 18000/20341\n",
      "处理进度: 19000/20341\n",
      "处理进度: 20000/20341\n",
      "总配对样本数: 169287\n",
      "数据收集进度: 0/169287\n",
      "数据收集进度: 10000/169287\n",
      "数据收集进度: 20000/169287\n",
      "数据收集进度: 30000/169287\n",
      "数据收集进度: 40000/169287\n",
      "数据收集进度: 50000/169287\n",
      "数据收集进度: 60000/169287\n",
      "数据收集进度: 70000/169287\n",
      "数据收集进度: 80000/169287\n",
      "数据收集进度: 90000/169287\n",
      "数据收集进度: 100000/169287\n",
      "数据收集进度: 110000/169287\n",
      "数据收集进度: 120000/169287\n",
      "数据收集进度: 130000/169287\n",
      "数据收集进度: 140000/169287\n",
      "数据收集进度: 150000/169287\n",
      "数据收集进度: 160000/169287\n",
      "control_CP: 均值=0.0175, 标准差=0.3551, 形状=(169287, 775)\n",
      "target_CP: 均值=-0.0107, 标准差=1.1325, 形状=(169287, 775)\n",
      "control_GE: 均值=-0.0003, 标准差=0.1331, 形状=(169287, 977)\n",
      "target_GE: 均值=-0.0007, 标准差=0.2798, 形状=(169287, 977)\n",
      "✅ 稳健配对数据集已保存到: ./Paired_CP_GE_Dataset.h5\n"
     ]
    }
   ],
   "source": [
    "import h5py\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from collections import defaultdict\n",
    "\n",
    "def create_robust_paired_dataset(CP_data, GE_data, out_path, max_pairs_per_smiles=20):\n",
    "    \"\"\"\n",
    "    创建稳健的样本级配对数据集\n",
    "    添加样本限制和数据处理\n",
    "    \"\"\"\n",
    "    \n",
    "    print(\"开始创建稳健配对数据集...\")\n",
    "    \n",
    "    # 构建SMILES到索引列表的映射\n",
    "    cp_smiles_to_indices = defaultdict(list)\n",
    "    ge_smiles_to_indices = defaultdict(list)\n",
    "    \n",
    "    for idx, smiles in enumerate(CP_data['canonical_smiles']):\n",
    "        cp_smiles_to_indices[smiles].append(idx)\n",
    "    \n",
    "    for idx, smiles in enumerate(GE_data['canonical_smiles']):\n",
    "        ge_smiles_to_indices[smiles].append(idx)\n",
    "    \n",
    "    # 找到共有的SMILES\n",
    "    common_smiles = set(cp_smiles_to_indices.keys()) & set(ge_smiles_to_indices.keys())\n",
    "    print(f\"共有化合物: {len(common_smiles)}\")\n",
    "    \n",
    "    # 收集所有有效配对(带采样限制)\n",
    "    paired_samples = []\n",
    "    \n",
    "    for i, smiles in enumerate(common_smiles):\n",
    "        # if i % 1000 == 0:\n",
    "        #     print(f\"处理进度: {i}/{len(common_smiles)}\")\n",
    "            \n",
    "        cp_indices = cp_smiles_to_indices[smiles]\n",
    "        ge_indices = ge_smiles_to_indices[smiles]\n",
    "        \n",
    "        # 限制每个SMILES的最大配对数,避免样本爆炸\n",
    "        max_cp_samples = min(3, len(cp_indices))\n",
    "        max_ge_samples = min(3, len(ge_indices))\n",
    "        \n",
    "        # 随机采样\n",
    "        sampled_cp = np.random.choice(cp_indices, max_cp_samples, replace=False)\n",
    "        sampled_ge = np.random.choice(ge_indices, max_ge_samples, replace=False)\n",
    "        \n",
    "        # 创建配对\n",
    "        for cp_idx in sampled_cp:\n",
    "            for ge_idx in sampled_ge:\n",
    "                paired_samples.append({\n",
    "                    'canonical_smiles': smiles,\n",
    "                    'cp_index': cp_idx,\n",
    "                    'ge_index': ge_idx\n",
    "                })\n",
    "    \n",
    "    print(f\"总配对样本数: {len(paired_samples)}\")\n",
    "    \n",
    "    # 创建最终的字典形数据集\n",
    "    dataset_dict = {\n",
    "        'canonical_smiles': [],\n",
    "        'control_CP': [],\n",
    "        'target_CP': [], \n",
    "        'control_GE': [],\n",
    "        'target_GE': []\n",
    "    }\n",
    "    \n",
    "    for i, sample in enumerate(paired_samples):\n",
    "        if i % 10000 == 0:\n",
    "            print(f\"数据收集进度: {i}/{len(paired_samples)}\")\n",
    "            \n",
    "        dataset_dict['canonical_smiles'].append(sample['canonical_smiles'])\n",
    "        dataset_dict['control_CP'].append(CP_data['control'][sample['cp_index']])\n",
    "        dataset_dict['target_CP'].append(CP_data['target'][sample['cp_index']])\n",
    "        dataset_dict['control_GE'].append(GE_data['control'][sample['ge_index']]) \n",
    "        dataset_dict['target_GE'].append(GE_data['target'][sample['ge_index']])\n",
    "    \n",
    "    # 转换为numpy数组并进行数据清洗\n",
    "    final_dataset = {}\n",
    "    final_dataset['canonical_smiles'] = np.array(dataset_dict['canonical_smiles'], dtype='S')\n",
    "    \n",
    "    # 数据清洗函数\n",
    "    def clean_and_validate_data(data_list, name):\n",
    "        data_array = np.array(data_list, dtype=np.float32)\n",
    "        \n",
    "        # 检查NaN和Inf\n",
    "        nan_count = np.isnan(data_array).sum()\n",
    "        inf_count = np.isinf(data_array).sum()\n",
    "        \n",
    "        if nan_count > 0 or inf_count > 0:\n",
    "            print(f\"警告: {name} 包含 {nan_count} NaN 和 {inf_count} Inf\")\n",
    "            data_array = np.nan_to_num(data_array, nan=0.0, posinf=1.0, neginf=-1.0)\n",
    "        \n",
    "        # 数据标准化\n",
    "        mean = data_array.mean()\n",
    "        std = data_array.std()\n",
    "        \n",
    "        print(f\"{name}: 均值={mean:.4f}, 标准差={std:.4f}, 形状={data_array.shape}\")\n",
    "        \n",
    "        return data_array\n",
    "    \n",
    "    final_dataset['control_CP'] = clean_and_validate_data(dataset_dict['control_CP'], 'control_CP')\n",
    "    final_dataset['target_CP'] = clean_and_validate_data(dataset_dict['target_CP'], 'target_CP')\n",
    "    final_dataset['control_GE'] = clean_and_validate_data(dataset_dict['control_GE'], 'control_GE')\n",
    "    final_dataset['target_GE'] = clean_and_validate_data(dataset_dict['target_GE'], 'target_GE')\n",
    "    \n",
    "    # 保存为HDF5\n",
    "    with h5py.File(out_path, 'w') as f:\n",
    "        for key, value in final_dataset.items():\n",
    "            f.create_dataset(key, data=value)\n",
    "    \n",
    "    print(f\"✅ 稳健配对数据集已保存到: {out_path}\")\n",
    "    return final_dataset\n",
    "\n",
    "\n",
    "out_path = './Paired_CP_GE_Dataset.h5'\n",
    "paired_dataset = create_robust_paired_dataset(CP_CSV, GE_CSV, out_path)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "out_path = './Paired_CP_GE_Dataset.h5'\n",
    "\n",
    "agg_data = load_from_HDF(out_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((169287, 775), (169287, 775), (169287, 977), (169287, 977))"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agg_data['control_CP'].shape, agg_data['target_CP'].shape, agg_data['control_GE'].shape, agg_data['target_GE'].shape"
   ]
  },
  {
   "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
}