2D MODPATH particle tracking animations with R and ImageMagick

December 14, 2012
By

(This article was first published on Bart Rogiers - Sreigor, and kindly contributed to R-bloggers)

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:

install.packages('animation')
library(animation)
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')
{
write.gif(nr=modpath$nr, x=modpath$x, y=modpath$y, t=modpath$time,
}

{
modpath <- scan(filename, what=character(), sep='\n')
modpath <- modpath[-c(1:3)]
modpath.data.frame <- matrix(nrow=length(modpath), ncol=10)
for(i in 1:length(modpath))
{
split <- strsplit(modpath[[i]],c(' '))
modpath.data.frame[i,] <- as.numeric(split[[1]][-which(split[[1]]=='')])
}
modpath.data.frame <- as.data.frame(modpath.data.frame)
names(modpath.data.frame) <- c('nr','x','y','z','global.z','time','i','j','k','dummy')
return(modpath.data.frame)
}

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)
saveGIF({
for(i in 1:steps)
{
time <- i*max.time/steps
times <- which(t <= time)
par(mar=c(0,0,0,0))
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')
}}, movie.name=file)
}
Created by Pretty R at inside-R.org