phylo 3.0.1

An extensible Phylogenetics library written in rust
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
use itertools::Itertools;
use num::{Zero, Float, NumCast, One};
use std::fmt::Debug;
use vers_vecs::BitVec;

#[cfg(feature = "non_crypto_hash")]
use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
#[cfg(not(feature = "non_crypto_hash"))]
use std::collections::{HashMap, HashSet};

#[cfg(feature = "parallel")]
use rayon::prelude::*;

use crate::prelude::*;

/// A type alias for zeta annotation of a node in a tree.
pub type TreeNodeZeta<T> = <<T as RootedTree>::Node as RootedZetaNode>::Zeta;

/// A trait describing the path functions in a tree.
pub trait PathFunction: RootedTree
where
    <Self as RootedTree>::Node: RootedZetaNode,
{
    /// Sets zeta value of all nodes in a tree by function
    fn set_zeta(
        &mut self,
        zeta_func: fn(&Self, TreeNodeID<Self>) -> TreeNodeZeta<Self>,
    ) -> Option<()> {
        let node_ids = self.get_node_ids().collect_vec();
        for node_id in node_ids {
            let zeta = zeta_func(self, node_id);
            self.set_node_zeta(node_id, Some(zeta))?;
        }
        Some(())
    }

    /// Returns zeta value of a node in a tree. None is no zeta value is set
    fn get_zeta(&self, node_id: TreeNodeID<Self>) -> Option<TreeNodeZeta<Self>> {
        self.get_node(node_id)?.get_zeta()
    }

    /// Returns true if node zeta value is not None
    fn is_zeta_set(&self, node_id: TreeNodeID<Self>) -> bool {
        self.get_node(node_id).unwrap().is_zeta_set()
    }

    /// Returns true if all node zeta value is not None    
    fn is_all_zeta_set(&self) -> bool {
        !self.get_nodes().any(|x| !x.is_zeta_set())
    }

    /// Sets zeta value of a node in a tree by value.
    fn set_node_zeta(
        &mut self,
        node_id: TreeNodeID<Self>,
        zeta: Option<TreeNodeZeta<Self>>,
    ) -> Option<()> {
        self.get_node_mut(node_id)?.set_zeta(zeta);
        Some(())
    }
}

/// A trait describing efficient computation of vertex to vertex distances
pub trait DistanceMatrix: RootedWeightedTree
where
    <Self as RootedTree>::Node: RootedWeightedNode,
{
    /// Return the symmetrical pairwise distance matrix.
    fn matrix(&self) -> Vec<Vec<TreeNodeWeight<Self>>>;

    /// Populates a pairwise distance matrix for a subtree
    fn pairwise_distance(
        &self,
        node_id_1: TreeNodeID<Self>,
        node_id_2: TreeNodeID<Self>,
    ) -> TreeNodeWeight<Self>;
}

