| 1 |
SpatialPixels = function(points, tolerance = sqrt(.Machine$double.eps), |
| 2 |
proj4string = CRS(as.character(NA)), round = NULL, grid = NULL) { |
| 3 |
if (!is(points, "SpatialPoints")) |
| 4 |
stop("points should be of class or extending SpatialPoints") |
| 5 |
is.gridded = gridded(points) |
| 6 |
if (is.na(slot(slot(points, "proj4string"), "projargs"))) |
| 7 |
proj4string(points) = proj4string |
| 8 |
if (is.null(grid)) |
| 9 |
grid = points2grid(points, tolerance, round) |
| 10 |
if (!is.gridded) { |
| 11 |
points@bbox[,1] = points@bbox[,1] - 0.5 * grid@cellsize |
| 12 |
points@bbox[,2] = points@bbox[,2] + 0.5 * grid@cellsize |
| 13 |
} |
| 14 |
new("SpatialPixels", points, grid = grid, |
| 15 |
grid.index = getGridIndex(coordinates(points), grid)) |
| 16 |
} |
| 17 |
|
| 18 |
SpatialGrid = function(grid, proj4string = CRS(as.character(NA))) { |
| 19 |
stopifnot(is(grid, "GridTopology")) |
| 20 |
if (is.character(proj4string)) |
| 21 |
proj4string = CRS(proj4string) |
| 22 |
cc = rbind([email protected] - 0.5 * grid@cellsize, |
| 23 |
[email protected] + ([email protected] - 0.5) * grid@cellsize) |
| 24 |
bb = .bboxCoords(cc) |
| 25 |
new("SpatialGrid", grid = grid, bbox = bb, proj4string = proj4string) |
| 26 |
} |
| 27 |
|
| 28 |
setAs("SpatialGrid", "SpatialPixels", |
| 29 |
function(from) { |
| 30 |
pts = as(from, "SpatialPoints") |
| 31 |
pts@bbox[,1] = pts@bbox[,1] - 0.5 * from@grid@cellsize |
| 32 |
pts@bbox[,2] = pts@bbox[,2] + 0.5 * from@grid@cellsize |
| 33 |
new("SpatialPixels", pts, grid = from@grid, grid.index = 1:length(pts)) |
| 34 |
} |
| 35 |
) |
| 36 |
|
| 37 |
setAs("SpatialGrid", "SpatialPoints", |
| 38 |
function(from) SpatialPoints(coordinates(from), from@proj4string)) |
| 39 |
|
| 40 |
setMethod("coordinates", "SpatialPixels", function(obj) obj@coords) |
| 41 |
|
| 42 |
row.names.SpatialPixels <- function(x) { |
| 43 |
ret = dimnames(slot(x, "coords"))[[1]] |
| 44 |
if (is.null(ret)) |
| 45 |
ret = seq_len(nrow(x@coords)) |
| 46 |
ret |
| 47 |
} |
| 48 |
|
| 49 |
row.names.SpatialGrid <- function(x) 1:prod(x@[email protected]) |
| 50 |
|
| 51 |
setMethod("coordinates", "SpatialGrid", function(obj) coordinates(obj@grid)) |
| 52 |
|
| 53 |
setMethod("plot", signature(x = "SpatialGrid", y = "missing"), |
| 54 |
function(x, y, ..., grid = TRUE) { |
| 55 |
if (grid) |
| 56 |
plot.SpatialGrid(x, ...) |
| 57 |
else |
| 58 |
plot(as(x, "SpatialPoints"), ...) |
| 59 |
} |
| 60 |
) |
| 61 |
|
| 62 |
setMethod("plot", signature(x = "SpatialPixels", y = "missing"), |
| 63 |
function(x, y, ..., grid = TRUE) { |
| 64 |
if (grid) |
| 65 |
plot.SpatialPixels(x, ...) |
| 66 |
else |
| 67 |
plot(as(x, "SpatialPoints"), ...) |
| 68 |
} |
| 69 |
) |
| 70 |
|
| 71 |
coordnamesSG = function(x, value) { |
| 72 |
dimnames(x@bbox)[[1]] = value |
| 73 |
if (is(x, "SpatialPixels")) |
| 74 |
dimnames(x@coords)[[2]] = value |
| 75 |
coordnames(x@grid) = value |
| 76 |
x |
| 77 |
} |
| 78 |
|
| 79 |
setReplaceMethod("coordnames", |
| 80 |
signature(x = "SpatialGrid", value = "character"), coordnamesSG) |
| 81 |
setReplaceMethod("coordnames", |
| 82 |
signature(x = "SpatialPixels", value = "character"), coordnamesSG) |
| 83 |
|
| 84 |
getGridTopology = function(obj) { |
| 85 |
if (!(is(obj, "SpatialPixels") || is(obj, "SpatialGrid"))) |
| 86 |
stop("object is not or does not extend class SpatialPixels or SpatialGrid") |
| 87 |
obj@grid |
| 88 |
} |
| 89 |
|
| 90 |
areaSpatialGrid = function(obj) { |
| 91 |
cellarea = prod(obj@grid@cellsize) |
| 92 |
if (is(obj, "SpatialGrid")) |
| 93 |
return(prod(obj@[email protected]) * cellarea) |
| 94 |
else # take number of cells: |
| 95 |
length([email protected]) * cellarea |
| 96 |
} |
| 97 |
|
| 98 |
gridparameters = function(obj) { |
| 99 |
if (is(obj, "SpatialPixels") || is(obj, "SpatialGrid")) |
| 100 |
obj = obj@grid |
| 101 |
if (is(obj, "GridTopology")) |
| 102 |
return(data.frame( |
| 103 |
cellcentre.offset = [email protected], |
| 104 |
cellsize = obj@cellsize, |
| 105 |
cells.dim = [email protected])) |
| 106 |
return(numeric(0)) |
| 107 |
} |
| 108 |
|
| 109 |
getGridIndex = function(cc, grid, all.inside = TRUE) { |
| 110 |
n = ncol(cc) |
| 111 |
idx = rep(1, nrow(cc)) |
| 112 |
cumprod = 1 |
| 113 |
for (i in 1:n) { |
| 114 |
this.idx = round((cc[,i] - [email protected][i])/grid@cellsize[i]) |
| 115 |
if (i == 2) |
| 116 |
this.idx = [email protected][2] - (this.idx + 1) |
| 117 |
outside = this.idx >= [email protected][i] | this.idx < 0 |
| 118 |
if (any(outside)) { |
| 119 |
if (all.inside) { |
| 120 |
print(summary(this.idx)) |
| 121 |
stop("this.idx out of range") |
| 122 |
} else |
| 123 |
this.idx[outside] = NA |
| 124 |
} |
| 125 |
idx = idx + this.idx * cumprod |
| 126 |
cumprod = cumprod * [email protected][i] |
| 127 |
} |
| 128 |
outside = idx < 1 | idx > .NumberOfCells(grid) |
| 129 |
if (any(na.omit(outside))) { |
| 130 |
print(summary(idx)) |
| 131 |
stop("index outside boundaries") |
| 132 |
} |
| 133 |
as.integer(round(idx)) |
| 134 |
} |
| 135 |
|
| 136 |
rcFromGridIndex = function(obj) { # returns <x,y> entries: col,row rather than row,col |
| 137 |
obj = as(obj, "SpatialPixels") |
| 138 |
gi = [email protected] |
| 139 |
grid = obj@grid |
| 140 |
stopifnot(ncol(coordinates(obj)) == 2) |
| 141 |
xi = ((gi - 1) %% [email protected][1]) + 1 |
| 142 |
yi = [email protected][2] - ((gi - 1) %/% [email protected][1]) |
| 143 |
cbind(xi,yi) |
| 144 |
} |
| 145 |
|
| 146 |
gridIndex2nb = function(obj, maxdist = sqrt(2), fullMat = TRUE, ...) { |
| 147 |
xy = rcFromGridIndex(obj) |
| 148 |
if (fullMat) |
| 149 |
lst = apply(as.matrix(dist(xy, ...)), 1, function(x) which(x <= maxdist)) |
| 150 |
else { |
| 151 |
dst = function(X, Xi) apply(X, 1, function(Y) sqrt(sum((Y-Xi)^2))) |
| 152 |
n = nrow(xy) |
| 153 |
lst = vector(mode = "list", length = n) |
| 154 |
for (i in 1:n) { # avoid the n x n matrix construction: |
| 155 |
d = dst(xy, xy[i,]) |
| 156 |
lst[[i]] = which(d <= maxdist) |
| 157 |
} |
| 158 |
} |
| 159 |
class(lst) = c("nb", "list") |
| 160 |
lst |
| 161 |
} |
| 162 |
|
| 163 |
setMethod("[", "SpatialPixels", |
| 164 |
function(x, i, j, ..., drop = FALSE) { |
| 165 |
if (!missing(j)) |
| 166 |
stop("can only select pixels with a single index") |
| 167 |
if (missing(i)) |
| 168 |
return(x) |
| 169 |
if (is(i, "Spatial")) |
| 170 |
i = !is.na(over(x, geometry(i))) |
| 171 |
if (drop) { # if FALSE: adjust bbox and grid |
| 172 |
res = as(x, "SpatialPoints")[i] |
| 173 |
tolerance = list(...)$tolerance |
| 174 |
if (!is.null(tolerance)) |
| 175 |
res = SpatialPixels(res, tolerance = tolerance) |
| 176 |
else |
| 177 |
gridded(res) = TRUE |
| 178 |
res |
| 179 |
} else # default: don't adjust bbox and grid |
| 180 |
new("SpatialPixels", bbox = x@bbox, |
| 181 |
proj4string = x@proj4string, |
| 182 |
coords = x@coords[i, , drop = FALSE], grid = x@grid, |
| 183 |
grid.index = [email protected][i]) |
| 184 |
} |
| 185 |
) |
| 186 |
|
| 187 |
setMethod("[", "SpatialGrid", |
| 188 |
function(x, i, j, ..., drop = TRUE) { |
| 189 |
drop <- FALSE |
| 190 |
# if (!missing(drop)) |
| 191 |
# stop("don't supply drop: it needs to be FALSE anyway") |
| 192 |
gr = x@grid |
| 193 |
if (missing(i)) |
| 194 |
rows = 1:[email protected][2] |
| 195 |
else { |
| 196 |
if (is(i, "Spatial")) |
| 197 |
stop("area selection only makes sense for objects of class SpatialPixels or SpatialGridDataFrame; for object of class SpatialGrid you can only select x[rows,cols]") |
| 198 |
rows = i |
| 199 |
} |
| 200 |
if (missing(j)) |
| 201 |
cols = 1:[email protected][1] |
| 202 |
else |
| 203 |
cols = j |
| 204 |
idx = 1:prod([email protected][1:2]) |
| 205 |
if (any(is.na(rows)) || any(is.na(cols))) |
| 206 |
stop("NAs not permitted in indices") |
| 207 |
m = matrix(idx, [email protected][2], [email protected][1], byrow = TRUE)[rows,cols] |
| 208 |
idx = as.vector(m) # t(m)? |
| 209 |
cc = SpatialPixels(SpatialPoints(coordinates(x)[idx,,drop=FALSE], rebuild_CRS(slot(x, "proj4string")))) |
| 210 |
cc = as(cc, "SpatialGrid") |
| 211 |
cc |
| 212 |
} |
| 213 |
) |
| 214 |
|
| 215 |
setAs("SpatialPixels", "SpatialGrid", function(from) SpatialGrid(from@grid, from@proj4string)) |
| 216 |
#setAs("SpatialGrid", "SpatialPixels", |
| 217 |
# function(from) { |
| 218 |
# pts = new("SpatialPoints", coords = coordinates(from), |
| 219 |
# bbox = from@bbox, proj4string = from@proj4string) |
| 220 |
# new("SpatialPixels", pts, grid = from@grid, grid.index = 1:NROW(cc)) |
| 221 |
#}) |
| 222 |
|
| 223 |
as.data.frame.SpatialPixels = function(x, row.names, optional, ...) |
| 224 |
as.data.frame(coordinates(x)) |
| 225 |
|
| 226 |
as.data.frame.SpatialGrid = as.data.frame.SpatialPixels |
| 227 |
|
| 228 |
setAs("SpatialPixels", "data.frame", |
| 229 |
function(from) as.data.frame.SpatialPixels(from)) |
| 230 |
setAs("SpatialGrid", "data.frame", |
| 231 |
function(from) as.data.frame.SpatialGrid(from)) |
| 232 |
|
| 233 |
print.SpatialPixels = function(x, ...) { |
| 234 |
cat("Object of class SpatialPixels\n") |
| 235 |
print(summary(x@grid)) |
| 236 |
cat("SpatialPoints:\n") |
| 237 |
print(coordinates(x)) |
| 238 |
pst <- paste(strwrap(paste( |
| 239 |
"Coordinate Reference System (CRS) arguments:", |
| 240 |
proj4string(x))), collapse="\n") |
| 241 |
cat(pst, "\n") |
| 242 |
invisible(x) |
| 243 |
} |
| 244 |
setMethod("show", "SpatialPixels", function(object) print.SpatialPixels(object)) |
| 245 |
|
| 246 |
print.SpatialGrid = function(x, ...) { |
| 247 |
cat("Object of class SpatialGrid\n") |
| 248 |
print(summary(x@grid)) |
| 249 |
cat("SpatialPoints:\n") |
| 250 |
print(coordinates(x)) |
| 251 |
pst <- paste(strwrap(paste( |
| 252 |
"Coordinate Reference System (CRS) arguments:", |
| 253 |
proj4string(x))), collapse="\n") |
| 254 |
cat(pst, "\n") |
| 255 |
invisible(x) |
| 256 |
} |
| 257 |
setMethod("show", "SpatialGrid", function(object) print.SpatialGrid(object)) |
| 258 |
|
| 259 |
# make a SpatialPolygons from a SpatialPixels - Kohris Sahlen workshop |
| 260 |
as.SpatialPolygons.SpatialPixels <- function(obj) { |
| 261 |
obj_crds <- coordinates(obj) |
| 262 |
IDs <- IDvaluesSpatialPixels(obj) |
| 263 |
nPolygons <- nrow(obj_crds) |
| 264 |
cS <- slot(slot(obj, "grid"), "cellsize") |
| 265 |
cS2 <- cS/2 |
| 266 |
cS2x <- cS2[1] |
| 267 |
cS2y <- cS2[2] |
| 268 |
Srl <- vector(mode="list", length=nPolygons) |
| 269 |
for (i in 1:nPolygons) { |
| 270 |
xi <- obj_crds[i,1] |
| 271 |
yi <- obj_crds[i,2] |
| 272 |
x <- c(xi-cS2x, xi-cS2x, xi+cS2x, xi+cS2x, xi-cS2x) |
| 273 |
y <- c(yi-cS2y, yi+cS2y, yi+cS2y, yi-cS2y, yi-cS2y) |
| 274 |
Srl[[i]] <- Polygons(list(Polygon(coords=cbind(x, y))), ID=IDs[i]) |
| 275 |
comment(Srl[[i]]) <- "0" |
| 276 |
} |
| 277 |
res <- SpatialPolygons(Srl, proj4string=rebuild_CRS(slot(obj, "proj4string"))) |
| 278 |
res |
| 279 |
} |
| 280 |
setAs("SpatialPixels", "SpatialPolygons", |
| 281 |
function(from) as.SpatialPolygons.SpatialPixels(from)) |
| 282 |
|
| 283 |
IDvaluesSpatialPixels <- function(obj) { |
| 284 |
if (!is(obj, "SpatialPixels")) |
| 285 |
stop("function only works for objects of class or extending SpatialPixels") |
| 286 |
|
| 287 |
cc <- slot(obj, "grid.index") |
| 288 |
res <- as.matrix(sapply(cc, as.integer)) |
| 289 |
paste("g", res, sep="") |
| 290 |
} |
| 291 |
|
| 292 |
length.SpatialPixels = function(x) { nrow(x@coords) } |
| 293 |
length.SpatialGrid = function(x) { .NumberOfCells(x@grid) } |
| 294 |
|
| 295 |
setAs("SpatialGrid", "SpatialPolygons", function(from) { |
| 296 |
ret = as.SpatialPolygons.GridTopology(from@grid) |
| 297 |
proj4string(ret) = proj4string(from) |
| 298 |
ret |
| 299 |
} |
| 300 |
) |
| 301 |
setMethod("coordnames", signature(x = "SpatialGrid"), |
| 302 |
function(x) dimnames(bbox(x))[[1]]) |
| 303 |
|
| 304 |
setReplaceMethod("coordnames", signature(x = "SpatialGrid", |
| 305 |
value = "character"), |
| 306 |
function(x, value) { |
| 307 |
dimnames(x@bbox)[[1]] = value |
| 308 |
coordnames(x@grid) = value |
| 309 |
x |
| 310 |
} |
| 311 |
) |
| 312 |
|
| 313 |
setAs("SpatialGrid", "GridTopology", function(from) getGridTopology(from)) |
| 314 |
setAs("SpatialPixels", "GridTopology", function(from) getGridTopology(from)) |
| 315 |
|
| 316 |
plot.SpatialGrid = function(obj, ..., col = par("fg"), |
| 317 |
lty = par("lty"), lwd = par("lwd"), add = FALSE) { |
| 318 |
|
| 319 |
if (! add) |
| 320 |
plot(as(obj, "Spatial"), ...) |
| 321 |
gr = obj@grid |
| 322 |
# Don MacQueen, Feb 12 2015 |
| 323 |
csiz <- gr@cellsize |
| 324 |
ncells <- [email protected] |
| 325 |
nbounds <- ncells+1 |
| 326 |
|
| 327 |
## first get and sort the cell centers |
| 328 |
cv <- coordinatevalues(gr) |
| 329 |
cv[[1]] <- sort(cv[[1]]) |
| 330 |
cv[[2]] <- sort(cv[[2]]) |
| 331 |
|
| 332 |
## calculate cell boundaries |
| 333 |
cv[[1]] <- c(cv[[1]][1] - csiz[1]/2, cv[[1]] + csiz[1]/2 ) |
| 334 |
cv[[2]] <- c(cv[[2]][1] - csiz[2]/2, cv[[2]] + csiz[2]/2 ) |
| 335 |
|
| 336 |
## construct endpoints of cell boundary lines |
| 337 |
## vertical lines |
| 338 |
vfrom <- cbind(cv[[1]], cv[[2]][1]) |
| 339 |
vto <- cbind(cv[[1]], cv[[2]][nbounds[2]]) |
| 340 |
|
| 341 |
## horizontal lines |
| 342 |
hfrom <- cbind(cv[[1]][1], cv[[2]]) |
| 343 |
hto <- cbind(cv[[1]][nbounds[1]], cv[[2]]) |
| 344 |
|
| 345 |
## add to plot |
| 346 |
segments(vfrom[,1], vfrom[,2] , vto[,1], vto[,2], |
| 347 |
col = col, lty = lty, lwd = lwd) |
| 348 |
segments(hfrom[,1], hfrom[,2] , hto[,1], hto[,2], |
| 349 |
col = col, lty = lty, lwd = lwd) |
| 350 |
} |
| 351 |
|
| 352 |
plot.SpatialPixels = function(obj, ..., col = par("fg"), |
| 353 |
lty = par("lty"), lwd = par("lwd"), add = FALSE) { |
| 354 |
|
| 355 |
# based on plot.SpatialGrid: |
| 356 |
if (! add) |
| 357 |
plot(as(obj, "Spatial"), ...) |
| 358 |
|
| 359 |
gr = obj@grid |
| 360 |
csiz <- gr@cellsize |
| 361 |
ncells <- [email protected] |
| 362 |
nbounds <- ncells + 1 |
| 363 |
|
| 364 |
m = matrix(FALSE, ncells[2], ncells[1]) |
| 365 |
rc = rcFromGridIndex(obj)[,c(2,1)] |
| 366 |
m[rc] = TRUE # the pattern |
| 367 |
|
| 368 |
## first get and sort the cell centers |
| 369 |
cv <- coordinatevalues(gr) |
| 370 |
cv[[1]] <- sort(cv[[1]]) |
| 371 |
cv[[2]] <- sort(cv[[2]]) |
| 372 |
|
| 373 |
## calculate cell boundaries |
| 374 |
x <- c(cv[[1]][1] - csiz[1]/2, cv[[1]] + csiz[1]/2 ) |
| 375 |
y <- c(cv[[2]][1] - csiz[2]/2, cv[[2]] + csiz[2]/2 ) |
| 376 |
|
| 377 |
# horizontal lines: |
| 378 |
p = do.call(rbind, lapply(1:nbounds[2], function(i) { |
| 379 |
if (i == 1) # bottom line |
| 380 |
cells = m[1,] |
| 381 |
else if (i == nbounds[2]) # top line |
| 382 |
cells = m[nbounds[2]-1,] |
| 383 |
else # in-between, draw for: |
| 384 |
cells = m[i-1,] | m[i,] |
| 385 |
r = rle(cells) # figure out line pieces |
| 386 |
if (any(r$values)) { |
| 387 |
wr = which(r$values) # where to draw/end |
| 388 |
cs0 = c(0, cumsum(r$lengths)) # all start/end indices |
| 389 |
cbind(x[cs0[wr] + 1], y[i], x[cs0[wr+1] + 1], y[i]) |
| 390 |
} |
| 391 |
} |
| 392 |
)) |
| 393 |
segments(p[,1], p[,2], p[,3], p[,4], col = col, lty = lty, lwd = lwd) |
| 394 |
# vertical lines: |
| 395 |
p = do.call(rbind, lapply(1:nbounds[1], function(i) { |
| 396 |
if (i == 1) # left boundary |
| 397 |
cells = m[,1] |
| 398 |
else if (i == nbounds[1]) # right boundary |
| 399 |
cells = m[,nbounds[1]-1] |
| 400 |
else # non-boundary lines, draw for: |
| 401 |
cells = m[,i-1] | m[,i] |
| 402 |
r = rle(cells) |
| 403 |
if (any(r$values)) { |
| 404 |
wr = which(r$values) |
| 405 |
cs0 = c(0, cumsum(r$lengths)) |
| 406 |
cbind(x[i], y[cs0[wr]+1], x[i], y[cs0[wr+1]+1]) |
| 407 |
} |
| 408 |
} |
| 409 |
)) |
| 410 |
segments(p[,1], p[,2], p[,3], p[,4], col = col, lty = lty, lwd = lwd) |
| 411 |
} |