Skip to content

Instantly share code, notes, and snippets.

@DomBennett
Created January 25, 2018 13:15
Show Gist options
  • Save DomBennett/c921b5370d6fce3603e90ad4b514766d to your computer and use it in GitHub Desktop.
Save DomBennett/c921b5370d6fce3603e90ad4b514766d to your computer and use it in GitHub Desktop.
Calculating trip dist in parallel
# LIB
library(treeman)
library(doMC)
library(foreach)
# FUNCTION
randTreeList <- function(n) {
res <- vector(mode='list', length=n)
for(i in 1:n) {
res[[i]] <- randTree(20, wndmtrx=TRUE)
}
res
}
# VARS
registerDoMC(cores=4)
treeset1 <- randTreeList(10)
treeset2 <- randTreeList(10)
# LOOP
res <- foreach(i=1:length(treeset1)) %dopar% {
prt <- vector('list', length=length(treeset2))
for(j in 1:length(treeset2)) {
prt[[j]] <- calcDstTrp(tree_1=treeset1[[i]],
tree_2=treeset2[[i]],
nrmlsd=TRUE)
}
prt
}
# CONVERT TO DF
dresultTD1 <- data.frame(res)
molmorph <- apply(dresultTD1, 1, FUN=min)
morphmol <- apply(dresultTD1, 2, FUN=min)
meanTD <- mean(molmorph)
meanTD <- append(meanTD,(mean(morphmol)))
TDbayes <- mean(meanTD)
# LIB
library(treeman)
library(doMC)
# VARS
# for windows you will need to use
# doSnow -- https://github.com/DomBennett/treeman/wiki/Running-in-parallel
# use detectCores() if you don't know how many parallel processes you can run
registerDoMC(cores=2)
tree1 <- randTree(100)
tree2 <- randTree(100)
# N.B. for small trees using parallel may make function take longer
# CALC DIST W PARALLEL
system.time(res <- calcDstTrp(tree1, tree2,
parallel=TRUE))
# WNDMTX
# Adding a node matrix *should* lead to a speed gain
# (particularly for large trees) at the cost of extra
# memory usage and taking longer to read the file.
tree1 <- addNdmtrx(tree1)
tree2 <- addNdmtrx(tree2)
system.time(res <- calcDstTrp(tree1, tree2,
parallel=TRUE))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment