Generating random fields using Rpy2

Following on the previous post, here’s one way to generate random fields using Rpy2 and the R RandomFields package. Let’s assume your data are in the lat, lon, data vectors, first we import modules, set some options and fit a variogram (check the RandomFields documentation for details)

import rpy2.robjects as robjects
import rpy2.robjects.numpy2ri
R=robjects.r
R.library('RandomFields')
TF={'table.format':True,'lsq.methods':'self','mle.methods':'NULL'}
estparam=robjects.FloatVector((mean(data),var(data),None,None,None))
F=R.fitvario(lon,lat,data=datam,model='whittlematern',param=estparam,**TF)

The number of parameters depends on the model selection, having the format (mean,variance,nugget,scale,…), while each parameter that needs to be estimated is set to None when calling fitvario. The option table.format sets the output to a matrix, so now we can get the parameters (first index is column, second is row), do a

print(F)

to check what the available values are, e.g.

nugget=F[2][3]
scale=F[2][2]
kappa=F[2][1]

Then we can simulated random field realizations

estparam=robjects.FloatVector((mean(data),var(data),nugget,scale,kappa))
newdata=R.GaussRF(lon,lat,grid=False,model='whittlematern',param=estparam,n=num)

where num is the number of realizations.

No comments yet

Leave a comment