//! Cardinality × composition decomposition of the 16-state transition cost //! matrix — replaces `sankoff::build_cost_matrix`'s elementary-edge graph //! and its Floyd-Warshall shortest-path closure, which double-counts //! multi-hop transitions once IQ-TREE's own matrix exponential composes //! them again. See `docmd/theory/evolutionary_distances.md`, "`R` via //! `exp(-cost)` is wrong for a CTMC; cardinality/composition decomposition". //! //! Two small, directly-estimated first-order Markov models (diagonals //! included — "stay the same" is a real, calibrated outcome, not implicit): //! a 5-state cardinality model (`0..=4` members of a family) and a 4-state //! base-composition model (`A,C,G,T`, unambiguous/cardinality-1 loci only — //! composition bias is a substitution phenomenon, only meaningful when //! cardinality is conserved). Composed per pair of 16 states via a //! parsimony-style pairing of the non-shared elements (see //! `pairwise_transition_matrix`'s doc), then symmetrised — Sankoff //! parsimony's score is only independent of root placement (as required, //! since TNT/PhyG search *unrooted* trees) if the cost matrix is //! symmetric, the discrete-parsimony analogue of CTMC reversibility. use crate::siblings::{BasePairTally, CardinalityTally}; /// Row-stochastic 5×5 cardinality transition probabilities (`0..=4`), /// diagonal included ("stay at the same cardinality"), from /// [`CardinalityTally`]'s pooled, symmetric co-occurrence counts. pub fn cardinality_transition_probs(tally: &CardinalityTally) -> [[f64; 5]; 5] { let mut p = [[0.0f64; 5]; 5]; for a in 0..5 { let row_sum: u64 = tally.counts[a].iter().sum(); if row_sum == 0 { continue; } for b in 0..5 { p[a][b] = tally.counts[a][b] as f64 / row_sum as f64; } } p } /// Row-stochastic 4×4 base-composition transition probabilities /// (`A,C,G,T`), diagonal included ("stay the same base"), from /// [`BasePairTally`]'s pooled substitution (off-diagonal) and agreement /// (`same`, diagonal) counts — unambiguous, cardinality-1 loci only. pub fn composition_transition_probs(tally: &BasePairTally) -> [[f64; 4]; 4] { let mut p = [[0.0f64; 4]; 4]; for a in 0..4 { let row_sum = tally.same[a] + (0..4).map(|b| tally.counts[a][b]).sum::(); if row_sum == 0 { continue; } p[a][a] = tally.same[a] as f64 / row_sum as f64; for b in 0..4 { if a != b { p[a][b] = tally.counts[a][b] as f64 / row_sum as f64; } } } p } /// Enumerate every injective mapping from `small` (indices `0..small.len()`) /// into `large` (indices `0..large.len()`, `large.len() >= small.len()`), /// calling `visit` with each full permutation of chosen `large` indices. /// `small.len() <= 4` always here (at most 4 bases can be lost or gained), /// so a plain recursive enumeration (at most `4! = 24` calls) is simplest — /// not worth a dependency for. fn for_each_injection(small_len: usize, large_len: usize, visit: &mut dyn FnMut(&[usize])) { let mut chosen = vec![0usize; small_len]; let mut used = vec![false; large_len]; fn go(pos: usize, chosen: &mut [usize], used: &mut [bool], visit: &mut dyn FnMut(&[usize])) { if pos == chosen.len() { visit(chosen); return; } for l in 0..used.len() { if used[l] { continue; } used[l] = true; chosen[pos] = l; go(pos + 1, chosen, used, visit); used[l] = false; } } if small_len == 0 { visit(&[]); return; } go(0, &mut chosen, &mut used, visit); } /// Parsimony-style pairing cost for the non-shared elements of a /// transition: pair every element of the smaller of `lost`/`gained` with /// some element of the larger one, choosing the pairing that minimises /// total `-ln(P_composition)` (maximises likelihood) — the discrete /// analogue of "prefer a substitution over an independent loss+gain". /// Leftover elements of the larger side (`|large|-|small|` of them) are /// *not* charged here — they're pure cardinality change, already priced by /// `P_cardinality(|A|→|B|)` in the caller. fn best_pairing_cost(lost: &[u8], gained: &[u8], p_comp: &[[f64; 4]; 4]) -> f64 { let (small, large) = if lost.len() <= gained.len() { (lost, gained) } else { (gained, lost) }; if small.is_empty() { return 0.0; } let mut best = f64::INFINITY; for_each_injection(small.len(), large.len(), &mut |perm| { let mut cost = 0.0; for (i, &li) in perm.iter().enumerate() { let (x, y) = (small[i], large[li]); let p = p_comp[x as usize][y as usize]; cost += if p > 0.0 { -p.ln() } else { f64::INFINITY }; } if cost < best { best = cost; } }); best } /// The full 16-state transition cost matrix, replacing /// `sankoff::build_cost_matrix`. For every pair of states `A`, `B` /// (bitmasks, bit `0..4` = `A,C,G,T`): `shared = A∩B` contributes /// `P_composition(x→x)` per shared base (diagonal — "stayed"); the /// remaining `lost = A\B`, `gained = B\A` are parsimony-paired into /// substitutions via [`best_pairing_cost`], and whatever's left over after /// pairing (only possible on one side, since one side is fully consumed) /// is *pure* cardinality change, priced once via `P_cardinality(|A|→|B|)` /// — never chained through intermediate states. Row-normalised (`P(A→·)` /// sums to `1` over all `B`), converted to a cost via `-ln`, then /// symmetrised (`(cost(A,B)+cost(B,A))/2` — the row-normalised `P` is not /// symmetric in general, but a Sankoff parsimony cost must be, so the /// score is independent of where an unrooted tree gets rooted). /// /// `free_loss`: drop the `P_cardinality(|A|→|B|)` factor entirely (never /// added to `log_p`) — the same low/incomplete-coverage argument that /// justifies recoding whole-family non-detection as `?` (see /// `docmd/theory/evolutionary_distances.md`, "Locus dropout under /// incomplete coverage") applies one level down: whether a genome shows 1 /// vs 2 (etc.) detected members of a *present* family is exactly as /// vulnerable to sampling failure as whether the family was detected at /// all. Without this, `∅`-involving transitions are neutralised (via the /// `?` recoding, bypassing this matrix's row/column 0 entirely) but /// cardinality changes *between two otherwise-detected, non-empty* states /// (e.g. `{A} -> {A,C}`) still carried the same calibrated /// `P_cardinality` penalty as any other gain/loss — inconsistent with /// `--free-loss`'s own rationale. With the factor dropped, cost is driven /// only by composition matching (shared-base retention and paired /// substitutions), never by a state pair's cardinality difference alone. pub fn pairwise_cost_matrix(p_card: &[[f64; 5]; 5], p_comp: &[[f64; 4]; 4], free_loss: bool) -> [[f64; 16]; 16] { let mut raw = [[0.0f64; 16]; 16]; for a in 0u8..16 { for b in 0u8..16 { let shared = a & b; let lost: Vec = (0..4).filter(|&i| a & (1 << i) != 0 && b & (1 << i) == 0).collect(); let gained: Vec = (0..4).filter(|&i| b & (1 << i) != 0 && a & (1 << i) == 0).collect(); let mut log_p = 0.0; // accumulate ln(P), so 0.0 = probability 1 if !free_loss { let card_a = a.count_ones() as usize; let card_b = b.count_ones() as usize; let p_c = p_card[card_a][card_b]; log_p += if p_c > 0.0 { p_c.ln() } else { f64::NEG_INFINITY }; } for i in 0..4u8 { if shared & (1 << i) != 0 { let p = p_comp[i as usize][i as usize]; log_p += if p > 0.0 { p.ln() } else { f64::NEG_INFINITY }; } } log_p -= best_pairing_cost(&lost, &gained, p_comp); raw[a as usize][b as usize] = log_p.exp(); } } // Row-normalise to a proper transition probability matrix. let mut p = [[0.0f64; 16]; 16]; for a in 0..16 { let row_sum: f64 = raw[a].iter().sum(); if row_sum > 0.0 { for b in 0..16 { p[a][b] = raw[a][b] / row_sum; } } } // Cost = -ln(P), then symmetrise (see doc comment: parsimony on an // unrooted tree requires a symmetric cost matrix). let mut cost = [[0.0f64; 16]; 16]; for a in 0..16 { for b in 0..16 { cost[a][b] = if p[a][b] > 0.0 { -p[a][b].ln() } else { f64::INFINITY }; } } let mut sym = [[0.0f64; 16]; 16]; for a in 0..16 { for b in 0..16 { sym[a][b] = if a == b { 0.0 } else { (cost[a][b] + cost[b][a]) / 2.0 }; } } sym } #[cfg(test)] mod tests { use super::*; #[test] fn cardinality_probs_row_normalised() { let mut counts = [[0u64; 5]; 5]; counts[0][0] = 10; counts[0][1] = 5; counts[1][0] = 5; counts[1][1] = 2; let tally = CardinalityTally { counts }; let p = cardinality_transition_probs(&tally); assert!((p[0].iter().sum::() - 1.0).abs() < 1e-12); assert!((p[1].iter().sum::() - 1.0).abs() < 1e-12); assert!((p[0][0] - 10.0 / 15.0).abs() < 1e-12); } #[test] fn composition_probs_include_diagonal() { let mut tally = BasePairTally { counts: [[0u64; 4]; 4], same: [0u64; 4] }; tally.same[0] = 90; // A stays A 90 times tally.counts[0][1] = 10; // A -> C 10 times tally.counts[1][0] = 10; let p = composition_transition_probs(&tally); assert!((p[0][0] - 0.9).abs() < 1e-12); assert!((p[0][1] - 0.1).abs() < 1e-12); assert!((p[0].iter().sum::() - 1.0).abs() < 1e-12); } #[test] fn pairwise_cost_matrix_is_symmetric_and_zero_diagonal() { // A plausible-looking pair of models (not calibrated from real // data — just needs every state reachable with nonzero probability // for this structural test). let p_card = [ [0.5, 0.3, 0.15, 0.04, 0.01], [0.3, 0.4, 0.2, 0.08, 0.02], [0.15, 0.2, 0.4, 0.2, 0.05], [0.04, 0.08, 0.2, 0.5, 0.18], [0.01, 0.02, 0.05, 0.18, 0.74], ]; let p_comp = [ [0.7, 0.1, 0.15, 0.05], [0.1, 0.7, 0.05, 0.15], [0.15, 0.05, 0.7, 0.1], [0.05, 0.15, 0.1, 0.7], ]; let cost = pairwise_cost_matrix(&p_card, &p_comp, false); for a in 0..16 { assert_eq!(cost[a][a], 0.0); for b in 0..16 { assert!((cost[a][b] - cost[b][a]).abs() < 1e-9, "cost[{a}][{b}]={} cost[{b}][{a}]={}", cost[a][b], cost[b][a]); } } } #[test] fn free_loss_ignores_cardinality_transition_probs() { // A skewed cardinality model (cardinality change made artificially // expensive) must have zero effect on the cost matrix once // `free_loss` is set — the whole point of the flag. let p_card_uniform = [[0.2f64; 5]; 5]; let p_card_skewed = [ [0.96, 0.01, 0.01, 0.01, 0.01], [0.01, 0.96, 0.01, 0.01, 0.01], [0.01, 0.01, 0.96, 0.01, 0.01], [0.01, 0.01, 0.01, 0.96, 0.01], [0.01, 0.01, 0.01, 0.01, 0.96], ]; let p_comp = [ [0.7, 0.1, 0.15, 0.05], [0.1, 0.7, 0.05, 0.15], [0.15, 0.05, 0.7, 0.1], [0.05, 0.15, 0.1, 0.7], ]; let cost_uniform = pairwise_cost_matrix(&p_card_uniform, &p_comp, true); let cost_skewed = pairwise_cost_matrix(&p_card_skewed, &p_comp, true); for a in 0..16 { for b in 0..16 { assert!( (cost_uniform[a][b] - cost_skewed[a][b]).abs() < 1e-9, "cost[{a}][{b}] differs between cardinality models under free_loss: {} vs {}", cost_uniform[a][b], cost_skewed[a][b], ); } } } }