tandemox 0.1.0

Pure-Rust tandem repeat finder: indel-tolerant detection of approximate tandem repeats in DNA, validated for concordance against Tandem Repeats Finder (TRF).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
//! Tandem repeat detection — DB-free, pure-Rust, no external tools.
//!
//! Finds approximate tandem repeats (period 1..=500, tolerating both mismatches
//! and indels) in a DNA sequence and returns them as [`TandemRepeat`] records.
//!
//! ```
//! let seq = b"GACTTCAGGATCCGATACGTTAGCACTGATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCCATGACTGACAGT";
//! let repeats = tandemox::detect(seq);
//! assert_eq!(repeats[0].period, 4);
//! ```
//!
//! Tandem Repeats Finder (TRF) is license-restricted, so no code is derived from
//! it. This is an independent implementation built from the published
//! literature — the wraparound alignment of Fischetti, Landau, Schmidt and
//! Sellers (CPM 1992) — and *validated against* TRF's output for concordance.
//!
//! ## Algorithm
//!
//! Detection runs in two stages: a cheap linear scan proposes candidates, and a
//! dynamic-programming alignment adjudicates them.
//!
//! 1. **Seeding** — for each period `p`, walk the "period-`p` diagonal",
//!    comparing `seq[i]` with `seq[i - p]`, scoring `+1` / `-3` and pulling out
//!    maximal-scoring runs (Kadane). This is only a *detector*: it is
//!    deliberately permissive, because an indel shifts the diagonal permanently
//!    and so a gapped repeat only ever shows up here as a partial run. Its job
//!    is to answer "is there any period-`p` structure near here", not to decide
//!    what the repeat is or where it ends.
//!
//! 2. **Refinement** — each seed's ungapped run votes for a consensus motif, and
//!    wraparound DP aligns a generous window around the seed against that motif
//!    repeated end-to-end, under TRF's `2 / -7 / -7` weights. The alignment
//!    supplies everything that gets reported: the true score, the
//!    match/mismatch/indel tallies, and the repeat's boundaries. Indels are
//!    absorbed here, which is what the seeding stage structurally cannot do.
//!
//! 3. **Gating** — a refined candidate must clear the significance floor
//!    (score >= 50, >= ~1.9 copies, >= 80% identity to the consensus), then
//!    greedy overlap dedup keeps one call per region so a repeat is reported at
//!    its fundamental period rather than once per harmonic.
//!
//! Scoring the *whole region* against the consensus — rather than just the
//! `len - p` diagonal pairs — is what puts that score floor on TRF's scale: a
//! perfect repeat of length `L` scores `2L`, matching TRF exactly.
//!
//! Seeding is linear per period and random sequence essentially never sustains a
//! positive run, so the practical cost sits far below the `O(n · 500)` bound.
//! The match-track scan advances a machine word at a time (SWAR), skipping runs
//! of non-matching positions in bulk. Periods are independent, so [`detect`] is
//! single-threaded and composable while [`detect_parallel`] spreads the same
//! work across threads for a single large sequence, with identical output.

mod wdp;

// ---- tunables (TRF `2 7 7 80 10 50 500` defaults) ----------------------------

/// Largest repeat period considered, matching TRF's `MaxPeriod` argument.
const MAX_PERIOD: usize = 500;
/// Shortest reportable repeat region.
const MIN_REGION_LEN: usize = 10;
/// TRF reports repeats down to roughly two copies.
const MIN_COPIES: f64 = 1.9;
/// Lower copies floor, allowed only for high-scoring long repeats (see
/// [`passes_copies`]). TRF's own minimum is ~1.82 copies.
const MIN_COPIES_STRONG: f64 = 1.8;
/// Score a sub-[`MIN_COPIES`] repeat must reach to be kept. Set well above the
/// significance floor so only long, unambiguous arrays qualify.
const STRONG_LOWCOPY_SCORE: f32 = 150.0;
/// Minimum identity between the repeat and its consensus (TRF's `PM = 80`).
const MIN_IDENT: f64 = 0.80;
/// TRF-default significance gate (`Minscore = 50`). Because refinement scores
/// the full region against the consensus, this is directly comparable to the
/// score in TRF's `.dat` output.
const MIN_SCORE: f32 = 50.0;

