Skip to content

Assembly API

tcrsift.assemble constructs full-length α, β, and synthesis-ready single-chain (β-2A-α) protein and DNA sequences from clonotype tables.

Overview

By default, input tables carry full-length V(D)J variable-region sequences (VDJ_alpha_aa, VDJ_beta_aa) from aggregate_clonotypes. When working with 5'-truncated contigs (partial_VDJ_{chain}_aa/_nt, where sequencing begins downstream of the leader start codon) or bare (v_gene, CDR3, j_gene) tables, pass germline_vdj_fallback=True (--germline-vdj-fallback on the CLI, after tcrsift data download --group germline or --auto-download-germline):

  • 5'-partial contig rescue (contig_5prime_germline_rescued): prepends only the missing N-terminal FR1/CDR1 segment from the best-matching IMGT V-REGION allele while preserving all sequenced donor framework SNPs, CDR3 codons, and FR4 codons verbatim.
  • Bare V+CDR3+J reconstruction (germline_vj_reconstructed): splices IMGT germline V-REGION (FR1–FR3 up to conserved Cys 104) + CDR3 + IMGT germline J-REGION (FR4 past [FW]GXG).
  • Every germline-imputed chain records {chain}_vdj_source, {chain}_vdj_germline_allele, and qc_warnings ({chain}_vdj_germline_reconstructed) and sets construct_contig_verified = False so germline imputation is never conflated with a 5'-to-3' contig-verified sequence.

Assembly configures four components:

  • Signal peptides (leaders): standard human or murine leader peptides per chain, native V-gene leaders extracted from Cell Ranger FASTA contigs, or no leader.
  • Constant regions: packaged canonical human (TRAC, TRBC1, TRBC2) and mouse (Trac, Trbc1, Trbc2) references (including chimeric human-VDJ + mouse-constant pairing via constant_species="mouse"), or explicit {chain}_constant_aa/_nt columns from input data.
  • Self-cleaving 2A linkers: T2A, P2A, E2A, or F2A.
  • Single-chain orientation: β-linker-α constructs with validation for start/stop codons, reading frame, J→C junction seam, and repeated k-mers.

Signal-peptide options

Each chain takes its own leader setting (defaults: CD28 on α and CD8A on β so chains remain distinguishable):

Value Behavior
"CD8A", "CD28", "mCD8B", "mCD28", "H2Kb", "IgK", "TRAC", "TRBC" Predefined signal peptide (table below)
"from_contig" Native V-gene leader extracted from Cell Ranger contig FASTAs (germline-anchored against IMGT L-PART1+L-PART2)
None Omit signal peptide
Name Origin Species Amino-acid sequence
CD8A CD8A signal peptide (UniProt P01732) Human MALPVTALLLPLALLLHAARP
CD28 CD28 signal peptide (UniProt P10747) Human MLRLLLALNLFPSIQVTG
mCD8B Cd8b1 signal peptide (UniProt P10300) Mouse MQPWLWLVFSMKLAALWSSSA
mCD28 Cd28 signal peptide (UniProt P31041) Mouse MTLRLLFLALNFFSVQVT
H2Kb H2-K1 (H-2Kb) signal peptide (UniProt P01901) Mouse MVPCTLLLLLAAALAPTQTRA
IgK IgGκ light-chain signal peptide Mouse METDTLLLWVLLLWVPGSTG
TRAC Synthetic TCR α-chain signal peptide Human MAGTWLLLLLALGCPALPTG
TRBC Synthetic TCR β-chain signal peptide Human MGTSLLCWMALCLLGADHADG

2A linkers

Name Virus Amino-acid sequence
T2A Thosea asigna virus EGRGSLLTCGDVEENPGP
P2A Porcine teschovirus-1 GSGATNFSLLKQAGDVEENPGP
E2A Equine rhinitis A virus QCTNYALLKLAGDVESNPGP
F2A Foot-and-mouth disease virus VKQTLNFDLLKLAGDVESNPGP

Usage examples

from tcrsift import assemble_full_sequences

# Default: CD28 leader on alpha, CD8A leader on beta
assembled = assemble_full_sequences(clonotypes)

# Native V-gene leaders from Cell Ranger contig FASTAs
assembled = assemble_full_sequences(
    clonotypes,
    contigs_dir="/path/to/contigs",
    alpha_leader="from_contig",
    beta_leader="from_contig",
)

# Leader on beta chain only (upstream chain in a β-2A-α construct)
assembled = assemble_full_sequences(
    clonotypes,
    alpha_leader=None,
    beta_leader="CD8A",
)

Constant-region construction

Canonical human (tcrsift/refseqs/canonical_constants.fasta) and mouse (tcrsift/refseqs/canonical_constants_mouse.fasta) TRAC, TRBC1, and TRBC2 sequences are bundled in the package. Pass species="mouse" for murine TCRs, or species="human", constant_species="mouse" for murinized chimeric TCR-T constructs (codon_species defaults to constant_species and can be set independently, e.g. codon_species="human" when expressing a murinized TCR in human T cells). The default constant_source="ensembl" is retained as a backward-compatible alias for "canonical" and performs no network or Ensembl lookup. Pass constant_source="from-data" to read explicit {chain}_constant_aa and {chain}_constant_nt columns instead.

When contigs_dir is provided, nucleotide assembly blends donor contig 3′ reads into the canonical constant region:

  1. Retain donor nucleotides across the J→C junction and subsequent complete codons while their translation matches the canonical constant-region protein.
  2. Complete a trailing 1- or 2-nt partial contig codon when a compatible codon exists for the canonical amino acid.
  3. Fill the remainder of the constant region with codon-optimized canonical nucleotides once contig coverage ends or diverges.

The translated constant-region protein stays canonical; {chain}_constant_source records how much donor sequence was kept, and qc_warnings flags any divergence. Without contigs_dir, codon-optimized canonical sequence is used across the entire constant region.

API reference

assemble

Full-length TCR sequence assembly for TCRsift.

Builds complete TCR sequences including leader peptides and constant regions.

CODON_TABLE module-attribute

CODON_TABLE = {'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M', 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACT': 'T', 'AAC': 'N', 'AAT': 'N', 'AAA': 'K', 'AAG': 'K', 'AGC': 'S', 'AGT': 'S', 'AGA': 'R', 'AGG': 'R', 'CTA': 'L', 'CTC': 'L', 'CTG': 'L', 'CTT': 'L', 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCT': 'P', 'CAC': 'H', 'CAT': 'H', 'CAA': 'Q', 'CAG': 'Q', 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGT': 'R', 'GTA': 'V', 'GTC': 'V', 'GTG': 'V', 'GTT': 'V', 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A', 'GAC': 'D', 'GAT': 'D', 'GAA': 'E', 'GAG': 'E', 'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGT': 'G', 'TCA': 'S', 'TCC': 'S', 'TCG': 'S', 'TCT': 'S', 'TTC': 'F', 'TTT': 'F', 'TTA': 'L', 'TTG': 'L', 'TAC': 'Y', 'TAT': 'Y', 'TAA': '*', 'TAG': '*', 'TGC': 'C', 'TGT': 'C', 'TGA': '*', 'TGG': 'W'}

LINKERS module-attribute

LINKERS = {'T2A': {'dna': 'GAGGGCAGAGGAAGTCTGCTAACATGCGGTGACGTCGAGGAGAATCCTGGCCCG', 'aa': 'EGRGSLLTCGDVEENPGP', 'source': 'Thosea asigna virus'}, 'P2A': {'dna': 'GGAAGCGGAGCTACTAACTTCAGCCTGCTGAAGCAGGCTGGAGACGTGGAGGAGAACCCTGGACCT', 'aa': 'GSGATNFSLLKQAGDVEENPGP', 'source': 'Porcine teschovirus-1'}, 'E2A': {'dna': 'CAGTGTACTAATTATGCTCTCTTGAAATTGGCTGGAGATGTTGAGAGCAACCCAGGTCCC', 'aa': 'QCTNYALLKLAGDVESNPGP', 'source': 'Equine rhinitis A virus'}, 'F2A': {'dna': 'GTGAAACAGACTTTGAATTTTGACCTTCTCAAGTTGGCGGGAGACGTGGAGTCCAACCCAGGGCCC', 'aa': 'VKQTLNFDLLKLAGDVESNPGP', 'source': 'Foot-and-mouth disease virus'}}

DEFAULT_LEADERS module-attribute

