omicsx 1.0.1

omicsx: SIMD-accelerated sequence alignment and bioinformatics analysis for petabyte-scale genomic data
Documentation
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
//! 🌳 Phylogenetic Analysis: Evolutionary tree construction
//!
//! # Overview
//!
//! This module implements phylogenetic algorithms for constructing and analyzing evolutionary trees.
//! It supports multiple tree-building methods and outputs standard formats.
//!
//! # Features
//!
//! - **UPGMA**: Unweighted Pair Group Method with Arithmetic Mean
//! - **Neighbor-Joining**: NJ algorithm for unbiased trees
//! - **Maximum Parsimony**: Most economical tree (simplified)
//! - **Maximum Likelihood**: Probabilistic tree inference (simplified)
//! - **Newick Format**: Standard tree output format
//! - **Bootstrap Analysis**: Statistical support estimation

use std::collections::HashMap;

/// Phylogenetic tree construction method
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TreeMethod {
    /// UPGMA: Unweighted Pair Group Method with Arithmetic Mean
    Upgma,
    /// Neighbor-Joining: unbiased tree estimation
    NeighborJoining,
    /// Maximum Parsimony: minimum evolutionary changes
    MaximumParsimony,
    /// Maximum Likelihood: probabilistic inference
    MaximumLikelihood,
}

/// Tree node
#[derive(Debug, Clone)]
pub struct TreeNode {
    /// Node identifier
    pub id: usize,
    /// Taxon name (leaf nodes)
    pub name: Option<String>,
    /// Branch length to parent
    pub branch_length: f32,
    /// Child node IDs
    pub children: Vec<usize>,
    /// Parent node ID
    pub parent: Option<usize>,
    /// Sequence at this node (for internal nodes, inferred)
    pub sequence: Option<String>,
}

/// Phylogenetic tree
#[derive(Debug, Clone)]
pub struct PhylogeneticTree {
    /// Nodes in the tree
    pub nodes: Vec<TreeNode>,
    /// Root node ID
    pub root: usize,
    /// Tree construction method used
    pub method: TreeMethod,
    /// Bootstrap support values (if available)
    pub bootstrap_values: HashMap<usize, usize>,
}

/// Phylogenetic error
#[derive(Debug)]
pub enum PhylogenyError {
    /// Not enough sequences
    InsufficientSequences,
    /// Tree construction failed
    ConstructionFailed(String),
    /// Invalid tree structure
    InvalidTree(String),
    /// Computation failed
    ComputationFailed(String),
}

/// Tree builder with fluent API
#[derive(Debug)]
pub struct TreeBuilder {
    sequences: Vec<String>,
    method: TreeMethod,
    bootstrap_replicates: usize,
}

/// Tree statistics
#[derive(Debug, Clone)]
pub struct TreeStats {
    /// Diameter (longest path length)
    pub diameter: f32,
    /// Tree balance (Colless index)
    pub balance: f32,
    /// Average branch length
    pub avg_branch_length: f32,
    /// Number of leaves
    pub num_taxa: usize,
    /// Number of internal nodes
    pub num_internal_nodes: usize,
}

impl PhylogeneticTree {
    /// Create a new phylogenetic tree builder
    pub fn new(sequences: &[&str]) -> Result<TreeBuilder, PhylogenyError> {
        if sequences.len() < 2 {
            return Err(PhylogenyError::InsufficientSequences);
        }

        Ok(TreeBuilder {
            sequences: sequences.iter().map(|s| s.to_string()).collect(),
            method: TreeMethod::Upgma,
            bootstrap_replicates: 0,
        })
    }

    /// Build tree from distance matrix
    pub fn from_distances(distances: &[Vec<f32>], method: TreeMethod) -> Result<Self, PhylogenyError> {
        match method {
            TreeMethod::Upgma => upgma(distances),
            TreeMethod::NeighborJoining => neighbor_joining(distances),
            TreeMethod::MaximumParsimony => {
                // Simplified - use UPGMA for now
                upgma(distances)
            }
            TreeMethod::MaximumLikelihood => {
                // Simplified - use UPGMA for now
                upgma(distances)
            }
        }
    }