// ---- seeding tunables --------------------------------------------------------

const SEED_MATCH: i64 = 1;
/// Break-even identity for the seed track sits at 75%, just under [`MIN_IDENT`],
/// so the detector stays slightly more permissive than the final gate.
const SEED_MISMATCH: i64 = -3;
/// Floor on a seed run's score. Low on purpose: seeds only have to notice a
/// repeat, and gapped repeats present as short partial runs. Refinement is what
/// rejects the noise.
const SEED_MIN_SUM: i64 = 8;
/// For long periods the floor scales up (`p / SEED_SUM_PERIOD_DIV`). A genuine
/// long-period repeat still shows a long clean run somewhere, while this keeps
/// random long-period seeds — whose refinement windows are the expensive ones —
/// from ever being proposed.
const SEED_SUM_PERIOD_DIV: i64 = 8;

/// Refinement window margin either side of a seed, as a multiple of the period,
/// letting WDP recover copies the ungapped seed run never reached.
const REFINE_MARGIN_PERIODS: usize = 6;
const REFINE_MARGIN_CONST: usize = 50;

/// How many periods of a seed to poll when voting for its consensus motif.
///
/// Deliberately short, and anchored at a seed's edge rather than spanning it. A
/// seed run is *not* indel-free: a deletion shifts `seq[i]` and `seq[i - p]` by
/// the same amount, so the period-`p` diagonal only breaks for the ~`p`
/// positions where one side has crossed the indel and the other has not, and
/// then recovers — the Kadane run rides straight through. Voting across that
/// span mixes two reading registers and yields a meaningless consensus, so the
/// vote is kept inside a stretch too short to reach an indel. WDP is what spans
/// the indels afterwards.
const CONS_VOTE_PERIODS: usize = 3;

/// Greedy dedup threshold: drop a candidate overlapping a kept one by more than
/// this fraction of the shorter region.
const MAX_OVERLAP_FRAC: f64 = 0.50;

/// When a shorter-period candidate overlaps a kept longer-period one, the
/// shorter (fundamental) period is preferred as long as its score is within this
/// fraction of the kept one's.
///
/// A repeat carrying indels can always be re-described at a longer period that
/// folds each indel into the motif — twelve copies of a 12-mer with one inserted
/// base is also two copies of a 73-mer — and, paying no indel penalty, the
/// longer period scores a little higher. That is not a better explanation, just
/// a coarser one, so within this relative band the fundamental period wins. A
/// genuinely different longer repeat scores far more than a few indel penalties
/// better and stays outside the band, so it is still reported at its own period.
const PERIOD_PREFER_TOL: f32 = 0.15;

/// A single detected tandem repeat on one sequence.
#[derive(Clone, Debug, PartialEq)]
pub struct TandemRepeat {
    /// 1-based inclusive left coordinate on the sequence.
    pub start: usize,
    /// 1-based inclusive right coordinate on the sequence.
    pub end: usize,
    /// Repeat period (motif length) in bp.
    pub period: usize,
    /// Fractional number of copies (`region_len / period`).
    pub copies: f64,
    /// Fractional identity to the consensus, in `0..=1`.
    pub identity: f64,
    /// TRF-comparable alignment score under `2 / -7 / -7` weights.
    pub score: f32,
    /// Consensus (motif) size in bp; equal to `period`.
    pub consensus_size: usize,
}

/// A refined candidate region (0-based, inclusive).
#[derive(Clone, Debug)]
struct Cand {
    start: usize,
    end: usize,
    period: usize,
    ident: f64,
    copies: f64,
    score: f32,
}

impl Cand {
    #[inline]
    fn len(&self) -> usize {
        self.end - self.start + 1
    }
}

#[inline]
pub(crate) fn is_acgt(b: u8) -> bool {
    matches!(b, b'A' | b'C' | b'G' | b'T')
}

/// Case-insensitive base match. Anything non-ACGT (including `N`) never matches,
/// so repeats never bridge ambiguous runs or assembly gaps.
#[inline]
pub(crate) fn base_match(a: u8, b: u8) -> bool {
    let x = a.to_ascii_uppercase();
    x == b.to_ascii_uppercase() && is_acgt(x)
}

