Created
October 23, 2011 02:45
-
-
Save brentp/1306786 to your computer and use it in GitHub Desktop.
simulate spatially correlated data in R and python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# generate autocorrelated data. | |
nLags = 75 # number of lags (size of region) | |
# fake, uncorrelated observations | |
X = rnorm(nLags) | |
############################################### | |
# fake sigma... correlated decreases distance. | |
sigma = diag(nLags) | |
corr = 0.7 | |
sigma <- corr ^ abs(row(sigma)-col(sigma)) | |
############################################### | |
# Y is autocorrelated... | |
Y <- t(X %*% chol(sigma)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from scipy.stats import norm | |
from numpy.linalg import cholesky as chol | |
qnorm = norm.ppf | |
pnorm = norm.cdf | |
def gen_correlated(sigma, n): | |
""" | |
generate autocorrelated data according to the matrix | |
sigma | |
""" | |
sigma = np.asmatrix(sigma) | |
X = np.random.uniform(0, 1, size=(sigma.shape[0], n)) | |
return pnorm(chol(sigma) * qnorm(X)) | |
def calc_w(ps, truncate_at=0.05): | |
# product of ps that are less than truncate_at | |
# avoid underflow by taking log. | |
return np.exp(np.sum(np.log(ps[ps <= truncate_at]))) | |
def sim(sigma, ps, nsims): | |
Y = gen_correlated(sigma, nsims) | |
w0 = calc_w(ps) | |
return sum(calc_w(row) <= w0 for row in Y.T) / float(nsims) | |
if __name__ == "__main__": | |
ps = np.array([0.01, 0.2, 0.04, 0.1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.05]) | |
ps = ps[:4] | |
sigma = np.eye(ps.shape[0]).astype('f') | |
sigma[0,1] = sigma[1, 0] = 0.9 | |
sigma[0,2] = sigma[2, 0] = 0.85 | |
sigma[0,3] = sigma[3, 0] = 0.7 | |
sigma[1,2] = sigma[2, 1] = 0.8 | |
sigma[1,3] = sigma[3, 1] = 0.6 | |
sigma[2,3] = sigma[3, 2] = 0.4 | |
print sigma | |
print sim(sigma, ps, 10000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment