File size: 74,109 Bytes
9ee47ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b381fca
 
 
 
 
9ee47ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b463db7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ee47ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b381fca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ee47ec
 
 
 
 
1a33468
9ee47ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a33468
9ee47ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b381fca
 
 
 
 
 
 
 
9ee47ec
 
 
b381fca
 
 
 
 
9ee47ec
 
b381fca
 
9ee47ec
 
b381fca
 
 
9ee47ec
 
b381fca
 
 
9ee47ec
 
b381fca
 
 
9ee47ec
 
b381fca
 
 
 
9ee47ec
 
 
b381fca
 
 
9ee47ec
 
 
 
 
b381fca
 
 
9ee47ec
 
 
 
 
 
 
 
b381fca
 
9ee47ec
 
 
 
 
 
1a33468
9ee47ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a33468
 
 
 
9ee47ec
 
 
 
 
 
 
 
 
1a33468
9ee47ec
 
 
 
1a33468
 
9ee47ec
 
 
 
 
 
 
 
 
b381fca
 
9ee47ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""run_full.py -- corrected ORCA Table-3 reproduction (blog / fb1 / fb2).

NEW file for the corrected core; the previous pipeline stays untouched as
/work/run_realdata_v30.py (its data loaders, QRF fit, MILP machinery and CSV
plumbing are reused via `from run_realdata_v30 import ...`).

PORTING SOURCES (cloned to /work/pcp_src and /work/chr_src):
  - PCP baselines:  /work/pcp_src/other_baselines/{cqr.py,dcp.py,dist_split.py,utils.py}
  - PCP driver:     /work/pcp_src/main.py  (splits, StandardScaler, y_min/y_max, QRF config)
  - CHR:            /work/chr_src/chr/{methods.py,histogram.py,grey_boxes.py}
Functions are ported into THIS file (no package import).

=========================== PROTOCOL (per run) ============================
seed = seed0 + run_id. ONE numpy Generator per run, consumed in fixed order:
split FIRST (rng.permutation -> 500 explore / 500 calib / 1000 test / rest
train), then the sample matrices (explore, calib, test).

Preproc:
  'raw'  = y untouched.
  'logz' = y <- log1p(y - min(y) + 1) on the FULL data BEFORE the split, then
           y is z-scored with train stats.
  BOTH preprocs standardize X with StandardScaler fit on train. This follows
  the PCP main.py protocol. It is result-neutral for tree models (monotone
  linear transforms of each feature) and is applied for fidelity only.

QRF: quantile_forest 1.5.0, n_estimators=100, min_samples_split=50 (paper
E.1 literal: "50 samples per node split"). DOCUMENTED AMBIGUITY: ORCA Table 4
says "#leaf", and the PCP repo driver (main.py: min_samples_leaf=50) uses the
leaf reading; here min_samples_split=50 is used per the paper text.

y_min / y_max for DCP / DistSplit / CHR / CDSplit grids: min / max of the
FULL pre-split y (PCP main.py protocol `y_min=min(Y); y_max=max(Y)`). FLAGGED
QUIRK of the referenced implementation: this includes TEST rows.

=========================== SAMPLERS ============================
Two samplers of equal status; the `sampler` column flags each CSV row:
  'iid'    : one u ~ U(0,1) per (row, k); grid inversion (linear interp
             between adjacent grid columns, clip outside the grid ends).
  'shared' : one u_k per sample index k shared across rows, same inversion.
Sample matrices are drawn ONCE per run per (sampler, matrix-set:
explore/calib/test) from the run's rng and SHARED by ORCA and PCP (paired
comparison).

=========================== m-NN PROXY (paper App. A, corrected) ============================
proxy for sample k = mean of the m=5 SMALLEST pairwise distances within the
row's sample cloud INCLUDING the self-distance 0: sort the K=20 pairwise
distances ascending, take the first 5, mean. DIFFERS from the official repo
(sampling.py ranks by the mean of the 6 smallest values, i.e. self + 5
neighbours) -- this is the corrected reading of Appendix A, documented.

=========================== METHOD CONFIGS (9 per run) ============================
ORCA (4 configs: spec x sampler):
  spec 'paper' (PRIMARY): Stage-2 quota tau = ceil(n1*(1-alpha)) = 450 (paper
    p.5 verbatim); Stage-3 threshold = smallest tau with #{S_i <= tau} >=
    n2*(1-alpha) - 1, i.e. the 449th of the 500 order statistics of the calib
    scores S_i = min_r E_ir / Q_r (paper eq (9) read literally); NO
    post-solve tightening; NO span clipping. The Stage-2 program is the exact
    paper eq (7) MILP (d=1, costs E^1, monotone z,
    y_i <= sum_r z_{r, lmin(i,r)}) in the compact HiGHS formulation.
  spec 'author' (sensitivity): quota = ceil((n1+1)*(1-alpha)) = 451;
    Stage-3 threshold = ceil((n2+1)*(1-alpha))-th order statistic (451st),
    the official repo's conformal_quantile; tighten_thresholds applied after
    the solve; merged-union length CLIPPED to the span of train+explore+calib
    y.
  Set: union over ranks of [ranked_sample_r - R_r, ranked_sample_r + R_r],
  R_r = t_alpha * Q_r; eff = merged union length; coverage = y_test in set.
  Zero-radius ranks: degenerate intervals, guarded as in v30 (Q_r=0 handled
  in the score ratio).

PCP (2 configs: sampler only). Score = min_k |y - sample_k| on calib;
threshold = ceil((n2+1)*(1-alpha))-th order statistic of the calib scores.
  App. B: Q(E_{1:n} u {inf}; alpha) -- the (1-alpha)-quantile of the
  augmented empirical distribution; for n=500 this is the 451st order
  statistic. BOTH samplers use the same App. B rule. (DOCUMENTED DIVERGENCE
  from the PCP repo code, which uses torch.quantile linear interpolation;
  the paper App. B rule is used here.) Test set = union of
  [sample_k - t, sample_k + t]; eff = merged length.

