-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrid_creation.R
84 lines (73 loc) · 2.55 KB
/
grid_creation.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# Forecasting Crime in Portland
# ** Creating Potential Tilings of Portland **
# Michael Chirico, Seth Flaxman,
# Charles Loeffler, Pau Pereira
library(maptools)
library(rgdal)
library(rgeos)
library(sp)
library(funchir)
#projection used by all official things Portland
prj = CRS("+init=epsg:2913")
portland <-
gBuffer(
gUnaryUnion(readShapePoly("./data/Portland_Police_Districts.shp",
proj4string = prj)),
byid = TRUE, width = 0
)
bb <- bbox(portland)
# =============================================================================
# RECTANGULAR GRIDS
# =============================================================================
## list out our choices of grid, including
## also a companion for easy saving
cell.sizes =
list(sq_max = list(dims = c(x = 600, y = 600),
name = 'rec600x600'),
sq_mid = list(dims = c(x = 460, y = 460),
name = 'rec460x460'),
#roughly gauging the typical block shape
rec_block = list(dims = c(x = 370, y = 750),
name = 'rec370x750'))
## create rectangular grids
invisible(
sapply(cell.sizes, function(c.type)
with(c.type, {
n.cells = round(apply(bb, 1L, diff)/dims)
# create SpatialPolygonsDataFrame:
grd.layer <-
SpatialPolygonsDataFrame(
as.SpatialPolygons.GridTopology(
GridTopology(cellcentre.offset = bb[ , 'min'],
cellsize = dims,
cells.dim = n.cells),
proj4string = prj), data = data.frame(id = integer(prod(n.cells))),
match.ID = FALSE
)
names(grd.layer) <- "ID"
# intersect grid with boundaries of Portland:
# See http://stackoverflow.com/questions/15881455/
# Apparently when the grid is small enough, some problems occur from
# cells which don't intersect the city?? Not sure. But this works:
grd =
gIntersection(
grd.layer[which(gIntersects(grd.layer, portland, byid = TRUE)), ],
portland, byid = TRUE
)
# Sanity checks
# grd.bdy <- gUnaryUnion(grd)
# areas <- poly.areas(grd)
# areas.total <- gArea(grd)
# turn grid to SpatialPointsDataFrame with data=id
grd =
SpatialPolygonsDataFrame(
grd, data = data.frame(grd.id = gsub("\\s.*", "", names(grd))),
match.ID = FALSE
)
#save output
writeOGR(grd, dsn = './data/grids/',
layer = name, driver = "ESRI Shapefile")
}
)
)
)