Skip to main content

rust_ise/
lib.rs

1// rust-ise — Rust-native ISEScan-equivalent IS-element scanner.
2// Pipeline: rustygal META gene-finding (LINKED LIBRARY, == pyrodigal) + strand-aware edge recovery
3//   -> mmseqs2 profile search (system `mmseqs` on PATH; same union DB/params as the Python reference pv2)
4//   -> 4-tier family call -> native affine Smith-Waterman-Gotoh TIR -> c/p -> dedup -> TSV/GFF/.sum.
5// Coordinates 1-based inclusive. mmseqs2 is the one external engine (call system binary); the IS DB is
6// external data resolved via --db / $ISSCAN_DB (not bundled in the crate).
7use rayon::prelude::*;
8use std::cell::RefCell;
9use std::collections::HashMap;
10use std::fs;
11use std::io::{BufRead, BufReader, Write, BufWriter};
12use std::path::{Path, PathBuf};
13use std::process::Command;
14
15// Compile-time perfect-hash map `REP_THRESHOLDS: phf::Map<&str, f32>` (rep -> min pident to accept a
16// hit to that profile), GTDB-calibrated, generated by build.rs from data/rep_thresholds.tsv.
17include!(concat!(env!("OUT_DIR"), "/rep_thresholds.rs"));
18
19// ---- family-call thresholds (tuned, == v2) ----
20const SIG_EVALUE: f64 = 1e-10;
21const LIKE_EVALUE: f64 = 1e-30;
22const LIKE_QCOV: f64 = 0.7;
23const LIKE_SPAN_OVERLAP: f64 = 0.5;
24const NOVEL_PIDENT: f64 = 30.0;
25// ---- TIR / flank params (== constants_isscan.py) ----
26const MAX_DIST: i64 = 500;
27const MIN_DIST_ABS: i64 = 150; // abs(minDist4ter2orf = -150)
28const SW_MATCH: i32 = 2;
29const SW_MISMATCH: i32 = -6;
30// affine gap (Gotoh, parasail convention: a length-g gap costs OPEN + EXTEND*(g-1)).
31// constants_isscan filters4ssw4trial = (match2, mismatch6, gap_open2, gap_extend2).
32const SW_OPEN: i32 = 2;
33const SW_EXTEND: i32 = 2;
34
35// ---------------------------------------------------------- sequence utils
36fn revcomp(s: &[u8]) -> Vec<u8> {
37    s.iter().rev().map(|&c| match c {
38        b'A' => b'T', b'T' => b'A', b'G' => b'C', b'C' => b'G',
39        b'a' => b't', b't' => b'a', b'g' => b'c', b'c' => b'g',
40        b'N' => b'N', b'n' => b'n', _ => b'N',
41    }).collect()
42}
43
44fn norm_fam(f: &str) -> String {
45    f.replace('/', "").replace('_', "").to_uppercase()
46}
47
48// standard genetic code (== v2 _CODON), index by 3 uppercase bases
49fn translate(s: &[u8]) -> Vec<u8> {
50    const TBL: &[u8] = b"FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG";
51    let code = |c: u8| -> i32 { match c { b'T'=>0, b'C'=>1, b'A'=>2, b'G'=>3, _=>-1 } };
52    let mut out = Vec::with_capacity(s.len()/3);
53    let mut i = 0;
54    while i + 3 <= s.len() {
55        let (a,b,c) = (code(s[i]), code(s[i+1]), code(s[i+2]));
56        if a<0 || b<0 || c<0 { out.push(b'X'); }
57        else { out.push(TBL[(a*16+b*4+c) as usize]); }
58        i += 3;
59    }
60    out
61}
62
63fn read_fasta(path: &str) -> Vec<(String, Vec<u8>)> {
64    let f = BufReader::new(fs::File::open(path).expect("open fasta"));
65    let mut out: Vec<(String, Vec<u8>)> = Vec::new();
66    let mut name: Option<String> = None;
67    let mut buf: Vec<u8> = Vec::new();
68    for line in f.lines() {
69        let line = line.unwrap();
70        if let Some(rest) = line.strip_prefix('>') {
71            if let Some(n) = name.take() { out.push((n, std::mem::take(&mut buf))); }
72            name = Some(rest.split_whitespace().next().unwrap_or("").to_string());
73        } else {
74            buf.extend(line.trim().bytes().map(|c| c.to_ascii_uppercase()));
75        }
76    }
77    if let Some(n) = name.take() { out.push((n, buf)); }
78    out
79}
80
81// ---------------------------------------------------------- 1. ORFs (rustygal + edge)
82struct Orf { begin: i64, end: i64, strand: char, prot: Vec<u8>, edge: bool }
83
84// Parse rustygal -a FASTA bytes: header ">{contig}_{geneidx} # b # e # strand # ID=..." , seq = protein.
85// (rv2 gets these bytes from the rustygal LIBRARY `run_meta`, not a file — same format as the binary's -a.)
86// Returns contig -> Vec<Orf> (pyrodigal-equivalent genes only; edge added later).
87fn parse_rustygal_faa(data: &[u8]) -> HashMap<String, Vec<Orf>> {
88    let mut map: HashMap<String, Vec<Orf>> = HashMap::new();
89    let mut cur: Option<(String, i64, i64, char)> = None;
90    let mut seq: Vec<u8> = Vec::new();
91    let flush = |map: &mut HashMap<String, Vec<Orf>>,
92                 cur: &Option<(String,i64,i64,char)>, seq: &mut Vec<u8>| {
93        if let Some((ctg, b, e, st)) = cur {
94            // strip trailing '*' to match v2 g.translate().rstrip("*")
95            while seq.last() == Some(&b'*') { seq.pop(); }
96            map.entry(ctg.clone()).or_default().push(Orf {
97                begin: *b, end: *e, strand: *st, prot: std::mem::take(seq), edge: false });
98        } else { seq.clear(); }
99    };
100    for raw in data.split(|&c| c == b'\n') {
101        let line = String::from_utf8_lossy(raw);
102        let line = line.trim_end_matches('\r');
103        if let Some(rest) = line.strip_prefix('>') {
104            flush(&mut map, &cur, &mut seq);
105            // rest: "{contig}_{geneidx} # b # e # strand # ID=..."
106            let first = rest.split_whitespace().next().unwrap();
107            let parts: Vec<&str> = rest.split('#').collect();
108            let b: i64 = parts[1].trim().parse().unwrap();
109            let e: i64 = parts[2].trim().parse().unwrap();
110            let strand = if parts[3].trim() == "1" { '+' } else { '-' };
111            // contig = first token minus the trailing "_{geneidx}"
112            let contig = match first.rfind('_') { Some(i) => &first[..i], None => first };
113            cur = Some((contig.to_string(), b, e, strand));
114        } else {
115            seq.extend(line.trim().bytes());
116        }
117    }
118    flush(&mut map, &cur, &mut seq);
119    map
120}
121
122// strand-aware edge recovery for one contig (== v2 _orf_one edge part).
123fn edge_orfs(seq: &[u8], pyr: &[Orf], minaa: usize, edge: i64) -> Vec<Orf> {
124    let l = seq.len() as i64;
125    let mut out = Vec::new();
126    for &strand in &['+', '-'] {
127        let s = if strand == '+' { seq.to_vec() } else { revcomp(seq) };
128        for frame in 0..3usize {
129            let prot = translate(&s[frame.min(s.len())..]);
130            // maximal non-stop stretches [a0,a1) (a1 exclusive)
131            let mut start = 0usize;
132            let mut stretches: Vec<(usize, usize)> = Vec::new();
133            for (k, &aa) in prot.iter().enumerate() {
134                if aa == b'*' { if k > start { stretches.push((start, k)); } start = k + 1; }
135            }
136            if start < prot.len() { stretches.push((start, prot.len())); }
137            for (a0, a1) in stretches {
138                if a1 - a0 < minaa { continue; }
139                let ns = frame as i64 + a0 as i64 * 3;
140                let ne = frame as i64 + a1 as i64 * 3;
141                if !(ns <= edge || ne >= l - edge) { continue; }
142                let (cb, ce) = if strand == '+' { (ns + 1, ne) } else { (l - ne + 1, l - ns) };
143                let suppressed = pyr.iter().any(|p| p.strand == strand
144                    && (ce.min(p.end) - cb.max(p.begin)) as f64 >= 0.5 * (ce - cb) as f64);
145                if suppressed { continue; }
146                out.push(Orf { begin: cb, end: ce, strand, prot: prot[a0..a1].to_vec(), edge: true });
147            }
148        }
149    }
150    out
151}
152
153// ---------------------------------------------------------- 2. mmseqs search
154#[derive(Clone)]
155struct Hit { fam: String, evalue: f64, qcov: f64, pident: f64, tstart: i64, tend: i64 }
156
157fn mmseqs_search(proteome: &Path, db_dir: &Path, tmp: &Path, nthread: usize, gpu: bool)
158    -> HashMap<String, Vec<Hit>> {
159    let profile_db = db_dir.join("mmdb_union").join("profileDb");
160    let manifest = db_dir.join("manifest_union.tsv");
161    let run = |args: &[&str]| {
162        let st = Command::new("mmseqs").args(args)
163            .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null())
164            .status().expect("spawn mmseqs");
165        assert!(st.success(), "mmseqs {:?} failed", &args[0]);
166    };
167    let qdb = tmp.join("qdb");
168    run(&["createdb", proteome.to_str().unwrap(), qdb.to_str().unwrap(), "-v", "0"]);
169    // cid -> family and cid -> rep (rep is the stable key for the embedded per-profile threshold)
170    let mut cid2fam: HashMap<String, String> = HashMap::new();
171    let mut cid2rep: HashMap<String, String> = HashMap::new();
172    for line in BufReader::new(fs::File::open(&manifest).unwrap()).lines() {
173        let line = line.unwrap();
174        let p: Vec<&str> = line.split('\t').collect();
175        if p.len() >= 2 && p[0] != "cid" { cid2fam.insert(p[0].to_string(), p[1].to_string()); }
176        if p.len() >= 4 && p[0] != "cid" { cid2rep.insert(p[0].to_string(), p[3].to_string()); }
177    }
178    let res = tmp.join("pres");
179    let aln = tmp.join("pres.tsv");
180    let tp = tmp.join("tp");
181    let nt = nthread.to_string();
182    let mut search_args: Vec<&str> = vec!["search", profile_db.to_str().unwrap(),
183        qdb.to_str().unwrap(), res.to_str().unwrap(), tp.to_str().unwrap(),
184        "-s", "7.5", "-e", "10", "--threads", &nt, "-v", "0"];
185    if gpu { search_args.push("--gpu"); search_args.push("1"); }
186    run(&search_args);
187    run(&["convertalis", profile_db.to_str().unwrap(), qdb.to_str().unwrap(),
188        res.to_str().unwrap(), aln.to_str().unwrap(),
189        "--format-output", "query,target,evalue,qcov,pident,tstart,tend", "-v", "0"]);
190    let mut hits: HashMap<String, Vec<Hit>> = HashMap::new();
191    for line in BufReader::new(fs::File::open(&aln).unwrap()).lines() {
192        let line = line.unwrap();
193        let p: Vec<&str> = line.split('\t').collect();
194        if p.len() < 7 { continue; }
195        let pident: f64 = p[4].parse().unwrap_or(0.0);
196        // per-profile pident gate (GTDB-calibrated, rep-keyed): drop hits to a contaminant /
197        // promiscuous profile when their identity is below the profile's threshold. Absent rep =>
198        // threshold 0 => accept. This runs before family_call so a gated hit cannot win the ORF.
199        if let Some(rep) = cid2rep.get(p[0]) {
200            let thr = REP_THRESHOLDS.get(rep.as_str()).copied().unwrap_or(0.0) as f64;
201            if pident < thr { continue; }
202        }
203        if let Some(fam) = cid2fam.get(p[0]) {
204            hits.entry(p[1].to_string()).or_default().push(Hit {
205                fam: fam.clone(),
206                evalue: p[2].parse().unwrap_or(1.0),
207                qcov: p[3].parse().unwrap_or(0.0),
208                pident,
209                tstart: p[5].parse().unwrap_or(0),
210                tend: p[6].parse().unwrap_or(0),
211            });
212        }
213    }
214    hits
215}
216
217// ---------------------------------------------------------- 3. family call (4-tier)
218// Total order on hits => representative selection is deterministic regardless of the
219// (run-to-run varying) mmseqs hit order. evalue asc, then pident/qcov desc, then
220// tstart/tend asc, then family — fully canonical so equal-E ties never flip the output.
221fn cmp_hit(a: &Hit, b: &Hit) -> std::cmp::Ordering {
222    a.evalue.partial_cmp(&b.evalue).unwrap()
223        .then(b.pident.partial_cmp(&a.pident).unwrap())
224        .then(b.qcov.partial_cmp(&a.qcov).unwrap())
225        .then(a.tstart.cmp(&b.tstart))
226        .then(a.tend.cmp(&b.tend))
227        .then_with(|| a.fam.cmp(&b.fam))
228}
229
230// returns (label, tier, best_hit) ; tier in {plain,like,chimera,novel}
231fn family_call(orfhits: &[Hit]) -> Option<(String, String, Hit)> {
232    if orfhits.is_empty() { return None; }
233    let mut perfam: HashMap<String, Hit> = HashMap::new();
234    for h in orfhits {
235        let nf = norm_fam(&h.fam);
236        match perfam.get(&nf) {
237            Some(cur) if cmp_hit(cur, h) != std::cmp::Ordering::Greater => {}
238            _ => { perfam.insert(nf, h.clone()); }
239        }
240    }
241    let mut ranked: Vec<Hit> = perfam.into_values().collect();
242    ranked.sort_by(cmp_hit);
243    let top = ranked[0].clone();
244    if top.evalue > SIG_EVALUE { return None; }
245    if top.pident < NOVEL_PIDENT { return Some(("novel".to_string(), "novel".to_string(), top)); }
246    // competitor: best DIFFERENT family, strong + good coverage
247    let comp = ranked[1..].iter().find(|x|
248        norm_fam(&x.fam) != norm_fam(&top.fam) && x.evalue <= LIKE_EVALUE && x.qcov >= LIKE_QCOV);
249    match comp {
250        None => Some((top.fam.clone(), "plain".to_string(), top)),
251        Some(c) => {
252            let ov = top.tend.min(c.tend) - top.tstart.max(c.tstart);
253            let span = ((top.tend - top.tstart).min(c.tend - c.tstart)).max(1);
254            if ov > 0 && ov as f64 >= LIKE_SPAN_OVERLAP * span as f64 {
255                Some((format!("{}-like", top.fam), "like".to_string(), top))
256            } else {
257                Some((format!("{}-chimera", top.fam), "chimera".to_string(), top))
258            }
259        }
260    }
261}
262
263// ---------------------------------------------------------- 4. TIR (native SW) + c/p
264#[derive(Clone)]
265pub struct Tir { pub irid: i64, pub irlen: i64, pub start1: i64, pub end1: i64, pub start2: i64, pub end2: i64,
266             pub seq1: Vec<u8>, pub seq2: Vec<u8> }
267
268#[derive(Default)]
269struct SwBuf {
270    ph: Vec<i32>, ch: Vec<i32>,   // H rows (prev / cur)
271    pf: Vec<i32>, cf: Vec<i32>,   // F rows (prev / cur) — vertical-gap matrix
272    hp: Vec<u8>, ep: Vec<u8>, fp: Vec<u8>,  // traceback pointer matrices
273}
274thread_local! {
275    // Reused across every TIR alignment on this worker thread → no per-call heap allocation.
276    // Buffers only grow to the largest flank seen so far.
277    static SW_SCRATCH: RefCell<SwBuf> = RefCell::new(SwBuf::default());
278}
279
280// Local Smith-Waterman-Gotoh with AFFINE gaps (parasail convention: a length-g gap costs
281// SW_OPEN + SW_EXTEND*(g-1)). Two gap matrices: E = horizontal (gap in query / consume ref),
282// F = vertical (gap in ref / consume query). When SW_OPEN==SW_EXTEND this is numerically
283// identical to the linear case. Returns (score, beg_q, end_q, beg_r, end_r) 0-based inclusive.
284fn sw_local(q: &[u8], r: &[u8]) -> Option<(i32, usize, usize, usize, usize)> {
285    let (n, m) = (q.len(), r.len());
286    if n == 0 || m == 0 { return None; }
287    const NEG: i32 = i32::MIN / 4;   // -inf for gap-matrix init (no overflow on -EXTEND)
288    SW_SCRATCH.with(|cell| {
289        let mut s = cell.borrow_mut();
290        let b = &mut *s;             // deref RefMut once so field borrows are provably disjoint
291        let stride = m + 1;
292        if b.ph.len() < stride {
293            b.ph.resize(stride, 0); b.ch.resize(stride, 0);
294            b.pf.resize(stride, 0); b.cf.resize(stride, 0);
295        }
296        let need = (n + 1) * stride;
297        if b.hp.len() < need { b.hp.resize(need, 0); b.ep.resize(need, 0); b.fp.resize(need, 0); }
298        let (ph, ch, pf, cf) = (&mut b.ph, &mut b.ch, &mut b.pf, &mut b.cf);
299        let (hp, ep, fp) = (&mut b.hp, &mut b.ep, &mut b.fp);
300        // row 0: H=0, F=-inf
301        for x in ph[..stride].iter_mut() { *x = 0; }
302        for x in pf[..stride].iter_mut() { *x = NEG; }
303        let (mut best, mut bi, mut bj) = (0i32, 0usize, 0usize);
304        for i in 1..=n {
305            ch[0] = 0; cf[0] = NEG;
306            let mut e_prev = NEG;        // E[i][0] = -inf
307            let qi = q[i-1];
308            let row = i * stride;
309            for j in 1..=m {
310                let sc = if qi == r[j-1] && matches!(qi, b'A'|b'C'|b'G'|b'T')
311                        { SW_MATCH } else { SW_MISMATCH };
312                // E[i][j] (horizontal): open from H[i][j-1] or extend from E[i][j-1]
313                let e_open = ch[j-1] - SW_OPEN;
314                let e_ext  = e_prev - SW_EXTEND;
315                let (e_val, e_code) = if e_ext > e_open { (e_ext, 1u8) } else { (e_open, 0u8) };
316                // F[i][j] (vertical): open from H[i-1][j] or extend from F[i-1][j]
317                let f_open = ph[j] - SW_OPEN;
318                let f_ext  = pf[j] - SW_EXTEND;
319                let (f_val, f_code) = if f_ext > f_open { (f_ext, 1u8) } else { (f_open, 0u8) };
320                // H[i][j]; tie-break order diag > F(up) > E(left) (matches the old linear order)
321                let diag = ph[j-1] + sc;
322                let mut h = 0i32; let mut hc = 0u8;
323                if diag > h { h = diag; hc = 1; }
324                if f_val > h { h = f_val; hc = 3; }
325                if e_val > h { h = e_val; hc = 2; }
326                ch[j] = h; cf[j] = f_val; e_prev = e_val;
327                hp[row + j] = hc; ep[row + j] = e_code; fp[row + j] = f_code;
328                // tie-break: keep LAST max cell (>=) — closer to parasail's striped traceback
329                if h >= best && h > 0 { best = h; bi = i; bj = j; }
330            }
331            std::mem::swap(ph, ch);
332            std::mem::swap(pf, cf);
333        }
334        if best <= 0 { return None; }
335        // 3-state traceback to the origin (where H came from 0). state: 0=H, 1=E, 2=F.
336        let (mut i, mut j, mut state) = (bi, bj, 0u8);
337        loop {
338            match state {
339                0 => match hp[i*stride + j] {
340                    0 => break,                       // origin
341                    1 => { i -= 1; j -= 1; }          // diagonal
342                    2 => state = 1,                   // enter horizontal gap (E)
343                    _ => state = 2,                   // enter vertical gap (F)
344                },
345                1 => { let ext = ep[i*stride + j] == 1; j -= 1; if !ext { state = 0; } }
346                _ => { let ext = fp[i*stride + j] == 1; i -= 1; if !ext { state = 0; } }
347            }
348            if i == 0 || j == 0 { break; }
349        }
350        Some((best, i, bi - 1, j, bj - 1))
351    })
352}
353
354fn find_tir(contig: &[u8], orf_b: i64, orf_e: i64, family: &str,
355            tir_tbl: &HashMap<String,(i64,i64,i64,i64)>) -> Option<Tir> {
356    let fam = family.split('-').next().unwrap();
357    let info = lookup(tir_tbl, fam);
358    if let Some(t) = info { if t.3 == 0 { return None; } }
359    let min_ir = info.map(|t| t.0).unwrap_or(4);
360    if min_ir > 1000 { return None; }
361    let l = contig.len() as i64;
362    let lb = (orf_b - MAX_DIST).max(1);
363    let le = (orf_b + MIN_DIST_ABS).min(l);
364    let rb = (orf_e - MIN_DIST_ABS).max(1);
365    let re = (orf_e + MAX_DIST).min(l);
366    if le < lb || re < rb { return None; }
367    let left = &contig[(lb-1) as usize..le as usize];
368    let right = &contig[(rb-1) as usize..re as usize];
369    if (left.len() as i64) < min_ir || (right.len() as i64) < min_ir { return None; }
370    let rrc = revcomp(right);
371    let (score, qs, qe, ts, te) = sw_local(left, &rrc)?;
372    if score < (2 * min_ir) as i32 { return None; }
373    let ir_len = qe as i64 - qs as i64 + 1;
374    if ir_len < min_ir { return None; }
375    let seq1 = left[qs..=qe].to_vec();
376    let r_local_end = right.len() - 1 - ts;
377    let r_local_beg = right.len() - 1 - te;
378    let start1 = lb + qs as i64; let end1 = lb + qe as i64;
379    let start2 = rb + r_local_beg as i64; let end2 = rb + r_local_end as i64;
380    let seq2 = right[r_local_beg..=r_local_end].to_vec();
381    let seq2rc = revcomp(&seq2);
382    let ir_id = seq1.iter().zip(seq2rc.iter()).filter(|(a, b)| a == b).count() as i64;
383    if ir_len == 0 || (ir_id as f64) / (ir_len as f64) < 0.5 { return None; }
384    Some(Tir { irid: ir_id, irlen: ir_len, start1, end1, start2, end2, seq1, seq2 })
385}
386
387// O(1): tables are built with normalized keys, so a direct get on norm_fam(fam) suffices.
388fn lookup<'a>(tbl: &'a HashMap<String,(i64,i64,i64,i64)>, fam: &str) -> Option<&'a (i64,i64,i64,i64)> {
389    tbl.get(&norm_fam(fam))
390}
391
392// returns (isBegin, isEnd, type c/p)
393fn classify_is(label: &str, b: i64, e: i64, tir: &Option<Tir>,
394               tir_tbl: &HashMap<String,(i64,i64,i64,i64)>,
395               tpase_tbl: &HashMap<String,(i64,i64,i64)>) -> (i64, i64, char) {
396    let fam = label.split('-').next().unwrap();
397    if let Some(t) = tir {
398        return (t.start1.min(t.start2), t.end1.max(t.end2), 'c');
399    }
400    let info = lookup(tir_tbl, fam);
401    let has_tir = info.map(|t| t.3).unwrap_or(-1);
402    let lenb = tpase_tbl.get(&norm_fam(fam)).copied();
403    let orflen = e - b + 1;
404    if has_tir == 0 {
405        if let Some((lo, hi, _)) = lenb {
406            if lo <= orflen && orflen <= hi { return (b, e, 'c'); }
407        }
408    }
409    (b, e, 'p')
410}
411
412// ---------------------------------------------------------- 5. assembly
413#[derive(Clone)]
414pub struct Call {
415    pub seqid: String, pub family: String, pub tier: String, pub is_begin: i64, pub is_end: i64, pub is_len: i64,
416    pub orf_begin: i64, pub orf_end: i64, pub strand: char, pub evalue: f64, pub qcov: f64, pub pident: f64,
417    pub typ: char, pub tir: Option<Tir>, pub ncopy: i64,
418    // (C) nt neg-pos FP-control verdict (which lineage the call nt resembles): IS | shared | host | unresolved
419    pub fp_flag: String,
420}
421
422fn dedup(mut calls: Vec<Call>, min_overlap: f64) -> Vec<Call> {
423    let mut by_contig: HashMap<String, Vec<Call>> = HashMap::new();
424    for c in calls.drain(..) { by_contig.entry(c.seqid.clone()).or_default().push(c); }
425    let mut kept: Vec<Call> = Vec::new();
426    for (_, mut cs) in by_contig {
427        // total order: best-E first, then canonical (orfBegin,orfEnd,strand) so the greedy
428        // keep is deterministic even when two overlapping ORFs tie on E-value.
429        cs.sort_by(|a, b| a.evalue.partial_cmp(&b.evalue).unwrap()
430            .then(a.orf_begin.cmp(&b.orf_begin))
431            .then(a.orf_end.cmp(&b.orf_end))
432            .then(a.strand.cmp(&b.strand)));
433        let mut acc: Vec<Call> = Vec::new();
434        for c in cs {
435            let (cb, ce) = (c.orf_begin, c.orf_end);
436            let clash = acc.iter().any(|a| {
437                let ov = ce.min(a.orf_end) - cb.max(a.orf_begin);
438                ov > 0 && ov as f64 >= min_overlap * ((ce - cb).min(a.orf_end - a.orf_begin)) as f64
439            });
440            if !clash { acc.push(c); }
441        }
442        kept.extend(acc);
443    }
444    kept
445}
446
447// Merge adjacent co-oriented same-family ORF calls into ONE IS element. Two-ORF IS families
448// (IS3/IS1/IS21/IS66 ...) encode their transposase as orfA + orfB on the same strand, joined by a
449// programmed -1 frameshift; the two ORFs are immediately consecutive (small gap or slight overlap).
450// dedup() only collapses ORFs that OVERLAP by >=min_overlap, so these adjacent pairs survive as two
451// calls => the IS is double-counted. ISEScan reports such a pair as a single element. We chain
452// consecutive calls of the same normalized family + same strand whose gap <= `gap` bp, then re-derive
453// the IS boundary (TIR re-searched over the merged span) and c/p from the merged span; family/E-value/
454// identity are taken from the strongest hit in the chain. Singletons pass through unchanged.
455fn merge_adjacent(calls: Vec<Call>, gap: i64, contig_map: &HashMap<&str, &Vec<u8>>,
456                  tir_tbl: &HashMap<String,(i64,i64,i64,i64)>,
457                  tpase_tbl: &HashMap<String,(i64,i64,i64)>) -> Vec<Call> {
458    let mut by_contig: HashMap<String, Vec<Call>> = HashMap::new();
459    for c in calls { by_contig.entry(c.seqid.clone()).or_default().push(c); }
460    let mut out: Vec<Call> = Vec::new();
461    for (_, cs) in by_contig {
462        let mut cs = cs;
463        // total order on genomic position so chaining is deterministic
464        cs.sort_by(|a, b| a.orf_begin.cmp(&b.orf_begin)
465            .then(a.orf_end.cmp(&b.orf_end))
466            .then(a.strand.cmp(&b.strand)));
467        let n = cs.len();
468        let mut slots: Vec<Option<Call>> = cs.into_iter().map(Some).collect();
469        let mut i = 0;
470        while i < n {
471            let fam = norm_fam(&slots[i].as_ref().unwrap().family);
472            let strand = slots[i].as_ref().unwrap().strand;
473            let mut chain_end = slots[i].as_ref().unwrap().orf_end;
474            let mut j = i + 1;
475            while j < n {
476                let cj = slots[j].as_ref().unwrap();
477                if norm_fam(&cj.family) == fam && cj.strand == strand
478                    && cj.orf_begin - chain_end <= gap {
479                    chain_end = chain_end.max(cj.orf_end);
480                    j += 1;
481                } else { break; }
482            }
483            if j - i == 1 {
484                out.push(slots[i].take().unwrap());
485            } else {
486                let chain: Vec<Call> = (i..j).map(|k| slots[k].take().unwrap()).collect();
487                let mb = chain.iter().map(|c| c.orf_begin).min().unwrap();
488                let me = chain.iter().map(|c| c.orf_end).max().unwrap();
489                // strongest hit = base for family/tier/evalue/qcov/pident (total-order tiebreak)
490                let bi = (0..chain.len()).min_by(|&a, &b|
491                    chain[a].evalue.partial_cmp(&chain[b].evalue).unwrap()
492                        .then(chain[a].orf_begin.cmp(&chain[b].orf_begin))
493                        .then(chain[a].orf_end.cmp(&chain[b].orf_end))
494                        .then(chain[a].strand.cmp(&chain[b].strand))).unwrap();
495                let base = &chain[bi];
496                let label = base.family.clone();
497                let tir = contig_map.get(base.seqid.as_str())
498                    .and_then(|seq| find_tir(seq, mb, me, &label, tir_tbl));
499                let (is_b, is_e, typ) = classify_is(&label, mb, me, &tir, tir_tbl, tpase_tbl);
500                out.push(Call {
501                    seqid: base.seqid.clone(), family: label, tier: base.tier.clone(),
502                    is_begin: is_b, is_end: is_e, is_len: is_e - is_b + 1,
503                    orf_begin: mb, orf_end: me, strand: base.strand,
504                    evalue: base.evalue, qcov: base.qcov, pident: base.pident,
505                    typ, tir, ncopy: 1,
506                    fp_flag: "IS".into(),
507                });
508            }
509            i = j;
510        }
511    }
512    out
513}
514
515// Target-site duplication (TSD): upon insertion an IS duplicates a short host target, leaving an
516// identical DIRECT repeat immediately flanking each end (...[TSD][element][TSD]...). A TSD is thus a
517// homology-INDEPENDENT positive signal of transposition, complementary to the TIR. Family TSD lengths
518// run ~3-14 bp, so we look for a direct repeat of length >= MIN_TSD whose left copy abuts is_begin and
519// right copy abuts is_end, allowing a small shift because the called boundary can be a few bp off.
520// Conservative (flush-ish, exact, >= MIN_TSD) to keep the chance-match rate low.
521const MIN_TSD: usize = 4;
522const MAX_TSD: usize = 14;
523fn has_tsd(seq: &[u8], is_begin: i64, is_end: i64) -> bool {
524    const W: i64 = 12;      // flank window scanned on each side
525    const SHIFT: usize = 2; // boundary-imprecision tolerance
526    let n = seq.len() as i64;
527    let (lb, le) = ((is_begin - 1 - W).max(0), (is_begin - 1).max(0)); // upstream flank [lb,le)
528    let (rb, re) = (is_end.min(n), (is_end + W).min(n));               // downstream flank [rb,re)
529    if le <= lb || re <= rb { return false; }
530    let left = &seq[lb as usize..le as usize];   // ends at the left boundary
531    let right = &seq[rb as usize..re as usize];  // starts at the right boundary
532    for l in (MIN_TSD..=MAX_TSD).rev() {
533        for ls in 0..=SHIFT {
534            if left.len() < l + ls { break; }
535            let lc = &left[left.len() - l - ls..left.len() - ls]; // l bp ending ls before boundary
536            for rs in 0..=SHIFT {
537                if right.len() < l + rs { break; }
538                let rc = &right[rs..rs + l];                       // l bp starting rs after boundary
539                if lc == rc { return true; }
540            }
541        }
542    }
543    false
544}
545
546// ---------------------------------------------------------- (C) nt neg-pos FP-control module
547// The HTH/DDE fold is shared between IS transposases and host proteins (regulators, nucleases,
548// recombinases) at the protein level -> the aa profile search cannot separate them (marA/soxS
549// called IS4). But at NUCLEOTIDE level, IS lineages and host lineages diverge, so the call's nt
550// discriminates. For each call, compare its nt to a positive IS-nt reference (db_dir/fpc/pos) and
551// a negative host-nt reference (db_dir/fpc/neg): pos-lineage match confirms IS; host-lineage match
552// with no IS support flags a likely FP. Two homology-INDEPENDENT structural signals (TIR and TSD)
553// add positive support that survives when nt homology is silent (divergent/novel IS): a call with
554// no nt evidence either way but a TIR/TSD is "putative" (structure suggests IS), not "unresolved";
555// and structure protects a host-leaning call from the droppable "host" verdict (never silently drop
556// a structurally-supported call -- the neg DB is contamination-fragile, TIR/TSD are IS-specific).
557// Validated on MG1655 (marA/soxS/fimB flagged, 49 curated IS retained) and 1500 GTDB strains
558// (85% regulator-FP rejection, robust to genus-level holdout => not overfit).
559fn fp_control_module(calls: &mut [Call], contig_map: &HashMap<&str, &Vec<u8>>,
560                     db_dir: &Path, tmp: &Path, nthread: usize) {
561    let fpc = db_dir.join("fpc");
562    if !fpc.join("refset.dbtype").exists() { return; } // no FP-control DB -> skip (module optional)
563    // write each call's element nt as >c{index}
564    let qfa = tmp.join("fpcq.fna");
565    let mut nq = 0usize;
566    {
567        let mut o = BufWriter::new(fs::File::create(&qfa).unwrap());
568        for (i, c) in calls.iter().enumerate() {
569            if let Some(seq) = contig_map.get(c.seqid.as_str()) {
570                let b = c.is_begin.max(1) as usize; let e = c.is_end as usize;
571                if e <= seq.len() && e >= b {
572                    let mut sub = seq[b-1..e].to_vec();
573                    if c.strand == '-' { sub = revcomp(&sub); }
574                    if sub.len() >= 60 {
575                        writeln!(o, ">c{}", i).unwrap();
576                        o.write_all(&sub).unwrap(); o.write_all(b"\n").unwrap();
577                        nq += 1;
578                    }
579                }
580            }
581        }
582    }
583    if nq == 0 { return; } // no extractable query nt (0 calls / all too short) -> mmseqs createdb would fail; all calls keep default "IS"
584    let run = |args: &[&str]| {
585        let st = Command::new("mmseqs").args(args)
586            .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null())
587            .status().expect("spawn mmseqs");
588        assert!(st.success(), "mmseqs {:?} failed", &args[0]);
589    };
590    let nt = nthread.to_string();
591    let qdb = tmp.join("fpcqdb");
592    run(&["createdb", qfa.to_str().unwrap(), qdb.to_str().unwrap(), "--dbtype", "2", "-v", "0"]);
593    // Best bits per call against the IS(pos) and host(neg) references, in ONE search over the combined
594    // refset (targets prefixed "P|" = IS-lineage, "N|" = host-lineage) -> ~40% faster than two searches.
595    let mut posb: HashMap<usize,f64> = HashMap::new();
596    let mut negb: HashMap<usize,f64> = HashMap::new();
597    let (res, aln, tp) = (tmp.join("fpcres"), tmp.join("fpcaln.tsv"), tmp.join("fpctp"));
598    run(&["search", qdb.to_str().unwrap(), fpc.join("refset").to_str().unwrap(), res.to_str().unwrap(),
599          tp.to_str().unwrap(), "--search-type", "3", "-s", "7", "--max-seqs", "50",
600          "-e", "1e-3", "--threads", &nt, "-v", "0"]);
601    run(&["convertalis", qdb.to_str().unwrap(), fpc.join("refset").to_str().unwrap(), res.to_str().unwrap(),
602          aln.to_str().unwrap(), "--format-output", "query,target,bits", "-v", "0"]);
603    for line in BufReader::new(fs::File::open(&aln).unwrap()).lines() {
604        let line = line.unwrap(); let p: Vec<&str> = line.split('\t').collect();
605        if p.len() < 3 { continue; }
606        let idx = match p[0].strip_prefix('c').and_then(|s| s.parse::<usize>().ok()) { Some(i)=>i, None=>continue };
607        let bits: f64 = p[2].parse().unwrap_or(0.0);
608        let tbl = if let Some(_) = p[1].strip_prefix("P|") { &mut posb }
609                  else if let Some(_) = p[1].strip_prefix("N|") { &mut negb } else { continue };
610        let ent = tbl.entry(idx).or_insert(0.0);
611        if bits > *ent { *ent = bits; }
612    }
613    for (i, c) in calls.iter_mut().enumerate() {
614        let pb = *posb.get(&i).unwrap_or(&0.0);
615        let nb = *negb.get(&i).unwrap_or(&0.0);
616        // homology-independent IS-architecture support (TIR present, or a flanking TSD direct repeat)
617        let structural = c.tir.is_some()
618            || contig_map.get(c.seqid.as_str()).map(|s| has_tsd(s, c.is_begin, c.is_end)).unwrap_or(false);
619        c.fp_flag = fp_verdict(pb, nb, structural).into();
620    }
621}
622
623// The 5-tier fpFlag decision, isolated as a pure fn so it is unit-testable and the semantics are locked.
624// pb/nb = best bits vs the IS(pos)/host(neg) nt references; structural = TIR or TSD present.
625fn fp_verdict(pb: f64, nb: f64, structural: bool) -> &'static str {
626    if pb > 0.0 && pb >= nb {                       // nt matches IS lineage (homology-confirmed)
627        "IS"
628    } else if nb > pb {                             // nt leans host
629        if !structural && pb == 0.0 { "host" }      // host-lineage only, no IS support of any kind -> droppable
630        else { "shared" }                           // matches both / structure-vs-nt conflict -> keep
631    } else {                                        // pb == 0 && nb == 0: no nt evidence either way
632        if structural { "putative" }                // structure (TIR/TSD) suggests IS
633        else { "unresolved" }                       // truly undecided
634    }
635}
636
637// Format like Python's "%.1e" (signed exponent, zero-padded to >=2 digits) so the
638// E-value column is byte-identical to pv2's. Rust's {:.1e} drops the sign and padding
639// (e.g. 0.0 -> "0.0e0"); Python gives "0.0e+00".
640fn py_e(x: f64) -> String {
641    let s = format!("{:.1e}", x);
642    let (m, e) = s.split_once('e').unwrap();
643    let exp: i32 = e.parse().unwrap_or(0);
644    format!("{}e{}{:02}", m, if exp < 0 { "-" } else { "+" }, exp.abs())
645}
646
647pub fn write_tsv(calls: &[Call], path: &Path) {
648    let mut o = BufWriter::new(fs::File::create(path).unwrap());
649    writeln!(o, "seqID\tfamily\ttier\tisBegin\tisEnd\tisLen\tncopy4is\torfBegin\torfEnd\tstrand\tE-value\tqcov\tpident\ttype\tirLen\tirId\tstart2\tend2\ttir\tfpFlag").unwrap();
650    let mut idx: Vec<usize> = (0..calls.len()).collect();
651    idx.sort_by(|&a, &b| (calls[a].seqid.as_str(), calls[a].is_begin)
652        .cmp(&(calls[b].seqid.as_str(), calls[b].is_begin)));
653    for &i in &idx {
654        let c = &calls[i];
655        let (irlen, irid, s2, e2, tirstr) = match &c.tir {
656            Some(t) => (t.irlen, t.irid, t.start2, t.end2,
657                        format!("{}:{}", String::from_utf8_lossy(&t.seq1), String::from_utf8_lossy(&t.seq2))),
658            None => (0, 0, 0, 0, "-".to_string()),
659        };
660        writeln!(o, "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{:.2}\t{:.0}\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
661            c.seqid, c.family, c.tier, c.is_begin, c.is_end, c.is_len, c.ncopy,
662            c.orf_begin, c.orf_end, c.strand, py_e(c.evalue), c.qcov, c.pident, c.typ,
663            irlen, irid, s2, e2, tirstr, c.fp_flag).unwrap();
664    }
665}
666
667pub fn write_gff(calls: &[Call], path: &Path) {
668    let mut o = BufWriter::new(fs::File::create(path).unwrap());
669    writeln!(o, "##gff-version 3").unwrap();
670    let mut idx: Vec<usize> = (0..calls.len()).collect();
671    idx.sort_by(|&a, &b| (calls[a].seqid.as_str(), calls[a].is_begin)
672        .cmp(&(calls[b].seqid.as_str(), calls[b].is_begin)));
673    for (n, &i) in idx.iter().enumerate() {
674        let c = &calls[i];
675        let id = n + 1;
676        writeln!(o, "{}\tisscan\tinsertion_sequence\t{}\t{}\t.\t{}\t.\tID=IS_{};family={};type={};tier={};ncopy={};evalue={};orf={}..{}",
677            c.seqid, c.is_begin, c.is_end, c.strand, id, c.family, c.typ, c.tier, c.ncopy, py_e(c.evalue), c.orf_begin, c.orf_end).unwrap();
678        if c.fp_flag != "IS" {
679            writeln!(o, "# IS_{} fpFlag={}", id, c.fp_flag).unwrap();
680        }
681        if let Some(t) = &c.tir {
682            writeln!(o, "{}\tisscan\tterminal_inverted_repeat\t{}\t{}\t.\t{}\t.\tParent=IS_{};irLen={};irId={}",
683                c.seqid, t.start1, t.end1, c.strand, id, t.irlen, t.irid).unwrap();
684            writeln!(o, "{}\tisscan\tterminal_inverted_repeat\t{}\t{}\t.\t{}\t.\tParent=IS_{};irLen={};irId={}",
685                c.seqid, t.start2, t.end2, c.strand, id, t.irlen, t.irid).unwrap();
686        }
687    }
688}
689
690pub fn write_sum(calls: &[Call], path: &Path) {
691    let mut o = BufWriter::new(fs::File::create(path).unwrap());
692    let mut byfam: HashMap<String, Vec<usize>> = HashMap::new();
693    for (i, c) in calls.iter().enumerate() {
694        byfam.entry(c.family.split('-').next().unwrap().to_string()).or_default().push(i);
695    }
696    let mut fams: Vec<&String> = byfam.keys().collect();
697    // total order: nIS desc, then family name asc — deterministic on count ties.
698    fams.sort_by(|a, b| byfam[*b].len().cmp(&byfam[*a].len()).then_with(|| a.cmp(b)));
699    writeln!(o, "family\tnIS\tcomplete\tpartial\tmeanIsLen").unwrap();
700    let (mut tot, mut nc, mut np) = (0i64, 0i64, 0i64);
701    for f in fams {
702        let cs = &byfam[f];
703        let comp = cs.iter().filter(|&&i| calls[i].typ == 'c').count() as i64;
704        let part = cs.len() as i64 - comp;
705        let mean: i64 = cs.iter().map(|&i| calls[i].is_len).sum::<i64>() / cs.len() as i64;
706        writeln!(o, "{}\t{}\t{}\t{}\t{}", f, cs.len(), comp, part, mean).unwrap();
707        tot += cs.len() as i64; nc += comp; np += part;
708    }
709    writeln!(o, "TOTAL\t{}\t{}\t{}\t-", tot, nc, np).unwrap();
710    // FP-control summary: how many calls the nt neg-pos discriminator supports vs flags
711    if calls.iter().any(|c| c.fp_flag != "IS") {
712        let cnt = |f: &str| calls.iter().filter(|c| c.fp_flag == f).count();
713        writeln!(o, "#fpControl\tIS\tputative\tshared\thost\tunresolved").unwrap();
714        writeln!(o, "#fpControl\t{}\t{}\t{}\t{}\t{}",
715            cnt("IS"), cnt("putative"), cnt("shared"), cnt("host"), cnt("unresolved")).unwrap();
716    }
717}
718
719// ---------------------------------------------------------- tables (== constants_isscan.py)
720fn tir_table() -> HashMap<String,(i64,i64,i64,i64)> {
721    [("IS1",(8,67,14,1)),("IS110",(2,31,14,-1)),("IS1182",(8,44,10,1)),("IS1380",(7,39,10,1)),
722     ("IS1595",(10,43,15,1)),("IS1634",(11,32,12,1)),("IS200/IS605",(10000,0,10000,0)),
723     ("IS21",(8,76,10,1)),("IS256",(8,48,15,1)),("IS3",(7,54,10,-1)),("IS30",(11,50,12,1)),
724     ("IS4",(8,67,12,1)),("IS481",(5,52,10,1)),("IS5",(7,45,14,1)),("IS6",(12,36,14,1)),
725     ("IS607",(12,46,12,-1)),("IS630",(3,92,11,1)),("IS66",(11,144,11,1)),("IS701",(12,38,12,1)),
726     ("IS91",(11,21,11,-1)),("IS982",(11,35,11,1)),("ISAS1",(12,34,12,1)),("ISAZO13",(18,48,18,1)),
727     ("ISH3",(11,31,15,1)),("ISKRA4",(15,40,18,1)),("ISL3",(6,50,11,1)),("ISNCY",(4,52,13,-1)),
728     ("new",(10,50,20,-1))]
729    .iter().map(|(k,v)| (norm_fam(k), *v)).collect()   // normalized keys -> O(1) lookup
730}
731fn tpase_table() -> HashMap<String,(i64,i64,i64)> {
732    [("IS1",(666,1119,252)),("IS110",(603,1380,156)),("IS1182",(822,1731,570)),("IS1380",(1158,1554,1158)),
733     ("IS1595",(576,1158,426)),("IS1634",(1314,1875,1314)),("IS200/IS605",(366,1482,147)),("IS21",(882,1758,231)),
734     ("IS256",(990,1389,990)),("IS3",(441,1581,120)),("IS30",(540,1419,189)),("IS4",(570,1629,219)),
735     ("IS481",(447,1794,447)),("IS5",(360,1908,75)),("IS6",(528,1062,246)),("IS607",(768,1653,453)),
736     ("IS630",(510,1194,318)),("IS66",(354,1695,165)),("IS701",(921,1410,921)),("IS91",(648,1548,648)),
737     ("IS982",(627,981,429)),("ISAS1",(594,1329,189)),("ISAZO13",(1203,2094,513)),("ISH3",(573,1206,549)),
738     ("ISKRA4",(1047,1719,114)),("ISL3",(414,1716,408)),("ISNCY",(573,1815,123)),("new",(300,2100,50))]
739    .iter().map(|(k,v)| (norm_fam(k), *v)).collect()   // normalized keys -> O(1) lookup
740}
741
742// ---------------------------------------------------------- main
743/// Configuration for [`run`].
744pub struct IseConfig {
745    /// mmseqs2 thread count.
746    pub threads: usize,
747    /// Use MMseqs2 GPU acceleration.
748    pub gpu: bool,
749    /// Precision mode: drop `fpFlag == "host"` (host-lineage FP) calls.
750    pub strict: bool,
751    /// IS database directory (must contain `mmdb_union/profileDb*` + `manifest_union.tsv`).
752    pub db_dir: PathBuf,
753}
754
755/// Run the IS-element detection pipeline on a genome FASTA, returning the calls.
756///
757/// `work_dir` is where the intermediate files (`proteome.faa`, mmseqs
758/// `isscan_tmp/`) are written; the caller owns it and any cleanup. Requires the
759/// `mmseqs` binary on PATH and a valid IS DB at `config.db_dir`. This is the exact
760/// pipeline the `rust-ise` binary runs (the binary just parses args and writes the
761/// TSV/GFF/.sum from the returned calls).
762pub fn run(seqfile: &Path, work_dir: &Path, config: &IseConfig) -> Result<Vec<Call>, String> {
763    if !config
764        .db_dir
765        .join("mmdb_union")
766        .join("profileDb.dbtype")
767        .exists()
768    {
769        return Err(format!(
770            "'{}' is not a valid isscan DB (missing mmdb_union/profileDb)",
771            config.db_dir.display()
772        ));
773    }
774    fs::create_dir_all(work_dir).map_err(|e| format!("create {}: {e}", work_dir.display()))?;
775    let tmp = work_dir.join("isscan_tmp");
776    fs::create_dir_all(&tmp).map_err(|e| format!("create {}: {e}", tmp.display()))?;
777
778    let seqfile = seqfile.to_str().ok_or("non-UTF8 seqfile path")?;
779    let contigs = read_fasta(seqfile);
780    let contig_map: HashMap<&str, &Vec<u8>> =
781        contigs.iter().map(|(k, v)| (k.as_str(), v)).collect();
782
783    // 1. ORFs: rustygal META gene-finding (rust-pure, no subprocess) + native edge recovery.
784    let meta = rustygal::meta_api::meta_bins();
785    let per_contig: Vec<Vec<u8>> = contigs
786        .par_iter()
787        .enumerate()
788        .map(|(i, (hdr, dna))| rustygal::meta_api::run_meta(i as i32 + 1, hdr, dna, &meta).trans_faa)
789        .collect();
790    let faa: Vec<u8> = per_contig.concat();
791    let mut orfs = parse_rustygal_faa(&faa);
792    let edges: Vec<(String, Vec<Orf>)> = contigs
793        .par_iter()
794        .map(|(cid, seq)| {
795            let empty = Vec::new();
796            let pyr = orfs.get(cid).unwrap_or(&empty);
797            (cid.clone(), edge_orfs(seq, pyr, 30, 3))
798        })
799        .collect();
800    for (cid, mut e) in edges {
801        orfs.entry(cid).or_default().append(&mut e);
802    }
803    // proteome.faa headers {cid}_{b}_{e}_{strand}[_edge], contigs in FASTA order
804    // (deterministic byte-order == pv2; mmseqs prefilter is order-sensitive).
805    let proteome = work_dir.join("proteome.faa");
806    {
807        let mut o = BufWriter::new(fs::File::create(&proteome).map_err(|e| e.to_string())?);
808        for (cid, _) in &contigs {
809            if let Some(list) = orfs.get(cid) {
810                for orf in list {
811                    let suffix = if orf.edge { "_edge" } else { "" };
812                    writeln!(o, ">{}_{}_{}_{}{}", cid, orf.begin, orf.end, orf.strand, suffix)
813                        .map_err(|e| e.to_string())?;
814                    o.write_all(&orf.prot).map_err(|e| e.to_string())?;
815                    o.write_all(b"\n").map_err(|e| e.to_string())?;
816                }
817            }
818        }
819    }
820
821    // 2. search
822    let hits = mmseqs_search(&proteome, &config.db_dir, &tmp, config.threads, config.gpu);
823
824    // 3. family call + TIR + classify (parallel over ORFs)
825    let tir_tbl = tir_table();
826    let tpase_tbl = tpase_table();
827    let hit_vec: Vec<(&String, &Vec<Hit>)> = hits.iter().collect();
828    let raw_calls: Vec<Call> = hit_vec
829        .par_iter()
830        .filter_map(|(orf, oh)| {
831            let (label, tier, best) = family_call(oh)?;
832            if tier == "novel" {
833                return None;
834            }
835            // parse orf id: contig_begin_end_strand[_edge]
836            let core: &str = if orf.ends_with("_edge") {
837                &orf[..orf.len() - 5]
838            } else {
839                orf
840            };
841            let mut it = core.rsplitn(4, '_');
842            let strand = it.next()?;
843            let e: i64 = it.next()?.parse().ok()?;
844            let b: i64 = it.next()?.parse().ok()?;
845            let contig = it.next()?;
846            let strand_c = strand.chars().next().unwrap_or('+');
847            let tir = contig_map
848                .get(contig)
849                .and_then(|seq| find_tir(seq, b, e, &label, &tir_tbl));
850            let (is_b, is_e, typ) = classify_is(&label, b, e, &tir, &tir_tbl, &tpase_tbl);
851            Some(Call {
852                seqid: contig.to_string(),
853                family: label,
854                tier,
855                is_begin: is_b,
856                is_end: is_e,
857                is_len: is_e - is_b + 1,
858                orf_begin: b,
859                orf_end: e,
860                strand: strand_c,
861                evalue: best.evalue,
862                qcov: best.qcov,
863                pident: best.pident,
864                typ,
865                tir,
866                ncopy: 1,
867                fp_flag: "IS".into(),
868            })
869        })
870        .collect();
871    let calls = dedup(raw_calls, 0.5);
872    // collapse two-ORF (orfA+orfB) IS into one element (see merge_adjacent)
873    let mut calls = merge_adjacent(calls, 50, &contig_map, &tir_tbl, &tpase_tbl);
874
875    // 3b. nt neg-pos FP-control: flag host-lineage calls
876    fp_control_module(&mut calls, &contig_map, &config.db_dir, &tmp, config.threads);
877    if config.strict {
878        calls.retain(|c| c.fp_flag != "host"); // precision mode: drop host-lineage FPs
879    }
880    Ok(calls)
881}
882
883// ---------------------------------------------------------- unit tests (golden: lock the logic)
884#[cfg(test)]
885mod tests {
886    use super::*;
887
888    #[test]
889    fn fp_verdict_five_tiers() {
890        // IS: nt matches IS lineage (pb>0 & pb>=nb), incl. the tie pb==nb>0
891        assert_eq!(fp_verdict(100.0, 0.0, false), "IS");
892        assert_eq!(fp_verdict(100.0, 100.0, false), "IS");
893        // shared: nt leans host but pb>0 (matches both, host closer)
894        assert_eq!(fp_verdict(50.0, 100.0, false), "shared");
895        // host: host-lineage only, pb==0, no structure -> the only droppable tier
896        assert_eq!(fp_verdict(0.0, 100.0, false), "host");
897        // structure PROTECTS a host-leaning call from "host" -> "shared" (never silently dropped)
898        assert_eq!(fp_verdict(0.0, 100.0, true), "shared");
899        // no nt evidence either way: structure -> putative, else unresolved
900        assert_eq!(fp_verdict(0.0, 0.0, true), "putative");
901        assert_eq!(fp_verdict(0.0, 0.0, false), "unresolved");
902    }
903
904    #[test]
905    fn tsd_detected_and_rejected() {
906        // ...[GGGGGG][ACGTAC]<TTTTTTTTTT>[ACGTAC][CCCCCC]... : 6bp TSD flanking element at 1-based [13,22]
907        let s = b"GGGGGGACGTACTTTTTTTTTTACGTACCCCCC";
908        assert!(has_tsd(s, 13, 22), "flanking 6bp direct repeat should be found");
909        // no flanking direct repeat -> false
910        let s2 = b"GGGGGGGGGGGGTTTTTTTTTTCCCCCCCCCCCC";
911        assert!(!has_tsd(s2, 13, 22), "distinct flanks have no TSD");
912        // 3bp repeat is below MIN_TSD(4) -> not counted
913        let s3 = b"GGGGGGGGGACGTTTTTTTTTTACGCCCCCCCCC";
914        assert!(!has_tsd(s3, 13, 22), "3bp repeat must not count as TSD");
915    }
916
917    #[test]
918    fn revcomp_translate_norm() {
919        assert_eq!(revcomp(b"ACGT"), b"ACGT");           // palindrome
920        assert_eq!(revcomp(b"AAAA"), b"TTTT");
921        assert_eq!(revcomp(b"ATGC"), b"GCAT");
922        assert_eq!(translate(b"ATGAAA"), b"MK");         // ATG=Met, AAA=Lys
923        assert_eq!(norm_fam("IS200/IS605"), "IS200IS605");
924        assert_eq!(norm_fam("is_3"), "IS3");
925    }
926
927    #[test]
928    fn py_e_matches_python_format() {
929        assert_eq!(py_e(0.0), "0.0e+00");
930        assert_eq!(py_e(1e-5), "1.0e-05");
931    }
932}