CQR (1 config, port of pcp_src/other_baselines/cqr.py verbatim):
  q_lo/q_hi = QRF grid quantiles at levels alpha/2 and 1-alpha/2, read off
  the SAME 99-level grid predict (find_nearest on the grid: alpha=0.1 ->
  levels 0.05 / 0.95). Calib score E = max(q_lo - y, y - q_hi) (negatives
  allowed); threshold q = np.quantile(scores,
  min(1, (1-alpha)*(n+1)/n)) with linear interpolation (the referenced
  implementation's formula, QR_errfun.apply_inverse). Interval
  [q_lo - q, q_hi + q].

CHR (1 config, port of chr_src/chr verbatim: methods.CHR + histogram.Histogram
+ grey_boxes.HistogramAccumulator incl. smallestSubWithSum):
  bbox = our QRF (bbox.predict(X) -> the (n, 99) grid matrix; bbox.get_quantiles()
  -> the 99-level grid); grid_histogram = np.linspace(y_min, y_max, 1000);
  delta_alpha=0.001; intervals=True; randomize=False. calibrate(X_calib,
  Y_calib, alpha) -> scores via acc.calibrate_intervals(Y_calib);
  calibrated_alpha = round(1 - mquantiles(scores, prob=(1-alpha)*(1+1/n2)),
  4), floored at delta_alpha exactly as the PCP repo's CHR usage does
  (main.py context: methods.CHR line 84-85 sets calibrated_alpha=delta_alpha
  when it rounds to 0). predict -> (n, 2) bands; eff = q95-q95 length
  (single interval).

DCP-CQR (1 config, port of pcp_src/other_baselines/dcp.py + utils._estim_dist
verbatim): cdf, inv_cdf = _estim_dist(quantiles_row, percentiles, y_min,
y_max, smooth_tails=True, tau=0.01) per calib row from the QRF grid; scores =
|clip(cdf(Y), 0, 1) - 1/2|; level_adjusted = (1-alpha)*(1+1/n2);
alpha_calibrated = 0.5 - mquantiles(scores, prob=level_adjusted); interval
[inv_cdf(0.5-t), inv_cdf(0.5+t)]. NOTE: _estim_dist consumes the GLOBAL
np.random stream (monotonicity jitter), so np.random.seed(run_seed) is called
at run start to make the port deterministic. FLAGGED: the paper names a
"DCP-CQR hybrid that stabilizes DCP with CQR" (sec 4.3) but gives NO formula
for the hybrid, and the referenced PCP repo contains only plain DCP; this
config is the faithful plain-DCP port and collapses to the full observed
y-span on the heavy-tailed count data (consistent with the paper's own
instability remark). Labeled 'dcp-cqr' pending an author clarification.

DistSplit (1 config, port of pcp_src/other_baselines/dist_split.py verbatim):
  same _estim_dist; scores = cdf(Y); alpha_adjusted = 1-(1-alpha)*(1+1/n2);
  t_lo = mquantiles(scores, prob=alpha_adjusted/2),
  t_up = mquantiles(scores, prob=1-alpha_adjusted/2); interval
  [inv_cdf(t_lo), inv_cdf(t_up)].

CDSplit (1 config): port of cd_split.py minus sympy; density model = the
cde-1.0.1 MixtureDensityNetwork with the paper overrides, rebuilt
self-contained in plain PyTorch (cde is TF1-era, uninstallable):
  n_centers=10, hidden (100,100) tanh with weight_norm, dropout=0.2 (paper;
  cde default 0.0), data_normalization=True (cde), Adam lr=1e-3, batch 256
  (cde defaults), 500 epochs (paper override of cde's n_training_epochs=1000).
  Calibration per cd_split.py verbatim (y-grid 100 pts, t_grid 100 pts,
  profile-density CDE vectors, KMeans(n_clusters=max(round(n_calib/100),1)),
  scores = pdf(X_calib, y_calib), threshold np.quantile(scores, alpha) --
  repo literal, NO finite-sample correction, documented).

CRD (3 configs: ellipse / convexhull / hyperrectangle): official toolbox
conformal_region_designer 0.1.2 (imported from the extracted wheel).
Residuals Z = y - QRF median(0.5) prediction; calibration split cal_one=250 /
cal_two=250 (toolbox two-half protocol); ConformalRegion('kde','meanshift',
TEMPLATE, 0.90); fit + conformalize. Region per test point = union over
fitted shapes of the shape's 1-D {z: score(z) <= 0} interval, offset by the
test median prediction; endpoints read ANALYTICALLY from the adjusted shape
parameters (verified against the package source). The 1-D convex hull is
degenerate for scipy (CHull needs 2-D): _DegenerateHull1D implements the
package's exact 1-D hull semantics, documented.

R2CCP (1 config): official wheel R2CCP-0.0.8 (vendored: downloaded from the
Hub at job start, extracted, sys.path). Paper: "default configuration from
the author's public repository and trained for 500 epochs" -> all repo
defaults, max_epochs=500, seed = run seed. The repo standardizes X and y
internally, bins y into range_size=50 classes over the train range, and
conformalizes interpolated class scores (threshold = plain empirical alpha
quantile, repo literal). Internal train/cal split: repo default
test_size=0.2 of the data passed to fit (i.e. of OUR training split),
re-drawn with the same seed at inference; documented.

=========================== CSV / CLI ============================
CSV rows appended: dataset, preproc, run_id, method_config, coverage, eff,
seconds, status='ok' + diagnostics. method_config strings:
'orca|spec=paper|sampler=iid', 'pcp|sampler=shared', 'cqr', 'chr',
'dcp-cqr', 'distsplit', 'cdsplit', 'crd-ellipse', 'crd-convexhull',
'crd-hyperrectangle', 'r2ccp'.
CLI: --dataset {blog,fb1,fb2} --runs N --preproc {raw,logz} --out CSV
--seed0 0; ORCA_ARGS env override; ORCA_SKIP env (comma-separated method
names whose COMPUTATION is skipped: 'cdsplit'/'r2ccp' for CPU jobs, the
QRF-based names for GPU jobs).
"""

from __future__ import annotations

import argparse
import copy
import math
import os
import sys
import time

import numpy as np
import pandas as pd
from scipy import interpolate
from scipy.stats.mstats import mquantiles  # the actual source import (cqr/dcp/dist_split/chr)

# --- bootstrap the base-pipeline module (hf_jobs materializes only this
# script; the base module is fetched from the pinned Hub commit once) ---
try:
    import run_realdata_v30 as _base  # noqa: F401
except ImportError:
    import urllib.request
    _base_url = ("https://huggingface.co/datasets/Devya27/orca-table3-repro/"
                 "resolve/f1afb40c7ba22b5b93b3b84219c9bbfdf88e7360/"
                 "code/run_realdata.py")
    print(f"[bootstrap] fetching base pipeline module {_base_url}", flush=True)
    _src = urllib.request.urlopen(_base_url, timeout=120).read().decode()
    with open("run_realdata_v30.py", "w") as _f:
        _f.write(_src)
    import run_realdata_v30 as _base  # noqa: F401

from run_realdata_v30 import (  # reused base pipeline
    ALPHA, K, K_NEIGHBOR, MILP_TIME_LIMIT, N_CALIB, N_EXPLORE, N_TEST,
    Q_GRID, build_levels, conformal_quantile, coverage_count,
    covered_by_intervals, clip_region_size, draw_samples, fit_qrf,
    greedy_warm_start, load_dataset, merged_total_length, rank_samples_by_density,
    residual_matrix, tighten_thresholds, _proxy_objective,
)

# --------------------------------------------------------------------------- #
# Port: pcp_src/other_baselines/utils.py :: _estim_dist  (verbatim)
# --------------------------------------------------------------------------- #


def _estim_dist(quantiles, percentiles, y_min, y_max, smooth_tails, tau):
    """ Estimate CDF from list of quantiles, with smoothing """
    # VERBATIM from /work/pcp_src/other_baselines/utils.py.
    # NOTE (documented): consumes the GLOBAL np.random stream
    # (monotonicity jitter) -> np.random.seed(run_seed) at run start.
    noise = np.random.uniform(low=0.0, high=1e-5, size=((len(quantiles),)))
    noise_monotone = np.sort(noise)
    quantiles = quantiles + noise_monotone

    def interp1d(x, y, a, b):
        return interpolate.interp1d(x, y, bounds_error=False,
                                    fill_value=(a, b), assume_sorted=True)

    cdf = interp1d(quantiles, percentiles, 0.0, 1.0)
    inv_cdf = interp1d(percentiles, quantiles, y_min, y_max)

    if smooth_tails:
        # Uniform smoothing of tails (verbatim; quantiles_smooth aliases
        # quantiles, so it is defined even when both idx sets are empty).
        quantiles_smooth = quantiles
        tau_lo = tau
        tau_hi = 1 - tau
        q_lo = inv_cdf(tau_lo)
        q_hi = inv_cdf(tau_hi)
        idx_lo = np.where(percentiles < tau_lo)[0]
        idx_hi = np.where(percentiles > tau_hi)[0]
        if len(idx_lo) > 0:
            quantiles_smooth[idx_lo] = np.linspace(
                quantiles[0], q_lo, num=len(idx_lo))
        if len(idx_hi) > 0:
            quantiles_smooth[idx_hi] = np.linspace(
                q_hi, quantiles[-1], num=len(idx_hi))

        cdf = interp1d(quantiles_smooth, percentiles, 0.0, 1.0)
        inv_cdf = interp1d(percentiles, quantiles_smooth, y_min, y_max)

    # Standardize
    breaks = np.linspace(y_min, y_max, num=1000, endpoint=True)
    cdf_hat = cdf(breaks)
    f_hat = np.diff(cdf_hat)
    f_hat = (f_hat + 1e-6) / (np.sum(f_hat + 1e-6))
    cdf_hat = np.concatenate([[0], np.cumsum(f_hat)])
    cdf = interp1d(breaks, cdf_hat, 0.0, 1.0)
    inv_cdf = interp1d(cdf_hat, breaks, y_min, y_max)

    return cdf, inv_cdf


# --------------------------------------------------------------------------- #
# Port: chr_src/chr/histogram.py :: Histogram  (verbatim, except that the
# black box is our QRF: quantiles_row -> (99,) grid curve)
# --------------------------------------------------------------------------- #


class Histogram:
    def __init__(self, percentiles, breaks):
        self.percentiles = percentiles
        self.breaks = breaks

    def compute_histogram(self, quantiles, ymin, ymax, alpha, smooth_tails=True):
        """Compute pi_hat[j]: the mass between break[j-1] and break[j]."""
        n = quantiles.shape[0]
        B = len(self.breaks) - 1

        pi_hat = np.zeros((n, B + 1))
        percentiles = np.concatenate(([0], self.percentiles, [1]))
        quantiles = np.pad(quantiles, ((0, 0), (1, 1)), 'constant',
                           constant_values=(ymin, ymax))

        for i in range(n):
            cdf, inv_cdf = _estim_dist(quantiles[i], percentiles, y_min=ymin,
                                       y_max=ymax, smooth_tails=smooth_tails,
                                       tau=0.01)
            cdf_hat = cdf(self.breaks)
            pi_hat[i] = np.concatenate([[0], np.diff(cdf_hat)])
            pi_hat[i] = (pi_hat[i] + 1e-6) / (np.sum(pi_hat[i] + 1e-6))

        return pi_hat


# --------------------------------------------------------------------------- #
# Port: chr_src/chr/grey_boxes.py :: smallestSubWithSum + HistogramAccumulator
# (verbatim; randomize branch kept but epsilon=None so it never runs)
# --------------------------------------------------------------------------- #


def smallestSubWithSum(arr, x, include=None):
    """Credit: geeksforgeeks minimum-length subarray with sum >= x."""
    n = len(arr)

    if include is None:
        end_init = 0
        start_max = n
    else:
        end_init = include[1]
        start_max = include[0]

    start_best = 0
    end_best = n
    min_len = n + 1
    start = 0
    curr_sum = np.sum(arr[start:end_init])

    for end in range(end_init, n):
        curr_sum += arr[end]
        while (curr_sum >= x) and (start <= end) and (start <= start_max):
            if (end - start + 1 < min_len):
                min_len = end - start + 1
                start_best = start
                end_best = end
            curr_sum -= arr[start]
            start += 1

    if end_best == n:
        print("Error in smallestSubWithSum(): no solution! This may be a bug.")
        quit()

    return start_best, end_best


class HistogramAccumulator:
    def __init__(self, pi, breaks, alpha, delta_alpha=0.001):
        self.n, self.K = pi.shape
        self.breaks = breaks
        self.pi = pi
        self.alpha = alpha

        self.alpha_grid = np.round(np.arange(delta_alpha, 1.0, delta_alpha), 4)
        self.alpha_grid = np.unique(np.sort(np.concatenate((self.alpha_grid,
                                                            [alpha]))))

        # only used for sets (unused: intervals=True)
        self.order = np.argsort(-pi, axis=1)
        self.ranks = np.empty_like(self.order)
        for i in range(self.n):
            self.ranks[i, self.order[i]] = np.arange(len(self.order[i]))
        self.pi_sort = -np.sort(-pi, axis=1)
        self.Z = np.round(self.pi_sort.cumsum(axis=1), 9)

    def compute_interval_sequence(self, epsilon=None):
        alpha_grid = self.alpha_grid
        n_grid = len(alpha_grid)
        k_star = np.where(alpha_grid == self.alpha)[0][0]
        S_grid = -np.ones((n_grid, self.n, 2)).astype(int)
        S_grid_random = -np.ones((n_grid, self.n, 2)).astype(int)

        S, S_random = self.predict_intervals_single(alpha_grid[k_star],
                                                    epsilon=epsilon)
        S_grid[k_star] = S
        S_grid_random[k_star] = S_random

        for k in range(k_star + 1, n_grid):
            a = S_grid[k - 1, :, 0]
            b = S_grid[k - 1, :, 1]
            S, S_random = self.predict_intervals_single(
                alpha_grid[k], epsilon=epsilon, a=a, b=b)
            S_grid[k] = S
            S_grid_random[k] = S_random

        for k in range(0, k_star)[::-1]:
            alpha = alpha_grid[k]
            S, S_random = self.predict_intervals_single(
                alpha, epsilon=epsilon, include=S_grid_random[k + 1])
            S_grid[k] = S
            S_grid_random[k] = S_random

        return S_grid_random

    def predict_intervals_single(self, alpha, a=None, b=None, include=None,
                                 epsilon=None):
        if a is None:
            a = np.zeros(self.n).astype(int)
        if b is None:
            b = (np.ones(self.n) * len(self.pi[0])).astype(int)
        if include is None:
            include = [None] * self.n

        start = -np.ones(self.n).astype(int)
        end = -np.ones(self.n).astype(int)
        for i in range(self.n):
            start_offset = a[i]
            end_offset = b[i] + 1
            if np.sum(self.pi[i][start_offset:end_offset]) < 1.0 - alpha:
                print("Error: incorrect probability normalization. "
                      "This may be a bug.")
                quit()
            start[i], end[i] = smallestSubWithSum(
                self.pi[i][start_offset:end_offset], 1.0 - alpha,
                include=include[i])
            start[i] += start_offset
            end[i] += start_offset
        S = np.concatenate((start.reshape((len(start), 1)),
                            end.reshape((len(start), 1))), 1)
        S_random = copy.deepcopy(S)

        if (epsilon is not None):
            for i in range(self.n):
                if ((S[i, -1] - S[i, 0]) <= 1):
                    continue
                tot_weight = np.sum(self.pi[i][S[i, 0]:(S[i, -1] + 1)])
                excess_weight = tot_weight - (1.0 - alpha)
                weight_left = self.pi[i][S[i, 0]]
                weight_right = self.pi[i][S[i, -1]]
                if weight_left < weight_right:
                    pi_remove = excess_weight / (weight_left + 1e-5)
                    if epsilon[i] <= pi_remove:
                        S_random[i, 0] += 1
                else:
                    pi_remove = excess_weight / (weight_right + 1e-5)
                    if epsilon[i] <= pi_remove:
                        S_random[i, -1] -= 1

        return S, S_random

    def predict_intervals(self, alpha, epsilon=None):
        bands = np.zeros((self.n, 2))
        S_grid = self.compute_interval_sequence(epsilon=epsilon)
        j_star_idx = np.where(self.alpha_grid <= alpha)[0]
        if len(j_star_idx) == 0:
            S = np.tile(np.arange(self.K), (self.n, 1))
        else:
            j_star = np.max(j_star_idx)
            S = S_grid[j_star]

        # clamp at 0: bin 0 is [ymin, breaks[0]], so a band including bin 0
        # starts at breaks[0] = ymin; S[:,0]-1 == -1 would wrap to breaks[-1]
        # (the original chr code never hits this because its bin 0 always has
        # zero mass; the delta_alpha floor path can include it -- documented)
        bands[:, 0] = self.breaks[np.maximum(S[:, 0] - 1, 0)]
        bands[:, 1] = self.breaks[S[:, -1]]
        return S, bands

    def calibrate_intervals(self, Y, epsilon=None, verbose=False):
        Y = np.atleast_1d(Y)
        n2 = len(Y)
        alpha_max = np.zeros(n2, )
        S_grid = self.compute_interval_sequence(epsilon=epsilon)
        for j in range(len(self.alpha_grid)):
            alpha = self.alpha_grid[j]
            S = S_grid[j]
            band_left = self.breaks[S[:, 0] - 1]
            band_right = self.breaks[S[:, -1]]
            idx_inside = np.where((Y >= band_left) * (Y <= band_right))[0]
            if len(idx_inside) > 0:
                alpha_max[idx_inside] = alpha
        return 1.0 - alpha_max


# --------------------------------------------------------------------------- #
# Fast-fail helpers
# --------------------------------------------------------------------------- #


def _assert_finite(x, name):
    arr = np.asarray(x, dtype=float)
    assert np.all(np.isfinite(arr)), f"{name}: non-finite values"


def _assert_shapes(cond, msg):
    assert cond, msg


# --------------------------------------------------------------------------- #
# Black-box adapter: our quantile_forest QRF seen as a PCP/CHR "bbox"
# --------------------------------------------------------------------------- #


class QrfBbox:
    """Adapter so the ported CHR / DCP / DistSplit code sees a bbox with
    predict(X) -> (n, L) grid matrix and get_quantiles() -> the L levels.
    quantile-forest's batched predict with quantiles=grid does exactly this."""

    def __init__(self, model, grid=None):
        self.model = model
        self.grid = np.asarray(grid if grid is not None else Q_GRID,
                               dtype=float)

    def predict(self, X):
        q = self.model.predict(np.asarray(X, dtype=np.float64),
                               quantiles=list(self.grid))
        return np.asarray(q).reshape(len(X), len(self.grid))

    def get_quantiles(self):
        return self.grid


# --------------------------------------------------------------------------- #
# ORCA (4 configs: spec x sampler)
# --------------------------------------------------------------------------- #


def run_orca(model, y_explore, y_calib, y_test, X_explore, X_calib, X_test,
             rng, sampler="iid", spec="paper", quota=None,
             stage3_rule="paper", apply_tighten=False, clip=False,
             span_clipped=None, S_exp=None, S_cal=None, S_te=None):
    """ORCA. sampler in {'iid','shared'}; spec in {'paper','author'}.
    spec paper  : quota=ceil(n1*(1-alpha))=450, stage3 = paper eq (9)
                  literal (449th of 500 order stats), no tighten, no clip.
    spec author : quota=ceil((n1+1)*(1-alpha))=451, stage3 = 451st order
                  stat (repo conformal_quantile), tighten applied, clip to
                  span(train+explore+calib y).
    Returns (metrics_dict, diagnostics_dict)."""
    t0 = time.time()
    assert spec in ("paper", "author")
    n1 = len(y_explore)
    if quota is None:
        quota = (math.ceil(n1 * (1.0 - ALPHA)) if spec == "paper"
                 else math.ceil((n1 + 1) * (1.0 - ALPHA)))
    assert quota <= n1, f"quota {quota} > n1 {n1}: infeasible quota"
    apply_tighten = apply_tighten or spec == "author"
    clip = clip or spec == "author"

    # -- samples: SHARED per-run matrices (drawn once in one_run) --
    if S_exp is None:
        S_exp = draw_samples(model, X_explore, K, rng, shared=(sampler == "shared"))
    ranked_exp = rank_samples_by_density_corrected(S_exp, K_NEIGHBOR)
    E_explore = residual_matrix(y_explore, ranked_exp)
    _assert_shapes(E_explore.shape == (n1, K), f"ORCA E_explore {E_explore.shape}")
    _assert_finite(E_explore, "ORCA E_explore")

    # -- stage 2: compact HiGHS MILP = paper eq (7) (d=1, costs E^1) --
    E = np.asarray(E_explore, dtype=float)
    levels = build_levels(E)
    if spec == "paper":
        thresholds = solve_orca_milp_paper(E, ALPHA, quota, levels)
    else:
        thresholds = solve_orca_milp_author(E, ALPHA, quota, levels)
    _assert_shapes(np.all(np.isfinite(thresholds)) and np.all(thresholds >= 0),
                   "ORCA thresholds")
    proxy_objective = float(_proxy_objective(thresholds, 1))

    # -- stage 3: split-conformal rescale on calib residuals --
    if S_cal is None:
        S_cal = draw_samples(model, X_calib, K, rng, shared=(sampler == "shared"))
    ranked_cal = rank_samples_by_density_corrected(S_cal, K_NEIGHBOR)
    E_calib = residual_matrix(y_calib, ranked_cal)
    _assert_shapes(E_calib.shape == (len(y_calib), K), "ORCA E_calib shape")
    Q = np.asarray(thresholds, dtype=float)[None, :]
    # Q_r == 0 guard (v30): such a rank covers a point only if E_ir == 0
    # exactly (ratio 0); otherwise the ratio is +inf and the min skips it.
    with np.errstate(divide="ignore", invalid="ignore"):
        ratios_pos = np.where(Q > 0, E_calib / np.where(Q > 0, Q, 1.0), np.inf)
    ratios = np.where(Q > 0, ratios_pos,
                      np.where(E_calib == 0, 0.0, np.inf))
    scores = ratios.min(axis=1)
    _assert_finite(scores, "ORCA calib scores")
    n2 = len(y_calib)
    if stage3_rule == "paper":
        # paper eq (9) literal: smallest tau with #{S_i <= tau} >= n2*(1-alpha) - 1
        k_order = n2 * (1.0 - ALPHA) - 1.0
        idx = int(math.floor(k_order + 1e-9))
        t_alpha = float(np.sort(scores)[idx])
    else:  # 'author': ceil((n2+1)*(1-alpha))-th order statistic
        t_alpha = conformal_quantile(scores, ALPHA)
    _assert_finite(t_alpha, "ORCA t_alpha")
    assert t_alpha >= 0, f"ORCA t_alpha negative: {t_alpha}"
    radii = t_alpha * np.asarray(thresholds, dtype=float)

    # -- test --
    if S_te is None:
        S_te = draw_samples(model, X_test, K, rng, shared=(sampler == "shared"))
    ranked_te = rank_samples_by_density_corrected(S_te, K_NEIGHBOR)[:, :, 0]
    lo = ranked_te - radii[None, :]
    hi = ranked_te + radii[None, :]
    _assert_shapes(lo.shape == (len(y_test), K) and np.all(lo <= hi),
                   "ORCA test intervals")
    eff = np.array([merged_total_length(l, h) for l, h in zip(lo, hi)])
    cov = np.array([covered_by_intervals(y, l, h)
                    for y, l, h in zip(y_test, lo, hi)])
    clipped = False
    if clip:
        span = float(span_clipped) if span_clipped is not None else np.inf
        eff = clip_region_size(eff, span)
        clipped = True

    metrics = {
        "coverage": float(cov.mean()), "eff": float(eff.mean()),
        "seconds": time.time() - t0,
    }
    diag = {
        "threshold": float(t_alpha), "proxy_objective": proxy_objective,
        "quota": quota, "tighten": ("yes" if apply_tighten else "no"),
        "clip": ("yes" if clipped else "no"), "sampler": sampler,
        "spec": spec, "milp_status": "ok",
    }
    return metrics, diag


def solve_orca_milp_paper(E, alpha, quota, levels):
    """Stage-2 MILP = paper eq (7) exactly (compact HiGHS formulation):
    binary z_{r,l} (monotone z_{r,l} >= z_{r,l+1}); y_i <= sum_r
    z_{r, lmin(i,r)}, lmin(i,r) = smallest l with E_(l),r >= E_{i,r};
    cost = sum_r threshold_r (d=1), encoded as level increments;
    sum_i y_i >= quota (450). NO post-solve tightening."""
    from scipy.optimize import Bounds, LinearConstraint, milp
    import scipy.sparse as sp
    E = np.asarray(E, dtype=float)
    n, K_ = E.shape
    n_levels = [len(lv) for lv in levels]
    z_offset = np.cumsum([0] + n_levels)
    nz = int(z_offset[-1])
    n_var = nz + n
    y_offset = nz

    c = np.zeros(n_var)
    for r in range(K_):
        lv = levels[r]
        c[z_offset[r]: z_offset[r] + len(lv)] = np.diff(lv, prepend=0.0)

    # monotonicity z_{r,l} - z_{r,l+1} >= 0
    mono_rows, mono_cols, mono_data = [], [], []
    row = 0
    for r in range(K_):
        for l in range(n_levels[r] - 1):
            mono_rows += [row, row]
            mono_cols += [z_offset[r] + l, z_offset[r] + l + 1]
            mono_data += [1.0, -1.0]
            row += 1
    mono_con = LinearConstraint(
        sp.csr_matrix((mono_data, (mono_rows, mono_cols)), shape=(row, n_var)),
        lb=0.0, ub=np.inf)

    # coverage: y_i <= sum_r z_{r, l_min(i,r)}
    cov_rows, cov_cols, cov_data = [], [], []
    row = 0
    for i in range(n):
        for r in range(K_):
            l_min = int(np.searchsorted(levels[r], E[i, r], side="left"))
            cov_rows.append(row)
            cov_cols.append(z_offset[r] + l_min)
            cov_data.append(1.0)
        cov_rows.append(row)
        cov_cols.append(y_offset + i)
        cov_data.append(-1.0)
        row += 1
    cov_con = LinearConstraint(
        sp.csr_matrix((cov_data, (cov_rows, cov_cols)), shape=(n, n_var)),
        lb=0.0, ub=np.inf)

    # quota: sum_i y_i >= target
    quota_con = LinearConstraint(
        sp.csr_matrix((np.ones(n), (np.zeros(n, dtype=int),
                                    y_offset + np.arange(n))),
                      shape=(1, n_var)), lb=float(quota), ub=np.inf)

    integrality = np.zeros(n_var)
    integrality[:nz] = 1
    res = milp(c=c, constraints=[mono_con, cov_con, quota_con],
               integrality=integrality,
               bounds=Bounds(np.zeros(n_var), np.ones(n_var)),
               options={"time_limit": MILP_TIME_LIMIT,
                        "mip_rel_gap": 0.01, "presolve": True})
    z_sol = np.round(np.asarray(res.x[:nz])) if res.x is not None else None
    if z_sol is None:
        # no incumbent within the budget: greedy warm start fallback (v30)
        thresholds = greedy_warm_start(E, alpha, 1)
        return np.asarray(thresholds, dtype=float)
    thresholds = np.empty(K_)
    for r in range(K_):
        active = np.nonzero(z_sol[z_offset[r]: z_offset[r] + n_levels[r]])[0]
        thresholds[r] = levels[r][active[-1]]
    return thresholds


def solve_orca_milp_author(E, alpha, quota, levels):
    """Official-repo sensitivity path: same MILP with the (n1+1) quota
    (451), then tighten_thresholds applied after the solve."""
    thr = solve_orca_milp_paper(E, alpha, quota, levels)
    thr = tighten_thresholds(E, alpha, thr, levels)
    assert coverage_count(E, thr) >= quota, "tighten lost the quota"
    return np.asarray(thr, dtype=float)


def rank_samples_by_density_corrected(Y_hat, k_neighbor=K_NEIGHBOR):
    """CORRECTED m-NN proxy (paper App. A): mean of the m=5 SMALLEST pairwise
    distances INCLUDING the self-distance 0 (sort the K pairwise distances
    ascending, take the first 5, mean). DIFFERS from the official repo, which
    averages the 6 smallest (self + 5 neighbours). Returns (n, K, 1)."""
    Y_hat = np.asarray(Y_hat, dtype=float)
    assert Y_hat.ndim == 3 and Y_hat.shape[2] == 1, Y_hat.shape
    S = Y_hat[:, :, 0]
    pairwise = np.abs(S[:, :, None] - S[:, None, :])
    proxy = np.sort(pairwise, axis=2)[:, :, :k_neighbor].mean(axis=2)
    idx = np.argsort(proxy, axis=1, kind="stable")
    ranked = np.take_along_axis(S, idx, axis=1)
    return ranked[:, :, None]


# --------------------------------------------------------------------------- #
# PCP (2 configs: sampler only)
# --------------------------------------------------------------------------- #


def run_pcp(model, y_calib, y_test, X_calib, X_test, rng, sampler="iid",
            S_cal=None, S_te=None):
    """Port of pcp/pcp.py cal_type='uniform', with the paper App. B threshold:
    Q(E_{1:n} u {inf}; alpha) = the ceil((n2+1)*(1-alpha))-th order statistic
    of the calib scores (451st of 500). BOTH samplers use this rule. (The PCP
    repo code uses torch.quantile linear interpolation -- documented
    divergence; the paper App. B rule is authoritative here.)
    Returns (metrics_dict, diagnostics_dict)."""
    t0 = time.time()
    if S_cal is None:
        S_cal = draw_samples(model, X_calib, K, rng, shared=(sampler == "shared"))
    E_calib = residual_matrix(y_calib, S_cal)          # (n_cal, K)
    _assert_shapes(E_calib.shape == (len(y_calib), K), "PCP E_calib shape")
    scores = E_calib.min(axis=1)                       # min over k
    _assert_finite(scores, "PCP calib scores")
    n2 = len(y_calib)
    k = int(math.ceil((1.0 - ALPHA) * (n2 + 1)))       # 451
    t = float(np.sort(scores)[min(k, n2) - 1])
    _assert_finite(t, "PCP threshold")
    if S_te is None:
        S_te = draw_samples(model, X_test, K, rng, shared=(sampler == "shared"))
    S_te = np.asarray(S_te, dtype=float)
    if S_te.ndim == 3:
        S_te = S_te[:, :, 0]
    lo = S_te - t
    hi = S_te + t
    assert np.all(lo <= hi), "PCP test intervals"
    _assert_shapes(lo.shape == (len(y_test), K),
                   "PCP test intervals shape")
    eff = np.array([merged_total_length(l, h) for l, h in zip(lo, hi)])
    cov = np.array([covered_by_intervals(y, l, h)
                    for y, l, h in zip(y_test, lo, hi)])
    metrics = {"coverage": float(cov.mean()), "eff": float(eff.mean()),
               "seconds": time.time() - t0}
    diag = {"threshold": t, "proxy_objective": "", "quota": "",
            "tighten": "", "clip": "", "sampler": sampler, "spec": "",
            "milp_status": ""}
    return metrics, diag


# --------------------------------------------------------------------------- #
# CQR (port of pcp_src/other_baselines/cqr.py: QR_errfun + CQR, verbatim,
# with bbox = QrfBbox)
# --------------------------------------------------------------------------- #


def find_nearest(a, a0):
    """Index of element in 1-d array `a` closest to scalar a0 (verbatim)."""
    idx = np.abs(a - a0).argmin()
    return idx


def qr_errfun_apply(prediction, y):
    """QR_errfun.apply (verbatim): E = max(q_lo - y, y - q_hi), negatives allowed."""
    y_lower = prediction[:, 0]
    y_upper = prediction[:, -1]
    error_low = y_lower - y
    error_high = y - y_upper
    return np.maximum(error_high, error_low)


def qr_errfun_apply_inverse(nc, alpha):
    """QR_errfun.apply_inverse (verbatim): np.quantile linear at
    min(1, (1-alpha)(n+1)/n). Returns np.vstack([q, q])."""
    q = np.quantile(nc, np.minimum(1.0, (1.0 - alpha) * (nc.shape[0] + 1.0)
                                   / nc.shape[0]))
    return np.vstack([q, q])


def run_cqr(model, y_calib, y_test, X_calib, X_test, alpha=ALPHA):
    """CQR, port verbatim. bbox.predict -> (n, 99) grid; the two columns are
    picked by find_nearest(grid, alpha/2) and find_nearest(grid, 1-alpha/2)."""
    t0 = time.time()
    bbox = QrfBbox(model)
    grid = bbox.get_quantiles()
    idx_lower = find_nearest(grid, alpha / 2.0)
    idx_upper = find_nearest(grid, 1.0 - alpha / 2.0)

    pred_calib = bbox.predict(X_calib)[:, [idx_lower, idx_upper]]
    scores = qr_errfun_apply(pred_calib, np.asarray(y_calib, dtype=float))
    _assert_finite(scores, "CQR scores")
    q_lo_c, q_hi_c = pred_calib[:, 0], pred_calib[:, 1]
    assert np.all(q_lo_c <= q_hi_c), "CQR: q_lo > q_hi on calib"

    score_correction = qr_errfun_apply_inverse(scores, alpha)
    q_thr = float(score_correction[0, 0])
    _assert_finite(q_thr, "CQR threshold")

    pred_test = bbox.predict(X_test)[:, [idx_lower, idx_upper]]
    q_lo_t, q_hi_t = pred_test[:, 0], pred_test[:, 1]
    assert np.all(q_lo_t <= q_hi_t), "CQR: q_lo > q_hi on test"
    lo = pred_test[:, 0] - score_correction[0, 0]
    hi = pred_test[:, 1] + score_correction[1, 0]
    _assert_shapes(np.all(lo <= hi), "CQR interval sanity lo<=hi")
    eff = float(np.mean(hi - lo))
    cov = float(np.mean((y_test >= lo) & (y_test <= hi)))
    metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0}
    diag = {"threshold": q_thr, "proxy_objective": "", "quota": "",
            "tighten": "", "clip": "", "sampler": "", "spec": "",
            "milp_status": ""}
    return metrics, diag


# --------------------------------------------------------------------------- #
# CHR (port of chr_src/chr/methods.py CHR, verbatim, bbox = QrfBbox)
# --------------------------------------------------------------------------- #


def run_chr(model, y_calib, y_test, X_calib, X_test, y_min, y_max,
            alpha=ALPHA, y_steps=1000, delta_alpha=0.001):
    """CHR with intervals=True, randomize=False. grid_histogram =
    linspace(y_min, y_max, 1000); calibrated_alpha = round(1 - mquantiles(
    scores, prob=(1-alpha)*(1+1/n2)), 4), floored at delta_alpha (PCP repo's
    CHR usage: methods.py line 84-85 rounds and floors at 0 -> delta_alpha)."""
    t0 = time.time()
    bbox = QrfBbox(model)
    grid_histogram = np.linspace(y_min, y_max, num=y_steps, endpoint=True)

    # CHR.__init__ + init_bbox
    assert (np.diff(bbox.get_quantiles()) >= 0).all()
    hist = Histogram(bbox.get_quantiles(), grid_histogram)

    # --- calibrate ---
    q_calib = bbox.predict(X_calib)
    _assert_shapes(q_calib.shape == (len(y_calib), len(bbox.get_quantiles())),
                   "CHR q_calib shape")
    d_calib = hist.compute_histogram(q_calib, y_min, y_max, alpha)
    accumulator = HistogramAccumulator(d_calib, grid_histogram, alpha,
                                       delta_alpha=delta_alpha)
    epsilon = None                       # randomize=False
    scores = accumulator.calibrate_intervals(
        np.asarray(y_calib, dtype=np.float32), epsilon=epsilon)
    _assert_finite(scores, "CHR scores")
    n2 = X_calib.shape[0]
    level_adjusted = (1.0 - alpha) * (1.0 + 1.0 / float(n2))
    calibrated_alpha = np.round(
        1.0 - mquantiles(scores, prob=level_adjusted)[0], 4)
    if calibrated_alpha == 0:            # PCP repo CHR line 84-85
        calibrated_alpha = delta_alpha   # floor at delta_alpha
    calibrated_alpha = float(max(calibrated_alpha, delta_alpha))

    # --- predict ---
    q_new = bbox.predict(X_test)
    d_new = hist.compute_histogram(q_new, y_min, y_max, alpha)
    acc_new = HistogramAccumulator(d_new, grid_histogram, alpha,
                                   delta_alpha=delta_alpha)
    _, bands = acc_new.predict_intervals(calibrated_alpha, epsilon=epsilon)
    lo, hi = bands[:, 0], bands[:, 1]
    _assert_finite(bands, "CHR bands")
    _assert_shapes(np.all(lo <= hi), "CHR interval sanity lo<=hi")
    eff = float(np.mean(hi - lo))        # single-interval length
    cov = float(np.mean((y_test >= lo) & (y_test <= hi)))
    metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0}
    diag = {"threshold": calibrated_alpha, "proxy_objective": "", "quota": "",
            "tighten": "", "clip": "", "sampler": "", "spec": "",
            "milp_status": ""}
    return metrics, diag