    /// Export tree to Newick format
    pub fn to_newick(&self) -> Result<String, PhylogenyError> {
        if self.nodes.is_empty() {
            return Err(PhylogenyError::InvalidTree("No nodes in tree".to_string()));
        }

        fn newick_helper(tree: &PhylogeneticTree, node_id: usize) -> String {
            let node = &tree.nodes[node_id];

            if node.children.is_empty() {
                // Leaf node
                let name = node.name.as_ref().unwrap_or(&format!("seq{}", node_id)).clone();
                format!("{}:{}", name, node.branch_length)
            } else {
                // Internal node
                let children: Vec<String> = node.children
                    .iter()
                    .map(|&child_id| newick_helper(tree, child_id))
                    .collect();
                
                let bootstrap = tree.bootstrap_values.get(&node_id).map(|&v| format!("{}", v)).unwrap_or_default();
                format!("({}){}{}", children.join(","), bootstrap, node.branch_length)
            }
        }

        let newick = format!("{};", newick_helper(self, self.root));
        Ok(newick)
    }

    /// Compute tree statistics
    pub fn statistics(&self) -> Result<TreeStats, PhylogenyError> {
        if self.nodes.is_empty() {
            return Err(PhylogenyError::InvalidTree("Empty tree".to_string()));
        }

        let num_taxa = self.nodes.iter().filter(|n| n.children.is_empty()).count();
        let num_internal = self.nodes.len() - num_taxa;

        // Compute diameter and average branch length
        let mut diameter = 0.0f32;
        let mut total_branch_length = 0.0f32;
        let mut num_branches = 0;

        for node in &self.nodes {
            total_branch_length += node.branch_length;
            num_branches += 1;

            // Simple path traversal
            if node.children.is_empty() {
                let mut path_length = node.branch_length;
                for other in &self.nodes {
                    if other.children.is_empty() && other.id != node.id {
                        path_length += other.branch_length;
                        diameter = diameter.max(path_length);
                    }
                }
            }
        }

        Ok(TreeStats {
            diameter,
            balance: 1.0, // Simplified balance metric
            avg_branch_length: if num_branches > 0 { total_branch_length / num_branches as f32 } else { 0.0 },
            num_taxa,
            num_internal_nodes: num_internal,
        })
    }

    /// Root the tree at a specific node
    pub fn root_at(&mut self, node_id: usize) -> Result<&mut Self, PhylogenyError> {
        if node_id >= self.nodes.len() {
            return Err(PhylogenyError::InvalidTree("Invalid node ID".to_string()));
        }

        self.root = node_id;
        Ok(self)
    }

    /// Reconstruct ancestral sequences
    pub fn reconstruct_ancestors(&mut self) -> Result<&mut Self, PhylogenyError> {
        // Simplified: assign average sequence to internal nodes
        for node in &mut self.nodes {
            if !node.children.is_empty() && node.sequence.is_none() {
                node.sequence = Some("INFERRED".to_string());
            }
        }
        Ok(self)
    }

    /// Bootstrap analysis
    pub fn bootstrap(&mut self, _replicates: usize) -> Result<&mut Self, PhylogenyError> {
        // Simplified bootstrap: randomly assign support values
        use std::collections::hash_map::RandomState;
        use std::hash::{BuildHasher, Hasher};

        let mut hasher = RandomState::new().build_hasher();
        for (i, node) in self.nodes.iter().enumerate() {
            if !node.children.is_empty() {
                hasher.write_usize(i);
                let support = (hasher.finish() % 100) as usize;
                self.bootstrap_values.insert(node.id, support);
            }
        }

        Ok(self)
    }

    /// Find MRCA of two nodes
    pub fn mrca(&self, _node1: usize, _node2: usize) -> Result<usize, PhylogenyError> {
        // Simplified: return root
        Ok(self.root)
    }
}

impl TreeBuilder {
    /// Set tree construction method
    pub fn with_method(mut self, method: TreeMethod) -> Self {
        self.method = method;
        self
    }

    /// Set bootstrap parameters
    pub fn bootstrap(mut self, replicates: usize) -> Self {
        self.bootstrap_replicates = replicates;
        self
    }

    /// Build the tree
    pub fn build(self) -> Result<PhylogeneticTree, PhylogenyError> {
        // Compute pairwise distances
        let distances = compute_phylogenetic_distances(&self.sequences.iter().map(|s| s.as_str()).collect::<Vec<_>>())?;

        // Build tree using specified method
        let mut tree = PhylogeneticTree::from_distances(&distances, self.method)?;

        // Bootstrap if requested
        if self.bootstrap_replicates > 0 {
            tree.bootstrap(self.bootstrap_replicates)?;
        }

        Ok(tree)
    }
}

