Wednesday, March 14, 2018

Some points moving around randomly in a box

For my PopGen I was thinking about writing some spatial population genetic simulations.

First I thought I'd write a little animation of things moving randomly in two dimensions. Here's what that looks like:

moving.randomly<-function(sig2=0.1,ngen=1000,sleep=0.1){
    x<-rep(1:9,9)
    y<-c()
    for(i in 1:9) y<-c(y,rep(i,9))
    n<-length(x)
    dev.hold()
    plot(x,y,xlim=c(0,10),ylim=c(0,10),pch=21,
        bg=phytools:::make.transparent("blue",0.2),cex=2)
    lines(c(0,0,10,10,0),c(0,10,10,0,0),lwd=6,
        col=phytools:::make.transparent("blue",0.2))    
    dev.flush()
    for(i in 1:ngen){
        x<-x+rnorm(n=n,sd=sqrt(sig2))
        while(!(all(x<10)&&all(x>0))){
            x[which(x<0)]<-abs(x[which(x<0)])
            x[which(x>10)]<-10-(x[which(x>10)]-10)
        }
        y<-y+rnorm(n=n,sd=sqrt(sig2))
        while(!(all(y<10)&&all(y>0))){
            y[which(y<0)]<-abs(y[which(y<0)])
            y[which(y>10)]<-10-(y[which(y>10)]-10)
        }
        dev.hold()
        plot(x,y,xlim=c(0,10),ylim=c(0,10),pch=21,
            bg=phytools:::make.transparent("blue",0.2),cex=2)
        lines(c(0,0,10,10,0),c(0,10,10,0,0),lwd=6,
            col=phytools:::make.transparent("blue",0.2))
        dev.flush()
        Sys.sleep(sleep)
    }
}
moving.randomly(sig2=0.01)

The above .gif I actually made & then subsequently embedded in the .html using ImageMagick as follows:

png(file="mr-%04d.png",width=600,height=600)
moving.randomly(sig2=0.01,sleep=0)
dev.off()
system("ImageMagick convert -delay 10 -loop 0 *.png 14Mar18b-post.gif")
file.remove(list.files(pattern=".png"))

1 comment:

  1. I bought a watch for my friend in this online store. My friend loves him very much. This replica watch has a very high quality and the quality is almost the same as that of the real brand. perfect luxury watches
    It is a very good shopping site. I share this shopping site with my friends. perfect roger-dubuis luxury watches

    ReplyDelete