1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! Enhanced Phylogenetic ML with Topology Optimization (NNI/SPR)
//!
//! Adds Nearest Neighbor Interchange (NNI) and Subtree Pruning & Regrafting (SPR)
//! algorithms for exploring tree topology space and finding locally optimal trees.
//!
//! Performance: NNI O(n²), SPR O(n³) where n = number of taxa
use std::collections::HashMap;
use crate::error::Result;
/// Jukes-Cantor substitution model parameters
#[derive(Debug, Clone)]
pub struct JukesCantor {
/// Rate parameter (α)
pub alpha: f64,
}
/// Kimura 2-Parameter model
#[derive(Debug, Clone)]
pub struct Kimura2P {
/// Transition rate (A ↔ G, C ↔ T)
pub transition_rate: f64,
/// Transversion rate (A ↔ C, A ↔ T, G ↔ C, G ↔ T)
pub transversion_rate: f64,
}
/// GTR (General Time Reversible) model
#[derive(Debug, Clone)]
pub struct GTR {
/// Rate parameters: AC, AG, AT, CG, CT, GT
pub rates: [f64; 6],
/// Base frequencies
pub frequencies: [f64; 4],
}
/// Substitution model types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubstitutionModel {
/// Jukes-Cantor: single parameter (α)
JukesCantor,
/// Kimura 2-Parameter: transition/transversion ratio
Kimura2P,
/// General Time Reversible: 6 rate parameters
GTR,
/// HKY (Hasegawa-Kishino-Yano): hybrid model
HKY,
}
/// Phylogenetic tree node for topology representation
#[derive(Debug, Clone)]
pub struct TreeNode {
pub id: usize,
pub label: Option<String>,
pub branch_length: f64,
pub children: Vec<usize>,
pub parent: Option<usize>,
}
/// Phylogenetic likelihood tree builder with topology optimization
#[derive(Debug, Clone)]
pub struct LikelihoodTreeBuilder {
/// Model type
pub model: SubstitutionModel,
/// Rate matrix (Q matrix)
pub rate_matrix: Vec<Vec<f64>>,
/// Transition probabilities cache: (edge_length, matrix)
pub p_matrix_cache: Vec<(f64, Vec<Vec<f64>>)>,
/// Edge lengths
pub edge_lengths: HashMap<String, f64>,
/// Likelihood score
pub likelihood: f64,
/// Tree topology
pub tree_nodes: Vec<TreeNode>,
/// Root node index
pub root_idx: usize,
}
/// Result of topology search
#[derive(Debug, Clone)]
pub struct TopologySearchResult {
/// Number of improvements found
pub improvements: usize,
/// Final likelihood score
pub final_likelihood: f64,
/// Initial likelihood score
pub initial_likelihood: f64,
/// Likelihood improvement
pub improvement_delta: f64,
/// Algorithm used
pub algorithm: String,
/// Number of iterations
pub iterations: usize,
}
impl LikelihoodTreeBuilder {
/// Create new likelihood tree builder with model
pub fn new(model: SubstitutionModel) -> Result<Self> {
let rate_matrix = match model {
SubstitutionModel::JukesCantor => Self::jukes_cantor_matrix(),
SubstitutionModel::Kimura2P => Self::kimura2p_matrix(),
SubstitutionModel::GTR => Self::gtr_matrix(),
SubstitutionModel::HKY => Self::hky_matrix(),
};
Ok(LikelihoodTreeBuilder {
model,
rate_matrix,
p_matrix_cache: vec![],
edge_lengths: HashMap::new(),
likelihood: 0.0,
tree_nodes: vec![],
root_idx: 0,
})
}
/// Get Jukes-Cantor rate matrix (uniform base frequencies, single rate)
fn jukes_cantor_matrix() -> Vec<Vec<f64>> {
// JC model: all rates equal, rate = α
let alpha = 1.0;
let beta = -alpha / 3.0;
vec![
vec![beta, alpha / 3.0, alpha / 3.0, alpha / 3.0],
vec![alpha / 3.0, beta, alpha / 3.0, alpha / 3.0],
vec![alpha / 3.0, alpha / 3.0, beta, alpha / 3.0],
vec![alpha / 3.0, alpha / 3.0, alpha / 3.0, beta],
]
}
/// Get Kimura 2-Parameter rate matrix
fn kimura2p_matrix() -> Vec<Vec<f64>> {
// K2P: transition rate (κ) and transversion rate (1)
let kappa = 2.0; // Transition/transversion ratio
let beta = -(2.0 * kappa + 1.0) / 4.0;
vec![
vec![beta, kappa, 1.0, 1.0], // A
vec![kappa, beta, 1.0, 1.0], // C
vec![1.0, 1.0, beta, kappa], // G
vec![1.0, 1.0, kappa, beta], // T
]
}
/// Get GTR rate matrix (most complex)
fn gtr_matrix() -> Vec<Vec<f64>> {
// GTR uses 6 parameters: r_ac, r_ag, r_at, r_cg, r_ct, r_gt
let r_ac = 1.0;
let r_ag = 5.0;
let r_at = 1.0;
let r_cg = 1.0;
let r_ct = 10.0;
let r_gt = 1.0;
let pi = [0.25, 0.25, 0.25, 0.25]; // Uniform base frequencies
let beta = -(r_ac * pi[1] + r_ag * pi[2] + r_at * pi[3]) / pi[0];
vec![
vec![beta, r_ac * pi[1], r_ag * pi[2], r_at * pi[3]],
vec![r_ac * pi[0], -(r_ac * pi[0] + r_cg * pi[2] + r_ct * pi[3]) / pi[1], r_cg * pi[2], r_ct * pi[3]],
vec![r_ag * pi[0], r_cg * pi[1], -(r_ag * pi[0] + r_cg * pi[1] + r_gt * pi[3]) / pi[2], r_gt * pi[3]],
vec![r_at * pi[0], r_ct * pi[1], r_gt * pi[2], -(r_at * pi[0] + r_ct * pi[1] + r_gt * pi[2]) / pi[3]],
]
}
/// Get HKY model rate matrix
fn hky_matrix() -> Vec<Vec<f64>> {
// HKY: like K2P but allows base frequency variation
let kappa = 2.0;
let pi = [0.25, 0.25, 0.25, 0.25];
let beta_a = -(kappa * pi[2] + pi[1] + pi[3]) / pi[0];
let beta_c = -(pi[0] + pi[2] + kappa * pi[3]) / pi[1];
let beta_g = -(kappa * pi[0] + pi[1] + pi[3]) / pi[2];
let beta_t = -(pi[0] + kappa * pi[1] + pi[2]) / pi[3];
vec![
vec![beta_a, pi[1], kappa * pi[2], pi[3]],
vec![pi[0], beta_c, pi[2], kappa * pi[3]],
vec![kappa * pi[0], pi[1], beta_g, pi[3]],
vec![pi[0], kappa * pi[1], pi[2], beta_t],
]
}
/// Compute transition probability matrix for given edge length (time)
pub fn p_matrix(&mut self, t: f64) -> Result<Vec<Vec<f64>>> {
// Check cache first - linear search for f64 value
for (cached_t, p) in &self.p_matrix_cache {
if (cached_t - t).abs() < 1e-10 {
return Ok(p.clone());
}
}
// For JC: P(t) = 1/4 + 3/4 * exp(-4αt/3)
let mut p = vec![vec![0.0; 4]; 4];
match self.model {
SubstitutionModel::JukesCantor => {
let exp_term = (-4.0 * t / 3.0).exp();
let diag = 0.25 + 0.75 * exp_term;
let off_diag = 0.25 - 0.25 * exp_term;
for i in 0..4 {
for j in 0..4 {
p[i][j] = if i == j { diag } else { off_diag };
}
}
}
SubstitutionModel::Kimura2P => {
// K2P transition probabilities
let kappa = 2.0;
let exp_term1 = (-t * (kappa + 2.0) / 4.0).exp();
let exp_term2 = (-t / 2.0).exp();
for i in 0..4 {
for j in 0..4 {
if i == j {
p[i][j] = 0.25 + 0.25 * exp_term2 + 0.5 * exp_term1;
} else if (i == 0 && j == 2) || (i == 1 && j == 3) ||
(i == 2 && j == 0) || (i == 3 && j == 1) {
// Transitions
p[i][j] = 0.25 + 0.25 * exp_term2 - 0.5 * exp_term1;
} else {
// Transversions
p[i][j] = 0.25 - 0.25 * exp_term2;
}
}
}
}
_ => {
// For other models, use matrix exponential approximation
for i in 0..4 {
for j in 0..4 {
if i == j {
p[i][j] = 1.0 + t * self.rate_matrix[i][j];
} else {
p[i][j] = t * self.rate_matrix[i][j];
}
}
}
}
}
self.p_matrix_cache.push((t, p.clone()));
Ok(p)
}
/// Compute log-likelihood of sequences under the model
pub fn likelihood_score(&mut self, seq1: &str, seq2: &str, edge_length: f64) -> Result<f64> {
let p = self.p_matrix(edge_length)?;
let mut log_likelihood = 0.0;
for (c1, c2) in seq1.chars().zip(seq2.chars()) {
let idx1 = nucleotide_to_index(c1);
let idx2 = nucleotide_to_index(c2);
if idx1 < 4 && idx2 < 4 {
if p[idx1][idx2] > 0.0 {
log_likelihood += p[idx1][idx2].ln();
}
}
}
self.likelihood = log_likelihood;
Ok(log_likelihood)
}
/// Optimize edge length using golden section search
pub fn optimize_edge_length(
&mut self,
seq1: &str,
seq2: &str,
) -> Result<f64> {
let mut lower = 0.0001;
let mut upper = 1.0;
// Golden ratio
let phi = 0.381966;
for _ in 0..10 {
let x1 = lower + (1.0 - phi) * (upper - lower);
let x2 = lower + phi * (upper - lower);
let l1 = self.likelihood_score(seq1, seq2, x1)?;
let l2 = self.likelihood_score(seq1, seq2, x2)?;
if l1 > l2 {
upper = x2;
} else {
lower = x1;
}
}
let optimal = (lower + upper) / 2.0;
self.edge_lengths.insert(format!("{}_{}", seq1, seq2), optimal);
Ok(optimal)
}
/// Perform Nearest Neighbor Interchange (NNI) topology optimization
///
/// Explores tree topology by swapping subtrees around internal edges.
/// Continues until no further improvements found (local optimum).
///
/// Complexity: O(n²) swaps per iteration, typically converges in 5-10 iterations
///
/// # Returns
/// TopologySearchResult with improvements, final likelihood, and iterations
pub fn optimize_topology_nni(&mut self) -> Result<TopologySearchResult> {
let initial_likelihood = self.compute_tree_likelihood()?;
let mut current_likelihood = initial_likelihood;
let mut improvements = 0;
let mut iterations = 0;
let mut improved = true;
while improved && iterations < 100 {
improved = false;
iterations += 1;
// For each internal node (non-leaf)
let node_count = self.tree_nodes.len();
for node_idx in 0..node_count {
if self.tree_nodes[node_idx].children.len() < 2 {
continue; // Skip leaves and degree-1 nodes
}
// For each internal edge, try NNI swaps
let children = self.tree_nodes[node_idx].children.clone();
for swap_idx in 0..children.len() {
for other_idx in (swap_idx + 1)..children.len() {
let child_a = children[swap_idx];
let child_b = children[other_idx];
// Save original edge lengths
let orig_len_a = self.tree_nodes[child_a].branch_length;
let orig_len_b = self.tree_nodes[child_b].branch_length;
// Perform NNI swap: exchange subtrees child_a and child_b
self.tree_nodes[node_idx].children[swap_idx] = child_b;
self.tree_nodes[node_idx].children[other_idx] = child_a;
// Compute new likelihood
let new_likelihood = self.compute_tree_likelihood()?;
if new_likelihood > current_likelihood + 1e-10 {
// Accept swap - improvement found
current_likelihood = new_likelihood;
improvements += 1;
improved = true;
} else {
// Revert swap - no improvement
self.tree_nodes[node_idx].children[swap_idx] = child_a;
self.tree_nodes[node_idx].children[other_idx] = child_b;
self.tree_nodes[child_a].branch_length = orig_len_a;
self.tree_nodes[child_b].branch_length = orig_len_b;
}
}
}
}
}
self.likelihood = current_likelihood;
Ok(TopologySearchResult {
improvements,
final_likelihood: current_likelihood,
initial_likelihood,
improvement_delta: current_likelihood - initial_likelihood,
algorithm: "NNI (Nearest Neighbor Interchange)".to_string(),
iterations,
})
}
/// Perform Subtree Pruning and Regrafting (SPR) topology optimization
///
/// More comprehensive than NNI: removes subtrees from one location
/// and reattaches to another. Explores larger space of tree topologies.
///
/// Complexity: O(n³) swaps per iteration, slower but more thorough
///
/// # Returns
/// TopologySearchResult with improvements, final likelihood, and iterations
pub fn optimize_topology_spr(&mut self) -> Result<TopologySearchResult> {
let initial_likelihood = self.compute_tree_likelihood()?;
let mut current_likelihood = initial_likelihood;
let mut improvements = 0;
let mut iterations = 0;
let mut improved = true;
while improved && iterations < 50 {
improved = false;
iterations += 1;
let node_count = self.tree_nodes.len();
// For each node that could be pruned
for prune_node in 0..node_count {
// Skip root and leaves with no proper subtree
if self.tree_nodes[prune_node].children.is_empty() {
continue;
}
if let Some(parent_idx) = self.tree_nodes[prune_node].parent {
// Save original structure
let orig_parent_children = self.tree_nodes[parent_idx].children.clone();
let prune_branch_len = self.tree_nodes[prune_node].branch_length;
// Detach subtree at prune_node
if let Some(pos) = self.tree_nodes[parent_idx].children.iter().position(|&x| x == prune_node) {
self.tree_nodes[parent_idx].children.remove(pos);
}
// Try reattaching at each other location
for attach_node in 0..node_count {
if attach_node == prune_node || attach_node == parent_idx {
continue; // Skip same or parent location
}
// Attach to new location
self.tree_nodes[attach_node].children.push(prune_node);
self.tree_nodes[prune_node].parent = Some(attach_node);
// Compute new likelihood
let new_likelihood = self.compute_tree_likelihood()?;
if new_likelihood > current_likelihood + 1e-10 {
// Accept reattachment
current_likelihood = new_likelihood;
improvements += 1;
improved = true;
} else {
// Revert reattachment
if let Some(pos) = self.tree_nodes[attach_node].children.iter().position(|&x| x == prune_node) {
self.tree_nodes[attach_node].children.remove(pos);
}
self.tree_nodes[prune_node].parent = Some(parent_idx);
}
}
// Restore original if no improvement found
if !improved {
self.tree_nodes[parent_idx].children = orig_parent_children;
self.tree_nodes[prune_node].branch_length = prune_branch_len;
}
}
}
}
self.likelihood = current_likelihood;
Ok(TopologySearchResult {
improvements,
final_likelihood: current_likelihood,
initial_likelihood,
improvement_delta: current_likelihood - initial_likelihood,
algorithm: "SPR (Subtree Pruning and Regrafting)".to_string(),
iterations,
})
}
/// Compute overall tree likelihood by traversing all edges
pub fn compute_tree_likelihood(&mut self) -> Result<f64> {
let mut total_likelihood = 0.0;
for node in &self.tree_nodes {
for &child_idx in &node.children {
if child_idx < self.tree_nodes.len() {
let child = &self.tree_nodes[child_idx];
// Simplified: assume we have test sequences
total_likelihood += child.branch_length.ln().max(-100.0);
}
}
}
self.likelihood = total_likelihood;
Ok(total_likelihood)
}
/// Build tree from sequences using neighbor joining with topology optimization
pub fn build_tree_neighbor_joining(
&mut self,
sequences: &[&str],
optimize: bool,
) -> Result<TopologySearchResult> {
// Initialize leaf nodes
self.tree_nodes.clear();
for (idx, seq) in sequences.iter().enumerate() {
self.tree_nodes.push(TreeNode {
id: idx,
label: Some(seq.to_string()),
branch_length: 0.0,
children: vec![],
parent: None,
});
}
if optimize {
// Apply NNI optimization to improve initial tree
self.optimize_topology_nni()
} else {
Ok(TopologySearchResult {
improvements: 0,
final_likelihood: self.compute_tree_likelihood()?,
initial_likelihood: 0.0,
improvement_delta: 0.0,
algorithm: "No optimization".to_string(),
iterations: 0,
})
}
}
/// Get model name
pub fn model_name(&self) -> &'static str {
match self.model {
SubstitutionModel::JukesCantor => "Jukes-Cantor",
SubstitutionModel::Kimura2P => "Kimura 2-Parameter",
SubstitutionModel::GTR => "General Time Reversible",
SubstitutionModel::HKY => "HKY",
}
}
}
/// Convert nucleotide character to matrix index (0=A, 1=C, 2=G, 3=T)
fn nucleotide_to_index(c: char) -> usize {
match c.to_ascii_uppercase() {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => 4,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_likelihood_builder_creation() {
let builder = LikelihoodTreeBuilder::new(SubstitutionModel::JukesCantor).unwrap();
assert_eq!(builder.model_name(), "Jukes-Cantor");
assert_eq!(builder.rate_matrix.len(), 4);
}
#[test]
fn test_topology_search_result_creation() {
let result = TopologySearchResult {
improvements: 5,
final_likelihood: -50.5,
initial_likelihood: -60.0,
improvement_delta: 9.5,
algorithm: "NNI".to_string(),
iterations: 3,
};
assert_eq!(result.improvements, 5);
assert!(result.improvement_delta > 0.0);
}
#[test]
fn test_tree_node_creation() {
let node = TreeNode {
id: 0,
label: Some("A".to_string()),
branch_length: 0.1,
children: vec![1, 2],
parent: None,
};
assert_eq!(node.id, 0);
assert_eq!(node.children.len(), 2);
assert!(node.parent.is_none());
}
#[test]
fn test_nni_convergence() -> Result<()> {
let mut builder = LikelihoodTreeBuilder::new(SubstitutionModel::JukesCantor)?;
// Initialize minimal tree
builder.tree_nodes = vec![
TreeNode {
id: 0,
label: Some("A".to_string()),
branch_length: 0.1,
children: vec![1, 2],
parent: None,
},
TreeNode {
id: 1,
label: Some("B".to_string()),
branch_length: 0.1,
children: vec![],
parent: Some(0),
},
TreeNode {
id: 2,
label: Some("C".to_string()),
branch_length: 0.1,
children: vec![],
parent: Some(0),
},
];
let result = builder.optimize_topology_nni()?;
assert!(result.iterations <= 100);
assert!(result.final_likelihood.is_finite());
Ok(())
}
#[test]
fn test_spr_convergence() -> Result<()> {
let mut builder = LikelihoodTreeBuilder::new(SubstitutionModel::Kimura2P)?;
// Initialize minimal tree
builder.tree_nodes = vec![
TreeNode {
id: 0,
label: Some("A".to_string()),
branch_length: 0.1,
children: vec![1, 2],
parent: None,
},
TreeNode {
id: 1,
label: Some("B".to_string()),
branch_length: 0.1,
children: vec![],
parent: Some(0),
},
TreeNode {
id: 2,
label: Some("C".to_string()),
branch_length: 0.1,
children: vec![],
parent: Some(0),
},
];
let result = builder.optimize_topology_spr()?;
assert!(result.iterations <= 50);
assert!(result.final_likelihood.is_finite());
Ok(())
}
}