/examples/example_V2.7.R

http://github.com/sbotond/phylosim · R · 65 lines · 25 code · 17 blank · 23 comment · 0 complexity · 60a25d2ff63e7475a2c0cb689b377d75 MD5 · raw file

  1. #!/usr/bin/env Rscript
  2. ##
  3. ## Example V2.7: Simulating many replicates in parallel
  4. ## See also the package vignette (vignette("PhyloSim",package="phylosim")).
  5. ##
  6. # load PhyloSim
  7. library("phylosim")
  8. # The the speed of the above method for simulating replicates can be improved on a multicore machine by running
  9. # many replicates in parallel by using the mclapply method from the multicore package.
  10. # Under default settings, the mclapply method launches one replication per core and this approach needs enough memory to run all
  11. # of them in parallel.
  12. # The following code illustrates how to simulate many replicates in parallel under the JC69+dG model.
  13. # Construct the root sequence object and attach the substitution process:
  14. p<-JC69();
  15. root.seq<-NucleotideSequence(length=50)
  16. attachProcess(root.seq,p)
  17. # Read the required phylogeny from file (this will remain fixed in the simulated replicates):
  18. tree<-read.tree("data/3taxa.nwk");
  19. # Function to simulate a single replication:
  20. sim.replicate<-function(i){
  21. name<-paste("replication_",i,sep="")
  22. clearStates(root.seq)
  23. plusGamma(root.seq,p,0.25)
  24. sampleStates(root.seq)
  25. sim<-Simulate(PhyloSim(
  26. name=name,
  27. root.seq=root.seq,
  28. phylo=tree,
  29. ),
  30. quiet=TRUE
  31. )
  32. saveAlignment(sim,file=paste("aln_",i,".fas",sep=""))
  33. return(sim)
  34. # return(TRUE)
  35. }
  36. # Note that the states are cleared and resampled; the rate multipliers
  37. # are resampled as well. The resulting alignments are stored in files aln_1.fas, aln_2.fas, aln_3.fas.
  38. # Memory can be saved by throwing away the objects generated by the replication by returning TRUE from the
  39. # sim.replicate function.
  40. # Load the multicore package:
  41. library(multicore)
  42. # Run replicates in parallel:
  43. nr.replicates <-3
  44. res.objects<-mclapply(1:nr.replicates, sim.replicate)
  45. # Print the resulting PhyloSim objects:
  46. print(res.objects)
  47. # Plot one of the resulting alignments:
  48. plot(res.objects[[1]])