File size: 91,028 Bytes
9392036
 
ed8f744
913507e
39eafab
6b1f66d
ff7de4b
5498932
b79fb2d
 
d967697
f5f7066
6141903
af68571
6b1f66d
ce05869
706a810
fa0575b
640dcd1
ff7de4b
 
f80e37d
 
706a810
1280fd8
6141903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
640dcd1
71eb50f
f24148c
71eb50f
9392036
1280fd8
9392036
2ee3fae
9392036
 
 
 
f68ccbb
 
 
1280fd8
 
913507e
574aa10
f24148c
6ee3759
574aa10
6ee3759
 
 
757102e
 
 
 
574aa10
6ee3759
f872421
 
529a2e6
89ffe36
529a2e6
 
 
 
 
 
 
 
09537d6
 
6b1f66d
757102e
6b1f66d
757102e
 
 
 
09537d6
757102e
09537d6
757102e
6b1f66d
757102e
 
 
 
09537d6
 
 
 
 
757102e
89ffe36
c300990
 
 
 
 
 
 
09537d6
1af1b88
c300990
 
1af1b88
 
 
6b1f66d
a448d0f
 
6b1f66d
a448d0f
 
 
09537d6
a448d0f
1af1b88
a448d0f
 
6b1f66d
a448d0f
 
 
09537d6
 
 
 
 
757102e
8bcb11e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ac9498
e9d1dec
0ac9498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7affc5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ac9498
89ffe36
 
 
f872421
a448d0f
09537d6
71eb50f
 
 
a448d0f
 
09537d6
 
a448d0f
 
 
 
09537d6
 
 
 
a448d0f
 
71eb50f
 
 
 
 
 
 
 
b79fb2d
 
 
 
 
 
 
 
 
 
 
 
 
 
71eb50f
b79fb2d
71eb50f
 
 
 
 
 
b79fb2d
 
 
 
 
 
 
 
 
 
 
a448d0f
 
 
 
71eb50f
a448d0f
 
71eb50f
b79fb2d
 
a448d0f
 
71eb50f
a448d0f
 
71eb50f
b79fb2d
 
a448d0f
 
b79fb2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a448d0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09537d6
a448d0f
2f05ff8
09537d6
 
a448d0f
 
 
09537d6
 
a448d0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09537d6
 
 
 
 
a448d0f
 
 
 
09537d6
 
6b1f66d
ed8f744
6ee3759
 
 
 
 
ed8f744
 
 
6b1f66d
6ee3759
 
6b1f66d
6ee3759
ed8f744
 
6b1f66d
6ee3759
6b1f66d
ed8f744
6b1f66d
 
 
 
 
 
ed8f744
f872421
757102e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b1f66d
 
 
ed8f744
6b1f66d
d966a8e
757102e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09537d6
 
 
 
 
 
6b1f66d
f541667
6b1f66d
ed8f744
6b1f66d
ed8f744
71eb50f
ed8f744
 
 
b79fb2d
89ffe36
f5f7066
 
6141903
f5f7066
89ffe36
f5e34b2
a448d0f
 
4279043
89ffe36
3139646
71eb50f
3139646
71eb50f
 
 
0598719
 
 
f5f7066
0598719
b79fb2d
 
 
 
71eb50f
 
b79fb2d
f872421
ed8f744
b79fb2d
ce05869
 
b79fb2d
 
ce05869
 
 
 
 
 
 
a448d0f
 
 
 
 
 
 
 
 
 
 
ce05869
a448d0f
 
 
 
 
2f05ff8
b79fb2d
ce05869
 
 
 
 
 
 
 
 
 
 
a448d0f
 
 
ce05869
 
 
 
 
b79fb2d
ce05869
 
b79fb2d
ce05869
2f05ff8
ce05869
 
 
 
 
3139646
a448d0f
 
 
 
 
 
0598719
71eb50f
 
 
a448d0f
3139646
 
 
 
 
a448d0f
640dcd1
 
 
 
 
 
b79fb2d
a448d0f
 
 
 
 
 
 
 
 
ce05869
a448d0f
 
 
 
 
 
b79fb2d
a448d0f
 
 
 
 
 
ce05869
a448d0f
 
 
 
f541667
a685ec6
f24148c
09537d6
529a2e6
 
f24148c
 
 
 
 
 
 
529a2e6
f24148c
f541667
529a2e6
a448d0f
 
a685ec6
 
8b0263d
a685ec6
 
 
 
 
a448d0f
a685ec6
a448d0f
6b1f66d
a448d0f
 
 
 
 
 
 
c300990
a448d0f
b79fb2d
c300990
b79fb2d
 
a448d0f
 
 
 
b79fb2d
f541667
a448d0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b79fb2d
a448d0f
 
 
 
 
 
 
 
0598719
 
71eb50f
0598719
71eb50f
0598719
 
 
b79fb2d
 
 
 
71eb50f
cbe4d30
 
 
 
 
3139646
cbe4d30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0598719
a448d0f
89ffe36
 
d966a8e
ed8f744
f541667
dc8144e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b6c8b4
dc8144e
 
 
 
 
 
 
 
 
8b6c8b4
dc8144e
c300990
af68571
 
 
6b1f66d
af68571
69db70c
af68571
08f9513
 
 
af68571
 
8b6c8b4
c300990
640dcd1
 
c300990
f5f7066
 
6141903
f5f7066
 
 
d967697
640dcd1
 
 
 
 
f5f7066
c300990
 
640dcd1
c300990
 
 
 
 
 
 
640dcd1
c300990
 
 
 
 
 
 
640dcd1
 
cbe4d30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eff2e30
640dcd1
 
 
eff2e30
640dcd1
eff2e30
576d618
 
640dcd1
 
eff2e30
 
640dcd1
eff2e30
 
576d618
640dcd1
 
eff2e30
 
640dcd1
eff2e30
 
576d618
640dcd1
 
eff2e30
 
640dcd1
eff2e30
640dcd1
 
eff2e30
640dcd1
eff2e30
 
 
 
 
 
 
 
 
 
 
 
 
640dcd1
 
eff2e30
640dcd1
 
eff2e30
 
 
 
 
 
 
 
640dcd1
 
 
eff2e30
 
 
 
b94baa7
eff2e30
b94baa7
 
eff2e30
 
 
640dcd1
 
eff2e30
 
 
 
 
b94baa7
 
eff2e30
 
 
 
 
 
640dcd1
8b0263d
2562163
640dcd1
2562163
 
 
 
640dcd1
 
 
 
 
 
 
 
 
2562163
 
 
 
 
 
 
 
 
 
 
 
 
 
640dcd1
 
 
 
 
 
 
 
eff2e30
 
 
 
640dcd1
 
b94baa7
 
 
 
640dcd1
b94baa7
 
 
 
 
 
640dcd1
b94baa7
640dcd1
 
eff2e30
 
 
b94baa7
640dcd1
eff2e30
640dcd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eff2e30
640dcd1
 
 
60b5cc8
ff7de4b
 
 
 
 
 
 
 
b245512
 
 
 
 
 
 
 
640dcd1
b245512
 
 
 
 
640dcd1
b245512
 
 
 
 
 
 
 
 
 
640dcd1
b245512
 
 
 
640dcd1
b245512
 
 
 
 
 
 
 
 
 
 
 
640dcd1
b245512
 
 
 
 
 
 
 
 
640dcd1
b245512
 
 
 
 
 
 
 
 
 
 
 
640dcd1
b245512
 
 
 
 
 
 
 
 
 
640dcd1
 
 
706a810
 
be6cf3a
706a810
 
 
640dcd1
706a810
 
 
 
bfe8480
706a810
 
 
bfe8480
 
706a810
bfe8480
706a810
104fcb7
fa0575b
104fcb7
ff7de4b
104fcb7
0416e62
 
 
706a810
 
 
 
2f91a8e
 
 
 
bfe8480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104fcb7
bfe8480
33f25cc
003c3e3
 
bfe8480
2f91a8e
bfe8480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f91a8e
bfe8480
 
2f91a8e
08ad32f
 
 
bfe8480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f91a8e
bfe8480
 
 
 
 
104fcb7
bfe8480
16e804d
bfe8480
 
 
 
 
 
16e804d
 
bfe8480
 
 
 
 
 
 
 
 
 
 
2f91a8e
bfe8480
2f91a8e
f80e37d
 
f68ccbb
f80e37d
 
f68ccbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f80e37d
 
 
f68ccbb
f80e37d
 
 
 
 
 
 
 
 
 
 
 
 
0838555
1904d0c
 
 
 
 
 
 
 
 
 
 
dc8144e
5289fc1
 
 
 
 
 
 
 
1904d0c
 
 
 
 
 
 
 
 
dc8144e
1904d0c
 
 
dc8144e
1904d0c
dc8144e
1904d0c
 
 
 
 
 
dc8144e
1904d0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a63ffd
1904d0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a63ffd
1904d0c
 
 
8a63ffd
1904d0c
 
 
 
 
 
 
6ff76c2
 
1904d0c
 
 
 
6ff76c2
 
5dd334e
357377d
6ff76c2
 
 
 
 
 
 
 
 
ec6ae3f
6ff76c2
 
357377d
 
 
1904d0c
5dd334e
1904d0c
 
877e0b7
 
1904d0c
 
 
 
 
 
 
 
 
 
 
 
 
f3b063f
 
 
 
554f351
 
 
1904d0c
 
 
 
 
 
f3b063f
1904d0c
 
 
 
 
 
f3b063f
1904d0c
 
ed9740d
1904d0c
 
ed9740d
1904d0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08ad32f
 
 
1904d0c
 
 
 
 
 
 
8a63ffd
1904d0c
 
f7e3ef0
 
 
 
 
 
 
 
 
 
 
 
 
1904d0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a63ffd
1904d0c
 
 
 
 
 
 
dc8144e
c300990
89ffe36
 
8bcb11e
89ffe36
69db70c
89ffe36
 
69db70c
89ffe36
0ac9498
8bcb11e
 
 
0ac9498
 
8bcb11e
7affc5d
 
6ee3759
 
f648357
 
 
 
 
ce01d7e
 
 
 
635ca44
cf4a9c9
7ec5586
ce01d7e
f648357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a873688
ce01d7e
 
60b5cc8
 
 
 
f648357
c300990
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
import streamlit as st
import pandas as pd
import numpy as np
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, DataTable, TableColumn, CustomJS, Select, Button, HoverTool, LinearColorMapper, ColorBar, FuncTickFormatter, FixedTicker
from bokeh.layouts import column
from bokeh.palettes import Reds9, Blues9, Oranges9, Purples9, Greys9, BuGn9, Greens9, RdYlGn11, linear_palette
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness
from sklearn.metrics import pairwise_distances
from sklearn.preprocessing import MinMaxScaler
from sklearn.pipeline import Pipeline
from sklearn.base import BaseEstimator, TransformerMixin
import io
import ot
from sklearn.linear_model import LinearRegression
from scipy.stats import binned_statistic_2d
import json
import itertools
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import zipfile
import tempfile


class RelativeScaler(BaseEstimator, TransformerMixin):
    """
    Escala la primera columna al rango [-1, 1] y ajusta las siguientes columnas
    manteniendo la proporción relativa respecto a la primera.
    """
    
    def fit(self, X, y=None):
        X = np.asarray(X)
        self.pc1_min_ = X[:, 0].min()
        self.pc1_max_ = X[:, 0].max()
        self.scaling_factor_ = (self.pc1_max_ - self.pc1_min_) / 2
        return self

    def transform(self, X):
        X = np.asarray(X)
        pc1 = X[:, 0]
        pc1_scaled = 2 * (pc1 - self.pc1_min_) / (self.pc1_max_ - self.pc1_min_) - 1
        
        transformed = [pc1_scaled.reshape(-1, 1)]
        
        for i in range(1, X.shape[1]):
            scaled_i = X[:, i] / self.scaling_factor_
            transformed.append(scaled_i.reshape(-1, 1))
        
        return np.hstack(transformed)

N_COMPONENTS = 3
TSNE_NEIGHBOURS = 150
# WEIGHT_FACTOR = 0.05

TOOLTIPS = """
<div>
    <div>
        <img src="@img{safe}" style="width:128px; height:auto; float: left; margin: 0px 15px 15px 0px;" alt="@img" border="2"></img>
    </div>
    <div>
        <span style="font-size: 17px; font-weight: bold;">@label</span>
    </div>
    <div>
        <span style="font-size: 14px;">X: @x, Y: @y</span>
    </div>
</div>
"""

def config_style():
    # st.set_page_config(layout="wide")
    st.markdown("""
        <style>
        .main-title { font-size: 50px; color: #4CAF50; text-align: center; }
        .sub-title { font-size: 30px; color: #555; }
        .custom-text { font-size: 18px; line-height: 1.5; }
        .bk-legend {
            max-height: 200px;
            overflow-y: auto;
        }
        </style>
    """, unsafe_allow_html=True)
    st.markdown('<h1 class="main-title">Merit Embeddings 🎒📃🏆</h1>', unsafe_allow_html=True)

def load_embeddings(model, version, embedding_prefix, weight_factor):
    if model == "Donut":
        df_real = pd.read_csv(f"data/donut/{version}/{embedding_prefix}/de_Rodrigo_merit_secret_all_{weight_factor}embeddings.csv")
        df_par = pd.read_csv(f"data/donut/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-paragraph-degradation-seq_{weight_factor}embeddings.csv")
        df_line = pd.read_csv(f"data/donut/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-line-degradation-seq_{weight_factor}embeddings.csv")
        df_seq  = pd.read_csv(f"data/donut/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-seq_{weight_factor}embeddings.csv")
        df_rot  = pd.read_csv(f"data/donut/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-rotation-degradation-seq_{weight_factor}embeddings.csv")
        df_zoom = pd.read_csv(f"data/donut/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-zoom-degradation-seq_{weight_factor}embeddings.csv")
        df_render = pd.read_csv(f"data/donut/{version}/{embedding_prefix}/de_Rodrigo_merit_es-render-seq_{weight_factor}embeddings.csv")
        df_pretratrained = pd.read_csv(f"data/donut/{version}/{embedding_prefix}/de_Rodrigo_merit_aux_IIT-CDIP_{weight_factor}embeddings.csv")
        
        # Asignar etiquetas de versión
        df_real["version"] = "real"
        df_par["version"] = "synthetic"
        df_line["version"] = "synthetic"
        df_seq["version"] = "synthetic"
        df_rot["version"] = "synthetic"
        df_zoom["version"] = "synthetic"
        df_render["version"] = "synthetic"
        df_pretratrained["version"] = "pretrained"

        # Asignar fuente (source)
        df_par["source"] = "es-digital-paragraph-degradation-seq"
        df_line["source"] = "es-digital-line-degradation-seq"
        df_seq["source"] = "es-digital-seq"
        df_rot["source"] = "es-digital-rotation-degradation-seq"
        df_zoom["source"] = "es-digital-zoom-degradation-seq"
        df_render["source"] = "es-render-seq"
        df_pretratrained["source"] = "pretrained"

        return {"real": df_real, 
                "synthetic": pd.concat([df_seq, df_line, df_par, df_rot, df_zoom, df_render], ignore_index=True),
                "pretrained": df_pretratrained}
    
    elif model == "Idefics2":
        df_real = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_secret_britanico_{weight_factor}embeddings.csv")
        df_par = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-paragraph-degradation-seq_{weight_factor}embeddings.csv")
        df_line = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-line-degradation-seq_{weight_factor}embeddings.csv")
        df_seq  = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-seq_{weight_factor}embeddings.csv")
        df_rot  = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-rotation-degradation-seq_{weight_factor}embeddings.csv")
        df_zoom = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-zoom-degradation-seq_{weight_factor}embeddings.csv")
        df_render = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-render-seq_{weight_factor}embeddings.csv")
        
        # Cargar ambos subconjuntos pretrained y combinarlos
        df_pretratrained_PDFA = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_aux_PDFA_{weight_factor}embeddings.csv")
        df_pretratrained_IDL = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_aux_IDL_{weight_factor}embeddings.csv")
        df_pretratrained = pd.concat([df_pretratrained_PDFA, df_pretratrained_IDL], ignore_index=True)
        
        # Asignar etiquetas de versión
        df_real["version"] = "real"
        df_par["version"] = "synthetic"
        df_line["version"] = "synthetic"
        df_seq["version"] = "synthetic"
        df_rot["version"] = "synthetic"
        df_zoom["version"] = "synthetic"
        df_render["version"] = "synthetic"
        df_pretratrained["version"] = "pretrained"

        # Asignar fuente (source)
        df_par["source"] = "es-digital-paragraph-degradation-seq"
        df_line["source"] = "es-digital-line-degradation-seq"
        df_seq["source"] = "es-digital-seq"
        df_rot["source"] = "es-digital-rotation-degradation-seq"
        df_zoom["source"] = "es-digital-zoom-degradation-seq"
        df_render["source"] = "es-render-seq"
        df_pretratrained["source"] = "pretrained"

        return {"real": df_real, 
                "synthetic": pd.concat([df_seq, df_line, df_par, df_rot, df_zoom, df_render], ignore_index=True),
                "pretrained": df_pretratrained}
    
    elif model == "Idefics2-patient":
        df_real = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_secret_britanico_{weight_factor}embeddings.csv")
        df_par = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-paragraph-degradation-seq_{weight_factor}embeddings.csv")
        df_line = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-line-degradation-seq_{weight_factor}embeddings.csv")
        df_seq  = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-seq_{weight_factor}embeddings.csv")
        df_rot  = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-rotation-degradation-seq_{weight_factor}embeddings.csv")
        df_zoom = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-zoom-degradation-seq_{weight_factor}embeddings.csv")
        df_render = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_es-render-seq_{weight_factor}embeddings.csv")
        
        # Cargar ambos subconjuntos pretrained y combinarlos
        df_pretratrained_PDFA = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_aux_PDFA_{weight_factor}embeddings.csv")
        df_pretratrained_IDL = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_aux_IDL_{weight_factor}embeddings.csv")
        df_pretratrained = pd.concat([df_pretratrained_PDFA, df_pretratrained_IDL], ignore_index=True)
        
        # Asignar etiquetas de versión
        df_real["version"] = "real"
        df_par["version"] = "synthetic"
        df_line["version"] = "synthetic"
        df_seq["version"] = "synthetic"
        df_rot["version"] = "synthetic"
        df_zoom["version"] = "synthetic"
        df_render["version"] = "synthetic"
        df_pretratrained["version"] = "pretrained"

        # Asignar fuente (source)
        df_par["source"] = "es-digital-paragraph-degradation-seq"
        df_line["source"] = "es-digital-line-degradation-seq"
        df_seq["source"] = "es-digital-seq"
        df_rot["source"] = "es-digital-rotation-degradation-seq"
        df_zoom["source"] = "es-digital-zoom-degradation-seq"
        df_render["source"] = "es-render-seq"
        df_pretratrained["source"] = "pretrained"

        return {"real": df_real, 
                "synthetic": pd.concat([df_seq, df_line, df_par, df_rot, df_zoom, df_render], ignore_index=True),
                "pretrained": df_pretratrained}
    
    elif model == "Paligemma":
        df_real = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_secret_all_{weight_factor}embeddings.csv")
        df_par = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-paragraph-degradation-seq_{weight_factor}embeddings.csv")
        df_line = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-line-degradation-seq_{weight_factor}embeddings.csv")
        df_seq  = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-seq_{weight_factor}embeddings.csv")
        df_rot  = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-rotation-degradation-seq_{weight_factor}embeddings.csv")
        df_zoom = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-zoom-degradation-seq_{weight_factor}embeddings.csv")
        df_render = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-render-seq_{weight_factor}embeddings.csv")
        
        # Cargar ambos subconjuntos pretrained y combinarlos
        # TODO Pretrained de idefics2, se mantienen para evitar error, pero se debe meter los de paligemma
        df_pretratrained_PDFA = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_aux_PDFA_{weight_factor}embeddings.csv")
        df_pretratrained_IDL = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_aux_IDL_{weight_factor}embeddings.csv")
        df_pretratrained = pd.concat([df_pretratrained_PDFA, df_pretratrained_IDL], ignore_index=True)
        
        # Asignar etiquetas de versión
        df_real["version"] = "real"
        df_par["version"] = "synthetic"
        df_line["version"] = "synthetic"
        df_seq["version"] = "synthetic"
        df_rot["version"] = "synthetic"
        df_zoom["version"] = "synthetic"
        df_render["version"] = "synthetic"
        df_pretratrained["version"] = "pretrained"

        # Asignar fuente (source)
        df_par["source"] = "es-digital-paragraph-degradation-seq"
        df_line["source"] = "es-digital-line-degradation-seq"
        df_seq["source"] = "es-digital-seq"
        df_rot["source"] = "es-digital-rotation-degradation-seq"
        df_zoom["source"] = "es-digital-zoom-degradation-seq"
        df_render["source"] = "es-render-seq"
        df_pretratrained["source"] = "pretrained"

        return {"real": df_real, 
                "synthetic": pd.concat([df_seq, df_line, df_par, df_rot, df_zoom, df_render], ignore_index=True),
                "pretrained": df_pretratrained}
    
    elif model == "Llava":
        df_real = pd.read_csv(f"data/llava/{version}/{embedding_prefix}/de_Rodrigo_merit_secret_all_{weight_factor}embeddings.csv")
        #TODO Embeddings de Paligemma se mantienen para evitar error
        df_par = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-paragraph-degradation-seq_{weight_factor}embeddings.csv")
        df_line = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-line-degradation-seq_{weight_factor}embeddings.csv")
        df_seq  = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-seq_{weight_factor}embeddings.csv")
        df_rot  = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-rotation-degradation-seq_{weight_factor}embeddings.csv")
        df_zoom = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-digital-zoom-degradation-seq_{weight_factor}embeddings.csv")
        df_render = pd.read_csv(f"data/paligemma/{version}/{embedding_prefix}/de_Rodrigo_merit_es-render-seq_{weight_factor}embeddings.csv")
        
        # Cargar ambos subconjuntos pretrained y combinarlos
        # TODO Pretrained de idefics2, se mantienen para evitar error, pero se debe meter los de paligemma
        df_pretratrained_PDFA = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_aux_PDFA_{weight_factor}embeddings.csv")
        df_pretratrained_IDL = pd.read_csv(f"data/idefics2/{version}/{embedding_prefix}/de_Rodrigo_merit_aux_IDL_{weight_factor}embeddings.csv")
        df_pretratrained = pd.concat([df_pretratrained_PDFA, df_pretratrained_IDL], ignore_index=True)
        
        # Asignar etiquetas de versión
        df_real["version"] = "real"
        df_par["version"] = "synthetic"
        df_line["version"] = "synthetic"
        df_seq["version"] = "synthetic"
        df_rot["version"] = "synthetic"
        df_zoom["version"] = "synthetic"
        df_render["version"] = "synthetic"
        df_pretratrained["version"] = "pretrained"

        # Asignar fuente (source)
        df_par["source"] = "es-digital-paragraph-degradation-seq"
        df_line["source"] = "es-digital-line-degradation-seq"
        df_seq["source"] = "es-digital-seq"
        df_rot["source"] = "es-digital-rotation-degradation-seq"
        df_zoom["source"] = "es-digital-zoom-degradation-seq"
        df_render["source"] = "es-render-seq"
        df_pretratrained["source"] = "pretrained"

        return {"real": df_real, 
                "synthetic": pd.concat([df_seq, df_line, df_par, df_rot, df_zoom, df_render], ignore_index=True),
                "pretrained": df_pretratrained}
    
    
    else:
        st.error("Modelo no reconocido")
        return None