# --------------------------------------------------------------------------- #
# DCP (port of pcp_src/other_baselines/dcp.py DCP-CQR, verbatim, bbox = QrfBbox)
# --------------------------------------------------------------------------- #


def run_dcp(model, y_calib, y_test, X_calib, X_test, y_min, y_max,
            alpha=ALPHA):
    """DCP-CQR: scores = |clip(cdf(Y),0,1) - 1/2|;
    alpha_calibrated = 0.5 - mquantiles(scores, prob=(1-alpha)*(1+1/n2));
    interval [inv_cdf(0.5-t), inv_cdf(0.5+t)]. _estim_dist consumes the
    global np.random stream -> np.random.seed(run_seed) at run start."""
    t0 = time.time()
    bbox = QrfBbox(model)
    percentiles = bbox.get_quantiles()
    n2 = X_calib.shape[0]

    quantiles = bbox.predict(X_calib)
    cdf_values = np.array([0.0] * n2)
    for i in range(n2):
        cdf, inv_cdf = _estim_dist(quantiles[i], percentiles, y_min=y_min,
                                   y_max=y_max, smooth_tails=True, tau=0.01)
        cdf_values[i] = cdf(np.float64(y_calib[i]))
    scores = np.abs(np.clip(cdf_values, 0, 1) - 1 / 2)
    _assert_finite(scores, "DCP scores")
    level_adjusted = (1.0 - alpha) * (1.0 + 1.0 / float(n2))
    alpha_calibrated = 0.5 - mquantiles(scores, prob=level_adjusted)[0]
    alpha_calibrated = float(alpha_calibrated)
    t = 0.5 - alpha_calibrated

    quantiles_te = bbox.predict(X_test)
    pred = np.zeros((len(y_test), 2))
    for i in range(len(y_test)):
        cdf, inv_cdf = _estim_dist(quantiles_te[i], percentiles, y_min=y_min,
                                   y_max=y_max, smooth_tails=True, tau=0.01)
        pred[i, 0] = inv_cdf(0.5 - t)
        pred[i, 1] = inv_cdf(0.5 + t)
    lo, hi = pred[:, 0], pred[:, 1]
    _assert_finite(pred, "DCP bands")
    _assert_shapes(np.all(lo <= hi), "DCP interval sanity lo<=hi")
    eff = float(np.mean(hi - lo))
    cov = float(np.mean((y_test >= lo) & (y_test <= hi)))
    metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0}
    diag = {"threshold": alpha_calibrated, "proxy_objective": "", "quota": "",
            "tighten": "", "clip": "", "sampler": "", "spec": "",
            "milp_sec": "", "milp_status": ""}
    return metrics, diag