/// A trait describing naive computation of Robinson Foulds distance
pub trait RobinsonFoulds
where
    Self: RootedTree + RootedMetaTree + Clusters,
    <Self as RootedTree>::Node: RootedMetaNode,
{
    /// Returns Robinson Foulds distance between tree and self.
    fn rf(&self, tree: &Self) -> usize {
        let mut dist = 0;
        let mut all_taxa: HashSet<&TreeNodeMeta<Self>> = self.get_taxa_space().collect();
        all_taxa.extend(tree.get_taxa_space());
        let num_taxa = all_taxa.len();
        let all_taxa_map: HashMap<&TreeNodeMeta<Self>, usize> = all_taxa
            .into_iter()
            .enumerate()
            .map(|x| (x.1, x.0))
            .collect();


        let mut self_bps: HashMap<TreeNodeID<Self>, BitVec> = vec![].into_iter().collect();
        let mut self_out_bps: HashSet<BitVec> = vec![].into_iter().collect();
        for n_id in self.postord_ids(self.get_root_id()) {
            let mut bp = BitVec::from_zeros(num_taxa);
            let mut bp_rev = BitVec::from_ones(num_taxa);
            match self.is_leaf(n_id) {
                true => {
                    let leaf_meta = self.get_node_taxa(n_id).unwrap();
                    bp.flip_bit(*all_taxa_map.get(leaf_meta).unwrap());

                    let _ = bp_rev.apply_mask_xor(&bp);
                    self_bps.insert(n_id, bp.clone());  
                    self_out_bps.insert(bp);
                    self_out_bps.insert(bp_rev);
                }
                false => {
                    if n_id==self.get_root_id(){
                        continue;
                    }
                    else{
                        self.get_node_children_ids(n_id)
                            .map(|x| self_bps.get(&x).unwrap())
                            .for_each(|x| {let _ = bp.apply_mask_or(x);});

                        let _ = bp_rev.apply_mask_xor(&bp);
                        self_bps.insert(n_id, bp.clone());
                        self_out_bps.insert(bp);
                        self_out_bps.insert(bp_rev);
                        
                    }
                }
            };
        }

        let mut tree_bps: HashMap<TreeNodeID<Self>, BitVec> = vec![].into_iter().collect();
        let mut tree_out_bps: HashSet<BitVec> = vec![].into_iter().collect();
        for n_id in tree.postord_ids(tree.get_root_id()) {
            let mut bp = BitVec::from_zeros(num_taxa);
            let mut bp_rev = BitVec::from_ones(num_taxa);

            match tree.is_leaf(n_id) {
                true => {
                    let leaf_meta = tree.get_node_taxa(n_id).unwrap();
                    bp.flip_bit(*all_taxa_map.get(leaf_meta).unwrap());

                    let _ = bp_rev.apply_mask_xor(&bp);

                    tree_bps.insert(n_id, bp.clone());
                    tree_out_bps.insert(bp);
                    tree_out_bps.insert(bp_rev);
                }
                false => {
                    if n_id==tree.get_root_id(){
                        continue;
                    }
                    else {
                        tree.get_node_children_ids(n_id)
                        .map(|x| tree_bps.get(&x).unwrap())
                        .for_each(|x| {let _ = bp.apply_mask_or(x);});    

                        let _ = bp_rev.apply_mask_xor(&bp);

                        tree_bps.insert(n_id, bp.clone());
                        tree_out_bps.insert(bp);
                        tree_out_bps.insert(bp_rev);
                    }
                }
            };
        }
        for i in self_out_bps.iter() {
            if tree_out_bps.contains(i){
                continue;                
            }
            else{
                dist += 1;
            }
        }
        for i in tree_out_bps.iter() {
            if self_out_bps.contains(i){
                continue;                
            }
            else{
                dist += 1;
            }

        }
        
        dist/2
    }
}

/// A trait describing naive computation of Cluster Matching distance
pub trait ClusterMatching
where
    Self: RootedTree + RootedMetaTree + Clusters,
    <Self as RootedTree>::Node: RootedMetaNode,
{
    /// Returns Cluster Matching distance between tree and self.
    fn cm(&self, tree: &Self) -> usize {
        let self_clusters = self
            .get_node_ids()
            .map(|node_id| {
                self.get_cluster_ids(node_id)
                    .map(|id| self.get_node_taxa(id).unwrap())
                    .collect_vec()
            })
            .collect::<HashSet<_>>();
        let tree_clusters = tree
            .get_node_ids()
            .map(|node_id| {
                tree.get_cluster_ids(node_id)
                    .map(|id| tree.get_node_taxa(id).unwrap())
                    .collect_vec()
            })
            .collect::<HashSet<_>>();

        self_clusters.difference(&tree_clusters).collect_vec().len()
            + tree_clusters.difference(&self_clusters).collect_vec().len()
    }
}