/// Per-base code for the non-ACGT sentinel. Kept `>= 4` so it never equals an
/// ACGT code (0..=3) — two ambiguous bases therefore never count as a match —
/// while staying small enough that the `& 0xFC == 0` validity test below holds
/// exactly for ACGT and fails for it.
const NON_ACGT: u8 = 4;

/// Encode a sequence to per-base codes: `A/C/G/T` (any case) → `0..=3`, anything
/// else (including `N`) → [`NON_ACGT`].
///
/// Computed once per sequence so the seeding scan never re-folds case or
/// re-tests ACGT per comparison, and so match tracks can be scanned a machine
/// word at a time (see [`next_match`]).
fn encode(seq: &[u8]) -> Vec<u8> {
    seq.iter()
        .map(|&b| match b & !0x20 {
            // `& !0x20` upper-cases ASCII letters; only A/C/G/T fold onto these.
            b'A' => 0,
            b'C' => 1,
            b'G' => 2,
            b'T' => 3,
            _ => NON_ACGT,
        })
        .collect()
}

// SWAR (SIMD-within-a-register) helpers for scanning a period's match track a
// word at a time. Random DNA matches at ~1/4 of positions, so advancing one
// base per non-match — as a scalar scan must — is where the old seeding spent
// most of its time; these let it skip 8 positions per step.
const SWAR_LOW: u64 = 0x0101010101010101;
const SWAR_HIGH: u64 = 0x8080808080808080;
/// `0xFC` in every byte — masks off the low two bits, so a byte ANDed with this
/// is zero exactly when the original was an ACGT code (`0..=3`).
const SWAR_VALID: u64 = 0xFCFC_FCFC_FCFC_FCFC;

/// Classic "which bytes are zero" test: `0x80` in each byte position of `y` that
/// holds zero, `0x00` elsewhere. Exact, no false marks.
#[inline]
fn zero_byte_mask(y: u64) -> u64 {
    y.wrapping_sub(SWAR_LOW) & !y & SWAR_HIGH
}

/// Read `code[i..i + 8]` as a little-endian word, so byte 0 is `code[i]`.
#[inline]
fn load8(code: &[u8], i: usize) -> u64 {
    let mut a = [0u8; 8];
    a.copy_from_slice(&code[i..i + 8]);
    u64::from_le_bytes(a)
}

/// An ungapped period-`p` run proposed by the seeding scan (0-based, inclusive).
#[derive(Clone, Copy, Debug)]
struct Seed {
    /// Start of the *earlier* copy on the sequence.
    left: usize,
    /// End of the ungapped run on the diagonal (the later copy's last base).
    right: usize,
}

/// Minimum seed run score for period `p`.
#[inline]
fn seed_threshold(p: usize) -> i64 {
    SEED_MIN_SUM.max(p as i64 / SEED_SUM_PERIOD_DIV)
}

/// Copies/score gate. Accepts a repeat with at least [`MIN_COPIES`] copies, or a
/// shorter one (down to [`MIN_COPIES_STRONG`]) only when it is long and scores
/// well past the significance floor.
///
/// The relaxation exists because TRF reports genuine repeats down to ~1.82
/// copies, and the strongest of those — a period-229 array scoring 744, say —
/// are unmistakable. Dropping the copies floor outright, however, lets in a
/// flood of weak ~1.8-copy microsatellites that TRF's probabilistic model
/// rejects, so the relaxation is gated on a high score that only long,
/// well-supported repeats reach.
#[inline]
fn passes_copies(copies: f64, score: f32) -> bool {
    copies >= MIN_COPIES || (copies >= MIN_COPIES_STRONG && score >= STRONG_LOWCOPY_SCORE)
}