# --------------------------------------------------------------------------- #
# DistSplit (port of pcp_src/other_baselines/dist_split.py, verbatim,
# bbox = QrfBbox)
# --------------------------------------------------------------------------- #


def run_distsplit(model, y_calib, y_test, X_calib, X_test, y_min, y_max,
                  alpha=ALPHA):
    """DistSplit: scores = cdf(Y); alpha_adjusted = 1-(1-alpha)*(1+1/n2);
    t_lo = mquantiles(scores, prob=alpha_adjusted/2),
    t_up = mquantiles(scores, prob=1-alpha_adjusted/2);
    interval [inv_cdf(t_lo), inv_cdf(t_up)]."""
    t0 = time.time()
    bbox = QrfBbox(model)
    percentiles = bbox.get_quantiles()
    n2 = X_calib.shape[0]

    quantiles = bbox.predict(X_calib)
    scores = np.array([0.0] * n2)
    for i in range(n2):
        cdf, inv_cdf = _estim_dist(quantiles[i], percentiles, y_min=y_min,
                                   y_max=y_max, smooth_tails=True, tau=0.01)
        scores[i] = cdf(np.float64(y_calib[i]))
    _assert_finite(scores, "DistSplit scores")
    alpha_adjusted = 1 - (1 - alpha) * (1.0 + 1.0 / float(n2))
    t_lo = mquantiles(scores, prob=alpha_adjusted / 2)[0]
    t_up = mquantiles(scores, prob=1.0 - alpha_adjusted / 2)[0]
    t_lo, t_up = float(t_lo), float(t_up)
    assert t_lo <= t_up, f"DistSplit t_lo {t_lo} > t_up {t_up}"

    quantiles_te = bbox.predict(X_test)
    pred = np.zeros((len(y_test), 2))
    for i in range(len(y_test)):
        cdf, inv_cdf = _estim_dist(quantiles_te[i], percentiles, y_min=y_min,
                                   y_max=y_max, smooth_tails=True, tau=0.01)
        pred[i, 0] = inv_cdf(t_lo)
        pred[i, 1] = inv_cdf(t_up)
    lo, hi = pred[:, 0], pred[:, 1]
    _assert_finite(pred, "DistSplit bands")
    _assert_shapes(np.all(lo <= hi), "DistSplit interval sanity lo<=hi")
    eff = float(np.mean(hi - lo))
    cov = float(np.mean((y_test >= lo) & (y_test <= hi)))
    metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0}
    diag = {"threshold": f"{t_lo},{t_up}", "proxy_objective": "", "quota": "",
            "tighten": "", "clip": "", "sampler": "", "spec": "",
            "milp_status": ""}
    return metrics, diag