/// A trait describing computation of Cluster Affinity
pub trait ClusterAffinity
where
    Self: RootedTree + RootedMetaTree + Clusters,
    <Self as RootedTree>::Node: RootedMetaNode,
{
    /// Returns Cluster Affinity cost from self to tree..
    fn ca(&self, tree: &Self) -> usize {
    let mut dist = 0;
    let mut t1_size_map: HashMap<TreeNodeID<Self>,usize> = [].into_iter().collect::<HashMap<_,_>>();
    let mut t2_size_map: HashMap<TreeNodeID<Self>,usize> = [].into_iter().collect::<HashMap<_,_>>();
    let mut intersection_map: HashMap<(TreeNodeID<Self>,TreeNodeID<Self>),usize> = [].into_iter().collect::<HashMap<_,_>>();
    for v in self.postord_ids(self.get_root_id()){
	let mut mindist = usize::MAX;
	let vsize;
	if self.is_leaf(v){
	    vsize = 1;
	}else{
	    vsize = self.get_node_children_ids(v).map(|x| t1_size_map.get(&x).unwrap()).sum();
	}
	t1_size_map.insert(v,vsize);
	for c in tree.postord_ids(tree.get_root_id()){
	    let mut size = 0;
	    let mut intersection = 0;
	    if tree.is_leaf(c){
		size = 1;
		if self.is_leaf(v){
		    if self.get_node_taxa(v).unwrap() == tree.get_node_taxa(c).unwrap(){
			intersection = 1
		    }
		    else{
			intersection = 0
		    }
		} else {
		    for ch in self.get_node_children_ids(v) {
			if *intersection_map.get(&(ch,c)).unwrap_or(&0) > 0 {
			    intersection = 1;
			    break;
			}
		    }
		}
	    } else {
		for cch in tree.get_node_children_ids(c) {
		    size += t2_size_map.get(&cch).unwrap();
		    intersection += intersection_map.get(&(v,cch)).unwrap();
		}
	    }
	    t2_size_map.insert(c,size);
	    intersection_map.insert((v,c),intersection);
	    let cdist = size + vsize - (2*intersection);
	    if mindist > cdist{
		mindist = cdist;
	    }
	}
	dist += mindist
    }
    return dist;
    }
}

/// A trait describing naive computation of Weighted Robinson Foulds distance
pub trait WeightedRobinsonFoulds
where
    Self: RootedWeightedTree + RootedMetaTree + Clusters,
    <Self as RootedTree>::Node: RootedWeightedNode + RootedMetaNode,
{
    /// Returns weighted Robinson Foulds distance between tree and self.
    fn wrfs(&self, tree: &Self) -> TreeNodeWeight<Self>;
}

/// A trait describing naive computation of cophenetic distance
pub trait CopheneticDistance:
    PathFunction + RootedMetaTree + Clusters + Ancestors + ContractTree + Debug