DEFAULT_LEADERS = {'CD8A': {'aa': 'MALPVTALLLPLALLLHAARP', 'dna': 'ATGGCCCTGCCTGTGACAGCCCTGCTGCTGCCTCTGGCTCTGCTGCTGCATGCCGCTAGACCC', 'source': 'Human CD8A signal peptide (UniProt P01732)', 'species': 'human'}, 'CD28': {'aa': 'MLRLLLALNLFPSIQVTG', 'dna': 'ATGCTCCGCCTGCTGCTGGCCCTGAACCTGTTCCCCAGCATCCAGGTGACCGGC', 'source': 'Human CD28 signal peptide (UniProt P10747)', 'species': 'human'}, 'mCD8B': {'aa': 'MQPWLWLVFSMKLAALWSSSA', 'dna': 'ATGCAGCCTTGGCTGTGGCTCGTGTTCAGCATGAAGCTGGCCGCTCTGTGGAGCTCCAGCGCC', 'source': 'Murine Cd8b1 signal peptide (UniProt P10300)', 'species': 'mouse'}, 'mCD28': {'aa': 'MTLRLLFLALNFFSVQVT', 'dna': 'ATGACCCTGAGACTGCTCTTCCTGGCCCTCAACTTCTTTAGCGTGCAGGTGACC', 'source': 'Murine Cd28 signal peptide (UniProt P31041)', 'species': 'mouse'}, 'H2Kb': {'aa': 'MVPCTLLLLLAAALAPTQTRA', 'dna': 'ATGGTGCCCTGCACCCTGCTCCTGCTTCTGGCCGCTGCCCTCGCTCCTACCCAGACAAGAGCC', 'source': 'Murine H2-K1 (H-2Kb) signal peptide (UniProt P01901)', 'species': 'mouse'}, 'IgK': {'aa': 'METDTLLLWVLLLWVPGSTG', 'dna': 'ATGGAGACAGACACACTCCTGCTATGGGTACTGCTGCTCTGGGTTCCAGGTTCCACTGGT', 'source': 'Murine IgGκ light chain signal peptide', 'species': 'mouse', 'note': 'Widely used for high secretion efficiency in mammalian expression'}, 'TRAC': {'aa': 'MAGTWLLLLLALGCPALPTG', 'dna': 'ATGGCTGGCACCTGGCTGCTGCTGCTGCTGGCCCTGGGATGCCCAGCACTGCCCACAGGC', 'source': 'Synthetic TCR alpha-chain leader peptide (legacy key TRAC)', 'species': 'human'}, 'TRBC': {'aa': 'MGTSLLCWMALCLLGADHADG', 'dna': 'ATGGGCACCAGCCTGCTGTGCTGGATGGCCCTGTGCCTGCTGGGAGCAGACCACGCCGATGGC', 'source': 'Synthetic TCR beta-chain leader peptide (legacy key TRBC)', 'species': 'human'}}

assemble_full_sequences

assemble_full_sequences(clonotypes: DataFrame, contigs_dir: str | Path | None = None, alpha_leader: str | None = 'CD28', beta_leader: str | None = 'CD8A', include_constant: bool = True, constant_source: str = 'ensembl', linker: str = 'T2A', trac_allele: str = 'auto', trbc1_allele: str = 'auto', trbc2_allele: str = 'auto', stop_codons: tuple[str, ...] = ('TAA', 'TGA'), verbose: bool = True, show_progress: bool = True, sample_name_from: str = 'parent', cellranger_dir: str | Path | None = None, sample_sheet: DataFrame | None = None, leader_fallback: str = 'germline', force_alpha_leader: str | None = None, force_beta_leader: str | None = None, secondary_alpha_leader: str | None = None, secondary_beta_leader: str | None = None, codon_optimization: str = 'focal', max_codon_repeats: int = 1, avoid_enzymes: tuple[str, ...] = (), species: str = 'human', constant_species: str | None = None, codon_species: str | None = None, germline_vdj_fallback: bool = False, data_dir: str | Path | None = None, auto_download_germline: bool = False) -> pd.DataFrame

Assemble full-length TCR sequences.

Parameters:

Name Type Description Default
clonotypes DataFrame

Clonotype DataFrame with VDJ sequences (from fwr1/cdr1/fwr2/cdr2/fwr3/cdr3/fwr4)

required
contigs_dir str or Path

Directory with CellRanger contig FASTA files. Required if alpha_leader or beta_leader is set to "from_contig".

None
alpha_leader str or None

Leader sequence for alpha chain. Options: - None: No leader sequence - "from_contig": Extract native leader from contig FASTA (requires contigs_dir) - Key from DEFAULT_LEADERS: "CD8A", "CD28", "IgK", "TRAC", "TRBC" Default is "CD28" to provide distinct sequences from beta chain.

'CD28'
beta_leader str or None

Leader sequence for beta chain. Same options as alpha_leader. Default is "CD8A" to provide distinct sequences from alpha chain.

'CD8A'
leader_fallback str or None