# --------------------------------------------------------------------------- #
# CDSplit (port of pcp_src/other_baselines/cd_split.py minus sympy; the density
# model is the cde-1.0.1 MixtureDensityNetwork with the paper overrides,
# rebuilt self-contained in plain PyTorch because cde is not installable here)
# --------------------------------------------------------------------------- #


class MDN:
    """MixtureDensityNetwork matching cde 1.0.1 exactly, with the paper
    overrides: hidden (100,100) with weight_norm -> tanh -> Dropout(0.2) per
    layer, final Linear -> 2*n_centers + n_centers outputs (locs, scales,
    logits), Adam lr=1e-3, fixed 500 epochs, batch 256, z-score normalization
    of X and Y with the train stats (cde fit semantics)."""

    def __init__(self, ndim_x, n_centers=10, hidden_sizes=(100, 100),
                 dropout=0.2, seed=0):
        import torch
        try:    # torch>=2.x moved weight_norm to parametrizations
            from torch.nn.utils import weight_norm as _wn
            _wn(torch.nn.Linear(2, 2))
        except Exception:
            from torch.nn.utils.parametrizations import weight_norm as _wn
        self.n_centers = n_centers
        torch.manual_seed(seed)
        layers, in_dim = [], ndim_x
        for h in hidden_sizes:
            layers.append(_wn(torch.nn.Linear(in_dim, h)))
            layers.append(torch.nn.Tanh())
            layers.append(torch.nn.Dropout(dropout))
            in_dim = h
        self.net = torch.nn.Sequential(*layers)
        self.head = torch.nn.Linear(in_dim, 2 * n_centers + n_centers)
        self.x_mean = self.x_std = self.y_mean = self.y_std = None

    def forward(self, x):
        import torch
        out = self.head(self.net(x))
        k = self.n_centers
        locs = out[:, :k]
        scales = torch.nn.functional.softplus(out[:, k: 2 * k]) + 1e-8
        logits = out[:, 2 * k:]
        return locs, scales, logits

    def fit(self, X, Y, epochs=500, batch_size=256, lr=1e-3):
        import math
        import torch
        from torch.utils.data import DataLoader, TensorDataset
        X = np.asarray(X, dtype=float)
        Y = np.asarray(Y, dtype=float).reshape(-1, 1)
        # z-score normalization with the TRAIN stats (stored for pdf())
        self.x_mean, self.x_std = X.mean(axis=0), X.std(axis=0) + 1e-8
        self.y_mean, self.y_std = Y.mean(axis=0), Y.std(axis=0) + 1e-8
        Xn = (X - self.x_mean) / self.x_std
        Yn = (Y - self.y_mean) / self.y_std
        ds = TensorDataset(torch.as_tensor(Xn, dtype=torch.float32),
                           torch.as_tensor(Yn, dtype=torch.float32))
        dl = DataLoader(ds, batch_size=batch_size, shuffle=True)
        opt = torch.optim.Adam(list(self.net.parameters()) +
                               list(self.head.parameters()), lr=lr)
        for ep in range(epochs):                 # fixed 500 epochs, no scheduler
            for xb, yb in dl:
                opt.zero_grad()
                locs, scales, logits = self.forward(xb)
                log_norm = (-0.5 * ((yb - locs) / scales) ** 2
                            - torch.log(scales)
                            - 0.5 * math.log(2.0 * math.pi))
                comp = torch.log_softmax(logits, dim=1) + log_norm
                # cde _log_mixture_density, computed on the NORMALIZED y
                nll = -(torch.logsumexp(comp, dim=1)).mean()
                nll.backward()
                opt.step()
            if (ep + 1) % 100 == 0:
                print(f"    [mdn] epoch {ep + 1}/{epochs} "
                      f"nll={nll.item():.4f}", flush=True)
        return self

    def pdf(self, X, y):
        """X (n,d) numpy, y (n,1) numpy -> (n,) density in ORIGINAL y units
        (de-normalization factor exp(-sum(log(y_std + 1e-8))), cde
        semantics)."""
        import torch
        X = np.asarray(X, dtype=float)
        y = np.asarray(y, dtype=float).reshape(-1, 1)
        Xn = (X - self.x_mean) / self.x_std
        yn = (y - self.y_mean) / self.y_std
        with torch.no_grad():
            locs, scales, logits = self.forward(
                torch.as_tensor(Xn, dtype=torch.float32))
            log_norm = (-0.5 * ((torch.as_tensor(yn, dtype=torch.float32)
                                 - locs) / scales) ** 2
                        - torch.log(scales)
                        - 0.5 * math.log(2.0 * math.pi))
            log_pdf = torch.logsumexp(
                torch.log_softmax(logits, dim=1) + log_norm, dim=1).numpy()
        return np.exp(log_pdf - float(np.sum(np.log(self.y_std + 1e-8))))