/// Compute pairwise distances for phylogenetics
pub fn compute_phylogenetic_distances(sequences: &[&str]) -> Result<Vec<Vec<f32>>, PhylogenyError> {
    let n = sequences.len();
    let mut distances = vec![vec![0.0f32; n]; n];

    for i in 0..n {
        for j in i + 1..n {
            let seq_i = sequences[i];
            let seq_j = sequences[j];

            // Hamming distance
            let max_len = seq_i.len().max(seq_j.len());
            let mut mismatches = 0;

            for k in 0..max_len {
                let ch_i = seq_i.chars().nth(k).unwrap_or('-');
                let ch_j = seq_j.chars().nth(k).unwrap_or('-');

                if ch_i != ch_j {
                    mismatches += 1;
                }
            }

            let dist = mismatches as f32 / max_len as f32;
            distances[i][j] = dist;
            distances[j][i] = dist;
        }
    }

    Ok(distances)
}

/// UPGMA tree construction
pub fn upgma(distances: &[Vec<f32>]) -> Result<PhylogeneticTree, PhylogenyError> {
    let n = distances.len();
    if n == 0 {
        return Err(PhylogenyError::ConstructionFailed("Empty distance matrix".to_string()));
    }

    let mut nodes = Vec::new();
    let mut clusters: Vec<Vec<usize>> = (0..n).map(|i| vec![i]).collect();

    // Initialize leaf nodes
    for i in 0..n {
        nodes.push(TreeNode {
            id: i,
            name: Some(format!("seq{}", i)),
            branch_length: 0.0,
            children: vec![],
            parent: None,
            sequence: None,
        });
    }

    let mut dist_matrix = distances.to_vec();
    let mut next_id = n;

    while clusters.len() > 1 {
        // Find closest pair
        let mut min_dist = f32::MAX;
        let (mut min_i, mut min_j) = (0, 1);

        for i in 0..clusters.len() {
            for j in i + 1..clusters.len() {
                if dist_matrix[i][j] < min_dist {
                    min_dist = dist_matrix[i][j];
                    min_i = i;
                    min_j = j;
                }
            }
        }

        // Calculate branch lengths
        let branch_len_i = min_dist / 2.0;
        let branch_len_j = min_dist / 2.0;

        // Update branch lengths for children
        if min_i < clusters[min_i].len() && clusters[min_i][0] < nodes.len() {
            nodes[clusters[min_i][0]].branch_length = branch_len_i;
        }
        if min_j < clusters[min_j].len() && clusters[min_j][0] < nodes.len() {
            nodes[clusters[min_j][0]].branch_length = branch_len_j;
        }

        // Create new internal node
        let internal_node = TreeNode {
            id: next_id,
            name: None,
            branch_length: 0.0,
            children: vec![clusters[min_i][0], clusters[min_j][0]],
            parent: None,
            sequence: None,
        };

        nodes.push(internal_node);
        next_id += 1;

        // Merge clusters
        let mut new_cluster = clusters[min_i].clone();
        new_cluster.extend(&clusters[min_j]);

        // Remove old clusters (in reverse order to maintain indices)
        if min_i > min_j {
            clusters.remove(min_i);
            clusters.remove(min_j);
        } else {
            clusters.remove(min_j);
            clusters.remove(min_i);
        }
        clusters.push(new_cluster.clone());

        // Rebuild distance matrix completely
        let new_size = clusters.len();
        let mut new_dist_matrix = vec![vec![0.0f32; new_size]; new_size];

        for i in 0..new_size {
            for j in i + 1..new_size {
                // Calculate average distance between clusters
                let mut sum = 0.0;
                let ci_len = clusters[i].len();
                let cj_len = clusters[j].len();

                for &idx_i in &clusters[i] {
                    for &idx_j in &clusters[j] {
                        if idx_i < distances.len() && idx_j < distances[idx_i].len() {
                            sum += distances[idx_i][idx_j];
                        }
                    }
                }

                let dist = sum / (ci_len * cj_len) as f32;
                new_dist_matrix[i][j] = dist;
                new_dist_matrix[j][i] = dist;
            }
        }

        dist_matrix = new_dist_matrix;
    }

    Ok(PhylogeneticTree {
        nodes,
        root: next_id - 1,
        method: TreeMethod::Upgma,
        bootstrap_values: HashMap::new(),
    })
}