Signal peptide to substitute when a from_contig leader is implausible — weak-Kozak over-capture, out-of-window length, missing Met/h-region (#263). Default "germline" uses the V gene's germline leader; curated keys CD8A/CD28/IgK/TRAC/TRBC are also accepted. None currently resolves to the same germline fallback. Only affects from_contig leaders.

'germline'
include_constant bool

Include constant region sequences.

True
constant_source str

Source for constant regions:

  • "canonical": splice in the packaged canonical human TRAC / TRBC1 / TRBC2 (:data:HUMAN_CONSTANT_REGIONS_AA). When CellRanger contigs are available, the canonical's first ~15 residues are verified against the observed contig start and a qc_warnings entry is emitted on mismatch.
  • "ensembl" (default): back-compat alias for "canonical". The earlier pyensembl-backed path was removed in #66 — it read the full mRNA at the wrong frame offset and silently truncated constants to 2–11 residues.
  • "from-data": read {chain}_constant_aa / {chain}_constant_nt directly from the input frame.
'ensembl'
linker str

Linker sequence for single-chain constructs: "T2A", "P2A", "E2A", "F2A"

'T2A'
trac_allele str

Per-gene allele selection (#113). Default "auto" runs the allele picker over packaged alleles in :data:HUMAN_CONSTANT_ALLELES scoring each against the donor's contig translation; pass an explicit allele label (e.g. "01" or "03") to force a specific canonical. Invalid labels emit a QC warning and fall back to the default. constant_source="from-data" ignores these knobs (the constant comes from the input frame, not the FASTA); a warning is logged in that combination.

'auto'
trbc1_allele str

Per-gene allele selection (#113). Default "auto" runs the allele picker over packaged alleles in :data:HUMAN_CONSTANT_ALLELES scoring each against the donor's contig translation; pass an explicit allele label (e.g. "01" or "03") to force a specific canonical. Invalid labels emit a QC warning and fall back to the default. constant_source="from-data" ignores these knobs (the constant comes from the input frame, not the FASTA); a warning is logged in that combination.

'auto'
trbc2_allele str

Per-gene allele selection (#113). Default "auto" runs the allele picker over packaged alleles in :data:HUMAN_CONSTANT_ALLELES scoring each against the donor's contig translation; pass an explicit allele label (e.g. "01" or "03") to force a specific canonical. Invalid labels emit a QC warning and fall back to the default. constant_source="from-data" ignores these knobs (the constant comes from the input frame, not the FASTA); a warning is logged in that combination.

'auto'
stop_codons tuple of str

Stop codons appended to the codon-optimized constant CDS. Default uses two non-redundant stops (recognized by different release factors → reduced read-through in synthesized constructs). Pass ("TAA",) for single-stop (pre-2.4 behavior) or () to omit stops entirely. Each entry must be one of "TAA"/"TAG"/"TGA"; invalid entries raise ValueError. Stops are only appended to the _optimized columns and the final _constant_nt (alias) — not to _contig columns, which preserve the donor's CellRanger contig bytes verbatim (and are typically truncated past the contig coverage edge).

``("TAA", "TGA")``
verbose bool

Print progress information

True
show_progress bool

Show progress bar

True

Returns:

Type Description
DataFrame

Clonotypes with full sequences added. Allele audit columns emitted per clone (#113):

  • {chain}_allele_called — e.g. "TRBC2*01" or None when no contig + non-explicit override.
  • {chain}_allele_score — float ∈ [0, 1] (1.0 = perfect AA agreement; 1.0 also when the user forced an allele).
  • {chain}_allele_alternatives — semicolon-joined string of runner-up alleles + scores, sorted by score desc with FASTA order as tie-break. Example: "TRBC2*01:1.000;TRBC2*03:0.933". None when the picker no-decided or only one allele was packaged.

Constant NT triad emitted per chain (#116):

  • {chain}_constant_nt_contig — pure CellRanger contig NT past the J→C junction (no canonical splicing, no codon optimization). Truncated where contig coverage ends. None when no contig is available for the clone.
  • {chain}_constant_nt_optimized — codon-optimized canonical CDS for the picked allele (motif-aware via :func:optimize_codons; avoids common restriction sites and homopolymer runs) plus the requested stop codons.
  • {chain}_constant_nt — the assembly-aware blend: uses donor-real bytes from the contig where they agree with the canonical AA, falls back to _optimized for the rest. This is the column most callers want; kept as the default for back-compat.

The same triad is also exposed for full_{chain}_nt (leader + VDJ + constant + stop).

Examples:

>>> # Default: CD28 on alpha, CD8A on beta (distinct leaders)
>>> assembled = assemble_full_sequences(clonotypes)
>>> # No leader sequences
>>> assembled = assemble_full_sequences(clonotypes, alpha_leader=None, beta_leader=None)
>>> # Leader only on beta chain (first in 2A construct)
>>> assembled = assemble_full_sequences(clonotypes, alpha_leader=None, beta_leader="CD8A")
>>> # Extract native leaders from contig FASTAs
>>> assembled = assemble_full_sequences(
...     clonotypes,
...     contigs_dir="/path/to/contigs",
...     alpha_leader="from_contig",
...     beta_leader="from_contig",
... )
Source code in tcrsift/assemble.py
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
def assemble_full_sequences(
    clonotypes: pd.DataFrame,
    contigs_dir: str | Path | None = None,
    alpha_leader: str | None = "CD28",
    beta_leader: str | None = "CD8A",
    include_constant: bool = True,
    constant_source: str = "ensembl",
    linker: str = "T2A",
    trac_allele: str = "auto",
    trbc1_allele: str = "auto",
    trbc2_allele: str = "auto",
    stop_codons: tuple[str, ...] = ("TAA", "TGA"),
    verbose: bool = True,
    show_progress: bool = True,
    sample_name_from: str = "parent",
    cellranger_dir: str | Path | None = None,
    sample_sheet: pd.DataFrame | None = None,
    leader_fallback: str = "germline",
    force_alpha_leader: str | None = None,
    force_beta_leader: str | None = None,
    secondary_alpha_leader: str | None = None,
    secondary_beta_leader: str | None = None,
    codon_optimization: str = "focal",
    max_codon_repeats: int = 1,
    avoid_enzymes: tuple[str, ...] = (),
    species: str = "human",
    constant_species: str | None = None,
    codon_species: str | None = None,
    germline_vdj_fallback: bool = False,
    data_dir: str | Path | None = None,
    auto_download_germline: bool = False,
) -> pd.DataFrame:
    """
    Assemble full-length TCR sequences.

    Parameters
    ----------
    clonotypes : pd.DataFrame
        Clonotype DataFrame with VDJ sequences (from fwr1/cdr1/fwr2/cdr2/fwr3/cdr3/fwr4)
    contigs_dir : str or Path, optional
        Directory with CellRanger contig FASTA files. Required if alpha_leader or
        beta_leader is set to "from_contig".
    alpha_leader : str or None
        Leader sequence for alpha chain. Options:
        - None: No leader sequence
        - "from_contig": Extract native leader from contig FASTA (requires contigs_dir)
        - Key from DEFAULT_LEADERS: "CD8A", "CD28", "IgK", "TRAC", "TRBC"
        Default is "CD28" to provide distinct sequences from beta chain.
    beta_leader : str or None
        Leader sequence for beta chain. Same options as alpha_leader.
        Default is "CD8A" to provide distinct sequences from alpha chain.
    leader_fallback : str or None
        Signal peptide to substitute when a ``from_contig`` leader is
        implausible — weak-Kozak over-capture, out-of-window length, missing
        Met/h-region (#263). Default ``"germline"`` uses the V gene's germline
        leader; curated keys CD8A/CD28/IgK/TRAC/TRBC are also accepted. ``None``
        currently resolves to the same germline fallback. Only affects
        ``from_contig`` leaders.
    include_constant : bool
        Include constant region sequences.
    constant_source : str
        Source for constant regions:

        - ``"canonical"``: splice in the packaged canonical
          human TRAC / TRBC1 / TRBC2 (:data:`HUMAN_CONSTANT_REGIONS_AA`).
          When CellRanger contigs are available, the canonical's first
          ~15 residues are verified against the observed contig start
          and a ``qc_warnings`` entry is emitted on mismatch.
        - ``"ensembl"`` (default): back-compat alias for ``"canonical"``. The
          earlier pyensembl-backed path was removed in #66 — it read
          the full mRNA at the wrong frame offset and silently
          truncated constants to 2–11 residues.
        - ``"from-data"``: read ``{chain}_constant_aa`` /
          ``{chain}_constant_nt`` directly from the input frame.
    linker : str
        Linker sequence for single-chain constructs: "T2A", "P2A", "E2A", "F2A"
    trac_allele, trbc1_allele, trbc2_allele : str
        Per-gene allele selection (#113). Default ``"auto"`` runs the
        allele picker over packaged alleles in
        :data:`HUMAN_CONSTANT_ALLELES` scoring each against the
        donor's contig translation; pass an explicit allele label
        (e.g. ``"01"`` or ``"03"``) to force a specific canonical.
        Invalid labels emit a QC warning and fall back to the
        default. ``constant_source="from-data"`` ignores these knobs
        (the constant comes from the input frame, not the FASTA);
        a warning is logged in that combination.
    stop_codons : tuple of str, default ``("TAA", "TGA")``
        Stop codons appended to the codon-optimized constant CDS.
        Default uses two non-redundant stops (recognized by
        different release factors → reduced read-through in
        synthesized constructs). Pass ``("TAA",)`` for single-stop
        (pre-2.4 behavior) or ``()`` to omit stops entirely. Each
        entry must be one of ``"TAA"``/``"TAG"``/``"TGA"``;
        invalid entries raise ``ValueError``. Stops are only
        appended to the ``_optimized`` columns and the final
        ``_constant_nt`` (alias) — not to ``_contig`` columns,
        which preserve the donor's CellRanger contig bytes verbatim
        (and are typically truncated past the contig coverage edge).
    verbose : bool
        Print progress information
    show_progress : bool
        Show progress bar

    Returns
    -------
    pd.DataFrame
        Clonotypes with full sequences added. Allele audit columns
        emitted per clone (#113):

        - ``{chain}_allele_called`` — e.g. ``"TRBC2*01"`` or ``None``
          when no contig + non-explicit override.
        - ``{chain}_allele_score`` — float ∈ [0, 1] (1.0 = perfect AA
          agreement; 1.0 also when the user forced an allele).
        - ``{chain}_allele_alternatives`` — semicolon-joined string
          of runner-up alleles + scores, sorted by score desc with
          FASTA order as tie-break. Example: ``"TRBC2*01:1.000;TRBC2*03:0.933"``.
          ``None`` when the picker no-decided or only one allele was
          packaged.

        Constant NT triad emitted per chain (#116):

        - ``{chain}_constant_nt_contig`` — pure CellRanger contig
          NT past the J→C junction (no canonical splicing, no
          codon optimization). Truncated where contig coverage
          ends. ``None`` when no contig is available for the clone.
        - ``{chain}_constant_nt_optimized`` — codon-optimized
          canonical CDS for the picked allele (motif-aware via
          :func:`optimize_codons`; avoids common restriction sites
          and homopolymer runs) plus the requested stop codons.
        - ``{chain}_constant_nt`` — the assembly-aware blend: uses
          donor-real bytes from the contig where they agree with
          the canonical AA, falls back to ``_optimized`` for the
          rest. This is the column most callers want; kept as the
          default for back-compat.

        The same triad is also exposed for ``full_{chain}_nt``
        (leader + VDJ + constant + stop).

    Examples
    --------
    >>> # Default: CD28 on alpha, CD8A on beta (distinct leaders)
    >>> assembled = assemble_full_sequences(clonotypes)

    >>> # No leader sequences
    >>> assembled = assemble_full_sequences(clonotypes, alpha_leader=None, beta_leader=None)

    >>> # Leader only on beta chain (first in 2A construct)
    >>> assembled = assemble_full_sequences(clonotypes, alpha_leader=None, beta_leader="CD8A")

    >>> # Extract native leaders from contig FASTAs
    >>> assembled = assemble_full_sequences(
    ...     clonotypes,
    ...     contigs_dir="/path/to/contigs",
    ...     alpha_leader="from_contig",
    ...     beta_leader="from_contig",
    ... )
    """
    from .species import normalize_species, resolve_species

    # Validate inputs
    clonotypes = validate_clonotype_df(clonotypes, for_assembly=True)
    vdj_sp = resolve_species(species, df=clonotypes, warn_mismatch=False)
    const_sp = normalize_species(constant_species) if constant_species else vdj_sp
    cod_sp = normalize_species(codon_species) if codon_species else const_sp

    # Validate stop_codons early so users get the error before any
    # heavy lifting. Empty tuple is allowed (caller wants no stops).
    stops_nt = stop_codons_nt(stop_codons)
    recode = CodonOptimization(
        mode=codon_optimization,
        max_codon_repeats=max_codon_repeats,
        avoid_enzymes=tuple(avoid_enzymes or ()),
        codon_species=cod_sp,
    )

    valid_constant_sources = ["canonical", "ensembl", "from-data"]
    if constant_source not in valid_constant_sources:
        raise TCRsiftValidationError(
            f"Invalid constant_source: '{constant_source}'",
            hint=f"Valid options are: {valid_constant_sources}",
        )

    if constant_source == "from-data" and any(
        a != "auto" for a in (trac_allele, trbc1_allele, trbc2_allele)
    ):
        logger.warning(
            "constant_source='from-data' ignores trac_allele / "
            "trbc1_allele / trbc2_allele — the constant comes from "
            "the input frame, not the packaged canonical FASTA. "
            "Reset the allele kwargs to 'auto' or switch to "
            "constant_source='canonical' to use them."
        )

    # Validate and resolve leader options for each chain
    leader_config = {}
    for chain, leader_param in [("alpha", alpha_leader), ("beta", beta_leader)]:
        if leader_param is None:
            leader_config[chain] = None
        elif leader_param.lower() == "from_contig":
            if not contigs_dir and not cellranger_dir:
                raise TCRsiftValidationError(
                    f"{chain}_leader='from_contig' requires contigs_dir or "
                    "cellranger_dir to be specified",
                    hint="Provide contigs_dir/cellranger_dir with CellRanger FASTA files, or use a default leader like 'CD8A'",
                )
            leader_config[chain] = "from_contig"
        else:
            hit = _lookup_default_leader(leader_param)
            if hit is not None:
                leader_config[chain] = hit[1]
            else:
                raise TCRsiftValidationError(
                    f"Unknown {chain}_leader: '{leader_param}'",
                    hint=f"Valid options are: None, 'from_contig', or one of {list(DEFAULT_LEADERS.keys())}",
                )

    if verbose:
        alpha_desc = _describe_leader(alpha_leader, leader_config["alpha"])
        beta_desc = _describe_leader(beta_leader, leader_config["beta"])
        logger.info(
            f"Assembling full sequences for {len(clonotypes):,} clonotypes "
            f"(species={vdj_sp}, constant_species={const_sp}, codon_species={cod_sp})"
        )
        logger.info(f"  Alpha leader: {alpha_desc}")
        logger.info(f"  Beta leader: {beta_desc}")
        logger.info(f"  Constant regions: {include_constant} (source: {constant_source})")
        logger.info(f"  Linker: {linker}")

    df = clonotypes.copy()
    if germline_vdj_fallback:
        df = reconstruct_germline_vdj(
            df,
            species=vdj_sp,
            codon_species=cod_sp,
            data_dir=data_dir,
            auto_download=auto_download_germline,
        )
        if verbose:
            for ch in ("alpha", "beta"):
                sc = df.get(f"{ch}_vdj_source")
                if sc is not None:
                    n_5p = int((sc == VDJ_SOURCE_5PRIME_RESCUED).sum())
                    n_vj = int((sc == VDJ_SOURCE_VJ_RECONSTRUCTED).sum())
                    if n_5p or n_vj:
                        logger.info(
                            f"  Germline VDJ fallback ({ch}): "
                            f"{n_5p:,} 5'-partial rescued, {n_vj:,} V+J reconstructed"
                        )

    constant_seqs = {}
    if include_constant and constant_source in ("canonical", "ensembl"):
        if constant_source == "ensembl" and verbose:
            logger.info(
                "  constant_source='ensembl' is now an alias for 'canonical' "
                f"(#66) — splicing canonical {const_sp} TRAC / TRBC1 / TRBC2."
            )
        constant_seqs = get_constant_region_sequences(
            stop_codons=stop_codons, species=const_sp, codon_species=cod_sp
        )
        if verbose:
            logger.info(
                f"    Loaded {len(constant_seqs)} canonical constant region sequences"
            )
            if stop_codons:
                logger.info(
                    f"    Appending stop codons {list(stop_codons)} to "
                    "codon-optimized constants."
                )
            else:
                logger.info(
                    "    No stop codons configured (stop_codons=()); "
                    "constants will not be terminated."
                )

    # Warn if from-data constants requested but not present
    if include_constant and constant_source == "from-data":
        constant_cols = [
            "alpha_constant_aa",
            "alpha_constant_nt",
            "beta_constant_aa",
            "beta_constant_nt",
        ]
        if not any(col in df.columns for col in constant_cols):
            logger.warning(
                "  constant_source='from-data' but no constant region columns found in input. "
                "Constants will be omitted."
            )

    # Load contigs whenever a contigs_dir is given. Pre-1.3 we only
    # loaded when a leader was "from_contig"; that gate is too narrow
    # now that the C-region NT blend (#103) also consumes contigs to
    # splice donor-real bytes into the J→C boundary. Loading is cheap
    # relative to assembly and avoids a silent "contigs given but
    # blend silently noop'd" failure mode.
    sample_contigs: dict = {}
    # cellranger_dir is shorthand for contigs_dir + sample_name_from='grandparent'
    # (#124). Resolved here so the rest of the function only sees contigs_dir.
    if cellranger_dir is not None:
        if contigs_dir is not None:
            raise ValueError(
                "assemble_full_sequences: pass exactly one of contigs_dir or "
                "cellranger_dir, not both."
            )
        contigs_dir = cellranger_dir
        sample_name_from = "grandparent"
    if contigs_dir:
        contigs_dir = validate_directory_exists(Path(contigs_dir), "contigs directory")
        if verbose:
            logger.info(
                f"  Loading contigs from {contigs_dir} (sample_name_from={sample_name_from!r})..."
            )
        sample_contigs = load_contigs(
            contigs_dir,
            sample_name_from=sample_name_from,
            sample_sheet=sample_sheet,
        )
        if verbose:
            total_contigs = sum(len(c) for c in sample_contigs.values())
            logger.info(f"    Loaded {total_contigs:,} contigs from {len(sample_contigs)} samples")

    # Process each clonotype
    if verbose:
        logger.info("  Assembling sequences...")

    assembly_results = []

    # Build per-gene allele override dict for the picker (#113).
    allele_overrides = {
        "TRAC": trac_allele,
        "TRBC1": trbc1_allele,
        "TRBC2": trbc2_allele,
    }

    # Create iterator with optional progress bar
    row_iter = df.iterrows()
    if show_progress:
        row_iter = tqdm(
            list(df.iterrows()),
            desc="Assembling sequences",
            unit="clone",
        )

    for idx, row in row_iter:
        result = _assemble_clone(
            row,
            sample_contigs,
            constant_seqs,
            leader_config,
            include_constant,
            constant_source,
            allele_overrides=allele_overrides,
            stops_nt=stops_nt,
            recode=recode,
            vdj_species=vdj_sp,
            constant_species=const_sp,
            codon_species=cod_sp,
        )
        assembly_results.append(result)

    # Add assembly columns to dataframe
    result_df = pd.DataFrame(assembly_results)
    for col in result_df.columns:
        df[col] = result_df[col].values

    # Correct blanket-N α junctions using a per-J consensus from this cohort's
    # contig-verified clones BEFORE building single-chain constructs and leader
    # policy views so full_alpha_*, full_alpha_nt_optimized, and single_chain_*
    # remain byte-for-byte synchronized (#242).
    df = _apply_cohort_alpha_junctions(df, codon_species=cod_sp)

    # Add single-chain construct if requested
    if linker and "full_beta_aa" in df.columns and "full_alpha_aa" in df.columns:
        if verbose:
            logger.info(f"  Creating single-chain constructs with {linker} linker...")
        df = _add_single_chain(df, linker)

    # Leader policy (#270)
    df = apply_leader_policy(
        df, linker,
        leader_fallback=leader_fallback or "germline",
        force_alpha=force_alpha_leader, force_beta=force_beta_leader,
        secondary_alpha=secondary_alpha_leader, secondary_beta=secondary_beta_leader,
        verbose=verbose,
        species=vdj_sp,
        recode=recode,
    )

    # Summary
    if verbose:
        n_with_alpha = df["full_alpha_aa"].notna().sum() if "full_alpha_aa" in df.columns else 0
        n_with_beta = df["full_beta_aa"].notna().sum() if "full_beta_aa" in df.columns else 0
        n_single_chain = (
            df["single_chain_aa"].notna().sum() if "single_chain_aa" in df.columns else 0
        )
        logger.info("  Assembly complete:")
        logger.info(f"    With full alpha: {n_with_alpha:,}")
        logger.info(f"    With full beta: {n_with_beta:,}")
        logger.info(f"    Single-chain constructs: {n_single_chain:,}")

    # Per-row override audit column (#90). True where the canonical
    # picked by the J-family rule disagreed with CellRanger's raw
    # `beta_c_gene` call. Lets users filter / inspect post-hoc
    # without going through the log. Written even when no overrides
    # fired so the column is always present (defaults to False).
    if "beta_c_gene" in df.columns:
        df["beta_c_gene_overridden"] = _trbc_override_mask(df)

    # One aggregate line for J-family overrides of CellRanger TRBC
    # (#90). pick_canonical_constant is silent per-call to avoid a
    # log flood on cohorts where every other clone hits the case.
    # Gated by `verbose` so silent runs stay silent — the override
    # itself still happens, this is the audit trail. The per-row
    # `beta_c_gene_overridden` column above is the data-side audit
    # that survives the log.
    if verbose:
        n_overrides = (
            int(df["beta_c_gene_overridden"].sum())
            if "beta_c_gene_overridden" in df.columns
            else 0
        )
        if n_overrides:
            n_beta = df["beta_c_gene"].notna().sum() if "beta_c_gene" in df.columns else 0
            logger.warning(
                "  Overrode CellRanger TRBC call on %d / %d β clones to match "
                "J-family parity (TRBJ1→TRBC1, TRBJ2→TRBC2). CellRanger's "
                "TRBC1/2 discrimination is unreliable; the locus rule is "
                "authoritative.",
                n_overrides, n_beta,
            )

        # Cohort allele audit (#119, #120). Emits the per-chain
        # called/no-called breakdown + any novel-allele candidates
        # detected across the cohort. Silent on small cohorts where
        # the heuristic thresholds don't fire.
        if any(
            f"{c}_allele_called_reason" in df.columns for c in ("alpha", "beta")
        ):
            for line in allele_audit_report(df).splitlines():
                logger.info(line)

    # Constant-allele fidelity (#187). Derive a scalar divergence count per
    # chain from the per-position column the assembler recorded against the
    # donor's sequenced bases, and warn loudly (regardless of verbose) so an
    # allele-level fidelity loss isn't silent. Both are no-ops without contigs
    # (the divergence columns stay None / 0).
    for chain in ("alpha", "beta"):
        div_col = f"{chain}_allele_divergence_positions"
        if div_col in df.columns:
            df[f"{chain}_constant_allele_divergence"] = df[div_col].apply(
                _count_divergence_positions
            )
    _warn_constant_allele_divergence(df)

    # Synthesis-hazard QC (#206). Scores each assembled construct NT for
    # gene-synthesis pitfalls (GC window, homopolymers, long repeats, surviving
    # restriction sites) plus cross-construct hazards (duplicate CDS, α/β swap).
    # No-op when no construct-NT column exists. Warn (regardless of verbose) on
    # any flagged construct so a vendor-rejection risk isn't silent.
    df = add_synthesis_qc(df)

    # Surface dual-α (allelic-inclusion) clones explicitly (#237) — easy to miss
    # when the second α is packed into ``merged_alpha_partners``. ``alpha_count``
    # is the number of distinct α the clone carries; ``dual_alpha`` flags >1.
    if "merged_alpha_partners" in df.columns and len(df):
        def _alpha_partners(val: object) -> list:
            s = "" if val is None or (isinstance(val, float) and pd.isna(val)) else str(val)
            return [p.strip() for p in s.split(";") if p.strip() and p.strip().lower() != "nan"]
        partners = df["merged_alpha_partners"].map(_alpha_partners)
        df["alpha_count"] = partners.map(lambda p: len(p) if p else 1)
        df["dual_alpha"] = df["alpha_count"] > 1
        # Explicit second-α identity (#237): the partner α that isn't this row's
        # primary CDR3_alpha (else the 2nd listed), so the dual nature reads
        # without unpacking merged_alpha_partners. None for single-α clones.
        prim = df["CDR3_alpha"] if "CDR3_alpha" in df.columns else pd.Series([None] * len(df), index=df.index)
        df["CDR3_alpha_2"] = [
            next((a for a in ps if a != p), (ps[1] if len(ps) > 1 else None))
            for ps, p in zip(partners, prim)
        ]

    # Per-construct contig-verification provenance (#243/#244): a construct is
    # contig-verified only when every present chain's J→C junction residue was
    # read from the donor's contig (not the canonical fallback). Drives the
    # fail-closed fidelity gate.
    if len(df):
        df["construct_contig_verified"] = [
            not _unverified_chains(row) for _, row in df.iterrows()
        ]

    if "synth_gc_ok" in df.columns and len(df):
        n_hazard = int(
            (~df["synth_gc_ok"]).sum()
            + (df.get("synth_max_homopolymer", pd.Series(dtype=int)) >= 9).sum()
            + (df.get("synth_max_repeat", pd.Series(dtype=int)) >= 20).sum()
            + (df.get("synth_restriction_sites", pd.Series(dtype=str)) != "").sum()
        )
        if n_hazard:
            logger.warning(
                "  Synthesis-hazard QC flagged %d construct-level issue(s) "
                "(GC window / homopolymer / repeat / restriction site). See the "
                "synth_* columns and synthesis_qc_report() for details.",
                n_hazard,
            )

    # Framework (FR1–FR3) germline divergence (#286 follow-up). Compares each
    # clone's V-domain framework to the IMGT V-REGION germline and records the
    # divergence for the `framework` rows of collect_germline_variants. No-op
    # (adds no columns) unless the V-REGION reference is cached
    # (`tcrsift data download --db imgt_trav_vregion imgt_trbv_vregion`).
    df = annotate_vregion_divergence(df, species=vdj_sp, data_dir=data_dir)

    # Schema stability (#278). `qc_warnings` is stashed per-clone only when a
    # warning fires, so the column is absent on a clean cohort and present on a
    # noisy one — 144 vs 145 columns across donors, which breaks naive
    # `df["qc_warnings"]` consumers and cross-cohort concats. Always emit it,
    # with an empty list per row where no warning was raised (a list, not NaN,
    # so the surfacing loop's `isinstance(qcs, list)` and callers' `... or []`
    # both stay correct).
    df = _ensure_qc_warnings_column(df)

    return df

reconstruct_germline_vdj

reconstruct_germline_vdj(clonotypes: DataFrame, *, species: str = 'human', codon_species: str | None = None, data_dir=None, auto_download: bool = False) -> pd.DataFrame

Populate missing VDJ_{alpha,beta}_{aa,nt} via IMGT germline rescue/reconstruction.

Parameters:

Name Type Description Default
clonotypes DataFrame

Clonotype table with CDR3_alpha/CDR3_beta, {chain}_v_gene, {chain}_j_gene, and optional partial_VDJ_{chain}_{aa,nt}.

required
species str

VDJ organism species ("human", "mouse", or "auto").

``"human"``
codon_species str or None

Species codon table for any untemplated junctional back-translation.

None
data_dir str or Path

Override tcrsift reference cache directory.

None
auto_download bool

When True, automatically download missing IMGT V-REGION and J-REGION references for species into the cache before reconstructing.

False

Returns:

Type Description
DataFrame

Copy of clonotypes with VDJ_{chain}_aa, VDJ_{chain}_nt, {chain}_vdj_source, {chain}_vdj_germline_allele, and updated qc_warnings.

Source code in tcrsift/_assemble_germline.py
def reconstruct_germline_vdj(
    clonotypes: pd.DataFrame,
    *,
    species: str = "human",
    codon_species: str | None = None,
    data_dir=None,
    auto_download: bool = False,
) -> pd.DataFrame:
    """Populate missing ``VDJ_{alpha,beta}_{aa,nt}`` via IMGT germline rescue/reconstruction.

    Parameters
    ----------
    clonotypes : pd.DataFrame
        Clonotype table with ``CDR3_alpha``/``CDR3_beta``, ``{chain}_v_gene``,
        ``{chain}_j_gene``, and optional ``partial_VDJ_{chain}_{aa,nt}``.
    species : str, default ``"human"``
        VDJ organism species (``"human"``, ``"mouse"``, or ``"auto"``).
    codon_species : str or None
        Species codon table for any untemplated junctional back-translation.
    data_dir : str or Path, optional
        Override tcrsift reference cache directory.
    auto_download : bool, default False
        When True, automatically download missing IMGT V-REGION and J-REGION
        references for ``species`` into the cache before reconstructing.

    Returns
    -------
    pd.DataFrame
        Copy of ``clonotypes`` with ``VDJ_{chain}_aa``, ``VDJ_{chain}_nt``,
        ``{chain}_vdj_source``, ``{chain}_vdj_germline_allele``, and updated
        ``qc_warnings``.
    """
    from .datacache import GROUPS, ensure_cached
    from .species import normalize_species, resolve_species

    sp = resolve_species(species, df=clonotypes, warn_mismatch=False)
    cod_sp = normalize_species(codon_species) if codon_species else sp

    if auto_download:
        grp = "germline_mouse" if sp == "mouse" else "germline"
        for db in GROUPS[grp]:
            if "leader" in db:
                continue
            ensure_cached(db, data_dir=data_dir, auto_download=True)

    df = clonotypes.copy()
    if len(df) == 0:
        for chain in ("alpha", "beta"):
            df[f"{chain}_vdj_source"] = pd.Series(dtype=object)
            df[f"{chain}_vdj_germline_allele"] = pd.Series(dtype=object)
        return df

    existing_qcs: list[list[str]] = []
    if "qc_warnings" in df.columns:
        for val in df["qc_warnings"]:
            if isinstance(val, list):
                existing_qcs.append(list(val))
            elif isinstance(val, str) and val.strip():
                existing_qcs.append([val.strip()])
            else:
                existing_qcs.append([])
    else:
        existing_qcs = [[] for _ in range(len(df))]

    for chain in ("alpha", "beta"):
        aa_col = f"VDJ_{chain}_aa"
        nt_col = f"VDJ_{chain}_nt"
        aa_out: list[str | None] = []
        nt_out: list[str | None] = []
        src_out: list[str | None] = []
        allele_out: list[str | None] = []

        for row_pos, (_, row) in enumerate(df.iterrows()):
            vdj_aa, vdj_nt, src, g_allele = reconstruct_germline_vdj_chain(
                row,
                chain,
                species=sp,
                codon_species=cod_sp,
                data_dir=data_dir,
            )
            aa_out.append(vdj_aa if vdj_aa is not None else row.get(aa_col))
            nt_out.append(vdj_nt if vdj_nt is not None else row.get(nt_col))
            src_out.append(src)
            allele_out.append(g_allele)
            if src in GERMLINE_IMPUTED_VDJ_SOURCES:
                tag = f"{chain}_vdj_germline_reconstructed"
                if tag not in existing_qcs[row_pos]:
                    existing_qcs[row_pos].append(tag)

        df[aa_col] = aa_out
        df[nt_col] = nt_out
        df[f"{chain}_vdj_source"] = src_out
        df[f"{chain}_vdj_germline_allele"] = allele_out

    df["qc_warnings"] = existing_qcs
    return df

translate_dna

translate_dna(dna_seq: str) -> tuple[str, str]

Translate DNA sequence to amino acids.

Returns:

Type Description
tuple

(amino_acid_sequence, ragged_3p_nucleotides)

Source code in tcrsift/_assemble_codons.py
def translate_dna(dna_seq: str) -> tuple[str, str]:
    """
    Translate DNA sequence to amino acids.

    Returns
    -------
    tuple
        (amino_acid_sequence, ragged_3p_nucleotides)
    """
    dna_seq = str(dna_seq).upper()
    seq_len = len(dna_seq)
    seq_len_trimmed = (seq_len // 3) * 3

    if seq_len != seq_len_trimmed:
        ragged_nt = dna_seq[seq_len_trimmed:]
        dna_seq = dna_seq[:seq_len_trimmed]
    else:
        ragged_nt = ""

    aa_seq = "".join([CODON_TABLE.get(dna_seq[i : i + 3], "X") for i in range(0, len(dna_seq), 3)])

    # Stop at first stop codon
    if "*" in aa_seq:
        ragged_nt = ""
        aa_seq = aa_seq[: aa_seq.index("*")]

    return aa_seq, ragged_nt

find_longest_orf

find_longest_orf(dna_seq: str) -> tuple[str, int, str]

Find and translate the longest open reading frame.

Returns:

Type Description
tuple

(amino_acid_sequence, start_offset, ragged_3p_nucleotides)

Source code in tcrsift/_assemble_codons.py
def find_longest_orf(dna_seq: str) -> tuple[str, int, str]:
    """
    Find and translate the longest open reading frame.

    Returns
    -------
    tuple
        (amino_acid_sequence, start_offset, ragged_3p_nucleotides)
    """
    dna_seq = str(dna_seq).upper()
    start_positions = [i for i in range(len(dna_seq)) if dna_seq[i : i + 3] == "ATG"]

    longest_aa = ""
    longest_offset = 0
    longest_ragged = ""

    for start in start_positions:
        subseq = dna_seq[start:]
        aa, ragged = translate_dna(subseq)
        if len(aa) > len(longest_aa):
            longest_aa = aa
            longest_offset = start
            longest_ragged = ragged

    return longest_aa, longest_offset, longest_ragged

parse_fasta

parse_fasta(path: str | Path) -> dict[str, str]

Parse a FASTA (or .fasta.gz) file.

Returns:

Type Description
dict

Mapping from sequence ID to sequence

Source code in tcrsift/_assemble_codons.py
def parse_fasta(path: str | Path) -> dict[str, str]:
    """
    Parse a FASTA (or ``.fasta.gz``) file.

    Returns
    -------
    dict
        Mapping from sequence ID to sequence
    """
    import gzip

    path = Path(path)
    results = {}
    curr_id = None
    lines = []

    opener = gzip.open if path.name.lower().endswith(".gz") else open
    with opener(path, "rt", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line.startswith(">"):
                if curr_id and lines:
                    results[curr_id] = "".join(lines)
                    lines = []
                curr_id = line[1:].split()[0]  # Take first word after >
            else:
                lines.append(line)

        # Don't forget last entry
        if curr_id and lines:
            results[curr_id] = "".join(lines)

    return results

load_contigs

load_contigs(contig_dir: str | Path | None = None, *, sample_name_from: str = 'parent', cellranger_dir: str | Path | None = None, sample_sheet: DataFrame | None = None) -> dict[str, dict[str, str]]

Load contig sequences from a CellRanger-style output tree (#124).

Parameters:

Name Type Description Default
contig_dir str or Path

Root directory to scan for *contig*.fasta. Mutually exclusive with cellranger_dir.

None
sample_name_from ('parent', 'grandparent', 'sheet')

How to derive the sample name from each discovered FASTA's path:

  • 'parent' (default, backward-compat) — sample = FASTA's immediate parent directory name. Matches the symlinked layout contig_dir/{sample}/filtered_contig.fasta.
  • 'grandparent' — sample = FASTA's grandparent directory name. Matches CellRanger multi output: per_sample_outs/{sample}/vdj_t/filtered_contig.fasta.
  • 'sheet' — match each FASTA against sample_sheet['vdj_dir'] and take the corresponding sample column. Most explicit; useful for non-standard layouts.
'parent'
cellranger_dir str or Path

Shorthand for contig_dir=cellranger_dir, sample_name_from='grandparent'. Pass a raw CellRanger per_sample_outs/ directory and the sample names will resolve correctly without a symlink tree. Mutually exclusive with contig_dir.

None
sample_sheet DataFrame

Required when sample_name_from='sheet'. Must have columns sample and vdj_dir; each FASTA's path must be inside one of the listed vdj_dir paths.

None

Returns:

Type Description
dict

Nested dict: sample -> contig_id -> sequence.

Source code in tcrsift/_assemble_codons.py
def load_contigs(
    contig_dir: str | Path | None = None,
    *,
    sample_name_from: str = "parent",
    cellranger_dir: str | Path | None = None,
    sample_sheet: pd.DataFrame | None = None,
) -> dict[str, dict[str, str]]:
    """
    Load contig sequences from a CellRanger-style output tree (#124).

    Parameters
    ----------
    contig_dir : str or Path, optional
        Root directory to scan for ``*contig*.fasta``. Mutually exclusive
        with ``cellranger_dir``.
    sample_name_from : {'parent', 'grandparent', 'sheet'}, default 'parent'
        How to derive the sample name from each discovered FASTA's path:

        - ``'parent'`` (default, backward-compat) — sample = FASTA's
          immediate parent directory name. Matches the symlinked layout
          ``contig_dir/{sample}/filtered_contig.fasta``.
        - ``'grandparent'`` — sample = FASTA's grandparent directory name.
          Matches CellRanger ``multi`` output:
          ``per_sample_outs/{sample}/vdj_t/filtered_contig.fasta``.
        - ``'sheet'`` — match each FASTA against ``sample_sheet['vdj_dir']``
          and take the corresponding ``sample`` column. Most explicit;
          useful for non-standard layouts.
    cellranger_dir : str or Path, optional
        Shorthand for ``contig_dir=cellranger_dir, sample_name_from='grandparent'``.
        Pass a raw CellRanger ``per_sample_outs/`` directory and the sample
        names will resolve correctly without a symlink tree. Mutually
        exclusive with ``contig_dir``.
    sample_sheet : pandas.DataFrame, optional
        Required when ``sample_name_from='sheet'``. Must have columns
        ``sample`` and ``vdj_dir``; each FASTA's path must be inside one of
        the listed ``vdj_dir`` paths.

    Returns
    -------
    dict
        Nested dict: ``sample -> contig_id -> sequence``.
    """
    if cellranger_dir is not None:
        if contig_dir is not None:
            raise ValueError(
                "load_contigs: pass exactly one of contig_dir or cellranger_dir, not both."
            )
        contig_dir = cellranger_dir
        sample_name_from = "grandparent"
    if contig_dir is None:
        raise ValueError(
            "load_contigs: must pass either contig_dir or cellranger_dir."
        )
    if sample_name_from not in SAMPLE_NAME_FROM_CHOICES:
        raise ValueError(
            f"load_contigs: sample_name_from={sample_name_from!r} not in "
            f"{SAMPLE_NAME_FROM_CHOICES}"
        )
    if sample_name_from == "sheet" and sample_sheet is None:
        raise ValueError(
            "load_contigs: sample_name_from='sheet' requires sample_sheet=..."
        )

    contig_dir = Path(contig_dir)
    sample_contigs: dict[str, dict[str, str]] = {}

    sheet_dir_to_sample: dict[Path, str] = {}
    if sample_name_from == "sheet":
        missing = {"sample", "vdj_dir"} - set(sample_sheet.columns)
        if missing:
            raise ValueError(
                f"load_contigs: sample_sheet is missing required columns {sorted(missing)}"
            )
        sheet_dir_to_sample = {}
        for row in sample_sheet.itertuples(index=False):
            p = Path(row.vdj_dir).resolve()
            sheet_dir_to_sample[p.parent if p.is_file() else p] = row.sample

    def _sample_for(fasta_path: Path) -> str | None:
        if sample_name_from == "parent":
            return fasta_path.parent.name
        if sample_name_from == "grandparent":
            return fasta_path.parent.parent.name
        # sheet
        resolved = fasta_path.resolve()
        for sheet_path, sample in sheet_dir_to_sample.items():
            try:
                resolved.relative_to(sheet_path)
            except ValueError:
                continue
            return sample
        return None

    fasta_candidates = sorted(
        {
            *contig_dir.rglob("*contig*.fasta"),
            *contig_dir.rglob("*contig*.fasta.gz"),
        }
    )
    for fasta_path in fasta_candidates:
        if not fasta_path.is_file():
            continue
        sample_name = _sample_for(fasta_path)
        if sample_name is None:
            logger.warning(
                "load_contigs: %s did not match any sample_sheet vdj_dir; skipping",
                fasta_path,
            )
            continue
        sample_contigs.setdefault(sample_name, {}).update(parse_fasta(fasta_path))

    # Flat-layout fallback: bare ``*.fasta(.gz)`` files directly in contig_dir
    # that were not already matched above by ``*contig*.fasta(.gz)``.
    if sample_name_from == "parent":
        seen_fastas = {p.resolve() for p in fasta_candidates}
        for fasta_path in sorted({*contig_dir.glob("*.fasta"), *contig_dir.glob("*.fasta.gz")}):
            if not fasta_path.is_file() or fasta_path.resolve() in seen_fastas:
                continue
            stem = fasta_path.name[:-9] if fasta_path.name.lower().endswith(".fasta.gz") else fasta_path.stem
            sample_name = stem.split("_")[0]
            sample_contigs.setdefault(sample_name, {}).update(parse_fasta(fasta_path))

    # CellRanger JSON fallback: GEO deposits frequently ship
    # ``all_contig_annotations.json(.gz)`` instead of ``filtered_contig.fasta``.
    # Supplement any sample lacking FASTA coverage (or missing contig IDs) from JSON.
    json_candidates = sorted(
        {
            *contig_dir.rglob("*contig_annotations*.json"),
            *contig_dir.rglob("*contig_annotations*.json.gz"),
        }
    )
    for json_path in json_candidates:
        if not json_path.is_file():
            continue
        sample_name = _sample_for(json_path)
        if sample_name is None:
            continue
        try:
            parsed_json = parse_contig_json(json_path)
        except Exception as exc:
            logger.warning("load_contigs: could not parse %s: %s", json_path, exc)
            continue
        if parsed_json:
            target = sample_contigs.setdefault(sample_name, {})
            for cid, seq in parsed_json.items():
                target.setdefault(cid, seq)

    logger.info(f"Loaded contigs from {len(sample_contigs)} samples")
    return sample_contigs

get_constant_region_sequences

get_constant_region_sequences(*, stop_codons: tuple[str, ...] = ('TAA', 'TGA'), species: str = 'human', codon_species: str | None = None) -> dict[str, str]

Return TCR constant-region CDS (DNA) via codon-aware back-translation.

Source code in tcrsift/assemble.py
def get_constant_region_sequences(
    *,
    stop_codons: tuple[str, ...] = ("TAA", "TGA"),
    species: str = "human",
    codon_species: str | None = None,
) -> dict[str, str]:
    """Return TCR constant-region CDS (DNA) via codon-aware back-translation."""
    from .species import normalize_species

    const_sp = normalize_species(species)
    cod_sp = normalize_species(codon_species) if codon_species else const_sp
    stops_nt = stop_codons_nt(stop_codons)
    regions = CONSTANT_REGIONS_AA_BY_SPECIES[const_sp]
    out: dict[str, str] = {}
    for name, aa in regions.items():
        out[name] = optimize_codons(aa, species=cod_sp) + stops_nt
    return out

validate_sequences

validate_sequences(df: DataFrame, strict: bool = False, fix: bool = False, *, species: str | None = None) -> list[ValidationMessage]

Validate assembled sequences end-to-end per row (#67, #68).

Per-chain checks on each full_{chain}_aa row:

  • Length window (200–450 aa).
  • CDR3 substring present in the assembled sequence.
  • Constant region's canonical C-terminus (from :data:CONSTANT_REGION_ENDINGS).
  • Constant region's canonical start (first 8+ residues of :data:HUMAN_CONSTANT_REGIONS_AA).
  • Constant length floor (:data:CONSTANT_AA_FLOOR).
  • No premature stop codon (* mid-chain).
  • Methionine start (when a leader was included).
  • Standard residue alphabet only (:data:_VALID_AA_CHARS).
  • Byte-for-byte equality of leader + vdj + constant and the assembled full_{chain}_aa, when all three parts are present.

Cross-row checks:

  • β-chain J→C in-cis parity: TRBJ1* pairs with TRBC1, TRBJ2* with TRBC2.
  • Single-chain integrity: linker present in single_chain_aa.
  • Per-row qc_warnings (stashed by _add_constant_regions) are surfaced.

Returns a flat list of :class:ValidationMessage (a str subclass with .idx and .severity attributes). When strict is True, raises :class:TCRsiftValidationError if any load-bearing checks fail. Informational notes ("didn't have enough info to check") are returned but never raise — distinguishing those from a silent pass was the gap that hid #66.

When fix is True, autocorrect β J→C parity mismatches in-place via :func:fix_jc_parity before validating (#89). Autocorrection notes are prepended to the returned messages and the input frame is mutated unconditionally — the mutation survives even when a later check fails and strict=True raises.

Source code in tcrsift/_assemble_qc.py
def validate_sequences(
    df: pd.DataFrame,
    strict: bool = False,
    fix: bool = False,
    *,
    species: str | None = None,
) -> list[ValidationMessage]:
    """Validate assembled sequences end-to-end per row (#67, #68).

    Per-chain checks on each ``full_{chain}_aa`` row:

    - Length window (200–450 aa).
    - CDR3 substring present in the assembled sequence.
    - Constant region's canonical C-terminus (from
      :data:`CONSTANT_REGION_ENDINGS`).
    - Constant region's canonical start (first 8+ residues of
      :data:`HUMAN_CONSTANT_REGIONS_AA`).
    - Constant length floor (:data:`CONSTANT_AA_FLOOR`).
    - No premature stop codon (``*`` mid-chain).
    - Methionine start (when a leader was included).
    - Standard residue alphabet only (:data:`_VALID_AA_CHARS`).
    - Byte-for-byte equality of ``leader + vdj + constant`` and the
      assembled ``full_{chain}_aa``, when all three parts are present.

    Cross-row checks:

    - β-chain J→C in-cis parity: ``TRBJ1*`` pairs with TRBC1,
      ``TRBJ2*`` with TRBC2.
    - Single-chain integrity: linker present in ``single_chain_aa``.
    - Per-row ``qc_warnings`` (stashed by ``_add_constant_regions``)
      are surfaced.

    Returns a flat list of :class:`ValidationMessage` (a ``str``
    subclass with ``.idx`` and ``.severity`` attributes). When
    ``strict`` is True, raises :class:`TCRsiftValidationError` if any
    load-bearing checks fail. Informational notes ("didn't have enough
    info to check") are returned but never raise — distinguishing
    those from a silent pass was the gap that hid #66.

    When ``fix`` is True, autocorrect β J→C parity mismatches in-place
    via :func:`fix_jc_parity` before validating (#89). Autocorrection
    notes are prepended to the returned messages and the input frame
    is mutated *unconditionally* — the mutation survives even when a
    later check fails and ``strict=True`` raises.
    """
    load_bearing: list[ValidationMessage] = []
    informational: list[ValidationMessage] = []
    autocorrect_notes: list[ValidationMessage] = []

    def _lb(idx, text):
        load_bearing.append(
            ValidationMessage(f"Clone {idx}: {text}", idx=idx, severity="load_bearing")
        )

    def _info(idx, text):
        informational.append(
            ValidationMessage(f"Clone {idx}: {text}", idx=idx, severity="informational")
        )

    from .species import detect_vdj_species, normalize_species

    _sp = normalize_species(species, allow_auto=True) if species else None
    explicit_vdj_sp = None if _sp == "auto" else _sp
    detected_vdj_sp = explicit_vdj_sp or detect_vdj_species(df)

    if fix:
        autocorrect_notes = fix_jc_parity(df)

    # 1. Per-chain, per-row shape and content checks.
    for chain in ["alpha", "beta"]:
        col = f"full_{chain}_aa"
        if col not in df.columns:
            continue
        for idx, row in df.iterrows():
            seq = row.get(col, "")
            if not seq or not isinstance(seq, str):
                continue

            if len(seq) < 200:
                _lb(idx, f"{chain} chain too short ({len(seq)} aa)")
            elif len(seq) > 450:
                _lb(idx, f"{chain} chain too long ({len(seq)} aa)")

            # Standard residue alphabet only.
            invalid = sorted(set(seq) - _VALID_AA_CHARS)
            if invalid:
                _lb(idx,
                    f"full_{chain}_aa has invalid residues {''.join(invalid)!r}")

            # Premature stop codon: ``*`` anywhere except the final position.
            body = seq.rstrip("*")
            if "*" in body:
                pos = body.index("*")
                _lb(idx,
                    f"full_{chain}_aa has premature stop "
                    f"at position {pos} of {len(seq)}")

            # Methionine start (only when leader was included).
            leader = row.get(f"{chain}_leader_aa")
            if isinstance(leader, str) and leader and not seq.startswith("M"):
                _lb(idx,
                    f"full_{chain}_aa doesn't start with M "
                    f"(starts with {seq[:5]!r}; leader present)")
            elif row.get(f"{chain}_leader_source") == "missing_from_contig":
                _lb(idx,
                    f"full_{chain}_aa is missing its requested from_contig "
                    f"signal peptide (starts with {seq[:5]!r})")

            # Surface a from_contig signal-peptide QC flag (#263) as an
            # informational note — the extracted leader is kept (it's the best
            # available), but a weak-Kozak over-capture / out-of-range length /
            # missing h-region shouldn't pass silently. Never load-bearing here:
            # the assembler already substitutes a curated SP when leader_fallback
            # is set; this just keeps the flag visible in a validation pass.
            lqc = row.get(f"{chain}_leader_qc")
            if isinstance(lqc, str) and lqc not in ("ok", "curated_fallback"):
                support = row.get(f"{chain}_leader_support")
                _info(idx,
                    f"{chain} signal peptide QC={lqc} "
                    f"(len {row.get(f'{chain}_leader_len')}, "
                    f"kozak {row.get(f'{chain}_leader_kozak_score')}, "
                    f"support {support})")

            cdr3_col = f"CDR3_{chain}"
            if cdr3_col in row:
                cdr3 = row[cdr3_col]
                if isinstance(cdr3, str) and cdr3 and cdr3 not in seq:
                    _lb(idx,
                        f"CDR3_{chain}={cdr3!r} not found in full sequence")

            # Constant region length floor (separate from full-chain
            # length check — catches truncations that hid behind a
            # long leader).
            const = row.get(f"{chain}_constant_aa")
            if isinstance(const, str) and const:
                floor = CONSTANT_AA_FLOOR[chain]
                if len(const) < floor:
                    _lb(idx,
                        f"{chain}_constant_aa too short "
                        f"({len(const)} aa, floor {floor})")

            # J→C junction-seam guard (#235). The constant must begin with a
            # valid junction residue (β: E; α: N/Y/D/H) followed by the bare
            # canonical — NOT the bare canonical directly. A direct-canonical
            # start means the junction residue was dropped and the chain is 1 aa
            # short at the seam. This is the check the prior self-consistent
            # canonical-start comparison (observed vs the row's own constant_aa)
            # could not make, which is how #235 shipped silently.
            c_base = _resolve_c_gene(row, chain).strip().upper().split("*")[0]
            row_const_sp = _infer_constant_species(
                const, seq, c_base, default=explicit_vdj_sp or detected_vdj_sp or "human"
            )
            bare = CONSTANT_REGIONS_AA_BY_SPECIES[row_const_sp].get(c_base)
            if isinstance(const, str) and const and bare:
                bare8 = bare[:8]
                if const.startswith(bare8):
                    _lb(idx,
                        f"{chain}_constant_aa starts at the bare canonical "
                        f"{bare8!r} — J→C junction residue missing (chain 1 aa "
                        f"short at the seam)")
                elif not (
                    const[0] in _VALID_JUNCTION_RESIDUES.get(chain, frozenset())
                    and const[1:].startswith(bare8)
                ):
                    _lb(idx,
                        f"{chain}_constant_aa has an unexpected J→C seam: "
                        f"{const[:9]!r} (expected a valid junction residue "
                        f"{sorted(_VALID_JUNCTION_RESIDUES.get(chain, ()))} "
                        f"+ canonical {bare8!r})")
                elif chain == "alpha":
                    j_gene_val = row.get("alpha_j_gene")
                    if explicit_vdj_sp:
                        expected_set = {
                            _traj_junction_residue(j_gene_val, species=explicit_vdj_sp)
                        } - {None}
                    elif detected_vdj_sp and row_const_sp == detected_vdj_sp:
                        expected_set = {
                            _traj_junction_residue(j_gene_val, species=detected_vdj_sp)
                        } - {None}
                    else:
                        # Auto-detected species can be ambiguous on uppercased mouse
                        # TRAJ calls or chimeric constructs; accept either germline.
                        expected_set = {
                            _traj_junction_residue(j_gene_val, species="human"),
                            _traj_junction_residue(j_gene_val, species="mouse"),
                        } - {None}
                    if expected_set and const[0] not in expected_set:
                        expected_disp = sorted(expected_set)[0] if len(expected_set) == 1 else sorted(expected_set)
                        _lb(idx,
                            f"alpha J→C junction {const[0]!r} disagrees with the "
                            f"germline residue {expected_disp!r} for "
                            f"{str(j_gene_val)!r} — likely a "
                            f"defaulted/misread junction (#242)")

            vdj = row.get(f"vdj_{chain}_aa")
            if (
                isinstance(leader, str) and leader
                and isinstance(vdj, str) and vdj
                and isinstance(const, str) and const
            ):
                expected = leader + vdj + const
                if expected != seq:
                    _lb(idx,
                        f"full_{chain}_aa != leader+vdj+constant "
                        f"(len {len(seq)} vs {len(expected)})")

            c_gene = _resolve_c_gene(row, chain)
            c_gene_base = c_gene.strip().upper().split("*")[0]
            endings_map = CONSTANT_REGION_ENDINGS_BY_SPECIES[row_const_sp]
            if c_gene_base in endings_map:
                expected_end = endings_map[c_gene_base]
                seq_no_stop = seq.rstrip("*")
                if not seq_no_stop.endswith(expected_end):
                    _lb(idx,
                        f"{chain} doesn't end with canonical "
                        f"{c_gene_base} C-terminus ({expected_end!r}); "
                        f"got {seq_no_stop[-len(expected_end):]!r}")
                expected_const = row.get(f"{chain}_constant_aa")
                used_bare_fallback = False
                if not isinstance(expected_const, str) or not expected_const:
                    expected_const = CONSTANT_REGIONS_AA_BY_SPECIES[row_const_sp].get(c_gene_base)
                    used_bare_fallback = True
                if expected_const:
                    obs_start = _expected_constant_start_from_full(seq_no_stop, row, chain)
                    ok_start = verify_canonical_constant_start(
                        obs_start, expected_const, min_match=8
                    ) or (
                        used_bare_fallback
                        and len(obs_start) > 1
                        and verify_canonical_constant_start(
                            obs_start[1:], expected_const, min_match=8
                        )
                    )
                    if not ok_start:
                        _lb(idx,
                            f"{chain} constant start doesn't match canonical "
                            f"{c_gene_base} (expected start "
                            f"{expected_const[:15]!r})")
            else:
                _info(idx,
                    f"{chain} c_gene={c_gene!r} not in "
                    "CONSTANT_REGION_ENDINGS — canonical ending/start unverifiable")

    # 2. β-chain J→C in-cis parity disagreement (#67).
    if "beta_j_gene" in df.columns:
        for idx, row in df.iterrows():
            j_gene = row.get("beta_j_gene", "")
            c_gene = _resolve_c_gene(row, "beta")
            j_family = _beta_j_family(j_gene)
            c_base = _beta_c_base(c_gene)
            expected_c = BETA_JC_PARITY.get(j_family) if j_family else None
            if expected_c and c_base and c_base != expected_c:
                _lb(idx,
                    f"β J→C parity mismatch — "
                    f"{j_gene} (family {j_family}) should pair with "
                    f"{expected_c}, got {c_base}")

    # 3. Single-chain (β-linker-α) construct integrity. Three checks:
    #    a) the linker appears in ``single_chain_aa`` exactly once,
    #    b) ``single_chain_aa == β.rstrip('*') + linker + α`` byte-for-byte
    #       (catches dropped residues or wrong concatenation order),
    #    c) if the linker AA matches a known 2A peptide name, it should
    #       be the canonical sequence from :data:`LINKERS`.
    if "single_chain_aa" in df.columns and "linker" in df.columns:
        for idx, row in df.iterrows():
            sc = row.get("single_chain_aa")
            linker = row.get("linker")
            if not isinstance(sc, str) or not sc:
                continue
            if not isinstance(linker, str) or not linker:
                continue
            count = sc.count(linker)
            if count == 0:
                _lb(idx, f"single_chain_aa missing linker {linker!r}")
            elif count > 1:
                _lb(idx,
                    f"single_chain_aa contains linker "
                    f"{linker!r} {count} times (expected 1)")

            beta = row.get("full_beta_aa")
            alpha = row.get("full_alpha_aa")
            if (
                isinstance(beta, str) and beta
                and isinstance(alpha, str) and alpha
                and count == 1
            ):
                expected_sc = beta.rstrip("*") + linker + alpha
                if sc != expected_sc:
                    _lb(idx,
                        f"single_chain_aa != β+linker+α "
                        f"(len {len(sc)} vs {len(expected_sc)})")

    # 4. NT → AA round-trip invariants (#91). Every NT column the
    # assembler emits must back-translate to its corresponding AA
    # column. This is the integration check that catches splice-time
    # frame bugs — the original #91 (+1 trailing nt in VDJ_*_nt was
    # not trimmed before concatenation, frame-shifting everything
    # past the VDJ→C boundary) would have been caught here on day one.
    _validate_nt_aa_roundtrip(df, _lb)

    # 5. Surface any per-row qc_warnings the assembler stashed. These are
    # *informational, self-corrected* notes (fell back to canonical, allele
    # not called, contig diverged at the C-region boundary, …) — the
    # assembler already handled them and the assembled sequence is valid, so
    # they must NOT be load-bearing (that aborted `tcrsift run` on real
    # CellRanger data, #129). Genuine structural failures are caught by the
    # explicit checks above and remain load-bearing.
    if "qc_warnings" in df.columns:
        for idx, qcs in df["qc_warnings"].items():
            if isinstance(qcs, list):
                for msg in qcs:
                    _info(idx, str(msg))

    all_messages = autocorrect_notes + load_bearing + informational
    if strict and load_bearing:
        raise TCRsiftValidationError(
            f"Sequence validation failed ({len(load_bearing)} load-bearing issues):\n  "
            + "\n  ".join(load_bearing[:10])
            + ("\n  ..." if len(load_bearing) > 10 else "")
        )
    return all_messages

export_fasta

export_fasta(df: DataFrame, output_path: str | Path, sequence_col: str = 'single_chain_aa')

Export sequences to FASTA format.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with sequences

required
output_path str or Path

Output file path

required
sequence_col str

Column containing sequences to export

'single_chain_aa'
Source code in tcrsift/_assemble_qc.py
def export_fasta(df: pd.DataFrame, output_path: str | Path, sequence_col: str = "single_chain_aa"):
    """
    Export sequences to FASTA format.

    Parameters
    ----------
    df : pd.DataFrame
        DataFrame with sequences
    output_path : str or Path
        Output file path
    sequence_col : str
        Column containing sequences to export
    """
    with open(output_path, "w") as f:
        for idx, row in df.iterrows():
            seq = row.get(sequence_col, "")
            if not isinstance(seq, str) or not seq.strip():
                continue

            # Build header
            cdr3ab = row.get("CDR3ab", idx)
            cdr3a = row.get("CDR3_alpha", "")
            cdr3b = row.get("CDR3_beta", "")

            header = f">{cdr3ab} CDR3a={cdr3a} CDR3b={cdr3b}"
            f.write(f"{header}\n{seq}\n")

    logger.info(f"Exported {len(df)} sequences to {output_path}")