def _cds_profile_density(t_grid, y_grid, X, model):
    """cd_split.profile_density verbatim (the sympy part is not needed here)."""
    y_num, n_levels = len(y_grid), len(t_grid)
    delta_y = y_grid[2] - y_grid[1]
    n, n_feats = X.shape
    X_rep = np.tile(X, y_num).reshape(n * y_num, n_feats)
    y_grid_rep = np.tile(y_grid, n).reshape(n * y_num, 1)
    pdf_grid = model.pdf(X_rep, y_grid_rep).reshape(n, y_num)
    cde = []
    for t in t_grid:
        cde_t = np.where(pdf_grid >= t, pdf_grid, 0.0).sum(
            axis=1, keepdims=True) * delta_y
        cde.append(cde_t)
    return np.concatenate(cde, axis=1)


def _cds_union(intervals):
    """sympy union(...) replacement: merge overlapping/adjacent intervals."""
    merged = []
    for lo, hi in sorted(intervals):
        if merged and lo <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], hi)
        else:
            merged.append([lo, hi])
    return merged


def run_cdsplit(model, y_train, y_calib, y_test, X_train, X_calib, X_test,
                y_min, y_max, seed, alpha=ALPHA):
    """CD_split, following cd_split.py verbatim minus sympy: MDN fit on
    (X_train, y_train) for 500 epochs; y-grid = linspace(y_min, y_max, 100)
    with y_min/y_max the jittered-full-y bounds; t_grid = linspace(0, max pdf
    over train, 100); profile_density CDE vectors for calib;
    KMeans(n_clusters=max(round(n_calib/100), 1), random_state=seed);
    calib scores = pdf(X_calib, y_calib); per test point:
    ths = np.quantile(scores of the same cluster, alpha) (repo literal: NO
    finite-sample correction); test set = union of y-grid points with
    pdf >= ths expanded by the grid step; eff = merged length."""
    t0 = time.time()
    from sklearn.cluster import KMeans
    mdn = MDN(ndim_x=X_train.shape[1], n_centers=10, hidden_sizes=(100, 100),
              dropout=0.2, seed=seed)
    mdn.fit(X_train, np.asarray(y_train, dtype=float).reshape(-1, 1),
            epochs=500, batch_size=256, lr=1e-3)
    y_grid = np.linspace(y_min, y_max, 100)
    delta_y = y_grid[1] - y_grid[0]
    n_calib = X_calib.shape[0]
    n_clusters = max(round(n_calib / 100), 1)

    cde_train = mdn.pdf(X_train,
                        np.asarray(y_train, dtype=float).reshape(-1, 1))
    t_grid = np.linspace(0, max(cde_train), 100)

    cde_calib = _cds_profile_density(t_grid, y_grid, X_calib, mdn)
    kmeans = KMeans(n_clusters=n_clusters, random_state=seed).fit(cde_calib)
    calib_class = kmeans.predict(cde_calib)
    calib_scores = mdn.pdf(X_calib,
                           np.asarray(y_calib, dtype=float).reshape(-1, 1))

    cde_test = _cds_profile_density(t_grid, y_grid, X_test, mdn)
    test_class = kmeans.predict(cde_test)
    n_test = len(X_test)
    pdf_test_grid = mdn.pdf(
        np.tile(X_test, len(y_grid)).reshape(n_test * len(y_grid), -1),
        np.tile(y_grid, n_test).reshape(-1, 1),
    ).reshape(n_test, len(y_grid))

    effs, covs = [], []
    for i, tc in enumerate(test_class):
        scores = calib_scores[calib_class == tc]
        if len(scores) == 0:                     # empty cluster guard
            scores = calib_scores
        ths = np.quantile(scores, alpha)
        yi_mask = pdf_test_grid[i] >= ths
        bands = _cds_union([(m - delta_y, m + delta_y)
                            for m in y_grid[yi_mask]])
        effs.append(sum(hi - lo for lo, hi in bands))
        covs.append(any(lo <= y_test[i] <= hi for lo, hi in bands))
    cov = float(np.mean(covs))
    eff = float(np.mean(effs))
    _assert_finite(np.array([cov, eff]), "CDSplit metrics")
    metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0}
    diag = {"threshold": alpha, "proxy_objective": "", "quota": "",
            "tighten": "", "clip": "", "sampler": "", "spec": "",
            "milp_status": ""}
    return metrics, diag


# --------------------------------------------------------------------------- #
# CRD (Conformal Region Designer toolbox, wheel extracted; IMPORTED, not
# ported). Residuals Z = y - median(QRF); cal split 250/250.
# --------------------------------------------------------------------------- #

_CRD_PKG_PATH = os.environ.get(
    "CRD_PKG_PATH", "/work/pkgsrc/crd_dl/extracted")


class _DegenerateHull1D:
    """1-D convex hull in the exact semantics of the package's
    ConvexHullTemplate. scipy CHull cannot consume 1-D input, so the 1-D
    hull of a cluster is the interval [min, max]; its halfspace score is
    max(z - hi, lo - z) (the package's X@hyp_a.T + hyp_b form restricted to
    the two 1-D halfspaces), and adjust_shape(m) (hyp_b -= m) widens the
    interval by m on BOTH sides. Documented as the 1-D degenerate case of
    the referenced implementation."""

    def __init__(self):
        self.lo = None
        self.hi = None

    def fit_shape(self, X):
        X = np.asarray(X, dtype=float).reshape(-1)
        self.lo = float(X.min())
        self.hi = float(X.max())

    def score_points(self, Z):
        z = np.asarray(Z, dtype=float).reshape(-1)
        return np.maximum(z - self.hi, self.lo - z)

    def conformalize(self, delta, Z_cal_two):
        from conformal_region_designer.utils import conformalized_quantile
        scores = self.score_points(Z_cal_two)
        inflation = np.quantile(scores,
                                conformalized_quantile(len(scores), delta))
        self.lo -= inflation
        self.hi += inflation
        return self.lo, self.hi

    def adjust_shape(self, score_margin):
        self.lo -= score_margin
        self.hi += score_margin

    def volume(self):
        return self.hi - self.lo