/// Smallest `t' >= t` (with `t' < m`) that is a period-`p` diagonal match — i.e.
/// `code[t']` is ACGT and equals `code[p + t']` — or `m` if there is none.
///
/// While a full 8-code window fits on both sides of the diagonal it tests all
/// eight at once: equal codes XOR to a zero byte, and ACGT codes clear under
/// [`SWAR_VALID`], so the byte-zero tests intersect to exactly the matching
/// valid positions. `trailing_zeros` then points at the lowest one.
#[inline]
fn next_match(code: &[u8], p: usize, mut t: usize, m: usize) -> usize {
    let n = code.len();
    while t < m {
        if t + 8 <= m && p + t + 8 <= n {
            let a = load8(code, t);
            let b = load8(code, p + t);
            let hits = zero_byte_mask(a ^ b) & zero_byte_mask(a & SWAR_VALID);
            if hits != 0 {
                return t + (hits.trailing_zeros() as usize / 8);
            }
            t += 8;
        } else {
            if code[t] < NON_ACGT && code[p + t] == code[t] {
                return t;
            }
            t += 1;
        }
    }
    m
}

/// Scan the period-`p` diagonal of the encoded sequence, emitting ungapped runs
/// worth refining. Takes codes from [`encode`] rather than raw bases so the
/// no-match stretches — the bulk of the work — can be skipped a word at a time.
fn scan_period_seeds(code: &[u8], p: usize, out: &mut Vec<Seed>) {
    let n = code.len();
    if p == 0 || p >= n {
        return;
    }
    let thresh = seed_threshold(p);
    // Track index `t` maps to sequence position `p + t`, compared against
    // `code[t]` — the copy one period earlier.
    let m = n - p;
    let mut t = next_match(code, p, 0, m);
    while t < m {
        // Kadane from the matching position: keep the arg-max end, close the run
        // once the running sum goes negative. Runs are intentionally short and
        // local — WDP re-derives the real extent later.
        let mut sum: i64 = 0;
        let mut best_sum: i64 = i64::MIN;
        let mut best_end = t;
        let mut k = t;
        while k < m {
            sum += if code[k] < NON_ACGT && code[p + k] == code[k] {
                SEED_MATCH
            } else {
                SEED_MISMATCH
            };
            if sum > best_sum {
                best_sum = sum;
                best_end = k;
            }
            if sum < 0 {
                break;
            }
            k += 1;
        }

        if best_sum >= thresh {
            out.push(Seed {
                left: t,
                right: p + best_end,
            });
        }
        t = next_match(code, p, best_end + 1, m);
    }
}

/// Turn a seed into a scored candidate via wraparound DP, or reject it.
///
/// The consensus motif is voted from a short stretch at each end of the seed
/// (see [`CONS_VOTE_PERIODS`]) and the two resulting alignments are compared;
/// the higher-scoring one wins. Two anchors are cheap insurance: if one end of
/// the seed happens to sit on a divergent copy, the other usually does not, and
/// for a clean seed both converge on the same motif.
fn refine(seq: &[u8], seed: Seed, p: usize) -> Option<Cand> {
    let n = seq.len();
    let vote_span = CONS_VOTE_PERIODS * p;

    // Window is generous; WDP's local semantics trim it, and a mismatch costing
    // -7 against a match's +2 stops extension through a spacer almost at once.
    let margin = REFINE_MARGIN_PERIODS * p + REFINE_MARGIN_CONST;
    let wstart = seed.left.saturating_sub(margin);
    let wend = (seed.right + margin).min(n - 1);
    let window = &seq[wstart..=wend];

    // Left-anchored and right-anchored consensus votes, each over a short span
    // unlikely to straddle an indel.
    let left_vote = (seed.left, (seed.left + vote_span).min(seed.right));
    let right_vote = (seed.right.saturating_sub(vote_span).max(seed.left), seed.right);

    let mut best: Option<wdp::Aln> = None;
    for (vs, ve) in [left_vote, right_vote] {
        let Some(cons) = wdp::consensus(seq, vs, ve, p) else {
            continue;
        };
        let Some(aln) = wdp::wraparound_local(window, &cons) else {
            continue;
        };
        if best.as_ref().is_none_or(|b| aln.score > b.score) {
            best = Some(aln);
        }
    }
    let aln = best?;

    let start = wstart + aln.start;
    let end = wstart + aln.end;
    let region_len = end - start + 1;
    let copies = region_len as f64 / p as f64;
    let ident = aln.identity();
    let score = aln.score as f32;

    if region_len < MIN_REGION_LEN
        || !passes_copies(copies, score)
        || ident < MIN_IDENT
        || score < MIN_SCORE
    {
        return None;
    }
    Some(Cand {
        start,
        end,
        period: p,
        ident,
        copies,
        score,
    })
}

