Skip to content

Pipeline & Prioritization API

Programmatic Python entry points backing tcrsift run (tcrsift.pipeline) and tcrsift prioritize (tcrsift.prioritize / tcrsift.til_prioritize).

pipeline

End-to-end TCRsift antigen-enrichment pipeline (:func:run_pipeline).

Provides the Python API backing tcrsift run, orchestrating sample loading, T-cell phenotyping, optional single-cell atlas embedding, paired stimulation scoring, clonotype aggregation, statistical/threshold filtering, public TCR database annotation, TIL matching, full-length construct assembly, and QC/PDF reporting.

PipelineResult dataclass

Structured output returned by :func:run_pipeline.

Source code in tcrsift/pipeline.py
@dataclass
class PipelineResult:
    """Structured output returned by :func:`run_pipeline`."""

    output_dir: Path
    data_dir: Path
    plots_dir: Path
    species: str
    clonotypes: pd.DataFrame
    filtered: pd.DataFrame
    annotated: pd.DataFrame
    til_matched: pd.DataFrame
    assembled: pd.DataFrame | None
    stimulation_response: pd.DataFrame | None
    funnel_counts: dict[str, int]

    def __getitem__(self, key: str) -> Any:
        return getattr(self, key)

run_pipeline

run_pipeline(sample_sheet: str | Path | SampleSheet, output_dir: str | Path, config: TCRsiftConfig | None = None, *, til_sample_specs: list[str] | None = None, cache_dir: str | Path | None = None, no_assemble: bool = False, no_sheet_contigs: bool = False, allow_canonical_fallback: bool = False, report_name: str | None = None) -> PipelineResult

Run the end-to-end TCRsift culture/stimulation pipeline.

Parameters:

Name Type Description Default
sample_sheet str, Path, or SampleSheet

Path to a YAML/CSV sample sheet or a pre-built :class:SampleSheet.

required
output_dir str or Path

Output directory for data/, plots/, config.yaml, and reports.

required
config TCRsiftConfig

Pipeline configuration (defaults to TCRsiftConfig()).

None
til_sample_specs list of str

Repeatable NAME=TYPE:PATH TIL sample specifications (overrides sheet TILs).

None
cache_dir str or Path

Reference-database cache directory override.

None
no_assemble bool

Skip Step 7 whole-repertoire construct assembly when True.

False
no_sheet_contigs bool