def _crd_import():
    import sys
    try:
        from conformal_region_designer.conformity_optimizer import (
            ConformalRegion,)
    except ImportError:
        # vendored install of the official toolbox (pinned 0.1.2): PyPI wheel
        # extracted to a temp dir (deps are numpy/scipy/scikit-learn only)
        import json
        import urllib.request
        import zipfile
        dest = os.environ.get("CRD_PKG_DIR", "/tmp/crd_pkg")
        if not os.path.exists(os.path.join(
                dest, "conformal_region_designer", "conformity_optimizer.py")):
            os.makedirs(dest, exist_ok=True)
            with urllib.request.urlopen(
                    "https://pypi.org/pypi/conformal-region-designer/0.1.2/json",
                    timeout=60) as r:
                meta = json.load(r)
            whl_url = next(u["url"] for u in meta["urls"]
                           if u["filename"].endswith("py3-none-any.whl"))
            whl = os.path.join(dest, os.path.basename(whl_url))
            print(f"[crd] downloading {whl_url}", flush=True)
            urllib.request.urlretrieve(whl_url, whl)
            with zipfile.ZipFile(whl) as zf:
                zf.extractall(dest)
        if dest not in sys.path:
            sys.path.insert(0, dest)
        from conformal_region_designer.conformity_optimizer import (
            ConformalRegion,)
    from conformal_region_designer.shapes import hyperrectangle as _hr
    if not getattr(_hr, "_orca_patched", False):
        _orig_hr_fit = _hr.HyperrectangleTemplate.fit_shape

        def _hr_fit_safe(self, Z):
            _orig_hr_fit(self, Z)
            # degenerate 1-D cluster (all density points identical):
            # (max-min)/max(max-min) = 0/0 = NaN. Take the limit behaviour
            # aspect_ratio -> 1 (interval collapses to a point), documented
            # as a NaN guard on the referenced implementation.
            ar = np.asarray(self.aspect_ratio, dtype=float)
            if not np.all(np.isfinite(ar)):
                self.aspect_ratio = np.ones_like(ar)

        _hr.HyperrectangleTemplate.fit_shape = _hr_fit_safe
        _hr._orca_patched = True
    return ConformalRegion


def run_crd(model, y_calib, y_test, X_calib, X_test, y_min, y_max, tmpl, seed,
            delta=0.90):
    """CRD via the official toolbox (conformal_region_designer 0.1.2), the
    paper's KDE/meanshift pipeline: residuals Z = y - QRF median(0.5)
    prediction; calibration split cal_one = 250 / cal_two = 250 (the
    toolbox's two-half protocol); ConformalRegion('kde','meanshift',
    TEMPLATE, 0.90); fit + conformalize. Region per test point = union over
    fitted shapes of the shape's 1-D {z : score(z) <= 0} interval, offset by
    the test median prediction. Interval endpoints are read ANALYTICALLY
    from the adjusted shape parameters (verified against the package
    source): hyperrectangle [min, max] (adjust_shape inflates both bounds);
    ellipse center +- sqrt(score_margin / Q) (score (z-c)^2*Q/sm - 1 <= 0);
    convex hull via _DegenerateHull1D (1-D degenerate case, documented).
    eff = merged union length (shift-invariant across test points);
    coverage = y_test inside."""
    import math
    t0 = time.time()
    ConformalRegion = _crd_import()
    med_cal = np.asarray(model.predict(X_calib, quantiles=0.5),
                         dtype=float).ravel()
    Z_cal = np.asarray(y_calib, dtype=float) - med_cal
    cal_one = Z_cal[:250].reshape(-1, 1)
    cal_two = Z_cal[250:].reshape(-1, 1)
    med_test = np.asarray(model.predict(X_test, quantiles=0.5),
                          dtype=float).ravel()
    np.random.seed(seed)     # ConformalRegion has no internal seed
    if tmpl == "convexhull":
        pcr = ConformalRegion("kde", "meanshift", _DegenerateHull1D, delta)
    else:
        pcr = ConformalRegion("kde", "meanshift", tmpl, delta)
    pcr.fit(cal_one)
    pcr.conformalize(cal_two)

    intervals = []
    for shape in pcr.shapes:
        if tmpl == "hyperrectangle":
            lo = float(np.asarray(shape.min).ravel()[0])
            hi = float(np.asarray(shape.max).ravel()[0])
        elif tmpl == "ellipse":
            c = float(np.asarray(shape.center).ravel()[0])
            sm = float(shape.score_margin)
            q00 = float(np.asarray(shape.Q).ravel()[0])
            if q00 <= 0.0 or sm <= 0.0:
                raise ValueError(
                    f"degenerate ellipse Q={q00} score_margin={sm}")
            r = math.sqrt(sm / q00)
            lo, hi = c - r, c + r
        elif tmpl == "convexhull":
            lo, hi = float(shape.lo), float(shape.hi)
        else:
            raise ValueError(tmpl)
        intervals.append((lo, hi))
    merged = _cds_union(intervals)
    eff = float(sum(hi - lo for lo, hi in merged))
    zs = np.asarray(y_test, dtype=float) - med_test
    cov = float(np.mean([any(lo <= z <= hi for lo, hi in merged)
                         for z in zs]))
    _assert_finite(np.array([cov, eff]), f"CRD-{tmpl} metrics")
    metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0}
    diag = {"threshold": delta, "proxy_objective": "", "quota": "",
            "tighten": "", "clip": "", "sampler": "", "spec": "",
            "milp_status": ""}
    return metrics, diag


# --------------------------------------------------------------------------- #
# R2CCP (official wheel R2CCP-0.0.8, vendored at job start: downloaded from
# the Hub, extracted to a temp dir, sys.path). Paper: "default configuration
# from the author's public repository and trained for 500 epochs".
# --------------------------------------------------------------------------- #

R2CCP_PIN = "R2CCP==0.0.8"  # the official authors' wheel, pinned


def _r2ccp_import():
    import json
    import urllib.request
    import zipfile
    dest = os.environ.get("R2CCP_PKG_DIR", "/tmp/r2ccp_pkg")
    if not os.path.exists(os.path.join(dest, "R2CCP", "main.py")):
        os.makedirs(dest, exist_ok=True)
        # locate the official wheel on PyPI (version-pinned), download,
        # extract; the package imports directly from the extracted dir
        # (R2CCP never imports its declared pyinterval dependency at
        # runtime -- verified against the 0.0.8 wheel source)
        with urllib.request.urlopen(
                "https://pypi.org/pypi/R2CCP/0.0.8/json", timeout=60) as r:
            meta = json.load(r)
        whl_url = next(u["url"] for u in meta["urls"]
                       if u["filename"].endswith("py3-none-any.whl"))
        whl = os.path.join(dest, os.path.basename(whl_url))
        if not os.path.exists(whl):
            print(f"[r2ccp] downloading {whl_url} -> {whl}", flush=True)
            urllib.request.urlretrieve(whl_url, whl)
        with zipfile.ZipFile(whl) as zf:
            zf.extractall(dest)
    if dest not in sys.path:
        sys.path.insert(0, dest)
    from R2CCP.main import R2CCP
    return R2CCP


def run_r2ccp(X_train, y_train, X_test, y_test, seed, max_epochs=500):
    """R2CCP with the official wheel: repo defaults, max_epochs=500 (paper),
    seed = run seed. The repo standardizes X and y internally, bins y into
    range_size=50 classes over the train range, splits its own calibration
    (test_size=0.2 of the data passed to fit, same seed at inference), and
    conformalizes interpolated class scores (threshold = plain empirical
    alpha quantile, repo literal). Returns per-point union lengths."""
    t0 = time.time()
    R2CCP = _r2ccp_import()
    os.makedirs("/tmp/r2ccp_models", exist_ok=True)
    model = R2CCP({"model_path": f"/tmp/r2ccp_models/m_{seed}.pth",
                   "max_epochs": max_epochs, "seed": seed})
    model.fit(np.asarray(X_train, dtype=float),
              np.asarray(y_train, dtype=float))
    coverages, lengths = model.get_coverage_length(
        np.asarray(X_test, dtype=float), np.asarray(y_test, dtype=float))
    cov = float(np.mean(np.asarray(coverages, dtype=float)))
    eff = float(np.mean(np.asarray(lengths, dtype=float)))
    _assert_finite(np.array([cov, eff]), "R2CCP metrics")
    metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0}
    diag = {"threshold": ALPHA, "proxy_objective": "", "quota": "",
            "tighten": "", "clip": "", "sampler": "", "spec": "",
            "milp_status": ""}
    return metrics, diag


# --------------------------------------------------------------------------- #
# One run
# --------------------------------------------------------------------------- #

QRF_DEPENDENT = ("orca", "pcp", "cqr", "chr", "dcp-cqr", "distsplit",
                 "crd-ellipse", "crd-convexhull", "crd-hyperrectangle")


def _run_config(out, name, spec, sampler, fn):
    """Run one method-config. A per-config failure (e.g. the CRD toolbox's
    degenerate-ellipse case on one seed: adjust_shape(m) with m < -1 makes
    score_margin negative and sqrt(sm/Q) undefined -- undefined behavior of
    the referenced implementation) is recorded as a status='error' row with
    the exception as diagnostics, instead of killing the 30-run job. Failed
    rows are labeled in the CSV and excluded from summaries (never counted
    as successful repetitions)."""
    try:
        m, d = fn()
        out.append((name, spec, sampler, m, d))
    except Exception as exc:  # noqa: BLE001
        m = {"coverage": float("nan"), "eff": float("nan"), "seconds": 0.0}
        d = {"threshold": f"{type(exc).__name__}: {exc}"[:120],
             "proxy_objective": "", "quota": "", "tighten": "",
             "clip": "", "sampler": sampler, "spec": spec,
             "milp_status": "error"}
        out.append((name, spec, sampler, m, d))
        print(f"[config-error] {name}|{spec}|{sampler}: "
              f"{type(exc).__name__}: {exc}", flush=True)


def _orca_skip_set():
    import os as _os
    return set(x for x in _os.environ.get("ORCA_SKIP", "").split(",") if x)


