UNPKG

phylojs

Version:

A simple typescript library for phylogenetic trees

50 lines (49 loc) 1.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.readTreesFromPhyJSON = exports.readPhyJSON = void 0; const __1 = require("../../"); function preprocessTaxa(taxa) { const taxaMap = {}; for (const taxon of taxa) { if (taxon.id && taxon.name) { taxaMap[taxon.id] = taxon.name; } } return taxaMap; } function buildTree(node, taxaMap, currentId) { const tree = new __1.Node(currentId); tree.label = node.taxon ? taxaMap[node.taxon] || undefined : undefined; // Use taxaMap for label lookup tree.branchLength = node.branch_length; // Recursively handle children, if any if (node.children) { node.children.forEach((child, index) => { const childNode = buildTree(child, taxaMap, currentId + 1 + index); // Increment ID for each child uniquely tree.addChild(childNode); }); } return tree; // Return the current tree node and the next available ID } function parse(phyNode, taxaMap) { const rootNode = buildTree(phyNode, taxaMap, 0); const tree = new __1.Tree(rootNode); return tree; } function readPhyJSON(phyJSONString) { const obj = JSON.parse(phyJSONString); const taxaMap = preprocessTaxa(obj.taxa); const phyRoot = obj.trees[0].root; return parse(phyRoot, taxaMap); } exports.readPhyJSON = readPhyJSON; function readTreesFromPhyJSON(phyJSONString) { const obj = JSON.parse(phyJSONString); const taxaMap = preprocessTaxa(obj.taxa); const trees = []; for (const treeObj of obj.trees) { const tree = parse(treeObj.root, taxaMap); trees.push(tree); } return trees; } exports.readTreesFromPhyJSON = readTreesFromPhyJSON;