Debian Codegraph @

R/spsample.R

raw
1 makegrid = function(x, n = 10000, nsig = 2, cellsize,
2 offset = rep(0.5, nrow(bb)), pretty = TRUE) {
3 if (is(x, "Spatial"))
4 bb = bbox(x)
5 else
6 bb = x
7 if (missing(cellsize)) {
8 pw = 1.0/nrow(bb)
9 cellsize = signif((prod(apply(bb, 1, diff))/n) ^ pw, nsig)
10 }
11 if (length(cellsize) == 1)
12 cellsize = rep(cellsize, nrow(bb))
13 # find pretty grid coordinates:
14 min.coords = bb[,1] + offset * cellsize
15 if (pretty)
16 min.coords = signif(min.coords, max(ceiling(log10(abs(bb[1,]) / cellsize))))
17 sel = min.coords - offset * cellsize > bb[,1]
18 if (any(sel))
19 min.coords[sel] = min.coords[sel] - cellsize[sel]
20 expand.grid.arglist = list()
21 for (i in 1:nrow(bb)) {
22 name = paste("x", i, sep = "")
23 from = min.coords[i]
24 by = cellsize[i]
25 length.out = round(1 + (bb[i,2] - from) / by)
26 expand.grid.arglist[[name]] = seq(from, by=by, length.out=length.out)
27 }
28 xy = do.call(expand.grid, expand.grid.arglist)
29 attr(xy, "cellsize") = cellsize
30 return(xy)
31 }
32
33 makegrid0 = function(x, n = 10000, nsig = 2, cellsize,
34 offset = rep(0.5,nrow(bb))) {
35 #cat("n in makegrid", n, "\n")
36 if (is(x, "Spatial"))
37 bb = bbox(x)
38 else
39 bb = x
40 # rx = bb[1,]
41 # ry = bb[2,]
42 if (missing(cellsize)) {
43 pw = 1.0/nrow(bb)
44 cellsize = signif((prod(apply(bb, 1, diff))/n) ^ pw, nsig)
45 cellsize = min(cellsize, min(apply(bb, 1, diff)))
46 }
47 if (length(cellsize) == 1)
48 cellsize = rep(cellsize, nrow(bb))
49 # in some cases with small n, min* can be larger than bbox max values
50 # so guard imposed to step down from cellsize
51 min.coords = pmax(bb[,1], signif(bb[,1] + offset * cellsize, nsig))
52 # minx = max(rx[1], signif(rx[1] + offset[1] * cellsize, nsig))
53 # miny = max(ry[1], signif(ry[1] + offset[2] * cellsize, nsig))
54 expand.grid.arglist = list()
55 for (i in 1:nrow(bb)) {
56 name = paste("x", i, sep = "")
57 sign = ifelse(min.coords[i] < bb[i,2], 1, -1)
58 expand.grid.arglist[[name]] = seq(min.coords[i], bb[i,2], sign * cellsize[i])
59 }
60 # if (minx < rx[2]) seqx = seq(minx, rx[2], by = cellsize)
61 # else seqx = seq(minx, rx[2], by = -cellsize)
62 # if (miny < ry[2]) seqy = seq(miny, ry[2], by = cellsize)
63 # else seqy = seq(miny, ry[2], by = -cellsize)
64 # type = "regular" :
65 xy = do.call(expand.grid, expand.grid.arglist)
66 attr(xy, "cellsize") = cellsize
67 return(xy)
68 }
69
70 sample.Spatial = function(x, n, type, bb = bbox(x), offset = runif(nrow(bb)),
71 cellsize, ..., nclusters = 1) {
72
73 if (missing(n)) n <- as.integer(NA)
74 n <- ceiling(n)
75 #cat("n in sample.Spatial", n, "\n")
76 if (type == "random")
77 xy = apply(bb, 1, function(x) runif(n) * diff(x) + x[1])
78 else if (type == "Fibonacci") {
79 if (!identical(is.projected(x), FALSE))
80 warning("Fibonacci sampling is supposed to work on long/lat only")
81 xy = fiboGrid(n %/% 2, bb[1,], bb[2,])
82 } else if (type == "hexagonal")
83 xy = hexGrid(bb, n = n, offset = offset, cellsize = cellsize)
84 else {
85 if (is.na(n))
86 xy = makegrid0(bb, nsig = 20, cellsize = cellsize,
87 offset = offset)
88 else
89 xy = makegrid0(bb, n = n, nsig = 20, cellsize = cellsize,
90 offset = offset)
91 cellsize = attr(xy, "cellsize")
92 if (type == "stratified") {
93 n = nrow(xy)
94 for (j in 1:ncol(xy))
95 xy[,j] = xy[,j] + (runif(n) - 0.5) * cellsize[j]
96 } else if (type == "clustered") {
97 n = nrow(xy) # BG, Mon May 9 14:58:18 CEST 2011
98 clus = rep(sample(1:n, nclusters, replace = FALSE), length = n)
99 for (j in 1:ncol(xy))
100 xy[,j] = xy[clus,j] + (runif(n) - 0.5) * cellsize[j]
101 } else if (type == "nonaligned") {
102 if (ncol(xy) != 2)
103 stop("sorry, nonaligned is only implemented for 2D")
104 nx = length(unique(xy[,1]))
105 ny = length(unique(xy[,2]))
106 x0 <- rep(runif(ny), rep(nx, ny))
107 y0 <- rep(runif(nx), ny)
108 xy[,1] = xy[,1] + (x0 - 0.5) * cellsize[1]
109 xy[,2] = xy[,2] + (y0 - 0.5) * cellsize[2]
110 } else if (type != "regular")
111 stop(paste("sampling type", type, "not recognized"))
112 }
113 # Patrick Girardoux 080217
114 if (!is.na(n) && n == 1 && !is.matrix(xy) && is.vector(xy))
115 xy <- matrix(xy, ncol=nrow(bb))
116 sel = xy[,1] >= bb[1,1] & xy[,1] <= bb[1,2] &
117 xy[,2] >= bb[2,1] & xy[,2] <= bb[2,2]
118 xy = xy[sel,, drop = FALSE]
119 rownames(xy) = NULL
120 SpatialPoints(xy, rebuild_CRS(slot(x, "proj4string")))
121 }
122
123 setMethod("spsample", signature(x = "Spatial"), sample.Spatial)
124
125 sample.Line = function(x, n, type, offset = runif(1), proj4string = CRS(as.character(NA)), ...) {
126 offset = offset[1]
127 if (missing(n)) n <- as.integer(NA)
128 if (!is.finite(n) || n < 1) return(NULL)
129 cc = coordinates(x)
130 lengths = LineLength(cc, longlat=FALSE, sum=FALSE)
131 if (any(abs(lengths) < .Machine$double.eps)) {
132 wl <- which(abs(lengths) < .Machine$double.eps)
133 cc <- cc[-(wl),]
134 lengths <- lengths[-(wl)]
135 }
136 csl = c(0, cumsum(lengths))
137 maxl = csl[length(csl)]
138 if (type == "random")
139 pts = runif(n) * maxl
140 else if (type == "stratified")
141 pts = ((1:n) - runif(n))/n * maxl
142 else if (type == "regular")
143 pts = ((1:n) - (1-offset))/n * maxl
144 else
145 stop(paste("type", type, "not available for Line"))
146 # find coordinates:
147 int = findInterval(pts, csl, all.inside = TRUE)
148 where = (pts - csl[int])/diff(csl)[int]
149 xy = cc[int, , drop=FALSE] + where * (cc[int+1, , drop=FALSE] -
150 cc[int, , drop=FALSE])
151 if (nrow(xy) < 1) return(NULL)
152 SpatialPoints(xy, proj4string)
153 }
154 setMethod("spsample", signature(x = "Line"), sample.Line)
155
156 sample.Lines = function(x, n, type, offset = runif(1), ...) {
157 L = x@Lines
158 lengths = sapply(L, function(x) LineLength(x@coords))
159 if (sum(lengths) < .Machine$double.eps)
160 stop("Lines object of no length")
161 nrs = round(lengths / sum(lengths) * n)
162 ret = vector("list", sum(nrs > 0))
163 j = 1
164 for (i in 1:length(L)) {
165 if (nrs[i] > 0) {
166 ret[[j]] = sample.Line(L[[i]], nrs[i], type = type, offset = offset, ...)
167 j = j+1
168 }
169 }
170 do.call(rbind, ret)
171 }
172 setMethod("spsample", signature(x = "Lines"), sample.Lines)
173
174 sample.SpatialLines = function(x, n, type, offset = runif(1), ...) {
175 # lengths = SpatialLinesLengths(x, longlat = isTRUE(!is.projected(x)))
176 if (isTRUE(!is.projected(x)))
177 warning("working under the assumption of projected data!")
178 lengths = SpatialLinesLengths(x, longlat = FALSE)
179 if (sum(lengths) < .Machine$double.eps)
180 stop("SpatialLines object of no length")
181 nrs = round(lengths / sum(lengths) * n)
182 if (sum(nrs) == 0)
183 warning("n too small, increase n and sample from output")
184 ret = vector("list", sum(nrs > 0))
185 j = 1
186 for (i in 1:length(lengths)) {
187 if (nrs[i] > 0) {
188 ret[[j]] = sample.Lines(x@lines[[i]], nrs[i], type = type,
189 offset = offset, ...)
190 j = j+1
191 }
192 }
193 ret = do.call(rbind, ret)
194 if (!is.null(ret))
195 proj4string(ret) = rebuild_CRS(slot(x, "proj4string"))
196 ret
197 }
198 setMethod("spsample", signature(x = "SpatialLines"), sample.SpatialLines)
199
200 sample.Polygon = function(x, n, type = "random", bb = bbox(x),
201 offset = runif(2), proj4string=CRS(as.character(NA)), iter=4, ...) {
202 if (missing(n)) n <- as.integer(NA)
203 #cat("n in sample.Polygon", n, "\n")
204 area = slot(x, "area")
205 if (area == 0.0)
206 spsample(Line(slot(x, "coords")),
207 n, type, offset = offset[1], proj4string=proj4string)
208 #CRS(proj4string(x))), n, type, offset = offset[1])
209 else {
210 res <- NULL
211 its <- 0
212 n_now <- 0
213 bb.area = prod(apply(bb, 1, function(x) diff(range(x))))
214 bb.area <- bb.area + bb.area*its*0.1
215 xSP <- new("Spatial", bbox=bbox(x), proj4string=proj4string)
216 if (type == "random") {
217 brks <- c(1,3,6,10,20,100)
218 reps <- c(5,4,3,2,1.5)
219 n_is <- round(n * reps[findInterval(n,
220 brks, all.inside=TRUE)] * bb.area/area)
221 } else n_is <- round(n * bb.area/area)
222 while (is.null(res) && its < iter && n_is > 0 &&
223 ifelse(type == "random", (n_now < n), TRUE)) {
224 pts = sample.Spatial(xSP, n_is, type=type,
225 offset = offset, ...)
226 id = over(pts, SpatialPolygons(list(Polygons(list(x),
227 "xx")), proj4string=proj4string))
228 Not_NAs <- !is.na(id)
229 if (!any(Not_NAs)) res <- NULL
230 else res <- pts[which(Not_NAs)]
231 if (!is.null(res)) n_now <- nrow(res@coords)
232 its <- its+1
233 }
234 if (type == "random")
235 if (!is.null(res) && n < nrow(res@coords))
236 res <- res[sample(nrow(res@coords), n)]
237 res
238 }
239 }
240 setMethod("spsample", signature(x = "Polygon"), sample.Polygon)
241
242 sample.Polygons = function(x, n, type = "random", bb = bbox(x),
243 offset = runif(2), proj4string=CRS(as.character(NA)), iter=4, ...) {
244 if (missing(n)) n <- as.integer(NA)
245 area = sapply(slot(x, "Polygons"), function(i) slot(i, "area")) # also available for Polygons!
246 if (sum(area) == 0.0)
247 # distribute n over the lines, according to their length?
248 stop("sampling over multiple lines not functioning yet...")
249 res <- NULL
250 its <- 0
251 holes <- sapply(slot(x, "Polygons"), function(y) slot(y, "hole"))
252 pls <- slot(x, "Polygons")
253 smple <- rep(TRUE, length(pls))
254 if (length(pls) > 1) {
255 # for (i in seq(along=pls)) {
256 # bbi <- .bbox2SPts(bbox(pls[[i]]), proj4string=proj4string)
257 # bb_in <- lapply(pls[-i], function(x, pts)
258 # pointsInPolygon(pts, x), pts = bbi)
259 # added condition 100716
260 # zzz <- do.call("rbind", bb_in)
261 # if (holes[i] || (any(unlist(bb_in) == 1) &&
262 # !(sum(zzz[i,]) %% 2) == 0)) smple[i] <- FALSE
263 # was [,i], changed to [i,] 110307 Aman Verma
264 # }
265 smple <- !holes
266 # all heuristics removed, hole slots must be correctly defined 110308
267 }
268 sum_area <- sum(area[smple])
269 while (is.null(res) && its < iter) {
270 ptsres <- vector(mode="list", length=length(area))
271 for (i in seq_along(ptsres)) {
272 if (smple[i]) {
273 nnow <- ceiling(n*(area[i]/sum_area))
274 ptsres[[i]] <- sample.Polygon(x=pls[[i]],
275 n=nnow, type = type, offset = offset, iter=iter)
276 }
277 }
278 crds <- do.call(rbind, lapply(ptsres, function(x)
279 if (!is.null(x)) {rownames(x) <- NULL; coordinates(x)}))
280 # RSB 151013 oddity - duplicate rownames
281 if (is.null(crds)) res <- NULL
282 else {
283 pts <- SpatialPoints(crds, proj4string=proj4string)
284 id = over(pts, SpatialPolygons(list(x), proj4string=proj4string))
285 Not_NAs <- !is.na(id)
286 if (!any(Not_NAs)) res <- NULL
287 else res <- pts[which(Not_NAs)]
288 # Patrick Girardoux 080217
289 # if (type == "random" && nrow(res@coords) < n) res <- NULL
290 if(!is.null(res))
291 if (type == "random" && nrow(res@coords) < n) res <- NULL
292 }
293 its <- its+1
294 }
295 if (type == "random")
296 if (!is.null(res) && n < nrow(res@coords))
297 res <- res[sample(nrow(res@coords), n)]
298 res
299 }
300 setMethod("spsample", signature(x = "Polygons"), sample.Polygons)
301
302 sample.SpatialPolygons = function(x, n, type = "random", bb = bbox(x),
303 offset = runif(2), iter=4, ...) {
304 #stop("not functioning yet...")
305 if (missing(n)) n <- as.integer(NA)
306 #cat("n in sample.SpatialPolygons", n, "\n")
307 # EJP, 12/6/07: replaced area calculation with negative areas for holes...
308 #area = sum(unlist(lapply(slot(x, "polygons"), function(x) slot(x, "area"))))
309 getArea = function(x) {
310 getAreaPolygons = function(x) {
311 holes = unlist(lapply(x@Polygons, function(x) x@hole))
312 areas = unlist(lapply(x@Polygons, function(x) x@area))
313 area = ifelse(holes, -1, 1) * areas
314 area
315 }
316 sum(unlist(lapply(x@polygons, getAreaPolygons)))
317 }
318 area = getArea(x)
319 if (area <= 0.0)
320 stop("cannot sample in zero-area polygons")
321 res <- NULL
322 its <- 0
323 bb.area = prod(apply(bb, 1, function(x) diff(range(x))))
324 n_tot = round(n * bb.area/area)
325 while (is.null(res) && its < iter) {
326 # enlarge n each iteration:
327 pts = sample.Spatial(as(x, "Spatial"), n_tot * (1 + its * 0.1),
328 type=type, offset = offset, ...)
329 Over_pts_x <- over(pts, geometry(x))
330 Not_NAs <- !is.na(Over_pts_x)
331 if (!any(Not_NAs)) res <- NULL
332 else res <- pts[Not_NAs]
333 # Patrick Girardoux 080217
334 # if (type == "random" && nrow(res@coords) < n) res <- NULL
335 if(!is.null(res))
336 if (type == "random" && nrow(res@coords) < n) res <- NULL
337 its <- its+1
338 }
339 if (type == "random")
340 if (!is.null(res) && n < nrow(res@coords))
341 res <- res[sample(nrow(res@coords), n)]
342 if (is.null(res))
343 stop("iteration did not converge; try enlarging argument iter")
344 proj4string(res) = rebuild_CRS(slot(x, "proj4string"))
345 res
346 }
347 setMethod("spsample", signature(x = "SpatialPolygons"), sample.SpatialPolygons)
348
349 sample.Sgrid = function(x, n, type = "random", bb = bbox(x),
350 offset = runif(nrow(bb)), ...) {
351 if (missing(n)) n <- as.integer(NA)
352 #cat("n in sample.Sgrid", n, "\n")
353 area = areaSpatialGrid(x)
354 if (area == 0.0)
355 stop("cannot sample from grid with zero area")
356 pts = spsample(as(x, "Spatial"), n, type, offset = offset, ...)
357 pts[!is.na(over(pts, geometry(x)))]
358 }
359 setMethod("spsample", signature(x = "SpatialGrid"), sample.Sgrid)
360
361 sample.Spixels = function(x, n, type = "random", bb = bbox(x),
362 offset = runif(nrow(bb)), ...) {
363 if (missing(n)) n <- as.integer(NA)
364 #cat("n in sample.Spixels", n, "\n")
365 area = areaSpatialGrid(x)
366 if (area == 0.0)
367 stop("cannot sample from grid with zero area")
368 bb.area = prod(apply(bb, 1, function(x) diff(range(x))))
369 pts = spsample(as(x, "Spatial"), round(n * bb.area/area), type,
370 offset = offset, ...)
371 pts[!is.na(over(pts, geometry(x)))]
372 }
373 setMethod("spsample", signature(x = "SpatialPixels"), sample.Spixels)
374
375 hexGrid = function(bb, n, offset, cellsize) {
376 if (missing(cellsize)) {
377 if (missing(n))
378 stop("need either cellsize or n")
379 area = prod(apply(bb, 1, diff))/n
380 # dx = area / (sqrt(3)/2)
381 # suggested by Don MacQueen, [email protected], Fri Mar 14 16:00:07 CET 2008
382 dx = sqrt(area)/(sqrt(3)/2)
383 } else
384 dx = cellsize
385 xy = genHexGrid(dx, bb[,1], bb[,2])
386
387 # also suggested by Don MacQueen, [email protected], Fri Mar 14 16:00:07 CET 2008:
388 xy[,1] <- xy[,1] + offset[1] * dx
389 xy[,2] <- xy[,2] + offset[2] * dx * sqrt(3)/2
390
391 attr(xy, "cellsize") = dx
392 xy
393 }
394
395 # THK, posted to r-sig-geo, 03/03/2007:
396
397 genHexGrid <- function(dx, ll = c(0, 0), ur = c(1, 1)) {
398 dy <- sqrt(3) * dx / 2
399
400 x <- seq(ll[1], ur[1] - dx / 2, dx)
401 y <- seq(ll[2], ur[2], dy)
402
403 y <- rep(y, each = length(x))
404 x <- rep(c(x, x + dx / 2), length.out = length(y))
405
406 x <- x + (ur[1] - max(x)) / 2
407 y <- y + (ur[2] - max(y)) / 2
408
409 data.frame(x = x, y = y)
410 }
411
412 genPolyList <- function(hexGrid, dx) {
413 # EJP; changed:
414 # how to figure out dx from a grid? THK suggested:
415 #dx <- hexGrid$x[2] - hexGrid$x[1]
416 # and the following will also not allways work:
417 if (missing(dx))
418 dx = 2 * min(diff(sort(unique(hexGrid$x))))
419 dy <- dx / sqrt(3)
420
421 x.offset <- c(-dx / 2, 0, dx / 2, dx / 2, 0, -dx / 2, -dx / 2)
422 y.offset <- c(dy / 2, dy, dy / 2, -dy / 2, -dy, -dy / 2, dy / 2)
423
424 f <- function(i) list(x = hexGrid$x[i] + x.offset,
425 y = hexGrid$y[i] + y.offset)
426
427 ret = lapply(1:length(hexGrid$x), f)
428 }
429
430 # EJP, added:
431 HexPoints2SpatialPolygons = function(hex, dx) {
432 ret = genPolyList(data.frame(coordinates(hex)), dx = dx)
433 npoly = length(ret)
434 Srl <- vector(mode="list", length=npoly)
435 IDS = paste("ID", 1:npoly, sep="")
436 for (i in 1:npoly)
437 Srl[[i]] = Polygons(list(Polygon(ret[[i]])), IDS[i])
438 res <- SpatialPolygons(Srl, proj4string=rebuild_CRS(slot(hex, "proj4string")))
439 res
440 }
441
442 fiboGrid <- function(N, xlim = c(-180,180), ylim = c(-90,90)) {
443 if (max(xlim) <= 180)
444 subtr = 180
445 else
446 subtr = 0
447 phi = (1 + sqrt(5))/2
448 i = seq(-N, N)
449 P = 2 * N + 1
450 lat = asin(2*i / P) * 180 / pi
451 lon = ((2 * pi * i / phi) %% pi) * 360 / pi - subtr
452 sel = lon <= xlim[2] & lon >= xlim[1] & lat <= ylim[2] & lat >= ylim[1]
453 cbind(lon, lat)[sel, ]
454 }