def split_versions(df_combined, reduced):
    # Asignar las coordenadas si la reducción es 2D
    if reduced.shape[1] == 2:
        df_combined['x'] = reduced[:, 0]
        df_combined['y'] = reduced[:, 1]
    df_real = df_combined[df_combined["version"] == "real"].copy()
    df_synth = df_combined[df_combined["version"] == "synthetic"].copy()
    df_pretrained = df_combined[df_combined["version"] == "pretrained"].copy()
    
    unique_real = sorted(df_real['label'].unique().tolist())
    unique_synth = {}
    for source in df_synth["source"].unique():
        unique_synth[source] = sorted(df_synth[df_synth["source"] == source]['label'].unique().tolist())
    unique_pretrained = sorted(df_pretrained['label'].unique().tolist())
    
    df_dict = {"real": df_real, "synthetic": df_synth, "pretrained": df_pretrained}
    unique_subsets = {"real": unique_real, "synthetic": unique_synth, "pretrained": unique_pretrained}
    return df_dict, unique_subsets

def get_embedding_from_df(df):
    # Retorna el embedding completo (4 dimensiones en este caso) guardado en la columna 'embedding'
    if 'embedding' in df.columns:
        return np.stack(df['embedding'].to_numpy())
    elif 'x' in df.columns and 'y' in df.columns:
        return df[['x', 'y']].values
    else:
        raise ValueError("No se encontró embedding o coordenadas x,y en el DataFrame.")

def compute_cluster_distance(synthetic_points, real_points, metric="wasserstein", bins=20):
    if metric.lower() == "wasserstein":
        n = synthetic_points.shape[0]
        m = real_points.shape[0]
        weights = np.ones(n) / n
        weights_real = np.ones(m) / m
        M = ot.dist(synthetic_points, real_points, metric='euclidean')
        return ot.emd2(weights, weights_real, M)
    elif metric.lower() == "euclidean":
        center_syn = np.mean(synthetic_points, axis=0)
        center_real = np.mean(real_points, axis=0)
        return np.linalg.norm(center_syn - center_real)
    elif metric.lower() == "kl":
        # Para KL usamos histogramas multidimensionales con límites globales en cada dimensión
        all_points = np.vstack([synthetic_points, real_points])
        edges = [
            np.linspace(np.min(all_points[:, i]), np.max(all_points[:, i]), bins+1)
            for i in range(all_points.shape[1])
        ]
        H_syn, _ = np.histogramdd(synthetic_points, bins=edges)
        H_real, _ = np.histogramdd(real_points, bins=edges)
        eps = 1e-10
        P = H_syn + eps
        Q = H_real + eps
        P = P / P.sum()
        Q = Q / Q.sum()
        kl = np.sum(P * np.log(P / Q))
        return kl
    else:
        raise ValueError("Métrica desconocida. Usa 'wasserstein', 'euclidean' o 'kl'.")

def compute_cluster_distances_synthetic_individual(synthetic_df: pd.DataFrame, df_real: pd.DataFrame, real_labels: list, metric="wasserstein", bins=20) -> pd.DataFrame:
    distances = {}
    groups = synthetic_df.groupby(['source', 'label'])
    for (source, label), group in groups:
        key = f"{label} ({source})"
        data = get_embedding_from_df(group)
        distances[key] = {}
        for real_label in real_labels:
            real_data = get_embedding_from_df(df_real[df_real['label'] == real_label])
            d = compute_cluster_distance(data, real_data, metric=metric, bins=bins)
            distances[key][real_label] = d
    for source, group in synthetic_df.groupby('source'):
        key = f"Global ({source})"
        data = get_embedding_from_df(group)
        distances[key] = {}
        for real_label in real_labels:
            real_data = get_embedding_from_df(df_real[df_real['label'] == real_label])
            d = compute_cluster_distance(data, real_data, metric=metric, bins=bins)
            distances[key][real_label] = d
    return pd.DataFrame(distances).T

def compute_continuity(X, X_embedded, n_neighbors=5):
    n = X.shape[0]
    D_high = pairwise_distances(X, metric='euclidean')
    D_low = pairwise_distances(X_embedded, metric='euclidean')
    indices_high = np.argsort(D_high, axis=1)
    indices_low = np.argsort(D_low, axis=1)
    k_high = indices_high[:, 1:n_neighbors+1]
    k_low = indices_low[:, 1:n_neighbors+1]
    total = 0.0
    for i in range(n):
        set_high = set(k_high[i])
        set_low = set(k_low[i])
        missing = set_high - set_low
        for j in missing:
            rank = np.where(indices_low[i] == j)[0][0]
            total += (rank - n_neighbors)
    norm = 2.0 / (n * n_neighbors * (2*n - 3*n_neighbors - 1))
    continuity_value = 1 - norm * total
    return continuity_value

def create_table(df_distances):
    df_table = df_distances.copy()
    df_table.reset_index(inplace=True)
    df_table.rename(columns={'index': 'Synthetic'}, inplace=True)
    min_row = {"Synthetic": "Min."}
    mean_row = {"Synthetic": "Mean"}
    max_row = {"Synthetic": "Max."}
    for col in df_table.columns:
        if col != "Synthetic":
            min_row[col] = df_table[col].min()
            mean_row[col] = df_table[col].mean()
            max_row[col] = df_table[col].max()
    df_table = pd.concat([df_table, pd.DataFrame([min_row, mean_row, max_row])], ignore_index=True)
    source_table = ColumnDataSource(df_table)
    columns = [TableColumn(field='Synthetic', title='Synthetic')]
    for col in df_table.columns:
        if col != 'Synthetic':
            columns.append(TableColumn(field=col, title=col))
    total_height = 30 + len(df_table)*28
    data_table = DataTable(source=source_table, columns=columns, sizing_mode='stretch_width', height=total_height)
    return data_table, df_table, source_table

def create_figure(dfs, unique_subsets, color_maps, model_name):
    # Se crea el plot para el embedding reducido (asumiendo que es 2D)
    fig = figure(width=600, height=600, tools="wheel_zoom,pan,reset,save", active_scroll="wheel_zoom", tooltips=TOOLTIPS, title="")
    fig.match_aspect = True
    
    # Renderizar datos reales
    real_renderers = add_dataset_to_fig(fig, dfs["real"], unique_subsets["real"],
                                        marker="circle", color_mapping=color_maps["real"],
                                        group_label="Real")
    
    # Renderizar datos sintéticos (por fuente)
    marker_mapping = {
        "es-digital-paragraph-degradation-seq": "x",
        "es-digital-line-degradation-seq": "cross",
        "es-digital-seq": "triangle",
        "es-digital-rotation-degradation-seq": "diamond",
        "es-digital-zoom-degradation-seq": "asterisk",
        "es-render-seq": "inverted_triangle"
    }
    synthetic_renderers = {}
    synth_df = dfs["synthetic"]
    for source in unique_subsets["synthetic"]:
        df_source = synth_df[synth_df["source"] == source]
        marker = marker_mapping.get(source, "square")
        renderers = add_synthetic_dataset_to_fig(fig, df_source, unique_subsets["synthetic"][source],
                                                  marker=marker,
                                                  color_mapping=color_maps["synthetic"][source],
                                                  group_label=source)
        synthetic_renderers.update(renderers)
    
    # Agregar el subset pretrained (se puede usar un marcador distinto, por ejemplo, "triangle")
    pretrained_renderers = add_dataset_to_fig(fig, dfs["pretrained"], unique_subsets["pretrained"],
                                               marker="triangle", color_mapping=color_maps["pretrained"],
                                               group_label="Pretrained")
    
    fig.legend.location = "top_right"
    fig.legend.click_policy = "hide"
    show_legend = st.checkbox("Show Legend", value=False, key=f"legend_{model_name}")
    fig.legend.visible = show_legend
    return fig, real_renderers, synthetic_renderers, pretrained_renderers

def add_dataset_to_fig(fig, df, selected_labels, marker, color_mapping, group_label):
    renderers = {}
    for label in selected_labels:
        subset = df[df['label'] == label]
        if subset.empty:
            continue
        source = ColumnDataSource(data=dict(
            x=subset['x'],
            y=subset['y'],
            label=subset['label'],
            img=subset.get('img', "")
        ))
        color = color_mapping[label]
        legend_label = f"{label} ({group_label})"
        if marker == "circle":
            r = fig.circle('x', 'y', size=10, source=source,
                           fill_color=color, line_color=color,
                           legend_label=legend_label)
        elif marker == "square":
            r = fig.square('x', 'y', size=10, source=source,
                           fill_color=color, line_color=color,
                           legend_label=legend_label)
        elif marker == "triangle":
            r = fig.triangle('x', 'y', size=12, source=source,
                             fill_color=color, line_color=color,
                             legend_label=legend_label)
        renderers[label + f" ({group_label})"] = r
    return renderers

def add_synthetic_dataset_to_fig(fig, df, labels, marker, color_mapping, group_label):
    renderers = {}
    for label in labels:
        subset = df[df['label'] == label]
        if subset.empty:
            continue
        source_obj = ColumnDataSource(data=dict(
            x=subset['x'],
            y=subset['y'],
            label=subset['label'],
            img=subset.get('img', "")
        ))
        color = color_mapping[label]
        legend_label = group_label
        if marker == "square":
            r = fig.square('x', 'y', size=10, source=source_obj,
                           fill_color=color, line_color=color,
                           legend_label=legend_label)
        elif marker == "triangle":
            r = fig.triangle('x', 'y', size=12, source=source_obj,
                             fill_color=color, line_color=color,
                             legend_label=legend_label)
        elif marker == "inverted_triangle":
            r = fig.inverted_triangle('x', 'y', size=12, source=source_obj,
                                      fill_color=color, line_color=color,
                                      legend_label=legend_label)
        elif marker == "diamond":
            r = fig.diamond('x', 'y', size=10, source=source_obj,
                            fill_color=color, line_color=color,
                            legend_label=legend_label)
        elif marker == "cross":
            r = fig.cross('x', 'y', size=12, source=source_obj,
                          fill_color=color, line_color=color,
                          legend_label=legend_label)
        elif marker == "x":
            r = fig.x('x', 'y', size=12, source=source_obj,
                      fill_color=color, line_color=color,
                      legend_label=legend_label)
        elif marker == "asterisk":
            r = fig.asterisk('x', 'y', size=12, source=source_obj,
                             fill_color=color, line_color=color,
                             legend_label=legend_label)
        else:
            r = fig.circle('x', 'y', size=10, source=source_obj,
                           fill_color=color, line_color=color,
                           legend_label=legend_label)
        renderers[label + f" ({group_label})"] = r
    return renderers

