feat(phylo): add --iqtree-min-freq to filter rare nucleotide states
Introduces --iqtree-min-freq (default 0.001) to treat low-frequency nucleotide states as missing data during IQ-TREE alignment generation when --free-loss is active. This triggers a recoding pass that folds rare states into the missing symbol, followed by non-informative site removal and alphabet recomputation to maintain output consistency. The change also adds Sankoff model configuration files and updates related tests and documentation.
This commit is contained in:
1 parent
c8f2b16b4c
commit
128db64564
10 files changed
+756
-7
No files matched your search
@@ -267,6 +267,25 @@ pub struct PhyloArgs {
|
||||
#[arg(long)]
|
||||
pub iqtree: bool,
|
||||
|
||||
/// Under `--iqtree --free-loss`, also recode to `?` (the same
|
||||
/// missing-data treatment as `-`) any state whose empirical frequency
|
||||
/// in the alignment falls below this threshold — not just genuinely
|
||||
/// absent calls. States encoding 3 or 4 simultaneously-observed
|
||||
/// central bases (IUPAC `V`/`H`/`K`.../`N` for 3, `N` for 4) are rare
|
||||
/// by construction and, on real data, land in exactly this low-frequency
|
||||
/// range — more likely assembly/detection noise than a genuine,
|
||||
/// widely-preserved multi-way polymorphism, the same "sampling failure,
|
||||
/// not true signal" reasoning `--free-loss` already applies to absence.
|
||||
/// Confirmed on real data to matter: `iqtree3`'s own "Numerical
|
||||
/// underflow for lh-derivative" warnings and the exact-zero
|
||||
/// exchangeability rows this was meant to fix (see
|
||||
/// `DevDocMD/theory/evolutionary_distances.md`) both trace back to
|
||||
/// states this thin. No effect without `--free-loss` (there is no
|
||||
/// missing-data symbol to recode to otherwise). `<prefix>_iqtree_states.csv`
|
||||
/// reports the frequency actually used to decide.
|
||||
#[arg(long, default_value = "0.001")]
|
||||
pub iqtree_min_freq: f64,
|
||||
|
||||
/// Scale factor applied before rounding real-valued costs to the
|
||||
/// integers both `--tnt`'s smatrix/cost commands and `--phyg`'s `tcm:`
|
||||
/// matrix require. Keep this small: the total tree score is this scale
|
||||
|
||||
@@ -107,6 +107,19 @@ fn drop_ascertainment_noninformative(alignment: &SnpAlignment) -> SnpAlignment {
|
||||
SnpAlignment { sequences }
|
||||
}
|
||||
|
||||
/// Recode every occurrence of a byte in `symbols` to `-` — the same
|
||||
/// "absent" byte `drop_ascertainment_noninformative`/`compact_alphabet`
|
||||
/// already treat specially under `--free-loss` (recoded to `?` further
|
||||
/// downstream). Used by `--iqtree-min-freq` to fold rare, likely-noisy
|
||||
/// states into the missing-data treatment before a second
|
||||
/// `compact_alphabet` pass, without duplicating that treatment's logic.
|
||||
fn recode_symbols_as_absent(alignment: &SnpAlignment, symbols: &[u8]) -> SnpAlignment {
|
||||
let sequences = alignment.sequences.iter()
|
||||
.map(|seq| seq.iter().map(|&b| if symbols.contains(&b) { b'-' } else { b }).collect())
|
||||
.collect();
|
||||
SnpAlignment { sequences }
|
||||
}
|
||||
|
||||
fn compact_alphabet(alignment: &SnpAlignment, free_loss: bool) -> CompactAlphabet {
|
||||
let iupac_to_state = state_index_table();
|
||||
|
||||
@@ -240,6 +253,7 @@ pub(super) fn write_iqtree(
|
||||
labels: &[String],
|
||||
output: &Option<PathBuf>,
|
||||
free_loss: bool,
|
||||
min_freq: f64,
|
||||
) {
|
||||
let filtered;
|
||||
let alignment = if free_loss {
|
||||
@@ -257,7 +271,41 @@ pub(super) fn write_iqtree(
|
||||
alignment
|
||||
};
|
||||
|
||||
let alphabet = compact_alphabet(alignment, free_loss);
|
||||
let mut alphabet = compact_alphabet(alignment, free_loss);
|
||||
|
||||
// `--iqtree-min-freq`: fold rare (likely-noisy) states into the same
|
||||
// missing-data treatment `-` already gets under `--free-loss`, then
|
||||
// recompute the alphabet on the further-filtered alignment — see
|
||||
// `args.rs`'s docs on `--iqtree-min-freq` and
|
||||
// `DevDocMD/theory/evolutionary_distances.md` for why (real data:
|
||||
// states encoding 3-4 simultaneous central bases land in exactly this
|
||||
// low-frequency range and correlate with `iqtree3`'s own numerical
|
||||
// instability warnings).
|
||||
let refiltered;
|
||||
let alignment = if free_loss {
|
||||
let low_freq_symbols: Vec<u8> = alphabet.compact_to_old.iter().zip(alphabet.freq.iter())
|
||||
.filter(|&(_, &f)| f < min_freq)
|
||||
.map(|(&old, _)| STATE_SYMBOL[old as usize] as u8)
|
||||
.collect();
|
||||
if low_freq_symbols.is_empty() {
|
||||
alignment
|
||||
} else {
|
||||
let recoded = recode_symbols_as_absent(alignment, &low_freq_symbols);
|
||||
let before = recoded.sequences.first().map(|s| s.len()).unwrap_or(0);
|
||||
refiltered = drop_ascertainment_noninformative(&recoded);
|
||||
let after = refiltered.sequences.first().map(|s| s.len()).unwrap_or(0);
|
||||
info!(
|
||||
"--iqtree-min-freq {min_freq}: {} rare state(s) ({}) recoded as missing, {before} → {after} sites",
|
||||
low_freq_symbols.len(),
|
||||
low_freq_symbols.iter().map(|&b| b as char).collect::<String>(),
|
||||
);
|
||||
alphabet = compact_alphabet(&refiltered, free_loss);
|
||||
&refiltered
|
||||
}
|
||||
} else {
|
||||
alignment
|
||||
};
|
||||
|
||||
let states_path = write_iqtree_states_csv(&alphabet, output);
|
||||
let model_path = write_iqtree_model(matrix, &alphabet, output);
|
||||
let (fasta_path, n_sites) = write_iqtree_alignment(alignment, labels, &alphabet, output, free_loss);
|
||||
@@ -349,4 +397,39 @@ mod tests {
|
||||
assert_eq!(lines.next(), Some("1,G,0.5"));
|
||||
assert!(lines.next().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iqtree_min_freq_folds_rare_states_into_missing() {
|
||||
// 20 common A/C sites (60 calls total across 3 genomes) plus one
|
||||
// site where genome 0 carries the rare ambiguity state `M` and
|
||||
// genome 1 carries `A` (kept informative by the first
|
||||
// ascertainment filter: two distinct non-`-` calls) — `M` ends up
|
||||
// at 1/62, well below the 0.05 threshold used here.
|
||||
let mut sequences: Vec<Vec<u8>> = vec![Vec::new(); 3];
|
||||
for i in 0..20 {
|
||||
let (a, b, c) = if i % 2 == 0 { (b'A', b'C', b'A') } else { (b'C', b'A', b'C') };
|
||||
sequences[0].push(a);
|
||||
sequences[1].push(b);
|
||||
sequences[2].push(c);
|
||||
}
|
||||
sequences[0].push(b'M');
|
||||
sequences[1].push(b'A');
|
||||
sequences[2].push(b'-');
|
||||
let alignment = SnpAlignment { sequences };
|
||||
let labels = vec!["g1".to_string(), "g2".to_string(), "g3".to_string()];
|
||||
let matrix = [[0.0f64; 16]; 16];
|
||||
let prefix = std::env::temp_dir().join(format!("obikmer_test_iqtree_minfreq_{}", std::process::id()));
|
||||
let output = Some(prefix.clone());
|
||||
|
||||
write_iqtree(&matrix, &alignment, &labels, &output, true, 0.05);
|
||||
|
||||
let states_path = format!("{}_iqtree_states.csv", prefix.display());
|
||||
let csv = std::fs::read_to_string(&states_path).unwrap();
|
||||
assert!(!csv.contains(",M,"), "M (freq ~1/62) must be folded into missing under --iqtree-min-freq 0.05, got:\n{csv}");
|
||||
assert!(csv.contains(",A,") && csv.contains(",C,"), "A/C must survive (well above threshold), got:\n{csv}");
|
||||
|
||||
for suffix in ["_iqtree_states.csv", "_iqtree.model", "_iqtree.fasta"] {
|
||||
std::fs::remove_file(format!("{}{suffix}", prefix.display())).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -249,7 +249,7 @@ pub fn run(args: PhyloArgs) {
|
||||
write_sankoff_phyg(&matrix, &args.output, args.sankoff_cost_scale);
|
||||
}
|
||||
if args.iqtree {
|
||||
write_iqtree(&matrix, &alignment, &kept_labels, &args.output, args.free_loss);
|
||||
write_iqtree(&matrix, &alignment, &kept_labels, &args.output, args.free_loss, args.iqtree_min_freq);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user