iham-parsers
Version:
orthoxml, phyloxml and newick parsers for the iHam widget
86 lines (81 loc) • 3.22 kB
JavaScript
/**
* Collection of functions operating on a tree
*
* Copyright (c) Adrian Altenhoff 2017
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
module.exports = {
extractParentRelations : function(tree) {
var uprels = {};
var rec_trav = function(node){
if (node !== undefined && node.children !== undefined) {
node.children.forEach(function (child) {
uprels[child.name] = node.name;
});
node.children.map(rec_trav);
}
};
rec_trav(tree);
return uprels;
},
ladderize: function(tree){
var rec_trav = function(node){
var tot_children;
if (node.children !== undefined){
var rec_res = node.children.map(rec_trav);
rec_res.sort(function(a,b){
if (a.cnts !== b.cnts) {
return a.cnts - b.cnts;
} else {
return a.data.name.localeCompare(b.data.name);
}
});
tot_children = rec_res.map(x => x.cnts).reduce((a, b) => a + b, 0);
node.children = rec_res.map(x => x.data);
} else {
tot_children = 1;
}
return {cnts: tot_children, data: node};
};
return rec_trav(tree).data;
},
extractTree: function (xmltree) {
if (xmltree && (xmltree.constructor === Array) && (xmltree[0].rooted !== undefined)){
return xmltree[0].children[0];
} else { return xmltree; }
},
add_nodenames_from_taxonomy_if_needed: function(tree){
var rec_trav = function(node){
if ((node.name === undefined) && (node.taxonomies !== undefined)){
node.name = node.taxonomies[0].scientific_name;
}
if (node.children !== undefined){
node.children.map(rec_trav);
}
};
rec_trav(tree);
return tree;
},
same_trees: function(t1, t2){
var rec_trav = function(n1, n2){
if (n1.name !== n2.name) return false;
if (!n1.children && !n2.children) return true; // identical leaves
if ((!n1.children && n2.children) || (n1.children && !n2.children) ||
(n1.children.length !== n2.children.length)) return false; // one leaf, the other not, or different nr children
let sames = n1.children.map(function(e, i){
return rec_trav(e, n2.children[i]);
});
return sames.every(x => x);
};
return rec_trav(t1, t2);
}
};