########################################
# Implementation of Birth-Death-Trees. #
#                 Daniel Dalquen, 2010 #
########################################

module external BirthDeathTree, ScaleTree, AddDeviation, ScaleTreeLength;
# Generates a sample Birth-Death-Tree with nSpecies descendents conforming to birth and death
# rate lambda and mu, respectively with an assumed time tHeight since origin.
# The procedure uses the equality of the birth-death process with a point process as described in
# T. Gernhard, 'The conditioned reconstructed process', J. Theo. Biol. (2008) 253(4): 769-778
# reducing the generation of the tree to drawing nSpecies time points from an exponential distribution
# Sampling is done using F^(-1) from Hartmann et al.,'Sampling Trees from Evolutionary Models', 
# Syst. Biol. (2010) 59(4):465-476, p. 475f
BirthDeathTree := proc(lambda:nonnegative, mu:nonnegative, nSpecies:posint, tHeight:positive)
    specPoints := sort([seq(tHeight - invCDF(lambda, mu, Rand(), tHeight), nSpecies - 1)], x->-x):
    
    living := 1:
    tree := [seq(Leaf('S'.i, tHeight), i=1..nSpecies)]:
    
    for i to nSpecies-1 do
        r := Rand(1..length(tree)-1):
        tree := [op(tree[1..r-1]), Tree(tree[r], specPoints[i], tree[r+1]), op(tree[r+2..-1])]:
    od:
    tree := op(tree):
end:


CDF := proc(lambda, mu, s, t) option internal;
    if lambda = mu then
        F := s / (1 + lambda*s) * (1 + lambda*t) / t;
    else
        F := (1-exp(-(lambda-mu)*s))*(lambda-mu*exp(-(lambda-mu)*t)) / ((lambda-mu*exp(-(lambda-mu)*s))*(1-exp(-(lambda-mu)*t)));
    fi:
    F
end:


invCDF := proc(lambda, mu, r, t) option internal;
    if lambda = mu then
        s := r * t / (1 + lambda * t * (1 - r));
    else
        c := (lambda - mu * exp(-(lambda - mu) * t))/(1 - exp(-(lambda - mu) * t));
        s := (ln(c - r * mu) - ln(c - r * lambda)) / (lambda - mu)
    fi:
    s
end:

FindDeepestLeaf := proc(tree:Tree) option internal;
    if type(tree, Leaf) then
        res := tree[Height]:
    else
        t1 := FindDeepestLeaf(tree[Left]):
        t2 := FindDeepestLeaf(tree[Right]):
        res := max(t1,t2):
    fi:
    res
end:

ScaleTreeHeight := proc(tree:Tree, factor:float, offset:float) option internal;
    tree[Height] := (tree[Height] - offset) * factor:
    if not type(tree, Leaf) then
        ScaleTreeHeight(tree[Left], factor, offset):
        ScaleTreeHeight(tree[Right], factor, offset):
    fi:
end:

ScaleTree := proc(tree:Tree, height:positive)
    newTree := copy(tree):
    curh := FindDeepestLeaf(newTree) - newTree[Height]:
    hfac := height / curh:
    ScaleTreeHeight(newTree, hfac, newTree[Height]):
    
    newTree
end:

ScaleTreeLength := proc(t:Tree, newLength)
    newTree := copy(t):
    oldLength := -TotalTreeWeight(t):
    fac := newLength/oldLength:
    ScaleTreeHeight(newTree, fac, newTree[Height]):
    
    newTree
end:

AddDeviation := proc(t:Tree; (remTrunk=true):boolean)
    newTree := copy(t):
    curh := FindDeepestLeaf(newTree) - newTree[Height]:
    #printf('curh: %g\n', curh):
    mu := 0.2/(0.001+Rand()):

    # add deviation to tree
    AddDeviation_R(newTree, mu):
    
    # normalize tree
    if remTrunk then
        newh := FindDeepestLeaf(newTree) - newTree[Height]:
        #printf('newh: %g\n', newh):
        ScaleTreeHeight(newTree, curh / newh, newTree[Height]):
    fi:
    newTree
end:

AddDeviation_R := proc(t:Tree, mu:numeric) option internal;
    # left subtree
    x := Rand(Exponential(0,mu)):
    curblen := t[Left, Height] - t[Height]:
    newblen := (1+x) * curblen:
    PropagateDeviation(t[Left], newblen - curblen):
    if not type(t[Left], Leaf) then
        AddDeviation_R(t[Left], mu):
    fi:

    # right subtree
    x := Rand(Exponential(0,mu)):
    curblen := t[Right, Height] - t[Height]:
    newblen := (1+x) * curblen:
    PropagateDeviation(t[Right], newblen - curblen):
    if not type(t[Right], Leaf) then
        AddDeviation_R(t[Right], mu):
    fi:
end:

PropagateDeviation := proc(t:Tree, delta:numeric) option internal;
    t[Height] := t[Height] + delta:
    if not type(t, Leaf) then
        PropagateDeviation(t[Left], delta):
        PropagateDeviation(t[Right], delta):
    fi:
end:

end: # module
