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