where
    <Self as RootedTree>::Node: RootedMetaNode + RootedZetaNode,
    TreeNodeZeta<Self>: NodeWeight,
{
    /// Returns zeta of leaf by taxa
    fn get_zeta_taxa(
        &self,
        taxa: &TreeNodeMeta<Self>,
    ) -> TreeNodeZeta<Self> {
        self.get_zeta(self.get_taxa_node_id(taxa).unwrap()).unwrap()
    }

    /// Reurns the nth norm of an iterator composed of floating point values
    fn compute_norm(
        vector: impl Iterator<Item = TreeNodeZeta<Self>>,
        norm: u32,
    ) -> TreeNodeZeta<Self> {
        if norm==0{
            return vector.fold(<TreeNodeZeta<Self>>::zero(), |acc, x| acc.max(x));
        }
        if norm == 1 {
            return vector.sum();
        }
        vector
            .map(|x| {
            let mut out = <TreeNodeZeta<Self>>::one();
                for _ in 0..norm{
                    out = out* x;
                }
                out
            })
            .sum::<TreeNodeZeta<Self>>()
            .powf(
                <TreeNodeZeta<Self> as NumCast>::from(norm)
                    .unwrap()
                    .powi(-1),
            )
    }

    #[cfg(feature = "parallel")]
    /// Returns the vector norm for an iterator
    fn compute_norm_par(
        vector: Vec<TreeNodeZeta<Self>>,
        norm: u32,
    ) -> TreeNodeZeta<Self> {
        if norm == 1 {
            return vector.into_iter().map(|x| x.clone()).sum();
        }
        vector
            .par_iter()
            .map(|x| {
                x.clone().powi(norm as i32)
            })
            .sum::<TreeNodeZeta<Self>>()
            .powf(
                <TreeNodeZeta<Self> as NumCast>::from(norm)
                    .unwrap()
                    .powi(-1),
            )
    }

    /// Reurns the cophenetic distance between two trees using the naive algorithm (\Theta(n^2))
    fn cophen_dist<'a>(
        &'a self,
        tree: &'a Self,
        norm: u32,
    ) -> TreeNodeZeta<Self> {
        if !self.is_all_zeta_set() || !tree.is_all_zeta_set() {
            panic!("Zeta values not set");
        }
        let binding1 = self
            .get_taxa_space()
            .collect::<HashSet<&TreeNodeMeta<Self>>>();
        let binding2 = tree
            .get_taxa_space()
            .collect::<HashSet<&TreeNodeMeta<Self>>>();
        let taxa_set = binding1.intersection(&binding2).cloned();

        self.cophen_dist_by_taxa(tree, norm, taxa_set)
    }

    #[cfg(feature = "parallel")]
    /// Returns the cophenetic distance between two trees using the naive algorithm (\Theta(n^2))
    fn cophen_dist_par<'a>(
        &'a self,
        tree: &'a Self,
        norm: u32,
    ) -> TreeNodeZeta<Self> {
        if !self.is_all_zeta_set() || !tree.is_all_zeta_set() {
            panic!("Zeta values not set");
        }
        let binding1 = self
            .get_taxa_space()
            .collect::<HashSet<&TreeNodeMeta<Self>>>();
        let binding2 = tree
            .get_taxa_space()
            .collect::<HashSet<&TreeNodeMeta<Self>>>();
        let taxa_set = binding1.intersection(&binding2).cloned().collect_vec();

        self.cophen_dist_by_taxa_par(tree, norm, taxa_set.into_iter())
    }

    #[cfg(feature = "parallel")]
    /// Returns the Cophenetic distance between two trees restricted to a taxa set using the \theta(n^2) naive algorithm.
    fn cophen_dist_by_taxa_par<'a>(
        &'a self,
        tree: &'a Self,
        norm: u32,
        taxa_set: impl Iterator<Item = &'a TreeNodeMeta<Self>> + Send,
    ) -> TreeNodeZeta<Self> {
        // let taxa_set = taxa_set.collect_vec();
        let cophen_vec: Vec<TreeNodeZeta<Self>> = taxa_set
            .combinations_with_replacement(2)
            .par_bridge()
            .map(|x| match x[0] == x[1] {
                true => {
                            let zeta_1 = self.get_zeta_taxa(x[0]);
                            let zeta_2 = tree.get_zeta_taxa(x[0]);
                            (zeta_1 - zeta_2).abs()
                        },
                false => {
                            let self_ids = x
                                .iter()
                                .map(|a| self.get_taxa_node_id(a).unwrap())
                                .collect_vec();
                            let tree_ids = x
                                .iter()
                                .map(|a| tree.get_taxa_node_id(a).unwrap())
                                .collect_vec();
                            let t_lca_id = self.get_lca_id(self_ids.as_slice());
                            let t_hat_lca_id = tree.get_lca_id(tree_ids.as_slice());
                            let zeta_1 = self.get_zeta(t_lca_id).unwrap();
                            let zeta_2 = tree.get_zeta(t_hat_lca_id).unwrap();
                            (zeta_1 - zeta_2).abs()
                        },
            })
            .collect();

        Self::compute_norm_par(cophen_vec, norm)
    }

    /// Returns the Cophenetic distance between two trees restricted to a taxa set using the \theta(n^2) naive algorithm.
    fn cophen_dist_by_taxa<'a>(
        &'a self,
        tree: &'a Self,
        norm: u32,
        taxa_set: impl Iterator<Item = &'a TreeNodeMeta<Self>>,
    ) -> TreeNodeZeta<Self> {
        // let taxa_set = taxa_set.collect_vec();
        let cophen_vec = taxa_set
            // .iter()
            .combinations_with_replacement(2)
            .map(|x| match x[0] == x[1] {
                true => {
                            let zeta_1 = self.get_zeta_taxa(x[0]);
                            let zeta_2 = tree.get_zeta_taxa(x[0]);
                            (zeta_1 - zeta_2).abs()
                        },
                false => {
                            let self_ids = x
                                .iter()
                                .map(|a| self.get_taxa_node_id(a).unwrap())
                                .collect_vec();
                            let tree_ids = x
                                .iter()
                                .map(|a| tree.get_taxa_node_id(a).unwrap())
                                .collect_vec();
                            let t_lca_id = self.get_lca_id(self_ids.as_slice());
                            let t_hat_lca_id = tree.get_lca_id(tree_ids.as_slice());
                            let zeta_1 = self.get_zeta(t_lca_id).unwrap();
                            let zeta_2 = tree.get_zeta(t_hat_lca_id).unwrap();
                            (zeta_1 - zeta_2).abs()
                        },
            });

        Self::compute_norm(cophen_vec, norm)
    }
}