1use std::process;
6use log::{info,debug};
7use std::collections::HashMap;
8pub const BLOCK: f32 = 60.0;
9pub const PIPEBLOCK: f32 = BLOCK / 4.0;
10
11#[derive(Debug)]
19pub struct Noeud<T>
20where
21    T: PartialEq
22{
23    pub idx: usize,             val: T,                     pub name: String,           pub support: String,           pub parent: Option<usize>,  pub parent2: Option<usize>,  pub children: Vec<usize>,   pub x: f32,                 pub xmod: f32,              pub y: f32,                 pub ymod: f32,              pub l: f32,                 pub e: Event,               pub location: String,       pub width: f32,             pub height: f32,            pub nbg: usize,             pub nodes: Vec<(usize,usize)>,      pub is_a_transfert: bool,   pub go_left: usize,                            pub go_right: usize,
69    pub fixed: bool,
71    pub transfers: Vec<usize>,      pub visible: bool,
75    pub virtualsvg: bool,
77    pub color_node_idx : usize,
79    pub collapsed : bool
81}
82impl<T> Noeud<T>
83where
84    T: PartialEq
85{
86    pub fn new(idx: usize, val: T) -> Self {
87        Self {
88            idx,
89            val,
90            name: String::from("Undefined"),
91            support: String::from("Undefined"),
92            parent: None,
93            parent2: None,
94            children: vec![],
95            x: 0.0,
96            xmod: 0.0,
97            y: 0.0,
98            ymod: 0.0,
99            l: 0.0,
100            e: Event::Undef,
101            location: String::from("Undefined"),
102            width: PIPEBLOCK ,
103            height: PIPEBLOCK ,
104            nbg: 0,
105            nodes: vec![],
106            is_a_transfert: false,
107            go_left: 0,
108            go_right: 0,
109            fixed: false,
110            transfers: vec![],
111            visible: true,
112            virtualsvg: false,
113            color_node_idx: 0,
114            collapsed: false
115        }
116    }
117    pub fn set_event(&mut self, e: Event)
119    {
120        self.e = e;
121    }
122    pub fn set_x_noref(&mut self, x: f32)
124    {
125        self.x = x;
126    }
127    pub fn set_xmod_noref(&mut self, xmod: f32)
129    {
130        self.xmod = xmod;
131    }
132    pub fn set_ymod_noref(&mut self, ymod: f32)
134    {
135        self.ymod = ymod;
136    }
137    pub fn set_y_noref(&mut self, y: f32)
139    {
140        self.y = y;
141    }
142}
143#[derive(Debug, Default)]
150pub struct ArenaTree<T>
151where
152    T: PartialEq
153{
154    pub arena: Vec<Noeud<T>>,
155}
156impl<T> ArenaTree<T>
157where
158    T: PartialEq + std::default::Default + std::fmt::Debug
159{
160    #[allow(dead_code)]
161    pub fn node(&mut self, val: T) -> usize {
164        for node in &self.arena {
166            if node.val == val {
167                return node.idx;
168            }
169        }
170        let idx = self.arena.len();
172        self.arena.push(Noeud::new(idx, val));
173        idx
174    }
175    pub fn new_node(&mut self, val: T) -> usize {
178        for node in &self.arena {
180            if node.val == val {
181                    panic!("Node already exists.{:?}",node);
182            }
183        }
184        let idx = self.arena.len();
186        self.arena.push(Noeud::new(idx, val));
187        idx
189    }
190	pub fn get_node(&mut self, val: T) -> usize {
193        for node in &self.arena {
195            if node.val == val {
196                return node.idx;
197            }
198        }
199        panic!("Node does not  exist.");
200    }
201    pub fn get_index(&mut self, name: String) -> Result <usize, usize> {
203        for node in &self.arena {
204            if node.name == name {
205                return Ok(node.idx)
206             }
207            }
208        info!("Note: Unable to find {} in the tree.",name);
209        Err(0)
210    }
211    pub fn get_root(&mut self) -> usize {
213        for node in &self.arena {
214            if node.parent == None {
215                return node.idx
216             }
217        }
218    	panic!("Unable to get root of the tree.");
219    }
220    pub fn is_leaf(&self, idx: usize) -> bool {
222        match self.arena[idx].children.len() {
223        0 => true,
224        _ => false,
225        }
226    }
227    pub fn is_left(&self, idx: usize) -> bool {
229        match self.arena[idx].parent {
230        Some(p) => {
231            let children = &self.arena[p].children;
232            idx == children[0]
233        },
234        None => false,
235        }
236    }
237    #[allow(dead_code)]
239    pub fn is_root(&self, idx: usize) -> bool {
240        match self.arena[idx].parent {
241        Some(_p) => false,
242        None => true,
243        }
244    }
245    pub fn depth(&self, idx: usize) -> usize {
247        match self.arena[idx].parent {
248            Some(id) => 1 + self.depth(id),
249            None => 0,
250        }
251    }
252    pub fn get_largest_x(&mut self) -> f32 {
254        let mut max = 0.0;
255        for node in &self.arena {
256            if node.x + node.width / 2.0 > max {
257                max = node.x + node.width / 2.0 ;
258                }
259            }
260        max
261    }
262    pub fn get_largest_y(&mut self) -> f32 {
264        let mut max = 0.0;
265        for node in &self.arena {
266            if node.y  + node.height / 2.0 > max {
267                max = node.y + node.height / 2.0  ;
268             }
269            }
270        max
271    }
272    pub fn get_largest_y_nofl(&mut self) -> f32 {
274        let mut max = 0.0;
275        for node in &self.arena {
276            if node.y  + node.height / 2.0 > max && node.location != "FREE_LIVING".to_string()
277            && node.name != "FREE_LIVING".to_string() {
278                max = node.y + node.height / 2.0  ;
279            }
280        }
281        max
282    }
283    pub fn get_smallest_x(&mut self) -> f32 {
285        let mut min = 1000000.0;
286        for node in &self.arena {
287            if node.x - node.width / 2.0 < min {
288                min = node.x  - node.width / 2.0 ;
289            }
290        }
291        min
292    }
293    pub fn get_smallest_y(&mut self) -> f32 {
295        let mut min = 1000000.0;
296        for node in &self.arena {
297            if node.y - node.height / 2.0 < min {
298                min = node.y - node.height / 2.0;
299            }
300        }
301        min
302    }
303    pub fn get_smallest_l(&mut self) -> f32 {
305        let mut min = 1000000.0;
306        for node in &self.arena {
307            if node.l < min {
308                min = node.l;
309            }
310        }
311        min
312    }
313    pub fn get_largest_height(&mut self) -> f32 {
315        let mut max = 0.0;
316        for node in &self.arena {
317            if node.height > max {
318                max = node.height;
319            }
320        }
321        max
322    }
323    pub fn shift_x_subtree(&mut self, idx: usize, shift: f32) {
325        let mut x = self.arena[idx].x;
326        x = x + shift;
327        debug!("[shift_x_subtree] shifting node {} ({}) of {}",&self.arena[idx].name,&self.arena[idx].x,shift);
328        let _ = &self.arena[idx].set_x_noref(x);
329        debug!("[shift_x_subtree] new value     {} ({})",&self.arena[idx].name,&self.arena[idx].x);
330        let children = &self.arena[idx].children;
331        if children.len() > 0 {
332            let left = children[0];
333            let right = children[1];
334            let _ = &self.shift_x_subtree(left, shift);
335            let _ = &self.shift_x_subtree(right, shift);
336        }
337    }
338    pub fn copie(&mut self) -> ArenaTree<String> {
340        let  mut new: ArenaTree<String> = ArenaTree::default();
341        let mut i = 0;
342        for node in &self.arena {
343            let  idx = new.new_node(i.to_string());
344            new.arena[idx].name = node.name.clone();
345            new.arena[idx].support = node.support.clone();
346            new.arena[idx].parent = node.parent;
347            new.arena[idx].children = node.children.clone();
348            new.arena[idx].x = node.x;
349            new.arena[idx].y = node.y;
350            new.arena[idx].xmod = node.xmod;
351            new.arena[idx].ymod = node.ymod;
352            new.arena[idx].l = node.l;
353            new.arena[idx].e = match node.e {
354                Event::Speciation => Event::Speciation,
355                Event::Duplication => Event::Duplication,
356                Event::Loss => Event::Loss,
357                Event::BranchingOut => Event::BranchingOut,
358                Event::TransferBack => Event::TransferBack,
359                Event::BifurcationOut => Event::BifurcationOut,
360                Event::Leaf => Event::Leaf,
361                Event::ObsoleteSpeciationLoss => Event::ObsoleteSpeciationLoss,
362                                Event::Hybridation => Event::Hybridation,
363                Event::Undef => Event::Undef,
364            };
365            new.arena[idx].location = node.location.clone();
366            new.arena[idx].width = node.width;
367            new.arena[idx].height = node.height;
368            new.arena[idx].nbg = node.nbg;
369            new.arena[idx].nodes = node.nodes.clone();
370            new.arena[idx].is_a_transfert = node.is_a_transfert;
371            new.arena[idx].go_left = node.go_left;
372            new.arena[idx].go_right = node.go_right;
373            new.arena[idx].fixed = node.fixed;
374            new.arena[idx].transfers = node.transfers.clone();
375            new.arena[idx].visible = node.visible;
376            new.arena[idx].virtualsvg = node.virtualsvg;
377            i = i + 1 ;
378        }
379        new
380    }
381}
382#[derive(Debug)]
384pub struct Options{
385    pub branch: bool,
387    pub gene_internal: bool,
389    pub species_internal: bool,
391    pub clado_flag: bool,
393    pub species_only_flag: bool,
395    pub real_length_flag: bool,
397    pub open_browser: bool,
399    pub verbose: bool,
401    pub disp_gene: usize,
403    pub scale: f32,
405    pub ratio: f32,
407    pub rotate: bool,
409    pub remove: bool,
411    pub thickness_flag: bool,
413    pub thickness_thresh: usize,
415    pub thickness_gene: usize,
417    pub thickness_disp_score:bool,
419    pub tidy: bool,
421    pub tidy_leaves_check: bool,
423    pub optimisation: bool,
425    pub height: f32,
427    pub width: f32,
429    pub support: bool,
431    pub free_living: bool,
433    pub free_living_shift: bool,
435    pub uniform: bool,
437    pub gthickness: usize,
439    pub sthickness: usize,
441    pub squaresize: f32,
443    pub trans_start: Option<String>,
445    pub trans_end: Option<String>,
447    pub mid_dist: bool,
449    pub gene_colors: Vec<String>,
451    pub node_colors: Vec<String>,
453    pub bckg_color: String,
455    pub hybrid: Vec<(String,String)>,
457    pub switches: Vec<String>,
459    pub fill_species: bool,
461    pub time_lines: Vec<HashMap<String,String>>,
463    pub pictures: HashMap<String,String>,
465    pub collapsed_nodes: Vec<String>,
467    pub species_compression: f32
469
470}
471impl Options {
472    pub fn new() -> Self {
473        Self {
474            branch: false,
475            gene_internal: false,
476            species_internal: false,
477            clado_flag: true,
478            species_only_flag: false,
479            real_length_flag: false,
480            open_browser: false,
481            verbose: false,
482            disp_gene: 0,
483            scale: 1.0,
484            ratio: 1.0,
485            rotate: true,
486            remove: false,
487            thickness_flag: false,
488            thickness_thresh: 0,
489            thickness_gene: 0,
490            thickness_disp_score: false,
491            tidy: false,
492            tidy_leaves_check: false,
493            optimisation: false,
494            height: 1.0,
495            width: 1.0,
496            support: false,
497            free_living: false,
498            free_living_shift: false,
499            uniform: false,
500            gthickness: 3,
501            sthickness: 6,
502            squaresize: 6.0,
503            trans_start:None,
504            trans_end:None,
505            mid_dist:false,
506            gene_colors: Vec::new(),
507            node_colors: Vec::new(),
508            bckg_color: "White".to_string(),
509            hybrid: Vec::new(),
510            switches: Vec::new(),
511            fill_species: false,
512            time_lines: Vec::new(),
513            pictures: HashMap::new(),
514            collapsed_nodes: Vec::new(),
515            species_compression: 0.0
516        }
517    }
518}
519#[derive(Debug)]
521pub struct Config{
522    pub species_color: String,
523    pub species_opacity: String,
524    pub single_gene_color: String,
525    pub gene_opacity: String,
526    pub species_police_color: String,
527    pub species_police_size: String,
528    pub gene_police_size: String,
529    pub bezier: String,
530    pub fill_species: bool,
531}
532impl Config {
533    pub fn new() -> Self {
534        Self {
535            species_color: "pink".to_string(),
536            species_opacity: "1.0".to_string(),
537            single_gene_color: "blue".to_string(),
538            gene_opacity: "0.9".to_string(),
539            species_police_color: "orange".to_string(),
540            species_police_size: "12".to_string(),
541            gene_police_size: "10".to_string(),
542            bezier: "1".to_string(),
543            fill_species: false,
544        }
545    }
546}
547
548#[allow(dead_code)]
553#[derive(Debug, PartialEq)]
554pub enum Event {
555    Speciation,
556    Duplication,
557    Loss,
558    BranchingOut,
559    TransferBack,
560    BifurcationOut,
561    Leaf,
562    ObsoleteSpeciationLoss,
563    Hybridation,
564    Undef,
565}
566impl Default for Event {
568    fn default() -> Self { Event::Undef }
569}
570
571pub fn newick2tree(
576    arbre: String,
577    tree: &mut ArenaTree<String>,
578    index: usize,
579    num: &mut usize
580    ) {
581    info!("[newick2tree] Tree = {}",arbre);
582    let arbre = arbre;
583    check_is_rooted(&arbre);
584    let (left, right, trail) = find_left_right(arbre);
585    info!("[newick2tree] Left = {} Right = {} Trail = {}",left, right, trail);
586    match trail.find(':') {
587        Some(j) => {
588            tree.arena[index].l = trail[j+1..].to_string().parse::<f32>().unwrap();
589            tree.arena[index].name = trail[0..j].to_string();
590        },
591        None => {
592            tree.arena[index].name = trail[..].to_string();
593        },
594    };
595    match left.find(',') {
596        Some(_i)=> {
597            *num = *num + 1;
598            let name = "NODE_".to_string()+&num.to_string();
600            let new_index = tree.new_node(name.to_string());
601            tree.arena[index].children.push(new_index);
602            tree.arena[new_index].parent = Some(index);
603            newick2tree(left, tree,new_index,num);
604        },
605        None => {
606            info!("[newick2tree] {} is a leaf",left);
607            *num = *num + 1;
608            let name = "NODE_".to_string() + &num.to_string();
609            let left_index = tree.new_node(name);
610            tree.arena[index].children.push(left_index);
611            tree.arena[left_index].parent = Some(index);
612            let left =  match left.find("[&&"){
615                Some(k) => left[..k].to_string(),
616                None => left[..].to_string(),
617            };
618            match left.find(':') {
619                Some(i)=> {
620                    tree.arena[left_index].name = left[0..i].to_string();
621                    tree.arena[left_index].l = left[i+1..].to_string().parse::<f32>().unwrap();
622                },
623                None => {
624                    tree.arena[left_index].name = left;
625                },
626            }
627        },
628    };
629    match right.find(',') {
630        Some(_i)=> {
631            *num = *num + 1;
632            let name = "NODE_".to_string() + &num.to_string();
633            let new_index = tree.new_node(name.to_string());
634            tree.arena[index].children.push(new_index);
635            tree.arena[new_index].parent = Some(index);
636            newick2tree(right, tree, new_index, num);
637        },
638        None => {
639            info!("[newick2tree] {} is a leaf",right);
640            *num = *num + 1;
641            let name = "NODE_".to_string() + &num.to_string();
642            let right_index = tree.new_node(name);
643            tree.arena[index].children.push(right_index);
644            tree.arena[right_index].parent = Some(index);
645            let right = match right.find("[&&"){
648                Some(k) => right[..k].to_string(),
649                None => right[..].to_string(),
650            };
651            match  right.find(':') {
652                Some(i) => {
653                    tree.arena[right_index].name = right[0..i].to_string();
654                    tree.arena[right_index].l = right[i+1..].to_string().parse::<f32>().unwrap();
655                },
656                None => {
657                    tree.arena[right_index].name = right;
658                },
659            }
660        },
661    };
662}
663pub fn check_is_rooted(arbre: &String) {
665    let p = arbre.matches('(').count();
666    let c = arbre.matches(',').count();
667    if p == c {
668        info!("Tree is rooted.");
669    }
670    else
671    if p + 1 == c  {
672        println!("Tree is unrooted.");
673        println!("Please use a rooted tree.");
674        process::exit(0);
675    }
676    else {
677        eprintln!("\nERROR:");
678        println!("Unable to determine if tree is rooted.");
679        eprintln!("It seems the input file is not in a correct newick format.");
680        eprintln!("You may use another format (phyloxml or recphyloxml) to read the file.");
681        process::exit(1)
682    }
683}
684pub fn find_left_right(arbre: String) -> (String, String, String) {
686    let mut len = arbre.len() - 1;
687    if &arbre[len..] == "\n" {
688        len -= 1;
689    }
690    if &arbre[..1] != "(" {
691        eprintln!("\nERROR:");
692        eprintln!("It seems the input file is not in a correct newick format.");
693        eprintln!("You may use another format (phyloxml or recphyloxml) to read the file.");
694        process::exit(1)
695    }
696    let mut num_par = 0;
697    let mut i = 0;
698    for char in arbre.chars() {
699        i += 1;
700        match char {
701            '(' => num_par += 1,
702            ')' => num_par -= 1,
703            ',' => {
704                if num_par == 1 {
705                    break
706                }
707            },
708            _ => {}
709        };
710    }
711    let left = (&arbre[1..i-1]).to_string();
712    let right = (&arbre[i..len+1]).to_string();
713    let trail =  match right.rfind(')') {
714        Some(k) =>  right[k+1..].to_string(),
715        None => "".to_string(),
716    };
717    let trail =  match trail.find(';') {
718        Some(k) =>  trail[0..k].to_string(),
719        None => trail,
720    };
721    let right =  match right.rfind(')') {
722        Some(k) =>  right[..k].to_string(),
723        None => right[..].to_string(),
724    };
725    let trail =  match trail.find("[&&") {
728        Some(k) =>  trail[..k].to_string(),
729        None => trail[..].to_string(),
730    };
731    (left, right, trail)
732}
733pub fn xml2tree (
735    node: roxmltree::Node,
736    parent: usize,
737    mut numero : &mut usize,
738    mut  tree: &mut ArenaTree<String>,
739    ) {
740    let children = node.children();
745    for child in children {
746        if child.has_tag_name("clade"){
747            *numero += 1;
749            let name = "N".to_owned() + &numero.to_string();
751            let name = tree.new_node(name.to_string());
753            tree.arena[parent].children.push(name);
755            tree.arena[name].parent = Some(parent);
757            let nb_att = child.attributes().len();
758            if nb_att >= 1 {
759                let mut i = 0;
760                while i < nb_att {
761                    if child.attributes().nth(i).unwrap().name() == "branch_length" {
762                        let dist = child.attributes().nth(i).unwrap().value().parse::<f32>();
763                        match dist {
764                            Ok(dist) => tree.arena[name].l = dist,
765                            Err(_err) => panic!("[xml2tree] Unable to read branch length"),
766                        };
767                    }
768                    i = i + 1 ;
769                }
770            }
771            xml2tree(child, name, &mut numero, &mut tree);
773        }
774        if child.has_tag_name("id"){
776            let nom = child.first_child().unwrap().text();
777            match nom {
778                Some(text) => tree.arena[parent].name = text.to_string(),
779                None => tree.arena[parent].name = "Unkwnown".to_string(),
780            };
781        }
782        if child.has_tag_name("name"){
784            let nom = child.first_child().unwrap().text();
785            match nom {
786                Some(text) => tree.arena[parent].name = text.to_string(),
787                None => tree.arena[parent].name = "Unkwnown".to_string(),
788            };
789        }
790        if child.has_tag_name("branch_length"){
792            let dist = child.first_child().unwrap().text();
793            match dist {
794                Some(text) => tree.arena[parent].l = text.to_string().parse::<f32>().unwrap(),
795                None => panic!("[xml2tree] Unable to read branch length"),
796            };
797        }
798        if child.has_tag_name("confidence"){
800            let support = child.first_child().unwrap().text();
801            match support {
802                Some(text) => tree.arena[parent].support = text.to_string(),
803                None => panic!("[xml2tree] Unable to read branch support"),
804            };
805        }
806        if child.has_tag_name("events"){
808            info!("[xml2tree]  phyloXML event detected at {:?}",tree.arena[parent]);
809            for evenement in child.children() {
810                if evenement.has_tag_name("speciations"){
811                    tree.arena[parent].set_event(Event::Speciation);
812                    info!("[xml2tree] setting event of {:?} : {:?}",
813                        tree.arena[parent].name, tree.arena[parent].e);
814                };
815                if evenement.has_tag_name("duplications"){
816                    tree.arena[parent].set_event(Event::Duplication);
817                    info!("[xml2tree] setting event of {:?} : {:?}",
818                        tree.arena[parent].name, tree.arena[parent].e);
819                };
820                if evenement.has_tag_name("losses"){
821                    tree.arena[parent].set_event(Event::Loss);
822                    info!("[xml2tree] setting event of {:?} : {:?}",
823                        tree.arena[parent].name, tree.arena[parent].e);
824                };
825            }
826        }
827        if child.has_tag_name("eventsRec"){
829            info!("[xml2tree] recPhyloXML event detected at {:?}",tree.arena[parent]);
830            let mut event_num = 0; let mut sploss_num = 0; let current_sploss_name = parent;
833            for evenement in child.children() {
834                let mut flag_correct_tag_found = true;
835                if evenement.is_element() {
836                    flag_correct_tag_found = false;
837                }
838                if evenement.has_tag_name("speciationLoss"){
839                    flag_correct_tag_found = true;
840                    info!("[xml2tree] Find obsolete tag speciationLoss (# {})", sploss_num);
843                    info!("[xml2tree] Index of current father (current_sploss_name)  {}",
844                        current_sploss_name);
845                    info!("[xml2tree] Initial tree {:?}", tree);
846                    sploss_num += 1;
847                    *numero += 1;
849                    let sploss_name = "ADDED_SPECLOSS".to_owned() + &numero.to_string();
851                    info!("[xml2tree] Create new node sploss {}",sploss_name);
852                    let sploss_name = tree.new_node(sploss_name.to_string());
854                    info!("[xml2tree] Modified tree 1  {:?}",tree);
855                    info!("[xml2tree] Index of current node {}",parent);
856                    let grandparent = match tree.arena[parent].parent {
860                        Some(p) => p,
861                        None => panic!("No parent! Unable to process obsolete format"),
862                    };
863                    tree.arena[sploss_name].set_event(Event::ObsoleteSpeciationLoss);
865                    tree.arena[sploss_name].name = "SpecOutLoss".to_string();
866                    assert!(evenement.has_attribute("speciesLocation"));
868                    assert_eq!(evenement.attributes().nth(0).unwrap().name(),"speciesLocation");
869                    let location = evenement.attributes().nth(0).unwrap().value();
870                    info!("[xml2tree] Location is {}",location);
871                    info!("[xml2tree] Set Location of sploss_name:");
872                    tree.arena[sploss_name].location = location.to_string();
873                    tree.arena[sploss_name].parent = Some(grandparent);
875                    tree.arena[grandparent].children.retain(|&x| x !=  parent);
877                    tree.arena[grandparent].children.push(sploss_name);
879                    tree.arena[sploss_name].children.push(parent);
881                    tree.arena[parent].parent = Some(sploss_name);
883                    info!("[xml2tree] Modified tree 2  {:?}",tree);
884                    let loss_name = "ADDED_LOSS".to_owned() + &numero.to_string();
886                    info!("[xml2tree] Create new node loss {}",loss_name);
887                    let loss_name = tree.new_node(loss_name.to_string());
889                    info!("[xml2tree] New node loss : {:?}",tree.arena[loss_name]);
890                    tree.arena[sploss_name].children.push(loss_name);
892                    tree.arena[loss_name].parent = Some(sploss_name);
893                    tree.arena[loss_name].set_event(Event::Loss);
895                    tree.arena[loss_name].name = "Added Loss".to_string();
896                }
897                if evenement.has_tag_name("speciationOutLoss"){
898                    panic!("Warning: taxon 'speciationOutLoss' is obsolete");
899                }
900                if evenement.has_tag_name("speciationOut"){
901                    panic!("Warning: taxon 'speciationOut' is obsolete");
902                }
903                if evenement.has_tag_name("loss"){
904                    flag_correct_tag_found = true;
905                    event_num += 1;
906                    info!("[xml2tree] event Nb {} = {:?}",event_num,evenement);
907                    tree.arena[parent].set_event(Event::Loss);
908                    info!("[xml2tree] setting event of {:?} : {:?}",
909                        tree.arena[parent].name, tree.arena[parent].e);
910                    assert!(evenement.has_attribute("speciesLocation"));
911                    assert_eq!(evenement.attributes().nth(0).unwrap().name(), "speciesLocation");
912                    let location = evenement.attributes().nth(0).unwrap().value();
913                    tree.arena[parent].location = location.to_string();
914                }
915                if evenement.has_tag_name("leaf"){
916                    flag_correct_tag_found = true;
917                    event_num += 1;
918                    info!("[xml2tree] event Nb {} = {:?}",event_num,evenement);
919                    tree.arena[parent].set_event(Event::Leaf);
932                    info!("[xml2tree] setting event of {:?} : {:?}",
933                        tree.arena[parent].name, tree.arena[parent].e);
934                    info!("[xml2tree] Attributes of {:?} are {:?}", evenement, evenement.attributes());
935                    let nb_att = evenement.attributes().len();
936                    info!("[xml2tree] Number of attributes  = {}",nb_att);
937                    assert!(evenement.has_attribute("speciesLocation"));
938                    if nb_att == 1 {
939                        assert_eq!(evenement.attributes().nth(0).unwrap().name(), "speciesLocation");
940                        let location = evenement.attributes().nth(0).unwrap().value();
941                        tree.arena[parent].location = location.to_string();
942                    }
943                    else {
944                        assert!(nb_att == 2);
948                        assert!(evenement.has_attribute("geneName"));
949                        assert!(evenement.has_attribute("speciesLocation"));
950                        if evenement.attributes().nth(0).unwrap().name() == "geneName" {
951                            assert_eq!(evenement.attributes().nth(1).unwrap().name(), "speciesLocation");
952                            let name = evenement.attributes().nth(0).unwrap().value();
953                            tree.arena[parent].name = name.to_string();
954                            info!("[xml2tree] set name {:?}",tree.arena[parent]);
955                            let location = evenement.attributes().nth(1).unwrap().value();
956                            tree.arena[parent].location = location.to_string();
957                        }
958                        if evenement.attributes().nth(1).unwrap().name() == "geneName" {
959                            assert_eq!(evenement.attributes().nth(0).unwrap().name(), "speciesLocation");
960                            let name = evenement.attributes().nth(1).unwrap().value();
961                            tree.arena[parent].name = name.to_string();
962                            info!("[xml2tree] set name {:?}",tree.arena[parent]);
963                            let location = evenement.attributes().nth(0).unwrap().value();
964                            tree.arena[parent].location = location.to_string();
965                        }
966                    }
967                }
968                if evenement.has_tag_name("speciation"){
969                    flag_correct_tag_found = true;
970                    event_num += 1;
971                    info!("[xml2tree] event Nb {} = {:?}", event_num, evenement);
972                    tree.arena[parent].set_event(Event::Speciation);
973                    info!("[xml2tree] setting event of {:?} : {:?}",
974                        tree.arena[parent].name, tree.arena[parent].e);
975                    info!("[xml2tree] Attributes of {:?} are {:?}", evenement, evenement.attributes());
976                    assert!(evenement.has_attribute("speciesLocation"));
977                    assert_eq!(evenement.attributes().nth(0).unwrap().name(), "speciesLocation");
978                    let location = evenement.attributes().nth(0).unwrap().value();
979                    info!("[xml2tree] set location = {}",location);
980                    tree.arena[parent].location = location.to_string();
981                }
982                if evenement.has_tag_name("duplication"){
983                    flag_correct_tag_found = true;
984                    event_num += 1;
985                    info!("[xml2tree] event Nb {} = {:?}", event_num, evenement);
986                    tree.arena[parent].set_event(Event::Duplication);
987                    info!("[xml2tree] setting event of {:?} : {:?}",
988                        tree.arena[parent].name, tree.arena[parent].e);
989                    info!("[xml2tree] Attributes of {:?} are {:?}", evenement, evenement.attributes());
990                    assert!(evenement.has_attribute("speciesLocation"));
991                    assert_eq!(evenement.attributes().nth(0).unwrap().name(), "speciesLocation");
992                    let location = evenement.attributes().nth(0).unwrap().value();
993                    info!("[xml2tree] set location = {}",location);
994                    tree.arena[parent].location = location.to_string();
995                }
996                if evenement.has_tag_name("branchingOut"){
997                    flag_correct_tag_found = true;
998                    event_num += 1;
999                    info!("[xml2tree] event Nb {} = {:?}", event_num, evenement);
1000                    tree.arena[parent].set_event(Event::BranchingOut);
1001                    info!("[xml2tree] setting event of {:?} : {:?}",
1002                        tree.arena[parent].name, tree.arena[parent].e);
1003                    info!("[xml2tree] Attributes of {:?} are {:?}", evenement, evenement.attributes());
1004                    assert!(evenement.has_attribute("speciesLocation"));
1005                    assert_eq!(evenement.attributes().nth(0).unwrap().name(), "speciesLocation");
1006                    let location = evenement.attributes().nth(0).unwrap().value();
1007                    info!("[xml2tree] set location = {}",location);
1008                    tree.arena[parent].location = location.to_string();
1009                }
1010                if evenement.has_tag_name("transferBack"){
1013                    flag_correct_tag_found = true;
1014                    event_num += 1;
1029                    info!("[xml2tree] event Nb {} = {:?}", event_num, evenement);
1030                    tree.arena[parent].set_event(Event::TransferBack);
1031                    info!("[xml2tree] setting event of {:?} : {:?}",
1033                        tree.arena[parent].name, tree.arena[parent].e);
1034                    info!("[xml2tree] Attributes of {:?} are {:?}", evenement, evenement.attributes());
1035                    assert!(evenement.has_attribute("destinationSpecies"));
1036                    assert_eq!(evenement.attributes().nth(0).unwrap().name(), "destinationSpecies");
1037                    let location = evenement.attributes().nth(0).unwrap().value();
1038                    info!("[xml2tree] set destinationSpecies = {}",location);
1039                    tree.arena[parent].location = location.to_string();
1040                    tree.arena[parent].is_a_transfert = true;
1041                }
1042                if evenement.has_tag_name("bifurcationOut"){
1044                    flag_correct_tag_found = true;
1045                    event_num += 1;
1046                    info!("[xml2tree] event Nb {} = {:?}", event_num, evenement);
1047                    tree.arena[parent].set_event(Event::BifurcationOut);
1048                    info!("[xml2tree] Attributes of {:?} are {:?}", evenement, evenement.attributes());
1049                    let grandparent =  tree.arena[parent].parent;
1050                    match grandparent {
1051                        Some(p) => {
1052                            let location =  &tree.arena[p].location;
1053                            info!("[xml2tree] set location according to its father = {}",location);
1054                            tree.arena[parent].location = location.to_string();
1055                        },
1056                        None => panic!("BifurcationOut node as no parent : {:?}",tree.arena[parent]),
1057                    };
1058                    tree.arena[parent].is_a_transfert = true;
1059                    }
1066                if flag_correct_tag_found == false {
1067                    eprintln!("\nERROR: The event [{:?}] is not a recPhyloXML standard event.",evenement.tag_name());
1068                    eprintln!("         The recPhyloXML  standard events are :");
1069                    eprintln!("         - leaf");
1070                    eprintln!("         - loss");
1071                    eprintln!("         - speciation");
1072                    eprintln!("         - duplication");
1073                    eprintln!("         - branchingOut");
1074                    eprintln!("         - transferBack");
1075                    eprintln!("         - bifurcationOut");
1076                    eprintln!("         - speciationLoss (obsolete)");
1077                    eprintln!("        See  http://phylariane.univ-lyon1.fr/recphyloxml/");
1078
1079                    process::exit(1)
1080                }
1081            }
1082            info!("[xml2tree]Event closed");
1083        }
1084    }
1085}
1086pub fn check_for_obsolete(gene_tree: &mut ArenaTree<String>, species_tree: &mut ArenaTree<String>) {
1088    info!("[check_for_obsolete] Initial gene tree {:?}",&gene_tree);
1089    let mut osls = Vec::new();
1090    for index in &mut gene_tree.arena {
1091        if index.e == Event::ObsoleteSpeciationLoss {
1092            info!("[check_for_obsolete] Find ObsoleteSpeciationLoss (OSL): {:?}",index);
1093            osls.push(index.idx);
1094        }
1095    }
1096    info!("[check_for_obsolete] Find {} OSL in the tree",osls.len());
1097    if osls.len() > 0 {
1098        println!("Warning! There was {} obsolete SpeciationLoss tag in the recPhyloXML",osls.len());
1099    }
1100    for osl in osls {
1101        info!("[check_for_obsolete] Processing: {:?}",osl);
1102        info!("[check_for_obsolete] OSL = {} at species {:?}",
1103            gene_tree.arena[osl].name, gene_tree.arena[osl].location);
1104        let children = &gene_tree.arena[osl].children;
1105        info!("[check_for_obsolete] Number of children: {:?}",children.len());
1106        assert_eq!(children.len(),2);
1107        let left = children[0];
1108        let right = children[1];
1109        info!("[check_for_obsolete] Left child = {} {:?}",
1110            gene_tree.arena[left].name, gene_tree.arena[left].e);
1111        info!("[check_for_obsolete] Right child = {} {:?}",
1112            gene_tree.arena[right].name, gene_tree.arena[right].e);
1113        let loss = match gene_tree.arena[left].e
1115            {
1116            Event::Loss => left,
1117            _ => right,
1118            };
1119        let species_not_loss = match gene_tree.arena[left].e
1121            {
1122            Event::Loss => &gene_tree.arena[right].location,
1123            _ => &gene_tree.arena[left].location,
1124            };
1125        info!("[check_for_obsolete] Loss node is {:?}",gene_tree.arena[loss]);
1126        info!("[check_for_obsolete] Species of the other child is {:?}",species_not_loss);
1127        let species = &gene_tree.arena[osl].location;
1129        let species_node = match species_tree.get_index(species.to_string())
1131            {
1132            Ok(index) => index,
1133            Err(_err) => panic!("[check_for_obsolete] Unable to find node {:?}",species.to_string()),
1134            };
1135        let species_node_left = &species_tree.arena[species_node].children[0];
1136        let species_node_right = &species_tree.arena[species_node].children[1];
1137        let species_left = &species_tree.arena[*species_node_left].name;
1138        let species_right = &species_tree.arena[*species_node_right].name;
1139        info!("[check_for_obsolete] Species under the OSL in species tree = {}, {}",
1140            species_left, species_right);
1141        let loss_species = match species_not_loss == species_left {
1142            true => species_right,
1143            false => species_left,
1144        };
1145        info!("[check_for_obsolete] Thus species of loss node is {}",loss_species);
1146        gene_tree.arena[loss].location = loss_species.to_string();
1147    }
1148    info!("[check_for_obsolete] Final gene tree {:?}",&gene_tree);
1149}
1150#[allow(dead_code)]
1151pub fn map_gene_trees(
1153    sp_tree: &mut ArenaTree<String>,
1154    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
1155    ) {
1156    let  nb_gntree =  gene_trees.len(); info!("[map_gene_trees] {} gene trees to be processed",nb_gntree);
1158    let mut idx_rcgen = 0;  loop {
1160        info!("[map_gene_trees] => Processing Gene Tree {}",idx_rcgen);
1161        for  index in &mut gene_trees[idx_rcgen].arena {
1162            let mut mapped = false;
1163            for spindex in  &mut sp_tree.arena {
1164                if  index.location == spindex.name {
1165                    mapped = true;
1166                    let x = spindex.x;
1167                    index.x = x;
1168                    let y = spindex.y;
1169                    index.y = y;
1170                    info!("[map_gene_trees] [{}] Gene node {:?} mapped to  species node {:?}",
1171                        idx_rcgen, index,spindex);
1172                }
1173            }
1174            if !mapped {
1175                panic!("Unable to map Node {:?}",index);
1176            }
1177        }
1178        idx_rcgen += 1;
1180        if idx_rcgen == nb_gntree {
1181            break;
1182        }
1183    } }
1185pub fn map_species_trees(
1187    sp_tree: &mut ArenaTree<String>,
1188    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
1189    ) {
1190    let  nb_gntree =  gene_trees.len(); info!("[map_species_trees] {} gene trees to be processed",nb_gntree);
1192    if nb_gntree > 0 {
1193        let mut idx_rcgen = 0;  loop {
1195            info!("[map_species_trees] => Processing Gene Tree {}",idx_rcgen);
1196            for  index in &mut gene_trees[idx_rcgen].arena {
1198                let mut mapped = false;
1199                for spindex in  &mut sp_tree.arena {
1201                    if  index.location == spindex.name {
1202                        mapped = true;
1203                        let mut nbg = spindex.nbg;
1205                        nbg = nbg + 1 ;
1206                        spindex.nbg = nbg;
1207                        spindex.nodes.push((idx_rcgen, index.idx));
1209                        info!("[map_species_trees] Gene node {:?} mapped to  species node {:?}", index, spindex);
1211                    }
1212                }
1213                if !mapped {
1214                    eprintln!("\nERROR: Unable to map Node {:?}",index);
1215                    eprintln!("\nThe species '{}' was not found in species tree",index.location);
1216                    eprintln!("\nMaybe you should use the 'free_living' option.");
1217                    process::exit(1)
1218                }
1219            }
1220            idx_rcgen += 1;
1222            if idx_rcgen == nb_gntree {
1223                break;
1224            }
1225        } } }
1228pub fn bilan_mappings_reti(
1230    sp_tree: &mut ArenaTree<String>,
1231    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
1232    index: usize,
1233    left_reti: bool,
1234    ) {
1235    info!("[bilan_mappings_reti] Species Node {}",sp_tree.arena[index].name);
1236    let widthgenes = sp_tree.arena[index].nbg  as f32 * PIPEBLOCK;
1237    let shift_left_x = ( sp_tree.arena[index].width - widthgenes ) / 2.0;
1238    let reti_factor = match left_reti {
1239        true => -1.0,
1240        false => 1.0
1241    };
1242    for (index_node, node) in &sp_tree.arena[index].nodes {
1243        info!("[bilan_mappings_reti] Gene node before {:?}",gene_trees[*index_node].arena[*node]);
1244        let x = gene_trees[*index_node].arena[*node].x;
1245        let x = x + shift_left_x * reti_factor;
1246        gene_trees[*index_node].arena[*node].set_x_noref(x);
1247        info!("[bilan_mappings_reti] Gene node after {:?}",gene_trees[*index_node].arena[*node]);
1248    }
1249}
1250pub fn bilan_mappings(
1252    sp_tree: &mut ArenaTree<String>,
1253    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
1254    index: usize,
1255    options: &Options,
1256    ) {
1257    info!("[bilan_mappings] Species Node {}",sp_tree.arena[index].name);
1258    let ratio = options.ratio ;   let  mut shift_left_x = 0.0;
1264    let  mut shift_y = 0.0;
1265    let  mut shift_right_x = sp_tree.arena[index].nbg as f32 -1.0 ;
1266    let incr = 1.0;
1267    for (index_node, node) in &sp_tree.arena[index].nodes {
1270        info!("[bilan_mappings] >>> {:?} {:?}",
1271            gene_trees[*index_node].arena[*node].name, gene_trees[*index_node].arena[*node].e);
1272        let bool_left = sp_tree.is_left(index);
1273        match  gene_trees[*index_node].arena[*node].e {
1274            Event::Duplication => {
1275                let x = gene_trees[*index_node].arena[*node].x;
1276                let x = match bool_left {
1277                    true   => x + PIPEBLOCK * shift_left_x / ratio,
1278                    false  => x + PIPEBLOCK * shift_right_x / ratio,
1279                };
1280                gene_trees[*index_node].arena[*node].set_x_noref(x);
1281                let y = gene_trees[*index_node].arena[*node].y;
1282                let y = y + PIPEBLOCK * shift_y / ratio;
1283                gene_trees[*index_node].arena[*node].set_y_noref(y);
1284                shift_y = shift_y + incr;
1287                },
1290            Event::Speciation => {
1291                let x = gene_trees[*index_node].arena[*node].x;
1292                let x = match bool_left {
1293                    true   => x + PIPEBLOCK * shift_left_x / ratio,
1294                    false  => x + PIPEBLOCK * shift_right_x / ratio,
1295                };
1296                gene_trees[*index_node].arena[*node].set_x_noref(x);
1297                let y = gene_trees[*index_node].arena[*node].y;
1298                let y = y + PIPEBLOCK * shift_y / ratio;
1299                gene_trees[*index_node].arena[*node].set_y_noref(y);
1300                shift_left_x = shift_left_x + incr;
1301                shift_y = shift_y + incr;
1302                shift_right_x = shift_right_x - incr;
1303            },
1304            Event::TransferBack => {
1305                let x = gene_trees[*index_node].arena[*node].x;
1306                let x = match bool_left {
1307                    true   => x + PIPEBLOCK * shift_left_x / ratio,
1308                    false  => x + PIPEBLOCK * shift_right_x / ratio,
1309                };
1310                gene_trees[*index_node].arena[*node].set_x_noref(x);
1311                let y = gene_trees[*index_node].arena[*node].y;
1312                let y = y + PIPEBLOCK * shift_y / ratio;
1313                gene_trees[*index_node].arena[*node].set_y_noref(y);
1314                shift_left_x = shift_left_x + incr;
1315                shift_y = shift_y + incr;
1316                shift_right_x = shift_right_x - incr;
1317            },
1318            Event::BranchingOut => {
1319                let x = gene_trees[*index_node].arena[*node].x;
1320                let x = match bool_left {
1321                    true   => x + PIPEBLOCK * shift_left_x / ratio,
1322                    false  => x + PIPEBLOCK * shift_right_x / ratio,
1323                };
1324                gene_trees[*index_node].arena[*node].set_x_noref(x);
1325                let y = gene_trees[*index_node].arena[*node].y;
1326                let y = y + PIPEBLOCK * shift_y / ratio;
1327                gene_trees[*index_node].arena[*node].set_y_noref(y);
1328                shift_left_x = shift_left_x + incr;
1329                shift_y = shift_y + incr;
1330                shift_right_x = shift_right_x - incr;
1331            },
1332            Event::Leaf => {
1333                let x = gene_trees[*index_node].arena[*node].x;
1334                let x = match bool_left {
1335                    true   => x + PIPEBLOCK * shift_left_x / ratio,
1336                    false  => x + PIPEBLOCK * shift_right_x / ratio,
1337                };
1338                gene_trees[*index_node].arena[*node].set_x_noref(x);
1339                let y = gene_trees[*index_node].arena[*node].y;
1340                let y = y + PIPEBLOCK * shift_y;
1341                gene_trees[*index_node].arena[*node].set_y_noref(y);
1342                shift_left_x = shift_left_x + incr;
1343                shift_y = shift_y + incr;
1344                shift_right_x = shift_right_x - incr;
1345            },
1346            Event::Loss => {
1347                let x = gene_trees[*index_node].arena[*node].x;
1348                let x = match bool_left {
1349                    true   => x + PIPEBLOCK * shift_left_x / ratio,
1350                    false  => x + PIPEBLOCK * shift_right_x / ratio,
1351                };
1352                gene_trees[*index_node].arena[*node].set_x_noref(x);
1353                let y = gene_trees[*index_node].arena[*node].y;
1354                let y = y + PIPEBLOCK * shift_y / ratio;
1355                gene_trees[*index_node].arena[*node].set_y_noref(y);
1356                shift_left_x = shift_left_x + incr;
1357                shift_y = shift_y + incr;
1358                shift_right_x = shift_right_x - incr;
1359            },
1360            Event::BifurcationOut => {
1361                let x = gene_trees[*index_node].arena[*node].x;
1362                let x = match bool_left {
1363                    true   => x + PIPEBLOCK * shift_left_x / ratio,
1364                    false  => x + PIPEBLOCK * shift_right_x / ratio,
1365                };
1366                gene_trees[*index_node].arena[*node].set_x_noref(x);
1367                let y = gene_trees[*index_node].arena[*node].y;
1368                let y = y + PIPEBLOCK * shift_y / ratio;
1369                gene_trees[*index_node].arena[*node].set_y_noref(y);
1370                shift_left_x = shift_left_x + incr;
1371                shift_y = shift_y + incr;
1372                shift_right_x = shift_right_x - incr;
1373            },
1374            Event::ObsoleteSpeciationLoss => {
1375                let x = gene_trees[*index_node].arena[*node].x;
1376                let x = match bool_left {
1377                    true   => x + PIPEBLOCK * shift_left_x / ratio,
1378                    false  => x + PIPEBLOCK * shift_right_x / ratio,
1379                };
1380                gene_trees[*index_node].arena[*node].set_x_noref(x);
1381                let y = gene_trees[*index_node].arena[*node].y;
1382                let y = y + PIPEBLOCK * shift_y / ratio;
1383                gene_trees[*index_node].arena[*node].set_y_noref(y);
1384                shift_left_x = shift_left_x + incr;
1385                shift_y = shift_y + incr;
1386                shift_right_x = shift_right_x - incr;
1387            },
1388            _=> { let x = gene_trees[*index_node].arena[*node].x;
1390                let x = match bool_left {
1391                    true   => x + PIPEBLOCK * shift_left_x / ratio,
1392                    false  => x + PIPEBLOCK * shift_right_x / ratio,
1393                };
1394                gene_trees[*index_node].arena[*node].set_x_noref(x);
1395                let y = gene_trees[*index_node].arena[*node].y;
1396                let y = y + PIPEBLOCK * shift_y / ratio;
1397                gene_trees[*index_node].arena[*node].set_y_noref(y);
1398                shift_left_x = shift_left_x + incr;
1399                shift_y = shift_y + incr;
1400                shift_right_x = shift_right_x - incr;
1401            },
1402        }
1403
1404    }
1405    let children = &mut  sp_tree.arena[index].children;
1406    if children.len() > 0 {
1407        let son_left = children[0];
1408        let son_right = children[1];
1409         bilan_mappings(sp_tree, gene_trees, son_left, options);
1410         bilan_mappings(sp_tree, gene_trees, son_right, options);
1411    }
1412}
1413pub fn move_dupli_mappings(
1415    sp_tree: &mut ArenaTree<String>,
1416    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
1417    index: usize,
1418    options: &Options,
1419    ) {
1420    for (index_node, node) in &sp_tree.arena[index].nodes {
1421        debug!("[move_dupli_mappings] >>> {:?} {:?}",
1422            gene_trees[*index_node].arena[*node].name, gene_trees[*index_node].arena[*node].e);
1423        match  gene_trees[*index_node].arena[*node].e {
1424            Event::Duplication => {
1425                let bool_left = sp_tree.is_left(index);
1426                let dupli_children =  &mut gene_trees[*index_node].arena[*node].children;
1428                let dupli_son = match bool_left {
1429                    true => dupli_children[0],
1430                    false => dupli_children[1],
1431                };
1432                let x = gene_trees[*index_node].arena[dupli_son].x;
1433                gene_trees[*index_node].arena[*node].set_x_noref(x);
1434                if options.mid_dist {
1437                    let species_parent =  gene_trees[*index_node].arena[*node].parent;
1438                    let midistance = match species_parent {
1443                        None =>  sp_tree.arena[index].height / 2.0,
1444                        Some(p) => (gene_trees[*index_node].arena[*node].y - gene_trees[*index_node].arena[p].y) / 1.5,
1445                    };
1446                    let y = gene_trees[*index_node].arena[*node].y - midistance ;
1447                    gene_trees[*index_node].arena[*node].set_y_noref(y);
1448                    gene_trees[*index_node].arena[*node].set_ymod_noref(0.0);
1449                }
1450            },
1451            Event::Leaf => {
1465                let y = sp_tree.arena[index].y + sp_tree.arena[index].height / 2.0 ;
1466                gene_trees[*index_node].arena[*node].set_y_noref(y);
1467                gene_trees[*index_node].arena[*node].set_ymod_noref(0.0);
1468            }
1469            _=> {},
1470        }
1471    }
1472    let children =  &mut sp_tree.arena[index].children;
1473    if children.len() > 0 {
1474        let son_left = children[0];
1475        let son_right = children[1];
1476        move_dupli_mappings(sp_tree, gene_trees, son_left, options);
1477        move_dupli_mappings(sp_tree, gene_trees, son_right, options);
1478    }
1479}
1480pub fn move_species_mappings(
1483    sp_tree: &mut ArenaTree<String>,
1484    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
1485    index: usize,
1486    ) {
1487    for (index_node, node) in &sp_tree.arena[index].nodes {
1488        debug!("[move_species_mappings] >>> {:?} {:?}",
1489            gene_trees[*index_node].arena[*node].name,gene_trees[*index_node].arena[*node].e);
1490        match  gene_trees[*index_node].arena[*node].e {
1491            Event::Speciation => {
1492                let species_children =  &mut  gene_trees[*index_node].arena[*node].children;
1494                let mut left = species_children[0];
1495                let mut right = species_children[1];
1496                if (sp_tree.arena[index].nodes.contains(&(*index_node,left))) &&
1498                   (sp_tree.arena[index].nodes.contains(&(*index_node,right))) {
1499                    let mut left_x = gene_trees[*index_node].arena[left].x;
1500                    let mut right_x = gene_trees[*index_node].arena[right].x;
1501                    if left_x > right_x {
1502                        let buf = left;
1503                        left = right;
1504                        right = buf;
1505                        left_x = gene_trees[*index_node].arena[left].x;
1506                        right_x = gene_trees[*index_node].arena[right].x;
1507                    };
1508                    let parent_x = gene_trees[*index_node].arena[*node].x;
1509                    if left_x > parent_x {
1510                    	gene_trees[*index_node].arena[*node].set_x_noref((left_x + right_x) / 2.0 );
1511                	}
1512                    if parent_x > right_x {
1513                        gene_trees[*index_node].arena[*node].set_x_noref((left_x + right_x) / 2.0 );
1514                    }
1515                }
1516            },
1517            _=> {},
1518        }
1519    }
1520    let children =  &mut  sp_tree.arena[index].children;
1521    if children.len() > 0 {
1522        let son_left = children[0];
1523        let son_right = children[1];
1524        move_species_mappings( sp_tree, gene_trees, son_left);
1525        move_species_mappings( sp_tree, gene_trees, son_right);
1526    }
1527}
1528pub fn process_fl(
1530    sp_tree: &mut ArenaTree<String>,
1531    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
1532    index: usize,
1533    options: &Options,
1534    ) {
1535    let mut  genes = vec![];
1537    let mut  feuilles = vec![];
1538    for (index_node, node) in &sp_tree.arena[index].nodes {
1539        info!("[process_fl] >>> {:?} {:?}",
1540            gene_trees[*index_node].arena[*node].name, gene_trees[*index_node].arena[*node].e);
1541        if gene_trees[*index_node].arena[*node].e == Event::Leaf {
1542            if !genes.contains(index_node) {
1543                genes.push(*index_node);
1544                feuilles.push((index_node, node));
1545            }
1546        };
1547    }
1548    let mut max_x_in_lf = 0.0;
1550    for (index_node, node) in feuilles {
1551        let mut _parent = *node;
1552        let shift = genes.iter().position(|x| x  == index_node);
1553        let shift = match shift {
1554            Some(val) => val  as f32  ,
1555            None => panic!("Unexpected error in process_fl"),
1556        };
1557        let mut parent = gene_trees[*index_node].arena[*node].parent.expect("[process_fl] ERROR Unexpected root (1)");
1558        while gene_trees[*index_node].arena[*node].location == gene_trees[*index_node].arena[parent].location
1559            {
1560            _parent = parent;
1561            parent = match gene_trees[*index_node].arena[parent].parent {
1562                Some(p) => p,
1563                None =>    {
1564                    break
1565                },
1566            };
1567        }
1568        info!("[process_fl] Ancestor of the gene {} in this species node is {:?}",
1569            index_node, gene_trees[*index_node].arena[_parent]);
1570        let mut fl_tree: ArenaTree<String> = ArenaTree::default();
1572        let mut parent_xmod = sp_tree.arena[index].x-sp_tree.arena[index].width + shift * PIPEBLOCK ;
1573        if options.free_living_shift {
1574            parent_xmod = parent_xmod + max_x_in_lf ;
1575        }
1576        let mut parent_ymod = sp_tree.arena[index].y / 2.0 + shift * PIPEBLOCK;
1578        copie_fl(&mut fl_tree, &mut gene_trees[*index_node], _parent);
1580        knuth_layout(&mut fl_tree,0, &mut 1);
1582        check_contour_postorder(&mut fl_tree, 0);
1583        shift_mod_xy(&mut fl_tree, 0, &mut parent_xmod, &mut parent_ymod);
1584        set_middle_postorder(&mut fl_tree, 0);
1585        max_x_in_lf = max_x_in_lf + fl_tree.get_largest_x() - parent_xmod;
1586        let mut compteur = 0 ;
1587        while compteur < fl_tree.arena.len() {
1588            remplace_fl_inv(&mut fl_tree, &mut gene_trees[*index_node], compteur);
1589            compteur = compteur + 1;
1590        }
1591    }
1592}
1593pub fn copie_fl(fl_tree: &mut ArenaTree<String>, gn_tree: &mut ArenaTree<String>, index: usize) {
1595    if gn_tree.arena[index].location == "FREE_LIVING" && gn_tree.arena[index].e != Event::BranchingOut {
1597        let fl_root_val = gn_tree.arena[index].val.clone();
1598        let fl_root_name = gn_tree.arena[index].name.clone();
1599        let new_index = fl_tree.node(fl_root_val.to_string());
1600        fl_tree.arena[new_index].name = fl_root_name;
1601        let children = &gn_tree.arena[index].children;
1602        if children.len() > 0 {
1603            let left = children[0];
1604            let right = children[1];
1605            let fl_left_val = gn_tree.arena[left].val.clone();
1606            let fl_left_name = gn_tree.arena[left].name.clone();
1607            let new_left_index = fl_tree.new_node(fl_left_val.to_string());
1608            fl_tree.arena[new_left_index].name = fl_left_name;
1609            fl_tree.arena[new_left_index].parent = Some(new_index);
1610            let fl_right_val = gn_tree.arena[right].val.clone();
1611            let fl_right_name = gn_tree.arena[right].name.clone();
1612            let new_right_index = fl_tree.new_node(fl_right_val.to_string());
1613            fl_tree.arena[new_right_index].name = fl_right_name;
1614            fl_tree.arena[new_right_index].parent = Some(new_index);
1615            fl_tree.arena[new_index].children.push(new_left_index);
1616            fl_tree.arena[new_index].children.push(new_right_index);
1617            copie_fl(fl_tree, gn_tree, left);
1618            copie_fl(fl_tree, gn_tree, right);
1619        }
1620    }
1621    if gn_tree.arena[index].location == "FREE_LIVING" && gn_tree.arena[index].e == Event::BranchingOut {
1623        let children = &gn_tree.arena[index].children;
1625        if children.len() > 0 {
1626            let left = children[0];
1627            let right = children[1];
1628            let fl_child  = match gn_tree.arena[right].location == "FREE_LIVING" {
1630                true => right,
1631                false => left,
1632            };
1633            let tr_child  = match gn_tree.arena[right].location == "FREE_LIVING" {
1635                true => left,
1636                false => right,
1637            };
1638            let fl_root_val = gn_tree.arena[index].val.clone();
1639            let fl_root_name = gn_tree.arena[index].name.clone();
1640            let new_index = fl_tree.node(fl_root_val.to_string());
1641            fl_tree.arena[new_index].name = fl_root_name;
1642            let fl_left_val = gn_tree.arena[tr_child].val.clone();
1644            let fl_left_name = gn_tree.arena[tr_child].name.clone();
1645            let new_left_index = fl_tree.new_node(fl_left_val.to_string());
1646            fl_tree.arena[new_left_index].name = fl_left_name;
1647            fl_tree.arena[new_left_index].parent = Some(new_index);
1648            fl_tree.arena[new_left_index].virtualsvg = true;
1651            let fl_right_val = gn_tree.arena[fl_child].val.clone();
1653            let fl_right_name = gn_tree.arena[fl_child].name.clone();
1654            let new_right_index = fl_tree.new_node(fl_right_val.to_string());
1655            fl_tree.arena[new_right_index].name = fl_right_name;
1656            fl_tree.arena[new_right_index].parent = Some(new_index);
1657            fl_tree.arena[new_index].children.push(new_left_index);
1658            fl_tree.arena[new_index].children.push(new_right_index);
1659            copie_fl(fl_tree, gn_tree, fl_child);
1661        }
1662    }
1663}
1664pub fn remplace_fl_inv(
1666    fl_tree: &mut ArenaTree<String>,
1667    gn_tree: &mut ArenaTree<String>,
1668    index: usize,
1669    ) {
1670    if ! fl_tree.arena[index].virtualsvg {
1671        let fl_val = fl_tree.arena[index].val.clone();
1672        let gn_index = gn_tree.get_node(fl_val.to_string());
1673        gn_tree.arena[gn_index].set_x_noref(fl_tree.arena[index].x);
1674        gn_tree.arena[gn_index].set_xmod_noref(fl_tree.arena[index].xmod);
1675        gn_tree.arena[gn_index].set_y_noref(fl_tree.arena[index].y);
1676        gn_tree.arena[gn_index].set_ymod_noref(fl_tree.arena[index].ymod);
1677    }
1678}
1679pub fn center_gene_nodes(
1681    sp_tree: &mut ArenaTree<String>,
1682    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
1683    index: usize,
1684    ) {
1685    let left_sp = sp_tree.arena[index].x - sp_tree.arena[index].width / 2.0  ;
1686    let right_sp = sp_tree.arena[index].x + sp_tree.arena[index].width / 2.0  ;
1687    let up_sp = sp_tree.arena[index].y + sp_tree.arena[index].ymod
1688        - sp_tree.arena[index].height / 2.0  ;
1689    let down_sp = sp_tree.arena[index].y + sp_tree.arena[index].ymod
1690        + sp_tree.arena[index].height / 2.0  ;
1691    let mut left_gene = -100000000.0;
1692    let mut right_gene = 100000000.0;
1693    let mut down_gene = -100000000.0;
1694    let mut up_gene = 100000000.0;
1695    for (index_node, node) in &sp_tree.arena[index].nodes {
1696        debug!("[center_gene_nodes] >>> {:?} {:?}",
1697            gene_trees[*index_node].arena[*node].name, gene_trees[*index_node].arena[*node].e);
1698        if  gene_trees[*index_node].arena[*node].x > left_gene {
1699            left_gene = gene_trees[*index_node].arena[*node].x;
1700        }
1701        if gene_trees[*index_node].arena[*node].x < right_gene {
1702            right_gene = gene_trees[*index_node].arena[*node].x;
1703        }
1704        if  gene_trees[*index_node].arena[*node].ymod > 0.0 {
1705            panic!("Unexpected ymod value");
1706        }
1707        if gene_trees[*index_node].arena[*node].y > down_gene {
1708            down_gene = gene_trees[*index_node].arena[*node].y;
1709        }
1710        if  gene_trees[*index_node].arena[*node].y < up_gene {
1711            up_gene = gene_trees[*index_node].arena[*node].y;
1712        }
1713    }
1714    let middle_sp = (left_sp + right_sp) / 2.0;
1715    let middle_gn = (left_gene + right_gene) / 2.0;
1716    let shift = middle_gn - middle_sp;
1717    let y_middle_sp = (up_sp + down_sp) / 2.0;
1718    let y_middle_gn = (up_gene + down_gene) / 2.0;
1719    let y_shift = y_middle_gn - y_middle_sp;
1720    for (index_node, node) in &sp_tree.arena[index].nodes {
1721        let x = gene_trees[*index_node].arena[*node].x;
1722        let x = x - shift ;
1723        gene_trees[*index_node].arena[*node].set_x_noref(x);
1724        let y = gene_trees[*index_node].arena[*node].y;
1725        let y = y - y_shift ;
1726        gene_trees[*index_node].arena[*node].set_y_noref(y);
1727    }
1728    let children = &mut sp_tree.arena[index].children;
1729    if children.len() > 0 {
1730        let son_left = children[0];
1731        let son_right = children[1];
1732        center_gene_nodes(sp_tree, gene_trees, son_left);
1733        center_gene_nodes(sp_tree, gene_trees, son_right);
1734    }
1735}
1736pub fn set_species_width(
1738    sp_tree: &mut ArenaTree<String>,
1739    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
1740    ) {
1741    for spindex in &mut sp_tree.arena {
1742        let nbg = spindex.nbg;
1743        let nodes = &spindex.nodes;
1744        let mut nb_duplication_node = 0;
1745        for (index_node, node) in nodes {
1746            if gene_trees[*index_node].arena[*node].e == Event::Duplication {
1747                nb_duplication_node = nb_duplication_node + 1;
1748            }
1749        }
1750        if nbg > 0 {
1752            spindex.width = ( nbg - nb_duplication_node ) as f32 * PIPEBLOCK;
1753            spindex.height = ( nbg - 0 ) as f32 * PIPEBLOCK;
1754        }
1755        else {
1756            spindex.width = PIPEBLOCK;
1757            spindex.height = PIPEBLOCK;
1758        }
1759    }
1760}
1761pub fn uniformise_gene_leaves_y_values(
1763    sp_tree: &mut ArenaTree<String>,
1764    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
1765    ) {
1766    let mut leave_y_max = 0.0;
1767    for spindex in & sp_tree.arena {
1768        if spindex.children.len() == 0 {
1770            for (index_node, node) in &sp_tree.arena[spindex.idx].nodes {
1771                if gene_trees[*index_node].arena[*node].location != "FREE_LIVING".to_string() &&
1772                gene_trees[*index_node].arena[*node].y > leave_y_max {
1773                     leave_y_max = gene_trees[*index_node].arena[*node].y;
1774                }
1775            }
1776        }
1777    }
1778    for spindex in & sp_tree.arena {
1779        if spindex.children.len() == 0 {
1781            for (index_node, node) in &sp_tree.arena[spindex.idx].nodes {
1782                if gene_trees[*index_node].arena[*node].location != "FREE_LIVING".to_string() &&  gene_trees[*index_node].arena[*node].e == Event::Leaf {
1784                    gene_trees[*index_node].arena[*node].set_y_noref(leave_y_max);
1785                }
1786            }
1787        }
1788    }
1789}
1790pub fn find_sptrees(doc: &mut roxmltree::Document) -> Result <Vec<roxmltree::NodeId>, usize> {
1792    let descendants = doc.root().descendants();
1793    let mut gene_nodes:std::vec::Vec<roxmltree::NodeId> = Vec::new();
1794    for  node in descendants {
1796        if node.has_tag_name("spTree"){
1797            gene_nodes.push(node.id());
1798        }
1799    }
1800    info!("[find_sptrees] Number of species trees in xml = {}",gene_nodes.len());
1801    match gene_nodes.len() > 0 {
1802        true => return Ok(gene_nodes),
1803        false => Err(0),
1804    }
1805}
1806pub fn find_rgtrees(doc: &mut roxmltree::Document) -> Result <Vec<roxmltree::NodeId>, usize> {
1808    let descendants = doc.root().descendants();
1809    let mut gene_nodes:std::vec::Vec<roxmltree::NodeId> = Vec::new();
1810    for  node in descendants {
1812        if node.has_tag_name("recGeneTree"){
1813            gene_nodes.push(node.id());
1814        }
1815    }
1816    info!("[find_rgtrees] Number of gene trees in xml = {}",gene_nodes.len());
1817    match gene_nodes.len() > 0 {
1818        true => return Ok(gene_nodes),
1819        false => Err(0),
1820    }
1821}
1822pub fn knuth_layout(tree: &mut ArenaTree<String>, index: usize, depth: &mut usize) {
1824    tree.arena[index].set_y_noref(BLOCK* (*depth as f32));
1825    let children  = &mut tree.arena[index].children;
1826    if children.len() > 2 {
1827        panic!("The tree must be binary.")
1828    }
1829    if children.len() > 0 {
1830        let son_left = children[0];
1831        let son_right = children[1];
1832        tree.arena[son_left].set_x_noref(0.0);
1833        tree.arena[son_right].set_x_noref(BLOCK);
1834        knuth_layout(tree, son_left, &mut(*depth+1));
1835        knuth_layout(tree, son_right, &mut(*depth+1));
1836    }
1837}
1838pub fn cladogramme(tree: &mut ArenaTree<String>) {
1840    let root = tree.get_root();
1841    let mut max_depth = get_maxdepth(tree, root, &mut 0);
1842    set_leaves_to_bottom(tree, root, &mut max_depth);
1843}
1844pub fn real_length(tree: &mut ArenaTree<String>, index: usize, dist: &mut f32, options: &Options) {
1846    let dist_father = tree.arena[index].l;
1847    let mut dist = *dist + dist_father;
1848    tree.arena[index].set_y_noref(dist * BLOCK * options.scale + BLOCK);
1849    let children  = &mut  tree.arena[index].children;
1850    if children.len() > 1 {
1851        let son_left = children[0];
1852        let son_right = children[1];
1853        real_length( tree, son_left, &mut dist, options);
1854        real_length( tree, son_right, &mut dist, options);
1855    }
1856}
1857pub fn get_maxdepth(tree: &mut ArenaTree<String>, index: usize, max :&mut usize) -> usize {
1859    let children  = &mut  tree.arena[index].children;
1860    if children.len() > 0 {
1861        let son_left = children[0];
1862        let son_right = children[1];
1863        if tree.depth(son_left) > *max {
1864            *max = tree.depth(son_left);
1865        }
1866        if tree.depth(son_right) > *max {
1867            *max = tree.depth(son_right);
1868        }
1869        get_maxdepth(tree,son_left,max);
1870        get_maxdepth(tree,son_right,max);
1871    }
1872    *max
1873}
1874pub fn get_root_distance(tree: &mut ArenaTree<String>, index: usize, dist :&mut usize) -> usize {
1876    match tree.arena[index].parent {
1877        None => *dist,
1878        Some(p) => {
1879            *dist = *dist + 1;
1880            return get_root_distance(tree,p,dist)
1881        }
1882    }
1883}
1884pub fn set_leaves_to_bottom(tree: &mut ArenaTree<String>, index: usize, max:&mut usize) {
1886    let children = &mut tree.arena[index].children;
1887    if children.len() > 0 {
1888        let son_left = children[0];
1889        let son_right = children[1];
1890        set_leaves_to_bottom(tree, son_left, max);
1891        set_leaves_to_bottom(tree, son_right, max);
1892    }
1893    else {
1894        match tree.arena[index].e {
1895            Event::Loss => tree.arena[index].set_y_noref(BLOCK* (*max as f32 + 0.5 )),
1896            _ => tree.arena[index].set_y_noref(BLOCK* (*max as f32 + 1.0)),
1897        };
1898    }
1899}
1900pub fn set_leaves_y_values(tree: &mut ArenaTree<String>, index: usize, y: f32) {
1902    let children  = &mut tree.arena[index].children;
1903    if children.len() > 0 {
1904        let son_left = children[0];
1905        let son_right = children[1];
1906        set_leaves_y_values(tree, son_left, y);
1907        set_leaves_y_values(tree, son_right, y);
1908    }
1909    else {
1910        match tree.arena[index].e {
1911            Event::Loss => {},
1912            _ => tree.arena[index].set_y_noref(y),
1913        };
1914    }
1915}
1916pub fn shift_nodes_y_values(tree: &mut ArenaTree<String>, index: usize, y:  f32) {
1918    let val = tree.arena[index].y + y ;
1919    tree.arena[index].set_y_noref(val);
1920    let children  = &mut  tree.arena[index].children;
1921    if children.len() > 0 {
1922        let son_left = children[0];
1923        let son_right = children[1];
1924        shift_nodes_y_values(tree, son_left, y);
1925        shift_nodes_y_values(tree, son_right, y);
1926    }
1927}
1928pub fn fusion_mod_xy(tree: &mut ArenaTree<String>, index_1: usize, index_2: usize) {
1930    if ((! tree.is_leaf(index_1) )  && ( tree.is_leaf(index_2) )) || (( tree.is_leaf(index_1) )  && ( !tree.is_leaf(index_2) )) {
1931        eprintln!("[fusion_mod_xy] ERROR Unable to merge {} and {}.",tree.arena[index_1].name,tree.arena[index_2].name);
1932        eprintln!("Merging between a leave and an internal node is not allowed.");
1933        process::exit(1)
1934    }
1935    let dist1 = tree.arena[index_1].x;
1936    let dist2 = tree.arena[index_2].x;
1937    let dist = ( dist1 + dist2 ) / 2.0 ;
1938    info!("[fusion_mod_xy] Before : x of {} = {}.",&tree.arena[index_1].name,tree.arena[index_1].x);
1939    info!("[fusion_mod_xy] Before : x of {} = {}.",&tree.arena[index_2].name,tree.arena[index_2].x);
1940    tree.arena[index_1].x = dist;
1941    tree.arena[index_2].x = dist;
1942    info!("[fusion_mod_xy] After : x of {} = {}.",&tree.arena[index_1].name,tree.arena[index_1].x);
1943    info!("[fusion_mod_xy] After : x of {} = {}.",&tree.arena[index_2].name,tree.arena[index_2].x);
1944    let width1 = tree.arena[index_1].width;
1945    let width2 = tree.arena[index_2].width;
1946    info!("[fusion_mod_xy] Before : width of {} = {}.",&tree.arena[index_1].name,tree.arena[index_1].width);
1947    info!("[fusion_mod_xy] Before : width of {} = {}.",&tree.arena[index_2].name,tree.arena[index_2].width);
1948    if tree.arena[index_1].nbg + tree.arena[index_1].nbg > 0 {
1949        tree.arena[index_1].width = width1 + width2;
1950        tree.arena[index_2].width = width1 + width2;
1951    }
1952    info!("[fusion_mod_xy] After : width of {} = {}.",&tree.arena[index_1].name,tree.arena[index_1].width);
1953    info!("[fusion_mod_xy] After : width of {} = {}.",&tree.arena[index_2].name,tree.arena[index_2].width);
1954    if (! tree.is_leaf(index_1) )  && (! tree.is_leaf(index_2) ) {
1955        let y1 = tree.arena[index_1].y;
1956        let y2 = tree.arena[index_2].y;
1957        info!("[fusion_mod_xy] Before : y of {} = {}.",&tree.arena[index_1].name,tree.arena[index_1].y);
1958        info!("[fusion_mod_xy] Before : y of {} = {}.",&tree.arena[index_2].name,tree.arena[index_2].y);
1959        match y1 as u32 > y2 as u32 {
1960            true =>  {
1961                tree.arena[index_2].y = tree.arena[index_1].y;
1962                let children = &tree.arena[index_2].children;
1963                let left = children[0];
1964                let right = children[1];
1965                shift_nodes_y_values(tree, left, y1 - y2);
1966                shift_nodes_y_values(tree, right, y1 - y2);
1967            },
1968            false => {
1969                tree.arena[index_1].y = tree.arena[index_2].y;
1970                let children = &tree.arena[index_1].children;
1971                let left = children[0];
1972                let right = children[1];
1973                shift_nodes_y_values(tree, left, y2 - y1);
1974                shift_nodes_y_values(tree, right, y2 - y1);
1975            },
1976        };
1977        info!("[fusion_mod_xy] After : y of {} = {}.",&tree.arena[index_1].name,tree.arena[index_1].y);
1978        info!("[fusion_mod_xy] After: y of {} = {}.",&tree.arena[index_2].name,tree.arena[index_2].y);
1979    }
1980}
1981pub fn shift_mod_xy(tree: &mut ArenaTree<String>, index: usize, xmod: &mut f32, ymod: &mut f32) {
1983    debug!("[shift_mod_xy] shifting {:?} xmod={} ymod={}", tree.arena[index], xmod, ymod);
1984    let x_father = tree.arena[index].x;
1985    let xmod_father = tree.arena[index].xmod;
1986    let mut xmod = *xmod + xmod_father;
1987    tree.arena[index].set_x_noref(x_father+xmod);
1988    let y_father = tree.arena[index].y;
1989    let ymod_father = tree.arena[index].ymod;
1990    let mut ymod = *ymod + ymod_father;
1991    tree.arena[index].set_y_noref(y_father+ymod);
1992    let children  = &mut  tree.arena[index].children;
1993    if children.len() > 2 {
1994        panic!("The tree must be binary")
1995    }
1996    if children.len() > 1 {
1997        let son_left = children[0];
1998        let son_right = children[1];
1999        shift_mod_xy(tree, son_left, &mut xmod, &mut ymod);
2000        shift_mod_xy(tree, son_right, &mut xmod, &mut ymod);
2001    }
2002}
2003pub fn scale_heigth(tree: &mut ArenaTree<String>, scale: f32) {
2005    for spindex in  &mut tree.arena {
2006        let y = spindex.y;
2007        spindex.y = y * scale;
2008    };
2009}
2010pub fn scale_width(tree: &mut ArenaTree<String>, scale: f32) {
2012    for spindex in  &mut tree.arena {
2013        let x = spindex.x;
2014        spindex.x = x * scale;
2015    };
2016}
2017pub fn species_uniformisation(tree: &mut ArenaTree<String>) {
2019    let mut max = 0;
2020    for spindex in  &mut tree.arena {
2021        if spindex.nbg > max {max = spindex.nbg};
2022    };
2023    for spindex in  &mut tree.arena {
2024        spindex.nbg = max;
2025    };
2026}
2027#[allow(dead_code)]
2028pub fn  explore_postorder(tree: &mut ArenaTree<String>, index: usize) {
2030    let children  = &mut tree.arena[index].children;
2031    if children.len() > 0 {
2032        let left = children[0];
2033        let right = children[1];
2034        explore_postorder(tree, left);
2035        explore_postorder(tree, right);
2036        println!("POST-ORDER TRAVERSAL : INTERNAL NODE  {:?} / DEPTH = {}",
2037            tree.arena[index], tree.depth(index));
2038    }
2039    else{
2040        println!("POST-ORDER TRAVERSAL : LEAF           {:?} / DEPTH = {}",
2041            tree.arena[index], tree.depth(index));
2042    }
2043}
2044pub fn  check_vertical_contour_postorder(tree: &mut ArenaTree<String>, index: usize, ymod: f32, compression: & f32) {
2046    let children  = &mut  tree.arena[index].children;
2047    if children.len() > 0 {
2048        let left = children[0];
2049        let right = children[1];
2050        debug!("[check_vertical_contour_postorder] Father = {} (ymod = {} ) , Left = {}, Right = {}",
2051            tree.arena[index].name, tree.arena[index].ymod, tree.arena[left].name,
2052            tree.arena[right].name);
2053        push_down(tree, index, left, right,compression);
2054        check_vertical_contour_postorder(tree, left, tree.arena[left].ymod + 0.0 *  ymod, compression);
2055        check_vertical_contour_postorder(tree, right, tree.arena[right].ymod + 0.0 * ymod, compression);
2056    }
2057}
2058pub fn push_down (tree: &mut ArenaTree<String>, parent: usize, left: usize, right: usize, compression: & f32) {
2061    let node_parent_down_pos = node_ypos(tree, parent, 1);
2062    let node_left_up_pos = node_ypos(tree, left, -1);
2063    let node_right_up_pos = node_ypos(tree, right, -1);
2064    if (node_left_up_pos <=  node_parent_down_pos + compression *  PIPEBLOCK ) ||
2065       (node_right_up_pos <= node_parent_down_pos + compression *  PIPEBLOCK ) {
2066        let shift_left = node_parent_down_pos - node_left_up_pos ;
2067        let shift_right = node_parent_down_pos - node_right_up_pos ;
2068        let mut shift_down = match shift_left > shift_right {
2069            true => shift_left,
2070            false => shift_right,
2071        };
2072        if shift_down <= PIPEBLOCK {
2073            shift_down = PIPEBLOCK;
2074        }
2075        let shift_down = shift_down + ( compression + 1.0 ) * PIPEBLOCK;
2077        debug!("[push_down] CONFLIT AT SPEC NODE {}: parent y = {} ymod = {} down = {} left up = {} right up = {} => shift = {}",
2078            tree.arena[parent].name, tree.arena[parent].y, tree.arena[parent].ymod,
2079            node_parent_down_pos, node_left_up_pos, node_right_up_pos, shift_down);
2080        debug!("[push_down] SHIFTING Y {} + 1xPIPEBLOCK = {}", shift_down, shift_down + 1.0 * PIPEBLOCK);
2081        debug!("Initial left : y = {}, ymod = {}", tree.arena[left].y, tree.arena[left].ymod);
2082        let y = tree.arena[left].y;
2083        let y = y + shift_down ;
2084        tree.arena[left].set_y_noref(y);
2085        let y = tree.arena[right].y;
2086        let y = y +shift_down ;
2087        tree.arena[right].set_y_noref(y);
2088    }
2089}
2090pub fn  check_contour_postorder(tree: &mut ArenaTree<String>, index: usize) {
2092    let children  = &mut  tree.arena[index].children;
2093    if children.len() > 0 {
2094        let left = children[0];
2095        let right = children[1];
2096        check_contour_postorder(tree, left);
2097        check_contour_postorder(tree, right);
2098        push_right(tree, left, right);
2099    }
2100    else{
2101    }
2102}
2103
2104
2105pub fn  check_contour_postorder_tidy_tree(
2107    tree: &mut ArenaTree<String>,
2108    index: usize,
2109    options: &Options,
2110    config: &Config,
2111    ) {
2112    info!("[check_contour_postorder_tidy_tree]");
2113    info!("[check_contour_postorder_tidy_tree] node {}",tree.arena[index].name);
2114    let children  = &mut  tree.arena[index].children;
2115    if children.len() > 0 {
2116        let left = children[0];
2117        let right = children[1];
2118        check_contour_postorder_tidy_tree(tree, right, options, config);
2119        check_contour_postorder_tidy_tree(tree, left, options, config);
2120        push_right_tidy_tree(tree, left, right, options, config);
2121        set_middle_postorder(tree, 0);
2122    }
2123}
2124
2125pub fn node_xpos(tree: &mut ArenaTree<String>, index: usize, xmod: f32, operator : i32) -> f32 {
2127    tree.arena[index].x + tree.arena[index].xmod
2128    + operator as f32 * tree.arena[index].nbg as f32 /2.0  *PIPEBLOCK + xmod
2129}
2130pub fn node_ypos(tree: &mut ArenaTree<String>, index: usize, operator: i32) -> f32 {
2132    tree.arena[index].y + tree.arena[index].ymod
2133    + operator as f32 * tree.arena[index].nbg as f32 /2.0  *PIPEBLOCK
2134}
2135pub fn  get_contour_left(
2137    tree: &mut ArenaTree<String>,
2138    index:usize,
2139    depth:usize,
2140    contour_left: &mut Vec<f32>,
2141    parent_xmod: f32,
2142    )  {
2143    debug!("[get_contour_left] >>> {:?}",tree.arena[index]);
2144    let local_depth = tree.depth(index) - depth; let node_left_pos = node_xpos(tree, index, parent_xmod, -1);
2146    if contour_left.len() <= local_depth {
2147        if tree.arena[index].xmod < 0.0 {
2148            panic!("Error: negative xmod.");
2149        }
2150        contour_left.push(node_left_pos);
2151        debug!("[get_contour_left] increment contour is now {:?}",contour_left);
2152    }
2153    if tree.arena[index].xmod < 0.0 {
2154        panic!("Error: negative  xmod.");
2155    }
2156    if node_left_pos <= contour_left[local_depth] {
2157        contour_left[local_depth] = node_left_pos;
2158       	debug!("[get_contour_left]: contour is now {:?}",contour_left);
2159    }
2160    let children  = &mut  tree.arena[index].children;
2161    if children.len() > 0 {
2162        let left = children[0];
2163        get_contour_left(tree, left, depth, contour_left, tree.arena[index].xmod + parent_xmod );
2164    }
2165}
2166pub fn  get_contour_right(
2168    tree: &mut ArenaTree<String>,
2169    index: usize,
2170    depth: usize,
2171    contour_right: &mut Vec<f32>,
2172    parent_xmod: f32,
2173    )  {
2174    debug!("[get_contour_right] process node {:?}",tree.arena[index]);
2175    let local_depth = tree.depth(index) - depth; let node_right_pos = node_xpos(tree, index, parent_xmod, 1);
2177    if contour_right.len() <= local_depth {
2178        if tree.arena[index].xmod < 0.0 {
2179            panic!("Error: negative xmod");
2180        }
2181        contour_right.push(node_right_pos);
2182            debug!("[get_contour_right] increment contour is now {:?}",contour_right);
2183    }
2184    if tree.arena[index].xmod < 0.0 {
2185        panic!("Error: negative xmod");
2186    }
2187    if node_right_pos >= contour_right[local_depth] {
2188        contour_right[local_depth] = node_right_pos ;
2189            debug!("[get_contour_right] contour is now {:?}",contour_right);
2190    }
2191    let children  = &mut tree.arena[index].children;
2192    if children.len() > 0 {
2193        let right = children[1];
2194        get_contour_right(tree, right, depth, contour_right, tree.arena[index].xmod + parent_xmod);
2195    }
2196}
2197pub fn  get_contour_tidy_right(
2199    tree: &mut ArenaTree<String>,
2200    index: usize,
2201    depth: usize,
2202    contour_right: &mut Vec<(f32,f32,String)>,
2203    ymax: &mut f32,
2204    options: &Options,
2205    config: &Config,
2206    )  {
2207    let x = tree.arena[index].x + tree.arena[index].nbg as f32 *PIPEBLOCK /2.0;
2209    let mut y = tree.arena[index].y + tree.arena[index].nbg as f32 *PIPEBLOCK /2.0;
2210    if tree.is_leaf(index) {
2212        y = y + match options.tidy_leaves_check {
2213            false => 5.0,
2214            true => {
2217                    match tree.arena[index].nbg > 0 {
2218                        true => {
2219                        5.0
2224                        },
2225                        false => tree.arena[index].name.len() as f32 * config.gene_police_size.parse::<f32>().unwrap(),
2226                    }
2227            },
2228        };
2229    }
2230    let name  = &tree.arena[index].name;
2231    if y >= *ymax {
2232        contour_right.push((x, y, name.to_string()));
2233        *ymax=y;
2234    }
2235    let children  = &mut  tree.arena[index].children;
2236    if children.len() > 0 {
2237        let right = children[1];
2238        let left = children[0];
2239        get_contour_tidy_right(tree, right, depth, contour_right, ymax, options, config);
2240        get_contour_tidy_right(tree, left, depth, contour_right, ymax, options, config);
2241    }
2242}
2243pub fn  get_contour_tidy_left(
2245    tree: &mut ArenaTree<String>,
2246    index: usize,
2247    depth: usize,
2248    contour_left: &mut Vec<(f32, f32, String)>,
2249    ymax: &mut f32,
2250    options: &Options,
2251    config: &Config,
2252    )  {
2253    let x = tree.arena[index].x  - tree.arena[index].nbg as f32 *PIPEBLOCK /2.0 ;
2254    let mut y = tree.arena[index].y + tree.arena[index].nbg as f32 *PIPEBLOCK /2.0;
2255    if tree.is_leaf(index) {
2257        y = y + match options.tidy_leaves_check {
2258            false => 5.0,
2259            true => tree.arena[index].name.len() as f32 *config.gene_police_size.parse::<f32>().unwrap(),
2260        };
2261    }
2262    let name =  &tree.arena[index].name;
2263    if y >= *ymax{
2264        *ymax = y;
2265        contour_left.push((x, y, name.to_string()));
2266    }
2267    let children  = &mut  tree.arena[index].children;
2268    if children.len() > 0 {
2269        let left = children[0];
2270        let right = children[1];
2271        get_contour_tidy_left(tree, left, depth, contour_left, ymax, options, config);
2272        get_contour_tidy_left(tree, right, depth, contour_left, ymax, options, config);
2273    }
2274}
2275pub fn  push_right(tree: &mut ArenaTree<String>, left_tree: usize, right_tree: usize) -> f32 {
2278    debug!("[push_right] compare right contour of {} and left contour of {}", left_tree, right_tree);
2279    let mut right_co_of_left_tr  = vec![tree.arena[left_tree].x
2280        + tree.arena[left_tree].xmod + tree.arena[left_tree].nbg as f32 *PIPEBLOCK];
2281    let depth_left_tr  = tree.depth(left_tree);
2282    get_contour_right(tree, left_tree, depth_left_tr, &mut right_co_of_left_tr, 0.0);
2283    debug!("[push_right] right contour of {} = {:?}", left_tree, right_co_of_left_tr);
2284    let mut left_co_of_right_tr  = vec![tree.arena[right_tree].x
2285        + tree.arena[right_tree].xmod - tree.arena[right_tree].nbg as f32 *PIPEBLOCK];
2286    let depth_right_tr  = tree.depth(right_tree);
2287    get_contour_left(tree, right_tree, depth_right_tr, &mut left_co_of_right_tr, 0.0);
2288    debug!("[push_right] left contour of {} = {:?}", right_tree, left_co_of_right_tr);
2289    let right_len = right_co_of_left_tr.len();
2293    let left_len = left_co_of_right_tr.len();
2294    if left_len > right_len {
2295        let last_val =  right_co_of_left_tr[right_len-1];
2296        let last_vals =  vec![last_val;left_len-right_len];
2297        right_co_of_left_tr.extend(last_vals.iter().copied());
2298        debug!("[push_right] complete right contour with last value {}",last_val);
2299    }
2300    if left_len < right_len {
2301        let last_val =  left_co_of_right_tr[left_len-1];
2302        let last_vals =  vec![last_val;right_len - left_len];
2303        left_co_of_right_tr.extend(last_vals.iter().copied());
2304        debug!("[push_right] complete left contour with last value {}",last_val);
2305    }
2306    debug!("[push_right] comparing  right cont. of left tree: {:?}",right_co_of_left_tr);
2307    debug!("[push_right] with left cont. of right tree:       {:?} ",left_co_of_right_tr);
2308    let iter = left_co_of_right_tr.iter().zip(right_co_of_left_tr).map(|(x, y )| (x-y));
2309    let shift = iter.min_by(|x, y| (*x as i64) .cmp(&(*y as i64 )));
2310    debug!("[push_right] distance max  = {:?}",shift);
2311    match shift {
2312        Some(val) => {
2313            debug!("[push_right] distance max  = {:?}",shift);
2314            if val <= 0.0 {debug!("[push_right] ================CONFLIT==========");
2316                debug!("[push_right] Modify node {:?}",tree.arena[right_tree]);
2317                let x_mod =  tree.arena[right_tree].xmod;
2318                debug!("[push_right] initial x_mod = {}",x_mod);
2319                let x_mod =  x_mod -1.0 *val + BLOCK ;debug!("[push_right] new x_mod = {}",x_mod);
2321                tree.arena[right_tree].set_xmod_noref(x_mod);
2322                debug!("[push_right] updated node {:?}",tree.arena[right_tree]);
2323                debug!("[push_right] ================CONFLIT==========");
2324            }
2325        },
2326        None => {}
2327    }
2328    0.0
2329}
2330pub fn  dmin_tidy(
2332    cont_left: Vec<(f32,f32,String)>,
2333    cont_right: Vec<(f32,f32,String)>,
2334    dmin: &mut f32,
2335    index_left: &mut usize,
2336    index_right: &mut usize,
2337    )  {
2338    let max_left = cont_left.len();
2339    let max_right = cont_right.len();
2340    debug!("[dmin_tidy] dmin {}",dmin);
2341    debug!("[dmin_tidy] left  contour {}{:?}", index_left, cont_left);
2342    debug!("[dmin_tidy] right contour {}{:?}", index_right, cont_right);
2343    debug!("[dmin_tidy] Compare x value of  right {} and  left  {}",
2344        cont_left[*index_left].2, cont_right[*index_right].2,);
2345    let d = cont_right[*index_right].0 - cont_left[*index_left].0;
2346    if d < *dmin {
2347        *dmin = d;
2348        debug!("[dmin_tidy] new dmin = {} ",dmin);
2349    }
2350    debug!("[dmin_tidy] Compare y value of  right {} {} and  left  {} {}",
2351        cont_left[*index_left].2, cont_left[*index_left].1, cont_right[*index_right].2,
2352        cont_right[*index_right].1);
2353    if cont_right[*index_right].1 <= cont_left[*index_left].1 {
2354        debug!("[dmin_tidy] increment right");
2355        *index_right = *index_right + 1;
2356        if *index_right < max_right {
2357            dmin_tidy(cont_left, cont_right, dmin, index_left, index_right);
2358        }
2359    }
2360    else  {
2361        debug!("[dmin_tidy] increment left");
2362        *index_left = *index_left + 1;
2363        if *index_left < max_left {
2364            dmin_tidy(cont_left, cont_right, dmin, index_left, index_right);
2365        }
2366    }
2367}
2368pub fn  push_right_tidy_tree(
2371    tree: &mut ArenaTree<String>,
2372    left_tree:usize,
2373    right_tree:usize,
2374    options: &Options,
2375    config: &Config
2376    ) {
2377    debug!("[push_right_tidy_tree]");
2378    debug!("[push_right_tidy_tree] Compare right contour of {} {} and left contour of {} {}",
2379        tree.arena[left_tree].val, tree.arena[left_tree].name, tree.arena[right_tree].val,
2380        tree.arena[right_tree].name);
2381    let mut  right_co_of_left_tr:std::vec::Vec<(f32,f32,String)> = Vec::new();
2382    let depth_left_tr = tree.depth(left_tree);
2383    get_contour_tidy_right(
2384        tree,
2385        left_tree,
2386        depth_left_tr,
2387        &mut right_co_of_left_tr,
2388        &mut 0.0,
2389        options,
2390        config,
2391    );
2392    debug!("[push_right_tidy_tree] Contour right = {:?}",right_co_of_left_tr);
2393    let mut  left_co_of_right_tr:std::vec::Vec<(f32,f32,String)> = Vec::new();
2394    let depth_right_tr  = tree.depth(right_tree);
2395    get_contour_tidy_left(
2396        tree,
2397        right_tree,
2398        depth_right_tr,
2399        &mut left_co_of_right_tr,
2400        &mut 0.0,
2401        options,
2402        config
2403    );
2404    debug!("[push_right_tidy_tree] Contour left = {:?}",left_co_of_right_tr);
2405    let mut dmin = 1000000.0;
2406    dmin_tidy(right_co_of_left_tr, left_co_of_right_tr, &mut dmin, &mut 0, &mut 0);
2407    debug!("[push_right_tidy_tree] DMIN = {:?} [max = {}]", dmin, PIPEBLOCK);
2408    if dmin > BLOCK * 0.50 {
2409        debug!("[push_right_tidy_tree] SHIFTING SUBTREE  {:?} {:?}",
2410            tree.arena[left_tree].val, tree.arena[left_tree].name);
2411        tree.shift_x_subtree(left_tree, dmin - BLOCK * 0.50  );
2412        set_middle_postorder(tree, 0);
2413    }
2414    else {
2415        debug!("[push_right_tidy_tree] NOT SHIFTING ");
2416    }
2417}
2418pub fn set_middle_postorder(tree: &mut ArenaTree<String>, index: usize) {
2420    let children  = &mut  tree.arena[index].children;
2421    if children.len() > 0 {
2422        let left = children[0];
2423        let right = children[1];
2424        set_middle_postorder(tree, left);
2425        set_middle_postorder(tree, right);
2426        debug!("[set_middle_postorder] node {:?}",index);
2427        let x_left = tree.arena[left].x;
2428        let x_right = tree.arena[right].x;
2429        let x = tree.arena[index].x;
2430        let x_middle = ( x_right + x_left ) / 2.0 ;
2431        debug!("[set_middle_postorder] x father set from {} to {}", x, x_middle);
2432        tree.arena[index].set_x_noref(x_middle);
2433        let x_mod =  tree.arena[right].xmod;
2434        let x_mod =  x_mod + x_middle - x;
2435        tree.arena[index].set_xmod_noref(x_mod);
2436    }
2437}
2438#[allow(dead_code)]
2440pub fn lca(tree: &mut ArenaTree<String>, index1: usize, index2: usize) -> usize {
2441    let p1 = tree.arena[index1].parent;
2442    let p2 = tree.arena[index2].parent;
2443    let p1 = match p1 {
2444        Some(p) => p,
2445        None => return index1,
2446    };
2447    let p2 = match p2 {
2448        Some(p) => p,
2449        None =>  return index2,
2450    };
2451    if p1 == index2 {
2452        return index2
2453    }
2454    if p2 == index1 {
2455        return index1
2456    }
2457    let d1 = tree.depth(index1);
2458    let d2 = tree.depth(index2);
2459    info!("[lca] Distance {}: {}", index1, d1);
2460    info!("[lca] Distance {}: {}", index2, d2);
2461    if d1 == d2 {
2462        info!("[lca] Comparison of {:?} and {:?}", tree.arena[index1], tree.arena[index2]);
2464        match p1 == p2  {
2465            true => {
2466                info!("[lca] LCA is {}",p1);
2467                 return p1
2468            },
2469            false => lca(tree, p1, p2),
2470        }
2471    }
2472    else if d1 > d2 {
2473        lca(tree, p1, index2)
2474    }
2475    else {
2476         lca(tree, index1, p2)
2477    }
2478}
2479#[allow(dead_code)]
2480pub fn summary_root(tree: &mut ArenaTree<String>, index: usize)  {
2481    let children  = &tree.arena[index].children;
2482    match children.len() > 0  {
2483        true => {
2484            let left = children[0];
2485            let right = children[1];
2486            println!("Node {} ({}) has 2 children: {} ({}) and {} ({})",
2487            index, &tree.arena[index].name,
2488            left, &tree.arena[left].name,
2489            right, &tree.arena[right].name);
2490            summary_root(tree, left);
2491            summary_root(tree, right);
2492        },
2493        false => {
2494            println!("Node {} ({}) has no children ", index, &tree.arena[index].name)
2495        },
2496    }
2497}
2498pub fn get_descendant(tree: & ArenaTree<String>, index: usize, descendants: &mut Vec<usize>)  {
2500    let node = & tree.arena[index];
2501    let children = &node.children;
2502    for child in children {
2503        descendants.push(*child);
2504        get_descendant(tree, *child, descendants);
2505    }
2506}
2507pub fn get_x_span(tree: & ArenaTree<String>, index: usize) -> (f32,f32) {
2509    let mut descendants:Vec<usize> = Vec::new();
2510    let mut min_x = 100000.0;
2511    let mut max_x = 0.0;
2512    get_descendant(tree,index,&mut descendants);
2513    for index in descendants {
2514        if tree.arena[index].x + tree.arena[index].width / 2.0 > max_x { max_x =  tree.arena[index].x + tree.arena[index].width / 2.0 }
2515        if tree.arena[index].x - tree.arena[index].width / 2.0 < min_x { min_x =  tree.arena[index].x - tree.arena[index].width / 2.0 }
2516        }
2517    (min_x, max_x)
2518}
2519
2520
2521pub fn make_invisible(tree: &mut ArenaTree<String>,
2525    gene_trees: &mut std::vec::Vec<ArenaTree<String>>,
2526    index: usize)  {
2527    let mut descendants:Vec<usize> = Vec::new();
2528    get_descendant(tree,index,&mut descendants);
2529    for index in descendants {
2531        tree.arena[index].visible = false;
2532        tree.arena[index].parent = None;
2533        for (idx_tree,idx_node) in  &tree.arena[index].nodes {
2534            gene_trees[*idx_tree].arena[*idx_node].visible = false;
2535
2536        }
2537    }
2538}
2539
2540#[allow(dead_code)]
2541pub fn reset_pos(tree: &mut ArenaTree<String>)  {
2543    for index in &mut tree.arena {
2544        index.x = 0.0;
2545        index.y = 0.0;
2546        index.xmod = 0.0;
2547        index.ymod = 0.0;
2548    };
2549}
2550#[allow(dead_code)]
2551pub fn summary(tree: &mut ArenaTree<String>)  {
2553    for index in &tree.arena {
2554        let children  = &index.children;
2555        let parent = match index.parent {
2556            Some(p) =>  &tree.arena[p].name,
2557            None => "None",
2558        };
2559        match children.len() > 0  {
2560            true => {
2561                print!("Node {} ({}) has {} children:", index.idx, index.name, children.len());
2562                for child in children {
2563                print!(" {} ({})", child, &tree.arena[*child].name);
2564            };
2565            print!(" and its parent is {}",parent);
2566            },
2567        false => {
2568            print!("Node {} ({}) has no children and its parent is {}", index.idx, index.name,parent)
2569            },
2570        }
2571        println!(" [{:?}]",index.e);
2572    }
2573}
2574#[allow(dead_code)]
2575pub fn add_child(tree: &mut ArenaTree<String>, parent: usize, child: usize)  {
2577    info!("[add_child] adding {} to {}",child,parent);
2578    tree.arena[child].parent = Some(parent);
2579    tree.arena[parent].children.push(child);
2580    info!("[add_child] parent node : {:?}",tree.arena[parent]);
2581}
2582#[allow(dead_code)]
2583pub fn move_child(tree: &mut ArenaTree<String>, child: usize, new_parent: usize)  {
2585    let parent =  match tree.arena[child].parent {
2586        Some(p) => p,
2587        None => panic!("Node {:?} has no parent.",child),
2588    };
2589    info!("[move_child] moving {} from {} to {}", child, parent, new_parent);
2590    tree.arena[child].parent = Some(new_parent);
2591    tree.arena[new_parent].children.push(child);
2592    tree.arena[parent].children.retain(|&x| x !=  child);
2593    info!("[move_child] parent node : {:?}",tree.arena[parent]);
2594    info!("[move_child] new parent node : {:?}",tree.arena[new_parent]);
2595}