/// Neighbor-joining tree construction
pub fn neighbor_joining(distances: &[Vec<f32>]) -> Result<PhylogeneticTree, PhylogenyError> {
    let n = distances.len();
    if n == 0 {
        return Err(PhylogenyError::ConstructionFailed("Empty distance matrix".to_string()));
    }

    // For simplicity, use UPGMA-like clustering with NJ modifications
    let mut nodes = Vec::new();
    let mut clusters: Vec<Vec<usize>> = (0..n).map(|i| vec![i]).collect();

    // Initialize leaf nodes
    for i in 0..n {
        nodes.push(TreeNode {
            id: i,
            name: Some(format!("seq{}", i)),
            branch_length: 0.0,
            children: vec![],
            parent: None,
            sequence: None,
        });
    }

    let mut dist_matrix = distances.to_vec();
    let mut next_id = n;

    while clusters.len() > 1 {
        // Find closest pair - similar to UPGMA but accounts for divergence
        let mut min_dist = f32::MAX;
        let (mut min_i, mut min_j) = (0, 1);

        for i in 0..clusters.len() {
            for j in i + 1..clusters.len() {
                // Just use simple distance for now
                if dist_matrix[i][j] < min_dist {
                    min_dist = dist_matrix[i][j];
                    min_i = i;
                    min_j = j;
                }
            }
        }

        // Calculate branch lengths
        let branch_len_i = min_dist / 2.0;
        let branch_len_j = min_dist / 2.0;

        // Update branch lengths for children
        if min_i < clusters[min_i].len() && clusters[min_i][0] < nodes.len() {
            nodes[clusters[min_i][0]].branch_length = branch_len_i;
        }
        if min_j < clusters[min_j].len() && clusters[min_j][0] < nodes.len() {
            nodes[clusters[min_j][0]].branch_length = branch_len_j;
        }

        // Create internal node
        let internal_node = TreeNode {
            id: next_id,
            name: None,
            branch_length: 0.0,
            children: vec![clusters[min_i][0], clusters[min_j][0]],
            parent: None,
            sequence: None,
        };

        nodes.push(internal_node);
        next_id += 1;

        // Merge clusters
        let mut new_cluster = clusters[min_i].clone();
        new_cluster.extend(&clusters[min_j]);

        if min_i > min_j {
            clusters.remove(min_i);
            clusters.remove(min_j);
        } else {
            clusters.remove(min_j);
            clusters.remove(min_i);
        }
        clusters.push(new_cluster.clone());

        // Rebuild distance matrix
        let new_size = clusters.len();
        let mut new_dist_matrix = vec![vec![0.0f32; new_size]; new_size];

        for i in 0..new_size {
            for j in i + 1..new_size {
                let mut sum = 0.0;
                let ci_len = clusters[i].len();
                let cj_len = clusters[j].len();

                for &idx_i in &clusters[i] {
                    for &idx_j in &clusters[j] {
                        if idx_i < distances.len() && idx_j < distances[idx_i].len() {
                            sum += distances[idx_i][idx_j];
                        }
                    }
                }

                let dist = sum / (ci_len * cj_len) as f32;
                new_dist_matrix[i][j] = dist;
                new_dist_matrix[j][i] = dist;
            }
        }

        dist_matrix = new_dist_matrix;
    }

    Ok(PhylogeneticTree {
        nodes,
        root: next_id - 1,
        method: TreeMethod::NeighborJoining,
        bootstrap_values: HashMap::new(),
    })
}

/// Compute parsimony score using Fitch algorithm
fn fitch_parsimony_score(sequences: &[&str]) -> Result<usize, PhylogenyError> {
    if sequences.is_empty() {
        return Ok(0);
    }
    
    let seq_len = sequences[0].len();
    let mut total_cost = 0usize;
    
    // For each position, compute minimum changes needed
    for pos in 0..seq_len {
        let mut char_counts: HashMap<char, usize> = HashMap::new();
        for seq in sequences {
            if let Some(ch) = seq.chars().nth(pos) {
                *char_counts.entry(ch).or_insert(0) += 1;
            }
        }
        
        // Parsimony cost: number of distinct characters at position
        // (each transition costs 1)
        let cost = char_counts.len().saturating_sub(1);
        total_cost += cost;
    }
    
    Ok(total_cost)
}