/// Overlap length (bp) of two inclusive 0-based intervals.
#[inline]
fn overlap_len(a: &Cand, b: &Cand) -> usize {
    let lo = a.start.max(b.start);
    let hi = a.end.min(b.end);
    if hi >= lo {
        hi - lo + 1
    } else {
        0
    }
}

/// True if `c` overlaps `k` by more than [`MAX_OVERLAP_FRAC`] of the shorter.
#[inline]
fn clashes(c: &Cand, k: &Cand) -> bool {
    let ov = overlap_len(c, k);
    ov > 0 && (ov as f64) / (c.len().min(k.len()) as f64) > MAX_OVERLAP_FRAC
}

/// Greedy dedup: keep one call per overlapping region.
///
/// Candidates are processed strongest-first (highest score). A new candidate
/// that clashes with something already kept is normally dropped — except when it
/// has a *smaller* period and scores within [`PERIOD_PREFER_TOL`] of every
/// clasher, in which case it replaces them, so a repeat is reported at its
/// fundamental period rather than a coarser indel-absorbing multiple. The
/// replacement only ever swaps a longer period for an equally-strong shorter
/// one over the same span, so it cannot introduce a region that was not already
/// going to be reported.
fn dedup(mut cands: Vec<Cand>) -> Vec<Cand> {
    cands.sort_by(|a, b| {
        b.score
            .partial_cmp(&a.score)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.period.cmp(&b.period))
            .then(b.len().cmp(&a.len()))
            .then(
                b.ident
                    .partial_cmp(&a.ident)
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
            .then(a.start.cmp(&b.start))
            .then(a.end.cmp(&b.end))
    });

    let mut kept: Vec<Cand> = Vec::new();
    for c in cands {
        let clashers: Vec<usize> = kept
            .iter()
            .enumerate()
            .filter(|(_, k)| clashes(&c, k))
            .map(|(i, _)| i)
            .collect();

        if clashers.is_empty() {
            kept.push(c);
            continue;
        }

        // Take over only if `c` is the more fundamental description of the same
        // region: a smaller period, scoring within tolerance of every clasher.
        // Kept candidates were processed first, so each has score >= c.score.
        let takeover = clashers.iter().all(|&i| {
            let k = &kept[i];
            c.period < k.period && c.score >= k.score * (1.0 - PERIOD_PREFER_TOL)
        });
        if takeover {
            for &i in clashers.iter().rev() {
                kept.remove(i);
            }
            kept.push(c);
        }
    }
    kept
}

/// Seed and refine every period in `periods`, collecting surviving candidates.
/// Periods are independent, so this is the unit of parallel work.
fn collect_cands(seq: &[u8], code: &[u8], periods: impl Iterator<Item = usize>) -> Vec<Cand> {
    let mut cands: Vec<Cand> = Vec::new();
    let mut seeds: Vec<Seed> = Vec::new();
    for p in periods {
        seeds.clear();
        scan_period_seeds(code, p, &mut seeds);
        for &s in seeds.iter() {
            if let Some(c) = refine(seq, s, p) {
                cands.push(c);
            }
        }
    }
    cands
}

/// Assemble the final sorted repeat list from raw candidates.
fn finish(mut cands: Vec<Cand>) -> Vec<TandemRepeat> {
    let mut kept = dedup(std::mem::take(&mut cands));
    kept.sort_by(|a, b| a.start.cmp(&b.start).then(a.end.cmp(&b.end)));
    kept.into_iter()
        .map(|c| TandemRepeat {
            start: c.start + 1, // 1-based inclusive
            end: c.end + 1,
            period: c.period,
            copies: c.copies,
            identity: c.ident,
            score: c.score,
            consensus_size: c.period,
        })
        .collect()
}

/// Detect tandem repeats in one sequence (ASCII ACGTN, mixed case).
///
/// Returns repeats sorted left-to-right, with 1-based inclusive coordinates.
/// Callers with multi-record FASTA loop over contigs themselves. Single-threaded
/// and allocation-light, so it composes cleanly when the caller is already
/// running one sequence per core; for a one-off large sequence see
/// [`detect_parallel`].
pub fn detect(seq: &[u8]) -> Vec<TandemRepeat> {
    let n = seq.len();
    if n < MIN_REGION_LEN {
        return Vec::new();
    }
    let max_p = MAX_PERIOD.min(n / 2);
    let code = encode(seq);
    finish(collect_cands(seq, &code, 1..=max_p))
}