Disable automatic sample-sheet contig assembly root detection (#201).

False
allow_canonical_fallback bool

Permit canonical constant/leader fallback when donor contigs cannot verify fidelity.

False
report_name str

Explicit report filename stem override.

None

Returns:

Type Description
PipelineResult

Structured summary of output paths, intermediate/final DataFrames, and funnel counts.

Source code in tcrsift/pipeline.py
 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
def run_pipeline(
    sample_sheet: str | Path | SampleSheet,
    output_dir: str | Path,
    config: TCRsiftConfig | None = None,
    *,
    til_sample_specs: list[str] | None = None,
    cache_dir: str | Path | None = None,
    no_assemble: bool = False,
    no_sheet_contigs: bool = False,
    allow_canonical_fallback: bool = False,
    report_name: str | None = None,
) -> PipelineResult:
    """Run the end-to-end TCRsift culture/stimulation pipeline.

    Parameters
    ----------
    sample_sheet : str, Path, or SampleSheet
        Path to a YAML/CSV sample sheet or a pre-built :class:`SampleSheet`.
    output_dir : str or Path
        Output directory for ``data/``, ``plots/``, ``config.yaml``, and reports.
    config : TCRsiftConfig, optional
        Pipeline configuration (defaults to ``TCRsiftConfig()``).
    til_sample_specs : list of str, optional
        Repeatable ``NAME=TYPE:PATH`` TIL sample specifications (overrides sheet TILs).
    cache_dir : str or Path, optional
        Reference-database cache directory override.
    no_assemble : bool
        Skip Step 7 whole-repertoire construct assembly when ``True``.
    no_sheet_contigs : bool
        Disable automatic sample-sheet contig assembly root detection (#201).
    allow_canonical_fallback : bool
        Permit canonical constant/leader fallback when donor contigs cannot verify fidelity.
    report_name : str, optional
        Explicit report filename stem override.

    Returns
    -------
    PipelineResult
        Structured summary of output paths, intermediate/final DataFrames, and funnel counts.
    """
    from ._schema import truthy_flag_series
    from .annotate import annotate_clonotypes
    from .assemble import (
        assemble_full_sequences,
        collect_germline_variants,
        enforce_contig_fidelity,
        export_fasta,
    )
    from .clonotype import aggregate_clonotypes, export_clonotypes_airr
    from .datacache import ensure_cached
    from .filter import (
        bucket_by_donor_sharing,
        filter_clonotypes,
        pick_strictest_populated_tier,
        resolve_fdr_scope,
        resolve_fdr_tiers_for_method,
        resolve_filter_mode_kwargs,
        split_by_tier,
        split_clonotypes_by_donor,
        split_clonotypes_by_sample,
    )
    from .loader import load_samples
    from .phenotype import apply_cd3_gate, filter_by_tcell_type, phenotype_cells
    from .plots import (
        create_pipeline_funnel,
        create_tcr_sequence_pdf,
        generate_report,
        plot_annotations,
        plot_assembly,
        plot_clonotypes,
        plot_filter,
        plot_phenotype,
        plot_qc,
        plot_til,
        set_plot_format,
    )
    from .provenance import write_provenance
    from .species import resolve_species
    from .til import load_til_specs, match_til

    if config is None:
        config = TCRsiftConfig()
    else:
        config = copy.deepcopy(config)

    set_plot_format(config.output.plot_format)

    if config.output.baseline_markers is not None:
        from .format import set_baseline_markers

        set_baseline_markers(*config.output.baseline_markers)

    sheet_obj = (
        sample_sheet
        if isinstance(sample_sheet, SampleSheet)
        else load_sample_sheet(sample_sheet)
    )

    if not config.til.til_samples:
        til_samples = sheet_obj.get_til_samples()
        if til_samples:
            til_sample_names = [s.sample for s in til_samples]
            config.til.til_samples = til_sample_names
            print(f"Auto-detected TIL samples from sample sheet: {til_sample_names}")

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    data_dir = output_dir / "data"
    data_dir.mkdir(exist_ok=True)
    plots_dir = output_dir / "plots"
    plots_dir.mkdir(exist_ok=True)

    config.to_yaml(output_dir / "config.yaml")
    write_provenance(output_dir)

    print("=" * 60)
    print("TCRsift Pipeline")
    print("=" * 60)

    funnel_counts: dict[str, int] = {}

    # Step 1: Load
    print("\n[1/7] Loading samples...")
    requested_species = (
        config.species
        if config.species != "auto"
        else (getattr(sheet_obj, "species", None) or "auto")
    )
    adata = load_samples(
        sheet_obj if isinstance(sample_sheet, SampleSheet) else sample_sheet,
        min_genes=config.load.min_genes,
        max_genes=config.load.max_genes,
        min_counts=config.load.min_counts,
        max_counts=config.load.max_counts,
        min_mito_pct=config.load.min_mito_pct,
        max_mito_pct=config.load.max_mito_pct,
        species=requested_species,
    )
    run_species = resolve_species(requested_species, adata=adata, warn_mismatch=False)
    adata.write_h5ad(data_dir / "loaded.h5ad")
    funnel_counts["Raw Cells"] = len(adata)
    print(f"  Loaded {len(adata)} cells")

    if "source" in adata.obs.columns:
        non_til_mask = adata.obs["source"] != "til"
        n_til = (~non_til_mask).sum()
        if n_til > 0:
            if non_til_mask.sum() == 0:
                raise TCRsiftValidationError(
                    "No non-TIL samples found for culture pipeline",
                    hint="The run command expects at least one non-TIL sample. "
                    "Use match-til or load/clonotype commands for TIL-only analysis.",
                )
            adata = adata[non_til_mask].copy()
            funnel_counts["Raw Cells"] = len(adata)
            print(f"  Excluding {n_til} TIL cells from culture pipeline")

    if "CDR3_beta" in adata.obs.columns:
        n_with_vdj = int(adata.obs["CDR3_beta"].notna().sum())
        funnel_counts["With VDJ"] = n_with_vdj
        print(f"  With VDJ data: {n_with_vdj} cells")

    if config.output.generate_plots:
        plot_qc(adata, plots_dir)

    # Step 2: Phenotype
    print("\n[2/7] Phenotyping T cells...")
    adata = phenotype_cells(
        adata,
        cd4_cd8_ratio=config.phenotype.cd4_cd8_ratio,
        min_cd3_reads=config.phenotype.min_cd3_reads,
    )
    adata.write_h5ad(data_dir / "phenotyped.h5ad")
    if config.output.generate_plots:
        plot_phenotype(adata, plots_dir)

    tcell_type = config.filter.tcell_type
    if tcell_type != "both":
        adata = filter_by_tcell_type(adata, tcell_type)
        print(f"  Filtered to {tcell_type.upper()}+: {len(adata)} cells")

    min_cd3 = config.phenotype.min_cd3_reads
    n_before_cd3 = len(adata)
    adata = apply_cd3_gate(adata, min_cd3)
    if len(adata) != n_before_cd3:
        print(f"  CD3 gate (>={min_cd3} reads): {len(adata)}/{n_before_cd3} cells pass")

    funnel_counts["Phenotyped"] = len(adata)

    if config.embed.enabled:
        print("\n  Embedding cells (Pearson residuals → PCA → Harmony → UMAP → Leiden)...")
        try:
            from .annotate_cells import annotate_cells, gates_from_phenotype_config
            from .embed import embed_cells
            from .plots import plot_umap

            atlas = embed_cells(adata, config.embed)
            annotate_cells(
                atlas,
                allowed_types=config.phenotype.allowed_types,
                gates=gates_from_phenotype_config(config.phenotype, species=run_species),
                min_subtype_frac=config.phenotype.min_subtype_frac,
                species=run_species,
            )
            atlas.write_h5ad(data_dir / "atlas.h5ad")
            print(
                f"  Atlas: {atlas.obs['leiden'].nunique()} Leiden clusters, "
                f"{atlas.obs['phenotype_base'].nunique()} cell types "
                f"→ {data_dir / 'atlas.h5ad'}"
            )
            if config.output.generate_plots:
                plot_umap(atlas, "phenotype", plots_dir / "atlas_umap_phenotype.png")
                plot_umap(atlas, "leiden", plots_dir / "atlas_umap_leiden.png")
                print(f"  Atlas UMAPs (phenotype, leiden) → {plots_dir}")
        except ImportError as e:
            print(f"  [embed] skipped — install tcrsift[atlas] to enable ({e})")

    # Step 3: Clonotype (with paired control comparison when source == 'control' is present)
    stim_resp_df = None
    stim_join_col = "CDR3ab" if config.clonotype.group_by == "CDR3ab" else "CDR3_beta"
    if "source" in adata.obs.columns and (adata.obs["source"].astype(str) == "control").any():
        non_ctrl_mask = adata.obs["source"].astype(str) != "control"
        n_ctrl_cells = int((~non_ctrl_mask).sum())
        if int(non_ctrl_mask.sum()) == 0:
            raise TCRsiftValidationError(
                "No non-control stimulated/culture cells remain for clonotype aggregation",
                hint="Provide at least one positive sample (e.g. source='culture') alongside source='control'.",
            )
        try:
            from .filter import score_stimulation_response

            stim_score_cols: list[str] = []
            if getattr(adata, "X", None) is not None and adata.n_vars > 0:
                import scanpy as sc

                from .signature_methods import score_by_name

                stim_adata = adata.copy()
                sc.pp.normalize_total(stim_adata, target_sum=10_000)
                sc.pp.log1p(stim_adata)
                for sig_name in ("AIM", "AcuteActivation"):
                    try:
                        vals = score_by_name(
                            stim_adata,
                            sig_name,
                            log1p=False,
                            on_missing="warn",
                            species=run_species,
                        )
                        col_name = f"signature_{sig_name}"
                        adata.obs[col_name] = vals.to_numpy(dtype=float)
                        stim_score_cols.append(col_name)
                    except Exception as sig_exc:
                        logger.debug("Skipping stimulation %s score: %s", sig_name, sig_exc)
                del stim_adata

            if (
                "patient_id" in adata.obs.columns
                and adata.obs["patient_id"].dropna().nunique() > 1
            ):
                per_donor_resp = []
                for _, donor_idx in adata.obs.groupby("patient_id", observed=True).indices.items():
                    donor_adata = adata[donor_idx]
                    donor_src = donor_adata.obs["source"].astype(str)
                    if (donor_src == "control").any() and (donor_src != "control").any():
                        per_donor_resp.append(
                            score_stimulation_response(
                                donor_adata,
                                clone_col=stim_join_col,
                                score_cols=stim_score_cols or None,
                            )
                        )
                stim_resp_df = (
                    pd.concat(per_donor_resp, ignore_index=True)
                    .sort_values(["fisher_pvalue", "stim_cells"], ascending=[True, False], kind="mergesort")
                    .drop_duplicates(stim_join_col)
                    if per_donor_resp
                    else None
                )
            else:
                stim_resp_df = score_stimulation_response(
                    adata,
                    clone_col=stim_join_col,
                    score_cols=stim_score_cols or None,
                )
            if stim_resp_df is not None:
                stim_resp_df.to_csv(data_dir / "stimulation_response.csv", index=False)
                print(
                    f"  Scored stimulation vs control ({n_ctrl_cells} control cells) -> stimulation_response.csv"
                )
        except TCRsiftValidationError as exc:
            print(f"  [stimulation] skipped control comparison: {exc}")
        adata = adata[non_ctrl_mask].copy()
        print(f"  Excluded {n_ctrl_cells} control cells before positive clonotype aggregation")

    print("\n[3/7] Aggregating clonotypes...")
    clonotypes = aggregate_clonotypes(
        adata,
        group_by=config.clonotype.group_by,
        min_umi=config.clonotype.min_umi,
        handle_doublets=config.clonotype.handle_doublets,
        attribution=config.attribution,
        doublet_warn_rate=config.clonotype.doublet_warn_rate,
    )
    if stim_resp_df is not None and stim_join_col in clonotypes.columns:
        extra_stim_cols = [
            c
            for c in stim_resp_df.columns
            if c.startswith(("stim_mean_", "control_mean_", "delta_"))
        ]
        stim_cols = (
            stim_resp_df[
                [
                    stim_join_col,
                    "control_cells",
                    "control_frequency",
                    "log2_fold_change",
                    "fisher_pvalue",
                    "fisher_fdr",
                    *extra_stim_cols,
                ]
            ]
            .rename(
                columns={
                    "log2_fold_change": "stim_log2_fc",
                    "fisher_pvalue": "stim_fisher_pvalue",
                    "fisher_fdr": "stim_fisher_fdr",
                }
            )
            .drop_duplicates(stim_join_col)
        )
        clonotypes = clonotypes.merge(stim_cols, on=stim_join_col, how="left")
        clonotypes["control_cells"] = clonotypes["control_cells"].fillna(0).astype(int)
        clonotypes["control_frequency"] = clonotypes["control_frequency"].fillna(0.0)

    if getattr(config.annotate, "call_multimers", False):
        from .multimer import call_multimers_for_adata

        mm_df = call_multimers_for_adata(
            adata,
            sheet_obj,
            clone_col=stim_join_col,
            min_umi=config.annotate.multimer_min_umi,
            min_nc_ratio=config.annotate.multimer_min_nc_ratio,
            min_specific_cells=config.annotate.multimer_min_specific_cells,
            min_concordance=config.annotate.multimer_min_concordance,
        )
        if not mm_df.empty and stim_join_col in clonotypes.columns:
            mm_df.to_csv(data_dir / "multimer_specificity.csv", index=False)
            clonotypes = clonotypes.merge(
                mm_df.drop(columns=["clone_cells"], errors="ignore"),
                on=stim_join_col,
                how="left",
            )
            clonotypes["multimer_confident"] = truthy_flag_series(
                clonotypes.get("multimer_confident", pd.Series(False, index=clonotypes.index))
            )
            print(
                f"  Called pMHC multimers across {int(clonotypes['multimer_confident'].sum())} confident clones -> multimer_specificity.csv"
            )
    if config.attribution.enabled:
        print("  Attribution ON: weighted fractional clone counts (#176)")

    if config.clonotype.add_pgen_ppost:
        from .annotate_tcrs import add_pgen_ppost

        clonotypes = add_pgen_ppost(clonotypes, backend="kmer", species=run_species)
        scored = [c for c in ("ppost_alpha", "ppost_beta") if c in clonotypes.columns]
        if scored:
            print(f"  Added k-mer Pgen/Ppost → {', '.join(scored)} (for PRISM)")

    clonotypes.to_csv(data_dir / "clonotypes.csv", index=False)
    funnel_counts["Clonotypes"] = len(clonotypes)
    print(f"  Found {len(clonotypes)} clonotypes")
    if config.output.generate_plots:
        plot_clonotypes(clonotypes, plots_dir)

    emit_long = config.output.emit_clone_sample_long
    n_samples_in_run = adata.obs["sample"].nunique() if "sample" in adata.obs.columns else 0
    should_emit_long = (
        emit_long == "always"
        or (emit_long == "auto" and n_samples_in_run >= 2)
    )
    have_method_axis = "enrichment_method" in adata.obs.columns
    has_selection_rules = bool(config.selection.get("rules"))

    long_df = None
    if should_emit_long or have_method_axis or has_selection_rules:
        from .clonotype import build_clone_sample_long

        long_df = build_clone_sample_long(adata, attribution=config.attribution)

    if long_df is not None and "sample" in long_df.columns:
        from .qc import clonal_expansion_metrics

        exp_qc = clonal_expansion_metrics(long_df)
        if not exp_qc.empty:
            exp_qc.to_csv(data_dir / "expansion_qc.csv", index=False)
            print(
                f"  Wrote expansion_qc.csv: {len(exp_qc)} samples "
                f"(top1% / effective-clones / clonality per sample)"
            )
            for _, r in exp_qc[exp_qc["unexpanded"]].iterrows():
                print(f"  ⚠️  sample {r['sample']!r}: {r['warning']}")

    if "sample" in adata.obs.columns:
        from .qc import inter_sample_barcode_jaccard, sample_integrity_qc

        sample_qc = sample_integrity_qc(adata)
        if not sample_qc.empty:
            sample_qc.to_csv(data_dir / "sample_qc.csv", index=False)
            print(
                f"  Wrote sample_qc.csv: {len(sample_qc)} samples "
                "(GEX↔VDJ overlap / barcode Jaccard / anchor integrity)"
            )
            jac = inter_sample_barcode_jaccard(adata)
            if not jac.empty:
                jac.to_csv(data_dir / "sample_barcode_jaccard.csv")
            for _, r in sample_qc[sample_qc["warning"] != ""].iterrows():
                print(f"  ⚠️  sample {r['sample']!r}: {r['warning']}")

    if "enrichment_method" in adata.obs.columns:
        try:
            from .sort_qc import sort_signature_consistency_from_adata

            sort_qc = sort_signature_consistency_from_adata(adata, species=run_species)
        except Exception as exc:
            logger.debug("sort-consistency QC skipped: %s", exc)
            sort_qc = pd.DataFrame()
        if not sort_qc.empty:
            sort_qc.to_csv(data_dir / "sort_consistency_qc.csv", index=False)
            print(
                f"  Wrote sort_consistency_qc.csv: {len(sort_qc)} "
                "(donor, sort) rows (signature enrichment vs label)"
            )
            for _, r in sort_qc[sort_qc["warning"] != ""].iterrows():
                print(f"  ⚠️  {r['donor']}/{r['enrichment_method']}: {r['warning']}")

    if should_emit_long and long_df is not None:
        from .selection import attach_per_sample_tiers

        emitted_long = attach_per_sample_tiers(long_df)
        emitted_long.to_csv(data_dir / "clone_sample_long.csv", index=False)
        print(
            f"  Wrote clone_sample_long.csv: {len(emitted_long)} rows "
            f"({emitted_long['CDR3ab'].nunique()} clones x {n_samples_in_run} samples)"
        )

    # Step 4: Filter
    print("\n[4/7] Filtering clonotypes...")
    user_filter_kwargs = {
        "min_donors": config.filter.min_donors,
        "min_methods_per_donor": config.filter.min_methods_per_donor,
        "min_cells_per_method": config.filter.min_cells_per_method,
        "min_frequency_per_method": config.filter.min_frequency_per_method,
        "min_timepoints": config.filter.min_timepoints,
        "min_timepoints_per_donor": config.filter.min_timepoints_per_donor,
        "min_apcs": config.filter.min_apcs,
        "min_apcs_per_donor": config.filter.min_apcs_per_donor,
        "min_til_cells_per_donor": config.filter.min_til_cells_per_donor,
    }
    mode_kwargs = resolve_filter_mode_kwargs(
        config.filter.filter_mode, user_filter_kwargs
    )

    if config.filter.filter_mode == "cross-donor-public" and "n_donors" in clonotypes.columns:
        if (clonotypes["n_donors"] >= 2).sum() == 0:
            print(
                "  WARNING: filter_mode='cross-donor-public' requested but no clone "
                "has n_donors >= 2. Result will likely be empty."
            )

    _cohort_donors: set[str] = set()
    if "patient_id" in adata.obs.columns:
        _cohort_donors = {
            str(v).strip()
            for v in adata.obs["patient_id"].dropna().unique()
            if str(v).strip()
        }
    if not _cohort_donors and "donors" in clonotypes.columns and len(clonotypes):
        for _dval in clonotypes["donors"].dropna().astype(str):
            _cohort_donors.update(t.strip() for t in _dval.split(";") if t.strip())
    n_donors_in_run = (
        len(_cohort_donors)
        if _cohort_donors
        else (
            int(clonotypes["n_donors"].max())
            if "n_donors" in clonotypes.columns and len(clonotypes)
            else 1
        )
    )
    sheet_shares_antigen = getattr(sheet_obj, "donors_share_antigen", False)
    donors_share_antigen = config.filter.donors_share_antigen or sheet_shares_antigen
    resolved_scope = resolve_fdr_scope(
        config.filter.fdr_scope,
        n_donors=n_donors_in_run,
        donors_share_antigen=donors_share_antigen,
    )
    print(f"  FDR scope: {resolved_scope}")

    fdr_tiers_arg, fdr_inert = resolve_fdr_tiers_for_method(
        config.filter.method, config.filter.fdr_tiers, FilterConfig().fdr_tiers
    )
    if fdr_inert:
        print(
            f"  WARNING: fdr_tiers is set but filter.method={config.filter.method!r}; "
            "fdr_tiers only applies to method='logistic'. Using fixed abundance "
            "tiers — the fdr_tiers list is ignored. Set method: logistic for "
            "FDR-based tiering."
        )

    def _filter_one(df_in: pd.DataFrame) -> pd.DataFrame:
        return filter_clonotypes(
            df_in,
            method=config.filter.method,
            tcell_type=tcell_type,
            min_cells=config.filter.min_cells,
            min_frequency=config.filter.min_frequency,
            require_complete=config.filter.require_complete,
            fdr_tiers=fdr_tiers_arg,
            stim_fdr_threshold=config.filter.stim_fdr_threshold,
            stim_log2_fc_threshold=config.filter.stim_log2_fc_threshold,
            stim_delta_threshold=config.filter.stim_delta_threshold,
            **mode_kwargs,
        )

    if resolved_scope == "global":
        filtered = _filter_one(clonotypes)
        tier_dfs = split_by_tier(filtered)
        tier_counts = {}
        for tier, tier_df in tier_dfs.items():
            tier_df.to_csv(data_dir / f"filtered_{tier}.csv", index=False)
            tier_counts[tier] = len(tier_df)
            print(f"  {tier}: {len(tier_df)} clonotypes")
    else:
        if long_df is None:
            from .clonotype import build_clone_sample_long

            long_df = build_clone_sample_long(adata, attribution=config.attribution)
        if resolved_scope == "per-donor":
            subsets = split_clonotypes_by_donor(clonotypes, long_df)
            label = "donor"
        else:
            subsets = split_clonotypes_by_sample(clonotypes, long_df)
            label = "sample"

        per_subset_filtered = []
        tier_counts = {}
        for key, sub_clonotypes in subsets.items():
            if len(sub_clonotypes) == 0:
                continue
            try:
                sub_filtered = _filter_one(sub_clonotypes)
            except TCRsiftValidationError as exc:
                print(
                    f"  WARNING: no clones survived filtering for "
                    f"{label}={key}: {exc}"
                )
                continue
            sub_filtered = sub_filtered.copy()
            sub_filtered[f"scope_{label}"] = key
            per_subset_filtered.append(sub_filtered)

            sub_tier_dfs = split_by_tier(sub_filtered)
            safe_key = str(key).replace("/", "_").replace(" ", "_")
            for tier, tier_df in sub_tier_dfs.items():
                tier_df.to_csv(
                    data_dir / f"filtered_{tier}_{safe_key}.csv",
                    index=False,
                )
                tier_counts[f"{tier}_{safe_key}"] = len(tier_df)
                print(f"  {label}={key} {tier}: {len(tier_df)} clonotypes")

        if per_subset_filtered:
            combined_sub = pd.concat(per_subset_filtered, ignore_index=True)
            scope_col = f"scope_{label}"
            tier_rank_map = {"tier1": 1, "tier2": 2, "tier3": 3, "tier4": 4, "tier5": 5}
            if "CDR3ab" in combined_sub.columns and combined_sub["CDR3ab"].duplicated().any():
                combined_sub = combined_sub.assign(
                    _trank=combined_sub.get("tier", pd.Series(dtype=object)).map(
                        lambda t: tier_rank_map.get(t, 99)
                    )
                ).sort_values(["_trank", "max_frequency"], ascending=[True, False], kind="mergesort")
                scopes_by_clone = (
                    combined_sub.groupby("CDR3ab", observed=True)[scope_col]
                    .apply(lambda s: ";".join(dict.fromkeys(str(x) for x in s.dropna())))
                    .to_dict()
                )
                deduped = combined_sub.drop_duplicates("CDR3ab", keep="first").drop(columns=["_trank"]).copy()
                deduped[scope_col] = deduped["CDR3ab"].map(scopes_by_clone)
            else:
                deduped = combined_sub.copy()
            if "CDR3ab" in deduped.columns and "CDR3ab" in clonotypes.columns:
                cohort_cols = [
                    c for c in (
                        "cell_count", "max_frequency", "mean_frequency", "n_samples",
                        "n_conditions", "n_methods", "max_methods_per_donor",
                        "max_cells_per_method", "max_frequency_per_method",
                        "n_timepoints", "max_timepoints_per_donor",
                        "n_apcs", "max_apcs_per_donor",
                    )
                    if c in clonotypes.columns and c in deduped.columns
                ]
                if cohort_cols:
                    base_lookup = clonotypes.drop_duplicates("CDR3ab").set_index("CDR3ab")[cohort_cols]
                    for c in cohort_cols:
                        deduped[c] = deduped["CDR3ab"].map(base_lookup[c]).values
            filtered = deduped.reset_index(drop=True)
        else:
            filtered = pd.DataFrame()

    if config.filter.filter_mode == "shared-high-freq":
        path = data_dir / "filtered_shared_high_freq.csv"
        filtered.to_csv(path, index=False)
        print(f"  shared-high-freq: {len(filtered)} clonotypes -> {path.name}")
    elif config.filter.filter_mode == "cross-donor-public":
        path = data_dir / "filtered_cross_donor_public.csv"
        filtered.to_csv(path, index=False)
        print(f"  cross-donor-public: {len(filtered)} clonotypes -> {path.name}")

    sharing_buckets = bucket_by_donor_sharing(filtered)
    for bucket, bucket_df in sharing_buckets.items():
        path = data_dir / f"filtered_{bucket}.csv"
        bucket_df.to_csv(path, index=False)
        print(f"  {bucket}: {len(bucket_df)} clonotypes -> {path.name}")

    if long_df is not None:
        from .clonotype import (
            build_method_overlap_matrices,
            build_method_recovery_table,
            build_per_method_rankings,
            build_selection_sets,
            set_overlap_table,
        )

        rankings = build_per_method_rankings(
            filtered, long_df, top_n=config.output.per_method_top_n
        )
        if rankings:
            method_dir = data_dir / "filtered_by_method"
            method_dir.mkdir(parents=True, exist_ok=True)
            for (donor, method), ranked in rankings.items():
                safe_donor = donor.replace("/", "_").replace(" ", "_")
                safe_method = method.replace("/", "_").replace(" ", "_")
                ranked.to_csv(
                    method_dir / f"{safe_donor}__{safe_method}.csv",
                    index=False,
                )
            print(
                f"  Wrote {len(rankings)} per-method ranked CSVs to "
                f"{method_dir.name}/"
            )

        similarity = config.output.method_overlap_similarity
        overlap_matrices = build_method_overlap_matrices(
            filtered, long_df, similarity=similarity
        )
        if overlap_matrices:
            for donor, mat in overlap_matrices.items():
                safe_donor = donor.replace("/", "_").replace(" ", "_")
                mat.to_csv(data_dir / f"method_overlap_{safe_donor}.csv")
                if config.output.generate_plots:
                    from .plots import plot_method_overlap

                    plot_method_overlap(
                        mat,
                        plots_dir / f"method_overlap_{safe_donor}.png",
                        similarity=similarity,
                        donor=donor,
                    )
            print(
                f"  Method overlap ({similarity}): "
                f"{len(overlap_matrices)} donor matrices"
            )

        method_sets = build_selection_sets(
            long_df, set_col="method", clones=set(filtered["CDR3ab"]) if "CDR3ab" in filtered.columns else set()
        )
        if len(method_sets) >= 2:
            set_overlap_table(method_sets).to_csv(
                data_dir / "method_overlap_sets.csv", index=False
            )
            if config.output.generate_plots:
                from .plots import plot_set_overlap

                plot_set_overlap(
                    method_sets,
                    plots_dir / "method_overlap_upset.png",
                    title="Selected-clone overlap across methods",
                )
            print(f"  Method set overlap (UpSet): {len(method_sets)} methods")

        target_tier = pick_strictest_populated_tier(filtered)
        recovery = build_method_recovery_table(
            filtered, long_df, tier=target_tier
        )
        if not recovery.empty:
            recovery.to_csv(data_dir / "method_recovery.csv", index=False)
            if config.output.generate_plots:
                from .plots import plot_method_recovery

                plot_method_recovery(
                    recovery,
                    plots_dir / "method_recovery.png",
                    tier_label=target_tier,
                )
            print(
                f"  Method recovery ({target_tier}): "
                f"{recovery['method'].nunique()} methods × "
                f"{recovery['donor'].nunique()} donors"
            )

    funnel_counts["Filtered"] = len(filtered)
    if config.output.generate_plots:
        plot_filter(filtered, plots_dir)

    # Step 5: Annotate
    auto_dl = bool(getattr(config.annotate, "auto_download", False))
    vdjdb_path = config.annotate.vdjdb_path or ensure_cached("vdjdb", cache_dir, auto_download=auto_dl)
    iedb_path = config.annotate.iedb_path or ensure_cached("iedb", cache_dir, auto_download=auto_dl)
    cedar_path = config.annotate.cedar_path or ensure_cached("cedar", cache_dir, auto_download=auto_dl)
    iedb_epitope_path = getattr(config.annotate, "iedb_epitope_path", None) or ensure_cached(
        "iedb_epitope", cache_dir, auto_download=auto_dl
    )
    annotated = filtered
    has_annotation = vdjdb_path or iedb_path or cedar_path
    if has_annotation:
        print("\n[5/7] Annotating with public databases...")
        annotated = annotate_clonotypes(
            filtered,
            vdjdb_path=vdjdb_path,
            iedb_path=iedb_path,
            cedar_path=cedar_path,
            iedb_epitope_path=iedb_epitope_path,
            match_by=config.annotate.match_by,
            match_strictness=getattr(config.annotate, "match_strictness", None),
            match_mode=getattr(config.annotate, "match_mode", "exact"),
            max_distance=getattr(config.annotate, "max_distance", 1),
            exclude_viral=config.annotate.exclude_viral,
            flag_only=config.annotate.flag_only,
            species=run_species,
            host_species_filter=getattr(config.annotate, "host_species_filter", "all"),
        )
        annotated.to_csv(data_dir / "annotated.csv", index=False)
        n_viral = annotated["is_viral"].sum() if "is_viral" in annotated.columns else 0
        print(f"  Flagged {n_viral} viral clonotypes")
        if config.output.generate_plots:
            plot_annotations(annotated, plots_dir)
    else:
        print("\n[5/7] Skipping annotation (no databases provided)")

    # Step 6: TIL matching
    til_matched = annotated
    if til_sample_specs:
        print("\n[6/7] Matching against TIL samples from --til-sample...")
        til_data = load_til_specs(til_sample_specs)
        total_cells = sum(len(df) for df in til_data.values())
        print(f"  Loaded {total_cells} TIL cells from {len(til_data)} sample(s)")

        if total_cells > 0:
            til_matched = match_til(
                annotated,
                til_data,
                match_by=config.til.match_by,
                min_til_cells=config.til.min_til_cells,
            )
            til_matched.to_csv(data_dir / "til_matched.csv", index=False)
            n_til = til_matched["til_match"].sum() if "til_match" in til_matched.columns else 0
            print(f"  Found {n_til} clonotypes in TILs")
            if config.output.generate_plots:
                plot_til(til_matched, plots_dir)
        else:
            print("  No TIL cells loaded")
    elif config.til.til_samples:
        print("\n[6/7] Matching against TIL samples...")
        from .til import load_til_samples as _load_til_samples

        til_sample_objs = sheet_obj.get_til_samples()
        til_sample_names = [s.sample for s in til_sample_objs]
        if config.til.til_samples != til_sample_names:
            til_sample_objs = [s for s in til_sample_objs if s.sample in config.til.til_samples]

        if til_sample_objs:
            til_data = _load_til_samples(til_sample_objs)
            total_cells = sum(len(df) for df in til_data.values())
            print(f"  Loaded {total_cells} TIL cells from {len(til_data)} sample(s)")

            if total_cells > 0:
                til_matched = match_til(
                    annotated,
                    til_data,
                    match_by=config.til.match_by,
                    min_til_cells=config.til.min_til_cells,
                )
                til_matched.to_csv(data_dir / "til_matched.csv", index=False)
                n_til = til_matched["til_match"].sum() if "til_match" in til_matched.columns else 0
                print(f"  Found {n_til} clonotypes in TILs")
                if config.output.generate_plots:
                    plot_til(til_matched, plots_dir)
            else:
                print("  No TIL cells loaded")
        else:
            print("  No TIL samples found matching configuration")
    else:
        print("\n[6/7] Skipping TIL matching (no TIL samples specified)")

    # Step 7: Assemble
    assembled = None
    n_selected_clones: int | None = None
    n_non_viral: int | None = None
    rules = None
    if config.selection.get("rules") and long_df is not None:
        from .selection import select_from_clone_sample_long

        selection_long = long_df
        sig_names = config.selection.get("signatures")
        if sig_names:
            from .signature_methods import (
                build_signature_methods,
                signatures_for_species,
            )

            sig_registry = signatures_for_species(run_species)
            genes = sorted({
                g for n in sig_names for g in sig_registry[n].all_genes
            })
            expr, apply_sig_log1p = _prepare_signature_expression(adata, genes)
            obs_sig = adata.obs
            if "CDR3ab" not in obs_sig.columns and {
                "CDR3_alpha", "CDR3_beta"
            } <= set(obs_sig.columns):
                obs_sig = obs_sig.assign(CDR3ab=paired_cdr3ab_key(obs_sig)[0])
            if not ({"CDR3ab", "sample"} <= set(obs_sig.columns)):
                raise ValueError(
                    f"selection.signatures={sig_names} requested but "
                    "adata.obs lacks CDR3ab/sample — cannot build "
                    "signature methods."
                )
            sig_long = build_signature_methods(
                expr, obs_sig, signatures=sig_names,
                log1p=apply_sig_log1p,
                positive_method=config.selection.get(
                    "signature_positive_method", "gap"
                ),
                species=run_species,
            )
            selection_long = pd.concat(
                [long_df, sig_long], ignore_index=True
            )
            print(
                f"  Added {len(sig_long)} signature-method rows "
                f"({', '.join(sig_names)}) to the selection input"
            )
        exclude_clones = None
        if config.selection.get("exclude_viral", True) and "is_viral" in til_matched.columns:
            viral_mask = truthy_flag_series(til_matched["is_viral"])
            exclude_clones = set(
                til_matched.loc[viral_mask, "CDR3ab"].astype(str)
            )
            if exclude_clones:
                audit_cols = [
                    c for c in (
                        "CDR3ab", "CDR3_alpha", "CDR3_beta", "is_viral",
                        "db_protein_canonical", "db_antigen_gene", "db_protein",
                        "db_species", "db_epitope", "db_database", "db_category",
                    )
                    if c in til_matched.columns
                ]
                til_matched.loc[viral_mask, audit_cols].to_csv(
                    data_dir / "excluded_viral_clones.csv", index=False
                )
                n_non_viral = int((~viral_mask).sum())
                print(
                    f"  Selection excluding {len(exclude_clones)} viral clones "
                    f"-> data/excluded_viral_clones.csv"
                )
        rules = select_from_clone_sample_long(
            selection_long, config.selection, exclude_clones=exclude_clones,
        )

    has_leaders = (
        config.assemble.alpha_leader is not None or config.assemble.beta_leader is not None
    )
    assemble_enabled = getattr(config.assemble, "enabled", True) and not no_assemble
    if assemble_enabled and (
        config.assemble.single_chain or has_leaders or config.assemble.include_constant
    ):
        print("\n[7/7] Assembling full-length sequences...")
        _sample_name_from = getattr(config.assemble, "sample_name_from", "parent")
        _contigs_dir = config.assemble.contigs_dir

        _explicit_contigs = config.assemble.contigs_dir or getattr(
            config.assemble, "cellranger_dir", None
        )
        _sheet_vdj_dirs = [s.vdj_dir for s in sheet_obj.samples if s.vdj_dir]
        if (
            _sample_name_from == "parent"
            and not _explicit_contigs
            and _sheet_vdj_dirs
            and not no_sheet_contigs
        ):
            _root = _common_contig_root(_sheet_vdj_dirs)
            if _root:
                _contigs_dir = _root
                _sample_name_from = "sheet"
                print(
                    f"  Allele fidelity: assembling against sample-sheet contigs "
                    f"under {_root} (#201; pass --no-sheet-contigs / --contigs-dir to change)"
                )

        _contig_sheet = (
            pd.DataFrame(
                [
                    {"sample": s.sample, "vdj_dir": s.vdj_dir}
                    for s in sheet_obj.samples
                    if s.vdj_dir
                ]
            )
            if _sample_name_from == "sheet"
            else None
        )
        _needs_leader_contigs = (
            config.assemble.alpha_leader == "from_contig"
            or config.assemble.beta_leader == "from_contig"
        )
        if _needs_leader_contigs and not (
            _contigs_dir or getattr(config.assemble, "cellranger_dir", None)
        ):
            raise TCRsiftValidationError(
                "Contigs directory required when extracting native leaders from contigs",
                hint="Provide --contigs-dir, --cellranger-dir, set assemble.contigs_dir "
                "in your config, or populate vdj_dir in your sample sheet.",
            )
        assembled = assemble_full_sequences(
            til_matched,
            contigs_dir=_contigs_dir,
            cellranger_dir=getattr(config.assemble, "cellranger_dir", None),
            sample_name_from=_sample_name_from,
            sample_sheet=_contig_sheet,
            alpha_leader=config.assemble.alpha_leader,
            beta_leader=config.assemble.beta_leader,
            include_constant=config.assemble.include_constant,
            constant_source=config.assemble.constant_source,
            linker=config.assemble.linker if config.assemble.single_chain else None,
            trac_allele=getattr(config.assemble, "trac_allele", "auto"),
            trbc1_allele=getattr(config.assemble, "trbc1_allele", "auto"),
            trbc2_allele=getattr(config.assemble, "trbc2_allele", "auto"),
            stop_codons=tuple(
                getattr(config.assemble, "stop_codons", ("TAA", "TGA"))
            ),
            leader_fallback=getattr(config.assemble, "leader_fallback", None) or "germline",
            force_alpha_leader=getattr(config.assemble, "force_alpha_leader", None),
            force_beta_leader=getattr(config.assemble, "force_beta_leader", None),
            secondary_alpha_leader=getattr(config.assemble, "secondary_alpha_leader", None),
            secondary_beta_leader=getattr(config.assemble, "secondary_beta_leader", None),
            codon_optimization=getattr(config.assemble, "codon_optimization", "focal"),
            max_codon_repeats=getattr(config.assemble, "max_codon_repeats", 1),
            avoid_enzymes=tuple(getattr(config.assemble, "avoid_enzymes", []) or []),
            species=run_species,
            constant_species=getattr(config.assemble, "constant_species", None),
            codon_species=getattr(config.assemble, "codon_species", None),
            germline_vdj_fallback=bool(
                getattr(config.assemble, "germline_vdj_fallback", False)
            ),
            data_dir=cache_dir,
            auto_download_germline=bool(
                getattr(config.assemble, "auto_download_germline", False)
                or getattr(config.annotate, "auto_download", False)
            ),
        )
        assembled.to_csv(data_dir / "full_sequences.csv", index=False)
        print(f"  Assembled {len(assembled)} sequences")

        _gv = collect_germline_variants(assembled)
        if not _gv.empty:
            _gv.to_csv(data_dir / "germline_variants.csv", index=False)
            print(f"  Germline variants: {len(_gv)} distinct (by region) → germline_variants.csv")

        _fidelity = enforce_contig_fidelity(
            assembled,
            allow_canonical_fallback=allow_canonical_fallback,
            context="run",
        )
        if _fidelity:
            print(f"  WARNING: {_fidelity}")

        if config.output.generate_plots:
            plot_assembly(assembled, plots_dir)

        if config.output.generate_report:
            pdf_annotations = None
            if long_df is not None and "method" in long_df.columns:
                from .selection import (
                    attach_method_tiers,
                    build_clone_method_long,
                    build_pdf_annotations,
                    select_from_clone_sample_long,
                )

                cml = attach_method_tiers(build_clone_method_long(long_df))
                sel_df = (
                    rules
                    if rules is not None
                    else (
                        select_from_clone_sample_long(long_df, config.selection)
                        if config.selection.get("rules") else None
                    )
                )
                pdf_annotations = build_pdf_annotations(cml, selection_df=sel_df)
            create_tcr_sequence_pdf(
                assembled,
                output_dir / "tcr_sequences.pdf",
                annotations=pdf_annotations,
                strict="skip",
                species=run_species,
            )

        if config.output.output_airr:
            airr_path = data_dir / "full_sequences.airr.tsv"
            export_clonotypes_airr(assembled, str(airr_path))
            print(f"  Exported AIRR table: {airr_path}")

        if config.output.output_fasta:
            fasta_path = data_dir / "full_sequences.fasta"
            seq_col = "single_chain_aa" if config.assemble.single_chain else "full_beta_aa"
            export_fasta(assembled, fasta_path, sequence_col=seq_col)
            print(f"  Exported FASTA: {fasta_path}")
    else:
        if not assemble_enabled:
            print(
                "\n[7/7] Skipping whole-repertoire assembly (--no-assemble). "
                "Analysis outputs written; assemble the selected basket with "
                "`tcrsift select` + `tcrsift report selected`."
            )
        else:
            print("\n[7/7] Skipping assembly")
        if config.output.output_airr or config.output.output_fasta:
            print("  Skipping AIRR/FASTA export because assembly was skipped")

    if rules is not None and not rules.empty:
        _selection_base = assembled if assembled is not None else til_matched
        if "CDR3ab" in _selection_base.columns:
            selected = (
                rules.merge(_selection_base, on="CDR3ab", how="left")
                .sort_values("global_rank")
                .reset_index(drop=True)
            )
            selected.to_csv(data_dir / "selected_clones.csv", index=False)
            n_selected_clones = len(selected)
            print(
                f"  Wrote selected_clones.csv: {len(selected)} clones "
                f"across {rules['selection_rule'].nunique()} rules"
            )

    if config.output.generate_plots:
        create_pipeline_funnel(
            raw_cells=funnel_counts.get("Raw Cells", 0),
            with_vdj=funnel_counts.get("With VDJ", funnel_counts.get("Raw Cells", 0)),
            phenotyped=funnel_counts.get("Phenotyped", 0),
            clonotypes=funnel_counts.get("Clonotypes", 0),
            filtered=funnel_counts.get("Filtered", 0),
            tier_counts=tier_counts,
            output_dir=plots_dir,
            selected_count=n_selected_clones,
            emit_selected_variant=n_selected_clones is not None,
            non_viral=n_non_viral,
        )

        if long_df is not None and "method" in getattr(long_df, "columns", []):
            from .plots import plot_vgene_usage_by_method

            plot_vgene_usage_by_method(
                long_df, clonotypes, plots_dir / "vgene_usage_by_method.png",
            )

        if assembled is not None and any(
            f"{c}_leader_aa" in getattr(assembled, "columns", []) for c in ("alpha", "beta")
        ):
            from .plots import plot_leader_summary

            plot_leader_summary(assembled, plots_dir / "leader_summary.png")

    if config.output.generate_report:
        if not list(plots_dir.glob("*.png")):
            print("\nSkipping figure report generation (no plot PNGs produced)")
        else:
            print("\nGenerating report...")
            from .report import resolve_report_name

            resolved_report_name = resolve_report_name(
                output_dir,
                clones_df=clonotypes,
                cli_name=report_name,
            )
            report_format = str(config.output.report_format).lower()
            if report_format == "both":
                generate_report(plots_dir, format="html", report_name=resolved_report_name)
                generate_report(plots_dir, format="pdf", report_name=resolved_report_name)
            elif report_format in {"html", "pdf"}:
                generate_report(plots_dir, format=report_format, report_name=resolved_report_name)
            else:
                raise TCRsiftValidationError(
                    f"Invalid report format: '{config.output.report_format}'",
                    hint="Use report_format: pdf, html, or both in config.",
                )

    print("\n" + "=" * 60)
    print("Pipeline complete!")
    print(f"Results saved to: {output_dir}")
    print("=" * 60)

    return PipelineResult(
        output_dir=output_dir,
        data_dir=data_dir,
        plots_dir=plots_dir,
        species=run_species,
        clonotypes=clonotypes,
        filtered=filtered,
        annotated=annotated,
        til_matched=til_matched,
        assembled=assembled,
        stimulation_response=stim_resp_df,
        funnel_counts=funnel_counts,
    )

prioritize

Explicit context presets and round-robin clone selection.

Presets are starting points, not tissue classifiers or specificity predictions. See docs/user-guide/til-signatures.md for their rationale and limitations.

PrioritizeConfig dataclass

Typed configuration for :func:tcrsift.til_prioritize.run_til_prioritize.

Source code in tcrsift/prioritize.py
@dataclass
class PrioritizeConfig:
    """Typed configuration for :func:`tcrsift.til_prioritize.run_til_prioritize`."""

    sample_sheet: Path
    output_dir: Path
    context: str = "generic"
    tcell_type: str = "cd8"
    species: str = "auto"
    signatures: list[str] | None = None
    exclude_signatures: list[str] | None = None
    max_clones: int = 200
    min_cells: int = 2
    min_frequency: float = 0.001
    signature_quantile: float = 0.9
    signature_cutoff: str = "background"
    signature_evidence: str | None = None
    signature_high_quantile: float = 0.9
    min_signature_high_cells: int = 5
    min_signature_high_fraction: float = 0.0
    signature_subset_pvalue: float = 0.01
    signature_background_quantile: float = 0.99
    signature_background_draws: int = 2000
    signature_background_seed: int = 0
    min_signature_score: float | None = None
    min_signature_support: int = 1
    vdjdb: Path | None = None
    iedb: Path | None = None
    iedb_epitope: Path | None = None
    cedar: Path | None = None
    cache_dir: Path | None = None
    auto_download: bool = False
    database_match: str = "strict_ab"
    round_robin_mode: str = "tiered"
    exclude_known_viral: bool = False
    exclude_known_mart1: bool = True
    exclude_trav12_2: bool = False
    exclude_public_quantile: float | None = None
    exclude_treg: bool = False
    treg_foxp3_fraction: float = 0.5
    assemble: bool = False
    germline_vdj_fallback: bool = False
    single_chain_linker: str | None = "T2A"
    call_multimers: bool = False
    multimer_min_umi: float = 10.0
    multimer_min_nc_ratio: float = 5.0
    multimer_min_concordance: float = 0.5
    multimer_min_specific_cells: int = 2
    min_genes: int = 250
    max_genes: int = 15000
    min_counts: int = 500
    max_counts: int = 100000
    min_mito_pct: float = 0.0
    max_mito_pct: float = 8.0
    min_vdj_umis: int = 2
    min_vdj_reads: int = 0
    min_cd3: int = 3
    min_alpha_cdr3_length: int = 0
    min_beta_cdr3_length: int = 0
    min_expression: list[str] = field(default_factory=list)
    max_expression: list[str] = field(default_factory=list)
    include_v_gene: list[str] = field(default_factory=list)
    exclude_v_gene: list[str] = field(default_factory=list)
    include_j_gene: list[str] = field(default_factory=list)
    exclude_j_gene: list[str] = field(default_factory=list)
    verbose: bool = False

    def __post_init__(self) -> None:
        self.sample_sheet = Path(self.sample_sheet)
        self.output_dir = Path(self.output_dir)
        for attr in ("vdjdb", "iedb", "iedb_epitope", "cedar", "cache_dir"):
            val = getattr(self, attr)
            if isinstance(val, str) and not val.strip():
                setattr(self, attr, None)
            elif val is not None and not isinstance(val, Path):
                setattr(self, attr, Path(val))
        for list_attr in (
            "min_expression",
            "max_expression",
            "include_v_gene",
            "exclude_v_gene",
            "include_j_gene",
            "exclude_j_gene",
        ):
            if getattr(self, list_attr) is None:
                setattr(self, list_attr, [])

    @classmethod
    def from_namespace(cls, args: Any) -> PrioritizeConfig:
        """Build a :class:`PrioritizeConfig` from an ``argparse.Namespace`` or similar object."""
        if isinstance(args, cls):
            return args
        kwargs: dict[str, Any] = {}
        for f in fields(cls):
            if hasattr(args, f.name):
                kwargs[f.name] = getattr(args, f.name)
        return cls(**kwargs)

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

from_namespace classmethod

from_namespace(args: Any) -> PrioritizeConfig

Build a :class:PrioritizeConfig from an argparse.Namespace or similar object.

Source code in tcrsift/prioritize.py
@classmethod
def from_namespace(cls, args: Any) -> PrioritizeConfig:
    """Build a :class:`PrioritizeConfig` from an ``argparse.Namespace`` or similar object."""
    if isinstance(args, cls):
        return args
    kwargs: dict[str, Any] = {}
    for f in fields(cls):
        if hasattr(args, f.name):
            kwargs[f.name] = getattr(args, f.name)
    return cls(**kwargs)

resolve_signatures

resolve_signatures(context, tcell_type, signatures=None, exclude_signatures=None, *, species: str = 'human')

Resolve names once; reject incompatible explicit lineage selections.

Source code in tcrsift/prioritize.py
def resolve_signatures(
    context,
    tcell_type,
    signatures=None,
    exclude_signatures=None,
    *,
    species: str = "human",
):
    """Resolve names once; reject incompatible explicit lineage selections."""
    lookup = {name.lower(): name for name in REGISTRY}

    def canonical(names):
        result = []
        for name in names:
            if name.lower() not in lookup:
                raise ValueError(f"Unknown signature {name!r}; choose from {', '.join(REGISTRY)}")
            result.append(lookup[name.lower()])
        return list(dict.fromkeys(result))

    ctx_map = (
        CONTEXT_SIGNATURES_MOUSE
        if normalize_species(species) == "mouse"
        else CONTEXT_SIGNATURES
    )
    names = canonical(signatures if signatures is not None else ctx_map[context])
    excluded = set(canonical(exclude_signatures or []))
    names = [name for name in names if name not in excluded]
    incompatible = [n for n in names if tcell_type != "both"
                    and SIGNATURE_LINEAGE.get(n, tcell_type) != tcell_type]
    if signatures is not None and incompatible:
        raise ValueError(f"Signatures {incompatible} are incompatible with --tcell-type {tcell_type}")
    names = [name for name in names if name not in incompatible]
    if not names:
        raise ValueError("No signatures remain after context, lineage, and exclusion settings")
    return names

signature_pass_mask

signature_pass_mask(scores, signature, quantile=0.9, min_score=None, cutoff='background', evidence='mean', min_high_cells=5, min_high_fraction=0.0, max_subset_p=0.01)

Qualify mean or high-cell subset evidence within the same stratum.

Source code in tcrsift/prioritize.py
def signature_pass_mask(scores, signature, quantile=0.9, min_score=None, cutoff="background",
                        evidence="mean", min_high_cells=5, min_high_fraction=0.0, max_subset_p=0.01):
    """Qualify mean or high-cell subset evidence within the same stratum."""
    if cutoff not in ("background", "legacy"):
        raise ValueError(f"Unknown signature cutoff {cutoff!r}")
    if evidence not in ("mean", "subset", "either"):
        raise ValueError(f"Unknown signature evidence {evidence!r}")
    if cutoff == "legacy" and evidence != "mean":
        raise ValueError("Subset evidence requires --signature-cutoff background")
    if evidence == "either":
        return signature_pass_mask(scores, signature, quantile, min_score, cutoff) | signature_pass_mask(
            scores, signature, quantile, min_score, cutoff, "subset",
            min_high_cells, min_high_fraction, max_subset_p,
        )
    col = f"signature_{signature}"
    values = scores[col].where(np.isfinite(scores[col]))
    if evidence == "subset":
        tail = scores[f"{col}_subset_tail_probability"]
        passing = (tail.between(0, max_subset_p) & scores[f"{col}_high_cells"].ge(min_high_cells)
                   & scores[f"{col}_high_fraction"].ge(min_high_fraction)
                   & scores[f"{col}_subset_percentile"].ge(quantile) & values.notna())
        if min_score is not None:
            passing &= values.gt(min_score)
        return passing.fillna(False)
    if cutoff == "background":
        floor = scores[f"{col}_noise_floor"]
        above_floor = values.gt(floor) & ~np.isclose(values, floor, rtol=1e-9, atol=1e-12)
    else:  # legacy; other values were rejected above
        above_floor = values.gt(0 if min_score is None else min_score)
    if min_score is not None:
        above_floor &= values.gt(min_score)
    groups = [scores[key] for key in ("donor", "sample", "lineage")]
    grouped = values.groupby(groups, observed=True)
    low, high = grouped.transform("min"), grouped.transform("max")
    varying = ~np.isclose(low, high, rtol=1e-9, atol=1e-12)
    return (above_floor & scores[f"{col}_percentile"].ge(quantile) & varying).fillna(False)

select_round_robin

select_round_robin(clones, scores, signatures, max_clones=200, quantile=0.9, min_score=None, cutoff='background', evidence='mean', min_high_cells=5, min_high_fraction=0.0, max_subset_p=0.01, *, priority_signatures=None)

Take one unseen clone per (signature, sample, lineage) list each round.

One budget covers the entire run. Clone identity includes the donor; shared sequences in different patients remain separate candidate rows. Only the qualifying head of each list participates. Exhausted lists contribute no more turns; other lists continue without quota limits. When priority_signatures is non-empty, those dedicated context signatures exhaust their qualifying lists first (Tier 1) before the remaining signatures backfill any leftover budget (Tier 2). When the budget ends inside a round, each remaining turn goes to the signature, then the sample, with the fewest turns in that round.

Source code in tcrsift/prioritize.py
def select_round_robin(clones, scores, signatures, max_clones=200, quantile=0.9,
                       min_score=None, cutoff="background", evidence="mean",
                       min_high_cells=5, min_high_fraction=0.0, max_subset_p=0.01,
                       *, priority_signatures=None):
    """Take one unseen clone per (signature, sample, lineage) list each round.

    One budget covers the entire run. Clone identity includes the donor;
    shared sequences in different patients remain separate candidate rows.
    Only the qualifying head of each list participates. Exhausted lists
    contribute no more turns; other lists continue without quota limits.
    When ``priority_signatures`` is non-empty, those dedicated context
    signatures exhaust their qualifying lists first (Tier 1) before the
    remaining signatures backfill any leftover budget (Tier 2).
    When the budget ends inside a round, each remaining turn goes to the
    signature, then the sample, with the fewest turns in that round.
    """
    scores = scores.reset_index(drop=True)
    result = clones.copy()
    result["selection_rank"] = pd.Series(pd.NA, index=result.index, dtype="Int64")
    for col in ("selected_signature", "selected_sample", "selected_lineage", "selected_evidence"):
        result[col] = ""
    for col in ("selected_cells", "selected_mean_score", "selected_high_cells", "selected_high_fraction"):
        result[col] = np.nan
    eligible = result[result.eligible_for_review]
    by_clone = dict(zip(zip(eligible.donor, eligible.CDR3ab), eligible.index))
    lists = []
    for signature in signatures:
        col = f"signature_{signature}"
        for route in (("mean", "subset") if evidence == "either" else (evidence,)):
            passing = scores[signature_pass_mask(
                scores, signature, quantile, min_score, cutoff, route,
                min_high_cells, min_high_fraction, max_subset_p,
            )]
            for (donor, sample, lineage), group in passing.groupby(
                ["donor", "sample", "lineage"], sort=True, observed=True,
            ):
                sort_cols = ([col, "frequency", "cells", "CDR3ab"] if route == "mean" else
                             [f"{col}_subset_tail_probability", f"{col}_high_fraction", "cells", "CDR3ab"])
                ranked = group.sort_values(sort_cols, ascending=[route == "subset", False, False, True])
                queue = deque((donor, row.CDR3ab, row_id) for row_id, row in ranked.iterrows()
                              if (donor, row.CDR3ab) in by_clone)
                if queue:
                    lists.append((signature, sample, lineage, route, queue))
    selected = set()
    limit = max_clones or float("inf")

    def unseen(entry):
        """Drop clones another list already supplied; True if any remain."""
        queue = entry[-1]
        while queue and queue[0][:2] in selected:
            queue.popleft()
        return bool(queue)

    def take(entry):
        signature, sample, lineage, route, queue = entry
        donor, cdr3, row_id = queue.popleft()
        clone = (donor, cdr3)
        selected.add(clone)
        idx = by_clone[clone]
        result.loc[idx, ["selection_rank", "selected_signature", "selected_sample", "selected_lineage", "selected_evidence"]] = [
            len(selected), signature, sample, lineage, route,
        ]
        row = scores.loc[row_id]
        result.loc[idx, ["selected_cells", "selected_mean_score", "selected_high_cells", "selected_high_fraction"]] = [
            row.cells, row[f"signature_{signature}"], row.get(f"signature_{signature}_high_cells", np.nan),
            row.get(f"signature_{signature}_high_fraction", np.nan),
        ]

    def _run_pool(pool_lists):
        while len(selected) < limit:
            before = len(selected)
            live = [entry for entry in pool_lists if unseen(entry)]
            if limit - len(selected) >= len(live):
                for entry in live:
                    if unseen(entry):
                        take(entry)
            else:
                turns, pending = Counter(), live
                while len(selected) < limit:
                    pending = [entry for entry in pending if unseen(entry)]
                    if not pending:
                        break
                    entry = min(pending, key=lambda item: (
                        turns[item[0]], turns[(item[-1][0][0], item[1], item[2])]))
                    pending = [item for item in pending if item is not entry]
                    turns[entry[0]] += 1
                    turns[(entry[-1][0][0], entry[1], entry[2])] += 1
                    take(entry)
            if len(selected) == before:
                break

    priority_set = set(priority_signatures or ())
    pools = (
        ([e for e in lists if e[0] in priority_set], [e for e in lists if e[0] not in priority_set])
        if priority_set
        else (lists,)
    )
    for pool in pools:
        if pool and len(selected) < limit:
            _run_pool(pool)

    result["selected_for_review"] = result.selection_rank.notna()
    for col in ("selected_cells", "selected_high_cells"):
        result[col] = result[col].astype("Int64")
    return result.sort_values(["selection_rank", "donor", "CDR3ab"], na_position="last")

til_prioritize

Prioritize clonotypes from paired 10x VDJ + GEX samples.

This workflow produces an auditable shortlist for experimental validation. It combines:

  • observed expansion (cells and within-sample frequency),
  • context-appropriate expression signatures with round-robin selection,
  • exact public-database annotation,
  • sequence-background publicness and alpha-chain promiscuity flags.

It writes every scored clone before writing the filtered shortlist, so no exclusion is hidden.

run_til_prioritize

run_til_prioritize(args: PrioritizeConfig | Namespace) -> tuple[pd.DataFrame, pd.DataFrame]

Score and prioritize clones from a standard CellRanger sample sheet.

Source code in tcrsift/til_prioritize.py
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
def run_til_prioritize(
    args: PrioritizeConfig | argparse.Namespace,
) -> tuple[pd.DataFrame, pd.DataFrame]:
    """Score and prioritize clones from a standard CellRanger sample sheet."""
    from .species import normalize_species, resolve_species

    func_name = getattr(getattr(args, "func", None), "__name__", "run_til_prioritize")
    args = PrioritizeConfig.from_namespace(args)
    arg_species = normalize_species(args.species, allow_auto=True)
    initial_species = "human" if arg_species == "auto" else arg_species
    names = resolve_signatures(
        args.context,
        args.tcell_type,
        args.signatures,
        args.exclude_signatures,
        species=initial_species,
    )
    evidence = args.signature_evidence or ("either" if args.signature_cutoff == "background" else "mean")
    if args.signature_cutoff == "legacy" and evidence != "mean":
        raise ValueError("--signature-evidence subset/either requires --signature-cutoff background")
    if not 0 < args.signature_high_quantile < 1:
        raise ValueError("--signature-high-quantile must be between 0 and 1 (exclusive)")
    if args.min_signature_high_cells < 1:
        raise ValueError("--min-signature-high-cells must be >= 1")
    if not 0 <= args.min_signature_high_fraction <= 1:
        raise ValueError("--min-signature-high-fraction must be in [0, 1]")
    if not 0 < args.signature_subset_pvalue < 1:
        raise ValueError("--signature-subset-pvalue must be between 0 and 1 (exclusive)")
    if not 0 <= args.signature_quantile <= 1:
        raise ValueError("--signature-quantile must be in [0, 1]")
    if args.min_signature_score is not None and not np.isfinite(args.min_signature_score):
        raise ValueError("--min-signature-score must be finite")
    from .signature_background import calibrate_signature_background, validate_background_parameters

    validate_background_parameters(args.signature_background_quantile,
                                   args.signature_background_draws, args.signature_background_seed)
    if args.round_robin_mode not in ("tiered", "flat"):
        raise ValueError(
            f"--round-robin-mode must be 'tiered' or 'flat'; got {args.round_robin_mode!r}"
        )
    if args.database_match not in ("strict_ab", "ab_with_partial", "b_only"):
        raise ValueError(
            f"--database-match must be 'strict_ab', 'ab_with_partial', or 'b_only'; got {args.database_match!r}"
        )
    if args.call_multimers:
        if args.multimer_min_umi < 0 or not np.isfinite(args.multimer_min_umi):
            raise ValueError("--multimer-min-umi must be finite and >= 0")
        if args.multimer_min_nc_ratio <= 0 or not np.isfinite(args.multimer_min_nc_ratio):
            raise ValueError("--multimer-min-nc-ratio must be finite and > 0")
        if not (0 <= args.multimer_min_concordance <= 1):
            raise ValueError("--multimer-min-concordance must be in [0, 1]")
        if args.multimer_min_specific_cells < 1:
            raise ValueError("--multimer-min-specific-cells must be >= 1")
    if args.exclude_public_quantile is not None and not (0 < args.exclude_public_quantile <= 1):
        raise ValueError("--exclude-public-quantile must be in (0, 1]")
    if not np.isfinite(args.treg_foxp3_fraction) or not (0 < args.treg_foxp3_fraction <= 1):
        raise ValueError("--treg-foxp3-fraction must be in (0, 1]")
    valid_linkers = {"T2A", "P2A", "E2A", "F2A", "NONE"}
    if args.single_chain_linker is not None and str(args.single_chain_linker).strip().upper() not in valid_linkers:
        raise ValueError(
            f"--single-chain-linker must be one of T2A, P2A, E2A, F2A, or none; got {args.single_chain_linker!r}"
        )
    if not 0 <= args.min_frequency <= 1:
        raise ValueError("--min-frequency must be in [0, 1]")
    if args.min_cells < 1:
        raise ValueError("--min-cells must be >= 1")
    max_possible_names = len(names)
    if arg_species == "auto":
        try:
            mouse_names = resolve_signatures(
                args.context,
                args.tcell_type,
                args.signatures,
                args.exclude_signatures,
                species="mouse",
            )
            max_possible_names = max(max_possible_names, len(mouse_names))
        except ValueError:
            pass
    if not 1 <= args.min_signature_support <= max_possible_names:
        raise ValueError(f"--min-signature-support must be between 1 and {max_possible_names}")
    for key in ("max_clones", "min_vdj_umis", "min_vdj_reads", "min_cd3",
                "min_alpha_cdr3_length", "min_beta_cdr3_length", *QC_DEFAULTS):
        if not np.isfinite(getattr(args, key)) or getattr(args, key) < 0:
            raise ValueError(f"--{key.replace('_', '-')} must be finite and >= 0")
    for low, high in (("min_genes", "max_genes"), ("min_counts", "max_counts"),
                      ("min_mito_pct", "max_mito_pct")):
        if getattr(args, low) > getattr(args, high):
            raise ValueError(f"--{low.replace('_', '-')} must not exceed --{high.replace('_', '-')}")
    if args.max_mito_pct > 100:
        raise ValueError("--max-mito-pct must not exceed 100")
    for option in ("min_expression", "max_expression"):
        try:
            parse_expression_limits(getattr(args, option))
        except ValueError as exc:
            raise ValueError(f"--{option.replace('_', '-')}: {exc}") from exc

    import scanpy as sc

    from .annotate import annotate_clonotypes
    from .annotate_tcrs import add_paired_ppost, add_pairing_promiscuity, add_pgen_ppost
    from .clonotype import aggregate_clonotypes, build_clone_sample_long
    from .datacache import ensure_cached
    from .loader import load_samples
    from .phenotype import phenotype_cells
    from .sample_sheet import load_sample_sheet

    args.output_dir.mkdir(parents=True, exist_ok=True)

    sheet = load_sample_sheet(args.sample_sheet)
    sample_names = [s.sample for s in sheet]
    if len(set(sample_names)) != len(sample_names):
        raise ValueError("Each sample must have a unique name")
    if any(not (s.gex_dir or s.gex_path) or not s.vdj_dir for s in sheet):
        raise ValueError("Every sample requires paired GEX (gex_dir or gex_path) and vdj_dir inputs")
    if any(s.patient_id is not None for s in sheet) and any(
        s.patient_id is None or not str(s.patient_id).strip() for s in sheet
    ):
        raise ValueError("patient_id must be populated for every sample when the column is used")
    adata = load_samples(sheet, **{key: getattr(args, key) for key in QC_DEFAULTS})
    sheet_species = getattr(sheet, "species", None)
    requested_species = arg_species if arg_species != "auto" else (sheet_species or "auto")
    resolved_species = resolve_species(
        requested_species,
        adata=adata if adata.n_vars > 0 else None,
        df=adata.obs,
        warn_mismatch=bool(requested_species != "auto"),
        context="til-prioritize",
    )
    adata.uns["species"] = resolved_species
    if resolved_species != initial_species:
        names = resolve_signatures(
            args.context,
            args.tcell_type,
            args.signatures,
            args.exclude_signatures,
            species=resolved_species,
        )
    if not 1 <= args.min_signature_support <= len(names):
        raise ValueError(f"--min-signature-support must be between 1 and {len(names)}")
    logger.info(
        "Species: %s; Context: %s; T cells: %s; signatures: %s",
        resolved_species, args.context, args.tcell_type, ", ".join(names),
    )
    if "sample" not in adata.obs or adata.obs["sample"].isna().any() or adata.obs["sample"].nunique() < 1:
        raise ValueError("prioritize requires at least one named sample")
    _analysis_units(adata)  # Validate before a cell filter can hide missing donors.
    _ensure_clone_key(adata)
    adata = phenotype_cells(adata, min_cd3_reads=args.min_cd3)
    adata, cell_filters, sample_counts = filter_cells(adata, args)

    clonotypes, clone_sample = _aggregate_within_patients(
        adata,
        aggregate_clonotypes,
        build_clone_sample_long,
        min_umi=args.min_vdj_umis,
    )

    # score_genes expects log-normalized expression. Using a copy preserves the
    # raw-count matrix used by the rest of the workflow.
    scored_adata = adata.copy()
    sc.pp.normalize_total(scored_adata, target_sum=10_000)
    sc.pp.log1p(scored_adata)

    signature_cols = []
    for name in names:
        col = f"signature_{name}"
        scored_adata.obs[col] = _score_within_samples(scored_adata, name)
        signature_cols.append(col)

    scored_adata.obs["donor"] = _analysis_units(scored_adata)
    per_cell_scores = scored_adata.obs[["donor", "CDR3ab", "sample", "lineage", *signature_cols]].dropna(
        subset=["CDR3ab"]
    )
    per_sample_scores = (
        per_cell_scores.groupby(["CDR3ab", "sample", "lineage"], observed=True)[signature_cols]
        .mean()
        .reset_index()
    )
    clone_sample = clone_sample.merge(
        per_sample_scores,
        on=["CDR3ab", "sample", "lineage"],
        how="left",
        validate="one_to_one",
    )
    signature_percentile_cols = []
    for col in signature_cols:
        percentile_col = f"{col}_percentile"
        clone_sample[percentile_col] = clone_sample.groupby(
            ["sample", "lineage"],
            observed=True,
        )[col].rank(method="average", pct=True)
        signature_percentile_cols.append(percentile_col)
    if args.signature_cutoff == "background":
        clone_sample, calibration = calibrate_signature_background(
            clone_sample, per_cell_scores, names, quantile=args.signature_background_quantile,
            draws=args.signature_background_draws, seed=args.signature_background_seed,
            high_quantile=args.signature_high_quantile,
        )
        calibration.to_csv(args.output_dir / "signature_background.csv", index=False)
    else:
        # A rerun in the same output directory must not leave a previous run's
        # calibration table looking like evidence for this legacy selection.
        (args.output_dir / "signature_background.csv").unlink(missing_ok=True)
    pass_cols, evidence_cols = [], []
    for name in names:
        for route in ("mean", "subset"):
            route_col = f"signature_{name}_{route}_passes_cutoff"
            clone_sample[route_col] = False
            if route == "mean" or args.signature_cutoff == "background":
                clone_sample[route_col] = signature_pass_mask(
                    clone_sample, name, args.signature_quantile, args.min_signature_score, args.signature_cutoff,
                    route, args.min_signature_high_cells, args.min_signature_high_fraction, args.signature_subset_pvalue,
                )
            evidence_cols.append(route_col)
        col = f"signature_{name}_passes_cutoff"
        routes = ("mean", "subset") if evidence == "either" else (evidence,)
        clone_sample[col] = clone_sample[[f"signature_{name}_{route}_passes_cutoff" for route in routes]].any(axis=1)
        pass_cols.append(col)
    clone_sample.to_csv(args.output_dir / "clone_sample_scores.csv", index=False)

    # A strong signal in any sample is retained in the clone-level review table;
    # the long table above shows which sample supplied it.
    signature_max = (
        clone_sample.groupby(["donor", "CDR3ab"], observed=True)[
            [*signature_cols, *signature_percentile_cols, *pass_cols, *evidence_cols]
        ]
        .max()
        .add_suffix("_max")
        .reset_index()
    )
    clonotypes = clonotypes.merge(
        signature_max,
        on=["donor", "CDR3ab"],
        how="left",
        validate="one_to_one",
    )

    clonotypes = add_pgen_ppost(clonotypes, backend="kmer", species=resolved_species)
    clonotypes = add_paired_ppost(clonotypes)
    clonotypes = add_pairing_promiscuity(clonotypes)
    cache_dir = getattr(args, "cache_dir", None)
    auto_dl = bool(getattr(args, "auto_download", False))
    vdjdb_path = args.vdjdb or ensure_cached("vdjdb", cache_dir, auto_download=auto_dl)
    iedb_path = args.iedb or ensure_cached("iedb", cache_dir, auto_download=auto_dl)
    cedar_path = args.cedar or ensure_cached("cedar", cache_dir, auto_download=auto_dl)
    iedb_epitope_path = getattr(args, "iedb_epitope", None) or ensure_cached(
        "iedb_epitope", cache_dir, auto_download=auto_dl
    )
    clonotypes = annotate_clonotypes(
        clonotypes,
        vdjdb_path=vdjdb_path,
        iedb_path=iedb_path,
        cedar_path=cedar_path,
        iedb_epitope_path=iedb_epitope_path,
        match_strictness=args.database_match,
        flag_only=True,
        species=resolved_species,
        host_species_filter="same",
    )
    clonotypes["known_viral_match"] = truthy_flag_series(clonotypes["is_viral"])
    clonotypes["known_mart1_match"] = _known_mart1_mask(clonotypes)

    if args.call_multimers:
        from .multimer import call_multimers_for_adata

        adata_for_multimer = adata.copy()
        adata_for_multimer.obs["donor"] = _analysis_units(adata_for_multimer)
        mm_summary = call_multimers_for_adata(
            adata_for_multimer,
            sheet,
            clone_col="CDR3ab",
            group_col="donor",
            min_umi=args.multimer_min_umi,
            min_nc_ratio=args.multimer_min_nc_ratio,
            min_specific_cells=args.multimer_min_specific_cells,
            min_concordance=args.multimer_min_concordance,
        )
        if not mm_summary.empty:
            mm_summary.to_csv(args.output_dir / "multimer_specificity.csv", index=False)
            clonotypes = clonotypes.merge(
                mm_summary.drop(columns=["clone_cells"], errors="ignore"),
                on=["donor", "CDR3ab"],
                how="left",
                validate="one_to_one",
            )
            clonotypes["multimer_confident"] = truthy_flag_series(
                clonotypes.get("multimer_confident", pd.Series(False, index=clonotypes.index))
            )
    clonotypes["uses_trav12_2"] = (
        _trav12_2_mask(clonotypes)
        if resolved_species == "human"
        else pd.Series(False, index=clonotypes.index)
    )

    # Audit per-clone FOXP3+ regulatory T-cell fraction on raw counts (human FOXP3 / mouse Foxp3).
    from .signature_methods import expression_frame_from_adata

    foxp3_expr = (
        expression_frame_from_adata(adata, ["FOXP3"], on_missing="ignore")
        if adata.n_obs > 0 and adata.n_vars > 0
        else pd.DataFrame()
    )
    foxp3_detected_in_matrix = "FOXP3" in foxp3_expr.columns
    if foxp3_detected_in_matrix:
        foxp3_raw = foxp3_expr["FOXP3"].to_numpy(dtype=float)
        foxp3_obs = pd.DataFrame(
            {
                "donor": _analysis_units(adata).to_numpy(),
                "CDR3ab": adata.obs["CDR3ab"].to_numpy(),
                "_foxp3_pos": (foxp3_raw > 0).astype(float),
            }
        ).dropna(subset=["CDR3ab"])
        foxp3_by_clone = (
            foxp3_obs.groupby(["donor", "CDR3ab"], observed=True)["_foxp3_pos"]
            .mean()
            .rename("foxp3_pos_fraction")
            .reset_index()
        )
        clonotypes = clonotypes.merge(
            foxp3_by_clone, on=["donor", "CDR3ab"], how="left", validate="one_to_one"
        )
        clonotypes["foxp3_pos_fraction"] = clonotypes["foxp3_pos_fraction"].fillna(0.0)
    else:
        if args.exclude_treg:
            logger.warning(
                "--exclude-treg requested, but FOXP3/Foxp3 is absent from the expression matrix; "
                "no clones excluded for Treg state."
            )
        clonotypes["foxp3_pos_fraction"] = 0.0
    clonotypes["is_treg_like"] = clonotypes["foxp3_pos_fraction"].ge(args.treg_foxp3_fraction)

    # ppost_either is ln(P) for the more common of the two chains. Higher
    # (less negative) values are more public; the percentile is cohort-relative.
    clonotypes["publicness_percentile"] = clonotypes.groupby("donor", observed=True)[
        "ppost_either"
    ].rank(method="average", pct=True)
    clonotypes["high_publicness"] = False
    if args.exclude_public_quantile is not None:
        donor_clone_counts = clonotypes.groupby("donor", observed=True)["CDR3ab"].transform("count")
        clonotypes["high_publicness"] = (
            (donor_clone_counts >= 2)
            & (clonotypes["publicness_percentile"] >= args.exclude_public_quantile)
        ).fillna(False)

    clonotypes["signature_support_count"] = (
        clonotypes[[f"{col}_max" for col in pass_cols]].sum(axis=1)
    )
    clonotypes["meets_abundance"] = clonotypes["cell_count"].ge(args.min_cells) & clonotypes[
        "max_frequency"
    ].ge(args.min_frequency)
    for chain in ("alpha", "beta"):
        clonotypes[f"{chain}_cdr3_length"] = clonotypes[f"CDR3_{chain}"].str.len()
        clonotypes[f"short_{chain}_cdr3"] = clonotypes[f"{chain}_cdr3_length"].lt(
            getattr(args, f"min_{chain}_cdr3_length")
        )
    clonotypes["gene_filter_failed"] = ~(
        gene_filter_mask(clonotypes, args.include_v_gene, args.exclude_v_gene, "v")
        & gene_filter_mask(clonotypes, args.include_j_gene, args.exclude_j_gene, "j")
    )

    risk_flags = [
        ("known_viral_match", "known_viral"),
        ("known_mart1_match", "known_MART1"),
        ("uses_trav12_2", "TRAV12-2"),
        ("high_publicness", "high_publicness"),
        ("alpha_promiscuous", "promiscuous_alpha"),
        ("is_treg_like", "treg_FOXP3"),
    ]
    clonotypes["risk_flags"] = _join_flags(clonotypes, risk_flags)

    excluded = pd.Series(False, index=clonotypes.index)
    exclusion_flags = [("short_alpha_cdr3", "short_alpha_cdr3"),
                       ("short_beta_cdr3", "short_beta_cdr3"),
                       ("gene_filter_failed", "gene_filter")]
    for col, _ in exclusion_flags:
        excluded |= clonotypes[col]
    if args.exclude_known_viral:
        excluded |= clonotypes["known_viral_match"]
        exclusion_flags.append(("known_viral_match", "known_viral"))
    if args.exclude_known_mart1:
        excluded |= clonotypes["known_mart1_match"]
        exclusion_flags.append(("known_mart1_match", "known_MART1"))
    if args.exclude_trav12_2:
        excluded |= clonotypes["uses_trav12_2"]
        exclusion_flags.append(("uses_trav12_2", "TRAV12-2"))
    if args.exclude_public_quantile is not None:
        excluded |= clonotypes["high_publicness"]
        exclusion_flags.append(("high_publicness", "high_publicness"))
    if args.exclude_treg:
        excluded |= clonotypes["is_treg_like"]
        exclusion_flags.append(("is_treg_like", "treg_FOXP3"))
    clonotypes["excluded_reason"] = _join_flags(clonotypes, exclusion_flags)

    clonotypes["eligible_for_review"] = (
        clonotypes["meets_abundance"]
        & clonotypes["signature_support_count"].ge(args.min_signature_support)
        & ~excluded
    )
    priority_sigs = (
        [s for s in PRIORITY_CONTEXT_SIGNATURES.get(args.context, ()) if s in names]
        if (args.round_robin_mode == "tiered" and args.signatures is None)
        else []
    )
    clonotypes = select_round_robin(
        clonotypes, clone_sample, names, args.max_clones, args.signature_quantile,
        args.min_signature_score, args.signature_cutoff,
        evidence, args.min_signature_high_cells, args.min_signature_high_fraction, args.signature_subset_pvalue,
        priority_signatures=priority_sigs or None,
    )
    candidates = clonotypes[clonotypes["selected_for_review"]].copy()

    clonotypes.to_csv(args.output_dir / "all_scored_clones.csv", index=False)
    candidates.to_csv(args.output_dir / "candidate_clones.csv", index=False)

    assembly_meta: dict[str, object] = {"enabled": bool(args.assemble)}
    constructs_csv = args.output_dir / "candidate_constructs.csv"
    constructs_fasta = args.output_dir / "candidate_constructs.fasta"
    if not args.assemble:
        constructs_csv.unlink(missing_ok=True)
        constructs_fasta.unlink(missing_ok=True)
    else:
        from ._assemble_qc import (
            assemble_fidelity_summary,
            enforce_contig_fidelity,
            export_fasta,
        )
        from .assemble import assemble_full_sequences, validate_sequences
        from .pipeline import _common_contig_root

        def _has_contig_source(path_str: str) -> bool:
            p = Path(path_str)
            if not p.exists():
                return False
            if p.is_file():
                low = p.name.lower()
                if low.endswith((".fasta", ".fasta.gz", ".json", ".json.gz")):
                    return True
                p = p.parent
            return any(
                any(p.rglob(pat))
                for pat in (
                    "*contig*.fasta",
                    "*contig*.fasta.gz",
                    "*contig_annotations*.json",
                    "*contig_annotations*.json.gz",
                )
            )

        raw_linker = (
            str(args.single_chain_linker).strip().upper()
            if args.single_chain_linker is not None
            else None
        )
        linker_arg = None if raw_linker in (None, "", "NONE") else raw_linker

        if len(candidates) > 0:
            existing_vdj_dirs = [
                str(s.vdj_dir)
                for s in sheet
                if s.vdj_dir and Path(s.vdj_dir).exists()
            ]
            has_contigs = any(_has_contig_source(d) for d in existing_vdj_dirs)
            contig_root = _common_contig_root(existing_vdj_dirs) if has_contigs else None
            contig_sheet = (
                pd.DataFrame(
                    [
                        {"sample": s.sample, "vdj_dir": s.vdj_dir}
                        for s in sheet
                        if s.vdj_dir and Path(s.vdj_dir).exists()
                    ]
                )
                if contig_root
                else None
            )
            leader_kwargs = (
                {"alpha_leader": "from_contig", "beta_leader": "from_contig"}
                if contig_root
                else {}
            )
            constructs = assemble_full_sequences(
                candidates,
                contigs_dir=contig_root,
                sample_name_from="sheet" if contig_root else "parent",
                sample_sheet=contig_sheet,
                **leader_kwargs,
                include_constant=True,
                linker=linker_arg,
                species=resolved_species,
                germline_vdj_fallback=bool(args.germline_vdj_fallback),
                data_dir=cache_dir,
                auto_download_germline=auto_dl,
                verbose=args.verbose,
                show_progress=False,
            )
            fidelity = assemble_fidelity_summary(constructs)
            fidelity_note = enforce_contig_fidelity(
                constructs,
                allow_canonical_fallback=True,
                context="prioritize",
            )
            if fidelity_note:
                logger.warning("%s", fidelity_note)
            val_errors = [
                m for m in validate_sequences(constructs, species=resolved_species)
                if m.severity == "load_bearing"
            ]
            constructs.to_csv(constructs_csv, index=False)
            if linker_arg:
                export_fasta(constructs, constructs_fasta, sequence_col="single_chain_aa")
                n_complete = (
                    int(constructs["single_chain_aa"].notna().sum())
                    if "single_chain_aa" in constructs.columns
                    else 0
                )
            else:
                with open(constructs_fasta, "w") as fh:
                    for idx_r, row_r in constructs.iterrows():
                        cab = row_r.get("CDR3ab", idx_r)
                        ca = row_r.get("CDR3_alpha", "")
                        cb = row_r.get("CDR3_beta", "")
                        fb = row_r.get("full_beta_aa", "")
                        fa = row_r.get("full_alpha_aa", "")
                        if isinstance(fb, str) and fb.strip():
                            fh.write(f">{cab}|beta CDR3b={cb}\n{fb}\n")
                        if isinstance(fa, str) and fa.strip():
                            fh.write(f">{cab}|alpha CDR3a={ca}\n{fa}\n")
                has_a = (
                    constructs["full_alpha_aa"].notna()
                    if "full_alpha_aa" in constructs.columns
                    else pd.Series(False, index=constructs.index)
                )
                has_b = (
                    constructs["full_beta_aa"].notna()
                    if "full_beta_aa" in constructs.columns
                    else pd.Series(False, index=constructs.index)
                )
                n_complete = int((has_a & has_b).sum())
            n_verified = int(fidelity["n_verified"])
            n_err = len(val_errors)
        else:
            empty_constructs = candidates.copy()
            for col in (
                "full_alpha_aa",
                "full_beta_aa",
                "single_chain_aa",
                "single_chain_nt",
                "construct_contig_verified",
                "qc_warnings",
            ):
                if col not in empty_constructs.columns:
                    empty_constructs[col] = pd.Series(dtype=object)
            empty_constructs.to_csv(constructs_csv, index=False)
            constructs_fasta.write_text("")
            n_complete = 0
            n_verified = 0
            n_err = 0

        assembly_meta = {
            "enabled": True,
            "candidate_count": len(candidates),
            "complete_constructs": n_complete,
            "contig_verified_constructs": n_verified,
            "load_bearing_validation_errors": n_err,
            "germline_vdj_fallback": bool(args.germline_vdj_fallback),
            "single_chain_linker": linker_arg,
            "constructs_csv": str(constructs_csv.name),
            "constructs_fasta": str(constructs_fasta.name),
        }

    from .version import __version__

    config = {
        "version": __version__, "arguments": args.to_dict() | {"func": func_name},
        "species": resolved_species,
        "resolved_signatures": names,
        "priority_signatures": priority_sigs,
        "round_robin_mode": args.round_robin_mode,
        "database_match": args.database_match,
        "signature_lineages": SIGNATURE_LINEAGE,
        "cell_filters": cell_filters, "sample_cell_counts": sample_counts,
        "selection": "one total budget; round-robin over signature/evidence/patient/sample/lineage lists",
        "signature_cutoff": {
            "method": args.signature_cutoff,
            "evidence": evidence,
            "rule": "pass all thresholds for any enabled evidence route within the same sample/lineage",
            "mean_rule": ("score > background floor AND optional minimum score" if args.signature_cutoff == "background"
                          else "score > explicit minimum score, defaulting to 0")
                         + "; mean percentile gate; flat lists excluded",
            "subset_rule": "high-cell count and fraction floors; exact hypergeometric tail <= pvalue; subset percentile gate; optional mean score floor",
            "high_cells": "score strictly above within-patient/sample/lineage cell quantile; ties excluded",
            "background": "uniform cell subsets without replacement within patient/sample/lineage, matched to clone cell count",
            "interpretation": "competitive expression enrichment; not technical-noise estimation, antigen specificity, or FDR control",
        },
        "database_annotation_available": bool(vdjdb_path or iedb_path or cedar_path),
        "foxp3_detected_in_matrix": bool(foxp3_detected_in_matrix),
        "candidate_count": len(candidates),
        "assembly": assembly_meta,
    }
    (args.output_dir / "prioritization.json").write_text(json.dumps(config, indent=2, default=str) + "\n")
    if args.exclude_known_mart1 and not config["database_annotation_available"]:
        logger.warning("MART-1 exclusion is enabled, but no reference database was supplied; "
                       "unannotated clones cannot be identified as MART-1 matches")
    return clonotypes, candidates