Skip to content

Hidden Functions

Hidden functions for all MixIns.

Advanced / Internal

The functions in this section are internal utilities. They may change without notice and are not guaranteed to remain stable across releases. Use only if you understand the internal architecture of pAnnData.


analysis

Provides core statistical and dimensionality reduction tools for analyzing single-cell proteomics data.

This mixin includes functionality for:

  • Differential expression (DE) analysis using t-tests, Mann-Whitney U, or Wilcoxon signed-rank tests
  • Mixed-model / pseudobulk DE with donor blocking via :meth:mixed_de
  • Ranking proteins or peptides by abundance within groups
  • Coefficient of Variation (CV) computation
  • Missing value imputation (global or group-wise) using statistical or KNN-based methods
  • Dimensionality reduction and clustering using PCA, UMAP, and Leiden
  • Neighbor graph construction for downstream manifold learning
  • Cleaning .X matrices by replacing NaNs
  • Row-wise normalization across multiple strategies

All functions are compatible with both protein- and peptide-level data and support use of AnnData layers.

Methods:

Name Description
cv

Compute coefficient of variation (CV) for each feature across or within sample groups.

de

Perform differential expression analysis between two sample groups.

rank

Rank features by mean abundance, compute standard deviation and numeric rank.

impute

Impute missing values globally or within groups using mean, median, min, or KNN.

neighbor

Compute neighborhood graph using PCA (or another embedding) for clustering or UMAP.

leiden

Run Leiden clustering on neighborhood graph, storing labels in .obs['leiden'].

umap

Perform UMAP dimensionality reduction using previously computed neighbors.

pca

Run PCA on normalized expression matrix, handling NaN exclusion and reinsertion of features.

clean_X

Replace NaNs in .X or a specified layer, optionally backing up the original.

_normalize_helper

Internal helper to compute per-sample scaling across multiple normalization methods.

log_transform

Apply log transform with pseudocount; register layer provenance.

Source code in src/scpviz/pAnnData/analysis.py
  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
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
class AnalysisMixin:
    """
    Provides core statistical and dimensionality reduction tools for analyzing single-cell proteomics data.

    This mixin includes functionality for:

    - Differential expression (DE) analysis using t-tests, Mann-Whitney U, or Wilcoxon signed-rank tests
    - Mixed-model / pseudobulk DE with donor blocking via :meth:`mixed_de`
    - Ranking proteins or peptides by abundance within groups  
    - Coefficient of Variation (CV) computation  
    - Missing value imputation (global or group-wise) using statistical or KNN-based methods  
    - Dimensionality reduction and clustering using PCA, UMAP, and Leiden  
    - Neighbor graph construction for downstream manifold learning  
    - Cleaning `.X` matrices by replacing NaNs  
    - Row-wise normalization across multiple strategies  

    All functions are compatible with both protein- and peptide-level data and support use of AnnData layers.

    Functions:
        cv: Compute coefficient of variation (CV) for each feature across or within sample groups.
        de: Perform differential expression analysis between two sample groups.
        rank: Rank features by mean abundance, compute standard deviation and numeric rank.
        impute: Impute missing values globally or within groups using mean, median, min, or KNN.
        neighbor: Compute neighborhood graph using PCA (or another embedding) for clustering or UMAP.
        leiden: Run Leiden clustering on neighborhood graph, storing labels in `.obs['leiden']`.
        umap: Perform UMAP dimensionality reduction using previously computed neighbors.
        pca: Run PCA on normalized expression matrix, handling NaN exclusion and reinsertion of features.
        clean_X: Replace NaNs in `.X` or a specified layer, optionally backing up the original.
        _normalize_helper: Internal helper to compute per-sample scaling across multiple normalization methods.
        log_transform: Apply log transform with pseudocount; register layer provenance.
    """

    def cv(self, classes = None, on = 'protein', layer = "X", debug = False):
        """
        Compute the coefficient of variation (CV) for each feature across sample groups.

        This method calculates CV for each protein or peptide across all samples in each group,
        storing the result as new columns in `.var`, one per group.

        Args:
            classes (str or list of str, optional): Sample-level class or list of classes used to define groups.
            on (str): Whether to compute CV on "protein" or "peptide" data.
            layer (str): Data layer to use for computation (default is "X").
            debug (bool): If True, prints debug information while filtering groups.

        Returns:
            None

        Example:
            Compute per-group CV for proteins using a custom normalization layer:
                ```python
                pdata.cv(classes=["group", "condition"], on="protein", layer="X_norm")
                ```
        """
        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            pass

        adata = self.prot if on == 'protein' else self.pep
        classes_list = utils.get_classlist(adata, classes)

        for j, class_value in enumerate(classes_list):
            data_filtered = utils.resolve_class_filter(adata, classes, class_value)

            cv_data = data_filtered.X.toarray() if layer == "X" else data_filtered.layers[layer].toarray() if layer in data_filtered.layers else None
            if cv_data is None:
                raise ValueError(f"Layer '{layer}' not found in adata.layers.")

            adata.var['CV: '+ class_value] = variation(cv_data, axis=0)

        self._history.append(f"{on}: Coefficient of Variation (CV) calculated for {layer} data by {classes}. CV stored in var['CV: {class_value}'].") # type: ignore[attr-defined]

    def de(self, values=None, class_type=None, method='ttest', layer='X', threshold=0.05, log2fc=1.0, fold_change_mode='mean', correct_fdr=False, equal_var=True, pval=None, min_valid_fraction=0.5):
        """
        Perform differential expression (DE) analysis on proteins across sample groups.

        This method compares protein abundance between two sample groups using a specified
        statistical test and fold change method. Input groups can be defined using either
        legacy-style (`class_type` + `values`) or dictionary-style filters.

        Args:
            values (list of dict or list of list): Sample group filters to compare.

                - Dictionary-style (recommended): [{'cellline': 'HCT116', 'treatment': 'DMSO'}, {...}]
                - Legacy-style (if `class_type` is provided): [['HCT116', 'DMSO'], ['HCT116', 'DrugX']]

            class_type (str or list of str, optional): Legacy-style class label(s) to interpret `values`.
            method (str): Statistical test to use. Options: "ttest", "mannwhitneyu", "wilcoxon", "limma".
                ``"limma"`` is a moderated t-test (empirical Bayes variance shrinkage, validated against R limma;
                see ``scpviz.utils.limma``). It needs a log-transformed layer and
                ``fold_change_mode="mean"``; ``test_statistic`` is the moderated t, and ``equal_var`` is ignored.
            layer (str): Name of the data layer to use (default is "X").
            threshold (float): Significance cutoff. Applied to raw ``p_value`` when
                ``correct_fdr=False``, and to ``adj_p_value`` when ``correct_fdr=True``. Defaults to 0.05.
            pval (float, optional): Deprecated alias for ``threshold``.

            log2fc (float): Minimum log2 fold change threshold for significance labeling.

            correct_fdr (bool): If True, apply Benjamini-Hochberg FDR correction and
                label significance using adjusted p-values. Default is False.

            equal_var (bool): Passed to :func:`scipy.stats.ttest_ind` when ``method='ttest'``.
                ``True`` (default) uses Student's t-test; ``False`` uses Welch's t-test.

            min_valid_fraction (float): Only used when ``correct_fdr=True``. Proteins with a
                fraction of non-missing values below this in either group are excluded from
                the BH correction (``adj_p_value`` is NaN; raw ``p_value`` is kept). Default 0.5.
                Ignored for ``method='limma'`` (filter sparse proteins upstream, e.g. with ``filter_prot``).

            fold_change_mode (str): Strategy for computing fold change. Options:

                - "mean": log2(mean(group1) / mean(group2))
                - "pairwise_median": median of all pairwise log2 ratios
                - "pep_pairwise_median": median of peptide-level pairwise log2 ratios, aggregated per protein

        Returns:
            pd.DataFrame: DataFrame with DE statistics including log2 fold change, p-values, and significance labels.

        Note:
            Zeros are treated as missing and set to NaN before testing and fold change. On a
            ``log_transform`` layer, a zero maps to ``log_base(pseudocount)`` and is detected
            from the layer provenance.

        Example:
            Legacy-style DE comparison using class types and value combinations:
                ```python
                pdata.de(
                    class_type=["cellline", "treatment"],
                    values=[["HCT116", "DMSO"], ["HCT116", "DrugX"]]
                )
                ```

            Dictionary-style (recommended) DE comparison:
                ```python
                pdata.de(
                    values=[
                        {"cellline": "HCT116", "treatment": "DMSO"},
                        {"cellline": "HCT116", "treatment": "DrugX"}
                    ]
                )
                ```

            DE comparison adjusted for multiple testing with BH correction, and with unequal sample size:
                ```python
                pdata.de(
                    values=[
                        {"cellline": "HCT116", "treatment": "DMSO"},
                        {"cellline": "HCT116", "treatment": "DrugX"}
                    ],
                    correct_fdr=True,
                    equal_var=False
                )
                ```
        """

        if pval is not None:
            print(
                f"{format_log_prefix('warn')} `pval` is deprecated in de(); "
                f"use `threshold` instead (applied pval={pval})."
            )
            if pval != threshold:
                print(
                    f"{format_log_prefix('warn')} Both `threshold`={threshold} and "
                    f"`pval={pval}` were passed to de(); using `pval`."
                )
            threshold = pval

        if method not in ('ttest', 'mannwhitneyu', 'wilcoxon', 'limma'):
            raise ValueError(f"{format_log_prefix('error')} Unsupported test method '{method}'. Choose 'ttest', 'mannwhitneyu', 'wilcoxon' or 'limma'.")

        # --- Handle legacy input ---
        if values is None:
            raise ValueError("Please provide `values` (new format) or both `class_type` and `values` (legacy format).")

        if class_type is not None:
            values = utils.format_class_filter(class_type, values, exact_cases=True)

        if not isinstance(values, list) or len(values) != 2:
            raise ValueError("`values` must be a list of two group dictionaries (or legacy value pairs).")

        if values[0] == values[1]:
            raise ValueError("Both groups in `values` refer to the same condition. Please provide two distinct groups.")

        group1_dict, group2_dict = (
            [values[0]] if not isinstance(values[0], list) else values[0],
            [values[1]] if not isinstance(values[1], list) else values[1]
        )


        # --- Sample filtering ---
        pdata_case1 = self._filter_sample_values(values=group1_dict, exact_cases=True, return_copy=True, verbose=False, cleanup=False) # type: ignore[attr-defined], FilteringMixin
        pdata_case2 = self._filter_sample_values(values=group2_dict, exact_cases=True, return_copy=True, verbose=False, cleanup=False) # type: ignore[attr-defined], FilteringMixin

        group1_string = format_de_group_label(group1_dict)
        group2_string = format_de_group_label(group2_dict)
        comparison_string = format_de_comparison_label(group1_dict, group2_dict)

        # --- Get layer data ---
        data1 = utils.get_adata_layer(pdata_case1.prot, layer)
        data2 = utils.get_adata_layer(pdata_case2.prot, layer)

        # Shape: (samples, features)
        data1 = np.asarray(data1)
        data2 = np.asarray(data2)

        _layer_is_log = utils.infer_layer_is_log(layer, pdata_case1.prot)
        if method == 'limma':
            if not _layer_is_log:
                raise ValueError(f"{format_log_prefix('error')} method='limma' needs a log-transformed layer; run log_transform() first.")
            if fold_change_mode != 'mean':
                raise ValueError(f"{format_log_prefix('error')} method='limma' requires fold_change_mode='mean' (log2fc is the modeled group difference).")

        # Log base and pseudocount from the layer's provenance chain
        _base_val, _log_base, _pseudocount = get_log_info(pdata_case1.prot, layer, _layer_is_log)

        # Zeros are missing values: mask to NaN so tests, means and fold changes ignore them
        _n_nan_before = int(np.isnan(data1).sum() + np.isnan(data2).sum())
        data1 = mask_zeros_as_nan(data1, _layer_is_log, _log_base, _pseudocount)
        data2 = mask_zeros_as_nan(data2, _layer_is_log, _log_base, _pseudocount)
        _n_zero = int(np.isnan(data1).sum() + np.isnan(data2).sum()) - _n_nan_before

        _finite_de = data1[np.isfinite(data1)]
        _median_val = float(np.nanmedian(_finite_de)) if _finite_de.size > 0 else 0.0

        if not _layer_is_log and _median_val > 1e4:
            print(
                f"{format_log_prefix('warn')} Layer {layer!r} appears to contain "
                f"non-log intensities (median={_median_val:.2e}). Statistical tests "
                "assume approximately normal distributions — consider log_transform() "
                "before DE analysis."
            )

        n1, n2 = len(pdata_case1.prot), len(pdata_case2.prot)
        print_de_run_header(
            assay="protein",
            comparing=comparison_string,
            group_sizes=f"{n1} vs {n2} samples",
            layer_line=(
                f"{layer} "
                f"{'(log-transformed)' if _layer_is_log else '(non-log)'}"
            ),
            method_line=f"{method} | Fold Change: {fold_change_mode}",
            correct_fdr=correct_fdr,
            threshold=threshold,
            log2fc_thresh=log2fc,
        )
        if _n_zero > 0:
            print(
                f"{format_log_prefix('info', 2)} {_n_zero} zero value(s) in the selected samples "
                "treated as missing (NaN) for testing and fold change."
            )

        # --- Compute fold change ---
        if fold_change_mode == 'mean':
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", RuntimeWarning)

                group1_mean = np.nanmean(data1, axis=0)
                group2_mean = np.nanmean(data2, axis=0)

                # Identify NaNs in either group (and zero means on linear data; on a log layer 0 is a real value)
                mask_invalid = np.isnan(group1_mean) | np.isnan(group2_mean)
                if not _layer_is_log:
                    mask_invalid |= (group1_mean == 0) | (group2_mean == 0)

                if _layer_is_log:
                    if _base_val in ("10",):
                        log2fc_vals = (group1_mean - group2_mean) / np.log10(2)
                        _base_label = "log10"
                    elif _base_val in ("e",):
                        log2fc_vals = (group1_mean - group2_mean) / np.log(2)
                        _base_label = "loge"
                    else:
                        log2fc_vals = group1_mean - group2_mean
                        _base_label = "log2"
                    log2fc_vals[mask_invalid] = np.nan
                    print(
                        f"{format_log_prefix('info')} Layer {layer!r} is log-transformed "
                        f"({_base_label}) — using mean difference for log2FC."
                    )
                else:
                    log2fc_vals = np.log2(group1_mean / group2_mean)
                    log2fc_vals[mask_invalid] = np.nan

                n_invalid = np.sum(mask_invalid)
                if n_invalid > 0:
                    print(f"{format_log_prefix('info',2)} {n_invalid} proteins were not comparable (zero or NaN mean in one group).")

        elif fold_change_mode == 'pairwise_median':
            # Detect invalid features (any NaN in either group; also any 0 on linear data)
            mask_invalid = np.any(np.isnan(data1), axis=0) | np.any(np.isnan(data2), axis=0)
            if not _layer_is_log:
                mask_invalid |= np.any(data1 == 0, axis=0) | np.any(data2 == 0, axis=0)
            # Compute median pairwise log2FC
            log2fc_vals = utils.pairwise_log2fc(data1, data2, _layer_is_log, _log_base)
            log2fc_vals[mask_invalid] = np.nan # Mark invalid features as NaN
            n_invalid = np.sum(mask_invalid)
            if n_invalid > 0:
                print(f"{format_log_prefix('info',2)} {n_invalid} proteins were not comparable (zero or NaN mean in one group).")

        elif fold_change_mode == 'pep_pairwise_median':
            # --- Validate .pep presence ---
            if self.pep is None:
                raise ValueError("Peptide-level data (.pep) is required for fold_change_mode='pep_pairwise_median', but self.pep is None.")

            # --- Handle peptide layer fallback ---
            actual_layer = layer
            if layer != 'X' and not (hasattr(self.pep, "layers") and layer in self.pep.layers):
                warnings.warn(
                    f"Layer '{layer}' not found in .pep.layers. Falling back to 'X'.",
                    UserWarning
                )
                actual_layer = 'X'

            # Get peptide data
            pep_data1 = np.asarray(utils.get_adata_layer(pdata_case1.pep, actual_layer))
            pep_data2 = np.asarray(utils.get_adata_layer(pdata_case2.pep, actual_layer))

            # Log base / pseudocount of the peptide layer actually used; zeros are missing values
            _pep_is_log = utils.infer_layer_is_log(actual_layer, pdata_case1.pep)
            _, _pep_base, _pep_pc = get_log_info(pdata_case1.pep, actual_layer, _pep_is_log)
            pep_data1 = mask_zeros_as_nan(pep_data1, _pep_is_log, _pep_base, _pep_pc)
            pep_data2 = mask_zeros_as_nan(pep_data2, _pep_is_log, _pep_base, _pep_pc)

            # Detect invalid peptides (any NaN in either group; also any 0 on linear data)
            mask_invalid_pep = np.any(np.isnan(pep_data1), axis=0) | np.any(np.isnan(pep_data2), axis=0)

            # Compute per-peptide pairwise log2FCs
            pep_log2fc = utils.pairwise_log2fc(pep_data1, pep_data2, _pep_is_log, _pep_base)
            pep_log2fc[mask_invalid_pep] = np.nan  # mark invalids

            n_invalid_pep = np.sum(mask_invalid_pep)
            if n_invalid_pep > 0:
                print(f"{format_log_prefix('info',2)} {n_invalid_pep} peptides were not comparable (zero or NaN mean in one group).")

            # Map peptides to proteins
            pep_to_prot = utils.get_pep_prot_mapping(self, return_series=True)

            # Aggregate peptide log2FCs into protein-level log2FCs
            prot_log2fc = pd.Series(index=self.prot.var_names, dtype=float)
            not_comparable_prot = []

            for prot in self.prot.var_names:
                matching_peptides = pep_to_prot[pep_to_prot == prot].index
                if len(matching_peptides) == 0:
                    continue

                idxs = self.pep.var_names.get_indexer(matching_peptides)
                valid_idxs = idxs[idxs >= 0]
                if len(valid_idxs) == 0:
                    continue

                valid_log2fc = pep_log2fc[valid_idxs]

                if np.all(np.isnan(valid_log2fc)):
                    prot_log2fc[prot] = np.nan
                    not_comparable_prot.append(prot)
                else:
                    prot_log2fc[prot] = np.nanmedian(pep_log2fc[valid_idxs])

            log2fc_vals = prot_log2fc.values
            if len(not_comparable_prot) > 0:
                print(f"{format_log_prefix('info',2)} {len(not_comparable_prot)} proteins were not comparable (all peptides invalid or missing).")

        else:
            raise ValueError(f"Unsupported fold_change_mode: {fold_change_mode}")

        # --- Statistical test ---
        if method == 'limma':
            lim = moderated_two_group_test(data1, data2)
            pvals, stats = lim['p_value'], lim['t']
            print_limma_summary(lim)
        else:
            results = [run_two_group_test(data1[:, i], data2[:, i], method, equal_var) for i in range(data1.shape[1])]
            pvals = [r[0] for r in results]
            stats = [r[1] for r in results]

        # --- Compile results ---
        var = self.prot.var.copy()
        df_stats = pd.DataFrame(index=self.prot.var_names)
        df_stats['Genes'] = var['Genes'] if 'Genes' in var.columns else var.index

        with warnings.catch_warnings():
            warnings.simplefilter("ignore", RuntimeWarning)
            df_stats[group1_string] = np.nanmean(data1, axis=0)
            df_stats[group2_string] = np.nanmean(data2, axis=0)
        df_stats['log2fc'] = log2fc_vals
        df_stats['p_value'] = pvals
        df_stats['test_statistic'] = stats

        df_stats['-log10(p_value)'] = -np.log10(
            df_stats['p_value'].replace(0, np.nan).astype(float)
        )
        df_stats['significance_score'] = df_stats['-log10(p_value)'] * df_stats['log2fc']

        if correct_fdr:
            if method == 'limma':  # the prior is fitted on the supplied proteins; filter upstream (filter_prot)
                pvals_bh, n_sparse = np.asarray(pvals, dtype=float), 0
            else:
                pvals_bh, n_sparse = exclude_sparse_pvalues(np.asarray(pvals, dtype=float), data1, data2, min_valid_fraction)
            if n_sparse > 0:
                print(
                    f"{format_log_prefix('info', 2)} {n_sparse} proteins had <{min_valid_fraction:.0%} valid values "
                    "in at least one group and were excluded from FDR correction (too sparse for a "
                    "reliable test); adj_p_value is NaN for these."
                )
            df_stats['adj_p_value'] = bh_adjust_pvalues(pvals_bh)
            df_stats['-log10(adj_p_value)'] = -np.log10(
                df_stats['adj_p_value'].replace(0, np.nan).astype(float)
            )
            p_for_sig = df_stats['adj_p_value']
        else:
            p_for_sig = df_stats['p_value']

        df_stats['significance'] = 'not significant'
        mask_not_comparable = df_stats['log2fc'].isna()
        df_stats.loc[mask_not_comparable, 'significance'] = 'not comparable'
        df_stats.loc[(p_for_sig < threshold) & (df_stats['log2fc'] > log2fc), 'significance'] = 'upregulated'
        df_stats.loc[(p_for_sig < threshold) & (df_stats['log2fc'] < -log2fc), 'significance'] = 'downregulated'
        df_stats['significance'] = pd.Categorical(df_stats['significance'], categories=['upregulated', 'downregulated', 'not significant', 'not comparable'], ordered=True)

        df_stats = df_stats.sort_values(by='significance')
        if method == 'limma':
            df_stats.attrs['limma'] = {k: lim[k] for k in ('s2_prior', 'df_prior', 'estimator')}

        # --- Store and return ---
        self._stats[comparison_string] = df_stats # type: ignore[attr-defined]
        self._append_history(f"prot: DE for {class_type} {values} using {method} and fold_change_mode='{fold_change_mode}'. Stored in .stats['{comparison_string}'].") # type: ignore[attr-defined], HistoryMixin

        print_de_result_summary(
            df_stats,
            stats_location=f'.stats["{comparison_string}"]',
            correct_fdr=correct_fdr,
        )

        return df_stats

    def mixed_de(
        self,
        donor_col: str,
        *,
        group_col: str | None = None,
        contrast: tuple[str, str] | None = None,
        contrast_mode: str = "specified",
        focal_level: str | None = None,
        formula: str | None = None,
        contrast_term: str | None = None,
        contrast_at: dict[str, str] | None = None,
        values: list[dict] | None = None,
        subset: dict | None = None,
        fixed_covariates: list[str] | None = None,
        reference_levels: dict[str, str] | None = None,
        random_effects: str = "intercept",
        re_slope_col: str | None = None,
        require_paired_donors: bool = False,
        observation_level: str = "auto",
        max_cells_per_stratum: int = 50,
        method: str = "auto",
        min_detected_fraction: float = 0.10,
        min_cells_detected: int = 3,
        on: str = "protein",
        layer: str = "X",
        auto_log2: bool = True,
        log_pseudocount: float = 1.0,
        correct_fdr: bool = True,
        fdr_scope: str = "per_contrast",
        threshold: float = 0.05,
        log2fc: float = 1.0,
        return_diagnostics: bool = False,
        store: bool = True,
        stats_key: str | None = None,
    ):
        """
        Mixed-model or pseudobulk differential expression with donor blocking.

        Compare groups while accounting for biological replicate structure (donor,
        animal, case, …). Supports a **simple path** (``group_col`` + ``contrast``)
        or an **advanced path** (``formula`` + ``contrast_term``). See mutual
        exclusion rules below.

        Args:
            donor_col (str): Column for biological replicate ID (donor, Case, mouse, …).
            group_col (str, optional): Contrast factor for the simple path.
            contrast (tuple of str, optional): ``(test, ref)``; log2fc = test − ref.
                Same order as ``values=[group1, group2]`` (DESeq2-style numerator /
                denominator).
            contrast_mode (str): ``"specified"`` (default), ``"pairwise"``, or
                ``"one_vs_rest"``.
            focal_level (str, optional): Focal level when ``contrast_mode="one_vs_rest"``.
            formula (str, optional): Patsy fixed-effects formula with LHS ``expr``.
                Random effects are **not** included in the string.
            contrast_term (str, optional): Factor to test when using ``formula``.
            contrast_at (dict, optional): Levels of interacting factors at which to
                evaluate the contrast (required when ``formula`` contains ``*`` on
                ``contrast_term``).
            values (list of dict, optional): Two-group sugar (simple path), same style
                as :meth:`de`. Order is ``[group1, group2]`` → stats key
                ``mixed: [{group1}] vs [{group2}] | ...`` and log2fc = group1 - group2.
                Equivalent to ``contrast=(group1, group2)`` i.e. ``(test, ref)``.
            subset (dict, optional): AND-combined observation filters, e.g.
                ``{"cell_type": "Astrocyte"}``. Stored as ``filter: [{...}]`` on the
                auto stats key.
            fixed_covariates (list of str, optional): Additive covariates (simple path).
            reference_levels (dict, optional): Reference level per categorical column.
            random_effects (str): ``"intercept"`` (default) or ``"intercept_slope"``.
            re_slope_col (str, optional): Column for random slope; defaults to
                ``group_col`` or ``contrast_term``.
            require_paired_donors (bool): If True, error when donors lack all levels.
            observation_level (str): ``"auto"`` (pseudobulk if n_cells > 500), ``"cells"``,
                ``"pseudobulk"``, or ``"subsample"``.
            max_cells_per_stratum (int): Max cells per donor × group stratum when
                ``observation_level="subsample"``.
            method (str): ``"auto"``, ``"mixedlm"``, or ``"pseudobulk"`` (cells path).
            min_detected_fraction (float): Min detection fraction per feature.
            min_cells_detected (int): Min detected observations per feature.
            on (str): ``"protein"`` or ``"peptide"``.
            layer (str): Expression layer. Must be **log2-scale** (or log-scale with
                provenance). Typical workflow: normalize on linear scale (e.g.
                directLFQ), then ``log_transform(base=2)`` and pass ``layer='X_log2'``.
                If ``layer`` looks linear-scale, ``auto_log2=True`` (default) applies
                ``log2(x + log_pseudocount)`` in memory for this run only.
            auto_log2 (bool): If True (default), apply in-memory log2 when ``layer``
                is not registered as log-transformed and values look linear-scale.
                Set False to raise with instructions instead.
            log_pseudocount (float): Pseudocount for in-memory auto log2 (default 1.0).
            correct_fdr (bool): Apply Benjamini-Hochberg FDR correction.
            fdr_scope (str): ``"per_contrast"`` (default), ``"global"``, or ``"both"``.
            threshold (float): Significance cutoff for labels.
            log2fc (float): |log2fc| threshold for up/down labels.
            return_diagnostics (bool): If True, return ``(volcano_df, diagnostics_df)``.
            store (bool): Store results in ``pdata.stats``.
            stats_key (str, optional): Override auto-generated ``.stats`` key.

        Returns:
            pd.DataFrame or dict: Volcano table for ``contrast_mode="specified"``;
            collection dict with ``contrasts``, ``meta`` for pairwise / one_vs_rest.

        Mutual exclusion:
            - **Simple path:** ``group_col`` + ``contrast`` (or ``values``). Do not pass
              ``formula`` or ``contrast_term``.
            - **Advanced path:** ``formula`` + ``contrast_term`` + ``contrast``. Do not pass
              ``group_col`` or ``fixed_covariates``.

        !!! tip "``subset`` vs ``contrast_at``"
            **Rule of thumb:** If the scientific question is “within L5 only,” use
            ``subset``. If the question is “condition effect at L5, adjusted for layer
            structure and donor blocking across layers,” use ``formula`` +
            ``contrast_at``.

            - ``subset={"layer": "L5"}`` — only L5 cells enter the model (population is
              L5-specific).
            - ``formula="expr ~ condition * layer"`` with ``contrast_at={"layer": "L5"}`` —
              all layers stay in the fit; the reported contrast is the condition effect
              **at** L5.

        Example:
            Do mixed-model analysis of region comparison with donor blocking AND plot volcano (returns volcano table + stores in
            ``pdata.stats``):
                ```python
                # (test, ref): log2fc = Cortex - SNpc

                volcano_df = pdata.mixed_de(
                    group_col="region",
                    contrast=("Cortex", "SNpc"),  # same as `values=[{"region": "Cortex"}, {"region": "SNpc"}]`
                    donor_col="animal",
                )
                # Auto stats key (also printed at end of run):
                stats_key = "mixed: [{'region': 'Cortex'}] vs [{'region': 'SNpc'}] | donor=animal"
                # volcano_df is the same table as pdata.stats[stats_key]

                import matplotlib.pyplot as plt
                from scpviz import plotting as scplt

                fig, ax = plt.subplots(figsize=(4, 4))
                scplt.plot_volcano(
                    ax, pdata, stats_key=stats_key, correct_fdr=True,
                )
                plt.show()
                ```

            Single cell type, simple path:
                ```python
                df = pdata.mixed_de(
                    group_col="condition",
                    contrast=("Agg+", "Agg-"),  # (test, ref)
                    donor_col="donor",
                    fixed_covariates=["batch"],
                    subset={"cell_type": "Astrocyte"},
                )
                ```

            Values sugar (same sign/key as ``contrast=("Agg+", "Agg-")`` above):
                ```python
                df = pdata.mixed_de(
                    values=[{"condition": "Agg+"}, {"condition": "Agg-"}],
                    donor_col="donor",
                    subset={"cell_type": "Astrocyte"},
                )
                ```

            Panel over cell types:
                ```python
                for ct in ["Astrocyte", "Microglia"]:
                    pdata.mixed_de(
                        group_col="condition",
                        contrast=("Agg+", "Agg-"),
                        donor_col="donor",
                        subset={"cell_type": ct},
                    )
                ```

            Testing random intercept + slope:
                ```python
                df = pdata.mixed_de(
                    group_col="Cortex",
                    contrast=("pSyn", "NeuN"),  # (test, ref)
                    donor_col="Case",
                    random_effects="intercept_slope",
                )
                ```

            Advanced interaction at a layer (not subset to L5):
                ```python
                df = pdata.mixed_de(
                    formula="expr ~ condition * layer",
                    contrast_term="condition",
                    contrast=("disease", "control"),  # (test, ref)
                    contrast_at={"layer": "L5"},
                    donor_col="donor",
                    subset={"cell_type": "Neuron"},
                )
                ```

            Population is L5 neurons — use subset:
                ```python
                df = pdata.mixed_de(
                    group_col="condition",
                    contrast=("disease", "control"),
                    donor_col="donor",
                    subset={"cell_type": "Neuron", "layer": "L5"},
                )
                ```

            Volcano from stored results (``de_data`` alternative):
                ```python
                stats_key = "mixed: [{'condition': 'Agg+'}] vs [{'condition': 'Agg-'}] | filter: [{'cell_type': 'Astrocyte'}] | donor=donor"
                scplt.plot_volcano(ax, pdata, stats_key=stats_key, correct_fdr=True)
                # equivalent: scplt.plot_volcano(ax, de_data=pdata.stats[stats_key], correct_fdr=True)
                ```
        """
        from scpviz.utils import mixed_de as mixed_de_utils

        if on not in ("protein", "peptide"):
            raise ValueError("`on` must be 'protein' or 'peptide'.")
        adata = getattr(self, "prot" if on == "protein" else "pep", None)
        if adata is None:
            raise ValueError(f"No .{on} data available.")

        path = mixed_de_utils.validate_mixed_de_paths(
            group_col=group_col,
            formula=formula,
            contrast_term=contrast_term,
            fixed_covariates=fixed_covariates,
            values=values,
        )

        if values is not None:
            group_col, contrast, subset = mixed_de_utils.resolve_values_sugar(
                values, group_col=group_col, contrast=contrast, subset=subset
            )

        if path == "simple":
            if group_col is None:
                raise ValueError("`group_col` is required for the simple path.")
            if contrast is None and contrast_mode == "specified":
                raise ValueError("`contrast` is required when contrast_mode='specified'.")
            terms = [group_col] + list(fixed_covariates or [])
            resolved_formula = f"expr ~ {' + '.join(terms)}"
            resolved_contrast_term = group_col
        else:
            if contrast is None and contrast_mode == "specified":
                raise ValueError("`contrast` is required when contrast_mode='specified'.")
            resolved_formula = formula
            resolved_contrast_term = contrast_term
            if mixed_de_utils.formula_has_interaction_on_term(formula, contrast_term):
                if not contrast_at:
                    raise ValueError(
                        f"`contrast_at` is required because `formula` contains an interaction "
                        f"involving {contrast_term!r}."
                    )

        meta_columns = list(
            dict.fromkeys(
                [donor_col, resolved_contrast_term]
                + list(fixed_covariates or [])
                + list((subset or {}).keys())
                + list((contrast_at or {}).keys())
                + list((reference_levels or {}).keys())
            )
        )
        summary = getattr(self, "_summary", None)
        meta_full = mixed_de_utils.resolve_obs_meta(adata, summary, meta_columns)
        mask = mixed_de_utils.subset_meta_mask(meta_full, subset)
        meta = meta_full.loc[mask].copy()
        if meta.empty:
            raise ValueError("No observations remain after applying `subset`.")

        if contrast_mode == "specified" and contrast is not None:
            test, ref = contrast
            meta = meta[meta[resolved_contrast_term].astype(str).isin([str(ref), str(test)])].copy()
            if meta.empty:
                raise ValueError(
                    f"No observations for contrast levels {test!r} and {ref!r} in "
                    f"{resolved_contrast_term!r}."
                )
            levels_present = set(meta[resolved_contrast_term].astype(str))
            missing = [lv for lv in (str(test), str(ref)) if lv not in levels_present]
            if missing:
                raise ValueError(
                    f"Contrast level(s) {missing} absent after filtering/subset for "
                    f"{resolved_contrast_term!r}."
                )

        diag = mixed_de_utils.preflight_donor_design(
            meta,
            donor_col=donor_col,
            group_col=resolved_contrast_term,
            require_paired_donors=require_paired_donors,
        )

        expr, expr_meta = mixed_de_utils.prepare_expr_for_mixed_de(
            adata,
            layer,
            auto_log2=auto_log2,
            log_pseudocount=log_pseudocount,
        )
        expr = expr[adata.obs_names.get_indexer(meta.index), :]

        if observation_level == "auto":
            obs_level = "pseudobulk" if len(meta) > 500 else "cells"
        else:
            obs_level = observation_level
        if observation_level == "subsample":
            rng = np.random.default_rng(0)
            meta, expr = mixed_de_utils.subsample_observations(
                meta,
                expr,
                donor_col=donor_col,
                group_col=resolved_contrast_term,
                max_cells_per_stratum=max_cells_per_stratum,
                rng=rng,
            )

        meta = mixed_de_utils.cast_formula_categoricals(meta, resolved_formula)
        for col in [resolved_contrast_term, donor_col] + list(fixed_covariates or []):
            if col in meta.columns and not pd.api.types.is_numeric_dtype(meta[col]):
                meta[col] = meta[col].astype("string").astype("category")
        # Apply after category casts — re-casting resets category order to alphabetical.
        resolved_reference_levels = mixed_de_utils.merge_contrast_reference_levels(
            reference_levels,
            contrast_term=resolved_contrast_term,
            contrast=contrast,
            contrast_mode=contrast_mode,
        )
        meta = mixed_de_utils.apply_reference_levels(meta, resolved_reference_levels)

        detect_mask = mixed_de_utils.feature_detection_mask(
            expr,
            min_detected_fraction=min_detected_fraction,
            min_cells_detected=min_cells_detected,
        )
        if not detect_mask.any():
            raise ValueError(
                "No features pass `min_detected_fraction` / `min_cells_detected`. "
                "Pre-filter sparse features with `filter_prot_found()` or lower thresholds."
            )

        levels = sorted(meta[resolved_contrast_term].astype(str).unique())
        contrasts = mixed_de_utils.list_contrasts_for_mode(
            levels,
            contrast_mode=contrast_mode,
            contrast=contrast,
            focal_level=focal_level,
            group_col=resolved_contrast_term,
        )

        n_features_tested = int(detect_mask.sum())
        n_features_total = len(detect_mask)
        comparing = mixed_de_utils.format_comparing_groups(
            contrast_mode=contrast_mode,
            contrasts=contrasts,
            values=values,
            focal_level=focal_level,
        )
        # Restrict before-filter sizes to the contrast levels when specified.
        meta_before = meta_full
        if contrast_mode == "specified" and contrast is not None:
            test, ref = contrast
            meta_before = meta_full[
                meta_full[resolved_contrast_term].astype(str).isin([str(ref), str(test)])
            ]
        group_sizes_before = mixed_de_utils.format_group_sizes(
            meta_before,
            resolved_contrast_term,
            contrast_mode=contrast_mode,
            contrasts=contrasts,
            values=values,
        )
        group_sizes = mixed_de_utils.format_group_sizes(
            meta,
            resolved_contrast_term,
            contrast_mode=contrast_mode,
            contrasts=contrasts,
            values=values,
        )
        slope_col = re_slope_col or resolved_contrast_term
        mixed_de_utils.print_mixed_de_run_header(
            on=on,
            comparing=comparing,
            group_sizes_before=group_sizes_before,
            path=path,
            contrast_mode=contrast_mode,
            formula=resolved_formula,
            donor_col=donor_col,
            group_col=resolved_contrast_term,
            slope_col=slope_col,
            layer_summary=mixed_de_utils.format_expr_layer_summary(expr_meta),
            method=method,
            observation_level=obs_level,
            random_effects=random_effects,
            fixed_covariates=fixed_covariates,
            subset=subset,
            correct_fdr=correct_fdr,
            threshold=threshold,
            log2fc_thresh=log2fc,
            n_donors_total=diag["n_donors_total"],
            n_donors_paired=diag["n_donors_paired"],
        )

        feature_names = adata.var_names
        var = adata.var.copy()
        paired_donors = diag["donors_with_both_conditions"]

        contrast_results: dict[str, pd.DataFrame] = {}
        contrast_diagnostics: dict[str, pd.DataFrame] = {}

        for test, ref, label in contrasts:
            rows, diag_rows = mixed_de_utils.run_single_contrast(
                expr,
                meta,
                feature_names,
                detect_mask,
                formula=resolved_formula,
                contrast_term=resolved_contrast_term,
                ref=ref,
                test=test,
                contrast_at=contrast_at,
                donor_col=donor_col,
                random_effects=random_effects,
                re_slope_col=slope_col,
                observation_level=obs_level,
                method=method,
                paired_donors=paired_donors,
                n_donors_paired=diag["n_donors_paired"],
            )
            vdf = mixed_de_utils.compile_volcano_dataframe(
                rows,
                feature_names,
                var,
                contrast_label=label,
                n_donors_paired=diag["n_donors_paired"],
                correct_fdr=correct_fdr,
                threshold=threshold,
                log2fc_thresh=log2fc,
                fdr_scope=fdr_scope,
            )
            ddf = pd.DataFrame(diag_rows).set_index("feature") if diag_rows else pd.DataFrame()
            contrast_results[label] = vdf
            contrast_diagnostics[label] = ddf

        if fdr_scope in ("global", "both") and len(contrast_results) > 1:
            flat_pvals: list[float] = []
            flat_index: list[tuple[str, int]] = []
            for label, vdf in contrast_results.items():
                for i, p in enumerate(vdf["p_value"].values):
                    if np.isfinite(p):
                        flat_pvals.append(float(p))
                        flat_index.append((label, i))
            if len(flat_pvals) > 1:
                global_adj = bh_adjust_pvalues(np.asarray(flat_pvals))
                for (label, i), adj in zip(flat_index, global_adj):
                    if "adj_p_value_global" not in contrast_results[label].columns:
                        contrast_results[label]["adj_p_value_global"] = np.nan
                    row_idx = contrast_results[label].index[i]
                    contrast_results[label].loc[row_idx, "adj_p_value_global"] = adj

        per_feature_testing, per_feature_failures = (
            mixed_de_utils.summarize_per_feature_testing_for_results(
                contrast_results,
                contrast_mode=contrast_mode,
                method=method,
                observation_level=obs_level,
            )
        )
        mixed_de_utils.print_mixed_de_info_section(
            diag=diag,
            group_col=resolved_contrast_term,
            group_sizes=group_sizes,
            n_features_tested=n_features_tested,
            n_features_total=n_features_total,
            per_feature_testing=per_feature_testing,
            per_feature_failures=per_feature_failures,
        )

        run_meta = {
            "path": path,
            "formula_resolved": resolved_formula,
            "group_col": group_col,
            "contrast_term": resolved_contrast_term,
            "contrast_mode": contrast_mode,
            "subset": subset,
            "donor_col": donor_col,
            "random_effects": random_effects,
            "observation_level_used": obs_level,
            "fdr_scope": fdr_scope,
            "on": on,
            "layer": layer,
            "reference_levels": resolved_reference_levels,
            **expr_meta,
            **diag,
        }

        if contrast_mode == "specified":
            label = contrasts[0][2]
            volcano_df = contrast_results[label]
            diagnostics_df = contrast_diagnostics[label]
            key = stats_key or mixed_de_utils.build_stats_key(
                contrast_label=label,
                subset=subset,
                donor_col=donor_col,
                contrast_mode=contrast_mode,
                group_col=resolved_contrast_term,
            )
            volcano_df.attrs["mixed_de"] = {**run_meta, "contrast": contrasts[0][:2], "contrast_label": label}
            if store:
                self._stats[key] = volcano_df  # type: ignore[attr-defined]
                self._append_history(  # type: ignore[attr-defined]
                    f"{on}: mixed_de {label} stored in .stats[{key!r}]."
                )
            mixed_de_utils.print_mixed_de_result_summary(
                volcano_df,
                stats_location=f'.stats["{key}"]',
                correct_fdr=correct_fdr,
                contrast_mode=contrast_mode,
            )
            if return_diagnostics:
                return volcano_df, diagnostics_df
            return volcano_df

        collection_key = stats_key or mixed_de_utils.build_stats_key(
            contrast_label="",
            subset=subset,
            donor_col=donor_col,
            contrast_mode=contrast_mode,
            group_col=resolved_contrast_term,
        )
        for label, vdf in contrast_results.items():
            vdf.attrs["mixed_de"] = {**run_meta, "contrast_label": label}
        collection = {
            "contrasts": contrast_results,
            "meta": run_meta,
            "diagnostics": contrast_diagnostics,
        }
        if store:
            self._stats[collection_key] = collection  # type: ignore[attr-defined]
            self._append_history(  # type: ignore[attr-defined]
                f"{on}: mixed_de {contrast_mode} collection stored in .stats[{collection_key!r}]."
            )
        mixed_de_utils.print_mixed_de_collection_summary(
            contrast_results,
            stats_location=f'.stats["{collection_key}"]',
            correct_fdr=correct_fdr,
            contrast_mode=contrast_mode,
        )
        if return_diagnostics:
            return collection
        return collection

    def joint_de(
        self,
        groupby,
        *,
        reference=None,
        comparisons=None,
        contrasts=None,
        method="limma",
        layer="X",
        correct_fdr=True,
        fdr_scope="per_contrast",
        threshold=0.05,
        log2fc=1.0,
        store=True,
        stats_key=None,
    ):
        """
        Joint multi-group differential expression with one linear model per protein.

        Fits ``abundance ~ 0 + group`` once across **all** groups of ``groupby`` (ordinary
        least squares, independent samples), then tests any number of contrasts of the
        group means. Every contrast uses the residual variance pooled over all groups, so
        it has more degrees of freedom than separate two-group tests (assuming a similar
        within-group variance in every group). Use :meth:`de` for a single pairwise test and
        :meth:`mixed_de` for repeated measures / random effects.

        Args:
            groupby (str or list of str): Column(s) in ``.obs`` / ``.summary`` defining the groups.
                With a list the values are joined with ``"_"`` (e.g. ``"NP40_drug"``). Samples
                with a missing value are left out of the fit.
            reference (str, optional): Shared control group. Use with ``comparisons``.
            comparisons (str or list of str, optional): Groups tested against ``reference``;
                ``log2fc = comparison - reference``.
            contrasts (dict, optional): ``{name: (test, ref)}`` for a pair or
                ``{name: {group: weight}}`` for a weighted contrast. Weights must be non-zero and
                sum to 0; ``effect = sum(weight * group mean)``. Exclusive with
                ``reference`` / ``comparisons``.
            method (str): ``"limma"`` (default; moderated variance, empirical Bayes prior fitted
                once over all proteins, see :func:`scpviz.utils.limma.squeeze_variance`) or ``"lm"``
                (ordinary t-test with the pooled residual variance). Both give identical ``log2fc``.
            layer (str): Log-transformed layer (``log_transform`` first). Zeros are treated as missing.
            correct_fdr (bool): Benjamini-Hochberg correction. Default True.
            fdr_scope (str): ``"per_contrast"`` (default; proteins within each contrast),
                ``"global"`` (``adj_p_value`` is BH over all protein x contrast p-values) or
                ``"both"`` (per-contrast ``adj_p_value`` plus ``adj_p_value_global``).
            threshold (float): Significance cutoff (on ``adj_p_value`` if ``correct_fdr``).
            log2fc (float): Minimum ``|log2fc|`` for up/down labels.
            store (bool): Store the result in ``pdata.stats``.
            stats_key (str, optional): Override the auto-generated ``.stats`` key.

        Returns:
            dict: ``{"contrasts": {label: DataFrame}, "meta": dict, "diagnostics": DataFrame}``.
            Each contrast table follows the :meth:`de` columns (``log2fc``, ``p_value``,
            ``adj_p_value``, ``significance``, ...) plus ``se`` and per-group counts ``n_<group>``;
            proteins where a group in the contrast is unobserved have NaN results and are labelled
            ``"not comparable"``. ``diagnostics`` has per-protein group counts, ``df_residual``,
            ``s2`` and (limma) ``s2_post``, ``df_total``.

        Note:
            - Samples are assumed independent. For paired / repeated measurements use :meth:`mixed_de`.
            - Pooling assumes a similar residual variance in every group; restrict the samples
              (e.g. ``filter_sample``) if some groups are unrelated or much noisier.
            - Proteins with fewer observations than needed simply get NaN (never silently dropped);
              filter sparse proteins upstream (``filter_prot``), as for ``de(method='limma')``.
            - ``limma`` is the no-trend, non-robust moderation validated against R limma
              (``lmFit(~0+group)`` + ``contrasts.fit`` + ``eBayes``).

        Example:
            Several doses against one vehicle, moderated (default) and with plain pooled t-tests:
                ```python
                res = pdata.joint_de(
                    groupby="condition",
                    reference="vehicle",
                    comparisons=["low", "mid", "high"],
                )
                res_lm = pdata.joint_de(
                    groupby="condition", reference="vehicle",
                    comparisons=["low", "mid", "high"], method="lm",
                )
                label = list(res["contrasts"])[0]
                scplt.plot_volcano(ax, de_data=res["contrasts"][label], correct_fdr=True)
                ```

            Each detergent has its own vehicle, so name the pairs yourself:
                ```python
                pdata.joint_de(
                    groupby=["detergent", "treatment"],
                    contrasts={
                        "NP40 drug vs vehicle": ("NP40_drug", "NP40_vehicle"),
                        "DDM drug vs vehicle": ("DDM_drug", "DDM_vehicle"),
                    },
                )
                ```

            Does the drug work differently in the two detergents? (difference in differences):
                ```python
                pdata.joint_de(
                    groupby=["detergent", "treatment"],
                    contrasts={
                        "drug effect: NP40 minus DDM": {
                            "NP40_drug": +1, "NP40_vehicle": -1,
                            "DDM_drug": -1, "DDM_vehicle": +1,
                        },
                    },
                )
                ```
                In plain terms: first measure how much the drug changes a protein in NP40
                (``NP40_drug - NP40_vehicle``), then how much it changes it in DDM
                (``DDM_drug - DDM_vehicle``). The weights are just the plus/minus signs that
                perform "NP40 change minus DDM change" in one step: groups with ``+1`` are added,
                groups with ``-1`` are subtracted, and unlisted groups are ignored. The weights must
                add up to zero so that only differences, never overall levels, are compared.
                ``log2fc`` is then (change in NP40) - (change in DDM): near 0 means the drug acts
                the same in both detergents, positive means it raises the protein more in NP40.
                A protein that is significant in NP40 but not in DDM does *not* prove the
                detergents differ (one test may just be noisier); only this contrast tests that.
        """
        from scpviz.utils import joint_de as joint_de_utils

        if self.prot is None:
            raise ValueError(f"{format_log_prefix('error')} No .prot data available.")
        collection = joint_de_utils.run_joint_de(
            self.prot,
            getattr(self, "_summary", None),
            groupby=groupby, reference=reference, comparisons=comparisons, contrasts=contrasts,
            method=method, layer=layer, correct_fdr=correct_fdr, fdr_scope=fdr_scope,
            threshold=threshold, log2fc=log2fc,
        )
        key = stats_key or joint_de_utils.build_stats_key(groupby, reference, contrasts, method)
        if store:
            self._stats[key] = collection  # type: ignore[attr-defined]
            self._append_history(  # type: ignore[attr-defined]
                f"prot: joint_de ({method}) groupby={groupby!r}, {len(collection['contrasts'])} contrast(s) stored in .stats[{key!r}]."
            )
        joint_de_utils.print_joint_de_summary(collection, stats_location=f'.stats["{key}"]', correct_fdr=correct_fdr)
        return collection

    # TODO: Need to figure out how to make this interface with plot functions, probably do reordering by each class_value within the loop?
    def rank(self, classes = None, on = 'protein', layer = "X"):
        """
        Rank proteins or peptides by average abundance across sample groups.

        This method computes the average and standard deviation for each feature within 
        each group and assigns a rank (highest to lowest) based on the group-level mean.
        The results are stored in `.var` with one set of columns per group.

        Args:
            classes (str or list of str, optional): Sample-level class/grouping column(s) in `.obs`.
            on (str): Whether to compute ranks on "protein" or "peptide" data.
            layer (str): Name of the data layer to use (default is "X").

        Returns:
            None

        Example:
            Rank proteins by average abundance across treatment groups:
                ```python
                pdata.rank(classes="treatment", on="protein", layer="X_norm")
                ```
        """
        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            pass

        adata = self.prot if on == 'protein' else self.pep
        classes_list = utils.get_classlist(adata, classes)

        for class_value in classes_list:
            rank_data = utils.resolve_class_filter(adata, classes, class_value)
            if layer == "X":
                layer_data = rank_data.X.toarray()
            elif layer in rank_data.layers:
                layer_data = rank_data.layers[layer].toarray()
            else:
                raise ValueError(f"Layer '{layer}' not found in layers.")

            # Convert sparse to dense if needed
            if hasattr(layer_data, 'toarray'):
                layer_data = layer_data.toarray()

            # Transpose to get DataFrame of shape (features, samples)
            rank_df = pd.DataFrame(layer_data.T, index=rank_data.var.index, columns=rank_data.obs_names)

            # Compute stats
            avg_col = f"Average: {class_value}"
            std_col = f"Stdev: {class_value}"
            rank_col = f"Rank: {class_value}"

            with np.errstate(invalid='ignore', divide='ignore'):
                rank_df[avg_col] = np.nanmean(layer_data, axis=0)
                rank_df[std_col] = np.nanstd(layer_data, axis=0)

            # Sort by average (descending), assign rank
            rank_df.sort_values(by=avg_col, ascending=False, inplace=True)
            rank_df[rank_col] = np.where(rank_df[avg_col].isna(), np.nan, np.arange(1, len(rank_df) + 1))

            # Reindex back to original order in adata.var
            rank_df = rank_df.reindex(adata.var.index)

            adata.var[avg_col] = rank_df[avg_col]
            adata.var[std_col] = rank_df[std_col]
            adata.var[rank_col] = rank_df[rank_col]

        self._history.append(f"{on}: Ranked {layer} data. Ranking, average and stdev stored in var.") # type: ignore[attr-defined], HistoryMixin

    def impute(self, classes=None, layer="X", method='mean', on='protein', min_scale=1, set_X=True, use_zeros_as_nan=False, **kwargs):
        """
        Impute missing values across samples globally or within groups.

        This method imputes missing values in the specified data layer using one of several strategies.
        It supports both global (across all samples) and group-wise imputation based on sample classes.

        Args:
            classes (str or list of str, optional): Sample-level class/grouping column(s). If None, imputation is global.
            layer (str): Data layer to impute from (default is "X").
            method (str): Imputation strategy to use. Options include:

                - "mean": Fill missing values with the mean of each feature.
                - "median": Fill missing values with the median of each feature.
                - "min": Fill with the minimum observed value (0 if all missing).
                - "knn": Use K-nearest neighbors (only supported for global imputation).
                - "pimms_dae": PIMMS Denoising Autoencoder (global only).
                - "pimms_vae": PIMMS Variational Autoencoder (global only).
                - "pimms_cf":  PIMMS Collaborative Filtering (global only).

            on (str): Whether to impute "protein" or "peptide" data.
            min_scale (float): Scaled multiplication of minimum value for imputation, i.e. 0.2 would be 20% of minimum value (default is 1).
            set_X (bool): If True, updates `.X` to use the imputed result.
            use_zeros_as_nan: If True, treat 0 values as NaN before imputing. Mostly used after `directlfq` normalization, which returns NaNs as 0s. Defaults to False.
            **kwargs: Additional arguments passed to the imputer (e.g., `n_neighbors` for KNN).

        Returns:
            None

        Example:
            Globally impute missing values using the median strategy:
                ```python
                pdata.impute(method="median", on="protein")
                ```

            Group-wise imputation based on treatment:
                ```python
                pdata.impute(classes="treatment", method="mean", on="protein")
                ```

        Note:
            - KNN imputation is only supported for global (non-grouped) mode.
            - If `directlfq` was used for normalization, set `use_zeros_as_nan` flag to `True`. Else, no imputation will be performed as `directlfq` only returns 0s.
            - Features that are entirely missing within a group or across all samples are skipped and preserved as NaN.
            - Imputed results are stored in a new layer named `"X_impute_<method>"`.
            - Imputation summaries are printed to the console by group or overall.
            - PIMMS, which stands for **Proteomics Imputation Modeling Mass Spectrometry**, for more information see: the [package](https://github.com/RasmussenLab/pimms) or the [manuscript](https://www.nature.com/articles/s41467-024-48711-5#Fig1).
        """
        from sklearn.impute import SimpleImputer, KNNImputer
        from scipy import sparse
        from scpviz import utils


        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            return

        adata = self.prot if on == 'protein' else self.pep
        if layer != "X" and layer not in adata.layers:
            raise ValueError(f"Layer '{layer}' not found in .{on}.")

        _resolved_input = utils.resolve_input_layer(adata, layer)

        impute_data = adata.layers[layer] if layer != "X" else adata.X
        was_sparse = sparse.issparse(impute_data)
        impute_data = impute_data.toarray() if was_sparse else impute_data.copy()
        original_data = impute_data.copy()

        if use_zeros_as_nan:
            impute_data = impute_data.astype(float)
            zero_mask = (impute_data == 0)
            impute_data[zero_mask] = np.nan
            original_data[zero_mask] = np.nan
            nan_message = f"{format_log_prefix('info_only',2)} Using zeros as nans for imputation. Recommended after `directlfq` normalization."
        else:
            nan_message = None

        layer_name = f"X_impute_{method}"

        if method not in {"mean", "median", "min","knn","pimms_dae","pimms_vae","pimms_cf"}:
            raise ValueError(f"Unsupported method: {method}")

        if classes is None:
            # Global imputation
            if method == 'min':
                min_vals = np.nanmin(impute_data, axis=0)
                min_vals = np.where(np.isnan(min_vals), 0, min_vals)
                min_vals = min_vals * min_scale
                mask = np.isnan(impute_data)
                impute_data[mask] = np.take(min_vals, np.where(mask)[1])
            elif method == 'knn':
                n_neighbors = kwargs.get('n_neighbors', 3)
                imputer = KNNImputer(n_neighbors=n_neighbors)
                impute_data = imputer.fit_transform(impute_data)
            elif method in {"pimms_dae", "pimms_vae", "pimms_cf"}:
                try:
                    from pimmslearn.sklearn.ae_transformer import AETransformer
                    from pimmslearn.sklearn.cf_transformer import CollaborativeFilteringTransformer
                except ImportError:
                    raise ImportError(
                        "The 'pimmslearn' package is required for PIMMS imputation.\n"
                        "Install with: pip install pimms-learn"
                    )

                df = pd.DataFrame(
                    impute_data,
                    index=adata.obs_names,
                    columns=adata.var_names
                )

                df = np.log2(df + 1)

                # --- AE (DAE / VAE) -----------------------------------------
                if method in {"pimms_dae", "pimms_vae"}:
                    model_type = "DAE" if method == "pimms_dae" else "VAE"
                    model = AETransformer(
                        model=model_type,
                        hidden_layers=kwargs.get("hidden_layers", [512]),
                        latent_dim=kwargs.get("latent_dim", 50),
                        batch_size=kwargs.get("batch_size", 10),
                    )

                    model.fit(df,
                            cuda=kwargs.get("cuda", False),
                            epochs_max=kwargs.get("epochs_max", 100))
                    df_imputed = model.transform(df)

                else:  # pimms_cf (collaborative filtering)
                    index_name = "Sample ID"
                    column_name = "protein group"
                    value_name = "intensity"

                    df.index.name = index_name       # "Sample ID"
                    df.columns.name = column_name    # "protein group"

                    series = df.stack(dropna=False)
                    series.name = value_name

                    model = CollaborativeFilteringTransformer(
                        target_column=value_name,
                        sample_column=index_name,
                        item_column=column_name,
                        n_factors=kwargs.get("n_factors", 30),
                        batch_size=kwargs.get("batch_size", 4096),
                    )

                    model.fit(series,
                            cuda=kwargs.get("cuda", False),
                            epochs_max=kwargs.get("epochs_max", 20))
                    df_imputed = model.transform(series).unstack()

                # Convert result back
                df_imputed = (2 ** df_imputed) - 1
                impute_data = df_imputed.to_numpy()

                # Store metadata
                self.stats.setdefault("imputation", {})  # type: ignore[attr-defined]
                self.stats["imputation"]["pimms"] = {
                    "method": method,
                    "params": kwargs,
                    "samples": df.shape[0],
                    "features": df.shape[1],
                }

            else: # mean or median
                imputer = SimpleImputer(strategy=method, keep_empty_features=True)
                nan_columns = np.isnan(impute_data).all(axis=0)  # features fully missing in this group
                impute_data = imputer.fit_transform(impute_data)
                impute_data[:, nan_columns] = np.nan

            min_message = "" if method != 'min' else f"Minimum scaled by {min_scale}."
            print(f"{format_log_prefix('user')} Global imputation using '{method}'. Layer saved as '{layer_name}'. {min_message}")
            if nan_message is not None:
                print(nan_message)
            skipped_features = np.sum(np.isnan(impute_data).all(axis=0))

        else:
            # Group-wise imputation
            if method == 'knn':
                raise ValueError("KNN imputation is not supported for group-wise imputation.")
            if method.startswith("pimms"):
                raise ValueError("PIMMS imputation is only supported for global (classes=None) mode.")

            sample_names = utils.get_samplenames(adata, classes)
            sample_names = np.array(sample_names)
            unique_groups = np.unique(sample_names)

            for group in unique_groups:
                idx = np.where(sample_names == group)[0]
                group_data = impute_data[idx, :]

                if method == 'min':
                    min_vals = np.nanmin(group_data, axis=0)
                    min_vals = np.where(np.isnan(min_vals), 0, min_vals)
                    min_vals = min_vals * min_scale
                    mask = np.isnan(group_data)
                    group_data[mask] = np.take(min_vals, np.where(mask)[1])
                    imputed_group = group_data
                else:
                    imputer = SimpleImputer(strategy=method, keep_empty_features=True)
                    nan_columns = np.isnan(group_data).all(axis=0)  # features fully missing in this group
                    imputed_group = imputer.fit_transform(group_data)
                    imputed_group[:, nan_columns] = np.nan # restore fully missing features

                impute_data[idx, :] = imputed_group

            min_message = "" if method != 'min' else f"Minimum scaled by {min_scale}."
            print(f"{format_log_prefix('user')} Group-wise imputation using '{method}' on class(es): {classes}. Layer saved as '{layer_name}'. {min_message}")

        summary_lines = []
        if classes is None:
            num_imputed = np.sum(np.isnan(original_data) & ~np.isnan(impute_data))
            # Row-wise missingness
            was_missing = np.isnan(original_data).any(axis=1)
            now_complete = ~np.isnan(impute_data).any(axis=1)
            now_incomplete = np.isnan(impute_data).any(axis=1)

            fully_imputed_samples = np.sum(was_missing & now_complete)
            partially_imputed_samples = np.sum(was_missing & now_incomplete)
            skipped_features = np.sum(np.isnan(impute_data).all(axis=0))

            summary_lines.append(
                f"{format_log_prefix('result_only', indent=2)} {num_imputed} values imputed."
            )
            summary_lines.append(
                f"{format_log_prefix('info_only', indent=2)} {fully_imputed_samples} samples fully imputed, {partially_imputed_samples} samples partially imputed, {skipped_features} skipped feature(s) with all missing values."
            )

        else:
            sample_names = utils.get_samplenames(adata, classes)
            sample_names = np.array(sample_names)
            unique_groups = np.unique(sample_names)

            counts_by_group = {}
            fully_by_group = {}
            partial_by_group = {}
            missing_features_by_group = {}
            total_samples_by_group = {}

            for group in unique_groups:
                idx = np.where(sample_names == group)[0]
                before = original_data[idx, :]
                after = impute_data[idx, :]

                # count imputed values
                mask = np.isnan(before) & ~np.isnan(after)
                counts_by_group[group] = np.sum(mask)

                # count fully and partially imputed samples
                was_missing = np.isnan(before).any(axis=1)
                now_complete = ~np.isnan(after).any(axis=1)
                now_incomplete = np.isnan(after).any(axis=1)
                now_missing = np.sum(np.isnan(before).all(axis=0))

                fully_by_group[group] = np.sum(was_missing & now_complete)
                partial_by_group[group] = np.sum(was_missing & now_incomplete)
                missing_features_by_group[group] = now_missing
                total_samples_by_group[group] = len(idx)

            # Compute dynamic width based on longest group name
            group_width = max(max(len(str(g)) for g in unique_groups), 20)

            # Summary totals
            total = sum(counts_by_group.values())
            summary_lines.append(f"{format_log_prefix('result_only', indent=2)} {total} values imputed total.")
            summary_lines.append(f"{format_log_prefix('info_only', indent=2)} Group-wise summary:")

            # Header row (aligned with computed width)
            header = (f"{'Group':<{group_width}} | Values Imputed | Skipped Features | Samples Imputed (Partial,Fully)/Total")
            divider = "-" * len(header)
            summary_lines.append(f"{' ' * 5}{header}")
            summary_lines.append(f"{' ' * 5}{divider}")

            # Data rows
            for group in unique_groups:
                count = counts_by_group[group]
                fully = fully_by_group[group]
                partial = partial_by_group[group]
                skipped = missing_features_by_group[group]
                total_samples = total_samples_by_group[group]
                summary_lines.append(
                    f"{' ' * 5}{group:<{group_width}} | {count:>14} | {skipped:>16} | {partial:>7}, {fully:>5} / {total_samples:<3}"
                )

        print("\n".join(summary_lines))

        actual_layer_name = utils.update_layer_provenance(
            adata,
            layer_name=layer_name,
            op="impute",
            input_layer=_resolved_input,
            method=method,
        )
        adata.layers[actual_layer_name] = (
            sparse.csr_matrix(impute_data) if was_sparse else impute_data
        )

        if set_X:
            self.set_X(layer=actual_layer_name, on=on)  # type: ignore[attr-defined], EditingMixin

        self._history.append(  # type: ignore[attr-defined]
            f"{on}: Imputed layer '{layer}' using '{method}' (grouped by {classes if classes else 'ALL'}). "
            f"Stored in '{actual_layer_name}'."
        )

    def log_transform(
        self,
        on: str = "protein",
        layer: str = "X",
        base: int | float | str = 2,
        pseudocount: float = 1.0,
        set_X: bool = True,
    ) -> None:
        """
        Log-transform intensities with a pseudocount and register layer provenance.

        Output is stored under a short fixed name: ``X_log2``, ``X_log10``, or ``X_loge``.
        If that name already exists with a different origin, a numeric suffix is applied
        (see :func:`scpviz.utils.update_layer_provenance`).

        Args:
            on: ``\"protein\"`` / ``\"prot\"`` or ``\"peptide\"`` / ``\"pep\"``.
            layer: Source layer (default ``\"X\"``).
            base: ``2``, ``10``, ``\"e\"``, or ``numpy.e``.
            pseudocount: Added before the logarithm (default ``1.0``).
            set_X: If True, point ``.X`` at the new log layer.
        """
        if not self._check_data(on):  # type: ignore[attr-defined], ValidationMixin
            return

        adata = utils.get_adata(self, on)
        SUPPORTED_BASES = {2: np.log2, 10: np.log10, "e": np.log, np.e: np.log}
        if base not in SUPPORTED_BASES:
            raise ValueError(
                f"{format_log_prefix('error')} base={base!r} not supported. "
                "Choose from: 2, 10, 'e', or numpy.e."
            )
        log_fn = SUPPORTED_BASES[base]

        base_str = (
            "e"
            if base in ("e", np.e)
            else (str(int(base)) if float(base) == int(float(base)) else str(base))
        )
        layer_name = f"X_log{base_str}"

        if layer == "X":
            raw_mx = adata.X
            data = raw_mx.toarray() if sparse.issparse(raw_mx) else raw_mx.copy()
        elif layer in adata.layers:
            raw_mx = adata.layers[layer]
            data = raw_mx.toarray() if sparse.issparse(raw_mx) else np.asarray(raw_mx)
        else:
            raise KeyError(
                f"{format_log_prefix('error')} Layer {layer!r} not found in adata.layers."
            )

        _already_log = utils.infer_layer_is_log(layer, adata)
        if _already_log:
            print(
                f"{format_log_prefix('warn')} Layer {layer!r} appears to already be "
                "log-transformed (provenance registry or layer name). "
                f"Proceeding — result stored under the resolved output layer name."
            )

        n_negative = int(np.sum(data < 0))
        if n_negative > 0:
            print(
                f"{format_log_prefix('warn')} {n_negative} value(s) < 0 detected. "
                f"Pseudocount ({pseudocount}) added — negative values become "
                f"log({pseudocount}). Consider checking your normalization."
            )

        data_log = log_fn(data + pseudocount)

        was_sparse = sparse.issparse(
            adata.layers[layer] if layer != "X" else adata.X
        )
        _resolved_input = utils.resolve_input_layer(adata, layer)
        actual_layer_name = utils.update_layer_provenance(
            adata,
            layer_name=layer_name,
            op="log_transform",
            input_layer=_resolved_input,
            base=base_str,
            pseudocount=pseudocount,
        )
        adata.layers[actual_layer_name] = (
            sparse.csr_matrix(data_log) if was_sparse else data_log
        )

        on_norm = "protein" if on in ("protein", "prot") else "peptide"
        subpdata = "prot" if on_norm == "protein" else "pep"
        log_prefix = format_log_prefix("user")
        print(f"{log_prefix} Log-transforming [{on_norm}] layer: {layer!r} → {actual_layer_name!r}")
        print(f"     🔸 base: {base_str} log base (pseudocount {pseudocount})")
        print(f"{format_log_prefix('result_only', indent=2)} Log transform complete. Results stored in:")
        print(f"       • .{subpdata}.layers[{actual_layer_name!r}]")
        if set_X:
            print(f"       • .{subpdata}.X updated")
        print(f"       • .{subpdata}.uns['layer_provenance'][{actual_layer_name!r}] updated")

        if set_X:
            self.set_X(layer=actual_layer_name, on=on)  # type: ignore[attr-defined]

        self._append_history(  # type: ignore[attr-defined]
            f"{on_norm}: log_transform(base={base}, pseudocount={pseudocount}) on layer={layer!r}. "
            f"Stored in {actual_layer_name!r}."
        )

    def neighbor(self, on = 'protein', layer = "X", use_rep='X_pca', user_indent=0, **kwargs):
        """
        Compute a neighbor graph based on protein or peptide data.

        This method builds a nearest-neighbors graph for downstream analysis using 
        `scanpy.pp.neighbors`. It optionally performs PCA before constructing the graph 
        if a valid representation is not already available.

        Args:
            on (str): Whether to use "protein" or "peptide" data.
            layer (str): Data layer to use (default is "X").
            use_rep (str): Key in `.obsm` to use for computing neighbors. Default is `"X_pca"`.
                If `"X_pca"` is requested, PCA will be run automatically. If an alternative rep is provided, PCA will not be re-run.
            **kwargs: Additional keyword arguments passed to `scanpy.pp.neighbors()`.

        Returns:
            None

        Example:
            Compute neighbors using default PCA representation:
                ```python
                pdata.neighbor(on="protein", layer="X")
                ```

            Use a custom representation stored in `.obsm["X_umap"]`:
                ```python
                pdata.neighbor(on="protein", use_rep="X_umap", n_neighbors=15)
                ```

        Note:
            - The neighbor graph is stored in `.obs["distances"]` and `.obs["connectivities"]`.
            - Neighbor metadata is stored in `.uns["neighbors"]`.
            - Automatically calls `self.set_X()` if a non-default layer is specified.
            - PCA is computed automatically if `use_rep='X_pca'`, else neighbor will use the rep provided by the user.

        Todo:
            Allow users to supply a custom `KNeighborsTransformer` or precomputed neighbor graph.
                ```python
                from sklearn.neighbors import KNeighborsTransformer
                transformer = KNeighborsTransformer(n_neighbors=10, metric='manhattan', algorithm='kd_tree')
                ```
        """
        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            pass

        if on.lower() in ["prot", "protein"]:
            adata = self.prot
        elif on.lower() in ["pep", "peptide"]:
            adata = self.pep

        if layer == "X":
            # do nothing
            pass
        elif layer in adata.layers.keys():
            self.set_X(layer = layer, on = on) # type: ignore[attr-defined], EditingMixin

        log_prefix = format_log_prefix("user") if user_indent == 0 else format_log_prefix("user_only",2)
        print(f"{log_prefix} Computing neighbors [{on}] using layer: {layer}")

        if use_rep == 'X_pca':
            print(f"{format_log_prefix('info_only',indent=2)} Recomputing PCA for neighbor graph.")
            self.pca(on=on, layer=layer)
        else:
            if use_rep not in adata.obsm:
                raise ValueError(f"PCA key '{use_rep}' not found in obsm. Please run PCA first and specify a valid key.")
            print(f"{format_log_prefix('info_only',indent=2)} Using '{use_rep}' found in obsm for neighbor graph.")

        if use_rep == 'X_pca':
            sc.pp.neighbors(adata, **kwargs)
        else:
            sc.pp.neighbors(adata, use_rep=use_rep, **kwargs)

        self._append_history(f'{on}: Neighbors fitted on {layer}, using {use_rep}, stored in obs["distances"] and obs["connectivities"]') # type: ignore[attr-defined], HistoryMixin
        print(f"{format_log_prefix('result_only',indent=2)} Neighbors computed on {layer}, using {use_rep}. Results stored in:")
        print(f"       • obs['distances'] (pairwise distances)")
        print(f"       • obs['connectivities'] (connectivity graph)")
        print(f"       • uns['neighbors'] (neighbor graph metadata)")

    def leiden(self, on = 'protein', layer = "X", **kwargs):
        """
        Perform Leiden clustering on protein or peptide data.

        This method runs community detection using the Leiden algorithm based on a precomputed
        neighbor graph using `scanpy.tl.leiden()`. If neighbors are not already computed, they will be generated automatically.

        Args:
            on (str): Whether to use "protein" or "peptide" data.
            layer (str): Data layer to use for clustering (default is "X").
            **kwargs: Additional keyword arguments passed to `scanpy.tl.leiden()`.

        Returns:
            None

        Example:
            Perform Leiden clustering using the default PCA-based neighbors:
                ```python
                pdata.leiden(on="protein", layer="X", resolution=0.25)
                ```

        Note:
            - Cluster labels are stored in `.obs["leiden"]`.
            - Neighbor graphs are automatically computed if not present in `.uns["neighbors"]`.
            - Automatically sets `.X` to the specified layer if it is not already active.
        """
        # uses sc.tl.leiden with default resolution of 0.25
        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            pass

        if on == 'protein':
            adata = self.prot
        elif on == 'peptide':
            adata = self.pep

        log_prefix = format_log_prefix("user")
        print(f"{log_prefix} Performing Leiden clustering [{on}] using layer: {layer}")

        if 'resolution' in kwargs:
            resolution = kwargs.pop("resolution", 0.25)

        if 'neighbors' not in adata.uns:
            print(f"{format_log_prefix('info_only', indent=2)} Neighbors not found in AnnData object. Running neighbors with default settings.")
            self.neighbor(on = on, layer = layer, **kwargs)

        if layer == "X":
            # do nothing
            pass
        elif layer in adata.layers.keys():
            self.set_X(layer = layer, on = on) # type: ignore[attr-defined], EditingMixin

        sc.tl.leiden(adata, resolution)
        self.update_summary(recompute=False, verbose=False) # type: ignore[attr-defined], SummaryMixin

        self._append_history(f'{on}: Leiden clustering fitted on {layer}, stored in obs["leiden"]') # type: ignore[attr-defined], HistoryMixin
        print(f"{format_log_prefix('result_only', indent=2)} Leiden clustering complete. Results stored in:")
        print(f"       • obs['leiden'] (cluster labels)")

    def umap(self, on = 'protein', layer = "X", force_neighbors=False, **kwargs):
        """
        Compute UMAP dimensionality reduction on protein or peptide data.

        This method runs UMAP (Uniform Manifold Approximation and Projection) on the selected data layer using `scanpy.tl.umap()`.
        If neighbor graphs are not already computed, they will be generated automatically.

        Args:
            on (str): Whether to use "protein" or "peptide" data.
            layer (str): Data layer to use for UMAP (default is "X").
            force_neighbors (bool): If True, recompute neighbors even if they exist.
            **kwargs: Additional keyword arguments passed to `scanpy.tl.umap()`, `scanpy.tl.neighbor()` or the scpviz `pca` function. If provided, neighbor() will always be recomputed.
                Example:
                    "n_neighbors": neighbor argument
                    "min_dist": umap argument
                    "metric": neighbor argument
                    "spread": umap argument
                    "random_state": umap argument
                    "n_pcs": neighbor argument

        Returns:
            None

        Example:
            Run UMAP using default settings:
                ```python
                pdata.umap(on="protein", layer="X")
                ```
        Note:
            - UMAP coordinates are stored in `.obsm["X_umap"]`.
            - UMAP settings are stored in `.uns["umap"]`.
            - Automatically computes neighbor graphs if not already available.
            - Will call `.set_X()` if a non-default layer is used.
        """
        # uses sc.tl.umap
        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            pass

        if on == 'protein':
            adata = self.prot
        elif on == 'peptide':
            adata = self.pep

        log_prefix = format_log_prefix("user")
        print(f"{log_prefix} Computing UMAP [{on}] using layer: {layer}")

        if "n_neighbors" in kwargs or "metric" in kwargs or "n_pcs" in kwargs:
                    n_neighbors = kwargs.pop("n_neighbors", None)
                    metric = kwargs.pop("metric", None)
                    n_pcs = kwargs.pop("n_pcs", None)

                    # Prepare a readable message
                    neighbor_args = []
                    if n_neighbors is not None:
                        neighbor_args.append(f"n_neighbors={n_neighbors}")
                    else:
                        n_neighbors = 15  # default value
                    if metric is not None:
                        neighbor_args.append(f"metric='{metric}'")
                    else:
                        metric = "euclidean"  # default value
                    if n_pcs is not None:
                        neighbor_args.append(f"n_pcs={n_pcs}")
                    else:
                        n_pcs = 50
                    arg_str = ", ".join(neighbor_args)

                    print(f"{format_log_prefix('info_only', indent=2)} {arg_str} provided. "
                        f"Re-running neighbors with these settings before UMAP.")

                    self.neighbor(on=on, layer=layer, n_neighbors=n_neighbors, metric=metric, user_indent=2)
                    self._append_history(f"{on}: Neighbors re-computed with {arg_str} before UMAP")  # type: ignore[attr-defined], HistoryMixin
        else:
            # check if neighbor has been run before, look for distances and connectivities in obsp
            if force_neighbors:
                self.neighbor(on=on, layer=layer)
                self._append_history(f"{on}: Neighbors computed with default settings before UMAP")
            elif 'neighbors' not in adata.uns:
                print(f"{format_log_prefix('info_only', indent=2)} Neighbors not found in AnnData object. Running neighbors with default settings.")
                self.neighbor(on = on, layer = layer)
                self._append_history(f"{on}: Neighbors computed with default settings before UMAP")  # type: ignore[attr-defined], HistoryMixin
            else:
                print(f"{format_log_prefix('info_only', indent=2)} Using existing neighbors found in AnnData object.")

        if layer == "X":
            # do nothing
            pass
        elif layer in adata.layers.keys():
            self.set_X(layer = layer, on = on) # type: ignore[attr-defined], EditingMixin

        sc.tl.umap(adata, **kwargs)

        self._append_history(f'{on}: UMAP fitted on {layer}, stored in obsm["X_umap"] and uns["umap"]') # type: ignore[attr-defined], HistoryMixin
        print(f"{format_log_prefix('result_only', indent=2)} UMAP complete. Results stored in:")
        print(f"       • obsm['X_umap'] (UMAP coordinates)")
        print(f"       • uns['umap'] (UMAP settings)")

    def pca(self, on = 'protein', layer = "X", **kwargs):
        """
        Perform PCA (Principal Component Analysis) on protein or peptide data.

        This method performs PCA on the selected data layer, after z-score normalization and removal of
        NaN-containing features. The results are stored in `.obsm["X_pca"]` and `.uns["pca"]`.

        Args:
            on (str): Whether to use "protein" or "peptide" data.
            layer (str): Data layer to use for PCA (default is "X").
            **kwargs: Additional keyword arguments passed to `scanpy.tl.pca()`. For example,
                `key_added` to store PCA in a different key.

        Returns:
            None

        Note:
            - Features (columns) with NaN values are excluded before PCA and then padded with zeros.
            - PCA scores are stored in `.obsm['X_pca']`.
            - Principal component loadings, variance ratios, and total variances are stored in `.uns['pca']`.
            - If you store PCs under a custom key using `key_added`, remember to set `use_rep` when calling `.neighbor()` or `.umap()`.
        """

        # uses sc.tl.pca
        # for kwargs can use key_added to store PCA in a different key - then for neighbors need to specify key by use_rep
        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            pass

        if on == 'protein':
            adata = self.prot
        elif on == 'peptide':
            adata = self.pep

        # make sample array
        if layer == "X":
            X = adata.X.toarray()
        elif layer in adata.layers.keys():
            X = adata.layers[layer].toarray()

        _layer_is_log_pca = utils.infer_layer_is_log(layer, adata)
        _finite_pca = X[np.isfinite(X)]
        if not _layer_is_log_pca and _finite_pca.size > 0 and np.nanmedian(_finite_pca) > 1e4:
            print(
                f"{format_log_prefix('info')} Layer {layer!r} appears to contain "
                f"non-log intensities (median={np.nanmedian(_finite_pca):.2e}). "
                "PCA will proceed with z-scoring (standard practice). Optionally "
                "run pdata.log_transform() first for better low-abundance separation."
            )
        elif _layer_is_log_pca:
            print(
                f"{format_log_prefix('info')} Layer {layer!r} detected as log-transformed. "
                "Using log-space values for PCA."
            )

        log_prefix = format_log_prefix("user")
        print(f"{log_prefix} Performing PCA [{on}] using layer: {layer}, removing NaN features.")
        print(f"   🔸 BEFORE (samples × proteins): {X.shape}")
        Xnorm = (X - X.mean(axis=0)) / X.std(axis=0)
        nan_cols = np.isnan(Xnorm).any(axis=0)
        Xnorm = Xnorm[:, ~nan_cols]
        print(f"   🔸 AFTER  (samples × proteins): {Xnorm.shape}")

        # TODO: fix bug here (ValueError: n_components=59 must be between 1 and min(n_samples, n_features)=31 with svd_solver='arpack')
        pca_data = sc.tl.pca(Xnorm, return_info=True, **kwargs)
        adata.obsm['X_pca'] = pca_data[0]
        PCs = np.zeros((pca_data[1].shape[0], nan_cols.shape[0]))

        # fill back the 0s where column was NaN in the original data, and thus not used in PCA
        counter = 0
        for i in range(PCs.shape[1]):
            if not nan_cols[i]:
                PCs[:, i] = pca_data[1][:, counter]
                counter += 1

        adata.uns['pca'] = {'PCs': PCs, 'variance_ratio': pca_data[2], 'variance': pca_data[3]}

        subpdata = "prot" if on == 'protein' else "pep"

        self._append_history(f'{on}: PCA fitted on {layer}, stored in obsm["X_pca"] and uns["pca"]["PCs"]') # type: ignore[attr-defined], HistoryMixin
        print(f"{format_log_prefix('result_only',indent=2)} PCA complete, fitted on {layer}. Results stored in:")
        print(f"       • .{subpdata}.obsm['X_pca']")
        print(f"       • .{subpdata}.uns['pca'] (includes PCs, variance, variance ratio)")
        var_pc1, var_pc2 = pca_data[2][:2]
        print(f"       • Variance explained by PC1/PC2: {var_pc1*100:.2f}% , {var_pc2*100:.2f}%") 

    def harmony(self, key, on = 'protein', **kwargs):
        """
        Perform batch correction using Harmony integration.

        This method applies Harmony-based batch correction (via `scanpy.external.pp.harmony_integrate`)
        on PCA-reduced protein or peptide data to mitigate batch effects across samples.

        Args:
            key (str): Column name in `.obs` representing the batch variable to correct.
            on (str): Whether to use "protein" or "peptide" data. Accepts "prot"/"protein" or "pep"/"peptide" (default: "protein").
            **kwargs: Passed to `harmonypy.run_harmony` (e.g. `nclust`, `max_iter_harmony`, `theta`).
                With few samples, set `nclust` explicitly; harmonypy's default can be 0 and fail.

        Returns:
            None

        Example:
            Perform Harmony integration on protein-level PCA embeddings:
                ```python
                pdata.harmony(key="batch", on="protein")
                ```

            Apply Harmony on peptide-level data instead:
                ```python
                pdata.harmony(key="run_id", on="peptide")
                ```

        Note:
            - Harmony requires prior PCA computation. If PCA is missing, it will be computed automatically.
            - The Harmony-corrected coordinates are stored in `.obsm["X_pca_harmony"]`.
            - Updates the processing history via `.history`.
        """

        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            pass

        if on == 'protein' or on == 'prot':
            adata = self.prot
        elif on == 'peptide' or on == 'pep':
            adata = self.pep

        log_prefix = format_log_prefix("user")
        print(f"{log_prefix} Performing Harmony batch correction on [{on}] PCA.")

        # check if pca has been run before, look for distances and connectivities in obsp
        if 'pca' not in adata.uns:
            print(f"{format_log_prefix('info_only', indent=2)} PCA not found in AnnData object. Running PCA with default settings.")
            self.pca(on = on, layer = "X")

        # check that key is valid column in adata.obs
        if key not in adata.obs.columns:
            raise ValueError(f"Batch key '{key}' not found in adata.obs.")

        sc.external.pp.harmony_integrate(adata, key, **kwargs)

        self._append_history(f'{on}: Harmony batch correction applied on key {key}, stored in obsm["X_pca_harmony"] and uns["umap"]') # type: ignore[attr-defined], HistoryMixin
        print(f"{format_log_prefix('result_only', indent=2)} Harmony batch correction complete. Results stored in:")
        print(f"       • obsm['X_pca_harmony'] (PCA coordinates)")

    def pca_gsea(self, pcs=[1, 2], on="protein", gene_sets=(
        "KEGG_2026,Reactome_Pathways_2024,WikiPathways_2024_Human,"
        "GO_Biological_Process_2025,MSigDB_Hallmark_2020"
    ), gene_col="Genes",
        min_size=5, max_size=500, permutation_num=1000, weight=1, threads=4, seed=0,
        key_added="pca_gsea", verbose=True, fdr_report_cutoffs=(0.05, 0.25), **kwargs,):
        """
        Run preranked GSEA on PCA loadings for selected principal components.

        Args:
            pcs (list[int] or None): Principal components to analyze, 1-indexed.
                Defaults to [1, 2]. If None, run all available PCs.
            on (str): Whether to use "protein" or "peptide" data.
            gene_sets (str or dict): Enrichr library name(s) for GSEApy. Pass a comma-separated
                string to merge multiple libraries; pathway keys are prefixed ``LIBRARY__term``
                in merged results.
            gene_col (str): Column in `.var` containing gene symbols.
            min_size (int): Minimum gene set size.
            max_size (int): Maximum gene set size.
            permutation_num (int): Number of permutations for prerank.
            weight (float): Weighting parameter for enrichment score.
            threads (int): Number of threads for GSEApy.
            seed (int): Random seed.
            key_added (str): Key for storing results in `.uns`.
            verbose (bool): Whether to print progress.
            fdr_report_cutoffs (tuple[float, ...]): FDR thresholds for verbose per-PC reporting
                (counts of terms with ``FDR q-val`` at or below each cutoff). Default ``(0.05, 0.25)``.
                Pass an empty tuple to omit.
            **kwargs: Additional keyword arguments passed to `gseapy.prerank()`.

        Returns:
            None

        Note:
            Each DataFrame in ``.{prot|pep}.uns[key_added]['results']`` includes gseapy columns
            plus ``library`` and ``pathway`` parsed from ``Term`` when using merged libraries
            (``LIBRARY__pathway_name``).
        """
        if not self._check_data(on):  # type: ignore[attr-defined]
            return

        if on == "protein":
            adata = self.prot
        elif on == "peptide":
            adata = self.pep
        else:
            raise ValueError("`on` must be either 'protein' or 'peptide'.")

        subpdata = "prot" if on == "protein" else "pep"

        if "pca" not in adata.uns or "PCs" not in adata.uns["pca"]:
            print(f"{format_log_prefix('warn')} PCA results not found in .{subpdata}.uns['pca'].")
            print(f"{format_log_prefix('blank', 3)} Please run `.pca()` first, then rerun `pca_gsea()`.")
            return

        # additional helper functions
        import logging
        import io
        from contextlib import contextmanager, redirect_stdout, redirect_stderr

        @contextmanager
        def _suppress_gseapy_output():
            previous_disable = logging.root.manager.disable
            sink = io.StringIO()
            logging.disable(logging.ERROR)
            try:
                with redirect_stdout(sink), redirect_stderr(sink):
                    yield
            finally:
                logging.disable(previous_disable)

        def _percent_tied_values(values):
            """Return percent of entries that are part of a duplicated value group."""
            s = pd.Series(values)
            if s.empty:
                return 0.0
            return 100 * s.duplicated(keep=False).sum() / len(s)

        def _build_pca_rank_df(adata, genes, loadings, use_abs_for_duplicates=False):
            rank_df = pd.DataFrame({
                "feature": adata.var_names.astype(str),
                "gene": genes.values,
                "loading": loadings,
            }).dropna(subset=["gene"]).copy()

            dup_genes = sorted(rank_df.loc[rank_df["gene"].duplicated(keep=False), "gene"].unique())

            if len(dup_genes) > 0:
                if use_abs_for_duplicates:
                    idx = rank_df.groupby("gene")["loading"].agg(lambda x: x.abs().idxmax())
                else:
                    idx = rank_df.groupby("gene")["loading"].idxmax()
                rank_df = rank_df.loc[idx].copy()

            rank_df["abs_loading"] = rank_df["loading"].abs()
            rank_df = rank_df.sort_values("loading", ascending=False).reset_index(drop=True)
            return rank_df, dup_genes

        # ----------------------------------

        genes = _gseapy_resolve_uppercase_genes(
            adata,
            gene_col=gene_col,
        )

        if genes is None:
            context="PCA GSEA"
            print(f"{format_log_prefix('warn')} `.var[{gene_col!r}]` not found.")
            print(f"{format_log_prefix('blank',3)} {context} requires resolved gene symbols.")
            print(f"{format_log_prefix('blank',3)} Please annotate gene names first, then rerun.")
            return

        pcs_all = adata.uns["pca"]["PCs"]
        n_pcs_available = pcs_all.shape[0]

        if pcs is None:
            pcs = list(range(1, n_pcs_available + 1))
            print(f"{format_log_prefix('warn')} `pcs=None` detected – running GSEA on all available PCs.")
            print(f"{format_log_prefix('blank', 3)} This may take a long time, especially with many PCs or large gene set libraries.")

        if not isinstance(pcs, (list, tuple, np.ndarray)):
            raise ValueError("`pcs` must be a list of integers or None.")

        pcs = [int(pc) for pc in pcs]

        invalid_pcs = [pc for pc in pcs if pc < 1 or pc > n_pcs_available]
        if invalid_pcs:
            raise ValueError(
                f"Invalid PCs requested: {invalid_pcs}. "
                f"Available PCs are 1 to {n_pcs_available}."
            )

        # Precompute tied-loading percentages once per requested PC
        _, dup_genes = _build_pca_rank_df(adata, genes, pcs_all[pcs[0] - 1, :], use_abs_for_duplicates=True)
        tied_pct_by_pc = {}
        for pc in pcs:
            loadings = pcs_all[pc - 1, :]
            rank_df_tmp, _ = _build_pca_rank_df(adata, genes, loadings, use_abs_for_duplicates=True)
            rnk_tmp = rank_df_tmp.set_index("gene")["loading"]
            tied_pct_by_pc[pc] = _percent_tied_values(rnk_tmp.values)

        if verbose:
            print(f"{format_log_prefix('user')} Running PCA GSEA [{on}] on PCs: {pcs}", flush=True)
            print(f"   🔸 Gene set library: {gene_sets}")
            print(f"   🔸 Gene column: {gene_col}")

            if len(dup_genes) > 0:
                preview = ", ".join(dup_genes[:10])
                suffix = " ..." if len(dup_genes) > 10 else ""
                print(f"{format_log_prefix('warn_only',2)} Duplicated genes ({len(dup_genes)}): {preview}{suffix}")
                print(f"     Using maximum absolute loading for duplicated genes.")

                base_params = dict(min_size=min_size, max_size=max_size, permutation_num=permutation_num, weight=weight, threads=threads, seed=seed)
                params = {**base_params, **kwargs}
                param_str = ", ".join(f"{k}={v}" for k, v in params.items())

                print(f"{format_log_prefix('api',2)} gseapy.prerank({param_str})")

            tied_msg = ", ".join([f"PC{pc} {tied_pct_by_pc[pc]:.2f}%" for pc in pcs])
            print(f"{format_log_prefix('info_only',3)} Tied prerank stats: {tied_msg}. GSEApy may order tied genes arbitrarily.")

        stored_results = {}
        stored_rankings = {}

        for pc in pcs:
            loadings = pcs_all[pc - 1, :]

            rank_df, _ = _build_pca_rank_df(adata, genes, loadings, use_abs_for_duplicates=True)
            rnk = rank_df.set_index("gene")["loading"]

            if verbose:
                print(
                    f"{format_log_prefix('blank',3)}🔹 PC{pc}: "
                    f"{len(loadings)} features -> "
                    f"{rank_df.shape[0]} unique uppercase genes"
                )

            with _suppress_gseapy_output():
                pre_res = gp.prerank(
                    rnk=rnk,
                    gene_sets=gene_sets,
                    min_size=min_size,
                    max_size=max_size,
                    permutation_num=permutation_num,
                    weight=weight,
                    threads=threads,
                    seed=seed,
                    outdir=None,
                    verbose=False,
                    **kwargs,
                )

            res_df = _annotate_pca_gsea_result_df(pre_res.res2d.copy())
            stored_results[f"PC{pc}"] = res_df
            stored_rankings[f"PC{pc}"] = rank_df.copy()

            if verbose:
                msg = f"{format_log_prefix('result_only', 4)} PC{pc}: {res_df.shape[0]} enriched terms returned"
                fdr_col = "FDR q-val"
                if fdr_report_cutoffs and fdr_col in res_df.columns:
                    s = pd.to_numeric(res_df[fdr_col], errors="coerce")
                    parts = [f"n(FDR<={c})={int((s <= c).sum())}" for c in fdr_report_cutoffs]
                    msg += "; " + ", ".join(parts)
                elif fdr_report_cutoffs and fdr_col not in res_df.columns:
                    msg += f"; (no '{fdr_col}' column for FDR counts)"
                print(msg)

        adata.uns[key_added] = {
            "params": {
                "pcs": pcs,
                "gene_sets": gene_sets,
                "gene_col": gene_col,
                "min_size": min_size,
                "max_size": max_size,
                "permutation_num": permutation_num,
                "weight": weight,
                "threads": threads,
                "seed": seed,
                "on": on,
            },
            "results": stored_results,
            "rankings": stored_rankings,
        }

        self._append_history(  # type: ignore[attr-defined]
            f'{on}: PCA GSEA run on PCs {pcs}, stored in .{subpdata}.uns["{key_added}"]'
        )

        if verbose:
            print(f"{format_log_prefix('result')} PCA GSEA complete.")
            print(f"   • Results stored in: .{subpdata}.uns['{key_added}']['results']")
            print(f"   • Keys: {list(stored_results.keys())}")

    def ssgsea(self, on="protein", layer="X", gene_sets="GO_Biological_Process_2023", gene_col="Genes", 
               min_size=5, max_size=500, threads=4, seed=0, key_added="ssgsea", verbose=True, **kwargs,):
        """
        Compute per-sample ssGSEA pathway scores.

        Args:
            on (str): Whether to use "protein" or "peptide" data.
            layer (str): Data layer to use.
            gene_sets (str or dict): Gene set library for GSEApy.
            gene_col (str): Column in `.var` containing gene symbols.
            min_size (int): Minimum gene set size.
            max_size (int): Maximum gene set size.
            threads (int): Number of threads for GSEApy.
            seed (int): Random seed.
            key_added (str): Base key for storing results.
            verbose (bool): Whether to print progress.
            **kwargs: Additional keyword arguments passed to `gseapy.ssgsea()`.

        Returns:
            None
        """
        if not self._check_data(on):  # type: ignore[attr-defined]
            return

        if on == 'protein':
            adata = self.prot
        elif on == 'peptide':
            adata = self.pep
        else:
            raise ValueError("`on` must be either 'protein' or 'peptide'.")

        genes = _gseapy_resolve_uppercase_genes(
            adata,
            gene_col=gene_col,
        )

        if genes is None:
            context="ssGSEA"
            print(f"{format_log_prefix('warn')} `.var[{gene_col!r}]` not found.")
            print(f"{format_log_prefix('blank',3)} {context} requires resolved gene symbols.")
            print(f"{format_log_prefix('blank',3)} Please annotate gene names first, then rerun.")
            return

        X = utils.get_adata_layer(adata, layer=layer)
        expr_df = pd.DataFrame(
            X.T,
            index=genes.values,
            columns=adata.obs_names.astype(str),
        )

        expr_df = expr_df[~pd.isna(expr_df.index)].copy()

        dup_genes = sorted(pd.Index(expr_df.index)[pd.Index(expr_df.index).duplicated(keep=False)].unique())
        if len(dup_genes) > 0:
            _print_duplicate_gene_warning(dup_genes, method_desc="mean abundance")
            expr_df = expr_df.groupby(expr_df.index).mean()

        log_prefix = format_log_prefix("user")
        subpdata = "prot" if on == "protein" else "pep"

        if verbose:
            print(f"{log_prefix} Running ssGSEA [{on}] using layer: {layer}")
            print(f"   🔸 Gene set library: {gene_sets}")
            print(f"   🔸 Gene column: {gene_col}")
            print(f"   🔸 Input matrix after cleanup (genes × samples): {expr_df.shape}")

        ss = gp.ssgsea(
            data=expr_df,
            gene_sets=gene_sets,
            min_size=min_size,
            max_size=max_size,
            threads=threads,
            seed=seed,
            outdir=None,
            verbose=False,
            **kwargs,
        )

        res_df = ss.res2d.copy()

        # GSEApy ssGSEA returns long-form results with:
        # Name = sample, Term = pathway, ES = enrichment score
        score_df = res_df.pivot(index="Term", columns="Name", values="ES").T
        score_df = score_df.reindex(adata.obs_names.astype(str))

        adata.obsm[f"X_{key_added}"] = score_df
        adata.uns[key_added] = {
            "params": {
                "layer": layer,
                "gene_sets": gene_sets,
                "gene_col": gene_col,
                "min_size": min_size,
                "max_size": max_size,
                "threads": threads,
                "seed": seed,
                "on": on,
            },
            "long_results": res_df,
            "pathway_names": list(score_df.columns),
        }

        self._append_history(  # type: ignore[attr-defined]
            f'{on}: ssGSEA run on {layer}, stored in .{subpdata}.obsm["X_{key_added}"] and .{subpdata}.uns["{key_added}"]'
        )

        if verbose:
            print(f"{format_log_prefix('result_only', indent=2)} ssGSEA complete. Results stored in:")
            print(f"       • .{subpdata}.obsm['X_{key_added}'] (samples × pathways)")
            print(f"       • .{subpdata}.uns['{key_added}']")
            print(f"       • Pathways scored: {score_df.shape[1]}")

    def nanmissingvalues(self, on = 'protein', limit = 0.5):
        """
        Set columns (proteins or peptides) with excessive missing values to NaN.

        This method scans all features and replaces their corresponding columns with NaN
        if the fraction of missing values exceeds the given threshold. It helps ensure
        downstream normalization and imputation steps are applied to meaningful features only.

        Args:
            on (str): Whether to use "protein" or "peptide" data. Accepts "prot"/"protein" or "pep"/"peptide" (default: "protein").
            limit (float): Proportion threshold for missing values (default: 0.5). 
                Features with more than `limit × 100%` missing values are set entirely to NaN.

        Returns:
            None

        !!! warning "Deprecation Notice"
            This function may be deprecated in future releases.  
            Use [`annotate_found`](reference/pAnnData/editing_mixins/#src.scpviz.pAnnData.editing_mixins.annotate_found)  
            and [`filter_prot_found`](reference/pAnnData/editing_mixins/#src.scpviz.pAnnData.editing_mixins.filter_prot_found)  
            for more robust and configurable detection-based filtering.

        Example:
            Mask proteins with more than 50% missing values:
                ```python
                pdata.nanmissingvalues(on="protein", limit=0.5)
                ```

            Apply the same filter for peptide-level data:
                ```python
                pdata.nanmissingvalues(on="peptide", limit=0.3)
                ```

        Note:
            - The missing-value fraction is computed per feature across all samples.
            - This operation modifies the `.X` matrix in-place.
            - The updated data are stored back into `.prot` or `.pep`.
        """
        import scipy.sparse
        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            pass

        if on == 'protein':
            adata = self.prot

        elif on == 'peptide':
            adata = self.pep

        if scipy.sparse.issparse(adata.X):
            X = adata.X.toarray()
        else:
            X = adata.X
        missing_proportion = np.isnan(X).mean(axis=0)
        columns_to_nan = missing_proportion > limit
        X[:, columns_to_nan] = np.nan
        adata.X = scipy.sparse.csr_matrix(X) if scipy.sparse.issparse(adata.X) else X

        if on == 'protein':
            self.prot = adata
        elif on == 'peptide':
            self.pep = adata

        self.update_summary(recompute=True, verbose=False) # type: ignore[attr-defined], SummaryMixin

    def normalize(self, classes = None, layer = "X", method = 'sum', on = 'protein', set_X = True, force = False, use_nonmissing = False, **kwargs):  
        """
        Normalize sample intensities across protein or peptide data.

        This method performs global or group-wise normalization of the selected data layer.
        It supports multiple normalization strategies ranging from simple scaling
        (e.g., sum, median) to advanced approaches such as `reference_feature` and
        [`directlfq`]((https://doi.org/10.1016/j.mcpro.2023.100581)).

        Args:
            classes (str or list, optional): Sample-level grouping column(s) in `.obs` to
                perform group-wise normalization. If None, normalization is applied globally.
            layer (str, optional): Data layer to normalize from (default: `"X"`).
            method (str, optional): Normalization strategy to apply. Options include:
                `'sum'`, `'median'`, `'mean'`, `'max'`, `'reference_feature'`,
                `'robust_scale'`, `'quantile_transform'`, `'directlfq'`.
            on (str, optional): Whether to use `"protein"` or `"peptide"` data.
            set_X (bool, optional): Whether to set `.X` to the normalized result (default: True).
            force (bool, optional): Proceed with normalization even if samples exceed the
                allowed fraction of missing values (default: False).
            use_nonmissing (bool, optional): If True, only use columns with no missing values
                across all samples when computing scaling factors (default: False).
            **kwargs: Additional keyword arguments for normalization methods.
                - `reference_columns` (list): For `'reference_feature'`, specify columns or
                gene names to normalize against.
                - `max_missing_fraction` (float): Maximum allowed fraction of missing values
                per sample (default: 0.5).
                - `n_neighbors` (int): For methods requiring neighbor-based computations.
                - `input_type_to_use` (str): For `'directlfq'`, specify `'pAnnData'`,
                `'diann_precursor_ms1'`, or `'diann_precursor_ms1_and_ms2'`.
                - `path` (str): For `'directlfq'`, path to the `report.tsv` or `report.parquet`
                file from DIA-NN output.
                - `strict` (bool): For `'directlfq'`, whether to use unique + shared peptides or only unique peptides. Defaults to False (unique + shared).

        Returns:
            None

        Example:
            Perform global normalization using the median intensity:
                ```python
                pdata.normalize(on="protein", method="median")
                ```

            Apply group-wise normalization by treatment class using sum-scaling:
                ```python
                pdata.normalize(classes="treatment", method="sum", on="protein")
                ```

            Run reference-feature normalization using specific genes:
                ```python
                pdata.normalize(
                    on="protein",
                    method="reference_feature",
                    reference_columns=["ACTB", "GAPDH"]
                )
                ```

        !!! tip "About `directlfq` normalization"
            - The `directlfq` method aggregates peptide-level data to protein-level intensities
            and stores results in a new protein-layer (e.g. `'X_norm_directlfq'`).
            - It does not support group-wise normalization.
            - Processing time may scale with dataset size.
            - For algorithmic and benchmarking details, see:  
            **Ammar, Constantin et al. (2023)**  
            *Accurate Label-Free Quantification by directLFQ to Compare Unlimited Numbers of Proteomes.*  
            *Molecular & Cellular Proteomics*, 22(7):100581.  
            [https://doi.org/10.1016/j.mcpro.2023.100581](https://doi.org/10.1016/j.mcpro.2023.100581)



        Note:
            - Results are stored in a new layer named `'X_norm_<method>'`.
            - The normalized layer replaces `.X` if `set_X=True`.
            - Normalization operations are recorded in `.history`.
            - For consistency across runs, consider running `.impute()` before normalization.

        Todo:
            - Add optional z-score and percentile normalization modes.
            - Add support for specifying external scaling factors.
        """


        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            return

        adata = self.prot if on == 'protein' else self.pep
        if layer != "X" and layer not in adata.layers:
            raise ValueError(f"Layer {layer} not found in .{on}.")

        normalize_data = adata.layers[layer] if layer != "X" else adata.X
        was_sparse = sparse.issparse(normalize_data)
        normalize_data = normalize_data.toarray() if was_sparse else normalize_data.copy()
        original_data = normalize_data.copy()

        layer_name = 'X_norm_' + method
        normalize_funcs = ['sum', 'median', 'mean', 'max', 'reference_feature', 'robust_scale', 'quantile_transform','directlfq']

        if method not in normalize_funcs:
            raise ValueError(f"Unsupported normalization method: {method}")

        # Special handling for directlfq
        if method == "directlfq":
            if classes is not None:
                print(f"{format_log_prefix('warn')} 'directlfq' does not support group-wise normalization. Proceeding with global normalization.")
                classes = None

            print(f"{format_log_prefix('user')} Running directlfq normalization on peptide-level data.")
            print(f"{format_log_prefix('info_only', indent=2)} Note: please be patient, directlfq can take a minute to run depending on data size. Output files will be produced.")
            normalize_data = self._normalize_helper_directlfq(**kwargs)

            adata = self.prot  # directlfq always outputs protein-level intensities
            _resolved_input = utils.resolve_input_layer(adata, layer)
            actual_layer_name = utils.update_layer_provenance(
                adata,
                layer_name=layer_name,
                op="normalize",
                input_layer=_resolved_input,
                method="directlfq",
            )
            adata.layers[actual_layer_name] = (
                sparse.csr_matrix(normalize_data) if was_sparse else normalize_data
            )

            if set_X:
                self.set_X(layer=actual_layer_name, on="protein")  # type: ignore[attr-defined]

            self._append_history(  # type: ignore[attr-defined]
                f"protein: Normalized layer using directlfq (input_type={kwargs.get('input_type_to_use', 'default')}). Stored in `{actual_layer_name}`."
            )
            print(
                f"{format_log_prefix('result_only', indent=2)} directlfq normalization complete. "
                f"Results are stored in layer '{actual_layer_name}'."
            )
            print(f"{format_log_prefix('warn_only',3)} Downstream imputation should be performed with the flag `use_zeros_as_nan` set to True due to directlfq output format returning NaNs as 0s.")
            return

        # --- standard normalization ---
        # Build the header message early
        if classes is None:
            msg = f"{format_log_prefix('user')} Global normalization using '{method}'"
        else:
            msg = f"{format_log_prefix('info_only')} Group-wise normalization using '{method}' on class(es): {classes}"

        if use_nonmissing and method in {'sum', 'mean', 'median', 'max'}:
            msg += " (using only fully observed columns)"
        msg += f". Layer will be saved as '{layer_name}'."

        # ✅ Print message before checking for missing values
        print(msg)

        # Check for bad rows (too many missing values)
        missing_fraction = np.isnan(normalize_data).sum(axis=1) / normalize_data.shape[1]
        max_missing_fraction = kwargs.pop("max_missing_fraction", 0.5)
        bad_rows_mask = missing_fraction > max_missing_fraction

        if np.any(bad_rows_mask):
            n_bad = np.sum(bad_rows_mask)
            print(f"{format_log_prefix('warn',2)} {n_bad} sample(s) have >{int(max_missing_fraction*100)}% missing values.")
            print("     Try running `.impute()` before normalization. Suggest to use the flag `use_nonmissing=True` to normalize using only consistently observed proteins.")
            if not force:
                print("     ➡️ Use `force=True` to proceed anyway.")
                return
            print(f"{format_log_prefix('warn',2)} Proceeding with normalization despite bad rows (force=True).")

        if classes is None:
            normalize_data = self._normalize_helper(normalize_data, method, use_nonmissing=use_nonmissing, **kwargs)
        else:
            # Group-wise normalization
            sample_names = utils.get_samplenames(adata, classes)
            sample_names = np.array(sample_names)
            unique_groups = np.unique(sample_names)

            for group in unique_groups:
                idx = np.where(sample_names == group)[0]
                group_data = normalize_data[idx, :]

                normalized_group = self._normalize_helper(group_data, method=method, use_nonmissing=use_nonmissing, **kwargs)
                normalize_data[idx, :] = normalized_group

        # summary printout
        summary_lines = []
        if classes is None:
            summary_lines.append(f"{format_log_prefix('result_only', indent=2)} Normalized all {normalize_data.shape[0]} samples.")
        else:
            for group in unique_groups:
                count = np.sum(sample_names == group)
                summary_lines.append(f"   - {group}: {count} samples normalized")
            summary_lines.insert(0, f"{format_log_prefix('result_only', indent=2)} Normalized {normalize_data.shape[0]} samples total.")
        print("\n".join(summary_lines))

        _resolved_input = utils.resolve_input_layer(adata, layer)
        actual_layer_name = utils.update_layer_provenance(
            adata,
            layer_name=layer_name,
            op="normalize",
            input_layer=_resolved_input,
            method=method,
        )
        adata.layers[actual_layer_name] = (
            sparse.csr_matrix(normalize_data) if was_sparse else normalize_data
        )

        if set_X:
            self.set_X(layer=actual_layer_name, on=on)  # type: ignore[attr-defined], EditingMixin

        # Determine if use_nonmissing note should be added
        note = ""
        if use_nonmissing and method in {'sum', 'mean', 'median', 'max'}:
            note = " (using only fully observed columns)"

        self._append_history(  # type: ignore[attr-defined], HistoryMixin
            f"{on}: Normalized layer {layer} using {method}{note} (grouped by {classes}). "
            f"Stored in `{actual_layer_name}`."
        )

    def _normalize_helper(self, data, method, use_nonmissing, **kwargs):
        """
        Perform row-wise normalization using a selected method.

        Used internally by `normalize()` to compute per-sample scaling.
        Supports reference feature scaling, robust methods, and quantile normalization.

        Args:
            data (np.ndarray): Sample × feature data matrix.
            method (str): Normalization strategy. Options:
                - 'sum'
                - 'mean'
                - 'median'
                - 'max'
                - 'reference_feature'
                - 'robust_scale'
                - 'quantile_transform'
            use_nonmissing (bool): If True, computes scaling using only columns with no NaNs.

        Returns:
            np.ndarray: Normalized data matrix.
        """

        if method in {'sum', 'mean', 'median', 'max'}:
            reducer = {
                    'sum': np.nansum,
                    'mean': np.nanmean,
                    'median': np.nanmedian,
                    'max': np.nanmax
                }[method]

            if use_nonmissing:
                fully_observed_cols = ~np.isnan(data).any(axis=0)
                if not np.any(fully_observed_cols):
                    raise ValueError("No fully observed columns available for normalization with `use_nonmissing=True`.")
                used_cols = np.where(fully_observed_cols)[0]
                print(f"{format_log_prefix('info_only',2)} Normalizing using only fully observed columns: {len(used_cols)}")
                row_vals = reducer(data[:, fully_observed_cols], axis=1)
            else:
                row_vals = reducer(data, axis=1)

            with np.errstate(divide='ignore', invalid='ignore'):
                scale = np.nanmax(row_vals) / row_vals
            scale = np.where(np.isnan(scale), 1.0, scale) # metaboanalyst: scale = 1.0 / row_vals
            data_norm = data * scale[:, None]

        elif method == 'reference_feature':
            # norm by reference feature: scale each row s.t. the reference column is the same across all rows (scale to max value of reference column)
            reference_columns = kwargs.get('reference_columns', [2])
            reference_method = kwargs.get('reference_method', 'median')  # default to median

            reducer_map = {
                'mean': np.nanmean,
                'median': np.nanmedian,
                'sum': np.nansum
            }

            if reference_method not in reducer_map:
                raise ValueError(f"Unsupported reference method: {reference_method}. Supported methods are: {list(reducer_map.keys())}")
            reducer = reducer_map[reference_method]

            # resolve reference column names if needed
            if isinstance(reference_columns[0], str):
                gene_to_acc, _ = self.get_gene_maps(on='protein') # type: ignore[attr-defined], IdentifierMixin
                resolved = utils.resolve_accessions(self.prot, reference_columns, gene_map=gene_to_acc)
                reference_acc = [ref for ref in resolved if ref in self.prot.var.index]
                reference_columns = [self.prot.var.index.get_loc(ref) for ref in reference_acc]
                print(f"{format_log_prefix('info')} Normalizing using found reference columns: {reference_acc}")
                self._history.append(f"Used reference_feature normalization with resolved accessions: {resolved}") # type: ignore[attr-defined]
            else:
                reference_columns = [int(ref) for ref in reference_columns]
                reference_acc = [self.prot.var.index[ref] for ref in reference_columns if ref < self.prot.shape[1]]
                print(f"{format_log_prefix('info')} Normalizing using reference columns: {reference_acc}")
                self._history.append(f"Used reference_feature normalization with resolved accessions: {reference_acc}") # type: ignore[attr-defined]

            scaling_factors = np.nanmean(np.nanmax(data[:, reference_columns], axis=0) / (data[:, reference_columns]), axis=1)

            nan_rows = np.where(np.isnan(scaling_factors))[0]
            if nan_rows.size > 0:
                print(f"{format_log_prefix('warn')} Rows {list(nan_rows)} have all missing reference values.")
                print(f"{format_log_prefix('info')} Falling back to row median normalization for these rows.")

                fallback = np.nanmedian(data[nan_rows, :], axis=1)
                fallback[fallback == 0] = np.nan  # avoid division by 0
                fallback_scale = np.nanmax(fallback) / fallback
                fallback_scale = np.where(np.isnan(fallback_scale), 1.0, fallback_scale)  # default to 1.0 if all else fails

                scaling_factors[nan_rows] = fallback_scale

            scaling_factors = np.where(np.isnan(scaling_factors), np.nanmean(scaling_factors), scaling_factors)
            data_norm = data * scaling_factors[:, None]

        elif method == 'robust_scale':
            # norm by robust_scale: Center to the median and component wise scale according to the interquartile range. See sklearn.preprocessing.robust_scale for more information.
            from sklearn.preprocessing import robust_scale
            data_norm = robust_scale(data, axis=1)

        elif method == 'quantile_transform':
            # norm by quantile_transform: Transform features using quantiles information. See sklearn.preprocessing.quantile_transform for more information.
            from sklearn.preprocessing import quantile_transform
            import warnings
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", UserWarning)
                data_norm = quantile_transform(data, axis=1)

        else:
            raise ValueError(f"Unknown method: {method}")

        return data_norm

    def _normalize_helper_directlfq(self, input_type_to_use="pAnnData", path=None, strict=False, **kwargs):
        """
        Run directlfq normalization and return normalized protein-level intensities.

        Args:
            input_type_to_use (str): Either 'pAnnData' (default) or 
                'diann_precursor_ms1_and_ms2'.
            path (str, optional): Path to DIA-NN report file (required if 
                input_type_to_use='diann_precursor_ms1_and_ms2').
            strict (bool): Whether to be strict and use only unique peptides, in which shared peptides are ignored for normalization. Defaults to False.
            **kwargs: Passed to directlfq.lfq_manager.run_lfq().

        Returns:
            np.ndarray: Normalized data (samples × proteins).
        """
        import directlfq.lfq_manager as lfq_manager
        import os

        strict = kwargs.pop("strict", False)

        if input_type_to_use == "diann_precursor_ms1_and_ms2":
            if path is None:
                raise ValueError("For input_type_to_use='diann_precursor_ms1_and_ms2', please provide the DIA-NN report path via `path`.")
            lfq_manager.run_lfq(path, input_type_to_use=input_type_to_use, **kwargs)

        else:
            # check if pep exists
            if self.pep is None:
                raise ValueError("Peptide-level data not found. Please load peptide data before running directlfq normalization.")

            # Build peptide-level input table from .pep
            X = self.pep.layers.get("X_precursor", self.pep.X)
            if not isinstance(X, pd.DataFrame):
                X = X.toarray() if hasattr(X, "toarray") else X
            X_df = pd.DataFrame(
                X.T,
                index=self.pep.var_names,
                columns=self.pep.obs_names
            )
            prot_col = "Protein.Group" if "Protein.Group" in self.pep.var.columns else "Master Protein Accessions"
            X_df.insert(0, "protein", self.pep.var[prot_col].to_list())
            X_df.insert(1, "ion", X_df.index.to_list())

            if not strict:
                # e.g. "P03995; P03995-2" → two rows with same intensities, one per protein
                # ensure directLFQ sees only single-accession protein IDs
                n_before = X_df.shape[0]
                X_df["protein"] = X_df["protein"].astype(str).str.split(";")
                X_df = X_df.explode("protein")
                X_df["protein"] = X_df["protein"].str.strip()
                X_df = X_df[X_df["protein"] != ""]

                n_after = X_df.shape[0]
                if n_after > n_before:
                    print(f"{format_log_prefix('info',2)} Expanded multi-protein peptide groups: {n_before} → {n_after} rows.")
                else:
                    print(f"{format_log_prefix('info',2)} No multi-protein peptide groups detected for directlfq input.")

            X_df.reset_index(drop=True, inplace=True)
            tmp_file = "peptide_matrix.aq_reformat.tsv"
            X_df.to_csv(tmp_file, sep="\t", index=False)
            lfq_manager.run_lfq(tmp_file, **kwargs)

        # Load directlfq output (look for protein_intensities file)
        out_file = None
        for f in os.listdir("."):
            if f.endswith("protein_intensities.tsv"):
                out_file = f
        if out_file is None:
            raise FileNotFoundError("directlfq did not produce a '*protein_intensities.tsv' file in current directory.")

        norm_prot = pd.read_csv(out_file, sep="\t").set_index("protein")
        aligned = norm_prot.reindex(
            index=self.prot.var_names,
            columns=self.prot.obs_names
        )

        return aligned.T.to_numpy()

    def pairwise_correlation(
        self,
        classes: str | list[str],
        on: str = "protein",
        layer: str = "X",
        method: str = "pearson",
        order: list | None = None,
        compute_sample_matrix: bool = False,
        force: bool = False,
        subset_mask: np.ndarray | list | None = None,
    ) -> None:
        """
        Compute pairwise proteome correlations across groups defined by `.obs` metadata.

        For each group label (one column, or combined labels from multiple columns),
        computes the mean expression profile (nanmean), drops features with NaN in any
        group, then computes an (n_groups × n_groups) correlation or distance matrix.
        Optionally also computes a sample-level matrix.
        Results are stored in `adata.uns["pairwise_corr"]`.

        Args:
            classes (str or list of str): One `.obs` column name, or a list of column
                names, defining sample groups (same convention as `normalize()` and
                `plot_pca()`). Multiple columns are combined per sample using
                :func:`~scpviz.utils.get_samplenames` (comma-space join, same as
                group-wise ``normalize``).
            on (str): Whether to use `"protein"` or `"peptide"` data (default: `"protein"`).
            layer (str): Data layer to use. `"X"` uses `.X`; any other value uses
                `.layers[layer]`. Default: `"X"`.
            method (str): Correlation/distance metric. One of:
                `"pearson"`, `"spearman"`, `"euclidean"`. Default: `"pearson"`.
            order (list or None): Preferred ordering of group labels. Unknown values
                are dropped (with a warning); groups not listed are appended after,
                sorted alphabetically (with a warning). If None, order is sorted
                alphabetically.
            compute_sample_matrix (bool): If True, also compute an (n_samples × n_samples)
                matrix sorted to match the resolved group order. Default: False.
            force (bool): If True, recompute even if results are cached in
                `adata.uns["pairwise_corr"]`. Default: False.
            subset_mask (array-like or None): Boolean mask of length `n_obs` selecting
                samples to include. If None, all samples are used.

        Returns:
            None

        Raises:
            ValueError: If `classes` is invalid or missing from `.obs`, `method` is
                invalid, or `subset_mask` has the wrong shape or is all-False.
            KeyError: If `layer` is not `"X"` and not in `adata.layers`.

        Note:
            Features where **any** group mean is NaN are dropped (complete cases only).
            A cache hit still appends a history entry noting that cached results were used.
            For multi-column ``classes``, combined labels use a comma-space separator;
            see ``uns['pairwise_corr']['separator']`` and ``classes_list`` for plotting.

        Example:
            Combined cell line and treatment (labels like ``"AS, kd"``):
                ```python
                pdata.pairwise_correlation(
                    classes=["cellline", "treatment"],
                    method="pearson",
                )
                ```
        """
        if not self._check_data(on):  # type: ignore[attr-defined], ValidationMixin
            pass

        adata = utils.get_adata(self, on)
        on_norm = "protein" if on in ("protein", "prot") else "peptide"
        subpdata = "prot" if on_norm == "protein" else "pep"

        _classes_list: list[str] = [classes] if isinstance(classes, str) else list(classes)
        if not _classes_list:
            raise ValueError(
                f"{format_log_prefix('error')} classes must be a non-empty string or "
                "list of strings."
            )
        _missing_cols = [c for c in _classes_list if c not in adata.obs.columns]
        if _missing_cols:
            raise ValueError(
                f"{format_log_prefix('error')} classes column(s) not found in "
                f"adata.obs: {_missing_cols}"
            )
        _separator: str | None = ", " if len(_classes_list) > 1 else None

        if method not in ("pearson", "spearman", "euclidean"):
            raise ValueError(
                f"{format_log_prefix('error')} method={method!r} is not supported. "
                "Choose from: 'pearson', 'spearman', 'euclidean'."
            )

        subset_indices: tuple[int, ...] | None
        if subset_mask is None:
            subset_indices = None
        else:
            sm = np.asarray(subset_mask, dtype=bool)
            if sm.ndim != 1 or sm.size != adata.n_obs:
                raise ValueError(
                    f"{format_log_prefix('error')} subset_mask must be a 1D boolean "
                    f"array of length n_obs={adata.n_obs}."
                )
            if not np.any(sm):
                raise ValueError(
                    f"{format_log_prefix('error')} subset_mask selects zero samples."
                )
            subset_indices = tuple(np.flatnonzero(sm).tolist())

        if layer != "X" and layer not in adata.layers:
            raise KeyError(
                f"{format_log_prefix('error')} Layer {layer!r} not found in adata.layers."
            )

        X_full = utils.get_adata_layer(adata, layer)
        X_full = np.asarray(X_full)

        _layer_is_log_pw = utils.infer_layer_is_log(layer, adata)
        _finite_pw = X_full[np.isfinite(X_full)]
        if not _layer_is_log_pw and _finite_pw.size > 0 and np.nanmedian(_finite_pw) > 1e4:
            print(
                f"{format_log_prefix('info')} Layer {layer!r} appears to contain "
                f"non-log intensities (median={np.nanmedian(_finite_pw):.2e}). "
                "Pairwise correlations on non-log data are dominated by highly abundant "
                "proteins. Consider normalize() then log_transform(), then rerun with "
                "the resulting log layer."
            )
        elif _layer_is_log_pw:
            print(
                f"{format_log_prefix('info')} Layer {layer!r} detected as log-transformed. "
                "Using log-space values for correlation."
            )

        raw_labels = utils.get_samplenames(adata, classes)
        obs_labels = pd.Series(
            raw_labels, index=adata.obs_names, name="_combined_class"
        )

        if subset_indices is not None:
            row_sel = np.array(subset_indices, dtype=int)
            X = X_full[row_sel]
            obs_names_used = adata.obs_names[row_sel]
            obs_labels = obs_labels.iloc[row_sel]
        else:
            X = X_full
            obs_names_used = adata.obs_names

        unique_groups = pd.unique(obs_labels).tolist()
        if len(unique_groups) == 0:
            raise ValueError(
                f"{format_log_prefix('error')} No groups found for classes={_classes_list!r} "
                "after applying subset_mask."
            )

        ug_set = set(unique_groups)
        if order is None:
            final_order = sorted(unique_groups)
        else:
            invalid_in_order = [v for v in order if v not in ug_set]
            if invalid_in_order:
                print(
                    f"{format_log_prefix('warn')} order contains values not present in "
                    f"combined labels from {_classes_list!r}; removing: {invalid_in_order}"
                )
            seen: set = set()
            valid_user: list = []
            for v in order:
                if v not in ug_set or v in seen:
                    continue
                seen.add(v)
                valid_user.append(v)
            omitted = sorted(ug_set - set(valid_user))
            if omitted:
                print(
                    f"{format_log_prefix('warn')} groups not listed in order will be "
                    f"appended after your order (alphabetically): {omitted}"
                )
            final_order = valid_user + omitted

        prev = adata.uns.get("pairwise_corr")
        cache_hit = False
        if (
            not force
            and isinstance(prev, dict)
            and prev.get("classes") == classes
            and prev.get("method") == method
            and prev.get("layer") == layer
            and prev.get("compute_sample_matrix") == compute_sample_matrix
            and prev.get("subset_indices") == subset_indices
            and prev.get("order") == final_order
        ):
            cache_hit = True

        if cache_hit:
            print(
                f"{format_log_prefix('info')} Pairwise correlation already computed "
                f"(classes={classes!r}, method={method}). Use force=True to recompute."
            )
            self._append_history(  # type: ignore[attr-defined], HistoryMixin
                f'{on_norm}: pairwise_correlation — used last cached result '
                f'(classes={classes!r}, method={method}, layer={layer}).'
            )
            return

        if not force and isinstance(prev, dict):
            print(
                f"{format_log_prefix('warn')} Recomputing pairwise correlation: "
                "parameters differ from cached result."
            )

        n_groups = len(final_order)
        group_means = np.zeros((n_groups, X.shape[1]), dtype=float)
        for i, g in enumerate(final_order):
            mask = (obs_labels == g).to_numpy()
            rows = X[mask, :]
            if rows.shape[0] == 0:
                group_means[i, :] = np.nan
            else:
                group_means[i, :] = np.nanmean(rows, axis=0)

        nan_mask = np.isnan(group_means).any(axis=0)
        group_means_clean = group_means[:, ~nan_mask]
        n_features_used = int(group_means_clean.shape[1])
        n_features_dropped = int(nan_mask.sum())

        if n_groups < 2:
            if method == "euclidean":
                group_corr_arr = np.zeros((1, 1), dtype=float)
            else:
                group_corr_arr = np.ones((1, 1), dtype=float)
        elif method == "pearson":
            group_corr_arr = np.corrcoef(group_means_clean)
        elif method == "spearman":
            sp = spearmanr(group_means_clean.T).statistic
            sp = np.asarray(sp)
            if sp.ndim == 0:
                group_corr_arr = np.array([[1.0, float(sp)], [float(sp), 1.0]])
            else:
                group_corr_arr = sp
        else:
            group_corr_arr = cdist(
                group_means_clean, group_means_clean, metric="euclidean"
            )

        group_corr_df = pd.DataFrame(
            group_corr_arr, index=final_order, columns=final_order
        )

        sample_corr_df = None
        if compute_sample_matrix:
            sorted_obs_names: list = []
            for group in final_order:
                sorted_obs_names.extend(
                    obs_labels[obs_labels == group].index.tolist()
                )
            if subset_indices is not None:
                _allowed = set(obs_names_used)
                assert all(n in _allowed for n in sorted_obs_names), (
                    "pairwise_correlation: sample-matrix obs names must stay within "
                    "subset_mask; obs_labels should remain sliced after subset_indices."
                )
            row_ix = adata.obs_names.get_indexer(sorted_obs_names)
            X_sorted = X_full[row_ix]
            X_sorted_clean = X_sorted[:, ~nan_mask]
            if method == "pearson":
                sample_corr_df = pd.DataFrame(X_sorted_clean).T.corr(method="pearson")
                sample_corr_df.index = sorted_obs_names
                sample_corr_df.columns = sorted_obs_names
            elif method == "spearman":
                sample_corr_df = pd.DataFrame(X_sorted_clean).T.corr(method="spearman")
                sample_corr_df.index = sorted_obs_names
                sample_corr_df.columns = sorted_obs_names
            else:
                # cdist treats NaNs as NaN output; raw abundance rows usually have missing
                # values, which yields an all-NaN matrix and a blank heatmap. Use nan-aware
                # Euclidean distance between sample vectors (sklearn).
                dist = nan_euclidean_distances(X_sorted_clean)
                sample_corr_df = pd.DataFrame(
                    dist, index=sorted_obs_names, columns=sorted_obs_names
                )

        adata.uns["pairwise_corr"] = {
            "group_matrix": group_corr_df,
            "sample_matrix": sample_corr_df,
            "classes": classes,
            "classes_list": _classes_list,
            "separator": _separator,
            "order": final_order,
            "method": method,
            "layer": layer,
            "compute_sample_matrix": compute_sample_matrix,
            "n_features_used": n_features_used,
            "n_features_dropped": n_features_dropped,
            "subset_indices": subset_indices,
        }

        _classes_display = classes if isinstance(classes, str) else list(classes)
        self._append_history(  # type: ignore[attr-defined], HistoryMixin
            f"{on_norm}: pairwise_correlation on classes={_classes_display!r}, "
            f"method={method}, layer={layer}"
            + (
                f", subset_indices={subset_indices}"
                if subset_indices is not None
                else ""
            )
        )

        print(
            f"{format_log_prefix('user')} Computing pairwise correlation [{on_norm}] "
            f"using layer: {layer}"
        )
        _fp_fc = format_log_prefix("filter_conditions")
        if isinstance(classes, str):
            print(f"{_fp_fc}classes: {classes}")
        else:
            print(f"{_fp_fc}classes: {list(classes)}")
        for _col in _classes_list:
            _u = pd.unique(adata.obs[_col])
            _head = [str(_v) for _v in _u[:5]]
            _more = len(_u) - 5
            _suffix = f" (+{_more} more)" if _more > 0 else ""
            print(f"{_fp_fc}{_col}: {', '.join(_head)}{_suffix}")
        print(f"{_fp_fc}method: {method}")
        order_preview = " | ".join(str(x) for x in final_order)
        print(
            f"{_fp_fc}order (N={len(final_order)}): "
            f"{order_preview}"
        )
        print(
            f"{_fp_fc}Features: {n_features_used} used / "
            f"{adata.n_vars} total ({n_features_dropped} dropped — NaN in ≥1 group mean)"
        )
        _ng = len(final_order)
        print(
            f"{format_log_prefix('result_only', indent=2)} Pairwise correlation complete. "
            "Results stored in:"
        )
        print(f"       • .{subpdata}.uns['pairwise_corr']")
        if compute_sample_matrix and sample_corr_df is not None:
            _ns = int(sample_corr_df.shape[0])
            print(
                f"       • Group matrix: ({_ng} × {_ng}) | "
                f"Sample matrix: ({_ns} × {_ns})"
            )
        else:
            print(f"       • Group matrix: ({_ng} × {_ng})")

    def clean_X(self, on='prot', inplace=True, set_to=0, layer=None, to_sparse=False, backup_layer="X_preclean", verbose=True):
        """
        Replace NaNs in `.X` or a specified layer with a given value (default: 0).

        Optionally backs up the original data to a layer (default: `'X_preclean'`) before overwriting.
        Typically used to prepare data for scanpy or sklearn functions that cannot handle missing values.

        Args:
            on (str): Target data to clean, either `'protein'` or `'peptide'`.
            inplace (bool): If True, update `.X` or `.layers[layer]` in place. If False, return cleaned matrix.
            set_to (float): Value to replace NaNs with (default: 0.0).
            layer (str or None): If specified, applies to `.layers[layer]`; otherwise uses `.X`.
            to_sparse (bool): If True, returns a sparse matrix.
            backup_layer (str or None): If `inplace=True` and `layer=None`, saves the original `.X` to this layer.
            verbose (bool): Whether to print summary messages.

        Returns:
            np.ndarray: Cleaned matrix if `inplace=False`, otherwise `None`.
        """
        if not self._check_data(on):
            return
        if on == 'prot' or on == 'protein':
            adata = self.prot
        elif on == 'pep' or on == 'peptide': 
            adata = self.pep

        print(f'{format_log_prefix("user")} Cleaning {on} data: making scanpy compatible, replacing NaNs with {set_to} in {"layer " + layer if layer else ".X"}.')

        # Choose source matrix
        X = adata.layers[layer] if layer else adata.X
        is_sparse = sparse.issparse(X)

        # Copy for manipulation
        X_clean = X.copy()
        nan_count = 0

        if is_sparse:
            nan_mask = np.isnan(X_clean.data)
            nan_count = np.sum(nan_mask)
            if nan_count > 0:
                X_clean.data[nan_mask] = set_to
        else:
            nan_mask = np.isnan(X_clean)
            nan_count = np.sum(nan_mask)
            X_clean[nan_mask] = set_to

        if to_sparse and not is_sparse:
            X_clean = sparse.csr_matrix(X_clean)

        # Apply result
        if inplace:
            if layer:
                self.prot.layers[layer] = X_clean
            else:
                # Save original .X if requested and not already backed up
                if backup_layer and backup_layer not in self.prot.layers:
                    self.prot.layers[backup_layer] = self.prot.X.copy()
                    if verbose:
                        print(f"{format_log_prefix('info')} Backed up .X to .layers['{backup_layer}']")
                self.prot.X = X_clean
            if verbose:
                print(f"{format_log_prefix('result')} Cleaned {'layer ' + layer if layer else '.X'}: replaced {nan_count} NaNs with {set_to}.")
            if not layer:
                self.update_summary(recompute=True, verbose=False) # type: ignore[attr-defined], SummaryMixin
        else:
            if verbose:
                print(f"{format_log_prefix('result')} Returning cleaned matrix: {nan_count} NaNs replaced with {set_to}.")
            return X_clean 

_normalize_helper

_normalize_helper(data, method, use_nonmissing, **kwargs)

Perform row-wise normalization using a selected method.

Used internally by normalize() to compute per-sample scaling. Supports reference feature scaling, robust methods, and quantile normalization.

Parameters:

Name Type Description Default
data ndarray

Sample × feature data matrix.

required
method str

Normalization strategy. Options: - 'sum' - 'mean' - 'median' - 'max' - 'reference_feature' - 'robust_scale' - 'quantile_transform'

required
use_nonmissing bool

If True, computes scaling using only columns with no NaNs.

required

Returns:

Type Description

np.ndarray: Normalized data matrix.

Source code in src/scpviz/pAnnData/analysis.py
def _normalize_helper(self, data, method, use_nonmissing, **kwargs):
    """
    Perform row-wise normalization using a selected method.

    Used internally by `normalize()` to compute per-sample scaling.
    Supports reference feature scaling, robust methods, and quantile normalization.

    Args:
        data (np.ndarray): Sample × feature data matrix.
        method (str): Normalization strategy. Options:
            - 'sum'
            - 'mean'
            - 'median'
            - 'max'
            - 'reference_feature'
            - 'robust_scale'
            - 'quantile_transform'
        use_nonmissing (bool): If True, computes scaling using only columns with no NaNs.

    Returns:
        np.ndarray: Normalized data matrix.
    """

    if method in {'sum', 'mean', 'median', 'max'}:
        reducer = {
                'sum': np.nansum,
                'mean': np.nanmean,
                'median': np.nanmedian,
                'max': np.nanmax
            }[method]

        if use_nonmissing:
            fully_observed_cols = ~np.isnan(data).any(axis=0)
            if not np.any(fully_observed_cols):
                raise ValueError("No fully observed columns available for normalization with `use_nonmissing=True`.")
            used_cols = np.where(fully_observed_cols)[0]
            print(f"{format_log_prefix('info_only',2)} Normalizing using only fully observed columns: {len(used_cols)}")
            row_vals = reducer(data[:, fully_observed_cols], axis=1)
        else:
            row_vals = reducer(data, axis=1)

        with np.errstate(divide='ignore', invalid='ignore'):
            scale = np.nanmax(row_vals) / row_vals
        scale = np.where(np.isnan(scale), 1.0, scale) # metaboanalyst: scale = 1.0 / row_vals
        data_norm = data * scale[:, None]

    elif method == 'reference_feature':
        # norm by reference feature: scale each row s.t. the reference column is the same across all rows (scale to max value of reference column)
        reference_columns = kwargs.get('reference_columns', [2])
        reference_method = kwargs.get('reference_method', 'median')  # default to median

        reducer_map = {
            'mean': np.nanmean,
            'median': np.nanmedian,
            'sum': np.nansum
        }

        if reference_method not in reducer_map:
            raise ValueError(f"Unsupported reference method: {reference_method}. Supported methods are: {list(reducer_map.keys())}")
        reducer = reducer_map[reference_method]

        # resolve reference column names if needed
        if isinstance(reference_columns[0], str):
            gene_to_acc, _ = self.get_gene_maps(on='protein') # type: ignore[attr-defined], IdentifierMixin
            resolved = utils.resolve_accessions(self.prot, reference_columns, gene_map=gene_to_acc)
            reference_acc = [ref for ref in resolved if ref in self.prot.var.index]
            reference_columns = [self.prot.var.index.get_loc(ref) for ref in reference_acc]
            print(f"{format_log_prefix('info')} Normalizing using found reference columns: {reference_acc}")
            self._history.append(f"Used reference_feature normalization with resolved accessions: {resolved}") # type: ignore[attr-defined]
        else:
            reference_columns = [int(ref) for ref in reference_columns]
            reference_acc = [self.prot.var.index[ref] for ref in reference_columns if ref < self.prot.shape[1]]
            print(f"{format_log_prefix('info')} Normalizing using reference columns: {reference_acc}")
            self._history.append(f"Used reference_feature normalization with resolved accessions: {reference_acc}") # type: ignore[attr-defined]

        scaling_factors = np.nanmean(np.nanmax(data[:, reference_columns], axis=0) / (data[:, reference_columns]), axis=1)

        nan_rows = np.where(np.isnan(scaling_factors))[0]
        if nan_rows.size > 0:
            print(f"{format_log_prefix('warn')} Rows {list(nan_rows)} have all missing reference values.")
            print(f"{format_log_prefix('info')} Falling back to row median normalization for these rows.")

            fallback = np.nanmedian(data[nan_rows, :], axis=1)
            fallback[fallback == 0] = np.nan  # avoid division by 0
            fallback_scale = np.nanmax(fallback) / fallback
            fallback_scale = np.where(np.isnan(fallback_scale), 1.0, fallback_scale)  # default to 1.0 if all else fails

            scaling_factors[nan_rows] = fallback_scale

        scaling_factors = np.where(np.isnan(scaling_factors), np.nanmean(scaling_factors), scaling_factors)
        data_norm = data * scaling_factors[:, None]

    elif method == 'robust_scale':
        # norm by robust_scale: Center to the median and component wise scale according to the interquartile range. See sklearn.preprocessing.robust_scale for more information.
        from sklearn.preprocessing import robust_scale
        data_norm = robust_scale(data, axis=1)

    elif method == 'quantile_transform':
        # norm by quantile_transform: Transform features using quantiles information. See sklearn.preprocessing.quantile_transform for more information.
        from sklearn.preprocessing import quantile_transform
        import warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", UserWarning)
            data_norm = quantile_transform(data, axis=1)

    else:
        raise ValueError(f"Unknown method: {method}")

    return data_norm

_normalize_helper_directlfq

_normalize_helper_directlfq(
    input_type_to_use="pAnnData",
    path=None,
    strict=False,
    **kwargs
)

Run directlfq normalization and return normalized protein-level intensities.

Parameters:

Name Type Description Default
input_type_to_use str

Either 'pAnnData' (default) or 'diann_precursor_ms1_and_ms2'.

'pAnnData'
path str

Path to DIA-NN report file (required if input_type_to_use='diann_precursor_ms1_and_ms2').

None
strict bool

Whether to be strict and use only unique peptides, in which shared peptides are ignored for normalization. Defaults to False.

False
**kwargs

Passed to directlfq.lfq_manager.run_lfq().

{}

Returns:

Type Description

np.ndarray: Normalized data (samples × proteins).

Source code in src/scpviz/pAnnData/analysis.py
def _normalize_helper_directlfq(self, input_type_to_use="pAnnData", path=None, strict=False, **kwargs):
    """
    Run directlfq normalization and return normalized protein-level intensities.

    Args:
        input_type_to_use (str): Either 'pAnnData' (default) or 
            'diann_precursor_ms1_and_ms2'.
        path (str, optional): Path to DIA-NN report file (required if 
            input_type_to_use='diann_precursor_ms1_and_ms2').
        strict (bool): Whether to be strict and use only unique peptides, in which shared peptides are ignored for normalization. Defaults to False.
        **kwargs: Passed to directlfq.lfq_manager.run_lfq().

    Returns:
        np.ndarray: Normalized data (samples × proteins).
    """
    import directlfq.lfq_manager as lfq_manager
    import os

    strict = kwargs.pop("strict", False)

    if input_type_to_use == "diann_precursor_ms1_and_ms2":
        if path is None:
            raise ValueError("For input_type_to_use='diann_precursor_ms1_and_ms2', please provide the DIA-NN report path via `path`.")
        lfq_manager.run_lfq(path, input_type_to_use=input_type_to_use, **kwargs)

    else:
        # check if pep exists
        if self.pep is None:
            raise ValueError("Peptide-level data not found. Please load peptide data before running directlfq normalization.")

        # Build peptide-level input table from .pep
        X = self.pep.layers.get("X_precursor", self.pep.X)
        if not isinstance(X, pd.DataFrame):
            X = X.toarray() if hasattr(X, "toarray") else X
        X_df = pd.DataFrame(
            X.T,
            index=self.pep.var_names,
            columns=self.pep.obs_names
        )
        prot_col = "Protein.Group" if "Protein.Group" in self.pep.var.columns else "Master Protein Accessions"
        X_df.insert(0, "protein", self.pep.var[prot_col].to_list())
        X_df.insert(1, "ion", X_df.index.to_list())

        if not strict:
            # e.g. "P03995; P03995-2" → two rows with same intensities, one per protein
            # ensure directLFQ sees only single-accession protein IDs
            n_before = X_df.shape[0]
            X_df["protein"] = X_df["protein"].astype(str).str.split(";")
            X_df = X_df.explode("protein")
            X_df["protein"] = X_df["protein"].str.strip()
            X_df = X_df[X_df["protein"] != ""]

            n_after = X_df.shape[0]
            if n_after > n_before:
                print(f"{format_log_prefix('info',2)} Expanded multi-protein peptide groups: {n_before} → {n_after} rows.")
            else:
                print(f"{format_log_prefix('info',2)} No multi-protein peptide groups detected for directlfq input.")

        X_df.reset_index(drop=True, inplace=True)
        tmp_file = "peptide_matrix.aq_reformat.tsv"
        X_df.to_csv(tmp_file, sep="\t", index=False)
        lfq_manager.run_lfq(tmp_file, **kwargs)

    # Load directlfq output (look for protein_intensities file)
    out_file = None
    for f in os.listdir("."):
        if f.endswith("protein_intensities.tsv"):
            out_file = f
    if out_file is None:
        raise FileNotFoundError("directlfq did not produce a '*protein_intensities.tsv' file in current directory.")

    norm_prot = pd.read_csv(out_file, sep="\t").set_index("protein")
    aligned = norm_prot.reindex(
        index=self.prot.var_names,
        columns=self.prot.obs_names
    )

    return aligned.T.to_numpy()

_annotate_pca_gsea_result_df

_annotate_pca_gsea_result_df(
    res_df: DataFrame,
) -> pd.DataFrame

Add library and pathway columns from gseapy Term when using merged Enrichr libraries (LIBRARY__pathway_name). Leaves Term unchanged.

Source code in src/scpviz/pAnnData/analysis.py
def _annotate_pca_gsea_result_df(res_df: pd.DataFrame) -> pd.DataFrame:
    """
    Add ``library`` and ``pathway`` columns from gseapy ``Term`` when using merged Enrichr
    libraries (``LIBRARY__pathway_name``). Leaves ``Term`` unchanged.
    """
    if "Term" not in res_df.columns:
        return res_df
    out = res_df.copy()
    term = out["Term"].astype(str)
    lib = term.map(lambda x: x.split("__", 1)[0] if "__" in x else "")
    pw = term.map(lambda x: x.split("__", 1)[1] if "__" in x else x)
    idx = list(out.columns).index("Term") + 1
    out.insert(idx, "library", lib.values)
    out.insert(idx + 1, "pathway", pw.values)
    return out

_gseapy_resolve_uppercase_genes

_gseapy_resolve_uppercase_genes(adata, gene_col='Genes')

For use with gseapy prerank and ssgsea functions. Resolves gene symbols from .var[gene_col], uppercase them, and return as a Series.

Hard-stops with a warning if gene names are unavailable.

Source code in src/scpviz/pAnnData/analysis.py
def _gseapy_resolve_uppercase_genes(adata, gene_col="Genes"):
    """
    For use with gseapy prerank and ssgsea functions. Resolves gene symbols from `.var[gene_col]`, uppercase them, and return as a Series.

    Hard-stops with a warning if gene names are unavailable.
    """
    if gene_col not in adata.var.columns:
        return None

    genes = adata.var[gene_col].copy()

    # Normalize empties to NaN
    genes = genes.replace("", np.nan)
    genes = genes.replace("nan", np.nan)

    # Uppercase non-missing values
    genes = genes.astype("object")
    genes = genes.where(genes.isna(), genes.astype(str).str.upper())

    return genes

_print_duplicate_gene_warning

_print_duplicate_gene_warning(
    dup_genes, method_desc="mean"
)

Print a warning listing duplicated gene symbols and chosen collapse method.

Source code in src/scpviz/pAnnData/analysis.py
def _print_duplicate_gene_warning(dup_genes, method_desc="mean"):
    """Print a warning listing duplicated gene symbols and chosen collapse method."""
    if len(dup_genes) == 0:
        return

    dup_text = ", ".join(dup_genes)
    print(f"{format_log_prefix('warn')} Found duplicated gene symbols.")
    print(f"{format_log_prefix('blank',3)} Duplicated genes ({len(dup_genes)}): {dup_text}")
    print(f"{format_log_prefix('blank',3)} Using {method_desc} for duplicated genes.")

base

Core base methods for pAnnData.

This mixin provides essential utility and management functions for cloning, checking, and managing core attributes of a pAnnData object. These methods serve as foundational building blocks for other mixins and functions.

Features:

  • Checks presence of data (.prot or .pep)
  • Safe object copying with state preservation
  • Internal metadata management (stats, history, summary)

Methods:

Name Description
_has_data

Check whether .prot and/or .pep data are present

copy

Return a new pAnnData object with retained internal state

show_layer_provenance

Print preprocessing provenance for one or all layers

Source code in src/scpviz/pAnnData/base.py
class BaseMixin:
    """
    Core base methods for pAnnData.

    This mixin provides essential utility and management functions for cloning, 
    checking, and managing core attributes of a `pAnnData` object. These methods
    serve as foundational building blocks for other mixins and functions.

    Features:

    - Checks presence of data (.prot or .pep)
    - Safe object copying with state preservation
    - Internal metadata management (stats, history, summary)

    Functions:
        _has_data: Check whether .prot and/or .pep data are present  
        copy: Return a new `pAnnData` object with retained internal state
        show_layer_provenance: Print preprocessing provenance for one or all layers
    """
    def _has_data(self) -> bool:
        """
        Check whether the pAnnData object contains either protein or peptide data.

        Returns:
            bool: True if either .prot or .pep is not None; otherwise False.
        """
        return self.prot is not None or self.pep is not None # type: ignore[attr-defined]

    def copy(self):
        """
        Return a new `pAnnData` object with the current state of all components.

        This method performs a shallow copy of core data (.prot, .pep) and a deep copy of internal attributes
        (e.g., RS matrix, summary, stats, and cached maps). It avoids full deepcopy for efficiency and retains
        the current filtered or processed state of the object.

        Returns:
            pAnnData: A new object containing copies of the current data and metadata.
        """
        new_obj = self.__class__.__new__(self.__class__)

        # Copy core AnnData components
        new_obj.prot = self.prot.copy() if self.prot is not None else None # type: ignore[attr-defined]
        new_obj.pep = self.pep.copy() if self.pep is not None else None # type: ignore[attr-defined]
        new_obj._rs = copy.deepcopy(self._rs) # type: ignore[attr-defined]

        # Copy summary and stats
        new_obj._stats = copy.deepcopy(self._stats) # type: ignore[attr-defined]
        new_obj._history = copy.deepcopy(self._history) # type: ignore[attr-defined]
        new_obj._metadata = copy.deepcopy(self.metadata) # type: ignore[attr-defined]
        new_obj._suppress_summary_log = True # type: ignore[attr-defined]
        new_obj.summary = self._summary.copy(deep=True) if self._summary is not None else None # go through setter to mark as stale, # type: ignore[attr-defined]
        del new_obj._suppress_summary_log # type: ignore[attr-defined]

        # Optional: cached maps
        if hasattr(self, "_gene_maps_protein"):
            new_obj._gene_maps_protein = copy.deepcopy(self._gene_maps_protein) # type: ignore[attr-defined]
        if hasattr(self, "_protein_maps_peptide"):
            new_obj._protein_maps_peptide = copy.deepcopy(self._protein_maps_peptide) # type: ignore[attr-defined]

        return new_obj

    def compare_current_to_raw(self, on="protein"):
        """
        Compare current pdata object to original raw data, showing how many samples and features were dropped.
        Compares current obs/var names to the original raw data (stored in .uns).

        Args:
            on (str): Dataset to compare ('protein' or 'peptide').

        Returns:
            dict: Dictionary summarizing dropped samples and features.
        """
        print(f"{format_log_prefix('user', 1)} Comparing current pdata to X_raw [{on}]:")

        adata = getattr(self, "prot" if on == "protein" else "pep", None)
        if adata is None:
            print(f"{format_log_prefix('warn', 2)} No {on} data found.")
            return None

        orig_obs = set(adata.uns.get("X_raw_obs_names", []))
        orig_var = set(adata.uns.get("X_raw_var_names", []))
        current_obs = set(adata.obs_names)
        current_var = set(adata.var_names)

        dropped_obs = sorted(list(orig_obs - current_obs))
        dropped_var = sorted(list(orig_var - current_var))

        print(f"   → Samples dropped: {len(dropped_obs)}")
        print(f"   → Features dropped: {len(dropped_var)}")

        return {"dropped_samples": dropped_obs, "dropped_features": dropped_var}

    def show_layer_provenance(
        self,
        layer: str | None = None,
        on: str = "protein",
    ) -> None:
        """
        Pretty-print the provenance chain for one or all layers.

        Uses ``adata.uns['current_X_layer']`` (maintained by ``set_X()``) to highlight
        the active ``.X`` matrix when printing the full registry. Chains walk through
        ``input_layer`` pointers and show non-registry roots (e.g. ``X_raw``) as
        ``(raw input)``.
        """
        adata = utils.get_adata(self, on)  # type: ignore[arg-type]
        registry: dict = adata.uns.get("layer_provenance", {})

        on_label = "protein" if on in ("protein", "prot") else "peptide"

        if not registry:
            print(
                f"{utils.format_log_prefix('info')} No layer provenance recorded yet "
                f"for [{on_label}]. Run normalize(), impute(), or log_transform() first."
            )
            return

        def _build_chain(target: str) -> list[tuple[str, dict | None]]:
            chain: list[tuple[str, dict | None]] = []
            visited: set[str] = set()
            current: str = target
            while current and current not in visited:
                visited.add(current)
                rec = registry.get(current)
                chain.append((current, rec))
                if rec is None:
                    break
                nxt = rec.get("input_layer", "")
                if not nxt:
                    break
                current = nxt
            chain.reverse()
            return chain

        def _print_chain(
            target: str,
            label: str | None = None,
            indent: int = 0,
        ) -> set[str]:
            chain = _build_chain(target)
            shown: set[str] = set()
            pad = "  " * indent
            header = label or f"'{target}'"
            print(f"\n{pad}{header}:")

            for i, (lname, rec) in enumerate(chain):
                shown.add(lname)
                depth_pad = "  " * (indent + i)
                step_num = f"[{i}]"

                if rec is None:
                    print(f"  {depth_pad}{step_num}  '{lname}'  (raw input)")
                else:
                    op = rec.get("op", "?")
                    inp = rec.get("input_layer", "?")
                    extras = {
                        k: v
                        for k, v in rec.items()
                        if k not in ("op", "input_layer")
                    }
                    extras_str = (
                        ", ".join(f"{k}={v}" for k, v in sorted(extras.items()))
                        if extras
                        else ""
                    )
                    tail = f", {extras_str}" if extras_str else ""
                    if i == 0:
                        print(f"  {depth_pad}{step_num}  '{lname}'")
                    else:
                        print(
                            f"  {depth_pad}{step_num}  '{lname}'  ← {op}({inp}{tail})"
                        )

            return shown

        def _find_current_X_layer() -> str | None:
            return adata.uns.get("current_X_layer")

        if layer is not None:
            if layer not in registry:
                print(
                    f"{utils.format_log_prefix('warn')} Layer '{layer}' not found "
                    "in provenance registry."
                )
                return
            _print_chain(layer)
            return

        print(f"  Layer provenance  [{on_label}]")

        shown_layers: set[str] = set()

        current_X = _find_current_X_layer()
        if current_X and current_X in registry:
            print(f"\n  ● Current .X layer:")
            shown_layers |= _print_chain(
                current_X, label=f"  '{current_X}'", indent=1
            )
        elif current_X:
            print(
                f"\n  ● Current .X layer: '{current_X}' (not in registry)"
            )
            shown_layers.add(current_X)

        remaining = sorted(
            lname for lname in registry if lname not in shown_layers
        )
        if remaining:
            print(f"\n  ○ Other layers:")
            for lname in remaining:
                shown_layers |= _print_chain(
                    lname, label=f"  '{lname}'", indent=1
                )

        print(f"\n{'─'*55}\n")

_has_data

_has_data() -> bool

Check whether the pAnnData object contains either protein or peptide data.

Returns:

Name Type Description
bool bool

True if either .prot or .pep is not None; otherwise False.

Source code in src/scpviz/pAnnData/base.py
def _has_data(self) -> bool:
    """
    Check whether the pAnnData object contains either protein or peptide data.

    Returns:
        bool: True if either .prot or .pep is not None; otherwise False.
    """
    return self.prot is not None or self.pep is not None # type: ignore[attr-defined]

editing

Provides utilities for modifying core components of a pAnnData object, including matrix layers, abundance formatting, exports, and the protein–peptide mapping.

This mixin includes utilities for:

  • Replacing .X with a specific layer from protein or peptide data.
  • Extracting long-form abundance DataFrames with metadata for plotting or analysis.
  • Exporting internal data (summary, matrix layers) to disk.
  • Setting or updating the RS (protein × peptide) relational mapping matrix.

Methods:

Name Description
set_X

Sets the .X matrix of protein or peptide data to a specified layer.

get_abundance

Returns long-form abundance + metadata for selected features.

export

Exports summary, matrix values, and layers to CSV.

export_layer

Exports a specific layer of the pAnnData object, with support for custom column and row headers.

_set_RS

Sets the RS (protein × peptide) mapping matrix, with optional validation.

Source code in src/scpviz/pAnnData/editing.py
  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
class EditingMixin:
    """
    Provides utilities for modifying core components of a `pAnnData` object, including 
    matrix layers, abundance formatting, exports, and the protein–peptide mapping.

    This mixin includes utilities for:

    - Replacing `.X` with a specific layer from protein or peptide data.
    - Extracting long-form abundance DataFrames with metadata for plotting or analysis.
    - Exporting internal data (summary, matrix layers) to disk.
    - Setting or updating the RS (protein × peptide) relational mapping matrix.

    Functions:
        set_X: Sets the `.X` matrix of protein or peptide data to a specified layer.
        get_abundance: Returns long-form abundance + metadata for selected features.
        export: Exports summary, matrix values, and layers to CSV.
        export_layer: Exports a specific layer of the pAnnData object, with support for custom column and row headers.
        _set_RS: Sets the RS (protein × peptide) mapping matrix, with optional validation.
    """

    def set_X(self, layer, on = 'protein'):
        """
        Set the `.X` matrix of protein or peptide data to a specified layer.

        This method replaces the active `.X` matrix with the contents of a named layer 
        from `.prot.layers` or `.pep.layers`. This is useful for switching between 
        different processing stages (e.g., normalized, imputed, or raw data).

        Args:
            layer (str): Name of the data layer to assign to `.X`.
            on (str): Whether to operate on `"protein"` or `"peptide"` data (default is `"protein"`).

        Returns:
            None

        Example:
            Set the protein matrix `.X` to the "normalized" layer:
                ```python
                pdata.set_X(layer="normalized", on="protein")
                ```

            Set the peptide matrix `.X` to the "imputed" layer:
                ```python
                pdata.set_X(layer="imputed", on="peptide")
                ```
        """
        # defines which layer to set X to
        if not self._check_data(on): # type: ignore[attr-defined]
            pass

        if on == 'protein':
            if layer not in self.prot.layers: # type: ignore[attr-defined]
                raise ValueError(f"Layer {layer} not found in protein data.")
            self.prot.X = self.prot.layers[layer] # type: ignore[attr-defined]
            self.prot.uns["current_X_layer"] = layer  # type: ignore[attr-defined]
            print(f"{format_log_prefix('info_only', indent=2)} Set {on} data to layer {layer}.")

        else:
            if layer not in self.pep.layers: # type: ignore[attr-defined]
                raise ValueError(f"Layer {layer} not found in peptide data.")
            self.pep.X = self.pep.layers[layer] # type: ignore[attr-defined]
            self.pep.uns["current_X_layer"] = layer  # type: ignore[attr-defined]
            print(f"{format_log_prefix('info_only', indent=2)} Set {on} data (.X) to layer {layer}.")

        self._history.append(f"{on}: Set X to layer {layer}.") # type: ignore[attr-defined]
        self.update_summary(recompute=True, verbose=False) # type: ignore[attr-defined], SummaryMixin

    def get_abundance(self, namelist=None, layer='X', on='protein', classes=None, log=True, x_label='gene', all_matches=False):
        """
        Extract a long-form abundance DataFrame from a pAnnData object.

        This method returns a melted (long-form) DataFrame containing abundance values
        along with optional sample metadata and protein/peptide annotations.

        Args:
            namelist (list of str, optional): List of accessions or gene names to extract. If None, returns all features.
            layer (str): Name of the data layer to use (default is "X").
            on (str): Whether to extract from "protein" or "peptide" data.
            classes (str or list of str, optional): Sample-level `.obs` column(s) to include for grouping or plotting.
            log (bool): If True, applies log2 transform to abundance values.
            x_label (str): Whether to label features by "gene" or "accession" in the output.
            all_matches (bool): If False (default), each gene name in ``namelist`` resolves to one
                accession; if True, returns every matching isoform (see ``resolve_accessions``).

        Returns:
            pd.DataFrame: Long-form DataFrame with abundance values and associated metadata.

        Example:
            Extract abundance values for selected proteins, grouped by sample-level metadata:
                ```python
                df_abund = pdata.get_abundance(
                    namelist=["UBE4B", "GAPDH"],
                    on="protein",
                    classes=["treatment", "cellline"]
                )
                ```

        Note:
            This method is also available as a utility function in utils, for `AnnData` or `pAnnData` objects:
                ```python
                from scutils import get_abundance
                df_abund = get_abundance(pdata, namelist=["UBE4B", "GAPDH"], on="protein", classes=["treatment", "cellline"])
                ```
        """
        on_user = on.lower()
        gene_to_acc, _ = self.get_gene_maps(on='protein' if on_user in ('peptide', 'pep') else on_user) # type: ignore[attr-defined]

        if namelist is not None:
            if isinstance(namelist, str):
                namelist = [namelist]

        if on == 'peptide' and namelist:
            pep_names = self.pep.var_names.astype(str) # type: ignore[attr-defined]
            matched_peptides = [name for name in namelist if name in pep_names]
            non_peptides = [name for name in namelist if name not in matched_peptides]

            adata = None
            if len(matched_peptides) < len(namelist):
                filtered = self.filter_prot(
                    accessions=non_peptides, all_matches=all_matches, return_copy=True
                ) # type: ignore[attr-defined]
                adata = filtered.pep

            if matched_peptides:
                direct_peps = self.pep[:, matched_peptides] # type: ignore[attr-defined]
                adata = direct_peps if adata is None else adata.concatenate(direct_peps, join='outer')

            if adata is None or adata.n_vars == 0:
                raise ValueError("No matching peptides found from the provided `namelist`.")

            adata = adata[:, ~adata.var_names.duplicated()]

        else:
            adata = utils.get_adata(self, on)

            if namelist:
                resolved = utils.resolve_accessions(
                    adata, namelist, gene_map=gene_to_acc, all_matches=all_matches
                )
                adata = adata[:, resolved]

        # Extract the abundance matrix
        X = adata.layers[layer] if layer in adata.layers else adata.X
        if hasattr(X, "toarray"):
            X = X.toarray()

        # Melt into long form
        df = pd.DataFrame(X, columns=adata.var_names, index=adata.obs_names).reset_index()
        df = df.melt(id_vars="index", var_name="accession", value_name="abundance")
        df = df.rename(columns={"index": "cell"})

        # Merge obs metadata
        df = df.merge(adata.obs.reset_index(), left_on="cell", right_on="index")

        _, pep_to_prot = self.get_gene_maps(on='peptide')  # peptide → protein map, # type: ignore[attr-defined]
        _, acc_to_gene = self.get_gene_maps(on='protein')  # protein accession → gene, # type: ignore[attr-defined]
        # Map to gene names
        if on == 'peptide':
            try:
                df['protein_accession'] = df['accession'].map(pep_to_prot)
                df['gene'] = df['protein_accession'].map(acc_to_gene)

                # Report unmapped peptides
                unmapped = df[df['gene'].isna()]['accession'].unique().tolist()
                if unmapped:
                    print(f"[get_abundance] {len(unmapped)} peptides could not be mapped to genes: {unmapped}")
            except Exception as e:
                print(f"[get_abundance] Mapping error: {e}")
                df['gene'] = None
        else:
            df['gene'] = df['accession'].map(acc_to_gene)

        # Determine x-axis label
        if x_label == 'gene':
            df['x_label_name'] = df['gene'].fillna(df['accession'])
        elif x_label == 'accession':
            if on == 'protein':
                df['x_label_name'] = df['accession']
            elif on == 'peptide':
                try:
                    mapping_col = utils.get_pep_prot_mapping(self)
                    pep_to_prot = self.pep.var[mapping_col].to_dict() # type: ignore[attr-defined]
                    df['x_label_name'] = df['protein_accession']
                except Exception as e:
                    warnings.warn(f"Could not map peptides to accessions: {e}")
                    df['x_label_name'] = df['accession']
        else:
            df['x_label_name'] = df['accession']  # fallback

        # Annotate class/grouping
        if classes:
            df['class'] = df[classes] if isinstance(classes, str) else df[classes].astype(str).agg('_'.join, axis=1)
        else:
            df['class'] = 'all'

        # Log transform
        if log:
            df['log2_abundance'] = np.log2(np.clip(df['abundance'], 1e-6, None))

        return df

    def export(self, filename, format = 'csv', verbose = True):
        """
        Export the pAnnData object's contents to file, including layers and summary metadata.

        This method saves the summary table, protein matrix, and all data layers as separate 
        CSV files using the specified filename as a prefix.

        Args:
            filename (str): Prefix for exported files. If None, uses the current date and time.
            format (str): File format to export (default is "csv").
            verbose (bool): Whether to print progress messages.

        Returns:
            None

        Todo:
            Add example usage showing how to export data and where files are saved. (HDF5, Parquet?)
        """
        if filename is None:
            filename = setup.get_datetime()

        if not self._has_data():
            raise ValueError("No data found in pAnnData object.")

        if verbose:
            print(f"{format_log_prefix('user')} Exporting pAnnData to <{filename}>...")

        # --- Summary ---
        self.summary.to_csv(f"{filename}_summary.csv")
        if verbose:
            print(f"{format_log_prefix('result_only',2)} Exported summary table → {filename}_summary.csv")

        # --- Protein matrix ---
        if self.prot is not None:
            self.prot.to_df().to_csv(f"{filename}_protein.csv")
            if verbose:
                print(f"{format_log_prefix('result_only',2)} Exported protein matrix → {filename}_protein.csv")

            for layer in self.prot.layers:
                if not isinstance(layer, str):
                    continue  # anndata >= 0.13 stores .X as layers[None]
                arr = self.prot.layers[layer]
                if hasattr(arr, 'toarray'):
                    arr = arr.toarray()
                df = pd.DataFrame(arr, index=self.prot.obs_names, columns=self.prot.var_names)
                df.to_csv(f"{filename}_protein_{layer}.csv")
                if verbose:
                    print(f"{format_log_prefix('result_only',2)} Exported protein layer '{layer}' → {filename}_protein_{layer}.csv")

        # --- Peptide matrix ---
        if self.pep is not None:
            self.pep.to_df().to_csv(f"{filename}_peptide.csv")
            if verbose:
                print(f"{format_log_prefix('result_only',2)} Exported peptide matrix → {filename}_peptide.csv")

            for layer in self.pep.layers:
                if not isinstance(layer, str):
                    continue  # anndata >= 0.13 stores .X as layers[None]
                arr = self.pep.layers[layer]
                if hasattr(arr, 'toarray'):
                    arr = arr.toarray()
                df = pd.DataFrame(arr, index=self.pep.obs_names, columns=self.pep.var_names)
                df.to_csv(f"{filename}_peptide_{layer}.csv")
                if verbose:
                    print(f"{format_log_prefix('result_only',2)} Exported peptide layer '{layer}' → {filename}_peptide_{layer}.csv")

    def export_layer(self, layer_name, filename=None, on='protein', obs_names=None, var_names=None, transpose=False):
        """
        Export a specified layer from the protein or peptide data to CSV with labeled rows and columns.

        Args:
            layer_name (str): Name of the layer to export (e.g., "X_raw"). If "X" is provided, exports `pdata.X`
            filename (str, optional): Output file name. Defaults to "<layer_name>.csv".
            on (str): One of 'protein' or 'peptide' to specify which data to use.
            obs_names (str, list of str, or None): Column name(s) in ``.obs`` for row labels.
                A single string uses that column; a list uses multiple columns, written as
                multiple index columns in the CSV (``MultiIndex``).
            var_names (str, list of str, or None): Column name(s) in ``.var`` for column labels.
                Same behavior as ``obs_names`` for the header (multiple header rows when a list).
            transpose: If True, then export as proteins/peptides (rows) by samples (columns)

        Returns:
            None
        """

        def _export_axis_labels(axis_df: pd.DataFrame, names, fallback):
            """Row or column labels for ``export_layer`` from ``.obs`` or ``.var`` columns."""
            if names is None:
                return fallback
            if isinstance(names, str):
                return axis_df[names]
            sub = axis_df[names]
            if isinstance(sub, pd.DataFrame) and sub.shape[1] > 1:
                return pd.MultiIndex.from_frame(sub)
            if isinstance(sub, pd.DataFrame) and sub.shape[1] == 1:
                return sub.iloc[:, 0]
            return sub

        # Select the appropriate AnnData object
        adata = self.prot if on == 'protein' else self.pep
        if layer_name == "X":
            layer=adata.X.toarray() if hasattr(adata.X, 'toarray') else adata.X
        else:
            layer = adata.layers[layer_name]

        # Convert to dense array if needed
        if not isinstance(layer, pd.DataFrame):
            layer = layer.toarray() if hasattr(layer, 'toarray') else layer

        # Get row (obs) and column (var) labels
        row_labels = _export_axis_labels(adata.obs, obs_names, adata.obs_names)
        col_labels = _export_axis_labels(adata.var, var_names, adata.var_names)

        # Build the DataFrame
        if transpose:
            df = pd.DataFrame(layer.T, columns=row_labels, index=col_labels)
        else:
            df = pd.DataFrame(layer, index=row_labels, columns=col_labels)

        # Save to CSV
        if filename is None:
            filename = f"{layer_name}.csv"
        df.to_csv(filename)

    def export_morpheus(self, filename='pdata', on='protein'):
        if not self._check_data(on):  # type: ignore[attr-defined], ValidationMixin
            return

        adata = self.prot if on == 'protein' else self.pep

        # alternatively, use morpheus to plot clustermap
        # will need two things
        # 1. dataset (proteins in column, samples in rows)
        dense_matrix = adata.X.toarray()
        df = pd.DataFrame(dense_matrix, index=adata.obs_names, columns=adata.var_names)
        df.to_csv(f'{filename}_protein_matrix.csv')
        # 2. File Annotations (each sample in a row, different annotations in columns)
        adata.obs.to_csv(f'{filename}_protein_annotations.csv')
        # 3. Protein Annotations (each protein in a row, different annotations in columns)
        adata.var.to_csv(f'{filename}_protein_annotations.csv')

        print(f"{format_log_prefix('result')} Morpheus export complete.")

    def _set_RS(self, rs, debug=False, validate=True):
        """
        Set the RS (protein × peptide) mapping matrix.

        This internal method assigns a new RS matrix to the object. If the input appears 
        to be in peptide × protein format, it will be automatically transposed.

        Args:
            rs (np.ndarray or sparse matrix): The new RS matrix to assign.
            debug (bool): If True, prints diagnostic information.
            validate (bool): If True (default), checks that the RS shape matches `.prot` and `.pep`.

        Returns:
            None
        """
        if debug:
            print(f"Setting rs matrix with dimensions {rs.shape}")

        # Only validate if requested (e.g. for external .rs = ... use)
        if validate:
            prot_n = self.prot.shape[1] if self.prot is not None else None
            pep_n = self.pep.shape[1] if self.pep is not None else None
            rs_shape = rs.shape

            valid_prot_pep = (prot_n is None or rs_shape[0] == prot_n) and (pep_n is None or rs_shape[1] == pep_n)
            valid_pep_prot = (prot_n is None or rs_shape[1] == prot_n) and (pep_n is None or rs_shape[0] == pep_n)

            if not (valid_prot_pep or valid_pep_prot):
                raise ValueError(
                    f"❌ RS shape {rs_shape} does not match expected protein × peptide "
                    f"({prot_n} × {pep_n}) or peptide × protein ({pep_n} × {prot_n})."
                )

            # Transpose if necessary
            if self.prot is not None and rs_shape[0] != prot_n:
                if debug:
                    print("↔️  Transposing RS matrix to match protein × peptide format")
                rs = rs.T

        # Always store as sparse
        self._rs = sparse.csr_matrix(rs)

        if debug:
            nnz = self._rs.nnz
            total = self._rs.shape[0] * self._rs.shape[1]
            sparsity = 100 * (1 - nnz / total)
            print(f"{format_log_prefix('result',indent=1)} RS matrix set: {self._rs.shape} (proteins × peptides), sparsity: {sparsity:.2f}%")

        prot_n = self.prot.n_vars if self.prot is not None else None
        pep_n = self.pep.n_vars if self.pep is not None else None
        rs_matches = (
            (prot_n is None or self._rs.shape[0] == prot_n)
            and (pep_n is None or self._rs.shape[1] == pep_n)
        )
        if rs_matches:
            self.update_summary(recompute=True, verbose=False) # type: ignore[attr-defined], SummaryMixin

_set_RS

_set_RS(rs, debug=False, validate=True)

Set the RS (protein × peptide) mapping matrix.

This internal method assigns a new RS matrix to the object. If the input appears to be in peptide × protein format, it will be automatically transposed.

Parameters:

Name Type Description Default
rs np.ndarray or sparse matrix

The new RS matrix to assign.

required
debug bool

If True, prints diagnostic information.

False
validate bool

If True (default), checks that the RS shape matches .prot and .pep.

True

Returns:

Type Description

None

Source code in src/scpviz/pAnnData/editing.py
def _set_RS(self, rs, debug=False, validate=True):
    """
    Set the RS (protein × peptide) mapping matrix.

    This internal method assigns a new RS matrix to the object. If the input appears 
    to be in peptide × protein format, it will be automatically transposed.

    Args:
        rs (np.ndarray or sparse matrix): The new RS matrix to assign.
        debug (bool): If True, prints diagnostic information.
        validate (bool): If True (default), checks that the RS shape matches `.prot` and `.pep`.

    Returns:
        None
    """
    if debug:
        print(f"Setting rs matrix with dimensions {rs.shape}")

    # Only validate if requested (e.g. for external .rs = ... use)
    if validate:
        prot_n = self.prot.shape[1] if self.prot is not None else None
        pep_n = self.pep.shape[1] if self.pep is not None else None
        rs_shape = rs.shape

        valid_prot_pep = (prot_n is None or rs_shape[0] == prot_n) and (pep_n is None or rs_shape[1] == pep_n)
        valid_pep_prot = (prot_n is None or rs_shape[1] == prot_n) and (pep_n is None or rs_shape[0] == pep_n)

        if not (valid_prot_pep or valid_pep_prot):
            raise ValueError(
                f"❌ RS shape {rs_shape} does not match expected protein × peptide "
                f"({prot_n} × {pep_n}) or peptide × protein ({pep_n} × {prot_n})."
            )

        # Transpose if necessary
        if self.prot is not None and rs_shape[0] != prot_n:
            if debug:
                print("↔️  Transposing RS matrix to match protein × peptide format")
            rs = rs.T

    # Always store as sparse
    self._rs = sparse.csr_matrix(rs)

    if debug:
        nnz = self._rs.nnz
        total = self._rs.shape[0] * self._rs.shape[1]
        sparsity = 100 * (1 - nnz / total)
        print(f"{format_log_prefix('result',indent=1)} RS matrix set: {self._rs.shape} (proteins × peptides), sparsity: {sparsity:.2f}%")

    prot_n = self.prot.n_vars if self.prot is not None else None
    pep_n = self.pep.n_vars if self.pep is not None else None
    rs_matches = (
        (prot_n is None or self._rs.shape[0] == prot_n)
        and (pep_n is None or self._rs.shape[1] == pep_n)
    )
    if rs_matches:
        self.update_summary(recompute=True, verbose=False) # type: ignore[attr-defined], SummaryMixin

enrichment

_pretty_vs_key

_pretty_vs_key(k)

Format a DE contrast key into a human-readable string.

This function attempts to convert a string representation of a DE comparison (e.g., a list of dictionaries) into a simplified "group1 vs group2" format, using the values from each dictionary in the left and right group.

Parameters:

Name Type Description Default
k str

DE key string, typically in the format "[{{...}}] vs [{{...}}]".

required

Returns:

Name Type Description
str

A simplified, human-readable version of the DE comparison key.

Source code in src/scpviz/pAnnData/enrichment.py
def _pretty_vs_key(k):
    """
    Format a DE contrast key into a human-readable string.

    This function attempts to convert a string representation of a DE comparison
    (e.g., a list of dictionaries) into a simplified `"group1 vs group2"` format,
    using the values from each dictionary in the left and right group.

    Args:
        k (str): DE key string, typically in the format `"[{{...}}] vs [{{...}}]"`.

    Returns:
        str: A simplified, human-readable version of the DE comparison key.
    """
    import ast
    try:
        parts = k.split(" vs ")
        left = "_".join(str(v) for d in ast.literal_eval(parts[0]) for v in d.values())
        right = "_".join(str(v) for d in ast.literal_eval(parts[1]) for v in d.values())
        return f"{left} vs {right}"
    except Exception:
        return k  # fallback to raw key if anything goes wrong

_resolve_de_key

_resolve_de_key(stats_dict, user_key, debug=False)

Resolve a user-supplied DE key to a valid key stored in .stats["de_results"].

This function matches a flexible, human-readable DE key against the internal keys stored in the DE results dictionary. It supports both raw and pretty-formatted keys, and can handle suffixes like _up, _down, or _both for directional analysis.

Parameters:

Name Type Description Default
stats_dict dict

Dictionary of DE results (typically pdata.stats["de_results"]).

required
user_key str

User-supplied key to resolve, e.g., "AS_kd vs AS_sc_down".

required
debug bool

If True, prints detailed debug output for tracing.

False

Returns:

Name Type Description
str

The matching internal DE result key.

Raises:

Type Description
ValueError

If no matching key is found.

Source code in src/scpviz/pAnnData/enrichment.py
def _resolve_de_key(stats_dict, user_key, debug=False):
    """
    Resolve a user-supplied DE key to a valid key stored in `.stats["de_results"]`.

    This function matches a flexible, human-readable DE key against the internal keys
    stored in the DE results dictionary. It supports both raw and pretty-formatted keys,
    and can handle suffixes like `_up`, `_down`, or `_both` for directional analysis.

    Args:
        stats_dict (dict): Dictionary of DE results (typically `pdata.stats["de_results"]`).
        user_key (str): User-supplied key to resolve, e.g., "AS_kd vs AS_sc_down".
        debug (bool): If True, prints detailed debug output for tracing.

    Returns:
        str: The matching internal DE result key.

    Raises:
        ValueError: If no matching key is found.
    """
    import re
    print(f"[DEBUG] Resolving user key: {user_key}") if debug else None

    # Extract suffix
    suffix = ""
    if user_key.endswith(_DE_DIRECTION_SUFFIXES):
        user_key, suffix = re.match(r"(.+)(_up|_down|_both)", user_key).groups()
        print(f"[DEBUG] Split into base='{user_key}', suffix='{suffix}'") if debug else None

    # Build pretty key mapping
    pretty_map = {}
    for full_key in stats_dict:
        if "vs" not in full_key:
            continue

        if full_key.endswith(_DE_DIRECTION_SUFFIXES):
            base = full_key.rsplit("_", 1)[0]
            full_suffix = "_" + full_key.rsplit("_", 1)[1]
        else:
            base = full_key
            full_suffix = ""

        pretty_key = _pretty_vs_key(base)
        final_key = pretty_key + full_suffix
        pretty_map[final_key] = full_key
        print(f"[DEBUG] Mapped '{final_key}' → '{full_key}'")  if debug else None

    full_user_key = user_key + suffix
    print(f"[DEBUG] Full user key for lookup: '{full_user_key}'")  if debug else None

    # Pretty-format the *user* key so short lookups ("BE_kd vs BE_sc") resolve
    # against dict-repr de() keys, and vice versa.
    pretty_user_key = _pretty_vs_key(user_key) + suffix
    print(f"[DEBUG] Pretty user key for lookup: '{pretty_user_key}'") if debug else None

    if full_user_key in stats_dict:
        print("[DEBUG] Found direct match in stats.") if debug else None
        return full_user_key
    if full_user_key in pretty_map:
        print(f"[DEBUG] Found in pretty map: {pretty_map[full_user_key]}")  if debug else None
        return pretty_map[full_user_key]
    if pretty_user_key != full_user_key and pretty_user_key in stats_dict:
        print("[DEBUG] Found pretty-formatted user key in stats.") if debug else None
        return pretty_user_key
    if pretty_user_key != full_user_key and pretty_user_key in pretty_map:
        print(f"[DEBUG] Found pretty user key in pretty map: {pretty_map[pretty_user_key]}") if debug else None
        return pretty_map[pretty_user_key]

    pretty_keys = "\n".join(f"  - {k}" for k in pretty_map.keys()) if pretty_map else "  (none found)"
    raise ValueError(
        f"'{full_user_key}' not found in stats.\n"
        f"Available DE keys:\n{pretty_keys}"
    )

filtering

_detect_ambiguous_input

_detect_ambiguous_input(group, var, group_metrics=None)

Detects ambiguous user input mixing file and group identifiers.

This helper checks whether the group list includes both file-like identifiers (present in .var as 'Found In: ') and group-like identifiers (present in .uns as ('group', 'count') tuples).

Parameters:

Name Type Description Default
group list of str

User-provided identifiers for filtering.

required
var DataFrame

The .var table of the corresponding AnnData object.

required
group_metrics DataFrame

MultiIndex DataFrame from .uns containing per-group ('count', 'ratio') metrics.

None

Returns:

Name Type Description
tuple (bool, list, list)

(is_ambiguous, annotated_files, annotated_groups) - is_ambiguous (bool): True if both file-like and group-like entries coexist. - annotated_files (list): Entries that match file-level columns. - annotated_groups (list): Entries that match group-level metrics.

Source code in src/scpviz/pAnnData/filtering.py
def _detect_ambiguous_input(group, var, group_metrics=None):
    """
    Detects ambiguous user input mixing file and group identifiers.

    This helper checks whether the `group` list includes both
    file-like identifiers (present in `.var` as 'Found In: <file>')
    and group-like identifiers (present in `.uns` as ('group', 'count') tuples).

    Args:
        group (list of str): User-provided identifiers for filtering.
        var (pd.DataFrame): The `.var` table of the corresponding AnnData object.
        group_metrics (pd.DataFrame, optional): MultiIndex DataFrame from `.uns`
            containing per-group ('count', 'ratio') metrics.

    Returns:
        tuple(bool, list, list):
            (is_ambiguous, annotated_files, annotated_groups)
            - is_ambiguous (bool): True if both file-like and group-like entries coexist.
            - annotated_files (list): Entries that match file-level columns.
            - annotated_groups (list): Entries that match group-level metrics.
    """
    annotated_files = [g for g in group if f"Found In: {g}" in var.columns]
    annotated_groups = []
    if group_metrics is not None:
        annotated_groups = [
            g for g in group
            if (g, "count") in group_metrics.columns or (g, "ratio") in group_metrics.columns
        ]

    has_file_like = bool(annotated_files)
    has_group_like = bool(annotated_groups)

    # Ambiguous only if both exist and sets are distinct
    is_ambiguous = has_file_like and has_group_like and set(annotated_files) != set(annotated_groups)

    return is_ambiguous, annotated_files, annotated_groups

Provides flexible filtering and annotation methods for samples, proteins, and peptides.

This mixin includes utilities for:

  • Filtering proteins and peptides by metadata conditions, group-level detection, or peptide mapping structure.
  • Filtering samples based on class annotations, numeric thresholds, file lists, or query strings.
  • Annotating detection status ("Found In") across samples and class-based groups.
  • Managing and validating the protein-peptide relational structure (RS matrix) after filtering.

Methods:

Name Description
filter_prot

Filters proteins using .var metadata conditions or a list of accessions/genes to retain.

filter_prot_found

Keeps proteins or peptides found in a minimum number or proportion of samples within a group or file list.

_filter_sync_peptides_to_proteins

Removes peptides orphaned by upstream protein filtering.

filter_sample

Filters samples using categorical metadata, numeric thresholds, file/sample lists, or POI abundance.

_filter_sample_condition

Internal helper for filtering samples using .summary conditions or name lists.

_filter_sample_values

Filters samples using dictionary-style matching on metadata fields.

_filter_sample_poi

Filters samples by protein/peptide abundance thresholds for a POI.

_filter_sample_query

Parses and applies a raw pandas-style query string to .obs or .summary.

filter_rs

Filters the RS matrix by peptide count and ambiguity, and updates .prot/.pep accordingly.

_apply_rs_filter

Applies protein/peptide masks to .prot, .pep, and .rs matrices.

_format_filter_query

Formats filter conditions for .eval() by quoting fields and handling includes syntax.

annotate_found

Adds group-level "Found In" indicators to .prot.var or .pep.var.

_annotate_found_samples

Computes per-sample detection flags for use by annotate_found().

Source code in src/scpviz/pAnnData/filtering.py
  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
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
class FilterMixin:
    """
    Provides flexible filtering and annotation methods for samples, proteins, and peptides.

    This mixin includes utilities for:

    - Filtering proteins and peptides by metadata conditions, group-level detection, or peptide mapping structure.
    - Filtering samples based on class annotations, numeric thresholds, file lists, or query strings.
    - Annotating detection status ("Found In") across samples and class-based groups.
    - Managing and validating the protein-peptide relational structure (RS matrix) after filtering.

    Functions:
        filter_prot: Filters proteins using `.var` metadata conditions or a list of accessions/genes to retain.
        filter_prot_found: Keeps proteins or peptides found in a minimum number or proportion of samples within a group or file list.
        _filter_sync_peptides_to_proteins: Removes peptides orphaned by upstream protein filtering.
        filter_sample: Filters samples using categorical metadata, numeric thresholds, file/sample lists, or POI abundance.
        _filter_sample_condition: Internal helper for filtering samples using `.summary` conditions or name lists.
        _filter_sample_values: Filters samples using dictionary-style matching on metadata fields.
        _filter_sample_poi: Filters samples by protein/peptide abundance thresholds for a POI.
        _filter_sample_query: Parses and applies a raw pandas-style query string to `.obs` or `.summary`.
        filter_rs: Filters the RS matrix by peptide count and ambiguity, and updates `.prot`/`.pep` accordingly.
        _apply_rs_filter: Applies protein/peptide masks to `.prot`, `.pep`, and `.rs` matrices.
        _format_filter_query: Formats filter conditions for `.eval()` by quoting fields and handling `includes` syntax.
        annotate_found: Adds group-level "Found In" indicators to `.prot.var` or `.pep.var`.
        _annotate_found_samples: Computes per-sample detection flags for use by `annotate_found()`.
    """

    def filter_prot(self, condition = None, accessions=None, valid_genes=False, unique_profiles=False, all_matches=False, return_copy = True, debug=False):
        """
        Filter protein data based on metadata conditions or accession list (protein name and gene name).

        This method filters the protein-level data either by evaluating a string condition on the protein metadata,
        or by providing a list of protein accession numbers (or gene names) to keep. Peptides that are exclusively
        linked to removed proteins are also removed, and the RS matrix is updated accordingly.

        Args:
            condition (str): A condition string to filter protein metadata. Supports:

                - Standard comparisons, e.g. `"Protein FDR Confidence: Combined == 'High'"`
                - Substring queries using `includes`, e.g. `"Description includes 'p97'"`
            accessions (list of str, optional): List of accession numbers (var_names) to keep.
            all_matches (bool): When filtering by gene name via ``accessions``, if True keep every
                protein whose ``Genes`` value matches; if False (default) keep one accession per
                gene (last duplicate in ``.var`` order).
            valid_genes (bool): If True, removes rows with missing gene names and resolves duplicate gene names by appending numeric suffixes.
            unique_profiles (bool): If True, remove rows with duplicate abundance profiles across samples.
            return_copy (bool): If True, returns a filtered copy. If False, modifies in place.
            debug (bool): If True, prints debugging information.

        Returns:
            pAnnData (pAnnData): Returns a filtered pAnnData object if `return_copy=True`. 
            None (None): Otherwise, modifies in-place and returns None.

        Example:
            Filter by metadata condition:
                ```python
                condition = "Protein FDR Confidence: Combined == 'High'"
                pdata.filter_prot(condition=condition)
                ```

            Substring match on protein description:
                ```python
                condition = "Description includes 'p97'"
                pdata.filter_prot(condition=condition)
                ```

            Numerical condition on metadata:
                ```python
                condition = "Score > 0.75"
                pdata.filter_prot(condition=condition)
                ```

            Filter by specific protein accessions:
                ```python
                accessions = ['GAPDH', 'P53']
                pdata.filter_prot(accessions=accessions)
                ```

            Filter out all that have no valid genes (potentially artefacts):
                ```python
                pdata.filter_prot(valid_genes=True)
                ```

            !!! tip
                Multiple filters can be combined in a single call. For example, to filger by condition and valid genes:
                ```python
                condition = "Score > 0.75"
                pdata.filter_prot(condition=condition, valid_genes=True)
        """
        from scipy.sparse import issparse

        if not self._check_data('protein'): # type: ignore[attr-defined]
            raise ValueError(f"No protein data found. Check that protein data was imported.")

        pdata = self.copy() if return_copy else self # type: ignore[attr-defined]
        action = "Returning a copy of" if return_copy else "Filtered and modified"
        orig_prot_names = pdata.prot.var_names.copy()

        message_parts = []

        # 1. Filter by condition
        if condition is not None:
            formatted_condition = self._format_filter_query(condition, pdata.prot.var)
            if debug:
                print(f"Formatted condition: {formatted_condition}")
            filtered_proteins = pdata.prot.var[pdata.prot.var.eval(formatted_condition)]
            pdata.prot = pdata.prot[:, filtered_proteins.index]
            message_parts.append(f"condition: {condition}")

        # 2. Filter by accession list or gene names
        if accessions is not None:
            gene_map, _ = pdata.get_gene_maps(on='protein') # type: ignore[attr-defined]
            resolved = utils.resolve_accessions(
                pdata.prot,
                list(accessions),
                gene_map=gene_map,
                all_matches=all_matches,
                on_empty="return",
            )

            if not resolved:
                warnings.warn("No matching accessions found. No proteins will be retained.")
                pdata.prot = pdata.prot[:, []]
                message_parts.append("accessions: 0 matched")
            else:
                pdata.prot = pdata.prot[:, pdata.prot.var_names.isin(resolved)]
                message_parts.append(f"accessions: {len(resolved)} matched / {len(accessions)} requested")

        # 3. Valid genes
        if valid_genes:
            # A. Remove invalid gene entries
            var = pdata.prot.var

            mask_missing_gene = var["Genes"].isna() | (var["Genes"].astype(str).str.strip() == "")
            keep_mask = ~mask_missing_gene

            if debug:
                print(f"Missing genes: {mask_missing_gene.sum()}")
                missing_names = pdata.prot.var_names[mask_missing_gene]
                print(f"Examples of proteins missing names: {missing_names[:5].tolist()}")

            pdata.prot = pdata.prot[:, keep_mask].copy()
            message_parts.append(f"valid_genes: removed {int(mask_missing_gene.sum())} proteins with invalid gene names")            

            # B. Resolve duplicate gene names
            var = pdata.prot.var  # refresh after filtering
            var_genes = var["Genes"].astype(str).str.strip()
            gene_counts = var_genes.value_counts()
            duplicates = gene_counts[gene_counts > 1].index.tolist()

            if len(duplicates) > 0:
                if debug:
                    print(f"Found {len(duplicates)} duplicate gene names.")

                # Track how many times each duplicate has appeared
                seen = {}
                new_names = []
                for gene in var["Genes"]:
                    if gene in duplicates:
                        seen[gene] = seen.get(gene, 0) + 1
                        if seen[gene] > 1:
                            gene = f"{gene}-{seen[gene]}"
                    new_names.append(gene)

                # Assign back to var
                pdata.prot.var["Genes"] = new_names

                message_parts.append(f"valid_genes: resolved {len(duplicates)} duplicate gene names by appending numeric suffixes")
                if debug:
                    example_dupes = [d for d in duplicates[:5]]
                    print(f"Examples of duplicate genes resolved: {example_dupes}")

        # 4. Remove duplicate profiles
        if unique_profiles:
            X = pdata.prot.X.toarray() if issparse(pdata.prot.X) else pdata.prot.X
            df_X = pd.DataFrame(X.T, index=pdata.prot.var_names)

            all_nan = np.all(np.isnan(X), axis=0)
            all_zero = np.all(X == 0, axis=0)
            empty_mask = all_nan | all_zero

            duplicated_mask = df_X.duplicated(keep="first").values  # mark duplicates

            # Combine removal conditions
            remove_mask = duplicated_mask | empty_mask
            keep_mask = ~remove_mask

            # Counts for each type
            n_dup = int(duplicated_mask.sum())
            n_empty = int(empty_mask.sum())
            n_total = int(remove_mask.sum())

            if debug:
                dup_names = pdata.prot.var_names[duplicated_mask]
                print(f"Duplicate abundance profiles detected: {n_dup} proteins")
                if len(dup_names) > 0:
                    print(f"Examples of duplicates: {dup_names[:5].tolist()}")
                print(f"Empty (all-zero or all-NaN) proteins detected: {n_empty}")

            # Apply filter
            pdata.prot = pdata.prot[:, keep_mask].copy()

            # Add summary message
            message_parts.append(
                f"unique_profiles: removed {n_dup} duplicate and {n_empty} empty abundance profiles "
                f"({n_total} total)"
            )

        if not message_parts:
            # no filters were applied
            message = f"{format_log_prefix('user')} Filtering proteins [failed]: {action} protein data.\n    → No filters applied."
        else:
            # at least 1 filter applied
            # PEPTIDES: also filter out peptides that belonged only to the filtered proteins
            if pdata.pep is not None and pdata.rs is not None: # type: ignore[attr-defined]
                proteins_to_keep, peptides_to_keep, orig_prot_names, orig_pep_names = pdata._filter_sync_peptides_to_proteins(
                    orig_prot_names=orig_prot_names,
                    updated_prot=pdata.prot, 
                    debug=debug)

                # Apply filtered RS and update .prot and .pep using the helper
                rs_message = pdata._apply_rs_filter(
                    keep_proteins=proteins_to_keep,
                    keep_peptides=peptides_to_keep,
                    orig_prot_names=orig_prot_names,
                    orig_pep_names=orig_pep_names,
                    debug=False
                )
            else:
                rs_message = None

            # detect which filters were applied
            active_filters = []
            if condition is not None:
                active_filters.append("condition")
            if accessions is not None:
                active_filters.append("accession")
            if valid_genes:
                active_filters.append("valid genes")
            if unique_profiles:
                active_filters.append("unique profiles")

            # build the header, joining multiple filters nicely
            joined_filters = ", ".join(active_filters) if active_filters else "unspecified"
            message = (
                f"{format_log_prefix('user')} Filtering proteins [{joined_filters}]:\n"
                f"    {action} protein data with the following filters applied:"
            )

            for part in message_parts:
                formatted = part.replace(":", " —", 1)
                message += f"\n     🔸 {formatted}"

            # Protein and peptide counts summary
            message += f"\n    → Proteins kept: {pdata.prot.shape[1]}"
            if pdata.pep is not None:
                message += f"\n    → Peptides kept (linked): {pdata.pep.shape[1]}\n"
            if rs_message is not None:
                message += rs_message

        print(message)
        pdata._append_history(message) # type: ignore[attr-defined]
        pdata.update_summary(recompute=True) # type: ignore[attr-defined]
        return pdata if return_copy else None

    def filter_prot_found(self, group, min_ratio=None, min_count=None, on='protein', return_copy=True, verbose=True, match_any=False):
        """
        Filter proteins or peptides based on 'Found In' detection across samples or groups.

        This method filters features by checking whether they are found in a minimum number or proportion 
        of samples, either at the group level (e.g., biological condition) or based on individual files.

        Args:
            group (str or list of str): Group name(s) corresponding to 'Found In: {group} ratio' 
                (e.g., "HCT116_DMSO") or a list of filenames (e.g., ["F1", "F2"]). If this argument matches one or more `.obs` columns, the function automatically 
                interprets it as a class name, expands it to all class values, and annotates the
                necessary `'Found In:'` features.
            min_ratio (float, optional): Minimum proportion (0.0-1.0) of samples the feature must be 
                found in. Ignored for file-based filtering.
            min_count (int, optional): Minimum number of samples the feature must be found in. Alternative 
                to `min_ratio`. Ignored for file-based filtering.
            on (str): Feature level to filter: either "protein" or "peptide".
            return_copy (bool): If True, returns a filtered copy. If False, modifies in place.
            verbose (bool): If True, prints verbose summary information.
            match_any (bool): Defaults to False, for a AND search condition. If True, matches features found in any of the specified groups/files (i.e. union).

        Returns:
            pAnnData: A filtered pAnnData object if `return_copy=True`; otherwise, modifies in place and returns None.

        Note:
            - If `group` matches `.obs` column names, the method automatically annotates found 
              features by class before filtering.
            - For file-based filtering, use the file identifiers from `.prot.obs_names`.            

        Example:
            Filter proteins found in all "cellline" groups (e.g. Cellline A, and cellline B), with at least 2 samples each:
                ```python
                pdata_filtered = pdata.filter_prot_found(group="cellline", min_count=2, match_any=False)
                ```

            Filter proteins found in any "cellline" groups (e.g. Cellline A, and cellline B), as long as they meet a minimum ratio of 0.4:
                ```python
                pdata_filtered = pdata.filter_prot_found(group="cellline", min_ratio=0.4, match_any=True)
                ```                

            Filter proteins found in all three input files:
                ```python
                pdata.filter_prot_found(group=["F1", "F2", "F3"])
                ```

            Filter proteins found in files of a specific sub-group:
                ```python
                pdata.annotate_found(classes=['group','treatment'])
                pdata.filter_prot_found(group=["groupA_control", "groupB_treated"])
                ```

            If a single class column (e.g., `"cellline"`) is given, filter proteins based on each of its unique values (e.g. Line A, Line B):
                ```python
                pdata.filter_prot_found(group="cellline", min_ratio=0.5)
                ```
        """
        if not self._check_data(on): # type: ignore[attr-defined]
            return

        adata = self.prot if on == 'protein' else self.pep
        var = adata.var

        # Normalize group to list
        if isinstance(group, str):
            group = [group]
        if not isinstance(group, (list, tuple)):
            raise TypeError("`group` must be a string or list of strings.")

        # Auto-resolve obs columns passed instead of group values
        auto_value_msg = None
        if all(g in adata.obs.columns for g in group):
            if len(group) == 1:
                obs_col = group[0]
                expanded_groups = adata.obs[obs_col].unique().tolist()
            else:
                expanded_groups = (
                    adata.obs[group]
                    .astype(str)
                    .agg("_".join, axis=1)
                    .unique()
                    .tolist()
                )
            # auto-annotate found features by these obs columns
            self.annotate_found(classes=group, on=on, verbose=False)
            group = expanded_groups
            auto_value_msg = (
                f"{format_log_prefix('info', 2)} Found matching groups(s): {group}. "
                "Automatically annotating detection by group values."
            )

        # Determine filtering mode: group vs file or handle ambiguity/missing
        group_metrics = adata.uns.get(f"found_metrics_{on}")
        if group_metrics is not None:
            # .uns isn't subset by feature filters; align to current features
            group_metrics = group_metrics.reindex(adata.var_names)

        mode = None
        all_file_cols = all(f"Found In: {g}" in var.columns for g in group)
        all_group_cols = (
            group_metrics is not None
            and all((g, "count") in group_metrics.columns for g in group)
        )

        # case 1: Explicit ambiguity: both file- and group-level indicators exist
        is_ambiguous, annotated_files, annotated_groups = _detect_ambiguous_input(group, var, group_metrics)
        if is_ambiguous:
            raise ValueError(
                f"Ambiguous input: items in {group} include both file identifiers {annotated_files} "
                f"and group values {annotated_groups}.\n"
                "Please separate group-based and file-based filters into separate calls."
            )

        # case 2: Group-based mode
        elif all_group_cols:
            mode = "group"

        # case 3: File-based mode
        elif all_file_cols:
            mode = "file"

        # case 4: Mixed or unresolved case (fallback) 
        else:
            missing = []
            for g in group:
                group_missing = (
                    group_metrics is None
                    or (g, "count") not in group_metrics.columns
                    or (g, "ratio") not in group_metrics.columns
                )
                file_missing = f"Found In: {g}" not in var.columns

                if group_missing and file_missing:
                    missing.append(g)

            # Consistent, readable user message
            msg = [f"The following group(s)/file(s) could not be found: {missing or '—'}"]
            msg.append("→ If these are group names, make sure you ran:")
            msg.append(f"   pdata.annotate_found(classes={group})")
            msg.append("→ If these are file names, ensure 'Found In: <file>' columns exist.\n")
            raise ValueError("\n".join(msg))

        # ---------------
        # Apply filtering
        mask = np.ones(len(var), dtype=bool)

        if mode == "file":
            if match_any: # OR logic
                mask = np.zeros(len(var), dtype=bool)
                for g in group:
                    col = f"Found In: {g}"
                    mask |= var[col]
            else:  # AND logic (default)
                for g in group:
                    col = f"Found In: {g}"
                    mask &= var[col]

        elif mode == "group":
            if min_ratio is None and min_count is None:
                raise ValueError(
                    "You must specify either `min_ratio` or `min_count` when filtering by group."
                )

            if match_any: # ANY logic
                mask = np.zeros(len(var), dtype=bool)
                for g in group:
                    count_series = group_metrics[(g, "count")]
                    ratio_series = group_metrics[(g, "ratio")]

                    if min_ratio is not None:
                        this_mask = ratio_series >= min_ratio
                    else:
                        this_mask = count_series >= min_count

                    mask |= this_mask
            else:
                for g in group:
                    count_series = group_metrics[(g, "count")]
                    ratio_series = group_metrics[(g, "ratio")]

                    if min_ratio is not None:
                        this_mask = ratio_series >= min_ratio
                    else:
                        this_mask = count_series >= min_count

                    mask &= this_mask

        # Apply filtering
        filtered = self.copy() if return_copy else self # type: ignore[attr-defined], EditingMixin
        adata_filtered = adata[:, mask.values]

        if on == 'protein':
            filtered.prot = adata_filtered

            # Optional: filter peptides + rs as well
            if filtered.pep is not None and filtered.rs is not None:
                proteins_to_keep, peptides_to_keep, orig_prot_names, orig_pep_names = filtered._filter_sync_peptides_to_proteins(
                    orig_prot_names=adata.var_names,
                    updated_prot=filtered.prot,
                    debug=False
                )

                rs_message = filtered._apply_rs_filter(
                    keep_proteins=proteins_to_keep,
                    keep_peptides=peptides_to_keep,
                    orig_prot_names=orig_prot_names,
                    orig_pep_names=orig_pep_names,
                    debug=False
                )
            else:
                rs_message = None

        else:
            filtered.pep = adata_filtered
            # Optionally, we could also remove proteins no longer linked to any peptides,
            # but that's less common and we can leave it out unless requested.

        if verbose:
            n_kept = int(mask.sum())
            n_total = len(mask)
            n_dropped = n_total - n_kept

            logic = "any" if match_any else "all"
            mode_str = "Group-mode" if mode == "group" else "File-mode"
            logic_tag = "ANY" if match_any else "ALL"
            return_copy_str = ("Returning a copy of" if return_copy else "Filtered and modified")

            # Header
            print(f"{format_log_prefix('user')} Filtering {on}s [Found|{mode_str}|{logic_tag}]:")

            # Auto-annotation info (if applicable)
            if auto_value_msg:
                print(auto_value_msg)

            # Main action block
            print(f"    {return_copy_str} {on} data based on detection thresholds:")

            if mode == "group":
                # Groups requested
                print(f"{format_log_prefix('filter_conditions')}Groups requested: {group}")

                # Threshold line
                if min_ratio is not None:
                    print(f"{format_log_prefix('filter_conditions')}Minimum ratio: {min_ratio}")
                if min_count is not None:
                    print(f"{format_log_prefix('filter_conditions')}Minimum count: {min_count}")

                # Logic explanation
                print(
                    f"{format_log_prefix('filter_conditions')}Logic: {logic} "
                    f"({on} must be detected in {'≥1' if match_any else 'all'} group(s))"
                )

            else:  # file mode
                print(f"{format_log_prefix('filter_conditions')}Files requested: {group}")
                print(
                    f"{format_log_prefix('filter_conditions')}Logic: {logic} "
                    f"({on} must be detected in {'≥1' if match_any else 'all'} file(s))"
                )

            # Footer: kept/dropped
            label = "Proteins" if on == "protein" else "Peptides"
            print(f"    → {label} kept: {n_kept}, {label} dropped: {n_dropped}")

            # RS summary (if any)
            if rs_message is not None and on == "protein":
                print(rs_message)

            print(f"")

        criteria_str = (
            f"min_ratio={min_ratio}"
            if mode == "group" and min_ratio is not None
            else f"min_count={min_count}"
            if mode == "group"
            else ("ANY files" if match_any else "ALL files")
        )
        logic_str = "ANY" if match_any else "ALL"
        filtered._append_history(  # type: ignore[attr-defined], HistoryMixin
            f"{on}: Filtered by detection in {mode} group(s) {group} using {criteria_str} (match_{logic_str})."
        )
        filtered.update_summary(recompute=True) # type: ignore[attr-defined], SummaryMixin

        return filtered if return_copy else None

    def filter_prot_significant(self, group=None, min_ratio=None, min_count=None, fdr_threshold=0.01, return_copy=True, verbose=True, match_any=True):
        """
        Filter proteins based on significance across samples or groups using FDR thresholds.

        This method filters proteins by checking whether they are significant (e.g. PG.Q.Value < 0.01)
        in a minimum number or proportion of samples, either per file or grouped.

        Args:
            group (str, list, or None): Group name(s) (e.g., sample classes or filenames). If None, uses all files.
            min_ratio (float, optional): Minimum proportion of samples to be significant.
            min_count (int, optional): Minimum number of samples to be significant.
            fdr_threshold (float): Significance threshold (default = 0.01).
            return_copy (bool): Whether to return a filtered copy or modify in-place.
            verbose (bool): Whether to print summary.
            match_any (bool): If True, retain proteins significant in *any* group/file (OR logic). If False, require *all* groups/files to be significant (AND logic).

        Returns:
            pAnnData or None: Filtered object (if `return_copy=True`) or modifies in-place.

        Example:
            Filter proteins significant by their global significance (e.g. PD-based imports):
                ```python
                pdata.filter_prot_significant()
                ```

            Filter proteins significant in the "cellline" group containing e.g. "groupA" and "groupB" groups, FDR of 0.01 (default):
                ```python
                pdata.filter_prot_significant(group=["cellline"], min_count=2)
                ```

            Filter proteins significant in all three input files:
                ```python
                pdata.filter_prot_significant(group=["F1", "F2", "F3"])
                ```

            Filter proteins significant in files of a specific sub-group:
                ```python
                pdata.annotate_significant(classes=['group','treatment'])
                pdata.filter_prot_significant(group=["groupA_control", "groupB_treated"])            
                ```

        Todo:
            Implement peptide then protein filter
        """
        if not self._check_data("protein"): # type: ignore[attr-defined]
            return

        adata = self.prot 
        var = adata.var

        # Detect per-sample significance layer.
        # anndata >= 0.13 stores .X as layers[None]; skip non-string keys.
        has_protein_level_significance = any(
            isinstance(k, str) and (k.lower().endswith("_qval") or k.lower().endswith("_fdr"))
            for k in adata.layers.keys()
        )

        # --- Handle missing significance data entirely ---
        if not has_protein_level_significance and "Global_Q_value" not in adata.var.columns:
            raise ValueError(
                "No per-sample layer (e.g., *_qval) or global significance column ('Global_Q_value') "
                "found in .prot. Please ensure your data includes q-values or run annotate_significant()."
            )

        # --- 1️⃣ Global fallback mode (e.g. PD-based imports) ---
        if not has_protein_level_significance and "Global_Q_value" in adata.var.columns:
            if group is not None:
                raise ValueError(
                    f"Cannot filter by group {group}: per-sample significance data missing "
                    "and only global q-values available."
                )

            global_mask = adata.var["Global_Q_value"] < fdr_threshold

            n_total = len(global_mask)
            n_kept = int(global_mask.sum())
            n_dropped = n_total - n_kept

            filtered = self.copy() if return_copy else self
            filtered.prot = adata[:, global_mask]

            if filtered.pep is not None and filtered.rs is not None:
                proteins_to_keep, peptides_to_keep, orig_prot_names, orig_pep_names = filtered._filter_sync_peptides_to_proteins(
                    orig_prot_names=adata.var_names, updated_prot=filtered.prot, debug=verbose
                )
                rs_message = filtered._apply_rs_filter(
                    keep_proteins=proteins_to_keep,
                    keep_peptides=peptides_to_keep,
                    orig_prot_names=orig_prot_names,
                    orig_pep_names=orig_pep_names,
                    debug=False,
                )

            filtered.update_summary(recompute=True)
            filtered._append_history(
                f"Filtered by global significance (Global_Q_value < {fdr_threshold}); "
                f"{n_kept}/{n_total} proteins retained."
            )

            if verbose:
                print(f"{format_log_prefix('user')} Filtering proteins by significance [Global-mode]:")
                print(f"{format_log_prefix('info', 2)} Using global protein-level q-values (no per-sample significance available).")
                return_copy_str = "Returning a copy of" if return_copy else "Filtered and modified"
                print(f"    {return_copy_str} protein data based on significance thresholds:")
                print(f"{format_log_prefix('filter_conditions')}Files requested: All")
                print(f"{format_log_prefix('filter_conditions')}FDR threshold: {fdr_threshold}")
                print(f"    → Proteins kept: {n_kept}, Proteins dropped: {n_dropped}\n")

            return filtered if return_copy else None

        # --- 2️⃣ Per-sample significance data available ---
        no_group_msg = None
        auto_group_msg = None
        auto_value_msg = None

        if group is None:
            group_list = list(adata.obs_names)
            if verbose:
                no_group_msg = f"{format_log_prefix('info', 2)} No group provided. Defaulting to sample-level significance filtering."
        else:
            group_list = [group] if isinstance(group, str) else group

        # Ensure annotations exist or auto-generate
        missing_cols = [f"Significant In: {g}" for g in group_list]
        if all(col in var.columns for col in missing_cols):
            # Case A: user passed actual group values, already annotated
            pass
        else:
            # Case B: need to resolve automatically
            if all(g in adata.obs.columns for g in group_list):
                # User passed obs column(s)
                if len(group_list) == 1:
                    obs_col = group_list[0]
                    expanded_groups = adata.obs[obs_col].unique().tolist()
                else:
                    expanded_groups = (
                        adata.obs[group_list].astype(str)
                            .agg("_".join, axis=1)
                            .unique()
                            .tolist()
                    )
                self.annotate_significant(classes=group_list,
                                        fdr_threshold=fdr_threshold,
                                        on="protein", verbose=False)
                group_list = expanded_groups
                auto_group_msg = f"{format_log_prefix('info', 2)} Found matching obs column '{group_list}'. Automatically annotating significance by group: {group_list} using FDR threshold {fdr_threshold}."

            else:
                # User passed group values, but not annotated yet
                found_obs_col = None
                for obs_col in adata.obs.columns:
                    if set(group_list).issubset(set(adata.obs[obs_col].unique())):
                        found_obs_col = obs_col
                        break

                if found_obs_col is not None:
                    self.annotate_significant(classes=[found_obs_col],
                                            fdr_threshold=fdr_threshold,
                                            on="protein", indent=2, verbose=False)
                    auto_value_msg = (f"{format_log_prefix('info', 2)} Found matching obs column '{found_obs_col}'"
                    f"for groups {group_list}. Automatically annotating significant features by group {found_obs_col} "
                    f"using FDR threshold {fdr_threshold}.")    
                else:
                    raise ValueError(
                        f"Could not find existing significance annotations for groups {group_list}. "
                        "Please either pass valid obs column(s), provide values from a valid `.obs` column or run `annotate_significant()` first."
                    )

        # --- 3️⃣ Mode detection and ambiguity handling ---
        metrics_key = "significance_metrics_protein"
        metrics_df = adata.uns.get(metrics_key, pd.DataFrame())
        if not metrics_df.empty and "Global" not in metrics_df.index:
            # .uns isn't subset by feature filters; align to current features
            metrics_df = metrics_df.reindex(adata.var_names)

        is_ambiguous, annotated_files, annotated_groups = _detect_ambiguous_input(group_list, var, metrics_df)
        if is_ambiguous:
            raise ValueError(
                f"Ambiguous input: items in {group_list} include both file identifiers {annotated_files} "
                f"and group values {annotated_groups}.\n"
                "Please separate group-based and file-based filters into separate calls."
            )

        all_group_cols = (
            metrics_df is not None
            and all((g, "count") in metrics_df.columns for g in group_list)
        )
        all_file_cols = all(f"Significant In: {g}" in var.columns for g in group_list)
        mode = "group" if all_group_cols else "file"

        # Build filtering mask
        mask = np.zeros(len(var), dtype=bool) if match_any else np.ones(len(var), dtype=bool)

        if mode == "group":
            if min_ratio is None and min_count is None:
                raise ValueError("Specify `min_ratio` or `min_count` for group-based filtering.")
            for g in group_list:
                count = metrics_df[(g, "count")]
                ratio = metrics_df[(g, "ratio")]
                this_mask = ratio >= min_ratio if min_ratio is not None else count >= min_count
                mask = mask | this_mask if match_any else mask & this_mask
        else:  # file mode
            for g in group_list:
                col = f"Significant In: {g}"
                this_mask = var[col].values
                mask = mask | this_mask if match_any else mask & this_mask

        # filter then rs sync
        filtered = self.copy() if return_copy else self
        filtered.prot = adata[:, mask]

        # Sync peptides and RS
        if filtered.pep is not None and filtered.rs is not None:
            proteins_to_keep, peptides_to_keep, orig_prot_names, orig_pep_names = filtered._filter_sync_peptides_to_proteins(
                orig_prot_names=adata.var_names, updated_prot=filtered.prot, debug=False
            )
            rs_message = filtered._apply_rs_filter(
                keep_proteins=proteins_to_keep,
                keep_peptides=peptides_to_keep,
                orig_prot_names=orig_prot_names,
                orig_pep_names=orig_pep_names,
                debug=False
            )
        else:
            rs_message = None

        filtered.update_summary(recompute=True)
        filtered._append_history(
            f"Filtered by significance (FDR < {fdr_threshold}) in group(s): {group_list}, "
            f"using min_ratio={min_ratio} / min_count={min_count}, match_any={match_any}"
        )

        if verbose:
            logic = "any" if match_any else "all"
            mode_str = "Group-mode" if mode == "group" else "File-mode"

            print(f"{format_log_prefix('user')} Filtering proteins [Significance|{mode_str}]:")

            if no_group_msg:
                print(no_group_msg)
            if auto_group_msg:
                print(auto_group_msg)
            if auto_value_msg:
                print(auto_value_msg)

            return_copy_str = "Returning a copy of" if return_copy else "Filtered and modified"
            print(f"    {return_copy_str} protein data based on significance thresholds:")

            if mode == "group":
                # Case A: obs column(s) expanded → show expanded_groups and add note
                if auto_group_msg:
                    group_note = f" (all values of obs column(s))"
                    print(f"{format_log_prefix('filter_conditions')}Groups requested: {group_list}{group_note}")
                else:
                    print(f"{format_log_prefix('filter_conditions')}Groups requested: {group_list}")
                print(f"{format_log_prefix('filter_conditions')}FDR threshold: {fdr_threshold}")
                if min_ratio is not None:
                    print(f"{format_log_prefix('filter_conditions')}Minimum ratio: {min_ratio} (match_{logic} = {match_any})")
                if min_count is not None:
                    print(f"{format_log_prefix('filter_conditions')}Minimum count: {min_count} (match_{logic} = {match_any})")
            else:
                print(f"{format_log_prefix('filter_conditions')}Files requested: All")
                print(f"{format_log_prefix('filter_conditions')}FDR threshold: {fdr_threshold}")
                print(f"{format_log_prefix('filter_conditions')}Logic: {logic} "
                    f"(protein must be significant in {'≥1' if match_any else 'all'} file(s))")

            n_kept = int(mask.sum())
            n_total = len(mask)
            n_dropped = n_total - n_kept
            print(f"    → Proteins kept: {n_kept}, Proteins dropped: {n_dropped}")

            if rs_message is not None:
                print(rs_message)

            print(f"")

        return filtered if return_copy else None

    def _filter_sync_peptides_to_proteins(self, orig_prot_names, updated_prot, debug=None):
        """
        Helper function to filter peptides based on the updated protein list.

        This method determines which peptides to retain after protein-level filtering,
        and returns the necessary inputs for `_apply_rs_filter`.

        Args:
            orig_prot_names (array-like): Protein names before filtering (RS row order). `.pep` and `.rs`
                must not be filtered yet.
            updated_prot (AnnData): Updated protein AnnData object to filter against.
            debug (bool, optional): If True, prints debugging information.

        Returns:
            tuple: Inputs needed for downstream `_apply_rs_filter` operation.
        """
        if debug:
            print(f"{format_log_prefix('info')} Applying RS-based peptide sync-up on peptides after protein filtering...")

        # .rs and .pep are still unfiltered here; .prot may already be filtered in place
        rs = self.rs
        orig_prot_names = np.array(orig_prot_names)
        orig_pep_names = np.array(self.pep.var_names)
        # Determine which protein rows to keep in RS
        proteins_to_keep=updated_prot.var_names
        keep_set = set(proteins_to_keep)
        prot_mask = np.fromiter((p in keep_set for p in orig_prot_names), dtype=bool)
        rs_filtered = rs[prot_mask, :]
        # Keep peptides that are still linked to ≥1 protein
        pep_mask = np.array(rs_filtered.sum(axis=0)).ravel() > 0
        peptides_to_keep = orig_pep_names[pep_mask]

        return proteins_to_keep, peptides_to_keep, orig_prot_names, orig_pep_names

    def filter_sample(
        self,
        values=None,
        exact_cases=False,
        condition=None,
        file_list=None,
        exclude_file_list=None,
        min_prot=None,
        poi=None,
        min_abundance=None,
        max_abundance=None,
        require_detected=True,
        match_any=False,
        layer="X",
        on="protein",
        cleanup=True,
        return_copy=True,
        debug=False,
        query_mode=False,
    ):
        """
        Filter samples in a pAnnData object based on categorical, numeric, or identifier-based criteria.

        You must specify **exactly one** of the following:

        - `values`: Dictionary or list of dictionaries specifying class-based filters (e.g., treatment, cellline).
        - `condition`: A string condition evaluated against summary-level numeric metadata (e.g., protein count).
        - `file_list`: List of sample or file names to retain.
        - `exclude_file_list`: List of sample or file names to exclude.
        - `min_prot`: Minimum protein count per sample (shortcut for a summary condition).
        - `poi`: Protein or peptide of interest; keep samples whose POI abundance meets ``min_abundance``
          and/or ``max_abundance`` (see ``_filter_sample_poi``).

        Args:
            values (dict or list of dict, optional): Categorical metadata filter. Matches rows in `.summary` or `.obs` with those field values.
                Example: `{'treatment': 'kd', 'cellline': 'A'}`.
            exact_cases (bool): If True, uses exact match across all class values when `values` is a list of dicts.
            condition (str, optional): Logical condition string referencing summary columns. This should reference columns in `pdata.summary`.
                Example: `"protein_count > 1000"`.
            file_list (list of str, optional): List of sample names or file identifiers to keep. Filters to only those samples (must match obs_names).
            exclude_file_list (list of str, optional): Similar to `file_list`, but excludes the specified files/samples instead of keeping them.
            min_prot (int, optional): Minimum number of proteins required in a sample to retain it.
            poi (str, optional): Gene name, accession, or peptide ID whose abundance is used to select samples.
            min_abundance (float, optional): Minimum raw abundance for the POI in a sample.
            max_abundance (float, optional): Maximum raw abundance for the POI in a sample.
            require_detected (bool): If True (default), undetected (NaN/zero) feature values are ignored;
                samples with no detected POI features fail. If False, undetected values are ignored and
                samples pass when nothing is detected.
            match_any (bool): When ``poi`` resolves to multiple isoforms/peptides, if False (default) all
                detected matches must pass the threshold; if True, any one detected match passing is enough.
            layer (str): Data layer for abundance values (default ``"X"``).
            on (str): ``"protein"`` or ``"peptide"``.
            cleanup (bool): If True (default), remove proteins that become all-NaN or all-zero after sample filtering and synchronize RS/peptide matrices. Set to False to retain all proteins for consistent feature alignment (e.g. during DE analysis).
            return_copy (bool): If True, returns a filtered pAnnData object; otherwise modifies in place.
            debug (bool): If True, prints query strings and filter summaries.
            query_mode (bool): If True, interprets `values` or `condition` as a raw pandas-style `.query()` string and evaluates it directly on `.obs` or `.summary` respectively.

        Returns:
            pAnnData: Filtered pAnnData object if `return_copy=True`; otherwise, modifies in place and returns None.

        Raises:
            ValueError: If more than one or none of the filter mode arguments (`values`, `condition`, `file_list`, `exclude_file_list`, `min_prot`, `poi`) is specified.

        Example:
            Filter by metadata values:
                ```python
                pdata.filter_sample(values={'treatment': 'kd', 'cellline': 'A'})
                ```

            Filter with multiple exact matching cases:
                ```python
                pdata.filter_sample(
                    values=[
                        {'treatment': 'kd', 'cellline': 'A'},
                        {'treatment': 'sc', 'cellline': 'B'}
                    ],
                    exact_cases=True
                )
                ```

            Filter by numeric condition on summary:
                ```python
                pdata.filter_sample(condition="protein_count > 1000")
                ```

            Filter samples with fewer than 1000 proteins:
                ```python
                pdata.filter_sample(min_prot=1000)
                ```

            Keep specific samples by name:
                ```python
                pdata.filter_sample(file_list=['Sample_001', 'Sample_007'])
                ```

            Exclude specific files from the dataset:
                ```python
                pdata.filter_sample(exclude_file_list=['Sample_001', 'Sample_007'])
                ```

            Filter control samples where a POI exceeds an abundance threshold (two-step):
                ```python
                control = pdata.filter_sample(values={'treatment': 'control'})
                high_poi = control.filter_sample(poi='ProteinA', min_abundance=1e4)
                ```

            For advanced usage using query mode, see the note below.

            !!! note "Advanced Usage"
                To enable **advanced filtering**, set `query_mode=True` to evaluate raw pandas-style queries:

                - Query `.obs` metadata:
                    ```python
                    pdata.filter_sample(values="cellline == 'AS' and treatment == 'kd'", query_mode=True)
                    ```

                - Query `.summary` metadata:
                    ```python
                    pdata.filter_sample(condition="protein_count > 1000 and missing_pct < 0.2", query_mode=True)
                    ```
        """
        # Ensure exactly one of the filter modes is specified
        provided = [values, condition, file_list, min_prot, exclude_file_list, poi]
        if sum(arg is not None for arg in provided) != 1:
            raise ValueError(
                "Invalid filter input. You must specify exactly one of the following keyword arguments:\n"
                "- `values=...` for categorical metadata filtering,\n"
                "- `condition=...` for summary-level condition filtering,\n"
                "- `min_prot=...` to filter by minimum protein count,\n"
                "- `file_list=...` to filter by sample IDs,\n"
                "- `exclude_file_list=...` to exclude specific sample IDs,\n"
                "- `poi=...` to filter by protein/peptide abundance.\n\n"
                "Examples:\n"
                "  pdata.filter_sample(condition='protein_quant > 0.2')\n"
                "  pdata.filter_sample(poi='GAPDH', min_abundance=1e4)"
            )

        if poi is not None:
            if min_abundance is None and max_abundance is None:
                raise ValueError(
                    "When filtering by `poi`, specify at least one of `min_abundance` or `max_abundance`."
                )
            return self._filter_sample_poi(
                poi=poi,
                min_abundance=min_abundance,
                max_abundance=max_abundance,
                require_detected=require_detected,
                match_any=match_any,
                layer=layer,
                on=on,
                cleanup=cleanup,
                return_copy=return_copy,
                debug=debug,
            )

        if min_prot is not None:
            condition = f"protein_count >= {min_prot}"

        if values is not None and not query_mode:
            return self._filter_sample_values(
                values=values,
                exact_cases=exact_cases,
                debug=debug,
                return_copy=return_copy, 
                cleanup=cleanup
            )

        if (condition is not None or file_list is not None or exclude_file_list is not None) and not query_mode:
            return self._filter_sample_condition(
                condition=condition,
                file_list=file_list,
                exclude_file_list=exclude_file_list,
                return_copy=return_copy,
                debug=debug, 
                cleanup=cleanup
            )

        if values is not None and query_mode:
            return self._filter_sample_query(query_string=values, source='obs', return_copy=return_copy, debug=debug, cleanup=cleanup)

        if condition is not None and query_mode:
            return self._filter_sample_query(query_string=condition, source='summary', return_copy=return_copy, debug=debug, cleanup=cleanup)

    def _filter_sample_poi(
        self,
        poi,
        min_abundance=None,
        max_abundance=None,
        require_detected=True,
        match_any=False,
        layer="X",
        on="protein",
        cleanup=True,
        return_copy=True,
        debug=False,
    ):
        """
        Filter samples by raw abundance thresholds for a protein or peptide of interest.

        See ``filter_sample(poi=...)`` for parameter documentation.
        """
        on_user = on.lower()
        feature_kind = "peptides" if on_user in ("peptide", "pep") else "proteins"
        notes: list[str] = []

        if on_user in ("peptide", "pep"):
            if self.pep is None:  # type: ignore[attr-defined]
                raise ValueError("Peptide data (.pep) is not available.")
            features = utils.resolve_peptides(
                self, [poi], all_matches=True, on_empty="return", quiet=True
            )  # type: ignore[arg-type]
        else:
            if not self._check_data("protein"):  # type: ignore[attr-defined]
                raise ValueError("No protein data found.")
            adata = self.prot  # type: ignore[attr-defined]
            features = utils.resolve_accessions(
                adata, [poi], all_matches=True, on_empty="return", quiet=True
            )

        if features and len(features) > 1:
            notes.append(
                f"{format_log_prefix('info')} "
                f"'{poi}' resolved to multiple {feature_kind}: {features}"
            )

        pdata = self.copy() if return_copy else self  # type: ignore[attr-defined], EditingMixin
        action = "Returning a copy of" if return_copy else "Filtered and modified"
        ref_adata = pdata.prot if pdata.prot is not None else pdata.pep  # type: ignore[attr-defined]
        orig_sample_count = len(ref_adata.obs)

        if not features:
            notes.append(
                f"{format_log_prefix('warn')} POI '{poi}' did not resolve to any "
                f"{feature_kind}. No samples retained."
            )
            index_filter = []
        else:
            adata = getattr(pdata, "pep" if on_user in ("peptide", "pep") else "prot")
            missing = [f for f in features if f not in adata.var_names]
            if missing:
                notes.append(
                    f"{format_log_prefix('warn')} POI features not in .var_names (skipped): {missing}"
                )
            features = [f for f in features if f in adata.var_names]
            if not features:
                index_filter = []
            else:
                X = adata[:, features].layers[layer] if layer in adata.layers else adata[:, features].X
                if hasattr(X, "toarray"):
                    X = X.toarray()
                else:
                    X = np.asarray(X)

                keep_mask = np.zeros(X.shape[0], dtype=bool)
                for i in range(X.shape[0]):
                    evaluated = []
                    for j in range(X.shape[1]):
                        val = X[i, j]
                        if np.isnan(val) or val <= 0:
                            continue
                        passes = True
                        if min_abundance is not None and val < min_abundance:
                            passes = False
                        if max_abundance is not None and val > max_abundance:
                            passes = False
                        evaluated.append(passes)

                    if not evaluated:
                        keep_mask[i] = not require_detected
                    elif match_any:
                        keep_mask[i] = any(evaluated)
                    else:
                        keep_mask[i] = all(evaluated)

                index_filter = adata.obs_names[keep_mask].tolist()

        if debug:
            print(f"POI features: {features}")
            print(f"Samples kept: {len(index_filter)} / {orig_sample_count}")

        if pdata.prot is not None:
            pdata.prot = pdata.prot[pdata.prot.obs_names.isin(index_filter)]  # type: ignore[attr-defined]
        if pdata.pep is not None:
            pdata.pep = pdata.pep[pdata.pep.obs_names.isin(index_filter)]  # type: ignore[attr-defined]

        if cleanup:
            cleanup_message = pdata._cleanup_proteins_after_sample_filter(verbose=True)  # type: ignore[attr-defined]
        else:
            cleanup_message = None
        pdata.update_summary(recompute=False, verbose=False)  # type: ignore[attr-defined], SummaryMixin

        log_prefix = format_log_prefix("user")
        logic = "OR" if match_any else "AND"
        threshold_parts = []
        if min_abundance is not None:
            threshold_parts.append(f"min_abundance={min_abundance}")
        if max_abundance is not None:
            threshold_parts.append(f"max_abundance={max_abundance}")
        threshold_str = ", ".join(threshold_parts)

        if len(index_filter) == 0:
            message = (
                f"{log_prefix} Filtering samples [poi]:\n"
                f"    → No matching samples found.\n"
                f"{format_log_prefix('filter_conditions')}POI: {poi} ({on}, {len(features)} feature(s))\n"
                f"{format_log_prefix('filter_conditions')}Threshold: {threshold_str}\n"
                f"    → Samples kept: 0, Samples dropped: {orig_sample_count}"
            )
        else:
            message = (
                f"{log_prefix} Filtering samples [poi]:\n"
                f"    {action} sample data based on POI abundance ({logic} across detected matches):\n"
                f"{format_log_prefix('filter_conditions')}POI: {poi} ({on}, {len(features)} feature(s))\n"
                f"{format_log_prefix('filter_conditions')}Threshold: {threshold_str}\n"
                f"{format_log_prefix('filter_conditions')}require_detected={require_detected}, match_any={match_any}\n"
            )
            message += (
                f"    → Samples kept: {len(index_filter)}, "
                f"Samples dropped: {orig_sample_count - len(index_filter)}\n"
            )
            if pdata.prot is not None:
                message += f"    → Proteins kept: {len(pdata.prot.var)}\n"

        if notes:
            message += "\n".join(notes) + "\n"
        if cleanup_message:
            message += cleanup_message + "\n"

        print(message)
        pdata._append_history(message)  # type: ignore[attr-defined], HistoryMixin
        return pdata if return_copy else None

    def _filter_sample_condition(self, condition = None, return_copy = True, file_list=None, exclude_file_list=None, cleanup=True, debug=False):
        """
        Filter samples based on numeric metadata conditions or a list of sample identifiers.

        This internal method supports two modes:

        - A string `condition` evaluated against `.summary` (e.g., `"protein_count > 1000"`).
        - A `file_list` of sample names or identifiers to retain (e.g., filenames or `.obs_names`).

        Args:
            condition (str, optional): Logical condition string referencing columns in `.summary`.
            file_list (list of str, optional): List of sample identifiers to keep.
            exclude_file_list (list of str, optional): Same as file_list, but excludes specified sample identifiers.
            cleanup (bool): If True (default), remove proteins that become all-NaN or all-zero
                after sample filtering and synchronize RS/peptide matrices. Set to False to
                retain all proteins for consistent feature alignment (e.g. during DE analysis).
            return_copy (bool): If True, returns a filtered pAnnData object. If False, modifies in place.
            debug (bool): If True, prints the query string or filtering summary.

        Returns:
            pAnnData: Filtered pAnnData object if `return_copy=True`; otherwise, modifies in place and returns None.

        Note:
            This method is intended for internal use by `filter_sample()`. For general-purpose filtering, 
            use `filter_sample()` with `condition=...` or `file_list=...`.

        Example:
            Filter samples with more than 1000 proteins:
                ```python
                pdata.filter_sample_condition(condition="protein_count > 1000")
                ```

            Keep only specific sample files:
                ```python
                pdata.filter_sample_condition(file_list=['fileA', 'fileB'])
                ```

            Exclude specific files from the dataset:
                ```python
                pdata.filter_sample(exclude_file_list=['Sample_001', 'Sample_007'])
                ```
        """
        if not self._has_data(): # type: ignore[attr-defined], ValidationMixin
            pass

        if self._summary is None: # type: ignore[attr-defined]
            self.update_summary(recompute=True) # type: ignore[attr-defined], SummaryMixin

        if file_list is not None and exclude_file_list is not None:
            raise ValueError(
                "You cannot specify both `file_list` and `exclude_file_list` simultaneously.\n"
                "Please use only one mode per call:\n"
                "  • `file_list=[...]` to keep only these samples, or\n"
                "  • `exclude_file_list=[...]` to remove these samples.\n"
                "If you need both operations, call `filter_sample()` twice in sequence."
            )

        # Determine whether to operate on a copy or in-place
        pdata = self.copy() if return_copy else self # type: ignore[attr-defined], EditingMixin
        action = "Returning a copy of" if return_copy else "Filtered and modified"

        orig_sample_count = len(pdata.prot.obs)

        if debug:
            print("self.prot id:", id(self.prot))
            print("pdata.prot id:", id(pdata.prot))
            print("Length of pdata.prot.obs_names:", len(pdata.prot.obs_names))

        # Determine sample indices to retain
        index_filter = None
        missing = []

        if condition is not None:
            formatted_condition = self._format_filter_query(condition, pdata._summary)  # type: ignore[attr-defined]
            if debug:
                print(formatted_condition)
            index_filter = pdata._summary[pdata._summary.eval(formatted_condition)].index
        elif file_list is not None or exclude_file_list is not None:
            all_samples = set(pdata.prot.obs_names)

            if file_list is not None:
                requested = set(file_list)
                missing = list(requested - all_samples)
                index_filter = list(all_samples.intersection(requested))
                mode_str = "including"
                exclude_mode = False

            else:  # exclude_file_list is not None
                requested = set(exclude_file_list)
                missing = list(requested - all_samples)
                index_filter = list(all_samples - requested)
                mode_str = "excluding"
                exclude_mode = True

            if missing:
                warnings.warn(f"Some sample IDs not found: {missing}")

        else:
            # No filtering applied
            message = "No filtering applied. Returning original data."
            return pdata if return_copy else None

        if debug:
            print(f"Length of index_filter: {len(index_filter)}")
            print(f"Length of pdata.prot.obs_names before filter: {len(pdata.prot.obs_names)}")
            print(f"Number of shared samples: {len(pdata.prot.obs_names.intersection(index_filter))}")

        # Filter out selected samples from prot and pep
        if pdata.prot is not None:
            pdata.prot = pdata.prot[pdata.prot.obs.index.isin(index_filter)]

        if pdata.pep is not None:
            pdata.pep = pdata.pep[pdata.pep.obs.index.isin(index_filter)]

        if cleanup:
            cleanup_message = pdata._cleanup_proteins_after_sample_filter(verbose=True)
        else:
            cleanup_message = None
        pdata.update_summary(recompute=False, verbose=False) # type: ignore[attr-defined], SummaryMixin

        print(f"Length of pdata.prot.obs_names after filter: {len(pdata.prot.obs_names)}") if debug else None

        # Construct formatted message
        filter_type = "condition" if condition else "file list" if (file_list or exclude_file_list) else "none"
        log_prefix = format_log_prefix("user")

        if len(index_filter) == 0:
            message = f"{log_prefix} Filtering samples [{filter_type}]:\n    → No matching samples found. No filtering applied."
            if cleanup_message:
                message += "\n" + cleanup_message
        else:
            message = f"{log_prefix} Filtering samples [{filter_type}]:\n"
            message += f"    {action} sample data based on {filter_type}:\n"
            if condition:
                message += f"{format_log_prefix('filter_conditions')}Condition: {condition}\n"
            elif file_list or exclude_file_list:
                flist = file_list if file_list is not None else exclude_file_list
                message += f"{format_log_prefix('filter_conditions')}Files requested ({mode_str}): {len(flist)}\n"
                if missing:
                    message += f"{format_log_prefix('filter_conditions')}Missing samples ignored: {len(missing)}\n"

            message += cleanup_message + "\n" if cleanup_message else ""
            message += f"    → Samples kept: {len(pdata.prot.obs)}, Samples dropped: {orig_sample_count - len(pdata.prot.obs)}"
            message += f"\n    → Proteins kept: {len(pdata.prot.var)}\n"

        # Logging and history updates
        print(message)
        pdata._append_history(message) # type: ignore[attr-defined], HistoryMixin

        return pdata if return_copy else None

    def _filter_sample_values(self, values, exact_cases, cleanup=True, verbose=True, debug=False, return_copy=True):
        """
        Filter samples using dictionary-style categorical matching.

        This internal method filters samples based on class-like annotations (e.g., treatment, cellline),
        using either loose field-wise filtering or strict combination matching. It supports:

        - Single dictionary (e.g., `{'cellline': 'A'}`)
        - List of dictionaries (e.g., `[{...}, {...}]` for multiple matching cases)
        - Exact matching (`exact_cases=True`) across all key-value pairs

        Args:
            values (dict or list of dict): Filtering conditions.
                - If `exact_cases=False`: A single dictionary with field: list of values. 
                Applies OR logic within fields and AND logic across fields.
                - If `exact_cases=True`: A list of dictionaries, each representing an exact combination of field values.
            exact_cases (bool): If True, performs exact match filtering using the provided list of dictionaries.
            cleanup (bool): If True (default), remove proteins that become all-NaN or all-zero
                after sample filtering and synchronize RS/peptide matrices. Set to False to
                retain all proteins for consistent feature alignment (e.g. during DE analysis).
            verbose (bool): If True, prints a summary of the filtering result.
            debug (bool): If True, prints internal queries and matching logic.
            return_copy (bool): If True, returns a filtered copy. Otherwise modifies in place.

        Returns:
            pAnnData: Filtered view of the input AnnData object if `return_copy=True`; otherwise modifies in place and returns None.

        Note:
            This method is used internally by `filter_sample()`. For general use, call `filter_sample()` directly.

        Example:
            Loose field-wise match (OR within fields, AND across fields):
                ```python
                pdata.filter_sample_values(values={'treatment': ['kd', 'sc'], 'cellline': 'A'})
                ```

            Exact combination matching:
                ```python
                pdata.filter_sample_values(
                    values=[
                        {'treatment': 'kd', 'cellline': 'A'},
                        {'treatment': 'sc', 'cellline': 'B'}
                    ],
                    exact_cases=True
                )
                ```
        """

        pdata = self.copy() if return_copy else self # type: ignore[attr-defined], EditingMixin
        obs_keys = pdata.summary.columns # type: ignore[attr-defined]
        orig_sample_count = len(pdata.prot.obs)

        if exact_cases:
            if not isinstance(values, list) or not all(isinstance(v, dict) for v in values):
                raise ValueError("When exact_cases=True, `values` must be a list of dictionaries.")

            for case in values:
                if not case:
                    raise ValueError("Empty dictionary found in values.")
                for key in case:
                    if key not in obs_keys:
                        raise ValueError(f"Field '{key}' not found in adata.obs.")

            query = " | ".join([
                " & ".join([
                    f"(adata.obs['{k}'] == '{v}')" for k, v in case.items()
                ])
                for case in values
            ])

        else:
            if not isinstance(values, dict):
                raise ValueError("When exact_cases=False, `values` must be a dictionary.")

            for key in values:
                if key not in obs_keys:
                    raise ValueError(f"Field '{key}' not found in adata.obs.")

            query_parts = []
            for k, v in values.items():
                v_list = v if isinstance(v, list) else [v]
                part = " | ".join([f"(adata.obs['{k}'] == '{val}')" for val in v_list])
                query_parts.append(f"({part})")
            query = " & ".join(query_parts)

        if debug:
                print(f"Filter query: {query}")

        if pdata.prot is not None:
            adata = pdata.prot
            pdata.prot = adata[eval(query)]
        if pdata.pep is not None:
            adata = pdata.pep
            pdata.pep = adata[eval(query)]

        if cleanup:
            cleanup_message = pdata._cleanup_proteins_after_sample_filter(verbose=True)
        else:
            cleanup_message = None
        pdata.update_summary(recompute=False, verbose=False) # type: ignore[attr-defined], SummaryMixin

        n_samples = len(pdata.prot)
        log_prefix = format_log_prefix("user")
        filter_mode = "exact match" if exact_cases else "class match"

        if n_samples == 0:
            message = (
                f"{log_prefix} Filtering samples [{filter_mode}]:\n"
                f"    → No matching samples found. No filtering applied."
            )
        else:
            message = (
                f"{log_prefix} Filtering samples [{filter_mode}]:\n"
                f"    {'Returning a copy of' if return_copy else 'Filtered and modified'} sample data based on {filter_mode}:\n"
            )

            if exact_cases:
                message += f"{format_log_prefix('filter_conditions')}Matching any of the following cases:\n"
                for i, case in enumerate(values, 1):
                    message += f"       {i}. {case}\n"
            else:
                message += "   🔸 Match samples where:\n"
                for k, v in values.items():
                    valstr = v if isinstance(v, str) else ", ".join(map(str, v))
                    message += f"      - {k}: {valstr}\n"

            message += cleanup_message + "\n" if cleanup_message else ""
            message += f"    → Samples kept: {n_samples}, Samples dropped: {orig_sample_count - n_samples}"
            message += f"\n    → Proteins kept: {len(pdata.prot.var)}\n"

        print(message) if verbose else None
        pdata._append_history(message) # type: ignore[attr-defined], HistoryMixin

        return pdata

    def _filter_sample_query(self, query_string, source='obs', cleanup=True, return_copy=True, debug=False):
        """
        Filter samples using a raw pandas-style query string on `.obs` or `.summary`.

        This method allows advanced filtering of samples using logical expressions evaluated 
        directly on the sample metadata.

        Args:
            query_string (str): A pandas-style query string. 
                Example: `"cellline == 'AS' and treatment in ['kd', 'sc']"`.
            source (str): The metadata source to query — either `"obs"` or `"summary"`.
            cleanup (bool): If True (default), remove proteins that become all-NaN or all-zero
                after sample filtering and synchronize RS/peptide matrices. Set to False to
                retain all proteins for consistent feature alignment (e.g. during DE analysis).
            return_copy (bool): If True, returns a filtered pAnnData object; otherwise modifies in place.
            debug (bool): If True, prints the parsed query and debug messages.

        Returns:
            pAnnData: Filtered pAnnData object if `return_copy=True`; otherwise, modifies in place and returns None.
        """
        pdata = self.copy() if return_copy else self # type: ignore[attr-defined], EditingMixin
        action = "Returning a copy of" if return_copy else "Filtered and modified"
        orig_sample_count = len(pdata.prot.obs)

        print(f"{format_log_prefix('warn',indent=1)} Advanced query mode enabled — interpreting string as a pandas-style expression.")

        if source == 'obs':
            df = pdata.prot.obs
        elif source == 'summary':
            if self._summary is None: # type: ignore[attr-defined]
                self.update_summary(recompute=True) # type: ignore[attr-defined], SummaryMixin
            df = pdata._summary # type: ignore[attr-defined]
        else:
            raise ValueError("source must be 'obs' or 'summary'")

        try:
            filtered_df = df.query(query_string)
        except Exception as e:
            raise ValueError(f"Failed to parse query string:\n  {query_string}\nError: {e}")

        index_filter = filtered_df.index

        if pdata.prot is not None:
            pdata.prot = pdata.prot[pdata.prot.obs_names.isin(index_filter)]
        if pdata.pep is not None:
            pdata.pep = pdata.pep[pdata.pep.obs_names.isin(index_filter)]

        if cleanup:
            cleanup_message = pdata._cleanup_proteins_after_sample_filter(verbose=True)
        else:
            cleanup_message = None
        pdata.update_summary(recompute=False, verbose=False) # type: ignore[attr-defined], SummaryMixin

        n_samples = len(pdata.prot)
        log_prefix = format_log_prefix("user")
        action = "Returning a copy of" if return_copy else "Filtered and modified"

        message = (
            f"{log_prefix} Filtering samples [query]:\n"
            f"    {action} sample data based on query string:\n"
            f"   🔸 Query: {query_string}\n"
        )

        if cleanup_message:
            message += f"{cleanup_message}\n"

        message += (
            f"    → Samples kept: {n_samples}, Samples dropped: {orig_sample_count - n_samples}\n"
            f"    → Proteins kept: {len(pdata.prot.var)}\n"
        )

        print(message)

        history_message = f"{action} samples based on query string. Samples kept: {len(index_filter)}."
        pdata._append_history(history_message) # type: ignore[attr-defined], HistoryMixin

        return pdata if return_copy else None

    def _cleanup_proteins_after_sample_filter(self, verbose=True, printout=False):
        """
        Internal helper to remove proteins that became all-NaN or all-zero
        after sample filtering. Called silently by `filter_sample()`.

        Ensures the RS matrix and peptide table are synchronized after cleanup.
        Called automatically by `filter_sample()` and during import.        

        Args:
            verbose (bool): If True, returns a cleanup summary message.
                            If False, runs silently.
            printout (bool): If True and verbose=True, directly prints the cleanup mesage.

        Returns:
            str or None: Cleanup message if verbose=True and any proteins removed,
                        otherwise None.
        """
        from scipy.sparse import issparse

        if not self._check_data("protein"):  # type: ignore[attr-defined]
            return

        X = self.prot.X.toarray() if issparse(self.prot.X) else self.prot.X
        original_var_names = self.prot.var_names.copy()
        all_nan = np.all(np.isnan(X), axis=0)
        all_zero = np.all(X == 0, axis=0)
        remove_mask = all_nan | all_zero

        if not remove_mask.any():
            if verbose:
                return f"{format_log_prefix('info_only',2)} Auto-cleanup: No empty proteins found (all-NaN or all-zero)."
            else:
                return None

        n_remove = int(remove_mask.sum())
        keep_mask = ~remove_mask

        # skip cleanup entirely if no samples or no protein data remain
        if self.prot is None or self.prot.n_obs == 0 or self.prot.n_vars == 0:
            if verbose:
                return f"{format_log_prefix('warn_only',2)} No samples or proteins to clean up. Skipping RS sync."
            return None

        # Filter protein data
        self.prot = self.prot[:, keep_mask].copy()

        if self.pep is not None and self.rs is not None:
            proteins_to_keep, peptides_to_keep, orig_prot_names, orig_pep_names = self._filter_sync_peptides_to_proteins(
                orig_prot_names=original_var_names,
                updated_prot=self.prot,
                debug=False
            )

            self._apply_rs_filter(
                keep_proteins=proteins_to_keep,
                keep_peptides=peptides_to_keep,
                orig_prot_names=orig_prot_names,
                orig_pep_names=orig_pep_names,
                debug=False
            )

        self.update_summary(recompute=True, verbose=False)

        if verbose:            
            removed_proteins = list(original_var_names[remove_mask])
            preview = ", ".join(removed_proteins[:10])
            if n_remove > 10:
                preview += ", ..."

            if printout and n_remove>0:
                # for startup
                print(f"{format_log_prefix('info_only',1)} Removed {n_remove} empty proteins (all-NaN or all-zero). Proteins: {preview}")
            else:
                # for filter
                return(f"{format_log_prefix('info_only',2)} Auto-cleanup: Removed {n_remove} empty proteins (all-NaN or all-zero). Proteins: {preview}")

        return None

    def filter_rs(
        self,
        min_peptides_per_protein=None,
        min_unique_peptides_per_protein=2,
        max_proteins_per_peptide=None,
        return_copy=True,
        preset=None,
        validate_after=True
    ):
        """
        Filter the RS matrix and associated `.prot` and `.pep` data based on peptide-protein relationships.

        This method applies rules for keeping proteins with sufficient peptide evidence and/or removing
        ambiguous peptides. It also updates internal mappings accordingly.

        Args:
            min_peptides_per_protein (int, optional): Minimum number of total peptides required per protein.
            min_unique_peptides_per_protein (int, optional): Minimum number of unique peptides required per protein 
                (default is 2).
            max_proteins_per_peptide (int, optional): Maximum number of proteins a peptide can map to; peptides 
                exceeding this will be removed.
            return_copy (bool): If True (default), returns a filtered pAnnData object. If False, modifies in place.
            preset (str or dict, optional): Predefined filter presets:
                - `"default"` → unique peptides ≥ 2
                - `"lenient"` → total peptides ≥ 2
                - A dictionary specifying filter thresholds manually.
            validate_after (bool): If True (default), calls `self.validate()` after filtering.

        Returns:
            pAnnData: Filtered pAnnData object if `return_copy=True`; otherwise, modifies in place and returns None.

        Note:
            Stores filter metadata in `.prot.uns['filter_rs']`, including indices of proteins/peptides kept and 
            filtering summary.
        """
        if self.rs is None: # type: ignore[attr-defined]
            print("⚠️ No RS matrix to filter.")
            return self if return_copy else None

        # --- Apply preset if given ---
        if preset:
            if preset == "default":
                min_peptides_per_protein = None
                min_unique_peptides_per_protein = 2
                max_proteins_per_peptide = None
            elif preset == "lenient":
                min_peptides_per_protein = 2
                min_unique_peptides_per_protein = None
                max_proteins_per_peptide = None
            elif isinstance(preset, dict):
                min_peptides_per_protein = preset.get("min_peptides_per_protein", min_peptides_per_protein)
                min_unique_peptides_per_protein = preset.get("min_unique_peptides_per_protein", min_unique_peptides_per_protein)
                max_proteins_per_peptide = preset.get("max_proteins_per_peptide", max_proteins_per_peptide)
            else:
                raise ValueError(f"Unknown RS filtering preset: {preset}")

        pdata = self.copy() if return_copy else self # type: ignore[attr-defined], EditingMixin

        rs = pdata.rs # type: ignore[attr-defined]

        # --- Step 1: Peptide filter (max proteins per peptide) ---
        if max_proteins_per_peptide is not None:
            peptide_links = rs.getnnz(axis=0)
            keep_peptides = peptide_links <= max_proteins_per_peptide
            rs = rs[:, keep_peptides]
        else:
            keep_peptides = np.ones(rs.shape[1], dtype=bool)

        # --- Step 2: Protein filters ---
        is_unique = rs.getnnz(axis=0) == 1
        unique_counts = rs[:, is_unique].getnnz(axis=1)
        peptide_counts = rs.getnnz(axis=1)

        keep_proteins = np.ones(rs.shape[0], dtype=bool)
        if min_peptides_per_protein is not None:
            keep_proteins &= (peptide_counts >= min_peptides_per_protein)
        if min_unique_peptides_per_protein is not None:
            keep_proteins &= (unique_counts >= min_unique_peptides_per_protein)

        rs_filtered = rs[keep_proteins, :]

        # --- Step 3: Re-filter peptides now unmapped ---
        keep_peptides_final = rs_filtered.getnnz(axis=0) > 0
        rs_filtered = rs_filtered[:, keep_peptides_final]

        # --- Apply filtered RS ---
        pdata._set_RS(rs_filtered, validate=False) # type: ignore[attr-defined], EditingMixin

        # --- Filter .prot and .pep ---
        if pdata.prot is not None:
            pdata.prot = pdata.prot[:, keep_proteins]
        if pdata.pep is not None:
            original_peptides = keep_peptides.nonzero()[0]
            final_peptides = original_peptides[keep_peptides_final]
            pdata.pep = pdata.pep[:, final_peptides]

        # --- History and summary ---
        n_prot_before = self.prot.shape[1] if self.prot is not None else rs.shape[0]
        n_pep_before = self.pep.shape[1] if self.pep is not None else rs.shape[1]
        n_prot_after = rs_filtered.shape[0]
        n_pep_after = rs_filtered.shape[1]

        n_prot_dropped = n_prot_before - n_prot_after
        n_pep_dropped = n_pep_before - n_pep_after

        msg = "🧪 Filtered RS"
        if preset:
            msg += f" using preset '{preset}'"
        if min_peptides_per_protein is not None:
            msg += f", min peptides per protein: {min_peptides_per_protein}"
        if min_unique_peptides_per_protein is not None:
            msg += f", min unique peptides: {min_unique_peptides_per_protein}"
        if max_proteins_per_peptide is not None:
            msg += f", max proteins per peptide: {max_proteins_per_peptide}"
        msg += (
            f". Proteins: {n_prot_before} → {n_prot_after} (dropped {n_prot_dropped}), "
            f"Peptides: {n_pep_before} → {n_pep_after} (dropped {n_pep_dropped})."
        )

        pdata._append_history(msg) # type: ignore[attr-defined], HistoryMixin
        print(msg)
        pdata.update_summary() # type: ignore[attr-defined], SummaryMixin

        # --- Save filter indices to .uns ---
        protein_indices = list(pdata.prot.var_names) if pdata.prot is not None else []
        peptide_indices = list(pdata.pep.var_names) if pdata.pep is not None else []
        pdata.prot.uns['filter_rs'] = {
            "kept_proteins": protein_indices,
            "kept_peptides": peptide_indices,
            "n_proteins": len(protein_indices),
            "n_peptides": len(peptide_indices),
            "description": msg
        }

        if validate_after:
            pdata.validate(verbose=True) # type: ignore[attr-defined], ValidationMixin

        return pdata if return_copy else None

    def _apply_rs_filter(
        self,
        keep_proteins=None,
        keep_peptides=None,
        orig_prot_names=None,
        orig_pep_names=None,
        debug=True
    ):
        """
        Apply filtering to `.prot`, `.pep`, and `.rs` based on protein/peptide masks or name lists.

        This method filters the relational structure (RS matrix) and associated data objects by retaining
        only the specified proteins and/or peptides. Original axis names can be provided to ensure correct
        alignment after prior filtering steps.

        Args:
            keep_proteins (list or np.ndarray or bool array, optional): List of protein names or boolean mask 
                indicating which proteins (RS matrix rows) to keep.
            keep_peptides (list or np.ndarray or bool array, optional): List of peptide names or boolean mask 
                indicating which peptides (RS matrix columns) to keep.
            orig_prot_names (list or np.ndarray, optional): Original protein names corresponding to RS matrix rows.
            orig_pep_names (list or np.ndarray, optional): Original peptide names corresponding to RS matrix columns.
            debug (bool): If True, prints filtering details and index alignment diagnostics.

        Returns:
            None
            str
        """

        if self.rs is None: # type: ignore[attr-defined]
            raise ValueError("No RS matrix to filter.")

        from scipy.sparse import issparse

        rs = self.rs # type: ignore[attr-defined]

        # Use provided names or fallback to current .prot/.pep
        prot_names = np.array(orig_prot_names) if orig_prot_names is not None else np.array(self.prot.var_names)
        pep_names = np.array(orig_pep_names) if orig_pep_names is not None else np.array(self.pep.var_names)

        if rs.shape[0] != len(prot_names) or rs.shape[1] != len(pep_names):
            raise ValueError(
                f"RS shape {rs.shape} does not match provided protein/peptide names "
                f"({len(prot_names)} proteins, {len(pep_names)} peptides). "
                "Did you forget to pass the original names?"
            )

        # --- Normalize protein mask ---
        if keep_proteins is None:
            prot_mask = np.ones(rs.shape[0], dtype=bool)
        elif isinstance(keep_proteins, (list, np.ndarray, pd.Index)) and isinstance(keep_proteins[0], str):
            keep_set = set(keep_proteins)
            prot_mask = np.fromiter((p in keep_set for p in prot_names), dtype=bool)
        elif isinstance(keep_proteins, (list, np.ndarray)) and isinstance(keep_proteins[0], (bool, np.bool_)):
            prot_mask = np.asarray(keep_proteins)
        else:
            raise TypeError("keep_proteins must be a list of str or a boolean mask.")

        # --- Normalize peptide mask ---
        if keep_peptides is None:
            pep_mask = np.ones(rs.shape[1], dtype=bool)
        elif isinstance(keep_peptides, (list, np.ndarray, pd.Index)) and isinstance(keep_peptides[0], str):
            keep_set = set(keep_peptides)
            pep_mask = np.fromiter((p in keep_set for p in pep_names), dtype=bool)
        elif isinstance(keep_peptides, (list, np.ndarray)) and isinstance(keep_peptides[0], (bool, np.bool_)):
            pep_mask = np.asarray(keep_peptides)
        else:
            raise TypeError("keep_peptides must be a list of str or a boolean mask.")

        # --- Final safety check ---
        if len(prot_mask) != rs.shape[0] or len(pep_mask) != rs.shape[1]:
            raise ValueError("Mismatch between mask lengths and RS matrix dimensions.")

        # --- Apply to RS ---
        self._set_RS(rs[prot_mask, :][:, pep_mask], validate=False) # type: ignore[attr-defined], EditingMixin

        # --- Apply to .prot and .pep ---
        kept_prot_names = np.array(orig_prot_names)[prot_mask]
        kept_pep_names = np.array(orig_pep_names)[pep_mask]

        if self.prot is not None:
            self.prot = self.prot[:, self.prot.var_names.isin(kept_prot_names)]

        if self.pep is not None:
            self.pep = self.pep[:, self.pep.var_names.isin(kept_pep_names)]

        if debug:
            print(f"{format_log_prefix('result')} RS matrix filtered: {prot_mask.sum()} proteins, {pep_mask.sum()} peptides retained.")
        else:
            return(f"{format_log_prefix('result')} RS matrix filtered: {prot_mask.sum()} proteins, {pep_mask.sum()} peptides retained.")

    def _format_filter_query(self, condition, dataframe):
        """
        Format a condition string for safe evaluation on a DataFrame with complex column names.

        This method prepares a query string for use with `pandas.eval()` or `.query()` by:
        - Wrapping column names containing spaces or special characters in backticks.
        - Converting custom `includes` syntax (for substring matching) into `.str.contains(...)` expressions.
        - Quoting unquoted string values automatically for object/category columns.

        Args:
            condition (str): The condition string to parse and format.
            dataframe (pd.DataFrame): The DataFrame whose column names and dtypes are used for formatting.

        Returns:
            str: A cleaned and properly formatted condition string suitable for `.eval()` or `.query()`.

        Note:
            This is an internal helper used by methods such as `filter_sample_condition()` and `filter_prot()` 
            to support user-friendly string-based queries.
        """

        # Wrap column names with backticks if needed
        column_names = dataframe.columns.tolist()
        column_names.sort(key=len, reverse=True) # Avoid partial matches

        for col in column_names:
            if re.search(r'[^\\w]', col):  # Non-alphanumeric characters
                condition = re.sub(fr'(?<!`)({re.escape(col)})(?!`)', f'`{col}`', condition)

        # Handle 'includes' syntax for substring matching
        match = re.search(r'`?(\w[\w\s:.-]*)`?\s+includes\s+[\'"]([^\'"]+)[\'"]', condition)
        if match:
            col_name = match.group(1)
            substring = match.group(2)
            condition = f"{col_name}.str.contains('{substring}', case=False, na=False)"

        # Auto-quote string values for categorical/text columns
        for col in dataframe.columns:
            if dataframe[col].dtype.name in ["object", "category"]:
                for op in ["==", "!="]:
                    pattern = fr"(?<![><=!])\b{re.escape(col)}\s*{op}\s*([^\s'\"()]+)"
                    matches = re.findall(pattern, condition)
                    for match_val in matches:
                        quoted_val = f'"{match_val}"'
                        condition = re.sub(fr"({re.escape(col)}\s*{op}\s*){match_val}\b", r"\1" + quoted_val, condition)

        return condition

    def _annotate_found_samples(self, threshold=0.0, layer='X'):
        """
        Annotate proteins and peptides with per-sample 'Found In' flags.

        For each sample, this method adds boolean indicators to `.prot.var` and `.pep.var` 
        indicating whether the feature was detected (i.e. exceeds the given threshold).

        Args:
            threshold (float): Minimum value to consider a feature as "found" (default is 0.0).
            layer (str): Name of the data layer to evaluate (e.g., "X", "imputed", etc.).

        Returns:
            None

        Note:
            This is an internal helper used to support downstream grouping-based detection 
            (e.g., in `annotate_found_in()`).
            Adds new columns to `.var` of the form: `'Found In: <sample>' → bool`.
        """
        for level in ['prot', 'pep']:
            adata = getattr(self, level)
            # Skip if the level doesn't exist
            if adata is None:
                continue

            # Handle layer selection
            if layer == 'X':
                data = pd.DataFrame(adata.X.toarray() if hasattr(adata.X, 'toarray') else adata.X,
                                    index=adata.obs_names,
                                    columns=adata.var_names).T
            elif layer in adata.layers:
                data = pd.DataFrame(adata.layers[layer].toarray() if hasattr(adata.layers[layer], 'toarray') else adata.layers[layer],
                                    index=adata.obs_names,
                                    columns=adata.var_names).T
            else:
                raise KeyError(f"Layer '{layer}' not found in {level}.layers and is not 'X'.")

            found = data > threshold
            for sample in found.columns:
                adata.var[f"Found In: {sample}"] = found[sample]

    def annotate_found(self, classes=None, on='protein', layer='X', threshold=0.0, indent=1, verbose=True):
        """
        Add group-level 'Found In' annotations for proteins or peptides.

        This method computes detection flags across groups of samples, based on a minimum intensity 
        threshold, and stores them in `.prot.var` or `.pep.var` as new boolean columns.

        Args:
            classes (str or list of str): Sample-level class/grouping column(s) in `.sample.obs`.
            on (str): Whether to annotate 'protein' or 'peptide' level features.
            layer (str): Data layer to use for evaluation (default is "X").
            threshold (float): Minimum intensity value to be considered "found".
            indent (int): Indentation level for printed messages.
            verbose (bool): If True, prints a summary message after annotation.

        Returns:
            None

        Example:
            Annotate proteins by group using sample-level metadata:
                ```python
                pdata.annotate_found(classes=["group", "condition"], on="protein")
                ```

            Filter for proteins found in at least 20% of samples from a given group:
                ```python
                pdata_filtered = pdata.filter_prot_found(group="Group_A", min_ratio=0.2)
                pdata_filtered.prot.var
                ```
        """
        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            return

        adata = self.prot if on == 'protein' else self.pep
        var = adata.var

        # Handle layer correctly (supports 'X' or adata.layers keys)
        if layer == 'X':
            data = pd.DataFrame(adata.X.toarray() if hasattr(adata.X, 'toarray') else adata.X,
                                index=adata.obs_names,
                                columns=adata.var_names).T
        elif layer in adata.layers:
            raw = adata.layers[layer]
            data = pd.DataFrame(raw.toarray() if hasattr(raw, 'toarray') else raw,
                                index=adata.obs_names,
                                columns=adata.var_names).T
        else:
            raise KeyError(f"Layer '{layer}' not found in {on}.layers and is not 'X'.")

        found_df = data > threshold

        # Prepare or retrieve existing numeric storage in .uns
        metrics_key = f"found_metrics_{on}"
        metrics_df = adata.uns.get(metrics_key, pd.DataFrame(index=adata.var_names)).reindex(adata.var_names)

        if classes is not None:
            classes_list = utils.get_classlist(adata, classes=classes)

            for class_value in classes_list:
                if "_" in class_value:
                    print(
                        f"{format_log_prefix('warn')} class_value '{class_value}' contains an underscore ('_'), "
                        "which may break format_class_filter(). Consider removing or replacing ('_')."
                    )

                class_data = utils.resolve_class_filter(adata, classes, class_value)
                class_samples = class_data.obs_names

                if len(class_samples) == 0:
                    continue

                sub_found = found_df[class_samples]
                count = sub_found.sum(axis=1)
                ratio = count / len(class_samples)

                # Store display-friendly annotations in .var
                var[f"Found In: {class_value}"] = sub_found.any(axis=1)
                var[f"Found In: {class_value} ratio"] = sub_found.sum(axis=1).astype(str) + "/" + str(len(class_samples))

                # Store numeric data in .uns
                metrics_df[(class_value, "count")] = count
                metrics_df[(class_value, "ratio")] = ratio

            # Store updated versions back into .uns
            metrics_df.columns = pd.MultiIndex.from_tuples(metrics_df.columns)
            metrics_df = metrics_df.sort_index(axis=1)
            adata.uns[metrics_key] = metrics_df

        self._history.append(  # type: ignore[attr-defined], HistoryMixin
            f"{on}: Annotated features 'found in' class combinations {classes} using threshold {threshold}."
        )
        if verbose:
            print(
                f"{format_log_prefix('user', indent=indent)} Annotated 'found in' features by group: "
                f"{classes} using threshold {threshold}."
            )

    def annotate_significant(self, classes=None, on='protein', fdr_threshold=0.01, indent=1, verbose=True):
        """
        Add group-level 'Significant In' annotations for proteins or peptides.

        This method computes significance flags (e.g., X_qval < threshold) across groups 
        of samples and stores them in `.prot.var` or `.pep.var` as new boolean columns.

        DIA-NN: protein X_qval originates from PG.Q.Value, peptide X_qval originates from Q.Value.

        Args:
            classes (str or list of str, optional): Sample-level grouping column(s) for group-based annotations.
            fdr_threshold (float): Significance threshold (default 0.01).
            on (str): Level to annotate ('protein' or 'peptide').
            indent (int): Indentation level for printed messages.
            verbose (bool): If True, prints a summary message after annotation.

        Returns:
            None

        Example:
            Annotate proteins by group using sample-level metadata:
                ```python
                pdata.annotate_significant(classes="celltype", on="protein", fdr_threshold=0.01)
                ```
        """
        if not self._check_data(on): # type: ignore[attr-defined], ValidationMixin
            return

        adata = self.prot if on == 'protein' else self.pep
        var = adata.var

        # Check if significance layer exists
        sig_layer = 'X_qval'
        if sig_layer not in adata.layers:
            # Try global q-values as fallback
            if "Global_Q_value" in var.columns:
                global_mask = var["Global_Q_value"] < fdr_threshold
                var["Significant In: Global"] = global_mask
                adata.uns[f"significance_metrics_{on}"] = pd.DataFrame(
                    {"Global_count": global_mask.sum(), "Global_ratio": global_mask.mean()},
                    index=["Global"]
                )
                if verbose:
                    print(f"{format_log_prefix('user', indent=indent)} Annotated global significant features using FDR threshold {fdr_threshold}.")
                return
            else:
                raise ValueError(
                    f"No per-sample layer ('{sig_layer}') or 'Global_Q_value' column found for {on}-level significance."
                )

        data = pd.DataFrame(
            adata.layers[sig_layer].toarray() if hasattr(adata.layers[sig_layer], 'toarray') else adata.layers[sig_layer],
            index=adata.obs_names,
            columns=adata.var_names).T  # shape: features × samples

        # Group-level summary
        metrics_key = f"significance_metrics_{on}"
        metrics_df = adata.uns.get(metrics_key, pd.DataFrame(index=adata.var_names)).reindex(adata.var_names)

        if classes is not None:
            classes_list = utils.get_classlist(adata, classes=classes)

            for class_value in classes_list:
                if "_" in class_value:
                    print(
                        f"{format_log_prefix('warn')} class_value '{class_value}' contains an underscore ('_'), "
                        "which may break format_class_filter(). Consider removing or replacing ('_')."
                    )

                class_data = utils.resolve_class_filter(adata, classes, class_value)
                class_samples = class_data.obs_names

                if len(class_samples) == 0:
                    continue

                sub_df = data[class_samples]
                count = (sub_df < fdr_threshold).sum(axis=1)
                ratio = count / len(class_samples)

                var[f"Significant In: {class_value}"] = (sub_df < fdr_threshold).any(axis=1)
                var[f"Significant In: {class_value} ratio"] = count.astype(str) + "/" + str(len(class_samples))

                metrics_df[(class_value, "count")] = count
                metrics_df[(class_value, "ratio")] = ratio

            metrics_df.columns = pd.MultiIndex.from_tuples(metrics_df.columns)
            metrics_df = metrics_df.sort_index(axis=1)
            adata.uns[metrics_key] = metrics_df

        self._history.append(  # type: ignore[attr-defined], HistoryMixin
            f"{on}: Annotated significance across classes {classes} using FDR threshold {fdr_threshold}."
        )
        if verbose:
            print(
                f"{format_log_prefix('user', indent=indent)} Annotated significant features by group: {classes} using FDR threshold {fdr_threshold}."
            )

    def _annotate_significant_samples(self, fdr_threshold=0.01):
        """
        Annotate proteins and peptides with per-sample 'Significant In' flags.

        For each sample, this method adds boolean indicators to `.prot.var` and `.pep.var`
        indicating whether the feature is significantly detected (i.e. FDR < threshold).

        Args:
            fdr_threshold (float): FDR threshold for significance (default: 0.01).

        Returns:
            None

        Note:
            This is an internal helper used to support downstream grouping-based annotation.
            Adds new columns to `.var` of the form: `'Significant In: <sample>' → bool`.
        """
        for level in ['prot', 'pep']:
            adata = getattr(self, level)
            if adata is None:
                continue

            if "Global_Q_value" in adata.var.columns:
                adata.var["Significant In: Global"] = adata.var["Global_Q_value"] < fdr_threshold

            sig_layer = 'X_qval'
            if sig_layer not in adata.layers:
                # Fallback to global q-values if available
                print(f"{format_log_prefix('info', 2)} Using global q-values for '{level}' significance annotation.")
                continue  # Skip if significance data not available

            print(f"{format_log_prefix('info', 2)} Using sample-specific q-values for '{level}' significance annotation.")

            data = pd.DataFrame(
                adata.layers[sig_layer].toarray() if hasattr(adata.layers[sig_layer], 'toarray') else adata.layers[sig_layer],
                index=adata.obs_names,
                columns=adata.var_names).T  # features × samples

            significant = data < fdr_threshold
            sig_df = significant.add_prefix("Significant In: ")
            adata.var = pd.concat([adata.var, sig_df], axis=1)

_filter_sync_peptides_to_proteins

_filter_sync_peptides_to_proteins(
    orig_prot_names, updated_prot, debug=None
)

Helper function to filter peptides based on the updated protein list.

This method determines which peptides to retain after protein-level filtering, and returns the necessary inputs for _apply_rs_filter.

Parameters:

Name Type Description Default
orig_prot_names array - like

Protein names before filtering (RS row order). .pep and .rs must not be filtered yet.

required
updated_prot AnnData

Updated protein AnnData object to filter against.

required
debug bool

If True, prints debugging information.

None

Returns:

Name Type Description
tuple

Inputs needed for downstream _apply_rs_filter operation.

Source code in src/scpviz/pAnnData/filtering.py
def _filter_sync_peptides_to_proteins(self, orig_prot_names, updated_prot, debug=None):
    """
    Helper function to filter peptides based on the updated protein list.

    This method determines which peptides to retain after protein-level filtering,
    and returns the necessary inputs for `_apply_rs_filter`.

    Args:
        orig_prot_names (array-like): Protein names before filtering (RS row order). `.pep` and `.rs`
            must not be filtered yet.
        updated_prot (AnnData): Updated protein AnnData object to filter against.
        debug (bool, optional): If True, prints debugging information.

    Returns:
        tuple: Inputs needed for downstream `_apply_rs_filter` operation.
    """
    if debug:
        print(f"{format_log_prefix('info')} Applying RS-based peptide sync-up on peptides after protein filtering...")

    # .rs and .pep are still unfiltered here; .prot may already be filtered in place
    rs = self.rs
    orig_prot_names = np.array(orig_prot_names)
    orig_pep_names = np.array(self.pep.var_names)
    # Determine which protein rows to keep in RS
    proteins_to_keep=updated_prot.var_names
    keep_set = set(proteins_to_keep)
    prot_mask = np.fromiter((p in keep_set for p in orig_prot_names), dtype=bool)
    rs_filtered = rs[prot_mask, :]
    # Keep peptides that are still linked to ≥1 protein
    pep_mask = np.array(rs_filtered.sum(axis=0)).ravel() > 0
    peptides_to_keep = orig_pep_names[pep_mask]

    return proteins_to_keep, peptides_to_keep, orig_prot_names, orig_pep_names

_filter_sample_poi

_filter_sample_poi(
    poi,
    min_abundance=None,
    max_abundance=None,
    require_detected=True,
    match_any=False,
    layer="X",
    on="protein",
    cleanup=True,
    return_copy=True,
    debug=False,
)

Filter samples by raw abundance thresholds for a protein or peptide of interest.

See filter_sample(poi=...) for parameter documentation.

Source code in src/scpviz/pAnnData/filtering.py
def _filter_sample_poi(
    self,
    poi,
    min_abundance=None,
    max_abundance=None,
    require_detected=True,
    match_any=False,
    layer="X",
    on="protein",
    cleanup=True,
    return_copy=True,
    debug=False,
):
    """
    Filter samples by raw abundance thresholds for a protein or peptide of interest.

    See ``filter_sample(poi=...)`` for parameter documentation.
    """
    on_user = on.lower()
    feature_kind = "peptides" if on_user in ("peptide", "pep") else "proteins"
    notes: list[str] = []

    if on_user in ("peptide", "pep"):
        if self.pep is None:  # type: ignore[attr-defined]
            raise ValueError("Peptide data (.pep) is not available.")
        features = utils.resolve_peptides(
            self, [poi], all_matches=True, on_empty="return", quiet=True
        )  # type: ignore[arg-type]
    else:
        if not self._check_data("protein"):  # type: ignore[attr-defined]
            raise ValueError("No protein data found.")
        adata = self.prot  # type: ignore[attr-defined]
        features = utils.resolve_accessions(
            adata, [poi], all_matches=True, on_empty="return", quiet=True
        )

    if features and len(features) > 1:
        notes.append(
            f"{format_log_prefix('info')} "
            f"'{poi}' resolved to multiple {feature_kind}: {features}"
        )

    pdata = self.copy() if return_copy else self  # type: ignore[attr-defined], EditingMixin
    action = "Returning a copy of" if return_copy else "Filtered and modified"
    ref_adata = pdata.prot if pdata.prot is not None else pdata.pep  # type: ignore[attr-defined]
    orig_sample_count = len(ref_adata.obs)

    if not features:
        notes.append(
            f"{format_log_prefix('warn')} POI '{poi}' did not resolve to any "
            f"{feature_kind}. No samples retained."
        )
        index_filter = []
    else:
        adata = getattr(pdata, "pep" if on_user in ("peptide", "pep") else "prot")
        missing = [f for f in features if f not in adata.var_names]
        if missing:
            notes.append(
                f"{format_log_prefix('warn')} POI features not in .var_names (skipped): {missing}"
            )
        features = [f for f in features if f in adata.var_names]
        if not features:
            index_filter = []
        else:
            X = adata[:, features].layers[layer] if layer in adata.layers else adata[:, features].X
            if hasattr(X, "toarray"):
                X = X.toarray()
            else:
                X = np.asarray(X)

            keep_mask = np.zeros(X.shape[0], dtype=bool)
            for i in range(X.shape[0]):
                evaluated = []
                for j in range(X.shape[1]):
                    val = X[i, j]
                    if np.isnan(val) or val <= 0:
                        continue
                    passes = True
                    if min_abundance is not None and val < min_abundance:
                        passes = False
                    if max_abundance is not None and val > max_abundance:
                        passes = False
                    evaluated.append(passes)

                if not evaluated:
                    keep_mask[i] = not require_detected
                elif match_any:
                    keep_mask[i] = any(evaluated)
                else:
                    keep_mask[i] = all(evaluated)

            index_filter = adata.obs_names[keep_mask].tolist()

    if debug:
        print(f"POI features: {features}")
        print(f"Samples kept: {len(index_filter)} / {orig_sample_count}")

    if pdata.prot is not None:
        pdata.prot = pdata.prot[pdata.prot.obs_names.isin(index_filter)]  # type: ignore[attr-defined]
    if pdata.pep is not None:
        pdata.pep = pdata.pep[pdata.pep.obs_names.isin(index_filter)]  # type: ignore[attr-defined]

    if cleanup:
        cleanup_message = pdata._cleanup_proteins_after_sample_filter(verbose=True)  # type: ignore[attr-defined]
    else:
        cleanup_message = None
    pdata.update_summary(recompute=False, verbose=False)  # type: ignore[attr-defined], SummaryMixin

    log_prefix = format_log_prefix("user")
    logic = "OR" if match_any else "AND"
    threshold_parts = []
    if min_abundance is not None:
        threshold_parts.append(f"min_abundance={min_abundance}")
    if max_abundance is not None:
        threshold_parts.append(f"max_abundance={max_abundance}")
    threshold_str = ", ".join(threshold_parts)

    if len(index_filter) == 0:
        message = (
            f"{log_prefix} Filtering samples [poi]:\n"
            f"    → No matching samples found.\n"
            f"{format_log_prefix('filter_conditions')}POI: {poi} ({on}, {len(features)} feature(s))\n"
            f"{format_log_prefix('filter_conditions')}Threshold: {threshold_str}\n"
            f"    → Samples kept: 0, Samples dropped: {orig_sample_count}"
        )
    else:
        message = (
            f"{log_prefix} Filtering samples [poi]:\n"
            f"    {action} sample data based on POI abundance ({logic} across detected matches):\n"
            f"{format_log_prefix('filter_conditions')}POI: {poi} ({on}, {len(features)} feature(s))\n"
            f"{format_log_prefix('filter_conditions')}Threshold: {threshold_str}\n"
            f"{format_log_prefix('filter_conditions')}require_detected={require_detected}, match_any={match_any}\n"
        )
        message += (
            f"    → Samples kept: {len(index_filter)}, "
            f"Samples dropped: {orig_sample_count - len(index_filter)}\n"
        )
        if pdata.prot is not None:
            message += f"    → Proteins kept: {len(pdata.prot.var)}\n"

    if notes:
        message += "\n".join(notes) + "\n"
    if cleanup_message:
        message += cleanup_message + "\n"

    print(message)
    pdata._append_history(message)  # type: ignore[attr-defined], HistoryMixin
    return pdata if return_copy else None

_filter_sample_condition

_filter_sample_condition(
    condition=None,
    return_copy=True,
    file_list=None,
    exclude_file_list=None,
    cleanup=True,
    debug=False,
)

Filter samples based on numeric metadata conditions or a list of sample identifiers.

This internal method supports two modes:

  • A string condition evaluated against .summary (e.g., "protein_count > 1000").
  • A file_list of sample names or identifiers to retain (e.g., filenames or .obs_names).

Parameters:

Name Type Description Default
condition str

Logical condition string referencing columns in .summary.

None
file_list list of str

List of sample identifiers to keep.

None
exclude_file_list list of str

Same as file_list, but excludes specified sample identifiers.

None
cleanup bool

If True (default), remove proteins that become all-NaN or all-zero after sample filtering and synchronize RS/peptide matrices. Set to False to retain all proteins for consistent feature alignment (e.g. during DE analysis).

True
return_copy bool

If True, returns a filtered pAnnData object. If False, modifies in place.

True
debug bool

If True, prints the query string or filtering summary.

False

Returns:

Name Type Description
pAnnData

Filtered pAnnData object if return_copy=True; otherwise, modifies in place and returns None.

Note

This method is intended for internal use by filter_sample(). For general-purpose filtering, use filter_sample() with condition=... or file_list=....

Example

Filter samples with more than 1000 proteins:

pdata.filter_sample_condition(condition="protein_count > 1000")

Keep only specific sample files:

pdata.filter_sample_condition(file_list=['fileA', 'fileB'])

Exclude specific files from the dataset:

pdata.filter_sample(exclude_file_list=['Sample_001', 'Sample_007'])

Source code in src/scpviz/pAnnData/filtering.py
def _filter_sample_condition(self, condition = None, return_copy = True, file_list=None, exclude_file_list=None, cleanup=True, debug=False):
    """
    Filter samples based on numeric metadata conditions or a list of sample identifiers.

    This internal method supports two modes:

    - A string `condition` evaluated against `.summary` (e.g., `"protein_count > 1000"`).
    - A `file_list` of sample names or identifiers to retain (e.g., filenames or `.obs_names`).

    Args:
        condition (str, optional): Logical condition string referencing columns in `.summary`.
        file_list (list of str, optional): List of sample identifiers to keep.
        exclude_file_list (list of str, optional): Same as file_list, but excludes specified sample identifiers.
        cleanup (bool): If True (default), remove proteins that become all-NaN or all-zero
            after sample filtering and synchronize RS/peptide matrices. Set to False to
            retain all proteins for consistent feature alignment (e.g. during DE analysis).
        return_copy (bool): If True, returns a filtered pAnnData object. If False, modifies in place.
        debug (bool): If True, prints the query string or filtering summary.

    Returns:
        pAnnData: Filtered pAnnData object if `return_copy=True`; otherwise, modifies in place and returns None.

    Note:
        This method is intended for internal use by `filter_sample()`. For general-purpose filtering, 
        use `filter_sample()` with `condition=...` or `file_list=...`.

    Example:
        Filter samples with more than 1000 proteins:
            ```python
            pdata.filter_sample_condition(condition="protein_count > 1000")
            ```

        Keep only specific sample files:
            ```python
            pdata.filter_sample_condition(file_list=['fileA', 'fileB'])
            ```

        Exclude specific files from the dataset:
            ```python
            pdata.filter_sample(exclude_file_list=['Sample_001', 'Sample_007'])
            ```
    """
    if not self._has_data(): # type: ignore[attr-defined], ValidationMixin
        pass

    if self._summary is None: # type: ignore[attr-defined]
        self.update_summary(recompute=True) # type: ignore[attr-defined], SummaryMixin

    if file_list is not None and exclude_file_list is not None:
        raise ValueError(
            "You cannot specify both `file_list` and `exclude_file_list` simultaneously.\n"
            "Please use only one mode per call:\n"
            "  • `file_list=[...]` to keep only these samples, or\n"
            "  • `exclude_file_list=[...]` to remove these samples.\n"
            "If you need both operations, call `filter_sample()` twice in sequence."
        )

    # Determine whether to operate on a copy or in-place
    pdata = self.copy() if return_copy else self # type: ignore[attr-defined], EditingMixin
    action = "Returning a copy of" if return_copy else "Filtered and modified"

    orig_sample_count = len(pdata.prot.obs)

    if debug:
        print("self.prot id:", id(self.prot))
        print("pdata.prot id:", id(pdata.prot))
        print("Length of pdata.prot.obs_names:", len(pdata.prot.obs_names))

    # Determine sample indices to retain
    index_filter = None
    missing = []

    if condition is not None:
        formatted_condition = self._format_filter_query(condition, pdata._summary)  # type: ignore[attr-defined]
        if debug:
            print(formatted_condition)
        index_filter = pdata._summary[pdata._summary.eval(formatted_condition)].index
    elif file_list is not None or exclude_file_list is not None:
        all_samples = set(pdata.prot.obs_names)

        if file_list is not None:
            requested = set(file_list)
            missing = list(requested - all_samples)
            index_filter = list(all_samples.intersection(requested))
            mode_str = "including"
            exclude_mode = False

        else:  # exclude_file_list is not None
            requested = set(exclude_file_list)
            missing = list(requested - all_samples)
            index_filter = list(all_samples - requested)
            mode_str = "excluding"
            exclude_mode = True

        if missing:
            warnings.warn(f"Some sample IDs not found: {missing}")

    else:
        # No filtering applied
        message = "No filtering applied. Returning original data."
        return pdata if return_copy else None

    if debug:
        print(f"Length of index_filter: {len(index_filter)}")
        print(f"Length of pdata.prot.obs_names before filter: {len(pdata.prot.obs_names)}")
        print(f"Number of shared samples: {len(pdata.prot.obs_names.intersection(index_filter))}")

    # Filter out selected samples from prot and pep
    if pdata.prot is not None:
        pdata.prot = pdata.prot[pdata.prot.obs.index.isin(index_filter)]

    if pdata.pep is not None:
        pdata.pep = pdata.pep[pdata.pep.obs.index.isin(index_filter)]

    if cleanup:
        cleanup_message = pdata._cleanup_proteins_after_sample_filter(verbose=True)
    else:
        cleanup_message = None
    pdata.update_summary(recompute=False, verbose=False) # type: ignore[attr-defined], SummaryMixin

    print(f"Length of pdata.prot.obs_names after filter: {len(pdata.prot.obs_names)}") if debug else None

    # Construct formatted message
    filter_type = "condition" if condition else "file list" if (file_list or exclude_file_list) else "none"
    log_prefix = format_log_prefix("user")

    if len(index_filter) == 0:
        message = f"{log_prefix} Filtering samples [{filter_type}]:\n    → No matching samples found. No filtering applied."
        if cleanup_message:
            message += "\n" + cleanup_message
    else:
        message = f"{log_prefix} Filtering samples [{filter_type}]:\n"
        message += f"    {action} sample data based on {filter_type}:\n"
        if condition:
            message += f"{format_log_prefix('filter_conditions')}Condition: {condition}\n"
        elif file_list or exclude_file_list:
            flist = file_list if file_list is not None else exclude_file_list
            message += f"{format_log_prefix('filter_conditions')}Files requested ({mode_str}): {len(flist)}\n"
            if missing:
                message += f"{format_log_prefix('filter_conditions')}Missing samples ignored: {len(missing)}\n"

        message += cleanup_message + "\n" if cleanup_message else ""
        message += f"    → Samples kept: {len(pdata.prot.obs)}, Samples dropped: {orig_sample_count - len(pdata.prot.obs)}"
        message += f"\n    → Proteins kept: {len(pdata.prot.var)}\n"

    # Logging and history updates
    print(message)
    pdata._append_history(message) # type: ignore[attr-defined], HistoryMixin

    return pdata if return_copy else None

_filter_sample_values

_filter_sample_values(
    values,
    exact_cases,
    cleanup=True,
    verbose=True,
    debug=False,
    return_copy=True,
)

Filter samples using dictionary-style categorical matching.

This internal method filters samples based on class-like annotations (e.g., treatment, cellline), using either loose field-wise filtering or strict combination matching. It supports:

  • Single dictionary (e.g., {'cellline': 'A'})
  • List of dictionaries (e.g., [{...}, {...}] for multiple matching cases)
  • Exact matching (exact_cases=True) across all key-value pairs

Parameters:

Name Type Description Default
values dict or list of dict

Filtering conditions. - If exact_cases=False: A single dictionary with field: list of values. Applies OR logic within fields and AND logic across fields. - If exact_cases=True: A list of dictionaries, each representing an exact combination of field values.

required
exact_cases bool

If True, performs exact match filtering using the provided list of dictionaries.

required
cleanup bool

If True (default), remove proteins that become all-NaN or all-zero after sample filtering and synchronize RS/peptide matrices. Set to False to retain all proteins for consistent feature alignment (e.g. during DE analysis).

True
verbose bool

If True, prints a summary of the filtering result.

True
debug bool

If True, prints internal queries and matching logic.

False
return_copy bool

If True, returns a filtered copy. Otherwise modifies in place.

True

Returns:

Name Type Description
pAnnData

Filtered view of the input AnnData object if return_copy=True; otherwise modifies in place and returns None.

Note

This method is used internally by filter_sample(). For general use, call filter_sample() directly.

Example

Loose field-wise match (OR within fields, AND across fields):

pdata.filter_sample_values(values={'treatment': ['kd', 'sc'], 'cellline': 'A'})

Exact combination matching:

pdata.filter_sample_values(
    values=[
        {'treatment': 'kd', 'cellline': 'A'},
        {'treatment': 'sc', 'cellline': 'B'}
    ],
    exact_cases=True
)

Source code in src/scpviz/pAnnData/filtering.py
def _filter_sample_values(self, values, exact_cases, cleanup=True, verbose=True, debug=False, return_copy=True):
    """
    Filter samples using dictionary-style categorical matching.

    This internal method filters samples based on class-like annotations (e.g., treatment, cellline),
    using either loose field-wise filtering or strict combination matching. It supports:

    - Single dictionary (e.g., `{'cellline': 'A'}`)
    - List of dictionaries (e.g., `[{...}, {...}]` for multiple matching cases)
    - Exact matching (`exact_cases=True`) across all key-value pairs

    Args:
        values (dict or list of dict): Filtering conditions.
            - If `exact_cases=False`: A single dictionary with field: list of values. 
            Applies OR logic within fields and AND logic across fields.
            - If `exact_cases=True`: A list of dictionaries, each representing an exact combination of field values.
        exact_cases (bool): If True, performs exact match filtering using the provided list of dictionaries.
        cleanup (bool): If True (default), remove proteins that become all-NaN or all-zero
            after sample filtering and synchronize RS/peptide matrices. Set to False to
            retain all proteins for consistent feature alignment (e.g. during DE analysis).
        verbose (bool): If True, prints a summary of the filtering result.
        debug (bool): If True, prints internal queries and matching logic.
        return_copy (bool): If True, returns a filtered copy. Otherwise modifies in place.

    Returns:
        pAnnData: Filtered view of the input AnnData object if `return_copy=True`; otherwise modifies in place and returns None.

    Note:
        This method is used internally by `filter_sample()`. For general use, call `filter_sample()` directly.

    Example:
        Loose field-wise match (OR within fields, AND across fields):
            ```python
            pdata.filter_sample_values(values={'treatment': ['kd', 'sc'], 'cellline': 'A'})
            ```

        Exact combination matching:
            ```python
            pdata.filter_sample_values(
                values=[
                    {'treatment': 'kd', 'cellline': 'A'},
                    {'treatment': 'sc', 'cellline': 'B'}
                ],
                exact_cases=True
            )
            ```
    """

    pdata = self.copy() if return_copy else self # type: ignore[attr-defined], EditingMixin
    obs_keys = pdata.summary.columns # type: ignore[attr-defined]
    orig_sample_count = len(pdata.prot.obs)

    if exact_cases:
        if not isinstance(values, list) or not all(isinstance(v, dict) for v in values):
            raise ValueError("When exact_cases=True, `values` must be a list of dictionaries.")

        for case in values:
            if not case:
                raise ValueError("Empty dictionary found in values.")
            for key in case:
                if key not in obs_keys:
                    raise ValueError(f"Field '{key}' not found in adata.obs.")

        query = " | ".join([
            " & ".join([
                f"(adata.obs['{k}'] == '{v}')" for k, v in case.items()
            ])
            for case in values
        ])

    else:
        if not isinstance(values, dict):
            raise ValueError("When exact_cases=False, `values` must be a dictionary.")

        for key in values:
            if key not in obs_keys:
                raise ValueError(f"Field '{key}' not found in adata.obs.")

        query_parts = []
        for k, v in values.items():
            v_list = v if isinstance(v, list) else [v]
            part = " | ".join([f"(adata.obs['{k}'] == '{val}')" for val in v_list])
            query_parts.append(f"({part})")
        query = " & ".join(query_parts)

    if debug:
            print(f"Filter query: {query}")

    if pdata.prot is not None:
        adata = pdata.prot
        pdata.prot = adata[eval(query)]
    if pdata.pep is not None:
        adata = pdata.pep
        pdata.pep = adata[eval(query)]

    if cleanup:
        cleanup_message = pdata._cleanup_proteins_after_sample_filter(verbose=True)
    else:
        cleanup_message = None
    pdata.update_summary(recompute=False, verbose=False) # type: ignore[attr-defined], SummaryMixin

    n_samples = len(pdata.prot)
    log_prefix = format_log_prefix("user")
    filter_mode = "exact match" if exact_cases else "class match"

    if n_samples == 0:
        message = (
            f"{log_prefix} Filtering samples [{filter_mode}]:\n"
            f"    → No matching samples found. No filtering applied."
        )
    else:
        message = (
            f"{log_prefix} Filtering samples [{filter_mode}]:\n"
            f"    {'Returning a copy of' if return_copy else 'Filtered and modified'} sample data based on {filter_mode}:\n"
        )

        if exact_cases:
            message += f"{format_log_prefix('filter_conditions')}Matching any of the following cases:\n"
            for i, case in enumerate(values, 1):
                message += f"       {i}. {case}\n"
        else:
            message += "   🔸 Match samples where:\n"
            for k, v in values.items():
                valstr = v if isinstance(v, str) else ", ".join(map(str, v))
                message += f"      - {k}: {valstr}\n"

        message += cleanup_message + "\n" if cleanup_message else ""
        message += f"    → Samples kept: {n_samples}, Samples dropped: {orig_sample_count - n_samples}"
        message += f"\n    → Proteins kept: {len(pdata.prot.var)}\n"

    print(message) if verbose else None
    pdata._append_history(message) # type: ignore[attr-defined], HistoryMixin

    return pdata

_filter_sample_query

_filter_sample_query(
    query_string,
    source="obs",
    cleanup=True,
    return_copy=True,
    debug=False,
)

Filter samples using a raw pandas-style query string on .obs or .summary.

This method allows advanced filtering of samples using logical expressions evaluated directly on the sample metadata.

Parameters:

Name Type Description Default
query_string str

A pandas-style query string. Example: "cellline == 'AS' and treatment in ['kd', 'sc']".

required
source str

The metadata source to query — either "obs" or "summary".

'obs'
cleanup bool

If True (default), remove proteins that become all-NaN or all-zero after sample filtering and synchronize RS/peptide matrices. Set to False to retain all proteins for consistent feature alignment (e.g. during DE analysis).

True
return_copy bool

If True, returns a filtered pAnnData object; otherwise modifies in place.

True
debug bool

If True, prints the parsed query and debug messages.

False

Returns:

Name Type Description
pAnnData

Filtered pAnnData object if return_copy=True; otherwise, modifies in place and returns None.

Source code in src/scpviz/pAnnData/filtering.py
def _filter_sample_query(self, query_string, source='obs', cleanup=True, return_copy=True, debug=False):
    """
    Filter samples using a raw pandas-style query string on `.obs` or `.summary`.

    This method allows advanced filtering of samples using logical expressions evaluated 
    directly on the sample metadata.

    Args:
        query_string (str): A pandas-style query string. 
            Example: `"cellline == 'AS' and treatment in ['kd', 'sc']"`.
        source (str): The metadata source to query — either `"obs"` or `"summary"`.
        cleanup (bool): If True (default), remove proteins that become all-NaN or all-zero
            after sample filtering and synchronize RS/peptide matrices. Set to False to
            retain all proteins for consistent feature alignment (e.g. during DE analysis).
        return_copy (bool): If True, returns a filtered pAnnData object; otherwise modifies in place.
        debug (bool): If True, prints the parsed query and debug messages.

    Returns:
        pAnnData: Filtered pAnnData object if `return_copy=True`; otherwise, modifies in place and returns None.
    """
    pdata = self.copy() if return_copy else self # type: ignore[attr-defined], EditingMixin
    action = "Returning a copy of" if return_copy else "Filtered and modified"
    orig_sample_count = len(pdata.prot.obs)

    print(f"{format_log_prefix('warn',indent=1)} Advanced query mode enabled — interpreting string as a pandas-style expression.")

    if source == 'obs':
        df = pdata.prot.obs
    elif source == 'summary':
        if self._summary is None: # type: ignore[attr-defined]
            self.update_summary(recompute=True) # type: ignore[attr-defined], SummaryMixin
        df = pdata._summary # type: ignore[attr-defined]
    else:
        raise ValueError("source must be 'obs' or 'summary'")

    try:
        filtered_df = df.query(query_string)
    except Exception as e:
        raise ValueError(f"Failed to parse query string:\n  {query_string}\nError: {e}")

    index_filter = filtered_df.index

    if pdata.prot is not None:
        pdata.prot = pdata.prot[pdata.prot.obs_names.isin(index_filter)]
    if pdata.pep is not None:
        pdata.pep = pdata.pep[pdata.pep.obs_names.isin(index_filter)]

    if cleanup:
        cleanup_message = pdata._cleanup_proteins_after_sample_filter(verbose=True)
    else:
        cleanup_message = None
    pdata.update_summary(recompute=False, verbose=False) # type: ignore[attr-defined], SummaryMixin

    n_samples = len(pdata.prot)
    log_prefix = format_log_prefix("user")
    action = "Returning a copy of" if return_copy else "Filtered and modified"

    message = (
        f"{log_prefix} Filtering samples [query]:\n"
        f"    {action} sample data based on query string:\n"
        f"   🔸 Query: {query_string}\n"
    )

    if cleanup_message:
        message += f"{cleanup_message}\n"

    message += (
        f"    → Samples kept: {n_samples}, Samples dropped: {orig_sample_count - n_samples}\n"
        f"    → Proteins kept: {len(pdata.prot.var)}\n"
    )

    print(message)

    history_message = f"{action} samples based on query string. Samples kept: {len(index_filter)}."
    pdata._append_history(history_message) # type: ignore[attr-defined], HistoryMixin

    return pdata if return_copy else None

_cleanup_proteins_after_sample_filter

_cleanup_proteins_after_sample_filter(
    verbose=True, printout=False
)

Internal helper to remove proteins that became all-NaN or all-zero after sample filtering. Called silently by filter_sample().

Ensures the RS matrix and peptide table are synchronized after cleanup. Called automatically by filter_sample() and during import.

Parameters:

Name Type Description Default
verbose bool

If True, returns a cleanup summary message. If False, runs silently.

True
printout bool

If True and verbose=True, directly prints the cleanup mesage.

False

Returns:

Type Description

str or None: Cleanup message if verbose=True and any proteins removed, otherwise None.

Source code in src/scpviz/pAnnData/filtering.py
def _cleanup_proteins_after_sample_filter(self, verbose=True, printout=False):
    """
    Internal helper to remove proteins that became all-NaN or all-zero
    after sample filtering. Called silently by `filter_sample()`.

    Ensures the RS matrix and peptide table are synchronized after cleanup.
    Called automatically by `filter_sample()` and during import.        

    Args:
        verbose (bool): If True, returns a cleanup summary message.
                        If False, runs silently.
        printout (bool): If True and verbose=True, directly prints the cleanup mesage.

    Returns:
        str or None: Cleanup message if verbose=True and any proteins removed,
                    otherwise None.
    """
    from scipy.sparse import issparse

    if not self._check_data("protein"):  # type: ignore[attr-defined]
        return

    X = self.prot.X.toarray() if issparse(self.prot.X) else self.prot.X
    original_var_names = self.prot.var_names.copy()
    all_nan = np.all(np.isnan(X), axis=0)
    all_zero = np.all(X == 0, axis=0)
    remove_mask = all_nan | all_zero

    if not remove_mask.any():
        if verbose:
            return f"{format_log_prefix('info_only',2)} Auto-cleanup: No empty proteins found (all-NaN or all-zero)."
        else:
            return None

    n_remove = int(remove_mask.sum())
    keep_mask = ~remove_mask

    # skip cleanup entirely if no samples or no protein data remain
    if self.prot is None or self.prot.n_obs == 0 or self.prot.n_vars == 0:
        if verbose:
            return f"{format_log_prefix('warn_only',2)} No samples or proteins to clean up. Skipping RS sync."
        return None

    # Filter protein data
    self.prot = self.prot[:, keep_mask].copy()

    if self.pep is not None and self.rs is not None:
        proteins_to_keep, peptides_to_keep, orig_prot_names, orig_pep_names = self._filter_sync_peptides_to_proteins(
            orig_prot_names=original_var_names,
            updated_prot=self.prot,
            debug=False
        )

        self._apply_rs_filter(
            keep_proteins=proteins_to_keep,
            keep_peptides=peptides_to_keep,
            orig_prot_names=orig_prot_names,
            orig_pep_names=orig_pep_names,
            debug=False
        )

    self.update_summary(recompute=True, verbose=False)

    if verbose:            
        removed_proteins = list(original_var_names[remove_mask])
        preview = ", ".join(removed_proteins[:10])
        if n_remove > 10:
            preview += ", ..."

        if printout and n_remove>0:
            # for startup
            print(f"{format_log_prefix('info_only',1)} Removed {n_remove} empty proteins (all-NaN or all-zero). Proteins: {preview}")
        else:
            # for filter
            return(f"{format_log_prefix('info_only',2)} Auto-cleanup: Removed {n_remove} empty proteins (all-NaN or all-zero). Proteins: {preview}")

    return None

_apply_rs_filter

_apply_rs_filter(
    keep_proteins=None,
    keep_peptides=None,
    orig_prot_names=None,
    orig_pep_names=None,
    debug=True,
)

Apply filtering to .prot, .pep, and .rs based on protein/peptide masks or name lists.

This method filters the relational structure (RS matrix) and associated data objects by retaining only the specified proteins and/or peptides. Original axis names can be provided to ensure correct alignment after prior filtering steps.

Parameters:

Name Type Description Default
keep_proteins list or np.ndarray or bool array

List of protein names or boolean mask indicating which proteins (RS matrix rows) to keep.

None
keep_peptides list or np.ndarray or bool array

List of peptide names or boolean mask indicating which peptides (RS matrix columns) to keep.

None
orig_prot_names list or ndarray

Original protein names corresponding to RS matrix rows.

None
orig_pep_names list or ndarray

Original peptide names corresponding to RS matrix columns.

None
debug bool

If True, prints filtering details and index alignment diagnostics.

True

Returns:

Type Description

None

str

Source code in src/scpviz/pAnnData/filtering.py
def _apply_rs_filter(
    self,
    keep_proteins=None,
    keep_peptides=None,
    orig_prot_names=None,
    orig_pep_names=None,
    debug=True
):
    """
    Apply filtering to `.prot`, `.pep`, and `.rs` based on protein/peptide masks or name lists.

    This method filters the relational structure (RS matrix) and associated data objects by retaining
    only the specified proteins and/or peptides. Original axis names can be provided to ensure correct
    alignment after prior filtering steps.

    Args:
        keep_proteins (list or np.ndarray or bool array, optional): List of protein names or boolean mask 
            indicating which proteins (RS matrix rows) to keep.
        keep_peptides (list or np.ndarray or bool array, optional): List of peptide names or boolean mask 
            indicating which peptides (RS matrix columns) to keep.
        orig_prot_names (list or np.ndarray, optional): Original protein names corresponding to RS matrix rows.
        orig_pep_names (list or np.ndarray, optional): Original peptide names corresponding to RS matrix columns.
        debug (bool): If True, prints filtering details and index alignment diagnostics.

    Returns:
        None
        str
    """

    if self.rs is None: # type: ignore[attr-defined]
        raise ValueError("No RS matrix to filter.")

    from scipy.sparse import issparse

    rs = self.rs # type: ignore[attr-defined]

    # Use provided names or fallback to current .prot/.pep
    prot_names = np.array(orig_prot_names) if orig_prot_names is not None else np.array(self.prot.var_names)
    pep_names = np.array(orig_pep_names) if orig_pep_names is not None else np.array(self.pep.var_names)

    if rs.shape[0] != len(prot_names) or rs.shape[1] != len(pep_names):
        raise ValueError(
            f"RS shape {rs.shape} does not match provided protein/peptide names "
            f"({len(prot_names)} proteins, {len(pep_names)} peptides). "
            "Did you forget to pass the original names?"
        )

    # --- Normalize protein mask ---
    if keep_proteins is None:
        prot_mask = np.ones(rs.shape[0], dtype=bool)
    elif isinstance(keep_proteins, (list, np.ndarray, pd.Index)) and isinstance(keep_proteins[0], str):
        keep_set = set(keep_proteins)
        prot_mask = np.fromiter((p in keep_set for p in prot_names), dtype=bool)
    elif isinstance(keep_proteins, (list, np.ndarray)) and isinstance(keep_proteins[0], (bool, np.bool_)):
        prot_mask = np.asarray(keep_proteins)
    else:
        raise TypeError("keep_proteins must be a list of str or a boolean mask.")

    # --- Normalize peptide mask ---
    if keep_peptides is None:
        pep_mask = np.ones(rs.shape[1], dtype=bool)
    elif isinstance(keep_peptides, (list, np.ndarray, pd.Index)) and isinstance(keep_peptides[0], str):
        keep_set = set(keep_peptides)
        pep_mask = np.fromiter((p in keep_set for p in pep_names), dtype=bool)
    elif isinstance(keep_peptides, (list, np.ndarray)) and isinstance(keep_peptides[0], (bool, np.bool_)):
        pep_mask = np.asarray(keep_peptides)
    else:
        raise TypeError("keep_peptides must be a list of str or a boolean mask.")

    # --- Final safety check ---
    if len(prot_mask) != rs.shape[0] or len(pep_mask) != rs.shape[1]:
        raise ValueError("Mismatch between mask lengths and RS matrix dimensions.")

    # --- Apply to RS ---
    self._set_RS(rs[prot_mask, :][:, pep_mask], validate=False) # type: ignore[attr-defined], EditingMixin

    # --- Apply to .prot and .pep ---
    kept_prot_names = np.array(orig_prot_names)[prot_mask]
    kept_pep_names = np.array(orig_pep_names)[pep_mask]

    if self.prot is not None:
        self.prot = self.prot[:, self.prot.var_names.isin(kept_prot_names)]

    if self.pep is not None:
        self.pep = self.pep[:, self.pep.var_names.isin(kept_pep_names)]

    if debug:
        print(f"{format_log_prefix('result')} RS matrix filtered: {prot_mask.sum()} proteins, {pep_mask.sum()} peptides retained.")
    else:
        return(f"{format_log_prefix('result')} RS matrix filtered: {prot_mask.sum()} proteins, {pep_mask.sum()} peptides retained.")

_format_filter_query

_format_filter_query(condition, dataframe)

Format a condition string for safe evaluation on a DataFrame with complex column names.

This method prepares a query string for use with pandas.eval() or .query() by: - Wrapping column names containing spaces or special characters in backticks. - Converting custom includes syntax (for substring matching) into .str.contains(...) expressions. - Quoting unquoted string values automatically for object/category columns.

Parameters:

Name Type Description Default
condition str

The condition string to parse and format.

required
dataframe DataFrame

The DataFrame whose column names and dtypes are used for formatting.

required

Returns:

Name Type Description
str

A cleaned and properly formatted condition string suitable for .eval() or .query().

Note

This is an internal helper used by methods such as filter_sample_condition() and filter_prot() to support user-friendly string-based queries.

Source code in src/scpviz/pAnnData/filtering.py
def _format_filter_query(self, condition, dataframe):
    """
    Format a condition string for safe evaluation on a DataFrame with complex column names.

    This method prepares a query string for use with `pandas.eval()` or `.query()` by:
    - Wrapping column names containing spaces or special characters in backticks.
    - Converting custom `includes` syntax (for substring matching) into `.str.contains(...)` expressions.
    - Quoting unquoted string values automatically for object/category columns.

    Args:
        condition (str): The condition string to parse and format.
        dataframe (pd.DataFrame): The DataFrame whose column names and dtypes are used for formatting.

    Returns:
        str: A cleaned and properly formatted condition string suitable for `.eval()` or `.query()`.

    Note:
        This is an internal helper used by methods such as `filter_sample_condition()` and `filter_prot()` 
        to support user-friendly string-based queries.
    """

    # Wrap column names with backticks if needed
    column_names = dataframe.columns.tolist()
    column_names.sort(key=len, reverse=True) # Avoid partial matches

    for col in column_names:
        if re.search(r'[^\\w]', col):  # Non-alphanumeric characters
            condition = re.sub(fr'(?<!`)({re.escape(col)})(?!`)', f'`{col}`', condition)

    # Handle 'includes' syntax for substring matching
    match = re.search(r'`?(\w[\w\s:.-]*)`?\s+includes\s+[\'"]([^\'"]+)[\'"]', condition)
    if match:
        col_name = match.group(1)
        substring = match.group(2)
        condition = f"{col_name}.str.contains('{substring}', case=False, na=False)"

    # Auto-quote string values for categorical/text columns
    for col in dataframe.columns:
        if dataframe[col].dtype.name in ["object", "category"]:
            for op in ["==", "!="]:
                pattern = fr"(?<![><=!])\b{re.escape(col)}\s*{op}\s*([^\s'\"()]+)"
                matches = re.findall(pattern, condition)
                for match_val in matches:
                    quoted_val = f'"{match_val}"'
                    condition = re.sub(fr"({re.escape(col)}\s*{op}\s*){match_val}\b", r"\1" + quoted_val, condition)

    return condition

_annotate_found_samples

_annotate_found_samples(threshold=0.0, layer='X')

Annotate proteins and peptides with per-sample 'Found In' flags.

For each sample, this method adds boolean indicators to .prot.var and .pep.var indicating whether the feature was detected (i.e. exceeds the given threshold).

Parameters:

Name Type Description Default
threshold float

Minimum value to consider a feature as "found" (default is 0.0).

0.0
layer str

Name of the data layer to evaluate (e.g., "X", "imputed", etc.).

'X'

Returns:

Type Description

None

Note

This is an internal helper used to support downstream grouping-based detection (e.g., in annotate_found_in()). Adds new columns to .var of the form: 'Found In: <sample>' → bool.

Source code in src/scpviz/pAnnData/filtering.py
def _annotate_found_samples(self, threshold=0.0, layer='X'):
    """
    Annotate proteins and peptides with per-sample 'Found In' flags.

    For each sample, this method adds boolean indicators to `.prot.var` and `.pep.var` 
    indicating whether the feature was detected (i.e. exceeds the given threshold).

    Args:
        threshold (float): Minimum value to consider a feature as "found" (default is 0.0).
        layer (str): Name of the data layer to evaluate (e.g., "X", "imputed", etc.).

    Returns:
        None

    Note:
        This is an internal helper used to support downstream grouping-based detection 
        (e.g., in `annotate_found_in()`).
        Adds new columns to `.var` of the form: `'Found In: <sample>' → bool`.
    """
    for level in ['prot', 'pep']:
        adata = getattr(self, level)
        # Skip if the level doesn't exist
        if adata is None:
            continue

        # Handle layer selection
        if layer == 'X':
            data = pd.DataFrame(adata.X.toarray() if hasattr(adata.X, 'toarray') else adata.X,
                                index=adata.obs_names,
                                columns=adata.var_names).T
        elif layer in adata.layers:
            data = pd.DataFrame(adata.layers[layer].toarray() if hasattr(adata.layers[layer], 'toarray') else adata.layers[layer],
                                index=adata.obs_names,
                                columns=adata.var_names).T
        else:
            raise KeyError(f"Layer '{layer}' not found in {level}.layers and is not 'X'.")

        found = data > threshold
        for sample in found.columns:
            adata.var[f"Found In: {sample}"] = found[sample]

_annotate_significant_samples

_annotate_significant_samples(fdr_threshold=0.01)

Annotate proteins and peptides with per-sample 'Significant In' flags.

For each sample, this method adds boolean indicators to .prot.var and .pep.var indicating whether the feature is significantly detected (i.e. FDR < threshold).

Parameters:

Name Type Description Default
fdr_threshold float

FDR threshold for significance (default: 0.01).

0.01

Returns:

Type Description

None

Note

This is an internal helper used to support downstream grouping-based annotation. Adds new columns to .var of the form: 'Significant In: <sample>' → bool.

Source code in src/scpviz/pAnnData/filtering.py
def _annotate_significant_samples(self, fdr_threshold=0.01):
    """
    Annotate proteins and peptides with per-sample 'Significant In' flags.

    For each sample, this method adds boolean indicators to `.prot.var` and `.pep.var`
    indicating whether the feature is significantly detected (i.e. FDR < threshold).

    Args:
        fdr_threshold (float): FDR threshold for significance (default: 0.01).

    Returns:
        None

    Note:
        This is an internal helper used to support downstream grouping-based annotation.
        Adds new columns to `.var` of the form: `'Significant In: <sample>' → bool`.
    """
    for level in ['prot', 'pep']:
        adata = getattr(self, level)
        if adata is None:
            continue

        if "Global_Q_value" in adata.var.columns:
            adata.var["Significant In: Global"] = adata.var["Global_Q_value"] < fdr_threshold

        sig_layer = 'X_qval'
        if sig_layer not in adata.layers:
            # Fallback to global q-values if available
            print(f"{format_log_prefix('info', 2)} Using global q-values for '{level}' significance annotation.")
            continue  # Skip if significance data not available

        print(f"{format_log_prefix('info', 2)} Using sample-specific q-values for '{level}' significance annotation.")

        data = pd.DataFrame(
            adata.layers[sig_layer].toarray() if hasattr(adata.layers[sig_layer], 'toarray') else adata.layers[sig_layer],
            index=adata.obs_names,
            columns=adata.var_names).T  # features × samples

        significant = data < fdr_threshold
        sig_df = significant.add_prefix("Significant In: ")
        adata.var = pd.concat([adata.var, sig_df], axis=1)

history

Mixin for tracking the history of operations performed on a pAnnData object.

This mixin provides simple utilities to log and review transformations or analysis steps performed on the data object. Each action is stored as a string in the internal _history list.

Features:

  • Track transformations or analysis steps as text entries
  • Print chronological history of actions performed

Methods:

Name Description
_append_history

Add a custom string to the internal history list

print_history

Print the full history in a formatted list

Source code in src/scpviz/pAnnData/history.py
class HistoryMixin:
    """
    Mixin for tracking the history of operations performed on a pAnnData object.

    This mixin provides simple utilities to log and review transformations or
    analysis steps performed on the data object. Each action is stored as a 
    string in the internal `_history` list.

    Features:

    - Track transformations or analysis steps as text entries
    - Print chronological history of actions performed

    Functions:
        _append_history: Add a custom string to the internal history list  
        print_history: Print the full history in a formatted list
    """
    def _append_history(self: HasHistory, action):
        """
        Append a timestamped entry to the internal transformation history log.

        Each entry records the current date and time alongside a string description 
        of the action performed. Useful for tracking the sequence and timing of 
        transformations on the pAnnData object.

        Args:
            action (str): Description of the action performed.
        """
        timestamp = datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
        self._history.append(f"{timestamp} {action}")

    def print_history(self: HasHistory): 
        """
        Print the current transformation history in a numbered format.

        Each logged action is printed with its index, showing the chronological
        sequence of operations applied to the object.
        """
        formatted_history = "\n".join(f"{i}: {action}" for i, action in enumerate(self._history, 1))
        print("-------------------------------\nHistory:\n-------------------------------\n" + formatted_history)

_append_history

_append_history(action)

Append a timestamped entry to the internal transformation history log.

Each entry records the current date and time alongside a string description of the action performed. Useful for tracking the sequence and timing of transformations on the pAnnData object.

Parameters:

Name Type Description Default
action str

Description of the action performed.

required
Source code in src/scpviz/pAnnData/history.py
def _append_history(self: HasHistory, action):
    """
    Append a timestamped entry to the internal transformation history log.

    Each entry records the current date and time alongside a string description 
    of the action performed. Useful for tracking the sequence and timing of 
    transformations on the pAnnData object.

    Args:
        action (str): Description of the action performed.
    """
    timestamp = datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
    self._history.append(f"{timestamp} {action}")

identifier

Handles mapping between genes, accessions, and peptides.

This mixin provides utilities for:

  • Building and caching bidirectional mappings:

    • For proteins: gene ↔ accession
    • For peptides: peptide ↔ protein accession
  • Updating or refreshing identifier maps manually or via UniProt

  • Automatically filling in missing gene names using the UniProt API

These mappings are cached and used throughout the pAnnData object to support resolution of user queries and consistent gene-accession-peptide tracking.

Methods:

Name Description
_build_identifier_maps

Create forward/reverse maps based on protein or peptide data

refresh_identifier_maps

Clear cached mappings to force rebuild

get_identifier_maps

Retrieve (gene → acc, acc → gene) or (peptide ↔ protein) maps

update_identifier_maps

Add or overwrite mappings (e.g., manual corrections)

update_missing_genes

Fill missing gene names using the UniProt API

Source code in src/scpviz/pAnnData/identifier.py
  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
class IdentifierMixin:
    """
    Handles mapping between genes, accessions, and peptides.

    This mixin provides utilities for:

    - Building and caching bidirectional mappings:
        * For proteins: gene ↔ accession  
        * For peptides: peptide ↔ protein accession

    - Updating or refreshing identifier maps manually or via UniProt
    - Automatically filling in missing gene names using the UniProt API

    These mappings are cached and used throughout the `pAnnData` object to support resolution of user queries and consistent gene-accession-peptide tracking.

    Functions:
        _build_identifier_maps: Create forward/reverse maps based on protein or peptide data
        refresh_identifier_maps: Clear cached mappings to force rebuild
        get_identifier_maps: Retrieve (gene → acc, acc → gene) or (peptide ↔ protein) maps
        update_identifier_maps: Add or overwrite mappings (e.g., manual corrections)
        update_missing_genes: Fill missing gene names using the UniProt API
    """

    def _build_identifier_maps(self, adata, gene_col="Genes"):
        """
        Build bidirectional identifier mappings for genes/proteins or peptides/proteins.

        Depending on whether `adata` is `.prot` or `.pep`, this builds:

        - For proteins: gene ↔ accession
        - For peptides: peptide ↔ protein accession

        Args:
            adata (AnnData): Either `self.prot` or `self.pep`.
            gene_col (str): Column name in `.var` containing gene names (default: "Genes").

        Returns:
            tuple: A pair of dictionaries (`forward`, `reverse`) for identifier lookup.

        Note:
            For peptides, mapping relies on `utils.get_pep_prot_mapping()` to resolve protein accessions.

        Raises:
            Warning if peptide-to-protein mapping cannot be built.
        """
        from pandas import notna

        forward = {}
        reverse = {}

        if adata is self.prot:
            if gene_col in adata.var.columns:
                for acc, gene in zip(adata.var_names, adata.var[gene_col]):
                    if notna(gene):
                        gene = str(gene)
                        forward[gene] = acc
                        reverse[acc] = gene

        elif adata is self.pep:
            try:
                prot_acc_col = utils.get_pep_prot_mapping(self)
                pep_to_prot = adata.var[prot_acc_col]
                for pep, prot in zip(adata.var_names, pep_to_prot):
                    if notna(prot):
                        forward[prot] = pep
                        reverse[pep] = prot
            except Exception as e:
                warnings.warn(f"Could not build peptide-to-protein map: {e}")

        return forward, reverse

    def refresh_identifier_maps(self):
        """
        Clear cached identifier maps to force regeneration on next access.

        This removes the following attributes if present:

        - `_gene_maps_protein`: Gene ↔ Accession map for proteins
        - `_protein_maps_peptide`: Protein ↔ Peptide map for peptides

        Useful when `.var` annotations are updated and identifier mappings may have changed.
        """
        for attr in ["_gene_maps_protein", "_protein_maps_peptide"]:
            if hasattr(self, attr):
                delattr(self, attr)

    def get_identifier_maps(self, on='protein'):
        """
        Retrieve gene/accession or peptide/protein mapping dictionaries.

        Depending on the `on` argument, returns a tuple of forward and reverse mappings:

        - If `on='protein'`: (gene → accession, accession → gene)

        - If `on='peptide'`: (protein accession → peptide, peptide → protein accession)

        Note: Alias `get_gene_maps()` also calls this function for compatibility.

        Args:
            on (str): Source of mapping. Must be `'protein'` or `'peptide'`.

        Returns:
            Tuple[dict, dict]: (forward mapping, reverse mapping)

        Raises:
            ValueError: If `on` is not `'protein'` or `'peptide'`.
        """
        if on in ('protein','prot'):
            return self._cached_identifier_maps_protein
        elif on in ('peptide','pep'):
            return self._cached_identifier_maps_peptide
        else:
            raise ValueError(f"Invalid value for 'on': {on}. Must be 'protein' or 'peptide'.")

    # TODO: add peptide remapping to var, but need to also update rs if you do this.
    def update_identifier_maps(self, mapping, on='protein', direction='forward', overwrite=False, verbose=True):
        """
        Update cached identifier maps with user-supplied mappings.

        This function updates the internal forward and reverse identifier maps
        for either proteins or peptides. Ensures consistency by updating both
        directions of the mapping.

        - For `'protein'`:
            * forward: gene → accession  
            * reverse: accession → gene

        - For `'peptide'`:
            * forward: protein accession → peptide
            * reverse: peptide → protein accession

        Args:
            mapping (dict): Dictionary of mappings to add.
            on (str): Which maps to update. Must be `'protein'` or `'peptide'`.
            direction (str): `'forward'` or `'reverse'` — determines how the `mapping` should be interpreted.
            overwrite (bool): If True, allows overwriting existing entries.
            verbose (bool): If True, prints a summary of updated keys.

        Note:
            The corresponding reverse map is automatically updated to maintain bidirectional consistency.

        Example:
            Add new gene-to-accession mappings (protein):
                ```python
                pdata.update_identifier_maps(
                    {'MYGENE1': 'P00001', 'MYGENE2': 'P00002'},
                    on='protein',
                    direction='forward'
                )
                ```

            Add peptide → protein mappings:
                ```python
                pdata.update_identifier_maps(
                    {'PEPTIDE_ABC': 'P12345'},
                    on='peptide',
                    direction='reverse'
                )
                ```

            Overwrite a protein → gene mapping:
                ```python
                pdata.update_identifier_maps(
                    {'P12345': 'NEWGENE'},
                    on='protein',
                    direction='reverse',
                    overwrite=True
                )
                ```

        """
        if on == 'protein':
            forward, reverse = self._cached_identifier_maps_protein
        elif on == 'peptide':
            forward, reverse = self._cached_identifier_maps_peptide
        else:
            raise ValueError(f"Invalid value for 'on': {on}. Must be 'protein' or 'peptide'.")

        source_map = forward if direction == 'forward' else reverse
        target_map = reverse if direction == 'forward' else forward

        added, updated, skipped = 0, 0, 0

        for key, val in mapping.items():
            if key in source_map:
                if overwrite:
                    source_map[key] = val
                    target_map[val] = key
                    updated += 1
                else:
                    skipped += 1
            else:
                source_map[key] = val
                target_map[val] = key
                added += 1

        message = (
            f"[update_identifier_maps] Updated '{on}' ({direction}): "
            f"{added} added, {updated} overwritten, {skipped} skipped."
        )

        if verbose:
            print(message)
        self._append_history(message)

        # Update .prot.var["Genes"] if updating protein identifier reverse map (accession → gene)
        if on == 'protein' and direction == 'reverse':
            updated_var_count = 0
            updated_accessions = []

            for acc, gene in mapping.items():
                if acc in self.prot.var_names:
                    self.prot.var.at[acc, "Genes"] = gene
                    updated_accessions.append(acc)
                    updated_var_count += 1

            if updated_var_count > 0:
                var_message = (
                    f"🔁 Updated `.prot.var['Genes']` for {updated_var_count} entries from custom mapping. "
                    f"(View details in `pdata.metadata['identifier_map_history']`)"
                )
                if verbose:
                    print(var_message)
                self._append_history(var_message)

        # Log detailed update history for all cases
        import datetime

        record = {
            'on': on,
            'direction': direction,
            'input_mapping': dict(mapping),  # shallow copy
            'overwrite': overwrite,
            'timestamp': datetime.datetime.now().isoformat(timespec='seconds'),
            'summary': {
                'added': added,
                'updated': updated,
                'skipped': skipped,
            }
        }

        if on == 'protein' and direction == 'reverse':
            record['updated_var_column'] = {
                'column': 'Genes',
                'accessions': updated_accessions,
                'n_updated': updated_var_count
            }

        self.metadata.setdefault("identifier_map_history", []).append(record)

    get_gene_maps = get_identifier_maps

    def update_missing_genes(self, gene_col="Genes", verbose=True):
        """
        Fill missing gene names in `.prot.var` using UniProt API.

        This function searches for missing values in the specified gene column
        and attempts to fill them by querying the UniProt API using protein
        accession IDs. If a gene name cannot be found, a placeholder
        'UNKNOWN_<accession>' is used instead.

        Args:
            gene_col (str): Column name in `.prot.var` to update (default: "Genes").
            verbose (bool): Whether to print summary information (default: True).

        Returns:
            None

        Note:
            - This function only operates on `.prot.var`, not `.pep.var`.
            - If UniProt is unavailable or returns no match, the missing entry is filled as `'UNKNOWN_<accession>'`.
            - To manually correct unknown entries later, use `update_identifier_maps()` with `direction='reverse'`.

        Example:
            Automatically fill missing gene names using UniProt:
                ```python
                pdata.update_missing_genes()
                ```
        """
        var = self.prot.var

        if gene_col not in var.columns:
            if verbose:
                print(f"{format_log_prefix('warn')} Column '{gene_col}' not found in .prot.var.")
            return

        missing_mask = var[gene_col].isna()
        if not missing_mask.any():
            if verbose:
                print(f"{format_log_prefix('result')} No missing gene names found.")
            return

        accessions = var.index[missing_mask].tolist()
        if verbose:
            print(f"{format_log_prefix('info_only')} {len(accessions)} proteins with missing gene names.")

        try:
            df = utils.get_uniprot_fields(
                accessions,
                search_fields=["accession", "gene_primary"],
                standardize=True
            )
        except Exception as e:
            print(f"{format_log_prefix('error')} UniProt query failed: {e}")
            return
        df = utils.standardize_uniprot_columns(df)

        if df.empty or "accession" not in df.columns or "gene_primary" not in df.columns:
            print(f"{format_log_prefix('warn')} UniProt returned no usable gene mapping columns.")
            return

        gene_map = dict(zip(df["accession"], df["gene_primary"]))
        filled = self.prot.var.loc[missing_mask].index.map(lambda acc: gene_map.get(acc))
        final_genes = [
            gene if pd.notna(gene) else f"UNKNOWN_{acc}"
            for acc, gene in zip(self.prot.var.loc[missing_mask].index, filled)
        ]
        self.prot.var.loc[missing_mask, gene_col] = final_genes

        found = sum(pd.notna(filled))
        unknown = len(final_genes) - found
        if verbose:
            if found:
                print(f"{format_log_prefix('result')} Recovered {found} gene name(s) from UniProt. Genes found:")
                filled_clean = [str(g) for g in filled if pd.notna(g)]
                preview = ", ".join(filled_clean[:10])
                if found > 10:
                    preview += "..."
                print("        ", preview)
            if unknown:
                missing_ids = self.prot.var.loc[missing_mask].index[pd.isna(filled)]
                print(f"{format_log_prefix('warn')} {unknown} gene name(s) still missing. Assigned as 'UNKNOWN_<accession>' for:")
                print("        ", ", ".join(missing_ids[:5]) + ("..." if unknown > 10 else ""))
                print("     💡 Tip: You can update these using `pdata.update_identifier_maps({'GENE': 'ACCESSION'}, on='protein', direction='reverse', overwrite=True)`\n")

    def search_annotations(self, query, on='protein', search_columns=None, case=False, return_all_matches=True):
        """
        Search protein or peptide annotations for matching biological terms.

        This function scans `.prot.var` or `.pep.var` for entries containing the provided keyword(s),
        across common annotation fields.

        Args:
            query (str or list of str): Term(s) to search for (e.g., "keratin", "KRT").
            on (str): Whether to search `"protein"` or `"peptide"` annotations (default: `"protein"`).
            search_columns (list of str, optional): Columns to search in. Defaults to common biological fields.
            case (bool): Case-sensitive search (default: False).
            return_all_matches (bool): If True, return matches from any column. If False, returns only rows that match all terms.

        Returns:
            pd.DataFrame: Filtered dataframe with a `Matched` column (True/False) and optionally match columns per term.

        Example:
            ```python
            pdata.search_annotations("keratin")
            pdata.search_annotations(["keratin", "cytoskeleton"], on="peptide", case=False)
            ```
        """
        import pandas as pd

        adata = self.prot if on == "protein" else self.pep
        df = adata.var.copy()

        if search_columns is None:
            search_columns = [
                "Accession", "Description", "Biological Process", "Cellular Component",
                "Molecular Function", "Genes", "Gene ID", "Reactome Pathways"
            ]

        # Ensure index is available as a searchable column
        df = df.copy()
        df["Accession"] = df.index.astype(str)

        # Convert query to list
        if isinstance(query, str):
            query = [query]

        # Search logic
        def match_func(val, term):
            if pd.isnull(val):
                return False
            return term in val if case else term.lower() in str(val).lower()

        match_results = pd.DataFrame(index=df.index)

        for term in query:
            per_col_match = pd.DataFrame({
                col: df[col].apply(match_func, args=(term,)) if col in df.columns else False
                for col in search_columns
            })
            row_match = per_col_match.any(axis=1)
            match_results[f"Matched_{term}"] = row_match

        if return_all_matches:
            matched_any = match_results.any(axis=1)
        else:
            matched_any = match_results.all(axis=1)

        result_df = df.copy()
        result_df["Matched"] = matched_any
        for col in match_results.columns:
            result_df[col] = match_results[col]

        return result_df[result_df["Matched"]]

_build_identifier_maps

_build_identifier_maps(adata, gene_col='Genes')

Build bidirectional identifier mappings for genes/proteins or peptides/proteins.

Depending on whether adata is .prot or .pep, this builds:

  • For proteins: gene ↔ accession
  • For peptides: peptide ↔ protein accession

Parameters:

Name Type Description Default
adata AnnData

Either self.prot or self.pep.

required
gene_col str

Column name in .var containing gene names (default: "Genes").

'Genes'

Returns:

Name Type Description
tuple

A pair of dictionaries (forward, reverse) for identifier lookup.

Note

For peptides, mapping relies on utils.get_pep_prot_mapping() to resolve protein accessions.

Source code in src/scpviz/pAnnData/identifier.py
def _build_identifier_maps(self, adata, gene_col="Genes"):
    """
    Build bidirectional identifier mappings for genes/proteins or peptides/proteins.

    Depending on whether `adata` is `.prot` or `.pep`, this builds:

    - For proteins: gene ↔ accession
    - For peptides: peptide ↔ protein accession

    Args:
        adata (AnnData): Either `self.prot` or `self.pep`.
        gene_col (str): Column name in `.var` containing gene names (default: "Genes").

    Returns:
        tuple: A pair of dictionaries (`forward`, `reverse`) for identifier lookup.

    Note:
        For peptides, mapping relies on `utils.get_pep_prot_mapping()` to resolve protein accessions.

    Raises:
        Warning if peptide-to-protein mapping cannot be built.
    """
    from pandas import notna

    forward = {}
    reverse = {}

    if adata is self.prot:
        if gene_col in adata.var.columns:
            for acc, gene in zip(adata.var_names, adata.var[gene_col]):
                if notna(gene):
                    gene = str(gene)
                    forward[gene] = acc
                    reverse[acc] = gene

    elif adata is self.pep:
        try:
            prot_acc_col = utils.get_pep_prot_mapping(self)
            pep_to_prot = adata.var[prot_acc_col]
            for pep, prot in zip(adata.var_names, pep_to_prot):
                if notna(prot):
                    forward[prot] = pep
                    reverse[pep] = prot
        except Exception as e:
            warnings.warn(f"Could not build peptide-to-protein map: {e}")

    return forward, reverse

io

_import_proteomeDiscoverer

_import_proteomeDiscoverer(
    prot_file: Optional[str] = None,
    pep_file: Optional[str] = None,
    obs_columns: Optional[List[str]] = ["sample"],
    **kwargs
)
Source code in src/scpviz/pAnnData/io.py
def _import_proteomeDiscoverer(prot_file: Optional[str] = None, pep_file: Optional[str] = None, obs_columns: Optional[List[str]] = ['sample'], **kwargs):
    fetch_uniprot = kwargs.pop("fetch_uniprot", True)

    if not prot_file and not pep_file:
        raise ValueError(f"{format_log_prefix('error')} At least one of prot_file or pep_file must be provided to function. Try prot_file='proteome_discoverer_prot.txt' or pep_file='proteome_discoverer_pep.txt'.")
    print("--------------------------\nStarting import [Proteome Discoverer]\n")

    if prot_file:
        # -----------------------------
        print(f"Source file: {prot_file} / {pep_file}")
        # PROTEIN DATA
        # check file format, if '.txt' then use read_csv, if '.xlsx' then use read_excel
        if prot_file.endswith('.txt') or prot_file.endswith('.tsv'):
            prot_all = pd.read_csv(prot_file, sep='\t')
        elif prot_file.endswith('.xlsx'):
            print("💡 Tip: The read_excel function is slower compared to reading .tsv or .txt files. For improved performance, consider converting your data to .tsv or .txt format.")
            prot_all = pd.read_excel(prot_file)
        # prot_X: sparse data matrix
        prot_X = sparse.csr_matrix(prot_all.filter(regex='Abundance: F', axis=1).values).transpose()
        # prot_layers['mbr']: protein MBR identification
        prot_layers_mbr = prot_all.filter(regex='Found in Sample', axis=1).values.transpose()
        # prot_var_names: protein names
        prot_var_names = prot_all['Accession'].values
        # prot_var: protein metadata
        used_patterns = [
            r'^Abundance: F',           # sample abundance columns (if any)
            r'^Found In',               # found-in sample flags
            r'^Significant In',         # significance flags
            r'^Ratio:',                 # ratio columns (if PD quant ratios exist)
            r'^Abundances \(Grouped\)', # grouped abundance or CV fields
        ]

        exclude_cols = prot_all.filter(regex='|'.join(used_patterns), axis=1).columns
        prot_var = prot_all.drop(columns=exclude_cols, errors='ignore').copy()        

        if 'Exp. q-value: Combined' in prot_all.columns:
            prot_var['Exp. q-value: Combined'] = prot_all['Exp. q-value: Combined']
        elif 'Exp. Protein Group q-value: Combined' in prot_all.columns:
            prot_var['Exp. q-value: Combined'] = prot_all['Exp. Protein Group q-value: Combined']
        else:
            warnings.warn("⚠️ Neither 'Exp. q-value: Combined' nor 'Exp. Protein Group q-value: Combined' found in input file.")

        prot_var.rename(columns={
            'Gene Symbol': 'Genes',
            'Exp. q-value: Combined': 'Global_Q_value',
            '# Unique Peptides': 'unique_peptides'
        }, inplace=True)
        # prot_obs_names: file names
        prot_obs_names = prot_all.filter(regex='Abundance: F', axis=1).columns.str.extract(r'Abundance: (F\d+):')[0].values
        # prot_obs: sample typing from the column name, drop column if all 'n/a'
        prot_obs = prot_all.filter(regex='Abundance: F', axis=1).columns.str.extract(r'Abundance: F\d+: (.+)$')[0].values
        prot_obs = pd.DataFrame(prot_obs, columns=['metadata'])['metadata'] \
            .str.split(',', expand=True)
        prot_obs = _safe_strip(prot_obs).astype('category')

        if (prot_obs == "n/a").all().any():
            print(f"{format_log_prefix('warn')} Found columns with all 'n/a'. Dropping these columns.")
            prot_obs = prot_obs.loc[:, ~(prot_obs == "n/a").all()]

        print(f"Number of files: {len(prot_obs_names)}")
        print(f"Proteins: {len(prot_var)}")
    else:
        prot_X = prot_layers_mbr = prot_var_names = prot_var = prot_obs_names = prot_obs = None

    if pep_file:
        # -----------------------------
        # PEPTIDE DATA
        if pep_file.endswith('.txt') or pep_file.endswith('.tsv'):
            pep_all = pd.read_csv(pep_file, sep='\t')
        elif pep_file.endswith('.xlsx'):
            print(f"{format_log_prefix('warn')} The read_excel function is slower compared to reading .tsv or .txt files. For improved performance, consider converting your data to .tsv or .txt format.")
            pep_all = pd.read_excel(pep_file)

        # Filter out any peptides that are not matched to a protein
        col = "Master Protein Accessions"
        if col in pep_all.columns:
            # treat NaN and empty/whitespace-only strings as missing
            mask_has_master = pep_all[col].notna() & pep_all[col].astype(str).str.strip().ne("")
            n_drop = (~mask_has_master).sum()
            if n_drop:
                print(f"{format_log_prefix('warn')} Dropping {n_drop} peptide rows with missing '{col}'.")
                pep_all = pep_all.loc[mask_has_master].copy()
        else:
            print(f"{format_log_prefix('warn')} Column '{col}' not found in peptide file; cannot filter missing master accessions.")

        # pep_X: sparse data matrix
        pep_X = sparse.csr_matrix(pep_all.filter(regex='Abundance: F', axis=1).values).transpose()
        # pep_layers['mbr']: peptide MBR identification
        pep_layers_mbr = pep_all.filter(regex='Found in Sample', axis=1).values.transpose()
        # pep_var_names: peptide sequence with modifications
        if 'Modifications' in pep_all.columns: # old PD version
            mod_col = 'Modifications'
        elif 'Modifications in Master Proteins' in pep_all.columns: # new PD version
            mod_col = 'Modifications in Master Proteins'
        else:
            mod_col = None # handle fallback if user didn't import?

        if mod_col is not None:
            pep_all[mod_col] = pep_all[mod_col].astype(str)
            pep_var_names = (
                pep_all['Annotated Sequence'] +
                np.where(pep_all[mod_col].isin(['nan', 'None', 'NaN']), '', ' MOD:' + pep_all[mod_col])
            ).values
        else:
            pep_var_names = pep_all['Annotated Sequence'].values
        # pep_obs_names: file names
        pep_obs_names = pep_all.filter(regex='Abundance: F', axis=1).columns.str.extract(r'Abundance: (F\d+):')[0].values
        # pep_var: peptide metadata
        pep_all.rename(columns={
            'Qvality q-value': 'Global_Q_Value',
            'q-Value': 'Global_Q_Value',
            'q-Value (Best File Local)': 'Global_Q_Value',
            'Qvality PEP': 'PEP',
            'PEP (Best File Local)': 'PEP',
        }, inplace=True)

        used_patterns = ['^Abundance: F', '^Found in Sample', '^Abundances \\(Grouped', '^Abundances \\(Grouped\\) CV']
        exclude_cols = pep_all.filter(regex='|'.join(used_patterns), axis=1).columns
        pep_var = pep_all.drop(columns=exclude_cols, errors='ignore')

        # ensure pep_var has only 1D columns
        for col in pep_var.columns:
            if isinstance(pep_var[col].iloc[0], (pd.Series, pd.DataFrame, np.ndarray, list, tuple)):
                print(f"{format_log_prefix('warn')} Dropping nested column '{col}' from peptide metadata.")
                pep_var = pep_var.drop(columns=[col])

        pep_var = pep_var.copy()
        for c in pep_var.columns:
            if not np.issubdtype(pep_var[c].dtype, np.number):
                pep_var[c] = pep_var[c].astype(str)

        # prot_obs: sample typing from the column name, drop column if all 'n/a'
        pep_obs = pep_all.filter(regex='Abundance: F', axis=1).columns.str.extract(r'Abundance: F\d+: (.+)$')[0].values
        pep_obs = pd.DataFrame(pep_obs, columns=['metadata'])['metadata'] \
            .str.split(',', expand=True)
        pep_obs = _safe_strip(pep_obs).astype('category')

        if (pep_obs == "n/a").all().any():
            print(f"{format_log_prefix('warn')} Found columns with all 'n/a'. Dropping these columns.")
            pep_obs = pep_obs.loc[:, ~(pep_obs == "n/a").all()]

        print(f"Peptides: {len(pep_var)}")
        if mod_col == 'Modifications in Master Proteins':
            print(f"\n{format_log_prefix('info_only')} Using 'Modifications in Master Proteins' for modification annotation.")
        elif mod_col == 'Modifications':
            print(f"\n{format_log_prefix('info_only')} Using 'Modifications' for modification annotation.")
        elif mod_col is None:
            print(f"\n{format_log_prefix('warn')} No modification column found. Peptide modifications were not annotated. Please check if 'Modifications' or 'Modifications in Master Protein' columns were exported from PD.")

    else:
        pep_X = pep_layers_mbr = pep_var_names = pep_var = pep_obs_names = pep_obs = None

    if prot_file and pep_file:
        # -----------------------------
        # RS DATA
        # rs is in the form of a binary matrix, protein x peptide
        pep_prot_list = pep_all['Master Protein Accessions'].str.split('; ')
        rs, mlb = _build_rs_matrix(pep_prot_list, prot_var_names = prot_var_names)

    else:
        rs = None

    # ASSERTIONS
    # -----------------------------
    # check if mlb.classes_ has overlap with prot_var
    if prot_file and pep_file:
        mlb_classes_set = set(mlb.classes_)
        prot_var_set = set(prot_var_names)

        if mlb_classes_set != prot_var_set:
            print(
                f"{format_log_prefix('warn')} Master proteins in the peptide matrix do not match proteins in the protein data, please check if files correspond to the same data.\n"
                f"{format_log_prefix('info')} If using PD3.2, this is a known issue due to changed protein grouping rules."
            )

    pdata = _create_pAnnData_from_parts(
        prot_X, pep_X, rs,
        prot_obs, prot_var, prot_obs_names, prot_var_names,
        pep_obs, pep_var, pep_obs_names, pep_var_names,
        obs_columns=obs_columns,
        X_mbr_prot=prot_layers_mbr,
        X_mbr_pep=pep_layers_mbr,
        metadata={
            "source": "proteomeDiscoverer",
            "prot_file": prot_file,
            "pep_file": pep_file
        },
        history_msg=f"Imported Proteome Discoverer data using source file(s): {prot_file}, {pep_file}.",
        fetch_uniprot=fetch_uniprot,
    )

    return pdata

_import_diann

_import_diann(
    report_file: Optional[str] = None,
    obs_columns: Optional[List[str]] = None,
    delimiter: Optional[str] = "_",
    obs: Optional[DataFrame] = None,
    prot_value="PG.MaxLFQ",
    pep_value="Precursor.Normalised",
    prot_var_columns=["Genes", "Master.Protein"],
    pep_var_columns=[
        "Genes",
        "Protein.Group",
        "Precursor.Charge",
        "Modified.Sequence",
        "Stripped.Sequence",
        "Precursor.Id",
        "All Mapped Proteins",
        "All Mapped Genes",
    ],
    **kwargs
)
Source code in src/scpviz/pAnnData/io.py
def _import_diann(report_file: Optional[str] = None, obs_columns: Optional[List[str]] = None, delimiter: Optional[str] = '_', obs: Optional[pd.DataFrame] = None, prot_value = 'PG.MaxLFQ', pep_value = 'Precursor.Normalised', prot_var_columns = ['Genes', 'Master.Protein'], pep_var_columns = ['Genes', 'Protein.Group', 'Precursor.Charge','Modified.Sequence', 'Stripped.Sequence', 'Precursor.Id', 'All Mapped Proteins', 'All Mapped Genes'], **kwargs):
    fetch_uniprot = kwargs.pop("fetch_uniprot", True)

    if not report_file:
        raise ValueError(f"{format_log_prefix('error')} Importing from DIA-NN: report.tsv or report.parquet must be provided to function. Try report_file='report.tsv' or report_file='report.parquet'")
    print("--------------------------\nStarting import [DIA-NN]\n")

    print(f"Source file: {report_file}")
    # if csv, then use pd.read_csv, if parquet then use pd.read_parquet('example_pa.parquet', engine='pyarrow')
    if report_file.endswith('.tsv'):
        report_all = pd.read_csv(report_file, sep='\t')
    elif report_file.endswith('.parquet'):
        report_all = pd.read_parquet(report_file, engine='pyarrow')
    report_all['Master.Protein'] = report_all['Protein.Group'].str.split(';')
    report_all = report_all.explode('Master.Protein')
    # -----------------------------
    # PROTEIN DATA
    # prot_X: sparse data matrix
    if prot_value != 'PG.MaxLFQ':
        if report_file.endswith('.tsv') and prot_value == 'PG.Quantity':
            # check if 'PG.Quantity' is in the columns, if yes then pass, if not then throw an error that DIA-NN version >2.0 does not have PG.quantity
            if 'PG.Quantity' not in report_all.columns:
                raise ValueError("Reports generated with DIA-NN version >2.0 do not contain PG.Quantity values, please use PG.MaxLFQ .")
        else:
            print(f"{format_log_prefix('info')} Protein value specified is not PG.MaxLFQ nor PG.Quantity, please check if correct.")
    prot_X_pivot = report_all.pivot_table(index='Master.Protein', columns='Run', values=prot_value, aggfunc='first', sort=False)
    prot_X = sparse.csr_matrix(prot_X_pivot.values).T
    # prot_var_names: protein names
    prot_var_names = prot_X_pivot.index.values
    # prot_obs: file names
    prot_obs_names = prot_X_pivot.columns.values

    # prot_var: protein metadata (default: Genes, Master.Protein)
    if 'First.Protein.Description' in report_all.columns and 'First.Protein.Description' not in prot_var_columns:
        prot_var_columns.insert(0, 'First.Protein.Description')

    if 'Global.PG.Q.Value' in report_all.columns and 'Global.PG.Q.Value' not in prot_var_columns:
        prot_var_columns.append('Global.PG.Q.Value')

    existing_prot_var_columns = [col for col in prot_var_columns if col in report_all.columns]
    missing_columns = set(prot_var_columns) - set(existing_prot_var_columns)

    if missing_columns:
        warnings.warn(
            f"{format_log_prefix('warn')} The following columns are missing: {', '.join(missing_columns)}. "
        )

    prot_var = report_all.loc[:, existing_prot_var_columns].drop_duplicates(subset='Master.Protein').drop(columns='Master.Protein').rename(columns={'Global.PG.Q.Value': 'Global_Q_value'})
    # prot_obs: sample typing from the column name
    if obs is not None:
        prot_obs = obs
        # obs_columns = obs_columns
    else:
        prot_obs = pd.DataFrame(prot_X_pivot.columns.values, columns=['Run'])['Run'].str.split(delimiter, expand=True).rename(columns=dict(enumerate(obs_columns)))

    # PG.Q.Value layer (sample x protein)
    if 'PG.Q.Value' in report_all.columns:
        pgq_pivot = report_all.pivot_table(index='Master.Protein', columns='Run', values='PG.Q.Value', aggfunc='first', sort=False)
        prot_pgq_layer = sparse.csr_matrix(pgq_pivot.values).T
    else:
        prot_pgq_layer = None

    print(f"Number of files: {len(prot_obs_names)}")
    print(f"Proteins: {len(prot_var)}")

    # -----------------------------
    # PEPTIDE DATA
    # pep_X: sparse data matrix
    pep_X_pivot = report_all.pivot_table(index='Precursor.Id', columns='Run', values=pep_value, aggfunc='first', sort=False)
    pep_X = sparse.csr_matrix(pep_X_pivot.values).T
    # pep_var_names: peptide sequence
    pep_var_names = pep_X_pivot.index.values
    # pep_obs_names: file names
    pep_obs_names = pep_X_pivot.columns.values
    # pep_var: peptide sequence with modifications (default: Genes, Protein.Group, Precursor.Charge, Modified.Sequence, Stripped.Sequence, Precursor.Id, All Mapped Proteins, All Mapped Genes)
    existing_pep_var_columns = [col for col in pep_var_columns if col in report_all.columns]
    missing_columns = set(pep_var_columns) - set(existing_pep_var_columns)
    # if missing columns are ['All Mapped Proteins'] and ['All Mapped Genes'], then it is likely that the DIA-NN version is <1.8.1, so we can skip the warning
    if missing_columns == {'All Mapped Proteins', 'All Mapped Genes'}:
        missing_columns = set()

    # Precursor.Quantity layer (if using directLFQ for nomalization)
    if 'Precursor.Quantity' in report_all.columns:
        precursor_q_pivot = report_all.pivot_table(index='Precursor.Id', columns='Run', values='Precursor.Quantity', aggfunc='first', sort=False)
        precursor_q_layer = sparse.csr_matrix(precursor_q_pivot.values).T
    else:
        precursor_q_layer = None


    pep_var = report_all.loc[:, existing_pep_var_columns].drop_duplicates(subset='Precursor.Id').drop(columns='Precursor.Id')
    # pep_obs: sample typing from the column name, same as prot_obs
    pep_obs = prot_obs

    # Q.Value layer (sample x peptide)
    if 'Q.Value' in report_all.columns:
        pepq_pivot = report_all.pivot_table(index='Precursor.Id', columns='Run', values='Q.Value', aggfunc='first', sort=False)
        pep_q_layer = sparse.csr_matrix(pepq_pivot.values).T
    else:
        pep_q_layer = None

    print(f"Peptides: {len(pep_var)}")
    if missing_columns:
        print(
            f"{format_log_prefix('warn')} The following columns are missing: {', '.join(missing_columns)}. "
            "Consider running analysis in the newer version of DIA-NN (1.8.1). "
            "Peptide-protein mapping may differ."
        )

    # -----------------------------
    # RS DATA
    # rs: protein x peptide relational data
    pep_prot_list = report_all.drop_duplicates(subset=['Precursor.Id'])['Protein.Group'].str.split(';')
    rs, mlb = _build_rs_matrix(pep_prot_list, prot_var_names = prot_var_names)

    # -----------------------------
    # ASSERTIONS
    # -----------------------------
    # check if mlb.classes_ has overlap with prot_var
    mlb_classes_set = set(mlb.classes_)
    prot_var_set = set(prot_var_names)

    if mlb_classes_set != prot_var_set:
        print(f"{format_log_prefix('warn')} Master proteins in the peptide matrix do not match proteins in the protein data, please check if files correspond to the same data.")
        print(f"Overlap: {len(mlb_classes_set & prot_var_set)}")
        print(f"Unique to peptide data: {mlb_classes_set - prot_var_set}")
        print(f"Unique to protein data: {prot_var_set - mlb_classes_set}")

    pdata = _create_pAnnData_from_parts(
        prot_X, pep_X, rs,
        prot_obs, prot_var, prot_obs_names, prot_var_names,
        pep_obs, pep_var, pep_obs_names, pep_var_names,
        obs_columns=obs_columns,
        X_qval_prot=prot_pgq_layer,
        X_qval_pep=pep_q_layer,
        X_precursor_pep=precursor_q_layer,
        metadata={
            "source": "diann",
            "file": report_file,
            "protein_metric": prot_value,
            "peptide_metric": pep_value
        },
        history_msg=f"Imported DIA-NN report from {report_file} using {prot_value} (protein) and {pep_value} (peptide).",
        fetch_uniprot=fetch_uniprot,
    )

    return pdata

_safe_strip

_safe_strip(df_like)

Safely strip whitespace from strings in a DataFrame or Series.

Source code in src/scpviz/pAnnData/io.py
def _safe_strip(df_like):
    """Safely strip whitespace from strings in a DataFrame or Series."""
    import sys
    if hasattr(df_like, "applymap") and (sys.version_info < (3, 9)):
        return df_like.applymap(lambda x: x.strip() if isinstance(x, str) else x)
    else:
        return df_like.map(lambda x: x.strip() if isinstance(x, str) else x)

_create_pAnnData_from_parts

_create_pAnnData_from_parts(
    prot_X,
    pep_X,
    rs,
    prot_obs,
    prot_var,
    prot_obs_names,
    prot_var_names,
    pep_obs=None,
    pep_var=None,
    pep_obs_names=None,
    pep_var_names=None,
    obs_columns=None,
    X_mbr_prot=None,
    X_mbr_pep=None,
    X_qval_prot=None,
    X_qval_pep=None,
    X_precursor_pep=None,
    found_threshold=0,
    fdr_threshold=0.01,
    metadata=None,
    history_msg="",
    fetch_uniprot: bool = True,
)

Assemble a pAnnData object from processed matrices and metadata.

This function is typically called internally by import functions. It constructs .prot and .pep AnnData objects, assigns optional metadata and MBR layers, adds identifier mappings and sample-level summary metrics, and returns a validated pAnnData object.

Parameters:

Name Type Description Default
prot_X csr_matrix

Protein-level expression matrix (samples × proteins).

required
pep_X csr_matrix or None

Peptide-level expression matrix (samples × peptides).

required
rs csr_matrix or None

Binary matrix linking proteins (rows) to peptides (columns).

required
prot_obs DataFrame

Sample-level metadata for protein data.

required
prot_var DataFrame

Feature-level metadata for proteins.

required
prot_obs_names list - like

Sample identifiers for .prot.

required
prot_var_names list - like

Protein accession identifiers for .prot.

required
pep_obs DataFrame

Sample metadata for .pep. If not provided, .prot.obs is reused.

None
pep_var DataFrame

Feature metadata for peptides.

None
pep_obs_names list - like

Sample identifiers for .pep.

None
pep_var_names list - like

Peptide identifiers.

None
obs_columns list of str

Columns from filenames to include in .summary and .obs. Use None at a position to parse that filename token but discard it.

None
X_mbr_prot ndarray or DataFrame

Optional protein-level MBR identification info.

None
X_mbr_pep ndarray or DataFrame

Optional peptide-level MBR identification info.

None
X_qval_prot ndarray or DataFrame

Optional protein-level Q-value info.

None
X_qval_pep ndarray or DataFrame

Optional peptide-level Q-value info.

None
X_precursor_pep ndarray or DataFrame

Optional peptide-level precursor quantity info. (for directLFQ normalization)

None
metadata dict

Optional dictionary of import metadata (e.g. {'source': 'diann'}).

None
history_msg str

Operation description to append to the history log.

''
fetch_uniprot bool

If True (default), fill missing .prot.var["Genes"] via UniProt during assembly. If False, skip the API call and leave missing gene names as NA.

True

Returns:

Name Type Description
pAnnData

Initialized object with .prot, .pep, .summary, .rs, and other metadata filled in.

Note

This is a low-level function. In most cases, users should call import_data(), import_proteomeDiscoverer(), or import_diann() instead.

Source code in src/scpviz/pAnnData/io.py
def _create_pAnnData_from_parts(
    prot_X, pep_X, rs,
    prot_obs, prot_var, prot_obs_names, prot_var_names,
    pep_obs=None, pep_var=None, pep_obs_names=None, pep_var_names=None,
    obs_columns=None,
    X_mbr_prot=None,
    X_mbr_pep=None,
    X_qval_prot=None,
    X_qval_pep=None,
    X_precursor_pep=None,
    found_threshold=0,
    fdr_threshold=0.01,
    metadata=None,
    history_msg="",
    fetch_uniprot: bool = True,
):
    """
    Assemble a `pAnnData` object from processed matrices and metadata.

    This function is typically called internally by import functions. It constructs
    `.prot` and `.pep` AnnData objects, assigns optional metadata and MBR layers,
    adds identifier mappings and sample-level summary metrics, and returns a
    validated `pAnnData` object.

    Args:
        prot_X (csr_matrix): Protein-level expression matrix (samples × proteins).
        pep_X (csr_matrix or None): Peptide-level expression matrix (samples × peptides).
        rs (csr_matrix or None): Binary matrix linking proteins (rows) to peptides (columns).
        prot_obs (pd.DataFrame): Sample-level metadata for protein data.
        prot_var (pd.DataFrame): Feature-level metadata for proteins.
        prot_obs_names (list-like): Sample identifiers for `.prot`.
        prot_var_names (list-like): Protein accession identifiers for `.prot`.
        pep_obs (pd.DataFrame, optional): Sample metadata for `.pep`. If not provided, `.prot.obs` is reused.
        pep_var (pd.DataFrame, optional): Feature metadata for peptides.
        pep_obs_names (list-like, optional): Sample identifiers for `.pep`.
        pep_var_names (list-like, optional): Peptide identifiers.
        obs_columns (list of str, optional): Columns from filenames to include in `.summary` and `.obs`.
            Use `None` at a position to parse that filename token but discard it.
        X_mbr_prot (np.ndarray or DataFrame, optional): Optional protein-level MBR identification info.
        X_mbr_pep (np.ndarray or DataFrame, optional): Optional peptide-level MBR identification info.
        X_qval_prot (np.ndarray or DataFrame, optional): Optional protein-level Q-value info.
        X_qval_pep (np.ndarray or DataFrame, optional): Optional peptide-level Q-value info.
        X_precursor_pep (np.ndarray or DataFrame, optional): Optional peptide-level precursor quantity info. (for directLFQ normalization)
        metadata (dict, optional): Optional dictionary of import metadata (e.g. `{'source': 'diann'}`).
        history_msg (str): Operation description to append to the history log.
        fetch_uniprot (bool): If True (default), fill missing `.prot.var["Genes"]`
            via UniProt during assembly. If False, skip the API call and leave
            missing gene names as NA.

    Returns:
        pAnnData: Initialized object with `.prot`, `.pep`, `.summary`, `.rs`, and other metadata filled in.

    Note:
        This is a low-level function. In most cases, users should call `import_data()`, `import_proteomeDiscoverer()`, or `import_diann()` instead.
    """
    from .pAnnData import pAnnData

    print("")
    pdata = pAnnData(prot_X, pep_X, rs)

    # None entries in obs_columns mark filename tokens to discard; names are assigned
    # first so a length mismatch still raises, then those positions are dropped.
    keep_obs = [c is not None for c in obs_columns] if obs_columns else slice(None)

    # --- PROTEIN ---
    if prot_X is not None:
        prot_var.index = prot_var.index.astype(str)

        pdata.prot.obs = pd.DataFrame(prot_obs) # type: ignore[attr-defined]
        pdata.prot.var = pd.DataFrame(prot_var) # type: ignore[attr-defined]
        pdata.prot.obs_names = list(prot_obs_names) # type: ignore[attr-defined]
        pdata.prot.var_names = list(prot_var_names) # type: ignore[attr-defined]
        pdata.prot.obs.columns = obs_columns if obs_columns else list(range(pdata.prot.obs.shape[1])) # type: ignore[attr-defined]
        pdata.prot.obs = pdata.prot.obs.iloc[:, keep_obs] # type: ignore[attr-defined]
        pdata.prot.layers['X_raw'] = prot_X # type: ignore[attr-defined]
        pdata.prot.uns['X_raw_obs_names'] = list(prot_obs_names) # type: ignore[attr-defined]
        pdata.prot.uns['X_raw_var_names'] = list(prot_var_names)
        pdata.prot.uns["current_X_layer"] = "X_raw"  # type: ignore[attr-defined]
        if X_mbr_prot is not None:
            pdata.prot.layers['X_mbr'] = X_mbr_prot # type: ignore[attr-defined]
        if X_qval_prot is not None:
            pdata.prot.layers['X_qval'] = X_qval_prot # type: ignore[attr-defined]

    gene_history_suffix = ""
    if pdata.prot is not None and "Genes" in pdata.prot.var.columns and pdata.prot.var["Genes"].isna().any(): # type: ignore[attr-defined]
        if fetch_uniprot:
            pdata.update_missing_genes(gene_col="Genes", verbose=True)
            gene_history_suffix = (
                " Queried UniProt API to fill missing gene names in .prot.var['Genes']."
            )
        else:
            n_missing = int(pdata.prot.var["Genes"].isna().sum()) # type: ignore[attr-defined]
            print(
                f"{format_log_prefix('warn')} Skipping UniProt gene lookup during import "
                f"({n_missing} missing). Set fetch_uniprot=True on import, or call "
                f"pdata.update_missing_genes() later."
            )
            gene_history_suffix = (
                " Skipped UniProt gene lookup during import (missing gene names left as NA)."
            )

    # --- PEPTIDE ---
    if pep_X is not None:
        pep_var.index = pep_var.index.astype(str)

        pdata.pep.obs = pd.DataFrame(pep_obs) # type: ignore[attr-defined]
        pdata.pep.var = pd.DataFrame(pep_var) # type: ignore[attr-defined]
        pdata.pep.obs_names = list(pep_obs_names) # type: ignore[attr-defined]
        pdata.pep.var_names = list(pep_var_names) # type: ignore[attr-defined]
        pdata.pep.obs.columns = obs_columns if obs_columns else list(range(pdata.pep.obs.shape[1])) # type: ignore[attr-defined]
        pdata.pep.obs = pdata.pep.obs.iloc[:, keep_obs] # type: ignore[attr-defined]
        pdata.pep.layers['X_raw'] = pep_X # type: ignore[attr-defined]
        pdata.pep.uns['X_raw_obs_names'] = list(pep_obs_names) # type: ignore[attr-defined]
        pdata.pep.uns['X_raw_var_names'] = list(pep_var_names)
        pdata.pep.uns["current_X_layer"] = "X_raw"  # type: ignore[attr-defined]
        if X_mbr_pep is not None:
            pdata.pep.layers['X_mbr'] = X_mbr_pep # type: ignore[attr-defined]
        if X_qval_pep is not None:
            pdata.pep.layers['X_qval'] = X_qval_pep # type: ignore[attr-defined]
        if X_precursor_pep is not None:
            pdata.pep.layers['X_precursor'] = X_precursor_pep # type: ignore[attr-defined]

    # --- Metadata ---
    metadata = metadata or {}
    metadata.setdefault("imported_at", datetime.datetime.now().isoformat())
    pdata.metadata.update(metadata)

    # --- Summary + Validation ---
    pdata.update_summary(recompute=True, verbose=False)
    if pdata.prot is not None:
        pdata._cleanup_proteins_after_sample_filter(printout=True)
    for level, adata in (("protein", pdata.prot), ("peptide", pdata.pep)):
        if adata is None:
            continue
        empty = adata.obs_names[adata.obs[f"{level}_count"] == 0].tolist()
        if empty:
            print(f"{format_log_prefix('warn')} {len(empty)} sample(s) have no quantified {level}s (all NaN/zero) and were kept: {', '.join(map(str, empty))}. "
                  "Consider removing them with filter_sample().")
    pdata._annotate_found_samples(threshold=found_threshold)
    pdata._annotate_significant_samples(fdr_threshold=fdr_threshold)

    print("")
    if not pdata.validate():
        print(f"{format_log_prefix('warn')} Validation issues found. Use `pdata.validate()` to inspect.")

    if history_msg:
        pdata._append_history(history_msg + gene_history_suffix)

    print(f"{format_log_prefix('result')} Import complete. Use `print(pdata)` to view the object.")
    print("--------------------------")

    return pdata

_build_rs_matrix

_build_rs_matrix(pep_prot_list, prot_var_names=None)

Build a sparse boolean RS (protein × peptide) relational matrix.

Parameters:

Name Type Description Default
pep_prot_list list or Series

List/Series where each entry contains one or more protein accessions (as lists or split strings).

required
prot_var_names list

Ordered list of protein accessions to align RS columns. If None, uses the order returned by MultiLabelBinarizer.

None

Returns:

Type Description

scipy.sparse.csr_matrix: Sparse boolean RS matrix (peptides × proteins).

Source code in src/scpviz/pAnnData/io.py
def _build_rs_matrix(pep_prot_list, prot_var_names=None):
    """
    Build a sparse boolean RS (protein × peptide) relational matrix.

    Args:
        pep_prot_list (list or pd.Series): List/Series where each entry
            contains one or more protein accessions (as lists or split strings).
        prot_var_names (list, optional): Ordered list of protein accessions to
            align RS columns. If None, uses the order returned by MultiLabelBinarizer.

    Returns:
        scipy.sparse.csr_matrix: Sparse boolean RS matrix (peptides × proteins).
    """
    # sparse bool RS matrix to save RAM
    mlb = MultiLabelBinarizer(sparse_output=True)
    rs = mlb.fit_transform(pep_prot_list).astype(bool)

    # reorder columns to match protein order
    if prot_var_names is not None:
        index_dict = {protein: idx for idx, protein in enumerate(mlb.classes_)}
        # proteins without any peptide get an empty column so RS stays aligned with prot.var_names
        missing = [p for p in prot_var_names if p not in index_dict]
        if missing:
            shown = ", ".join(map(str, missing[:10])) + (f", ... (+{len(missing) - 10} more)" if len(missing) > 10 else "")
            print(f"{format_log_prefix('warn')} {len(missing)} protein(s) have no peptides in the peptide data and were given empty RS columns: {shown}. "
                  "Check that your protein and peptide exports are complete and use matching filters.")
            rs = sparse.hstack([rs, sparse.csr_matrix((rs.shape[0], 1), dtype=bool)], format="csr")
        reorder_indices = [index_dict.get(p, rs.shape[1] - 1) for p in prot_var_names]
        rs = rs[:, reorder_indices]

    # make csr matrix so downstream operations are faster
    rs = sparse.csr_matrix(rs, dtype=bool)
    rs.eliminate_zeros()

    return rs, mlb

metrics

Computes descriptive and RS-derived metrics for proteomic data.

This mixin provides utility functions for calculating summary statistics on protein and peptide abundance data, as well as inspecting the structure of the RS (protein × peptide) relational matrix.

Features:

  • Computes per-sample quantification and abundance metrics for both proteins and peptides
  • Calculates RS-derived properties such as the number of peptides per protein and the number of unique peptides
  • Updates .obs, .var, and .summary with relevant metrics
  • Provides visualization and tabular summaries of RS matrix connectivity

Methods:

Name Description
_update_metrics

Computes per-sample and RS-derived metrics for .prot and .pep.

_update_summary_metrics

Adds per-sample high-confidence protein counts to .summary.

describe_rs

Returns a DataFrame summarizing peptide connectivity per protein.

plot_rs

Generates histograms of peptide–protein and protein–peptide mapping counts.

Source code in src/scpviz/pAnnData/metrics.py
class MetricsMixin:
    """
    Computes descriptive and RS-derived metrics for proteomic data.

    This mixin provides utility functions for calculating summary statistics on
    protein and peptide abundance data, as well as inspecting the structure of
    the RS (protein × peptide) relational matrix.

    Features:

    - Computes per-sample quantification and abundance metrics for both proteins and peptides
    - Calculates RS-derived properties such as the number of peptides per protein and the number of unique peptides
    - Updates `.obs`, `.var`, and `.summary` with relevant metrics
    - Provides visualization and tabular summaries of RS matrix connectivity

    Functions:
        _update_metrics: Computes per-sample and RS-derived metrics for `.prot` and `.pep`.
        _update_summary_metrics: Adds per-sample high-confidence protein counts to `.summary`.
        describe_rs: Returns a DataFrame summarizing peptide connectivity per protein.
        plot_rs: Generates histograms of peptide–protein and protein–peptide mapping counts.
    """
    def _update_metrics(self):
        """
        Compute and update core QC and RS-based metrics for `.obs` and `.var`.

        This internal method updates:

        - `.prot.obs` and `.pep.obs` with per-sample metrics:
            • `*_quant`: Proportion of detected (non-NaN, non-zero) values
            • `*_count`: Number of detected (non-NaN, non-zero) values
            • `*_abundance_sum`: Sum of observed abundances
            • `mbr_count`, `high_count`: Count of MBR annotations (if present in layer 'X_mbr')

        - `.prot.var` with RS-derived metrics (if available):
            • `peptides_per_protein`: Total peptides mapped to each protein
            • `unique_peptides`: Number of peptides uniquely mapping to each protein

        Note:
            This function is typically called automatically after filtering, imputation,
            or importing new data. It should not be run manually under normal usage.
        """
        if self.prot is not None:
            if self.prot.is_view:
                self.prot = self.prot.copy()

            X = self.prot.X.toarray() if hasattr(self.prot.X, "toarray") else np.asarray(self.prot.X)
            detected = (~np.isnan(X)) & (X != 0)
            self.prot.obs['protein_quant'] = detected.sum(axis=1) / X.shape[1]
            self.prot.obs['protein_count'] = detected.sum(axis=1)
            self.prot.obs['protein_abundance_sum'] = np.nansum(X, axis=1)

            if 'X_mbr' in self.prot.layers:
                self.prot.obs['mbr_count'] = (self.prot.layers['X_mbr'] == 'Peak Found').sum(axis=1)
                self.prot.obs['high_count'] = (self.prot.layers['X_mbr'] == 'High').sum(axis=1)

        if self.pep is not None:
            if self.pep.is_view:
                self.pep = self.pep.copy()
            X = self.pep.X.toarray() if hasattr(self.pep.X, "toarray") else np.asarray(self.pep.X)
            detected = (~np.isnan(X)) & (X != 0)
            self.pep.obs['peptide_quant'] = detected.sum(axis=1) / X.shape[1]
            self.pep.obs['peptide_count'] = detected.sum(axis=1)
            self.pep.obs['peptide_abundance_sum'] = np.nansum(X, axis=1)

            if 'X_mbr' in self.pep.layers:
                self.pep.obs['mbr_count'] = (self.pep.layers['X_mbr'] == 'Peak Found').sum(axis=1)
                self.pep.obs['high_count'] = (self.pep.layers['X_mbr'] == 'High').sum(axis=1)

        # RS metrics for prot.var
        if (
            self.rs is not None
            and self.prot is not None
            and self.rs.shape[0] == self.prot.n_vars
        ):
            rs = self.rs  # leave it sparse
            peptides_per_protein = rs.getnnz(axis=1)
            unique_mask = rs.getnnz(axis=0) == 1
            unique_counts = rs[:, unique_mask].getnnz(axis=1)
            self.prot.var['peptides_per_protein'] = peptides_per_protein
            self.prot.var['unique_peptides'] = unique_counts

    def _update_summary_metrics(self, unique_peptide_thresh=2):
        """
        Compute RS-derived per-sample summary metric for protein confidence.

        Adds the following column to `.summary`:

        - `unique_pep2_protein_count`: Number of proteins per sample with at least 
        `unique_peptide_thresh` uniquely mapping peptides (default: 2).

        This is useful for quality control and filtering based on protein-level confidence.

        Args:
            unique_peptide_thresh (int): Minimum number of uniquely mapping peptides required
                to consider a protein as confidently quantified.
        """
        if (
            self.rs is not None and
            self.prot is not None and
            hasattr(self, '_summary') and
            'unique_peptides' in self.prot.var.columns
        ):
            unique_mask = self.prot.var['unique_peptides'] >= unique_peptide_thresh
            quant_matrix = (
                self.prot.X.toarray()
                if hasattr(self.prot.X, "toarray")
                else np.asarray(self.prot.X)
            )
            high_conf_matrix = quant_matrix[:, unique_mask]
            high_conf_count = ((~np.isnan(high_conf_matrix)) & (high_conf_matrix != 0)).sum(axis=1)
            self._summary['unique_pep2_protein_count'] = high_conf_count

    def describe_rs(self):
        """
        Summarize the protein–peptide RS (relational) matrix.

        Returns a DataFrame with one row per protein, describing its peptide mapping coverage:

        - `peptides_per_protein`: Total number of peptides mapped to each protein.
        - `unique_peptides`: Number of uniquely mapping peptides (peptides linked to only one protein).

        Returns:
            pd.DataFrame: Summary statistics for each protein in the RS matrix.

        Note:
            If `.prot` is available, index labels are taken from `.prot.var_names`.
        """
        if self.rs is None:
            print("⚠️ No RS matrix set.")
            return None

        rs = self.rs

        # peptides per protein
        peptides_per_protein = rs.getnnz(axis=1)
        # unique peptides per protein (those mapped only to this protein)
        unique_mask = rs.getnnz(axis=0) == 1
        unique_counts = rs[:, unique_mask].getnnz(axis=1)

        summary_df = pd.DataFrame({
            "peptides_per_protein": peptides_per_protein,
            "unique_peptides": unique_counts
        }, index=self.prot.var_names if self.prot is not None else range(rs.shape[0]))

        return summary_df

_update_metrics

_update_metrics()

Compute and update core QC and RS-based metrics for .obs and .var.

This internal method updates:

  • .prot.obs and .pep.obs with per-sample metrics: • *_quant: Proportion of detected (non-NaN, non-zero) values • *_count: Number of detected (non-NaN, non-zero) values • *_abundance_sum: Sum of observed abundances • mbr_count, high_count: Count of MBR annotations (if present in layer 'X_mbr')

  • .prot.var with RS-derived metrics (if available): • peptides_per_protein: Total peptides mapped to each protein • unique_peptides: Number of peptides uniquely mapping to each protein

Note

This function is typically called automatically after filtering, imputation, or importing new data. It should not be run manually under normal usage.

Source code in src/scpviz/pAnnData/metrics.py
def _update_metrics(self):
    """
    Compute and update core QC and RS-based metrics for `.obs` and `.var`.

    This internal method updates:

    - `.prot.obs` and `.pep.obs` with per-sample metrics:
        • `*_quant`: Proportion of detected (non-NaN, non-zero) values
        • `*_count`: Number of detected (non-NaN, non-zero) values
        • `*_abundance_sum`: Sum of observed abundances
        • `mbr_count`, `high_count`: Count of MBR annotations (if present in layer 'X_mbr')

    - `.prot.var` with RS-derived metrics (if available):
        • `peptides_per_protein`: Total peptides mapped to each protein
        • `unique_peptides`: Number of peptides uniquely mapping to each protein

    Note:
        This function is typically called automatically after filtering, imputation,
        or importing new data. It should not be run manually under normal usage.
    """
    if self.prot is not None:
        if self.prot.is_view:
            self.prot = self.prot.copy()

        X = self.prot.X.toarray() if hasattr(self.prot.X, "toarray") else np.asarray(self.prot.X)
        detected = (~np.isnan(X)) & (X != 0)
        self.prot.obs['protein_quant'] = detected.sum(axis=1) / X.shape[1]
        self.prot.obs['protein_count'] = detected.sum(axis=1)
        self.prot.obs['protein_abundance_sum'] = np.nansum(X, axis=1)

        if 'X_mbr' in self.prot.layers:
            self.prot.obs['mbr_count'] = (self.prot.layers['X_mbr'] == 'Peak Found').sum(axis=1)
            self.prot.obs['high_count'] = (self.prot.layers['X_mbr'] == 'High').sum(axis=1)

    if self.pep is not None:
        if self.pep.is_view:
            self.pep = self.pep.copy()
        X = self.pep.X.toarray() if hasattr(self.pep.X, "toarray") else np.asarray(self.pep.X)
        detected = (~np.isnan(X)) & (X != 0)
        self.pep.obs['peptide_quant'] = detected.sum(axis=1) / X.shape[1]
        self.pep.obs['peptide_count'] = detected.sum(axis=1)
        self.pep.obs['peptide_abundance_sum'] = np.nansum(X, axis=1)

        if 'X_mbr' in self.pep.layers:
            self.pep.obs['mbr_count'] = (self.pep.layers['X_mbr'] == 'Peak Found').sum(axis=1)
            self.pep.obs['high_count'] = (self.pep.layers['X_mbr'] == 'High').sum(axis=1)

    # RS metrics for prot.var
    if (
        self.rs is not None
        and self.prot is not None
        and self.rs.shape[0] == self.prot.n_vars
    ):
        rs = self.rs  # leave it sparse
        peptides_per_protein = rs.getnnz(axis=1)
        unique_mask = rs.getnnz(axis=0) == 1
        unique_counts = rs[:, unique_mask].getnnz(axis=1)
        self.prot.var['peptides_per_protein'] = peptides_per_protein
        self.prot.var['unique_peptides'] = unique_counts

_update_summary_metrics

_update_summary_metrics(unique_peptide_thresh=2)

Compute RS-derived per-sample summary metric for protein confidence.

Adds the following column to .summary:

  • unique_pep2_protein_count: Number of proteins per sample with at least unique_peptide_thresh uniquely mapping peptides (default: 2).

This is useful for quality control and filtering based on protein-level confidence.

Parameters:

Name Type Description Default
unique_peptide_thresh int

Minimum number of uniquely mapping peptides required to consider a protein as confidently quantified.

2
Source code in src/scpviz/pAnnData/metrics.py
def _update_summary_metrics(self, unique_peptide_thresh=2):
    """
    Compute RS-derived per-sample summary metric for protein confidence.

    Adds the following column to `.summary`:

    - `unique_pep2_protein_count`: Number of proteins per sample with at least 
    `unique_peptide_thresh` uniquely mapping peptides (default: 2).

    This is useful for quality control and filtering based on protein-level confidence.

    Args:
        unique_peptide_thresh (int): Minimum number of uniquely mapping peptides required
            to consider a protein as confidently quantified.
    """
    if (
        self.rs is not None and
        self.prot is not None and
        hasattr(self, '_summary') and
        'unique_peptides' in self.prot.var.columns
    ):
        unique_mask = self.prot.var['unique_peptides'] >= unique_peptide_thresh
        quant_matrix = (
            self.prot.X.toarray()
            if hasattr(self.prot.X, "toarray")
            else np.asarray(self.prot.X)
        )
        high_conf_matrix = quant_matrix[:, unique_mask]
        high_conf_count = ((~np.isnan(high_conf_matrix)) & (high_conf_matrix != 0)).sum(axis=1)
        self._summary['unique_pep2_protein_count'] = high_conf_count

pAnnData

Bases: BaseMixin, ValidationMixin, SummaryMixin, MetricsMixin, BiophysicalMixin, IdentifierMixin, HistoryMixin, EditingMixin, FilterMixin, AnalysisMixin, EnrichmentMixin, IOMixin, PlotMixin

Unified data container for protein and peptide expression in single-cell and bulk proteomics.

pAnnData integrates matched protein-level and peptide-level AnnData objects, along with an optional binary relational structure (rs) that maps peptides to their parent proteins. It is designed for single-cell and bulk proteomics data, and supports a range of analysis workflows, including filtering, normalization, imputation, differential expression, enrichment, and visualization.

This class is composed of modular mixins to enhance maintainability and organization.

Mixins
  • BaseMixin: Core internal utilities, copying, and simple logic.
  • ValidationMixin: Ensures structural and dimensional consistency across .prot, .pep, .summary, and rs.
  • SummaryMixin: Maintains .summary, synchronizes metadata, and caches per-sample metrics.
  • MetricsMixin: Computes descriptive statistics from expression data and relational structure (RS matrix).
  • BiophysicalMixin: Sequence-level biophysical properties (e.g. GRAVY, molecular weight, pI) via Biopython ProtParam.
  • IdentifierMixin: Manages bidirectional gene/accession mappings and handles missing gene resolution via UniProt.
  • HistoryMixin: Tracks all operations performed on the object for transparency.
  • EditingMixin: Supports in-place editing, direct manipulation of expression matrices, and data export.
  • FilterMixin: Provides flexible filtering of samples and proteins/peptides based on metadata, presence, or quantification.
  • AnalysisMixin: Core statistical operations: differential expression, imputation, PCA, clustering, etc.
  • EnrichmentMixin: Runs STRING-based enrichment analyses (GO, pathways, PPI) using ranked or unranked protein sets.
  • PlotMixin: Used to plot and visualize attributes of the pAnnData object, frequently for QC.

Parameters:

Name Type Description Default
prot AnnData

Protein-level expression matrix, with .obs containing sample metadata and .var describing protein features.

None
pep AnnData

Peptide-level expression matrix, structured analogously to prot.

None
rs ndarray or spmatrix

Binary relational matrix (proteins × peptides), where non-zero entries indicate a parent-protein relationship.

None
Note

summary, stats, history, and metadata are created internally (empty by default) and populated as you use the object; they are not constructor arguments. metadata holds import provenance (e.g. source); for hand-built objects, set pdata.metadata['source'] so peptide-to-protein mapping works.

Source code in src/scpviz/pAnnData/pAnnData.py
class pAnnData(BaseMixin, ValidationMixin, SummaryMixin, MetricsMixin,
               BiophysicalMixin, IdentifierMixin, HistoryMixin, EditingMixin,
               FilterMixin, AnalysisMixin, EnrichmentMixin, IOMixin, PlotMixin):
    """
    Unified data container for protein and peptide expression in single-cell and bulk proteomics.

    `pAnnData` integrates matched protein-level and peptide-level `AnnData` objects, along with an optional
    binary relational structure (`rs`) that maps peptides to their parent proteins. It is designed for single-cell and bulk
    proteomics data, and supports a range of analysis workflows, including filtering, normalization, imputation, differential
    expression, enrichment, and visualization.

    This class is composed of modular mixins to enhance maintainability and organization.

    ## Mixins

    - **BaseMixin**: Core internal utilities, copying, and simple logic.
    - **ValidationMixin**: Ensures structural and dimensional consistency across `.prot`, `.pep`, `.summary`, and `rs`.
    - **SummaryMixin**: Maintains `.summary`, synchronizes metadata, and caches per-sample metrics.
    - **MetricsMixin**: Computes descriptive statistics from expression data and relational structure (RS matrix).
    - **BiophysicalMixin**: Sequence-level biophysical properties (e.g. GRAVY, molecular weight, pI) via Biopython ProtParam.
    - **IdentifierMixin**: Manages bidirectional gene/accession mappings and handles missing gene resolution via UniProt.
    - **HistoryMixin**: Tracks all operations performed on the object for transparency.
    - **EditingMixin**: Supports in-place editing, direct manipulation of expression matrices, and data export.
    - **FilterMixin**: Provides flexible filtering of samples and proteins/peptides based on metadata, presence, or quantification.
    - **AnalysisMixin**: Core statistical operations: differential expression, imputation, PCA, clustering, etc.
    - **EnrichmentMixin**: Runs STRING-based enrichment analyses (GO, pathways, PPI) using ranked or unranked protein sets.
    - **PlotMixin**: Used to plot and visualize attributes of the pAnnData object, frequently for QC.

    Args:
        prot (AnnData, optional): Protein-level expression matrix, with `.obs` containing sample metadata and `.var` describing protein features.

        pep (AnnData, optional): Peptide-level expression matrix, structured analogously to `prot`.

        rs (np.ndarray or sparse.spmatrix, optional):
            Binary relational matrix (proteins × peptides), where non-zero entries indicate a parent-protein relationship.

    Note:
        ``summary``, ``stats``, ``history``, and ``metadata`` are created internally (empty by default) and populated as you use the object; they are not constructor arguments.
        ``metadata`` holds import provenance (e.g. ``source``); for hand-built objects, set
        ``pdata.metadata['source']`` so peptide-to-protein mapping works.

    """
    def __init__(self, 
                 prot = None, # np.ndarray | sparse.spmatrix 
                 pep = None, # np.ndarray | sparse.spmatrix
                 rs = None): # np.ndarray | sparse.spmatrix, protein x peptide relational data

        self._prot = ad.AnnData(prot) if prot is not None else None
        self._pep = ad.AnnData(pep) if pep is not None else None
        self._rs = None
        if rs is not None:
            self._set_RS(rs) # Defined in the EditingMixin

        # Internal attributes
        self._history = []
        self._summary = pd.DataFrame()
        self._stats = {}
        self._metadata = {}
        self._summary_is_stale = False

        if self._prot is not None or self._pep is not None:
            self.update_summary(recompute=True, verbose=False)

    def __repr__(self):
        def format_summary(summary):
            if summary is None:
                return "Summary:\n  None"

            default_cols = {"protein_count", "peptide_count", "protein_quant", "peptide_quant"}
            grouping_cols = [col for col in summary.columns
                            if col not in default_cols and summary[col].nunique() < len(summary)]

            avg_prot = summary["protein_count"].mean() if "protein_count" in summary else None
            avg_quant = summary["protein_quant"].mean() if "protein_quant" in summary else None
            low_quant = (summary["protein_quant"] < 0.5).sum() if "protein_quant" in summary else None

            lines = []
            if grouping_cols:
                lines.append(f"Groups: {', '.join(grouping_cols)}")
            if avg_prot is not None:
                lines.append(f"Avg proteins/sample: {avg_prot:.1f}")
            if avg_quant is not None:
                lines.append(f"Avg protein quant: {avg_quant:.2f}")
            if low_quant is not None:
                lines.append(f"Samples < 50% quant: {low_quant}")

            return "Summary:\n" + "\n".join(f"  {line}" for line in lines) if lines else "Summary:\n  —"

        def format_ann(adata, label, shared_obs=False):
            if adata is None:
                return f"{label}: None"

            shape_str = f"{adata.shape[0]} files × {adata.shape[1]} {label.lower()}s"
            obs_cols = ', '.join(adata.obs.columns[:5]) + ('...' if len(adata.obs.columns) > 5 else '')
            var_cols = ', '.join(adata.var.columns[:5]) + ('...' if len(adata.var.columns) > 5 else '')
            obsm_keys = ', '.join(adata.obsm.keys())
            # anndata >= 0.13 stores .X as layers[None]
            layers_keys = ', '.join(k for k in adata.layers.keys() if isinstance(k, str))

            obs_line = "  obs:    (same as protein)" if shared_obs and label == "Peptide" else f"  obs:    {obs_cols or '—'}"

            return (f"{label} (shape: {shape_str})\n"
                    f"{obs_line}\n"
                    f"  var:    {var_cols or '—'}\n"
                    f"  obsm:   {obsm_keys or '—'}\n"
                    f"  layers: {layers_keys or '—'}")

        def format_rs_summary(rs):
            if rs is None:
                return "RS:\n  None"

            peptides_per_protein = rs.getnnz(axis=1)
            unique_mask = rs.getnnz(axis=0) == 1
            unique_counts = rs[:, unique_mask].getnnz(axis=1)

            mean_pep = peptides_per_protein.mean()
            mean_uniq = unique_counts.mean()
            pct_highconf = (unique_counts >= 2).mean() * 100

            return (
                f"RS (shape: {rs.shape[0]} proteins × {rs.shape[1]} peptides)\n"
                f"  Avg peptides/protein: {mean_pep:.2f}\n"
                f"  Avg unique peptides : {mean_uniq:.2f}\n"
                f"  Proteins with ≥2 unique peptides: {pct_highconf:.1f}%"
            )

        def format_enrichments(stats):
            functional = stats.get("functional", {})
            ppi_keys = stats.get("ppi", {})
            de_keys = {k for k in stats if "vs" in k and not k.endswith(("_up", "_down", "_both"))}

            enriched_de = {
                meta.get("input_key", k)
                for k, meta in functional.items()
                if "vs" in k and meta.get("input_key", None) in de_keys
            }

            n_de = len(de_keys)
            n_func = len(functional)
            n_ppi = len(ppi_keys)
            n_unenriched = n_de - len(enriched_de)

            lines = []
            if n_de:
                lines.append(f"DE comparisons: {n_de}")
                if n_func:
                    examples = sorted(k for k in functional if "vs" in k)[:3]
                    lines.append(f"Functional enrichment: {n_func} result(s) (e.g. {', '.join(examples)})")
                if n_ppi:
                    lines.append(f"PPI enrichment: {n_ppi} result(s)")
                if n_unenriched > 0:
                    lines.append(f"Pending enrichment: {n_unenriched}")
            elif n_func or n_ppi:
                if n_func:
                    lines.append(f"Functional enrichment: {n_func} result(s)")
                if n_ppi:
                    lines.append(f"PPI enrichment: {n_ppi} result(s)")

            if lines:
                lines.append("↪ Use `pdata.list_enrichments()` for details")

            return "STRING Enrichment:\n" + "\n".join(f"  {line}" for line in lines) if lines else "STRING Enrichment:\n  —"

        shared_obs = self.prot is not None and self.pep is not None and self.prot.obs.equals(self.pep.obs)

        lines = ["pAnnData object"]
        lines.append("")  # Spacer

        # Summary
        lines.append(format_summary(self._summary))
        lines.append("")  # Spacer

        # Protein and Peptide
        lines.append(format_ann(self.prot, "Protein", shared_obs=shared_obs))
        lines.append("")  # Spacer
        lines.append(format_ann(self.pep, "Peptide", shared_obs=shared_obs))
        lines.append("")  # Spacer

        # RS Matrix
        lines.append(format_rs_summary(self._rs))
        lines.append("")  # Spacer

        # Enrichment Summary
        enrichment_info = format_enrichments(self.stats)
        lines.append(enrichment_info)

        return "\n".join(lines)

    # -----------------------------
    # Properties (GETTERS)
    @property
    def prot(self):
        return self._prot

    @property
    def pep(self):
        return self._pep

    @property
    def rs(self):
        return self._rs

    @property
    def history(self):
        return self._history

    @property
    def summary(self):
        if not hasattr(self, "_summary"):
            raise AttributeError("Summary has not been initialized.")
        if getattr(self, "_summary_is_stale", False):
            print("[summary] ⚠️ Warning: .summary has been modified. Run `(pdata).update_summary()` to sync changes back to .obs.")
        return self._summary

    @property
    def stats(self):
        return self._stats

    @property
    def metadata(self):
        if "_metadata" not in vars(self):  # objects created before metadata moved off .uns (e.g. unpickled)
            legacy = [a.uns.pop("metadata") for a in (self._prot, self._pep) if a is not None and "metadata" in a.uns]
            self._metadata = dict(legacy[0]) if legacy else {}
        return self._metadata

    @property
    def _cached_identifier_maps_protein(self):
        if not hasattr(self, "_gene_maps_protein"):
            self._gene_maps_protein = self._build_identifier_maps(self.prot)
        return self._gene_maps_protein

    @property
    def _cached_identifier_maps_peptide(self):
        if not hasattr(self, "_protein_maps_peptide"):
            self._protein_maps_peptide = self._build_identifier_maps(self.pep)
        return self._protein_maps_peptide

    # -----------------------------
    # Properties (SETTERS)
    @prot.setter
    def prot(self, value: ad.AnnData):
        self._prot = value

    @pep.setter
    def pep(self, value: ad.AnnData):
        self._pep = value

    @rs.setter
    def rs(self, value):
        self._set_RS(value)  # From EditingMixin

    @history.setter
    def history(self, value):
        self._history = value

    @summary.setter
    def summary(self, value: pd.DataFrame):
        self._summary = TrackedDataFrame(
            value,
            parent=self,
            mark_stale_fn=self._mark_summary_stale  # You likely have this defined in SummaryMixin or base
        )
        self._summary_is_stale = True
        suppress = getattr(self, "_suppress_summary_log", False)
        self.update_summary(recompute=True, sync_back=True, verbose=not suppress)

    @stats.setter
    def stats(self, value):
        self._stats = value

    @metadata.setter
    def metadata(self, value):
        self._metadata = value

_cached_identifier_maps_protein property

_cached_identifier_maps_protein

_cached_identifier_maps_peptide property

_cached_identifier_maps_peptide

summary

Handles creation, synchronization, and metric updates for the .summary attribute.

This mixin maintains a unified sample-level summary table by merging .prot.obs and .pep.obs, with automatic flagging and update mechanisms to track when recomputation or syncing is needed.

Features:

  • Merges sample-level metadata from .prot.obs and .pep.obs into .summary
  • Tracks when .summary becomes out of sync via _summary_is_stale
  • Supports recomputing per-sample metrics and syncing edits back to .obs
  • Enables passive refresh of .summary after filtering or manual editing

Methods:

Name Description
update_summary

Rebuild and optionally recompute or sync .summary

_update_summary

Legacy alias for update_summary()

_merge_obs

Internal merge logic for .prot.obs and .pep.obs

_push_summary_to_obs

Sync edited .summary values back into .obs

_mark_summary_stale

Mark the summary as stale for downstream tracking

Source code in src/scpviz/pAnnData/summary.py
class SummaryMixin:
    """
    Handles creation, synchronization, and metric updates for the `.summary` attribute.

    This mixin maintains a unified sample-level summary table by merging `.prot.obs` and `.pep.obs`,
    with automatic flagging and update mechanisms to track when recomputation or syncing is needed.

    Features:

    - Merges sample-level metadata from `.prot.obs` and `.pep.obs` into `.summary`
    - Tracks when `.summary` becomes out of sync via `_summary_is_stale`
    - Supports recomputing per-sample metrics and syncing edits back to `.obs`
    - Enables passive refresh of `.summary` after filtering or manual editing

    Functions:
        update_summary: Rebuild and optionally recompute or sync `.summary`
        _update_summary: Legacy alias for `update_summary()`
        _merge_obs: Internal merge logic for `.prot.obs` and `.pep.obs`
        _push_summary_to_obs: Sync edited `.summary` values back into `.obs`
        _mark_summary_stale: Mark the summary as stale for downstream tracking
    """
    def update_summary(self, recompute=True, sync_back=False, verbose=True):
        """
        Update the `.summary` DataFrame to reflect current state of `.obs` and metadata.

        This function ensures `.summary` stays synchronized with sample-level metadata
        stored in `.prot.obs` / `.pep.obs`. You can choose to recompute metrics,
        sync edits back to `.obs`, or simply refresh the merged view.

        Args:
            recompute (bool): If True, re-calculate protein/peptide stats.
            sync_back (bool): If True, push edited `.summary` values back to `.prot.obs` / `.pep.obs`.
                False by default, as `.summary` is derived.
            verbose (bool): If True, print action messages.

        ??? example "Typical Usage Scenarios"
            | Scenario                        | Call                                | recompute | sync_back | _summary_is_stale | Effect                                                           |
            |---------------------------------|-------------------------------------|-----------|-----------|-------------------|------------------------------------------------------------------|
            | Filtering `.prot` or `.pep`     | `.update_summary(recompute=True)`   | ✅        | ❌        | ❌                | Recalculate protein/peptide stats and merge into `.summary`.     |
            | Filtering samples               | `.update_summary(recompute=False)`  | ❌        | ❌        | ❌                | Refresh `.summary` view of `.obs` without recomputation.         |
            | Manual `.summary[...] = ...`    | `.update_summary()`                 | ✅/❌     | ✅        | ✅                | Push edited `.summary` values back to `.obs`.                    |
            | After setting `.summary = ...`  | `.update_summary()`                 | ✅        | ✅        | ✅                | Sync back and recompute stats from new `.summary`.               |
            | No changes                      | `.update_summary()`                 | ❌        | ❌        | ❌                | No-op other than passive re-merge.                               |

        Note:
            - For most typical use cases, we auto-detect which flags need to be applied.
                You usually don’t need to set `recompute` or `sync_back` manually.
            - `recompute=True` triggers `_update_metrics()` from `.prot` / `.pep` data.
            - `sync_back=True` ensures changes to `.summary` are reflected in `.obs`.
            - `.summary_is_stale` is automatically set when `.summary` is edited directly
            (e.g. via `TrackedDataFrame`) or when assigned via the setter.
        """

        # 1. Push back first if summary was edited by the user
        if sync_back or getattr(self, "_summary_is_stale", False):
            updated_prot, updated_pep = self._push_summary_to_obs()
            updated_cols = list(set(updated_prot + updated_pep))
            updated_str = f" Columns updated: {', '.join(updated_cols)}." if updated_cols else ""

            if verbose:
                reason = " (marked stale)" if not sync_back else ""
                print(f"{format_log_prefix('update',indent=1)} Updating summary [sync_back]: pushed edits from `.summary` to `.obs`{reason}.\n{format_log_prefix('blank',indent=2)}{updated_str}")

            self._summary_is_stale = False  # reset before recompute

        # 2. Recompute or re-merge afterward
        if recompute:
            self._update_metrics() # type: ignore #, in MetricsMixin
        self._merge_obs()
        self._update_summary_metrics() # type: ignore #, in MetricsMixin
        self.refresh_identifier_maps() # type: ignore #, in IdentifierMixin

        # 3. Final messaging
        if verbose and not (sync_back or self._summary_is_stale):
            if recompute:
                print(f"{format_log_prefix('update',indent=3)} Updating summary [recompute]: Recomputed metrics and refreshed `.summary` from `.obs`.")
            else:
                print(f"{format_log_prefix('update',indent=3)} Updating summary [refresh]: Refreshed `.summary` view (no recompute).")

        # 4. Final cleanup
        self._summary_is_stale = False

    def _update_summary(self):
        """
        Legacy method for updating the `.summary` table.

        This method is retained for backward compatibility and simply calls the newer
        `update_summary()` function with default arguments:
        `recompute=True`, `sync_back=False`, and `verbose=False`.

        Note:
            This method is deprecated and may be removed in a future version.
            Use `update_summary()` instead.
        """
        print("⚠️  Legacy _update_summary() called — consider switching to update_summary()")
        self.update_summary(recompute=True, sync_back=False, verbose=False)

    def _merge_obs(self):
        """
        Merge `.prot.obs` and `.pep.obs` into a unified sample-level summary.

        This function combines metadata from protein-level and peptide-level `.obs` tables
        into a single summary DataFrame. Shared columns (e.g., 'gradient', 'condition') 
        are taken from `.prot.obs` by default if present in both.

        Returns:
            pandas.DataFrame: Merged observation metadata for all samples.
        """
        if self.prot is not None:
            summary = self.prot.obs.copy()
            if self.pep is not None:
                for col in self.pep.obs.columns:
                    if col not in summary.columns:
                        summary[col] = self.pep.obs[col]
        elif self.pep is not None:
            summary = self.pep.obs.copy()
        else:
            summary = pd.DataFrame()


        self._summary = TrackedDataFrame(
            summary, parent=self, mark_stale_fn=self._mark_summary_stale)

    def _push_summary_to_obs(self, skip_if_contains='pep', verbose=False):
        """
        Push changes from `.summary` back into `.prot.obs` and `.pep.obs`.

        This function updates `.prot.obs` and `.pep.obs` with any modified columns
        in `.summary`. To avoid overwriting incompatible fields, columns containing
        `skip_if_contains` are excluded when updating `.prot.obs`, and similarly,
        columns containing 'prot' are excluded when updating `.pep.obs`.

        Args:
            skip_if_contains (str): Substring used to skip incompatible columns for `.prot.obs`.
                                    Defaults to 'pep'.
            verbose (bool): If True, print updates being pushed to `.obs`.

        Note:
            This is typically called internally by `update_summary(sync_back=True)`.
        """
        if not self._has_data():
            return

        def update_obs_with_summary(obs, summary, skip_if_contains):
            skipped, updated = [], []
            for col in summary.columns:
                if skip_if_contains in str(col):
                    skipped.append(col)
                    continue
                if col not in obs.columns or not obs[col].equals(summary[col]):
                    updated.append(col)
                obs[col] = summary[col]
            return skipped, updated

        # remove unused categorical columns
        for col in self._summary.select_dtypes(['category']).columns:
            self._summary[col] = self._summary[col].cat.remove_unused_categories()

        if self.prot is not None:
            if self.prot.is_view:
                self.prot = self.prot.copy()
            if not self.prot.obs.index.equals(self._summary.index):
                raise ValueError("Mismatch: .summary and .prot.obs have different sample indices.")
            skipped_prot, updated_prot = update_obs_with_summary(self.prot.obs, self._summary, skip_if_contains)
        else:
            skipped_prot, updated_prot = None, []

        if self.pep is not None:
            if self.pep.is_view:
                self.pep = self.pep.copy()
            if not self.pep.obs.index.equals(self._summary.index):
                raise ValueError("Mismatch: .summary and .pep.obs have different sample indices.")
            skipped_pep, updated_pep = update_obs_with_summary(self.pep.obs, self._summary, skip_if_contains='prot')
        else:
            skipped_pep, updated_pep = None, []

        msg = "Pushed summary values back to obs. "
        if skipped_prot:
            msg += f"Skipped for prot: {', '.join(skipped_prot)}. "
        if skipped_pep:
            msg += f"Skipped for pep: {', '.join(skipped_pep)}. "

        self._append_history(msg)
        if verbose:
            print(msg)

        return updated_prot, updated_pep

    def _mark_summary_stale(self):
        """
        Mark the `.summary` as stale.

        This sets the `_summary_is_stale` flag to True, indicating that the
        summary is out of sync with `.obs` or metrics and should be updated
        using `update_summary()`.

        Note:
            This is typically triggered automatically when `.summary` is edited
            (e.g., via `TrackedDataFrame`) or reassigned.
        """
        self._summary_is_stale = True

_update_summary

_update_summary()

Legacy method for updating the .summary table.

This method is retained for backward compatibility and simply calls the newer update_summary() function with default arguments: recompute=True, sync_back=False, and verbose=False.

Note

This method is deprecated and may be removed in a future version. Use update_summary() instead.

Source code in src/scpviz/pAnnData/summary.py
def _update_summary(self):
    """
    Legacy method for updating the `.summary` table.

    This method is retained for backward compatibility and simply calls the newer
    `update_summary()` function with default arguments:
    `recompute=True`, `sync_back=False`, and `verbose=False`.

    Note:
        This method is deprecated and may be removed in a future version.
        Use `update_summary()` instead.
    """
    print("⚠️  Legacy _update_summary() called — consider switching to update_summary()")
    self.update_summary(recompute=True, sync_back=False, verbose=False)

_merge_obs

_merge_obs()

Merge .prot.obs and .pep.obs into a unified sample-level summary.

This function combines metadata from protein-level and peptide-level .obs tables into a single summary DataFrame. Shared columns (e.g., 'gradient', 'condition') are taken from .prot.obs by default if present in both.

Returns:

Type Description

pandas.DataFrame: Merged observation metadata for all samples.

Source code in src/scpviz/pAnnData/summary.py
def _merge_obs(self):
    """
    Merge `.prot.obs` and `.pep.obs` into a unified sample-level summary.

    This function combines metadata from protein-level and peptide-level `.obs` tables
    into a single summary DataFrame. Shared columns (e.g., 'gradient', 'condition') 
    are taken from `.prot.obs` by default if present in both.

    Returns:
        pandas.DataFrame: Merged observation metadata for all samples.
    """
    if self.prot is not None:
        summary = self.prot.obs.copy()
        if self.pep is not None:
            for col in self.pep.obs.columns:
                if col not in summary.columns:
                    summary[col] = self.pep.obs[col]
    elif self.pep is not None:
        summary = self.pep.obs.copy()
    else:
        summary = pd.DataFrame()


    self._summary = TrackedDataFrame(
        summary, parent=self, mark_stale_fn=self._mark_summary_stale)

_push_summary_to_obs

_push_summary_to_obs(skip_if_contains='pep', verbose=False)

Push changes from .summary back into .prot.obs and .pep.obs.

This function updates .prot.obs and .pep.obs with any modified columns in .summary. To avoid overwriting incompatible fields, columns containing skip_if_contains are excluded when updating .prot.obs, and similarly, columns containing 'prot' are excluded when updating .pep.obs.

Parameters:

Name Type Description Default
skip_if_contains str

Substring used to skip incompatible columns for .prot.obs. Defaults to 'pep'.

'pep'
verbose bool

If True, print updates being pushed to .obs.

False
Note

This is typically called internally by update_summary(sync_back=True).

Source code in src/scpviz/pAnnData/summary.py
def _push_summary_to_obs(self, skip_if_contains='pep', verbose=False):
    """
    Push changes from `.summary` back into `.prot.obs` and `.pep.obs`.

    This function updates `.prot.obs` and `.pep.obs` with any modified columns
    in `.summary`. To avoid overwriting incompatible fields, columns containing
    `skip_if_contains` are excluded when updating `.prot.obs`, and similarly,
    columns containing 'prot' are excluded when updating `.pep.obs`.

    Args:
        skip_if_contains (str): Substring used to skip incompatible columns for `.prot.obs`.
                                Defaults to 'pep'.
        verbose (bool): If True, print updates being pushed to `.obs`.

    Note:
        This is typically called internally by `update_summary(sync_back=True)`.
    """
    if not self._has_data():
        return

    def update_obs_with_summary(obs, summary, skip_if_contains):
        skipped, updated = [], []
        for col in summary.columns:
            if skip_if_contains in str(col):
                skipped.append(col)
                continue
            if col not in obs.columns or not obs[col].equals(summary[col]):
                updated.append(col)
            obs[col] = summary[col]
        return skipped, updated

    # remove unused categorical columns
    for col in self._summary.select_dtypes(['category']).columns:
        self._summary[col] = self._summary[col].cat.remove_unused_categories()

    if self.prot is not None:
        if self.prot.is_view:
            self.prot = self.prot.copy()
        if not self.prot.obs.index.equals(self._summary.index):
            raise ValueError("Mismatch: .summary and .prot.obs have different sample indices.")
        skipped_prot, updated_prot = update_obs_with_summary(self.prot.obs, self._summary, skip_if_contains)
    else:
        skipped_prot, updated_prot = None, []

    if self.pep is not None:
        if self.pep.is_view:
            self.pep = self.pep.copy()
        if not self.pep.obs.index.equals(self._summary.index):
            raise ValueError("Mismatch: .summary and .pep.obs have different sample indices.")
        skipped_pep, updated_pep = update_obs_with_summary(self.pep.obs, self._summary, skip_if_contains='prot')
    else:
        skipped_pep, updated_pep = None, []

    msg = "Pushed summary values back to obs. "
    if skipped_prot:
        msg += f"Skipped for prot: {', '.join(skipped_prot)}. "
    if skipped_pep:
        msg += f"Skipped for pep: {', '.join(skipped_pep)}. "

    self._append_history(msg)
    if verbose:
        print(msg)

    return updated_prot, updated_pep

_mark_summary_stale

_mark_summary_stale()

Mark the .summary as stale.

This sets the _summary_is_stale flag to True, indicating that the summary is out of sync with .obs or metrics and should be updated using update_summary().

Note

This is typically triggered automatically when .summary is edited (e.g., via TrackedDataFrame) or reassigned.

Source code in src/scpviz/pAnnData/summary.py
def _mark_summary_stale(self):
    """
    Mark the `.summary` as stale.

    This sets the `_summary_is_stale` flag to True, indicating that the
    summary is out of sync with `.obs` or metrics and should be updated
    using `update_summary()`.

    Note:
        This is typically triggered automatically when `.summary` is edited
        (e.g., via `TrackedDataFrame`) or reassigned.
    """
    self._summary_is_stale = True

validation

Provides internal validation checks for data consistency across .prot, .pep, .summary, and the RS matrix.

This mixin ensures that core components of the pAnnData object are structurally aligned and reports any mismatches or inconsistencies in dimensionality, identifiers, and matrix shapes.

Functions:

validate:
    Comprehensive integrity check for .prot, .pep, .summary, and RS matrix. Returns True if all checks pass.

_check_data:
    Utility method to verify that protein or peptide data exists. Raises error if missing.

_check_rankcol:
    Verifies presence of 'Average: <class>' and 'Rank: <class>' columns in `.var` for use with rank-based plotting.
Source code in src/scpviz/pAnnData/validation.py
class ValidationMixin:
    """
    Provides internal validation checks for data consistency across `.prot`, `.pep`, `.summary`, and the RS matrix.

    This mixin ensures that core components of the pAnnData object are structurally aligned and reports any mismatches
    or inconsistencies in dimensionality, identifiers, and matrix shapes.

    Functions:

        validate:
            Comprehensive integrity check for .prot, .pep, .summary, and RS matrix. Returns True if all checks pass.

        _check_data:
            Utility method to verify that protein or peptide data exists. Raises error if missing.

        _check_rankcol:
            Verifies presence of 'Average: <class>' and 'Rank: <class>' columns in `.var` for use with rank-based plotting.
    """
    def validate(self, verbose=True):
        """
        Check internal consistency of the pAnnData object.

        This function verifies that `.prot`, `.pep`, `.summary`, and `.rs` are 
        internally aligned, with matching dimensions, index values, and consistency
        between shared sample identifiers. It prints helpful diagnostics if issues
        are detected.

        Checks Performed:
        -----------------
        - `.obs` and `.var` shapes match `.X` for both `.prot` and `.pep`
        - `.obs` and `.var` indices are unique
        - `.prot.obs_names` match `.pep.obs_names`
        - `.summary.index` matches `.obs.index` for both `.prot` and `.pep`
        - `.rs.shape` matches (n_proteins, n_peptides)
        - Prints RS matrix sparsity and connectivity stats (if verbose=True)

        Args:
            verbose (bool): If True, print summary of validation and RS stats.

        Returns:
            bool: True if all checks pass, False otherwise.

        Example:
            To validate the pAnnData object and check for consistency issues:
                ```python
                is_valid = pdata.validate()
                if not is_valid:
                    print("Fix issues before proceeding.")
                ```
        """
        issues = []

        # --- Check prot and pep dimensions ---
        for label, ad in [('prot', self.prot), ('pep', self.pep)]:
            if ad is not None:
                if ad.obs.shape[0] != ad.X.shape[0]:
                    issues.append(f"{label}.obs rows ({ad.obs.shape[0]}) != {label}.X rows ({ad.X.shape[0]})")
                if ad.var.shape[0] != ad.X.shape[1]:
                    issues.append(f"{label}.var rows ({ad.var.shape[0]}) != {label}.X cols ({ad.X.shape[1]})")
                if ad.obs.index.duplicated().any():
                    issues.append(f"{label}.obs has duplicated index values")
                if ad.var.index.duplicated().any():
                    issues.append(f"{label}.var has duplicated index values")

        # --- Check obs name overlap between prot and pep ---
        if self.prot is not None and self.pep is not None:
            prot_names = set(self.prot.obs_names)
            pep_names = set(self.pep.obs_names)
            if prot_names != pep_names:
                missing_in_pep = prot_names - pep_names
                missing_in_prot = pep_names - prot_names
                issues.append("prot and pep obs_names do not match")
                if missing_in_pep:
                    issues.append(f"  - {len(missing_in_pep)} samples in prot but not in pep")
                if missing_in_prot:
                    issues.append(f"  - {len(missing_in_prot)} samples in pep but not in prot")

        # --- Check .summary alignment ---
        if self._summary is not None:
            for label, ad in [('prot', self.prot), ('pep', self.pep)]:
                if ad is not None:
                    if not ad.obs.index.equals(self._summary.index):
                        issues.append(f"{label}.obs index does not match .summary index")

        # --- Check RS matrix shape + stats ---
        if self.rs is not None and self.prot is not None and self.pep is not None:
            rs_shape = self.rs.shape
            expected_shape = (self.prot.shape[1], self.pep.shape[1])
            if rs_shape != expected_shape:
                issues.append(f"RS shape mismatch: got {rs_shape}, expected {expected_shape} (proteins × peptides)")
            elif verbose:
                nnz = self.rs.nnz if sparse.issparse(self.rs) else np.count_nonzero(self.rs)
                total = self.rs.shape[0] * self.rs.shape[1]
                sparsity = 100 * (1 - nnz / total)
                print(f"{format_log_prefix('info_only', indent=1)} RS matrix: {rs_shape} (proteins × peptides), sparsity: {sparsity:.2f}%")

                rs = self.rs

                row_links = rs.getnnz(axis=1)  # peptides per protein
                col_links = rs.getnnz(axis=0)  # proteins per peptide

                # Unique peptides (linked to only 1 protein)
                unique_peptides_mask = col_links == 1
                unique_counts = rs[:, unique_peptides_mask].getnnz(axis=1)  # unique peptides per protein

                # Summary stats
                print(f"   - Proteins with ≥2 *unique* linked peptides: {(unique_counts >= 2).sum()}/{rs_shape[0]}")
                print(f"   - Peptides linked to ≥2 proteins: {(col_links >= 2).sum()}/{rs_shape[1]}")
                print(f"   - Mean peptides per protein: {row_links.mean():.2f}")
                print(f"   - Mean proteins per peptide: {col_links.mean():.2f}")

        # --- Summary of results ---
        if issues:
            if verbose:
                print(f"{format_log_prefix('error')} Validation failed with the following issues:")
                for issue in issues:
                    print(" -", issue)
            return False
        else:
            if verbose:
                print(f"{format_log_prefix('result')} pAnnData object is valid.")
            return True

    def _check_data(self, on):
        """
        Internal check for existence of protein or peptide data.

        Args:
            on (str): One of 'protein', 'peptide', 'prot', or 'pep'.

        Returns:
            bool: True if corresponding data exists.

        Raises:
            ValueError: If `on` is not a valid option or if the corresponding data is missing.
        """
        # check if protein or peptide data exists
        if on not in ['protein', 'peptide' , 'prot', 'pep']:
            raise ValueError("Invalid input: on must be either 'protein' or 'peptide'.")
        elif (on == 'protein' or on == 'prot') and self.prot is None:
            raise ValueError("No protein data found in AnnData object.")
        elif (on == 'peptide' or on == 'pep') and self.pep is None:
            raise ValueError("No peptide data found in AnnData object.")
        else:
            return True

    def _check_rankcol(self, on = 'protein', class_values = None):
        """
        Internal check for existence of average and rank columns in `.var`.

        This function ensures that for each `class_value`, both of the following 
        columns exist in the `.var` of the chosen modality:
            - 'Average: <class_value>'
            - 'Rank: <class_value>'

        Args:
            on (str): 'protein' or 'peptide'.
            class_values (list of str): Class values expected to have been used in plot_rankquank().

        Raises:
            ValueError: If class_values is None, or if required columns are missing from `.var`.
        """
        # check if average and rank columns exist for the specified class values
        if on == 'protein':
            adata = self.prot
        elif on == 'peptide':
            adata = self.pep

        if class_values is None:
            raise ValueError("class_values must be None")

        for class_value in class_values:
            average_col = f'Average: {class_value}'
            rank_col = f'Rank: {class_value}'
            if average_col not in adata.var.columns or rank_col not in adata.var.columns:
                raise ValueError(f"Class name not found in .var. Please run plot_rankquank() beforehand and check that the input matches the class names in {on}.var['Average: ']")

_check_data

_check_data(on)

Internal check for existence of protein or peptide data.

Parameters:

Name Type Description Default
on str

One of 'protein', 'peptide', 'prot', or 'pep'.

required

Returns:

Name Type Description
bool

True if corresponding data exists.

Raises:

Type Description
ValueError

If on is not a valid option or if the corresponding data is missing.

Source code in src/scpviz/pAnnData/validation.py
def _check_data(self, on):
    """
    Internal check for existence of protein or peptide data.

    Args:
        on (str): One of 'protein', 'peptide', 'prot', or 'pep'.

    Returns:
        bool: True if corresponding data exists.

    Raises:
        ValueError: If `on` is not a valid option or if the corresponding data is missing.
    """
    # check if protein or peptide data exists
    if on not in ['protein', 'peptide' , 'prot', 'pep']:
        raise ValueError("Invalid input: on must be either 'protein' or 'peptide'.")
    elif (on == 'protein' or on == 'prot') and self.prot is None:
        raise ValueError("No protein data found in AnnData object.")
    elif (on == 'peptide' or on == 'pep') and self.pep is None:
        raise ValueError("No peptide data found in AnnData object.")
    else:
        return True

_check_rankcol

_check_rankcol(on='protein', class_values=None)

Internal check for existence of average and rank columns in .var.

This function ensures that for each class_value, both of the following columns exist in the .var of the chosen modality: - 'Average: ' - 'Rank: '

Parameters:

Name Type Description Default
on str

'protein' or 'peptide'.

'protein'
class_values list of str

Class values expected to have been used in plot_rankquank().

None

Raises:

Type Description
ValueError

If class_values is None, or if required columns are missing from .var.

Source code in src/scpviz/pAnnData/validation.py
def _check_rankcol(self, on = 'protein', class_values = None):
    """
    Internal check for existence of average and rank columns in `.var`.

    This function ensures that for each `class_value`, both of the following 
    columns exist in the `.var` of the chosen modality:
        - 'Average: <class_value>'
        - 'Rank: <class_value>'

    Args:
        on (str): 'protein' or 'peptide'.
        class_values (list of str): Class values expected to have been used in plot_rankquank().

    Raises:
        ValueError: If class_values is None, or if required columns are missing from `.var`.
    """
    # check if average and rank columns exist for the specified class values
    if on == 'protein':
        adata = self.prot
    elif on == 'peptide':
        adata = self.pep

    if class_values is None:
        raise ValueError("class_values must be None")

    for class_value in class_values:
        average_col = f'Average: {class_value}'
        rank_col = f'Rank: {class_value}'
        if average_col not in adata.var.columns or rank_col not in adata.var.columns:
            raise ValueError(f"Class name not found in .var. Please run plot_rankquank() beforehand and check that the input matches the class names in {on}.var['Average: ']")