/// Same result as [`detect`], but the per-period work is split across up to
/// `threads` OS threads. Identical output regardless of thread count — the final
/// dedup imposes a total order — so this is purely a latency optimisation for a
/// single large sequence.
///
/// `threads <= 1` runs inline with no threads spawned. Periods are assigned
/// round-robin so the cheap-seed/expensive-refine long periods spread evenly.
/// When processing many sequences, prefer running [`detect`] once per sequence
/// across your own pool over calling this per sequence — that avoids
/// oversubscribing the CPU.
pub fn detect_parallel(seq: &[u8], threads: usize) -> Vec<TandemRepeat> {
    let n = seq.len();
    if n < MIN_REGION_LEN {
        return Vec::new();
    }
    let max_p = MAX_PERIOD.min(n / 2);
    let code = encode(seq);

    let threads = threads.min(max_p);
    if threads <= 1 {
        return finish(collect_cands(seq, &code, 1..=max_p));
    }

    let code = &code;
    let cands: Vec<Cand> = std::thread::scope(|scope| {
        let handles: Vec<_> = (0..threads)
            .map(|tid| {
                scope.spawn(move || {
                    collect_cands(seq, code, (1 + tid..=max_p).step_by(threads))
                })
            })
            .collect();
        handles
            .into_iter()
            .flat_map(|h| h.join().unwrap())
            .collect()
    });
    finish(cands)
}

#[cfg(test)]
mod tests {
    use super::*;

    // Non-repetitive filler used to flank repeats. Hand-checked to contain no
    // homopolymer run >= 3 and no short-period tandem structure.
    const FL_L: &[u8] = b"GACTTCAGGATCCGATACGTTAGCACTG";
    const FL_R: &[u8] = b"CATGACTGACAGTGCACTAGCTAGCTAA";

    /// Repeat of `period` covering `s..=e` (1-based), allowing boundary drift.
    fn covering(reps: &[TandemRepeat], period: usize, s: usize, e: usize, slack: usize) -> bool {
        reps.iter()
            .any(|r| r.period == period && r.start <= s + slack && r.end + slack >= e)
    }

    #[test]
    fn parallel_matches_serial() {
        // detect_parallel must return exactly detect's result at any thread count
        // — the SWAR seeding and threaded period split must not perturb output.
        let mut seq = Vec::new();
        seq.extend_from_slice(FL_L);
        for _ in 0..20 {
            seq.extend_from_slice(b"ACGGTTACGATC"); // period-12 array
        }
        seq.extend_from_slice(FL_R);
        for _ in 0..30 {
            seq.extend_from_slice(b"ATGCA"); // period-5 microsatellite
        }
        seq.extend_from_slice(FL_R);
        let mut rep = Vec::new();
        for _ in 0..12 {
            rep.extend_from_slice(b"GTTATCTTTTCG");
        }
        rep.remove(50); // an indel, exercising the refinement path too
        seq.extend_from_slice(&rep);

        let serial = detect(&seq);
        assert!(!serial.is_empty());
        for threads in [1, 2, 3, 8, 64] {
            assert_eq!(
                detect_parallel(&seq, threads),
                serial,
                "detect_parallel(_, {threads}) diverged from detect"
            );
        }
    }

    #[test]
    fn a_clean_perfect_repeat_period4() {
        let mut seq = Vec::new();
        seq.extend_from_slice(FL_L);
        let rep_start = seq.len();
        for _ in 0..10 {
            seq.extend_from_slice(b"ATGC"); // 40 bp, period 4
        }
        let rep_end = seq.len();
        seq.extend_from_slice(FL_R);

        let reps = detect(&seq);
        let r = reps.iter().find(|r| r.period == 4).expect("period-4 repeat");
        assert!(
            r.start <= rep_start + 1 && r.end >= rep_end,
            "period-4 repeat {}..{} must cover {}..{}",
            r.start,
            r.end,
            rep_start + 1,
            rep_end
        );
        assert_eq!(r.consensus_size, 4);
        // Perfect 40 bp repeat: every base matches the consensus -> 2 * 40.
        assert_eq!(r.score, 80.0);
        assert_eq!(r.identity, 1.0);
    }

