library(ape)

tre <- read.tree("https://raw.githubusercontent.com/macroevolution/bamm/ab1b69be13e9841d9e103170d0f61e4324f78676/examples/diversification/whales/whaletree.tre")

## Compute root to tip distances
N <- Ntip(tre)
root_node <- N + 1
root_to_tip <- dist.nodes(tre)[1:N, root_node]
scaled_root_to_tip <- root_to_tip * 1000

## Method: variance of root to tip distnace
var(root_to_tip)
var(scaled_root_to_tip)

## Method: relative difference of root to tip
min_tip <- min(root_to_tip)
max_tip <- max(root_to_tip)
(max_tip - min_tip) / max_tip

min_tip <- min(scaled_root_to_tip)
max_tip <- max(scaled_root_to_tip)
(max_tip - min_tip) / max_tip

## Method - difference for each node

# This holds our internal calculations for how "old" a node should be.
tre_node_adjust <- reorder(tre, "postorder")
ages <- numeric(N + tre_node_adjust$Nnode)
e1 <- tre_node_adjust$edge[, 1] # parent node
e2 <- tre_node_adjust$edge[, 2] # child node
EL <- tre_node_adjust$edge.length

for (ii in seq_along(EL)) {
    if (ages[e1[ii]] == 0) {
        ages[e1[ii]] <- ages[e2[ii]] + EL[ii]
    } else {
        recorded_age <- ages[e1[ii]]
        new_age <- ages[e2[ii]] + EL[ii]
        if (recorded_age != new_age) {
            cat(sprintf("node %i age %.6f != %.6f\n", e1[ii], recorded_age, new_age))
            # "Adjust" the edge length
            EL[ii] <- recorded_age - ages[e2[ii]]
        }
    }
}

# Copy over the new edge lengths
tre_node_adjust$edge.length <- EL
tre_node_adjust <- reorder(tre_node_adjust, "cladewise")

# Fix 1: Extend tips
# Use root to tip distances from before
tre_extend <- tre
age_difference <- max(root_to_tip) - root_to_tip

# tip edges should be in the same 1:N order in the edge matrix
tip_edges <- tre_extend$edge[, 2] <= Ntip(tre_extend)
tre_extend$edge.length[tip_edges] <- tre_extend$edge.length[tip_edges] + age_difference

is.ultrametric(tre_extend)

# Fix 3: NNLS (phytools / phangorn)
tre_nnls <- phangorn::nnls.tree(cophenetic(tre), tre, rooted = TRUE)

is.ultrametric(tre, tol = .Machine$double.eps * 2)
is.ultrametric(tre_extend, tol = .Machine$double.eps * 2)
is.ultrametric(tre_node_adjust, tol = .Machine$double.eps * 2)
is.ultrametric(tre_nnls, tol = .Machine$double.eps * 2)
is.ultrametric(tre_nnls, tol = .Machine$double.eps * 4)

## Highlight differing tips

diff_edge_lengths <- function(phy, phy2) {
    diffs <- phy2$edge.length - phy$edge.length
    cols <- sign(diffs)
    cols[cols == 1] <- "#7fbc41"
    cols[cols == -1] <- "#de77ae"
    cols[cols == 0] <- NA
    plot(phy, show.tip.label = FALSE, no.margin = TRUE)
    edgelabels(pch = 15, col = cols)
    sprintf("%i longer branches, %i shorter branches", sum(diffs > 0), sum(diffs < 0))
}

png("extend.png", width = 7, height = 7, units = "in", bg = "transparent", res = 150)
diff_edge_lengths(tre, tre_extend)
dev.off()

png("nnls.png", width = 7, height = 7, units = "in", bg = "transparent", res = 150)
diff_edge_lengths(tre, tre_nnls)
dev.off()

png("adjust_nodes.png", width = 7, height = 7, units = "in", bg = "transparent", res = 150)
diff_edge_lengths(tre, tre_node_adjust)
dev.off()

# rmarkdown::render("go.R", "md_document")
