Here, essentially based on the code presented in the previous document, we develop a function for the calculation of a variogram. The function is a little bit different from the previous one, because we do not start with the number of bins as an input parameter. Below, we compare the results of our function with the output of the variogram function of the gstat library.
The function below is just for teaching purposes and might be useful
to understand what a variogram calculation does. It is a greatly
simplified compared to the corresponding function in the gstat
library which has much more features. Hence, use only
gstat::variogram for real tasks.
myVariogram <- function(measurement, cutoff = NULL, width = NULL) {
if(!is.numeric(measurement[,1])) stop("Column 1 must be numeric.")
if(!is.numeric(measurement[,2])) stop("Column 2 must be numeric.")
if(!is.numeric(measurement[,3])) stop("Column 3 must be numeric.")
x = measurement[,1] # OOPS!: that limits the input file format!
y = measurement[,2]
z = measurement[,3]
# Euclidian distance between point pairs:
distances = dist(measurement[,1:2]) # Euclidian distance is default (exclude z-values!)
distVector = as.numeric(distances)
# Point pairs:
pairs = combn(1:nrow(measurement), 2)
colnames(pairs) = paste0("pair", 1:ncol(pairs))
rownames(pairs) = c("i", "j")
# Cutoff and width:
if(is.null(cutoff)) { # no cutoff supplied
if(is.null(width)) { # no cutoff, no width supplied
# we run the gstat default:
dx = max(x) - min(x)
dy = max(y) - min(y)
diagonal = sqrt(dx^2 + dy^2) # diagonal of the box determined by the spatial data
cutoff = diagonal/3
width = cutoff/15
} else { # no cutoff supplied, but width
cutoff = max(distVector) + 1 # actually no cutoff at all
}
} else { # cutoff has been supplied
if(is.null(width)) { # cutoff supplied, but no width
width = cutoff/15 # gstat default
# no else branch if cutoff and width have been supplied ==> nothing to do here!
}
}
# Cut long distances if required:
if(cutoff < max(distVector)) { # cut the distances if required
logVector = distVector <= cutoff
distVector = distVector[logVector] # remove entries above cutoff
pairs = pairs[, logVector] # remove corresponding entries in pairs array
}
# Get the breaks:
breaks = seq(0, cutoff, width)
numBins = length(breaks) - 1
if(numBins < 2) stop("Less than 2 bins does not make sense.")
if(numBins < 6) print(paste0("WARNING: You have only ", numBins, " bins."))
# Get the groups:
groups = as.integer(cut(distVector, breaks = breaks))
group_index = list()
for (i in 1:numBins) {
group_index[[i]] = which(groups == i)
}
# Remove empty bins from list:
group_index = group_index[lapply(group_index,length) > 0] # keep only non-empty list entries
numBins = length(group_index) # recalculate numBins because empty bins have been removed
# Get gamma for each bin:
gamma = rep(NA, numBins)
N = rep(NA, numBins)
for (i in 1:numBins) {
binPairs = as.matrix(pairs[,group_index[[i]]])
N[i] = ncol(binPairs)
term = rep(NA, N[i])
for (k in 1:N[i]) {
term[k] = (z[binPairs[2,k]] - z[binPairs[1,k]])^2
}
gamma[i] = 0.5/N[i]*sum(term)
}
# Mean distance in each bin:
meanDistance = rep(NA, numBins) # initialise with NA
for (i in 1:numBins) {
meanDistance[i] = mean(distVector[group_index[[i]]])
}
# Results:
res_df = data.frame(Nbin = N, dist = meanDistance, gamma = gamma)
results = list()
results[["width"]] = width
results[["breaks"]] = breaks
results[["groups"]] = groups
results[["numBins"]] = numBins
results[["table"]] = res_df
results[["data"]] = cbind(x, y, z)
return(results)
}
The input data frame must contain the coordinates in the first two columns and the measurement values in the 3rd column .
To start with, we use the same (actually insufficient) data from the previous document:
{
x = c(0.1, -2.23, -0.5, 1.46, -1.46)
y = c(1.8, -2.14, 1.0, 2.27, 2.27)
z = c(399.55, 427.19, 360.49, 376.66, 378.24)
measurement = data.frame(x = x, y = y, z = z)
measurement
}
## x y z
## 1 0.10 1.80 399.55
## 2 -2.23 -2.14 427.19
## 3 -0.50 1.00 360.49
## 4 1.46 2.27 376.66
## 5 -1.46 2.27 378.24
The function takes as input the spatial coordinates \((x,y)\) and the measurements \(z\) corresponding to these coordinates. Moreover, it takes the parameters cutoff and width. If a cutoff is set, all pairwise distances above this cutoff are ignored in order to save computation time (we might have much bigger datasets!). The width parameter determines the width of the (equally spaced) bins.
The default values of cutoff and width come into effect in our function if they are set to NULL. The default values have been chosen to be the same as in the variogram function of the gstat library.
The default values are computed in the following manner:
dx = max(x) - min(x)
dy = max(y) - min(y)
diagonal = sqrt(dx^2 + dy^2)
cutoff = diagonal/3
cutoff
## [1] 1.916716
width = cutoff/15
width
## [1] 0.1277811
We start comparing the results for the default values.
We use the self-made function:
res1 <- myVariogram(measurement) # requires coordinates in columns 1 and 2, and measurements in column 3 !
res1$table
## Nbin dist gamma
## 1 1 1.000000 762.8418
## 2 1 1.438923 261.9760
## 3 2 1.610637 192.2947
We compare with the variogram function:
suppressWarnings(library(gstat))
gst1 <- variogram(z ~ 1, locations = ~ x + y, data = measurement) # requires correct column names x, y, and z !
gst1
## np dist gamma dir.hor dir.ver id
## 1 1 1.000000 762.8418 0 0 var1
## 2 1 1.438923 261.9760 0 0 var1
## 3 2 1.610637 192.2947 0 0 var1
Luckily, these are the same results. We take note that the default cutoff of 1.92 is much too small for our dataset. This becomes obvious if we once again take a look at the pairwise distances between the individual data points:
dist(measurement[,1:2])
## 1 2 3 4
## 2 4.577390
## 3 1.000000 3.585038
## 4 1.438923 5.750148 2.335487
## 5 1.629264 4.476718 1.592011 2.920000
Most of the distances are larger than the default cutoff. We see in the np (or Nbin) column of the output above, that only 4 distances “survived” the cutoff (out of a total of n(n-1)/2 = 10). Consequently, we are going to choose a different cutoff in the next function call.
We try a cutoff of 4. This should exclude 3 pairwise distances (see dist command above). We start with our script:
res2 <- myVariogram(measurement, cutoff = 4)
res2$table
## Nbin dist gamma
## 1 1 1.000000 762.8418
## 2 2 1.515467 209.7536
## 3 1 1.629264 227.0581
## 4 1 2.335487 130.7345
## 5 1 2.920000 1.2482
## 6 1 3.585038 2224.4450
The width was not invoked in the function call, and was therefore automatically set to cutoff/15:
res2$width
## [1] 0.2666667
4/15
## [1] 0.2666667
Consequently, the breaks are located 0.2666667 units apart:
res2$breaks
## [1] 0.0000000 0.2666667 0.5333333 0.8000000 1.0666667 1.3333333 1.6000000
## [8] 1.8666667 2.1333333 2.4000000 2.6666667 2.9333333 3.2000000 3.4666667
## [15] 3.7333333 4.0000000
We look at the gstat output:
gst2 <- variogram(z ~ 1, locations = ~ x + y, data = measurement, cutoff = 4)
gst2
## np dist gamma dir.hor dir.ver id
## 1 1 1.000000 762.8418 0 0 var1
## 2 2 1.515467 209.7536 0 0 var1
## 3 1 1.629264 227.0581 0 0 var1
## 4 1 2.335487 130.7345 0 0 var1
## 5 1 2.920000 1.2482 0 0 var1
## 6 1 3.585038 2224.4450 0 0 var1
We confirm that the width in gstat::variogram was also
chosen to be cutoff/15 by looking at the boundaries (called
breaks in our function):
attr(gst2, "boundaries")
## [1] 0.0000000 0.2666667 0.5333333 0.8000000 1.0666667 1.3333333 1.6000000
## [8] 1.8666667 2.1333333 2.4000000 2.6666667 2.9333333 3.2000000 3.4666667
## [15] 3.7333333 4.0000000
We are lucky that the results agree, but remark that these results do not deliver the expected shape of a variogram because of the very sparse data.
We use the same width as in the previous text:
res3 <- myVariogram(measurement, cutoff = NULL, width = 1.916716)
## [1] "WARNING: You have only 3 bins."
res3$table
## Nbin dist gamma
## 1 4 1.415050 352.3518
## 2 3 2.946842 785.4759
## 3 3 4.934752 952.2255
In our function, the cutoff is set to a value larger than the maximum distance, therewith disabling it:
res3$breaks
## [1] 0.000000 1.916716 3.833432 5.750148
The gstat function using the same input yields:
gst3 <- variogram(z ~ 1, locations = ~ x + y, data = measurement, width = 1.916716)
gst3
## np dist gamma dir.hor dir.ver id
## 1 4 1.41505 352.3518 0 0 var1
Here, we have differing results. Let’s have a closer look at the boundaries created by the variogram function:
attr(gst3, "boundaries")
## [1] 0.000000 1.916697
We see that the cutoff is set to the default value (see above). This causes the algorithm to be restricted to just one bin. In spite of the differences to variogram, we won’t change our version with respect to this setting.
res4 <- myVariogram(measurement, cutoff = 4, width = 1.916716)
## [1] "WARNING: You have only 2 bins."
res4$table
## Nbin dist gamma
## 1 4 1.415050 352.3518
## 2 3 2.946842 785.4759
gst4 <- variogram(z ~ 1, locations = ~ x + y, data = measurement, cutoff = 4, width = 1.916716)
gst4
## np dist gamma dir.hor dir.ver id
## 1 4 1.415050 352.3518 0 0 var1
## 2 3 2.946842 785.4759 0 0 var1
Both results agree again.
In the next document, we are going to use a much bigger dataset, which hopefully yields nicer variograms!
Mail to Uwe Menzel