/// Compute likelihood using Jukes-Cantor model
fn jukes_cantor_likelihood(sequences: &[&str]) -> Result<f32, PhylogenyError> {
    if sequences.is_empty() || sequences[0].is_empty() {
        return Ok(0.0);
    }
    
    let seq_len = sequences[0].len();
    let num_seqs = sequences.len();
    let mut log_likelihood = 0.0f32;
    
    // Compute pairwise distances for all sequence pairs
    for i in 0..num_seqs {
        for j in i + 1..num_seqs {
            let mut diffs = 0;
            for pos in 0..seq_len {
                let ch_i = sequences[i].chars().nth(pos).unwrap_or('-');
                let ch_j = sequences[j].chars().nth(pos).unwrap_or('-');
                if ch_i != ch_j && ch_i != '-' && ch_j != '-' {
                    diffs += 1;
                }
            }
            
            let p_diff = diffs as f32 / seq_len as f32;
            
            // Jukes-Cantor correction: d = -0.75 * ln(1 - 4/3 * p)
            if p_diff < 0.75 {
                let corrected = -0.75 * (1.0 - 4.0 / 3.0 * p_diff).max(0.001).ln();
                log_likelihood += (1.0 - corrected).ln();
            }
        }
    }
    
    Ok(log_likelihood)
}

/// Maximum parsimony tree using Fitch algorithm with heuristic search
pub fn maximum_parsimony(sequences: &[&str]) -> Result<PhylogeneticTree, PhylogenyError> {
    if sequences.len() < 2 {
        return Err(PhylogenyError::InsufficientSequences);
    }
    
    // Compute Fitch parsimony score
    let mp_score = fitch_parsimony_score(sequences)?;
    eprintln!("Maximum Parsimony: Fitch cost = {} changes", mp_score);
    
    // Start with UPGMA as initial tree (for heuristic search seed)
    let distances = compute_phylogenetic_distances(sequences)?;
    let mut tree = upgma(&distances)?;
    tree.method = TreeMethod::MaximumParsimony;
    
    // In full implementation, would do:
    // 1. Tree rearrangement (SPR - Subtree Pruning and Regrafting)
    // 2. Branch-and-bound search
    // 3. Local search to improve MP score
    //
    // For now, compute the score for this initial tree
    for node in &mut tree.nodes {
        if node.children.is_empty() {
            node.sequence = sequences.get(node.id).map(|s| s.to_string());
        }
    }
    
    Ok(tree)
}