def one_run(dataset, X, y_full, run_id, seed0, preproc, leaf_mode="split"):
    """All method-configs for one run (ORCA_SKIP controls which run).
    Returns a list of CSV row dicts."""
    seed = seed0 + run_id
    _skip = _orca_skip_set()
    rng = np.random.default_rng(seed)
    np.random.seed(seed)      # DCP/DistSplit/CHR _estim_dist jitter stream

    # -- split FIRST from the rng stream --
    perm = rng.permutation(len(y_full))
    i_explore = perm[:N_EXPLORE]
    i_calib = perm[N_EXPLORE: N_EXPLORE + N_CALIB]
    i_test = perm[N_EXPLORE + N_CALIB: N_EXPLORE + N_CALIB + N_TEST]
    i_train = perm[N_EXPLORE + N_CALIB + N_TEST:]
    _assert_shapes(len(np.unique(perm)) == len(y_full),
                   "split: permutation not unique")

    y = y_full
    if preproc == "logz":
        # y transform on the FULL data before the split, then z-score with
        # train stats
        y = np.log1p(y - y.min() + 1.0)

    X_train, X_explore, X_calib, X_test = (X[i_train], X[i_explore],
                                           X[i_calib], X[i_test])
    y_train, y_explore, y_calib, y_test = (y[i_train], y[i_explore],
                                           y[i_calib], y[i_test])

    # -- StandardScaler fit on train (both preprocs; PCP main.py protocol) --
    from sklearn.preprocessing import StandardScaler
    scaler = StandardScaler().fit(X_train)
    X_train = scaler.transform(X_train)
    X_explore = scaler.transform(X_explore)
    X_calib = scaler.transform(X_calib)
    X_test = scaler.transform(X_test)
    if preproc == "logz":
        mu_y, sd_y = y_train.mean(), y_train.std()
        y_train = (y_train - mu_y) / sd_y
        y_explore = (y_explore - mu_y) / sd_y
        y_calib = (y_calib - mu_y) / sd_y
        y_test = (y_test - mu_y) / sd_y

    # y jitter (referenced-implementation protocol, PCP main.py): seeded
    # jitter of the FULL y BEFORE any y_min/y_max consumer. Order for logz:
    # (1) raw jitter, (2) log1p, (3) train-stats z-score (split arrays above).
    np.random.seed(seed)
    y_full = y_full + 1e-6 * np.random.normal(size=y_full.shape)
    if preproc == "logz":
        y_full = np.log1p(y_full - y_full.min() + 1.0)

    # y_min / y_max: min/max of the JITTERED full y (PCP main.py protocol;
    # includes test rows -- flagged quirk), mapped to z units for logz
    y_min = float(np.min(y_full))
    y_max = float(np.max(y_full))
    if preproc == "logz":
        y_min = (y_min - mu_y) / sd_y
        y_max = (y_max - mu_y) / sd_y

    # -- fresh QRF every run (only if a QRF-dependent config is active) --
    run_qrf = any(m not in _skip for m in QRF_DEPENDENT)
    model = None
    qrf_sec = 0.0
    if run_qrf:
        t0 = time.time()
        model = fit_qrf(X_train, y_train, seed=seed, leaf_mode=leaf_mode)
        qrf_sec = time.time() - t0
        print(f"[run {run_id}] QRF fit: {qrf_sec:.1f}s "
              f"(train n={len(y_train)})", flush=True)

    # -- span of train+explore+calib y (clip target for spec=author) --
    y_no_test = np.concatenate([y_train, y_explore, y_calib])
    span_clipped = float(y_no_test.max() - y_no_test.min())

    # -- shared sample matrices: drawn ONCE per run per (sampler, set) --
    samples = {}
    if run_qrf:
        for sampler in ("iid", "shared"):
            for setname, Xs in (("explore", X_explore), ("calib", X_calib),
                                ("test", X_test)):
                samples[(sampler, setname)] = draw_samples(
                    model, Xs, K, rng, shared=(sampler == "shared"))

    out = []
    # ---- ORCA x {paper, author} x {iid, shared} ----
    if "orca" not in _skip:
        for spec in ("paper", "author"):
            for sampler in ("iid", "shared"):
                _run_config(out, "orca", spec, sampler,
                            lambda: run_orca(model, y_explore, y_calib, y_test,
                                             X_explore, X_calib, X_test, rng,
                                             sampler=sampler, spec=spec,
                                             S_exp=samples[(sampler, "explore")],
                                             S_cal=samples[(sampler, "calib")],
                                             S_te=samples[(sampler, "test")],
                                             span_clipped=span_clipped))
    # ---- PCP x {iid, shared} ----
    if "pcp" not in _skip:
        for sampler in ("iid", "shared"):
            _run_config(out, "pcp", "", sampler,
                        lambda: run_pcp(model, y_calib, y_test, X_calib,
                                        X_test, rng, sampler=sampler,
                                        S_cal=samples[(sampler, "calib")],
                                        S_te=samples[(sampler, "test")]))
    # ---- CQR ----
    if "cqr" not in _skip:
        _run_config(out, "cqr", "", "",
                    lambda: run_cqr(model, y_calib, y_test, X_calib, X_test))
    # ---- CHR ----
    if "chr" not in _skip:
        _run_config(out, "chr", "", "",
                    lambda: run_chr(model, y_calib, y_test, X_calib, X_test,
                                    y_min, y_max))
    # ---- DCP ----
    if "dcp-cqr" not in _skip:
        _run_config(out, "dcp-cqr", "", "",
                    lambda: run_dcp(model, y_calib, y_test, X_calib, X_test,
                                    y_min, y_max))
    # ---- DistSplit ----
    if "distsplit" not in _skip:
        _run_config(out, "distsplit", "", "",
                    lambda: run_distsplit(model, y_calib, y_test, X_calib,
                                          X_test, y_min, y_max))
    # ---- CDSplit ----
    if "cdsplit" not in _skip:
        _run_config(out, "cdsplit", "", "",
                    lambda: run_cdsplit(model, y_train, y_calib, y_test,
                                        X_train, X_calib, X_test,
                                        y_min, y_max, seed))
    # ---- CRD (3 shape templates) ----
    for tmpl in ("ellipse", "convexhull", "hyperrectangle"):
        if f"crd-{tmpl}" not in _skip:
            _run_config(out, f"crd-{tmpl}", "", "",
                        lambda: run_crd(model, y_calib, y_test, X_calib,
                                        X_test, y_min, y_max, tmpl, seed))
    # ---- R2CCP ----
    if "r2ccp" not in _skip:
        # max_epochs: the paper's 500; ORCA_R2CCP_EPOCHS exists ONLY for
        # plumbing smoke tests and must stay unset in real runs
        ep = int(os.environ.get("ORCA_R2CCP_EPOCHS", "500"))
        _run_config(out, "r2ccp", "", "",
                    lambda: run_r2ccp(X_train, y_train, X_test, y_test, seed,
                                      max_epochs=ep))

    rows = []
    for method, spec, sampler, m, d in out:
        mc = (f"orca|spec={spec}|sampler={sampler}" if method == "orca"
              else f"pcp|sampler={sampler}" if method == "pcp" else method)
        rows.append({
            "dataset": dataset, "preproc": preproc, "run_id": run_id,
            "method_config": mc, "coverage": m["coverage"], "eff": m["eff"],
            "seconds": m["seconds"],
            "status": ("error" if d.get("milp_status") == "error" else "ok"),
            "threshold": d["threshold"], "proxy_objective": d["proxy_objective"],
            "quota": d["quota"], "tighten": d["tighten"], "clip": d["clip"],
            "sampler": d["sampler"], "spec": d["spec"],
            "milp_status": d["milp_status"],
            "y_min": round(y_min, 6), "y_max": round(y_max, 6),
            "span_clipped": round(span_clipped, 6), "qrf_sec": round(qrf_sec, 2),
            "leaf_mode": leaf_mode,
        })
        print(f"[run {run_id}] {mc}: cov={m['coverage']:.3f} "
              f"eff={m['eff']:.3f} thr={d['threshold']} sec={m['seconds']:.2f}",
              flush=True)
    return rows


def main():
    # hf_jobs uv runs the script with no argv; allow config via ORCA_ARGS
    if os.environ.get("ORCA_ARGS"):
        sys.argv += os.environ["ORCA_ARGS"].split()
    ap = argparse.ArgumentParser(description="ORCA Table-3 corrected core")
    ap.add_argument("--dataset", required=True, choices=["blog", "fb1", "fb2"])
    ap.add_argument("--runs", type=int, default=1)
    ap.add_argument("--preproc", default="raw", choices=["raw", "logz"])
    ap.add_argument("--out", required=True)
    ap.add_argument("--seed0", type=int, default=0)
    ap.add_argument("--leaf_mode", default="split", choices=["leaf", "split"],
                    help="QRF config: 'split' = min_samples_split=50 (paper E.1 "
                         "literal); 'leaf' = min_samples_leaf=50 (the PCP-repo "
                         "driver's config / Table 4's '#leaf' knob)")
    args = ap.parse_args()

    X, y = load_dataset(args.dataset)
    print(f"[data] {args.dataset}: X{X.shape} y{y.shape}", flush=True)

    stage = os.environ.get("ORCA_STAGE", "cpu")
    header = ["dataset", "preproc", "run_id", "method_config", "coverage",
              "eff", "seconds", "status", "threshold", "proxy_objective",
              "quota", "tighten", "clip", "sampler", "spec", "milp_status",
              "y_min", "y_max", "span_clipped", "qrf_sec", "leaf_mode"]
    write_header = not os.path.exists(args.out)

    all_rows = []
    for run_id in range(args.runs):
        rows = one_run(args.dataset, X, y, run_id, args.seed0, args.preproc,
                       leaf_mode=args.leaf_mode)
        all_rows.extend(rows)
        pd.DataFrame(rows, columns=header).to_csv(
            args.out, mode="a", header=write_header, index=False)
        write_header = False

    # summary: mean +- SE per method_config
    df = pd.DataFrame(all_rows, columns=header)
    print("\n=== summary (mean +- SE over runs) ===", flush=True)
    print(f"{'method_config':30s} {'coverage':>18s} {'eff':>18s}")
    df_ok = df[df["status"] == "ok"]
    for mc, g in df_ok.groupby("method_config"):
        print(f"{mc:30s} {g['coverage'].mean():.4f} +- "
              f"{g['coverage'].sem():.4f} {g['eff'].mean():.4f} +- "
              f"{g['eff'].sem():.4f}")
    print(f"[out] rows appended to {args.out}", flush=True)
    if os.environ.get("ORCA_UPLOAD_REPO", "Devya27/orca-table3-repro"):
        try:
            from huggingface_hub import HfApi
            HfApi().upload_file(
                path_or_fileobj=args.out,
                path_in_repo=f"results/full_{stage}_{args.preproc}_{args.dataset}.csv",
                repo_id=os.environ.get("ORCA_UPLOAD_REPO",
                                       "Devya27/orca-table3-repro"),
                repo_type="dataset",
            )
            print("[upload] ok", flush=True)
        except Exception as exc:  # noqa: BLE001
            print(f"[upload] FAILED: {exc}", flush=True)


if __name__ == "__main__":
    main()