Skip to content

Commit

Permalink
fromNewick can reuse leafs
Browse files Browse the repository at this point in the history
  • Loading branch information
starius committed May 16, 2015
1 parent f56f6ed commit 34b0286
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
40 changes: 40 additions & 0 deletions spec/newick_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,44 @@ D E
assert.equal(5, #tree2:nodes())
assert.equal(3, #tree2:leafs())
end)

it("serializes and parses a complex tree (same leafs)",
function()
local Tree = require 'tree.Tree'
local A = {name='A'}
local B = {name='B'}
local C = {name='C'}
local D = {name='D'}
local E = {name='E'}
local tree = Tree {
[A] = {[B] = {length=1}, [C] = {length=2}},
[B] = {[D] = {length=3}, [E] = {length=4}},
}
--
local toNewick = require 'tree.toNewick'
local newick = toNewick(tree)
assert.truthy(newick:match('%)B:1'))
assert.truthy(newick:match('C:2'))
assert.truthy(newick:match('D:3'))
assert.truthy(newick:match('E:4'))
--
local fromNewick = require 'tree.fromNewick'
local leafs = {C, D, E}
local tree2 = fromNewick(newick, leafs)
assert.equal(5, #tree2:nodes())
assert.equal(3, #tree2:leafs())
assert.truthy(tree2:isLeaf(C))
assert.truthy(tree2:isLeaf(D))
assert.truthy(tree2:isLeaf(E))
assert.falsy(tree2:isNode(A))
assert.falsy(tree2:isNode(B))
local A2 = tree2:parentOf(C)
local B2 = tree2:parentOf(D)
assert.equal(A2, tree2:parentOf(B2))
assert.equal(B2, tree2:parentOf(E))
assert.equal(1, tree2:edge(A2, B2).length)
assert.equal(2, tree2:edge(A2, C).length)
assert.equal(3, tree2:edge(B2, D).length)
assert.equal(4, tree2:edge(B2, E).length)
end)
end)
12 changes: 10 additions & 2 deletions src/tree/fromNewick.lua
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ grammar (semicolon, parentheses, comma, and colon) are
prohibited.
]]

return function(text)
return function(text, leafs)
local lpeg = require 'lpeg'
local V, R, S, L = lpeg.V, lpeg.R, lpeg.S, lpeg.locale()

Expand Down Expand Up @@ -93,10 +93,18 @@ return function(text)
}
]]

local name2leaf = {}
if leafs then
for _, leaf in ipairs(leafs) do
name2leaf[leaf.name] = leaf
end
end

local children_of = {}

local function fromNewick(raw_node)
local node = {name = raw_node.name}
local name = raw_node.name
local node = name2leaf[name] or {name = name}
children_of[node] = {}
for _, raw_child in ipairs(raw_node) do
local child = fromNewick(raw_child)
Expand Down

0 comments on commit 34b0286

Please sign in to comment.