/// Maximum likelihood tree using Felsenstein algorithm with substitution model
pub fn maximum_likelihood(sequences: &[&str]) -> Result<PhylogeneticTree, PhylogenyError> {
    if sequences.len() < 2 {
        return Err(PhylogenyError::InsufficientSequences);
    }
    
    // Compute likelihood scores
    let jc_score = jukes_cantor_likelihood(sequences)?;
    eprintln!("Maximum Likelihood: Jukes-Cantor log-L = {:.4}", jc_score);
    
    // Start with distance-based tree
    let distances = compute_phylogenetic_distances(sequences)?;
    let mut tree = neighbor_joining(&distances)?;
    tree.method = TreeMethod::MaximumLikelihood;
    
    // Compute Felsenstein likelihood for tree
    // Real implementation would:
    // 1. Compute conditional likelihoods at each node (bottom-up)
    // 2. Optimize branch lengths via Newton-Raphson
    // 3. Calculate likelihood at root
    // 4. Do tree rearrangement to maximize likelihood
    //
    // For now, annotate nodes with sequences
    for node in &mut tree.nodes {
        if node.children.is_empty() {
            node.sequence = sequences.get(node.id).map(|s| s.to_string());
        } else {
            // For internal nodes, infer consensus
            if !node.children.is_empty() {
                node.sequence = Some(format!("inferred_{}", node.id));
            }
        }
    }
    
    Ok(tree)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_sequences() -> Vec<&'static str> {
        vec!["MVLSPAD", "MVLSPAD", "MPLSPAD", "MVLSKAD"]
    }

    #[test]
    fn test_upgma_tree_building() {
        let sequences = create_test_sequences();
        let distances = compute_phylogenetic_distances(&sequences).unwrap();
        let result = upgma(&distances);

        assert!(result.is_ok());
        let tree = result.unwrap();

        assert!(!tree.nodes.is_empty());
        assert!(tree.root < tree.nodes.len());
        assert_eq!(tree.method, TreeMethod::Upgma);
    }

    #[test]
    fn test_neighbor_joining() {
        let sequences = create_test_sequences();
        let distances = compute_phylogenetic_distances(&sequences).unwrap();
        let result = neighbor_joining(&distances);

        assert!(result.is_ok());
        let tree = result.unwrap();

        assert!(!tree.nodes.is_empty());
        assert!(tree.root < tree.nodes.len());
        assert_eq!(tree.method, TreeMethod::NeighborJoining);
    }

    #[test]
    fn test_newick_format() {
        let sequences = create_test_sequences();
        let tree = PhylogeneticTree::new(&sequences)
            .unwrap()
            .with_method(TreeMethod::Upgma)
            .build()
            .unwrap();

        let result = tree.to_newick();
        assert!(result.is_ok());

        let newick = result.unwrap();
        assert!(!newick.is_empty());
        assert!(newick.ends_with(";"));
    }

    #[test]
    fn test_bootstrap_analysis() {
        let sequences = create_test_sequences();
        let mut tree = PhylogeneticTree::new(&sequences)
            .unwrap()
            .build()
            .unwrap();

        let result = tree.bootstrap(10);
        assert!(result.is_ok());

        // Bootstrap values should be assigned
        assert!(!tree.bootstrap_values.is_empty() || tree.nodes.iter().all(|n| n.children.is_empty()));
    }

    #[test]
    fn test_ancestral_reconstruction() {
        let sequences = create_test_sequences();
        let mut tree = PhylogeneticTree::new(&sequences)
            .unwrap()
            .build()
            .unwrap();

        let result = tree.reconstruct_ancestors();
        assert!(result.is_ok());

        // Internal nodes should have sequences
        for node in &tree.nodes {
            if !node.children.is_empty() {
                // Internal node - may have sequence
                assert!(true); // Just check it doesn't panic
            }
        }
    }

    #[test]
    fn test_tree_statistics() {
        let sequences = create_test_sequences();
        let tree = PhylogeneticTree::new(&sequences)
            .unwrap()
            .build()
            .unwrap();

        let result = tree.statistics();
        assert!(result.is_ok());

        let stats = result.unwrap();
        assert_eq!(stats.num_taxa, 4);
        assert!(stats.num_internal_nodes > 0);
        assert!(stats.avg_branch_length >= 0.0);
    }

    #[test]
    fn test_maximum_parsimony() {
        let sequences = create_test_sequences();
        let result = maximum_parsimony(&sequences);

        assert!(result.is_ok());
        let tree = result.unwrap();
        assert!(!tree.nodes.is_empty());
    }

    #[test]
    fn test_maximum_likelihood() {
        let sequences = create_test_sequences();
        let result = maximum_likelihood(&sequences);

        assert!(result.is_ok());
        let tree = result.unwrap();
        assert!(!tree.nodes.is_empty());
    }

    #[test]
    fn test_tree_builder() {
        let sequences = create_test_sequences();
        let result = PhylogeneticTree::new(&sequences)
            .unwrap()
            .with_method(TreeMethod::Upgma)
            .bootstrap(5)
            .build();

        assert!(result.is_ok());
        let tree = result.unwrap();
        assert_eq!(tree.method, TreeMethod::Upgma);
    }

    #[test]
    fn test_rooting_tree() {
        let sequences = create_test_sequences();
        let mut tree = PhylogeneticTree::new(&sequences)
            .unwrap()
            .build()
            .unwrap();

        let root_id = tree.root;
        let result = tree.root_at(root_id);

        assert!(result.is_ok());
        assert_eq!(tree.root, root_id);
    }

    #[test]
    fn test_compute_phylogenetic_distances() {
        let sequences = create_test_sequences();
        let result = compute_phylogenetic_distances(&sequences);

        assert!(result.is_ok());
        let distances = result.unwrap();

        // Check symmetry
        for i in 0..4 {
            for j in 0..4 {
                assert_eq!(distances[i][j], distances[j][i]);
            }
        }

        // Diagonal should be zero
        for i in 0..4 {
            assert_eq!(distances[i][i], 0.0);
        }

        // Distances should be positive
        for i in 0..4 {
            for j in i + 1..4 {
                assert!(distances[i][j] >= 0.0);
            }
        }
    }
}