def get_color_maps(unique_subsets):
    color_map = {}
    num_real = len(unique_subsets["real"])
    red_palette = Reds9[:num_real] if num_real <= 9 else (Reds9 * ((num_real // 9) + 1))[:num_real]
    color_map["real"] = {label: red_palette[i] for i, label in enumerate(sorted(unique_subsets["real"]))}
    
    color_map["synthetic"] = {}
    for source, labels in unique_subsets["synthetic"].items():
        if source == "es-digital-seq":
            palette = Blues9[:len(labels)] if len(labels) <= 9 else (Blues9 * ((len(labels)//9)+1))[:len(labels)]
        elif source == "es-digital-line-degradation-seq":
            palette = Purples9[:len(labels)] if len(labels) <= 9 else (Purples9 * ((len(labels)//9)+1))[:len(labels)]
        elif source == "es-digital-paragraph-degradation-seq":
            palette = BuGn9[:len(labels)] if len(labels) <= 9 else (BuGn9 * ((len(labels)//9)+1))[:len(labels)]
        elif source == "es-digital-rotation-degradation-seq":
            palette = Greys9[:len(labels)] if len(labels) <= 9 else (Greys9 * ((len(labels)//9)+1))[:len(labels)]
        elif source == "es-digital-zoom-degradation-seq":
            palette = Oranges9[:len(labels)] if len(labels) <= 9 else (Oranges9 * ((len(labels)//9)+1))[:len(labels)]
        elif source == "es-render-seq":
            palette = Greens9[:len(labels)] if len(labels) <= 9 else (Greens9 * ((len(labels)//9)+1))[:len(labels)]
        else:
            palette = Blues9[:len(labels)] if len(labels) <= 9 else (Blues9 * ((len(labels)//9)+1))[:len(labels)]
        color_map["synthetic"][source] = {label: palette[i] for i, label in enumerate(sorted(labels))}
    
    # Asignar colores al subset pretrained usando, por ejemplo, la paleta Purples9
    num_pretrained = len(unique_subsets["pretrained"])
    purple_palette = Purples9[:num_pretrained] if num_pretrained <= 9 else (Purples9 * ((num_pretrained // 9) + 1))[:num_pretrained]
    color_map["pretrained"] = {label: purple_palette[i] for i, label in enumerate(sorted(unique_subsets["pretrained"]))}
    
    return color_map

def calculate_cluster_centers(df, labels):
    centers = {}
    for label in labels:
        subset = df[df['label'] == label]
        if not subset.empty and 'x' in subset.columns and 'y' in subset.columns:
            centers[label] = (subset['x'].mean(), subset['y'].mean())
    return centers

def compute_global_regression(df_combined, embedding_cols, tsne_params, df_f1, reduction_method="t-SNE", distance_metric="wasserstein"):
    if reduction_method == "PCA":
        reducer = Pipeline([
            ("pca", PCA(n_components=N_COMPONENTS)),
            ("rel_scaler", RelativeScaler())
        ])
    else:
        reducer = TSNE(n_components=2, random_state=42, 
                         perplexity=tsne_params["perplexity"], 
                         learning_rate=tsne_params["learning_rate"])
    
    reduced = reducer.fit_transform(df_combined[embedding_cols].values)
    # Guardamos el embedding completo (por ejemplo, 4 dimensiones en PCA)
    df_combined['embedding'] = list(reduced)
    # Si el embedding es 2D, asignamos x e y para visualización
    if reduced.shape[1] == 2:
        df_combined['x'] = reduced[:, 0]
        df_combined['y'] = reduced[:, 1]
    
    explained_variance = None
    if reduction_method == "PCA":
        explained_variance = reducer.named_steps["pca"].explained_variance_ratio_
    
    trust = None
    cont = None
    if reduction_method == "t-SNE":
        X = df_combined[embedding_cols].values
        trust = trustworthiness(X, reduced, n_neighbors=TSNE_NEIGHBOURS)
        cont = compute_continuity(X, reduced, n_neighbors=TSNE_NEIGHBOURS)
    
    dfs_reduced, unique_subsets = split_versions(df_combined, reduced)
    
    df_distances = compute_cluster_distances_synthetic_individual(
        dfs_reduced["synthetic"],
        dfs_reduced["real"],
        unique_subsets["real"],
        metric=distance_metric
    )
    
    global_distances = {}
    for idx in df_distances.index:
        if idx.startswith("Global"):
            source = idx.split("(")[1].rstrip(")")
            global_distances[source] = df_distances.loc[idx].values
            
    all_x = []
    all_y = []
    for source in df_f1.columns:
        if source in global_distances:
            x_vals = global_distances[source]
            y_vals = df_f1[source].values
            all_x.extend(x_vals)
            all_y.extend(y_vals)
    all_x_arr = np.array(all_x).reshape(-1, 1)
    all_y_arr = np.array(all_y)
    
    model_global = LinearRegression().fit(all_x_arr, all_y_arr)
    r2 = model_global.score(all_x_arr, all_y_arr)
    slope = model_global.coef_[0]
    intercept = model_global.intercept_
    
    scatter_fig = figure(width=600, height=600, tools="pan,wheel_zoom,reset,save", y_range=(0, 1), 
                         title="Scatter Plot: Distance vs F1")
    source_colors = {
        "es-digital-paragraph-degradation-seq": "blue",
        "es-digital-line-degradation-seq": "green",
        "es-digital-seq": "red",
        "es-digital-zoom-degradation-seq": "orange",
        "es-digital-rotation-degradation-seq": "purple",
        "es-digital-rotation-zoom-degradation-seq": "brown",
        "es-render-seq": "cyan"
    }
    for source in df_f1.columns:
        if source in global_distances:
            x_vals = global_distances[source]
            y_vals = df_f1[source].values
            data = {"x": x_vals, "y": y_vals, "Fuente": [source]*len(x_vals)}
            cds = ColumnDataSource(data=data)
            scatter_fig.circle('x', 'y', size=8, alpha=0.7, source=cds,
                               fill_color=source_colors.get(source, "gray"),
                               line_color=source_colors.get(source, "gray"),
                               legend_label=source)
    scatter_fig.xaxis.axis_label = "Distance (Global, por Colegio)"
    scatter_fig.yaxis.axis_label = "F1 Score"
    scatter_fig.legend.location = "top_right"
    hover_tool = HoverTool(tooltips=[("Distance", "@x"), ("F1", "@y"), ("Subset", "@Fuente")])
    scatter_fig.add_tools(hover_tool)
    # scatter_fig.match_aspect = True
    
    x_line = np.linspace(all_x_arr.min(), all_x_arr.max(), 100)
    y_line = model_global.predict(x_line.reshape(-1, 1))
    scatter_fig.line(x_line, y_line, line_width=2, line_color="black", legend_label="Global Regression")
    
    results = {
        "R2": r2,
        "slope": slope,
        "intercept": intercept,
        "scatter_fig": scatter_fig,
        "dfs_reduced": dfs_reduced,
        "unique_subsets": unique_subsets,
        "df_distances": df_distances,
        "explained_variance": explained_variance,
        "trustworthiness": trust,
        "continuity": cont
    }
    
    if reduction_method == "PCA":
        results["pca_model"] = reducer  # Agregamos el objeto PCA para usarlo luego en los plots
    
    return results

# def get_color(color_entry):
#     if isinstance(color_entry, dict):
#         # Extrae el primer valor (o ajusta según convenga)
#         return list(color_entry.values())[0]
#     return color_entry

def optimize_tsne_params(df_combined, embedding_cols, df_f1, distance_metric):
    perplexity_range = np.linspace(30, 50, 10)
    learning_rate_range = np.linspace(200, 1000, 20)
    
    best_R2 = -np.inf
    best_params = None
    total_steps = len(perplexity_range) * len(learning_rate_range)
    step = 0

    progress_text = st.empty()
    
    for p in perplexity_range:
        for lr in learning_rate_range:
            step += 1
            progress_text.text(f"Evaluating: Perplexity={p:.2f}, Learning Rate={lr:.2f} (Step {step}/{total_steps})")
            
            tsne_params = {"perplexity": p, "learning_rate": lr}
            result = compute_global_regression(df_combined, embedding_cols, tsne_params, df_f1, reduction_method="t-SNE", distance_metric=distance_metric)
            r2_temp = result["R2"]
            st.write(f"Parameters: Perplexity={p:.2f}, Learning Rate={lr:.2f} -> R²={r2_temp:.4f}")
            
            if r2_temp > best_R2:
                best_R2 = r2_temp
                best_params = (p, lr)
    
    progress_text.text("Optimization completed!")
    return best_params, best_R2

def run_model(model_name):
    version = st.selectbox("Select Model Version:", options=["vanilla", "finetuned_real"], key=f"version_{model_name}")
    # Selector para el método de cómputo del embedding
    embedding_computation = st.selectbox("¿Cómo se computa el embedding?", options=["averaged", "weighted"], key=f"embedding_method_{model_name}")
    # Se asigna el prefijo correspondiente

    if embedding_computation == "weighted":
         selected_weight_factor = st.selectbox(
             "Seleccione el Weight Factor", 
             options=[0.05, 0.1, 0.25, 0.5], 
             index=0,  # índice 1 para que por defecto sea 0.05
             key=f"weight_factor_{model_name}"
         )
         weight_factor = f"{selected_weight_factor}_"
    else:
         weight_factor = ""
    
    embeddings = load_embeddings(model_name, version, embedding_computation, weight_factor)
    if embeddings is None:
        return

    # Nuevo selector para incluir o excluir el dataset pretrained
    include_pretrained = st.checkbox("Incluir dataset pretrained", value=False, key=f"legend_{model_name}_pretrained")
    if not include_pretrained:
        # Removemos la entrada pretrained del diccionario, si existe.
        embeddings.pop("pretrained", None)
    
    # Extraer columnas de embedding de los datos "real"
    embedding_cols = [col for col in embeddings["real"].columns if col.startswith("dim_")]
    # Concatenamos los datasets disponibles (ahora, sin pretrained si se deseleccionó)
    df_combined = pd.concat(list(embeddings.values()), ignore_index=True)
    
    try:
        df_f1 = pd.read_csv("data/f1-donut.csv", sep=';', index_col=0)
    except Exception as e:
        st.error(f"Error loading f1-donut.csv: {e}")
        return

    st.markdown('<h6 class="sub-title">Select Dimensionality Reduction Method</h6>', unsafe_allow_html=True)
    reduction_method = st.selectbox("", options=["PCA", "t-SNE"], key=f"reduction_{model_name}")
    
    distance_metric = st.selectbox("Select Distance Metric:", 
                                   options=["Euclidean", "Wasserstein", "KL"], 
                                   key=f"distance_metric_{model_name}")
    
    tsne_params = {}
    if reduction_method == "t-SNE":
        if st.button("Optimize TSNE parameters", key=f"optimize_tsne_{model_name}"):
            st.info("Running optimization, this can take a while...")
            best_params, best_R2 = optimize_tsne_params(df_combined, embedding_cols, df_f1, distance_metric.lower())
            st.success(f"Best parameters: Perplexity = {best_params[0]:.2f}, Learning Rate = {best_params[1]:.2f} with R² = {best_R2:.4f}")
            tsne_params = {"perplexity": best_params[0], "learning_rate": best_params[1]}
        else:
            perplexity_val = st.number_input(
                "Perplexity", 
                min_value=5.0, 
                max_value=50.0, 
                value=30.0, 
                step=1.0, 
                format="%.2f",
                key=f"perplexity_{model_name}"
            )
            learning_rate_val = st.number_input(
                "Learning Rate", 
                min_value=10.0, 
                max_value=1000.0, 
                value=200.0, 
                step=10.0, 
                format="%.2f",
                key=f"learning_rate_{model_name}"
            )
            tsne_params = {"perplexity": perplexity_val, "learning_rate": learning_rate_val}
    
    result = compute_global_regression(df_combined, embedding_cols, tsne_params, df_f1, reduction_method=reduction_method, distance_metric=distance_metric.lower())
    
    reg_metrics = pd.DataFrame({
        "Slope": [result["slope"]],
        "Intercept": [result["intercept"]],
        "R2": [result["R2"]]
    })
    st.table(reg_metrics)
    
    if reduction_method == "PCA" and result["explained_variance"] is not None:
        st.subheader("Explained Variance Ratio")
        component_names = [f"PC{i+1}" for i in range(len(result["explained_variance"]))]
        variance_df = pd.DataFrame({
            "Component": component_names,
            "Explained Variance": result["explained_variance"]
        })
        st.table(variance_df)
    elif reduction_method == "t-SNE":
        st.subheader("t-SNE Quality Metrics")
        st.write(f"Trustworthiness: {result['trustworthiness']:.4f}")
        st.write(f"Continuity: {result['continuity']:.4f}")

    # # Mostrar los plots de loadings si se usó PCA (para el conjunto combinado)
    # if reduction_method == "PCA" and result.get("pca_model") is not None:
    #     # pca_model = result["pca_model"]
    #     pca_model = result["pca_model"].named_steps["pca"]
    #     components = pca_model.components_  # Shape: (n_components, n_features)
        
    #     st.subheader("Pesos de las Componentes Principales (Loadings) - Conjunto Combinado")
    #     for i, comp in enumerate(components):
    #         source = ColumnDataSource(data=dict(
    #             dimensions=embedding_cols,
    #             weight=comp
    #         ))
    #         p = figure(x_range=embedding_cols, title=f"Componente Principal {i+1}",
    #                    plot_height=400, plot_width=600,
    #                    toolbar_location="above",
    #                    tools="pan,wheel_zoom,reset,save,hover",
    #                    active_scroll="wheel_zoom")

    #         # Establecer fondo blanco
    #         p.background_fill_color = "white"
    #         # Mostrar solo grilla horizontal
    #         p.xgrid.grid_line_color = None
    #         p.ygrid.grid_line_color = "gray"
    #         p.vbar(x='dimensions', top='weight', width=0.8, source=source)
    #         p.xaxis.major_label_text_font_size = '0pt'
    #         hover = HoverTool(tooltips=[("Dimensión", "@dimensions"), ("Peso", "@weight")])
    #         p.add_tools(hover)
    #         p.xaxis.axis_label = "Dimensiones originales"
    #         p.yaxis.axis_label = "Peso"
    #         st.bokeh_chart(p)
    
    data_table, df_table, source_table = create_table(result["df_distances"])
    real_subset_names = list(df_table.columns[1:])
    real_select = Select(title="", value=real_subset_names[0], options=real_subset_names)
    reset_button = Button(label="Reset Colors", button_type="primary")
    line_source = ColumnDataSource(data={'x': [], 'y': []})
    
    # if (reduction_method == "t-SNE" and N_COMPONENTS == 2) or (reduction_method == "PCA" and N_COMPONENTS == 2):
    #     fig, real_renderers, synthetic_renderers, pretrained_renderers = create_figure(
    #         result["dfs_reduced"],
    #         result["unique_subsets"],
    #         get_color_maps(result["unique_subsets"]),
    #         model_name
    #     )
    #     fig.line('x', 'y', source=line_source, line_width=2, line_color='black')
    #     centers_real = calculate_cluster_centers(result["dfs_reduced"]["real"], result["unique_subsets"]["real"])
    #     real_centers_js = {k: [v[0], v[1]] for k, v in centers_real.items()}
    #     synthetic_centers = {}
    #     synth_labels = sorted(result["dfs_reduced"]["synthetic"]['label'].unique().tolist())
    #     for label in synth_labels:
    #         subset = result["dfs_reduced"]["synthetic"][result["dfs_reduced"]["synthetic"]['label'] == label]
    #         if 'x' in subset.columns and 'y' in subset.columns:
    #             synthetic_centers[label] = [subset['x'].mean(), subset['y'].mean()]
    #     callback = CustomJS(args=dict(source=source_table, line_source=line_source,
    #                               synthetic_centers=synthetic_centers,
    #                               real_centers=real_centers_js,
    #                               real_select=real_select),
    #     code="""
    #         var selected = source.selected.indices;
    #         if (selected.length > 0) {
    #             var idx = selected[0];
    #             var data = source.data;
    #             var synth_label = data['Synthetic'][idx];
    #             var real_label = real_select.value;
    #             var syn_coords = synthetic_centers[synth_label];
    #             var real_coords = real_centers[real_label];
    #             line_source.data = {'x': [syn_coords[0], real_coords[0]], 'y': [syn_coords[1], real_coords[1]]};
    #             line_source.change.emit();
    #         } else {
    #             line_source.data = {'x': [], 'y': []};
    #             line_source.change.emit();
    #         }
    #     """)
    #     source_table.selected.js_on_change('indices', callback)
    #     real_select.js_on_change('value', callback)
    
    #     reset_callback = CustomJS(args=dict(line_source=line_source),
    #     code="""
    #         line_source.data = {'x': [], 'y': []};
    #         line_source.change.emit();
    #     """)
    #     reset_button.js_on_event("button_click", reset_callback)
    #     layout = column(fig, result["scatter_fig"], column(real_select, reset_button, data_table))
    # else:
    #     layout = column(result["scatter_fig"], column(real_select, reset_button, data_table))
    
    # st.bokeh_chart(layout, use_container_width=True)

    buffer = io.BytesIO()
    df_table.to_excel(buffer, index=False)
    buffer.seek(0)
    
    st.download_button(
        label="Export Table",
        data=buffer,
        file_name=f"cluster_distances_{model_name}.xlsx",
        mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        key=f"download_button_excel_{model_name}"
    )

    if reduction_method == "PCA":
        st.markdown("## PCA - Solo Muestras Reales")
        # -------------------------------------------------------------------------
        # 1. PCA sobre las muestras reales
        df_real_only = embeddings["real"].copy()
        reducer_real = Pipeline([
            ("pca", PCA(n_components=N_COMPONENTS)),
            ("rel_scaler", RelativeScaler())
        ])

        reduced_real = reducer_real.fit_transform(df_real_only[embedding_cols].values)

        
        # Agregar columnas PC1, PC2, … a df_real_only
        for i in range(reduced_real.shape[1]):
            df_real_only[f'PC{i+1}'] = reduced_real[:, i]
        
        explained_variance_real = reducer_real.named_steps["pca"].explained_variance_ratio_
        unique_labels_real = sorted(df_real_only['label'].unique().tolist())
        
        # Mapeo de colores para las muestras reales usando la paleta Reds9
        num_labels = len(unique_labels_real)
        if num_labels <= 9:
            red_palette = Reds9[:num_labels]
        else:
            red_palette = (Reds9 * ((num_labels // 9) + 1))[:num_labels]
        real_color_mapping = {label: red_palette[i] for i, label in enumerate(unique_labels_real)}
        
        # Mostrar tabla de Explained Variance Ratio
        st.subheader("PCA - Real: Explained Variance Ratio")
        component_names_real = [f"PC{i+1}" for i in range(len(explained_variance_real))]
        variance_df_real = pd.DataFrame({
            "Component": component_names_real,
            "Explained Variance": explained_variance_real
        })
        st.table(variance_df_real)
        
        # Mostrar los plots de loadings para cada componente
        # st.subheader("PCA - Real: Component Loadings")
        # st.markdown("### Pesos de las Componentes Principales (Loadings) - Conjunto Combinado")
        # for i, comp in enumerate(reducer_real.named_steps["pca"].components_):
        #     source = ColumnDataSource(data=dict(
        #         dimensions=embedding_cols,
        #         weight=comp
        #     ))
        #     p = figure(
        #         x_range=embedding_cols,
        #         title=f"Componente Principal {i+1}",
        #         plot_height=400,
        #         plot_width=600,
        #         toolbar_location="above",
        #         tools="pan,wheel_zoom,reset,save,hover",
        #         active_scroll="wheel_zoom"
        #     )
        #     p.background_fill_color = "white"
        #     p.xgrid.grid_line_color = None
        #     p.ygrid.grid_line_color = "gray"
        #     p.vbar(x='dimensions', top='weight', width=0.8, source=source,
        #         fill_color="#2b83ba", line_color="#2b83ba")
        #     p.xaxis.axis_label = "Dimensiones Originales"
        #     p.xaxis.major_label_text_font_size = '0pt'
        #     hover = p.select_one(HoverTool)
        #     hover.tooltips = [("Dimensión", "@dimensions"), ("Peso", "@weight")]
        #     st.bokeh_chart(p)
        
        # -------------------------------------------------------------------------
        # 2. Proyección de todos los subconjuntos usando los loadings de df_real (para PC completos)
        # Se proyectan real, synthetic y pretrained (si existen) y se agregan todas las PC's.
        df_all = {}
        # Real
        df_real_proj = embeddings["real"].copy()
        # proj_real = reducer_real.named_steps["pca"].transform(df_real_proj[embedding_cols].values)
        proj_real = reducer_real.transform(df_real_proj[embedding_cols].values)
        for i in range(proj_real.shape[1]):
            df_real_proj[f'PC{i+1}'] = proj_real[:, i]
        df_all["real"] = df_real_proj

        # Synthetic
        if "synthetic" in embeddings:
            df_synth_proj = embeddings["synthetic"].copy()
            proj_synth = reducer_real.transform(df_synth_proj[embedding_cols].values)
            for i in range(proj_synth.shape[1]):
                df_synth_proj[f'PC{i+1}'] = proj_synth[:, i]
            df_all["synthetic"] = df_synth_proj

        # Pretrained
        if "pretrained" in embeddings:
            df_pretr_proj = embeddings["pretrained"].copy()
            proj_pretr = reducer_real.transform(df_pretr_proj[embedding_cols].values)
            for i in range(proj_pretr.shape[1]):
                df_pretr_proj[f'PC{i+1}'] = proj_pretr[:, i]
            df_all["pretrained"] = df_pretr_proj

        # Para el plot global usaremos PC1 y PC2 (se asignan a 'x' y 'y')
        for key in df_all:
            df_all[key]["x"] = df_all[key]["PC1"]
            df_all[key]["y"] = df_all[key]["PC2"]

        # Construir los subconjuntos únicos para agrupar:
        unique_subsets = {}
        unique_subsets["real"] = sorted(df_all["real"]['label'].unique().tolist())
        if "synthetic" in df_all:
            unique_synth = {}
            for source in df_all["synthetic"]["source"].unique():
                unique_synth[source] = sorted(df_all["synthetic"][df_all["synthetic"]["source"] == source]['label'].unique().tolist())
            unique_subsets["synthetic"] = unique_synth
        else:
            unique_subsets["synthetic"] = {}
        if "pretrained" in df_all:
            unique_subsets["pretrained"] = sorted(df_all["pretrained"]['label'].unique().tolist())
        else:
            unique_subsets["pretrained"] = []
        
        # Obtener mapeo de colores para cada subconjunto (función definida externamente)
        color_maps = get_color_maps(unique_subsets)
        
        # Mapeo de marcadores para synthetic (por source)
        marker_mapping = {
            "es-digital-paragraph-degradation-seq": "x",
            "es-digital-line-degradation-seq": "cross",
            "es-digital-seq": "triangle",
            "es-digital-rotation-degradation-seq": "diamond",
            "es-digital-zoom-degradation-seq": "asterisk",
            "es-render-seq": "inverted_triangle"
        }
        
        # Plot global: se muestran real, synthetic y pretrained (según checkbox)
        st.subheader("PCA - Todos los subconjuntos proyectados (PC1 vs PC2)")
        fig_all = figure(
            title="PCA - Todos los subconjuntos proyectados",
            plot_width=600,
            plot_height=600,
            tools="pan,wheel_zoom,reset,save",
            active_scroll="wheel_zoom",
            background_fill_color="white",
            tooltips=TOOLTIPS
        )
        fig_all.xgrid.grid_line_color = None
        fig_all.ygrid.grid_line_color = "gray"
        
        # Plotear las muestras reales, agrupadas por label
        for label in unique_subsets["real"]:
            subset = df_all["real"][df_all["real"]['label'] == label]
            source = ColumnDataSource(data={
                'x': subset['x'],
                'y': subset['y'],
                'label': subset['label'],
                'img': subset['img']
            })
            fig_all.circle('x', 'y', size=10,
                        fill_color=color_maps["real"][label],
                        line_color=color_maps["real"][label],
                        legend_label=f"Real: {label}",
                        source=source)
        
        show_real_only = st.checkbox("Show only real samples", value=True, key=f"show_real_only_{model_name}")
        if not show_real_only:
            # Agregar synthetic
            if unique_subsets["synthetic"]:
                for source_name, labels in unique_subsets["synthetic"].items():
                    df_source = df_all["synthetic"][df_all["synthetic"]["source"] == source_name]
                    marker = marker_mapping.get(source_name, "square")
                    # Se usa el mapeo de colores para synthetic
                    color_val = color_maps["synthetic"][source_name]
                    renderers = add_synthetic_dataset_to_fig(
                        fig_all, df_source, labels,
                        marker=marker,
                        color_mapping=color_val,
                        group_label=source_name
                    )
            # Agregar pretrained
            if unique_subsets["pretrained"]:
                for label in unique_subsets["pretrained"]:
                    subset = df_all["pretrained"][df_all["pretrained"]['label'] == label]
                    source = ColumnDataSource(data={
                        'x': subset['x'],
                        'y': subset['y'],
                        'label': subset['label'],
                        'img': subset['img']
                    })
                    fig_all.triangle('x', 'y', size=10,
                                    fill_color=color_maps["pretrained"][label],
                                    line_color=color_maps["pretrained"][label],
                                    legend_label=f"Pretrained: {label}",
                                    source=source)
        
        show_legend_global = st.checkbox("Show Legend", value=False, key=f"legend_global_{model_name}")
        fig_all.legend.visible = show_legend_global
        fig_all.legend.location = "top_right"
        fig_all.match_aspect = True
        st.bokeh_chart(fig_all)
        
        # Calcular centroide y radio (usando solo las muestras reales)
        center_x = df_all["real"]['x'].mean()
        center_y = df_all["real"]['y'].mean()
        distances = np.sqrt((df_all["real"]['x'] - center_x)**2 + (df_all["real"]['y'] - center_y)**2)
        radius = distances.max()
        
        # Dibujar el centroide y la circunferencia
        centroid_glyph = fig_all.circle(
            x=center_x, y=center_y, size=15,
            fill_color="white", line_color="black",
            legend_label="Centroide",
            name="centroid"
        )
        circumference_glyph = fig_all.circle(
            x=center_x, y=center_y, radius=radius,
            fill_color=None, line_color="black",
            line_dash="dashed",
            legend_label="Circunferencia",
            name="circumference"
        )
        
        # Ajustar ejes y tooltips
        fig_all.xaxis.axis_label = "PC1"
        fig_all.yaxis.axis_label = "PC2"
        hover_all = fig_all.select_one(HoverTool)
        hover_all.renderers = [r for r in fig_all.renderers if r.name not in ["centroid", "circumference"]]
        
        st.write(f"El radio de la circunferencia (calculado a partir de las muestras reales) es: {radius:.4f}")
        
        # -------------------------------------------------------------------------
        # Calcular el rango global: recorrer todas las proyecciones de todos los subconjuntos
        all_vals = []
        for key in df_all:
            for comp in [f'PC{i+1}' for i in range(N_COMPONENTS)]:
                all_vals.append(df_all[key][comp])
        all_vals = pd.concat(all_vals)
        # Tomar el máximo valor absoluto de todas las proyecciones
        max_val = all_vals.abs().max()
        global_range = (-max_val, max_val)

        # 3. Scatter plots para cada combinación (vistas planta, alzado y perfil)
        st.subheader("Scatter Plots: Vistas de Componentes (Combinaciones)")
        pairs = list(itertools.combinations(range(N_COMPONENTS), 2))
        for (i, j) in pairs:
            x_comp = f'PC{i+1}'
            y_comp = f'PC{j+1}'
            
            st.markdown(f"### Scatter Plot: {x_comp} vs {y_comp}")
            # Usar el rango global para ambos ejes
            p = figure(
                title=f"{x_comp} vs {y_comp}",
                plot_width=700,
                plot_height=700,
                x_range=global_range,
                y_range=global_range,
                tools="pan,wheel_zoom,reset,save,hover",
                active_scroll="wheel_zoom",
                background_fill_color="white",
                tooltips=TOOLTIPS
            )
            # Etiquetas de ejes
            p.xaxis.axis_label = x_comp
            p.yaxis.axis_label = y_comp

            # Muestras reales: se usan directamente los valores de PC{i+1} y PC{j+1}
            for label in unique_subsets["real"]:
                subset = df_all["real"][df_all["real"]['label'] == label]
                source = ColumnDataSource(data={
                    'x': subset[x_comp],
                    'y': subset[y_comp],
                    'label': subset['label'],
                    'img': subset['img']
                })
                p.circle('x', 'y', size=10,
                        fill_color=color_maps["real"][label],
                        line_color=color_maps["real"][label],
                        legend_label=f"Real: {label}",
                        source=source)
            
            # Selector para incluir o no synthetic y pretrained en este gráfico
            show_pair_only_real = st.checkbox("Show only real samples", value=True, key=f"pair_show_real_{i}_{j}_{model_name}")
            if not show_pair_only_real:
                # Synthetic
                if "synthetic" in df_all:
                    for source_name, labels in unique_subsets["synthetic"].items():
                        # Obtener las filas de synthetic para ese source y asignar el rango adecuado
                        df_source = df_all["synthetic"][df_all["synthetic"]["source"] == source_name].copy()
                        df_source["x"] = df_source[x_comp]
                        df_source["y"] = df_source[y_comp]
                        marker = marker_mapping.get(source_name, "square")
                        renderers = add_synthetic_dataset_to_fig(
                            p, df_source, labels,
                            marker=marker,
                            color_mapping=color_maps["synthetic"][source_name],
                            group_label=source_name
                        )
                # Pretrained
                if "pretrained" in df_all:
                    for label in unique_subsets["pretrained"]:
                        subset = df_all["pretrained"][df_all["pretrained"]['label'] == label]
                        source = ColumnDataSource(data={
                            'x': subset[x_comp],
                            'y': subset[y_comp],
                            'label': subset['label'],
                            'img': subset['img']
                        })
                        p.triangle('x', 'y', size=10,
                                fill_color=color_maps["pretrained"][label],
                                line_color=color_maps["pretrained"][label],
                                legend_label=f"Pretrained: {label}",
                                source=source)
            show_legend_pair = st.checkbox("Show Legend", value=False, key=f"legend_pair_{i}_{j}_{model_name}")
            p.legend.visible = show_legend_pair
            st.bokeh_chart(p)

        
        # -------------------------------------------------------------------------
        # 4. Cálculo de distancias y scatter plot: Distance vs F1 (usando PC1 y PC2 globales)
        


        # Genera una paleta de 256 colores basada en RdYlGn11
        cmap = plt.get_cmap("RdYlGn")
        red_green_palette = [mcolors.rgb2hex(cmap(i)) for i in np.linspace(0, 1, 256)]



        # real_labels_new = sorted(df_all["real"]['label'].unique().tolist())
        # df_distances_new = compute_cluster_distances_synthetic_individual(
        #     df_all["synthetic"],
        #     df_all["real"],
        #     real_labels_new,
        #     metric="wasserstein",  # O la métrica que prefieras
        #     bins=20
        # )
        
        # global_distances_new = {}
        # for idx in df_distances_new.index:
        #     if idx.startswith("Global"):
        #         source_name = idx.split("(")[1].rstrip(")")
        #         global_distances_new[source_name] = df_distances_new.loc[idx].values
        
        # all_x_new = []
        # all_y_new = []
        # for source in df_f1.columns:
        #     if source in global_distances_new:
        #         x_vals = global_distances_new[source]
        #         y_vals = df_f1[source].values
        #         all_x_new.extend(x_vals)
        #         all_y_new.extend(y_vals)
        # all_x_arr_new = np.array(all_x_new).reshape(-1, 1)
        # all_y_arr_new = np.array(all_y_new)
        
        # model_global_new = LinearRegression().fit(all_x_arr_new, all_y_arr_new)
        # r2_new = model_global_new.score(all_x_arr_new, all_y_arr_new)
        # slope_new = model_global_new.coef_[0]
        # intercept_new = model_global_new.intercept_
        
        # scatter_fig_new = figure(
        #     width=600,
        #     height=600,
        #     tools="pan,wheel_zoom,reset,save,hover",
        #     active_scroll="wheel_zoom",
        #     title="Scatter Plot: Distance vs F1 (Nueva PCA)",
        #     background_fill_color="white",
        #     y_range=(0, 1)
        # )
        # scatter_fig_new.xgrid.grid_line_color = None
        # scatter_fig_new.ygrid.grid_line_color = "gray"
        # scatter_fig_new.match_aspect = True
        
        # source_colors = {
        #     "es-digital-paragraph-degradation-seq": "blue",
        #     "es-digital-line-degradation-seq": "green",
        #     "es-digital-seq": "red",
        #     "es-digital-zoom-degradation-seq": "orange",
        #     "es-digital-rotation-degradation-seq": "purple",
        #     "es-digital-rotation-zoom-degradation-seq": "brown",
        #     "es-render-seq": "cyan"
        # }
        
        # for source in df_f1.columns:
        #     if source in global_distances_new:
        #         x_vals = global_distances_new[source]
        #         y_vals = df_f1[source].values
        #         data = {"x": x_vals, "y": y_vals, "Fuente": [source]*len(x_vals)}
        #         cds = ColumnDataSource(data=data)
        #         scatter_fig_new.circle(
        #             'x', 'y', size=8, alpha=0.7, source=cds,
        #             fill_color=source_colors.get(source, "gray"),
        #             line_color=source_colors.get(source, "gray"),
        #             legend_label=source
        #         )
        
        # scatter_fig_new.xaxis.axis_label = "Distance (Global, por Colegio) - Nueva PCA"
        # scatter_fig_new.yaxis.axis_label = "F1 Score"
        # scatter_fig_new.legend.location = "top_right"
        # hover_tool_new = scatter_fig_new.select_one(HoverTool)
        # hover_tool_new.tooltips = [("Distance", "@x"), ("F1", "@y"), ("Subset", "@Fuente")]
        # x_line_new = np.linspace(all_x_arr_new.min(), all_x_arr_new.max(), 100)
        # y_line_new = model_global_new.predict(x_line_new.reshape(-1,1))
        # scatter_fig_new.line(x_line_new, y_line_new, line_width=2, line_color="black", legend_label="Global Regression")
        # st.bokeh_chart(scatter_fig_new)
        # st.write(f"Regresión global (Nueva PCA): R² = {r2_new:.4f}, Slope = {slope_new:.4f}, Intercept = {intercept_new:.4f}")
        
        # -------------------------------------------------------------------------
        # 5. BLOQUE: Heatmap de Características
        st.markdown("## Heatmap de Características")
        try:
            df_heat = pd.read_csv(f"data/heatmaps_{model_name.lower()}.csv")
        except Exception as e:
            st.error(f"Error al cargar heatmaps.csv: {e}")
            df_heat = None
        
        if df_heat is not None:
            if 'img' not in df_all["real"].columns:
                st.error("La columna 'img' no se encuentra en las muestras reales para hacer el merge con heatmaps.csv.")
            else:
                # Crear columna 'name' en las muestras reales (si aún no existe)
                df_all["real"]["name"] = df_all["real"]["img"].apply(
                    lambda x: x.split("/")[-1].replace(".png", "") if isinstance(x, str) else x
                )
                # Merge de las posiciones reales con el CSV de heatmaps (se usa el merge base)
                df_heatmap_base = pd.merge(df_all["real"], df_heat, on="name", how="inner")
                
                # Extraer opciones de feature (excluyendo 'name')
                feature_options = [col for col in df_heat.columns if col != "name"]
                selected_feature = st.selectbox("Select heatmap feature:", 
                                                options=feature_options, key=f"heatmap_{model_name}")
                select_extra_dataset_hm = st.selectbox("Select a dataset:", 
                                                options=model_options_with_default, key=f"heatmap_extra_dataset_{model_name}")
                
                # Definir un rango fijo para los ejes (por ejemplo, de -1 a 1) y rejilla
                x_min, x_max = -1, 1
                y_min, y_max = -1, 1
                grid_size = 50
                x_bins = np.linspace(x_min, x_max, grid_size + 1)
                y_bins = np.linspace(y_min, y_max, grid_size + 1)
                
                # Listas para almacenar las figuras de heatmap y sus nombres
                heatmap_figures = []
                heatmap_names = []

                # Generar heatmaps para cada combinación de componentes
                pairs = list(itertools.combinations(range(N_COMPONENTS), 2))
                for (i, j) in pairs:
                    x_comp = f'PC{i+1}'
                    y_comp = f'PC{j+1}'
                    st.markdown(f"### Heatmap: {x_comp} vs {y_comp}")
                    
                    # Crear un DataFrame de heatmap para la combinación actual a partir del merge base
                    df_heatmap = df_heatmap_base.copy()
                    df_heatmap["x"] = df_heatmap[x_comp]
                    df_heatmap["y"] = df_heatmap[y_comp]
                    
                    # Si la feature seleccionada no es numérica, convertir a códigos y guardar la correspondencia
                    cat_mapping = None
                    if df_heatmap[selected_feature].dtype == bool or not pd.api.types.is_numeric_dtype(df_heatmap[selected_feature]):
                        cat = df_heatmap[selected_feature].astype('category')
                        cat_mapping = list(cat.cat.categories)
                        df_heatmap[selected_feature] = cat.cat.codes
                    
                    # Calcular la estadística binned (por ejemplo, la media) en la rejilla
                    try:
                        heat_stat, x_edges, y_edges, binnumber = binned_statistic_2d(
                            df_heatmap['x'], df_heatmap['y'], df_heatmap[selected_feature],
                            statistic='mean', bins=[x_bins, y_bins]
                        )
                    except TypeError:
                        cat = df_heatmap[selected_feature].astype('category')
                        cat_mapping = list(cat.cat.categories)
                        df_heatmap[selected_feature] = cat.cat.codes
                        heat_stat, x_edges, y_edges, binnumber = binned_statistic_2d(
                            df_heatmap['x'], df_heatmap['y'], df_heatmap[selected_feature],
                            statistic='mean', bins=[x_bins, y_bins]
                        )
                    # Transponer la matriz para alinear correctamente los ejes
                    # Transponer y limpiar valores inválidos (NaN, inf, -inf)
                    heatmap_data = heat_stat.T
                    # heatmap_data = np.nan_to_num(heat_stat.T, nan=0.0, posinf=0.0, neginf=0.0)
                    
                    # Definir el color mapper
                    if selected_feature in model_options:
                        color_mapper = LinearColorMapper(
                            palette=red_green_palette,
                            low=0,
                            high=1,
                            nan_color='rgba(0, 0, 0, 0)'
                        )
                    else:
                        color_mapper = LinearColorMapper(
                            palette="Viridis256",
                            low=np.nanmin(heatmap_data),
                            high=np.nanmax(heatmap_data),
                            nan_color='rgba(0, 0, 0, 0)'
                        )
                    
                    # Crear la figura para el heatmap con la misma escala para x e y
                    heatmap_fig = figure(title=f"Heatmap de '{selected_feature}' ({x_comp} vs {y_comp})",
                                        x_range=(x_min, x_max), y_range=(y_min, y_max),
                                        width=600, height=600,
                                        tools="pan,wheel_zoom,reset,save", active_scroll="wheel_zoom", tooltips=TOOLTIPS,
                                        sizing_mode="fixed")
                    heatmap_fig.match_aspect = True
                    
                    # Asignar etiquetas a los ejes
                    heatmap_fig.xaxis.axis_label = x_comp
                    heatmap_fig.yaxis.axis_label = y_comp

                    heatmap_fig.background_fill_color = "white"
                    heatmap_fig.border_fill_color = "white"

                    # Dibujar la imagen del heatmap
                    heatmap_fig.image(image=[heatmap_data], x=x_min, y=y_min,
                                    dw=x_max - x_min, dh=y_max - y_min,
                                    color_mapper=color_mapper)
                    
                    # Agregar la barra de color
                    color_bar = ColorBar(color_mapper=color_mapper, location=(0, 0))
                    if cat_mapping is not None:
                        ticks = list(range(len(cat_mapping)))
                        color_bar.ticker = FixedTicker(ticks=ticks)
                        categories_json = json.dumps(cat_mapping)
                        color_bar.formatter = FuncTickFormatter(code=f"""
                            var categories = {categories_json};
                            var index = Math.round(tick);
                            if(index >= 0 && index < categories.length) {{
                                return categories[index];
                            }} else {{
                                return "";
                            }}
                        """)
                    heatmap_fig.add_layout(color_bar, 'right')
                    
                    # Agregar renderer invisible para tooltips
                    source_points = ColumnDataSource(data={
                        'x': df_heatmap['x'],
                        'y': df_heatmap['y'],
                        'img': df_heatmap['img'],
                        'label': df_heatmap['name']
                    })
                    invisible_renderer = heatmap_fig.circle('x', 'y', size=10, source=source_points, fill_alpha=0, line_alpha=0.5)
                    # school = "patria"
                    if select_extra_dataset_hm != "-":
                        df_extra = df_all["synthetic"][df_all["synthetic"]["source"] == select_extra_dataset_hm].copy()
                        df_extra["x"] = df_extra[x_comp]
                        df_extra["y"] = df_extra[y_comp]
                        if 'name' not in df_extra.columns:
                            df_extra["name"] = df_extra["img"].apply(lambda x: x.split("/")[-1].replace(".png", "") if isinstance(x, str) else x)
                        # mask = df_extra["name"].str.contains(school, case=False, na=False)
                        # df_extra = df_extra[mask].copy()
                        source_extra_points = ColumnDataSource(data={
                            'x': df_extra['x'],
                            'y': df_extra['y'],
                            'img': df_extra['img'],
                            'label': df_extra['name']
                        })
                        extra_renderer = heatmap_fig.circle('x', 'y', size=5, source=source_extra_points, fill_alpha=0, line_alpha=0.5, color="purple")
                    
                    hover_tool_points = HoverTool(renderers=[invisible_renderer], tooltips=TOOLTIPS)
                    heatmap_fig.add_tools(hover_tool_points)
                    
                    # Mostrar el heatmap en la app
                    st.bokeh_chart(heatmap_fig)

        # Botón para descargar df_all (Embeddings in PCA Space)
        if st.button("Download Embeddings in PCA Space", key=f"click_download_pca_coordinates_{model_name}"):
            # Crear un nuevo diccionario para almacenar solo las columnas que comienzan con "PC" o "name"
            df_all_pca = {}
            for key, df in df_all.items():
                # Si es el conjunto sintético, separamos cada subset según la columna "source"
                if key == "synthetic":
                    for source in df["source"].unique():
                        df_subset = df[df["source"] == source].copy()
                        # Asegurarse de que exista la columna "name" (como se hace en el snippet de heatmaps)
                        if "img" in df_subset.columns and "name" not in df_subset.columns:
                            df_subset["name"] = df_subset["img"].apply(lambda x: x.split("/")[-1].replace(".png", "") if isinstance(x, str) else x)
                        pca_cols = [col for col in df_subset.columns if col.startswith("PC") or col == "name"]
                        # Usar un nombre de hoja que identifique que es sintético y el source correspondiente
                        sheet_name = f"synthetic_{source}"
                        df_all_pca[sheet_name] = df_subset[pca_cols].copy()
                else:
                    # Para "real" y otros (como "pretrained"), se guardan en una sola hoja
                    pca_cols = [col for col in df.columns if col.startswith("PC") or col == "name"]
                    df_all_pca[key] = df[pca_cols].copy()

            # Crear un buffer en memoria para el archivo Excel
            excel_buffer = io.BytesIO()
            # Escribir cada DataFrame en una hoja separada usando ExcelWriter
            with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer:
                for key_name, df in df_all_pca.items():
                    df.to_excel(writer, sheet_name=key_name, index=False)
            excel_buffer.seek(0)
            
            st.download_button(
                label="Download Embeddings in PCA Space",
                data=excel_buffer,
                file_name=f"df_all_pca_{model_name.lower()}.xlsx",
                mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                key=f"download_pca_coordinates_{model_name}"
            )
            
    elif reduction_method == "t-SNE":
        st.markdown("## t-SNE - Solo Muestras Reales")
        # -------------------------------------------------------------------------
        # 1. t-SNE sobre las muestras reales
        df_real_only = embeddings["real"].copy()
        
        reducer_real = TSNE(n_components=2, perplexity=30, random_state=42)
        reduced_real = reducer_real.fit_transform(df_real_only[embedding_cols].values)
        
        # Agregar columnas TSNE1, TSNE2
        df_real_only['TSNE1'] = reduced_real[:, 0]
        df_real_only['TSNE2'] = reduced_real[:, 1]

        # Construir df_all de forma consistente con PCA
        df_all = {}
        df_all["real"] = df_real_only.copy()
        if "synthetic" in embeddings:
            df_all["synthetic"] = embeddings["synthetic"].copy()
        if "pretrained" in embeddings:
            df_all["pretrained"] = embeddings["pretrained"].copy()

        unique_labels_real = sorted(df_real_only['label'].unique().tolist())
        
        # Mapeo de colores para las muestras reales usando la paleta Reds9
        num_labels = len(unique_labels_real)
        if num_labels <= 9:
            red_palette = Reds9[:num_labels]
        else:
            red_palette = (Reds9 * ((num_labels // 9) + 1))[:num_labels]
        real_color_mapping = {label: red_palette[i] for i, label in enumerate(unique_labels_real)}

        # -------------------------------------------------------------------------
        # Crear plot interactivo con Bokeh
        st.subheader("t-SNE - Real: Visualización Interactiva")

        source = ColumnDataSource(df_real_only)

        hover = HoverTool(tooltips=[
            ("Index", "$index"),
            ("Label", "@label"),
            ("TSNE1", "@TSNE1"),
            ("TSNE2", "@TSNE2")
        ])

        p = figure(
            width=800,
            height=600,
            title="t-SNE sobre muestras reales",
            tools=["pan", "wheel_zoom", "box_zoom", "reset", hover]
        )

        for label in unique_labels_real:
            subset = df_real_only[df_real_only['label'] == label]
            p.scatter(
                x=subset["TSNE1"],
                y=subset["TSNE2"],
                size=8,
                color=real_color_mapping[label],
                alpha=0.7,
                legend_label=str(label)
            )

        p.legend.title = "Label"
        p.legend.location = "top_right"
        p.xaxis.axis_label = "t-SNE 1"
        p.yaxis.axis_label = "t-SNE 2"

        st.bokeh_chart(p, use_container_width=True)

        # -------------------------------------------------------------------------
        # BLOQUE: Heatmap de Características (adaptado a TSNE1 y TSNE2)
        st.markdown("## Heatmap de Características")
        try:
            df_heat = pd.read_csv(f"data/heatmaps_{model_name.lower()}.csv")
        except Exception as e:
            st.error(f"Error al cargar heatmaps.csv: {e}")
            df_heat = None
        
        if df_heat is not None:
            if 'img' not in df_all["real"].columns:
                st.error("La columna 'img' no se encuentra en las muestras reales para hacer el merge con heatmaps.csv.")
            else:
                # Crear columna 'name' en las muestras reales (si aún no existe)
                df_all["real"]["name"] = df_all["real"]["img"].apply(
                    lambda x: x.split("/")[-1].replace(".png", "") if isinstance(x, str) else x
                )
                # Merge con heatmaps.csv
                df_heatmap_base = pd.merge(df_all["real"], df_heat, on="name", how="inner")
                
                # Opciones de features
                feature_options = [col for col in df_heat.columns if col != "name"]
                selected_feature = st.selectbox("Select heatmap feature:", 
                                                options=feature_options, key=f"heatmap_{model_name}")
                select_extra_dataset_hm = st.selectbox("Select a dataset:", 
                                                options=model_options_with_default, key=f"heatmap_extra_dataset_{model_name}")        
                
                # Solo una combinación: TSNE1 vs TSNE2
                x_comp, y_comp = "TSNE1", "TSNE2"
                st.markdown(f"### Heatmap: {x_comp} vs {y_comp}")

                # Rango real de los datos
                df_heatmap = df_heatmap_base.copy()
                # Rango real de los datos
                x_min, x_max = df_heatmap[x_comp].min(), df_heatmap[x_comp].max()
                y_min, y_max = df_heatmap[y_comp].min(), df_heatmap[y_comp].max()

                # Opcional: ampliar un poco
                padding = 0.05
                x_min, x_max = x_min - padding, x_max + padding
                y_min, y_max = y_min - padding, y_max + padding

                # Definir rejilla
                grid_size = st.slider("Grid size (resolución del heatmap)", min_value=10, max_value=100, value=40, step=5, key=f"grid_size_{model_name}")
                x_bins = np.linspace(x_min, x_max, grid_size + 1)
                y_bins = np.linspace(y_min, y_max, grid_size + 1)

                # Usar los mismos valores para figure y image
                x_range, y_range = (x_min, x_max), (y_min, y_max)
                
                
                df_heatmap["x"] = df_heatmap[x_comp]
                df_heatmap["y"] = df_heatmap[y_comp]
                df_heatmap['x'] = np.nan_to_num(df_heatmap['x'], nan=0.0, posinf=0.0, neginf=0.0)
                df_heatmap['y'] = np.nan_to_num(df_heatmap['y'], nan=0.0, posinf=0.0, neginf=0.0)
                
                # Si la feature seleccionada no es numérica, convertir
                cat_mapping = None
                if df_heatmap[selected_feature].dtype == bool or not pd.api.types.is_numeric_dtype(df_heatmap[selected_feature]):
                    cat = df_heatmap[selected_feature].astype('category')
                    cat_mapping = list(cat.cat.categories)
                    df_heatmap[selected_feature] = cat.cat.codes
                
                # Calcular estadística binned
                heat_stat, x_edges, y_edges, binnumber = binned_statistic_2d(
                    df_heatmap['x'], df_heatmap['y'], df_heatmap[selected_feature],
                    statistic='mean', bins=[x_bins, y_bins]
                )

                # Mantener NaN para celdas vacías
                heatmap_data = heat_stat.T

                cmap = plt.get_cmap("RdYlGn")
                red_green_palette = [mcolors.rgb2hex(cmap(i)) for i in np.linspace(0, 1, 256)]

                # Color mapper
                if selected_feature in model_options:
                    color_mapper = LinearColorMapper(
                        palette=red_green_palette,
                        low=0,
                        high=1,
                        nan_color="white"
                    )
                else:
                    color_mapper = LinearColorMapper(
                        palette="Viridis256",
                        low=np.nanmin(heatmap_data),
                        high=np.nanmax(heatmap_data),
                        nan_color="white"
                    )
                

                # Figura heatmap
                heatmap_fig = figure(title=f"Heatmap de '{selected_feature}' ({x_comp} vs {y_comp})",
                                    x_range=x_range, y_range=y_range,
                                    width=600, height=600,
                                    tools="pan,wheel_zoom,reset,save", active_scroll="wheel_zoom", tooltips=TOOLTIPS,
                                    sizing_mode="fixed")
                heatmap_fig.match_aspect = True
                heatmap_fig.xaxis.axis_label = x_comp
                heatmap_fig.yaxis.axis_label = y_comp

                heatmap_fig.image(image=[heatmap_data], x=x_min, y=y_min,
                                dw=x_max - x_min, dh=y_max - y_min,
                                color_mapper=color_mapper)
                
                # Barra de color
                color_bar = ColorBar(color_mapper=color_mapper, location=(0, 0))
                if cat_mapping is not None:
                    ticks = list(range(len(cat_mapping)))
                    color_bar.ticker = FixedTicker(ticks=ticks)
                    categories_json = json.dumps(cat_mapping)
                    color_bar.formatter = FuncTickFormatter(code=f"""
                        var categories = {categories_json};
                        var index = Math.round(tick);
                        if(index >= 0 && index < categories.length) {{
                            return categories[index];
                        }} else {{
                            return "";
                        }}
                    """)
                heatmap_fig.add_layout(color_bar, 'right')

                heatmap_fig.background_fill_color = "white"
                heatmap_fig.border_fill_color = "white"
                
                # Tooltips
                source_points = ColumnDataSource(data={
                    'x': df_heatmap['x'],
                    'y': df_heatmap['y'],
                    'img': df_heatmap['img'],
                    'label': df_heatmap['name']
                })
                invisible_renderer = heatmap_fig.circle('x', 'y', size=10, source=source_points, fill_alpha=0, line_alpha=0.5)
                
                # if select_extra_dataset_hm != "-":
                #     df_extra = df_all["synthetic"][df_all["synthetic"]["source"] == select_extra_dataset_hm].copy()
                #     df_extra["x"] = df_extra[x_comp]
                #     df_extra["y"] = df_extra[y_comp]
                #     if 'name' not in df_extra.columns:
                #         df_extra["name"] = df_extra["img"].apply(lambda x: x.split("/")[-1].replace(".png", "") if isinstance(x, str) else x)
                #     source_extra_points = ColumnDataSource(data={
                #         'x': df_extra['x'],
                #         'y': df_extra['y'],
                #         'img': df_extra['img'],
                #         'label': df_extra['name']
                #     })
                #     heatmap_fig.circle('x', 'y', size=5, source=source_extra_points, fill_alpha=0, line_alpha=0.5, color="purple")
                
                hover_tool_points = HoverTool(renderers=[invisible_renderer], tooltips=TOOLTIPS)
                heatmap_fig.add_tools(hover_tool_points)
                
                st.bokeh_chart(heatmap_fig)

        # -------------------------------------------------------------------------
        # Botón para descargar df_all (Embeddings en t-SNE Space)
        if st.button("Download Embeddings in t-SNE Space", key=f"click_download_tsne_coordinates_{model_name}"):
            df_all_tsne = {}
            for key, df in df_all.items():
                if key == "synthetic":
                    for source in df["source"].unique():
                        df_subset = df[df["source"] == source].copy()
                        if "img" in df_subset.columns and "name" not in df_subset.columns:
                            df_subset["name"] = df_subset["img"].apply(lambda x: x.split("/")[-1].replace(".png", "") if isinstance(x, str) else x)
                        tsne_cols = [col for col in df_subset.columns if col.startswith("TSNE") or col == "name"]
                        sheet_name = f"synthetic_{source}"
                        df_all_tsne[sheet_name] = df_subset[tsne_cols].copy()
                else:
                    tsne_cols = [col for col in df.columns if col.startswith("TSNE") or col == "name"]
                    df_all_tsne[key] = df[tsne_cols].copy()

            excel_buffer = io.BytesIO()
            with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer:
                for key_name, df in df_all_tsne.items():
                    df.to_excel(writer, sheet_name=key_name, index=False)
            excel_buffer.seek(0)
            
            st.download_button(
                label="Download Embeddings in t-SNE Space",
                data=excel_buffer,
                file_name=f"df_all_tsne_{model_name.lower()}.xlsx",
                mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                key=f"download_tsne_coordinates_{model_name}"
            )


def main():
    config_style()
    tabs = st.tabs(["Donut", "Idefics2", "Idefics2-patient", "Paligemma", "Llava"])
    with tabs[0]:
        st.markdown('<h2 class="sub-title">Donut 🤗</h2>', unsafe_allow_html=True)
        run_model("Donut")
    with tabs[1]:
        st.markdown('<h2 class="sub-title">Idefics2 🤗</h2>', unsafe_allow_html=True)
        run_model("Idefics2")
    with tabs[2]:
        st.markdown('<h2 class="sub-title">Idefics2-patient 🤗</h2>', unsafe_allow_html=True)
        run_model("Idefics2-patient")
    with tabs[3]:
        st.markdown('<h2 class="sub-title">Paligemma 🤗</h2>', unsafe_allow_html=True)
        run_model("Paligemma")
    with tabs[4]:
        st.markdown('<h2 class="sub-title">Llava 🤗</h2>', unsafe_allow_html=True)
        run_model("Llava")

if __name__ == "__main__":
    model_options = [
            "es-digital-paragraph-degradation-seq", 
            "es-digital-line-degradation-seq", 
            "es-digital-seq",
            "es-digital-noisy-degradation-seq",
            "es-digital-seq_es-digital-seq_britanico",
            "es-digital-seq_retamar_train-asc-synth",
            "es-digital-seq_britanico_es-digital-seq_aletamar",
            "es-digital-seq_retamar_train-asc-synth_es-digital-seq_britanico",
            "es-digital-seq_retamar_train-asc-synth_es-digital-seq_britanico_v2",
            "es-digital-seq_es-digital-seq_aletamar",
            "es-render-seq_es-render-seq_aletamar",
            "retamar_train-asc-synth_es-digital-seq_britanico",
            "es-digital-rotation-degradation-seq", 
            "es-digital-zoom-degradation-seq", 
            "es-render-seq",
            "es-digital-seq_filtered_deus",
            "es-digital-seq_filtered_liceo",
            "es-digital-seq_filtered_lusitano",
            "es-digital-seq_filtered_monterraso",
            "es-digital-seq_filtered_patria",
            "es-digital-zoom-0.25-degradation-seq_filtered_deus-liceo-lusitano-monterraso-patria-frozen-encoder",
            "es-digital-zoom-0.5-degradation-seq_filtered_deus-liceo-lusitano-monterraso-patria-frozen-encoder",
            "es-digital-zoom-0.625-degradation-seq_filtered_deus-liceo-lusitano-monterraso-patria-frozen-encoder",
            "es-digital-zoom-0.75-degradation-seq_filtered_deus-liceo-lusitano-monterraso-patria-frozen-encoder",
            "es-digital-seq_filtered_deus-liceo-lusitano-monterraso-patria-frozen-encoder",
            "es-digital-zoom-degradation-seq_filtered_deus-liceo-lusitano-monterraso-patria-frozen-encoder",
            "es-render-seq_filtered_deus-liceo-lusitano-monterraso-patria-frozen-encoder-017",
            "es-render-seq_filtered_deus-liceo-lusitano-monterraso-patria-frozen-encoder-016",
            "es-digital-rotation-degradation-seq_filtered_deus-liceo-lusitano-monterraso-patria-frozen-encoder",
            "retamar_train-asc-synth_filtered_retamar_train-frozen-encoder",
            "britanico-retamar_train-asc-synth_filtered_retamar_train-frozen-encoder",
            "combination-es-digital-seq",
            "combination-es-render-seq",
            "retamar_train-asc-synth_es-digital-seq_britanico",

    ]
    
    model_options_with_default = [""]
    model_options_with_default.extend(model_options)
    
    main()