Friday, 14 December 2012

2D MODPATH particle tracking animations with R and ImageMagick 14.12.12

The PMPATH particle tracking output, with a file format similar to the pathline output mode of MODPATH (see above), can be transformed easily into a GIF animation using R and ImageMagick (see below for a simple example).
First of all, you need a working installation of ImageMagick and you have to install and load the R animation package. Possibly you have to adjust the path to the convert executable (default paths are specified, but if something goes wrong, this would be the first thing to check), as shown below:

ani.options(convert='C:/Program Files/ImageMagick-6.7.9-Q16/convert.exe')

The following functions provide you a way to read the modpath pathline output mode format, and create a 2D GIF animation based on the particle numbers (nr), x- and y-coordinates (x; y) and time indication (t). Additionally you need to specify the number of frames (steps), duration of a single frame (step.time), maximum time (max.time) and a scaling factor (scaling.factor) to get different particle tracking animations in proportion. The rest of the code should be pretty straightforward.

animate <- function(filename, axes=T, cex=0.5, pch=16, lines=T, pathline.file.extension='.pathline.dat', animation.file.extension='.gif')
  modpath <- read.modpath(paste(filename,pathline.file.extension,sep=''))
  write.gif(nr=modpath$nr, x=modpath$x, y=modpath$y, t=modpath$time,
            file=paste(filename,filename.adj,sep=''), axes=axes, cex=cex, pch=pch, lines=lines)
read.modpath <- function(filename)
  modpath <- scan(filename, what=character(), sep='\n')
  modpath <- modpath[-c(1:3)] <- matrix(nrow=length(modpath), ncol=10)
  for(i in 1:length(modpath))
    split <- strsplit(modpath[[i]],c(' '))[i,] <- as.numeric(split[[1]][-which(split[[1]]=='')])
  } <-
  names( <- c('nr','x','y','z','global.z','time','i','j','k','dummy')
write.gif <- function(nr, x, y, t, file, steps=500, step.time=0.1, max.time=72000, axes, cex, pch, lines, scaling.factor=200)
  ani.options(interval=step.time,outdir = getwd(),nmax=steps, ani.width=max(x)*scaling.factor,ani.height=max(y)*scaling.factor)
    for(i in 1:steps) 
      time <- i*max.time/steps 
      times <- which(t <= time)
      plot(x, y, type='n', xlab='x',ylab='y',axes=axes)
      for(j in 1:max(nr))
        if(lines) lines(x[times][which(nr[times]==j)], y[times][which(nr[times]==j)],lty=2, col='gray')
        points(x[times][max(which(nr[times]==j))], y[times][max(which(nr[times]==j))],cex=cex,pch=pch)
      legend('bottomright',legend=c(time), bty='n')
5 Bart Rogiers: 2D MODPATH particle tracking animations with R and ImageMagick The PMPATH   particle tracking output, with a file format similar to the pathline output mode of ...

No comments:

Post a comment:

< >