    #[test]
    fn b_homopolymer_period1() {
        // 30 A's: a perfect period-1 run scoring 2 * 30 = 60 >= MIN_SCORE.
        let seq = b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
        let reps = detect(seq);
        assert_eq!(reps.len(), 1, "one homopolymer repeat");
        let r = &reps[0];
        assert_eq!(r.period, 1);
        assert_eq!(r.start, 1);
        assert_eq!(r.end, 30);
    }

    #[test]
    fn b2_trivial_short_repeat_filtered() {
        // A 10 bp homopolymer scores 20, below the TRF significance gate.
        assert!(
            detect(b"AAAAAAAAAA").is_empty(),
            "trivial 10bp microsatellite must be filtered by MIN_SCORE"
        );
    }

    #[test]
    fn c_no_repeats_empty() {
        let seq = b"GACTTCAGGATCCGATACGTTAGCACTGCATGACAGTCAGTGCTAGACT";
        let reps = detect(seq);
        assert!(
            reps.is_empty(),
            "non-repetitive sequence must yield no repeats, got {:?}",
            reps.iter()
                .map(|r| (r.period, r.start, r.end))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn d_imperfect_repeat_still_detected() {
        // "ATGC" x 14 with two point mutations.
        let mut rep = Vec::new();
        for _ in 0..14 {
            rep.extend_from_slice(b"ATGC");
        }
        rep[10] = b'A';
        rep[22] = b'T';

        let mut seq = Vec::new();
        seq.extend_from_slice(FL_L);
        let rep_start = seq.len();
        seq.extend_from_slice(&rep);
        let rep_end = seq.len();
        seq.extend_from_slice(FL_R);

        let reps = detect(&seq);
        assert!(
            covering(&reps, 4, rep_start + 1, rep_end, 6),
            "imperfect period-4 repeat must still be detected, got {:?}",
            reps.iter()
                .map(|r| (r.period, r.start, r.end))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn e_two_separate_regions() {
        // (ATGC)x8, a non-repetitive spacer, then (CTA)x12. Period 3 is coprime
        // with 4, so neither region's track can bridge the spacer into the other.
        let mut seq = Vec::new();
        let a_start = seq.len();
        for _ in 0..8 {
            seq.extend_from_slice(b"ATGC");
        }
        seq.extend_from_slice(b"CAGTCAGACTGACAGT");
        let b_start = seq.len();
        for _ in 0..12 {
            seq.extend_from_slice(b"CTA");
        }

        let reps = detect(&seq);
        assert_eq!(
            reps.len(),
            2,
            "two separate repeat regions: {:?}",
            reps.iter()
                .map(|r| (r.period, r.start, r.end))
                .collect::<Vec<_>>()
        );
        assert_eq!(reps[0].period, 4, "first region period 4");
        assert_eq!(reps[1].period, 3, "second region period 3");
        assert!(reps[0].start <= a_start + 1);
        assert!(reps[1].start <= b_start + 1 && reps[1].end >= b_start + 20);
    }

    #[test]
    fn f_mixed_case_and_n_handling() {
        let mut seq = Vec::new();
        seq.extend_from_slice(FL_L);
        for _ in 0..10 {
            seq.extend_from_slice(b"atgc"); // lower-case period-4 repeat
        }
        seq.extend_from_slice(FL_R);
        seq.extend_from_slice(b"NNNNNNNNNNNNNNNN");

        let reps = detect(&seq);
        assert!(
            reps.iter().any(|r| r.period == 4),
            "lower-case repeat detected"
        );
        let n_start = seq.len() - 16 + 1;
        assert!(
            !reps.iter().any(|r| r.start >= n_start),
            "N run must not be reported as a tandem repeat"
        );
    }

    // ---- indel-bearing repeats: the cases the ungapped scan cannot reach -----

    #[test]
    fn g_repeat_with_deletion_is_detected() {
        // 12 copies of a 12-mer with one base deleted in the middle. The
        // deletion shifts the period-12 diagonal permanently, so an ungapped
        // scan sees two shorter repeats at best; WDP spans the whole thing.
        let mut rep = Vec::new();
        for _ in 0..12 {
            rep.extend_from_slice(b"GTTATCTTTTCG");
        }
        rep.remove(72); // delete one base mid-repeat

        let mut seq = Vec::new();
        seq.extend_from_slice(FL_L);
        let rep_start = seq.len();
        seq.extend_from_slice(&rep);
        let rep_end = seq.len();
        seq.extend_from_slice(FL_R);

        let reps = detect(&seq);
        assert!(
            covering(&reps, 12, rep_start + 1, rep_end, 13),
            "period-12 repeat with a deletion must be detected end-to-end, got {:?}",
            reps.iter()
                .map(|r| (r.period, r.start, r.end, r.copies))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn h_repeat_with_insertion_is_detected() {
        let mut rep = Vec::new();
        for _ in 0..12 {
            rep.extend_from_slice(b"GTTATCTTTTCG");
        }
        rep.insert(72, b'A'); // insert one base mid-repeat

        let mut seq = Vec::new();
        seq.extend_from_slice(FL_L);
        let rep_start = seq.len();
        seq.extend_from_slice(&rep);
        let rep_end = seq.len();
        seq.extend_from_slice(FL_R);

        let reps = detect(&seq);
        assert!(
            covering(&reps, 12, rep_start + 1, rep_end, 13),
            "period-12 repeat with an insertion must be detected end-to-end, got {:?}",
            reps.iter()
                .map(|r| (r.period, r.start, r.end, r.copies))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn i_repeat_with_multiple_indels() {
        // Three separate indels across the repeat — the diagonal is broken
        // repeatedly, and each break is bridged independently by the alignment.
        let mut rep = Vec::new();
        for _ in 0..16 {
            rep.extend_from_slice(b"ACGGTTACGATC");
        }
        rep.remove(150);
        rep.insert(100, b'T');
        rep.remove(50);

        let mut seq = Vec::new();
        seq.extend_from_slice(FL_L);
        let rep_start = seq.len();
        seq.extend_from_slice(&rep);
        let rep_end = seq.len();
        seq.extend_from_slice(FL_R);

        let reps = detect(&seq);
        assert!(
            covering(&reps, 12, rep_start + 1, rep_end, 15),
            "period-12 repeat with 3 indels must be detected, got {:?}",
            reps.iter()
                .map(|r| (r.period, r.start, r.end, r.copies))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn j_two_copy_repeat_at_trf_score_boundary() {
        // The exact shape the old `len - p` scoring dropped: ~2 copies of a
        // 12-mer, 25 bp, perfect. TRF scores this 50 and reports it; scoring
        // only the 13 diagonal pairs gives 26 and silently loses it.
        let mut seq = Vec::new();
        seq.extend_from_slice(FL_L);
        let rep_start = seq.len();
        seq.extend_from_slice(b"GTTATCTTTTTTGTTATCTTTTTTG"); // 25 bp
        let rep_end = seq.len();
        seq.extend_from_slice(FL_R);

        let reps = detect(&seq);
        let r = reps
            .iter()
            .find(|r| r.period == 12 && r.start <= rep_start + 2)
            .unwrap_or_else(|| {
                panic!(
                    "2-copy period-12 repeat must clear MIN_SCORE, got {:?}",
                    reps.iter()
                        .map(|r| (r.period, r.start, r.end, r.score))
                        .collect::<Vec<_>>()
                )
            });
        assert_eq!(r.score, 50.0, "score must match TRF's 2*L convention");
        assert_eq!(r.end, rep_end);
    }

    #[test]
    fn k_identity_and_copies_are_sane() {
        let mut seq = Vec::new();
        seq.extend_from_slice(FL_L);
        for _ in 0..10 {
            seq.extend_from_slice(b"ATGCAG"); // 60 bp, period 6
        }
        seq.extend_from_slice(FL_R);

        let reps = detect(&seq);
        let r = reps.iter().find(|r| r.period == 6).expect("period-6 repeat");
        assert_eq!(r.identity, 1.0);
        assert!((r.copies - 10.0).abs() < 0.2, "copies ~10, got {}", r.copies);
        assert_eq!(r.consensus_size, 6);
    }
}