File: spatstat.R

package info (click to toggle)
r-cran-sf 0.9-7%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,796 kB
  • sloc: cpp: 5,333; sh: 18; makefile: 2
file content (306 lines) | stat: -rw-r--r-- 10,062 bytes parent folder | download
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# window_polygons_from_edges = function (w) {
#	mw = as.matrix(w$ends)
#	lst1 = lapply(seq_len(NROW(mw)), function(i) st_linestring(matrix(mw[i,], 2, byrow = TRUE)))
#	p0 = st_polygonize(do.call(c, do.call(st_sfc, lst1)))
#	if (length(p0) > 1) # multiple POLYGONs, returned as sfc_
#		do.call(c, st_collection_extract(p0, "POLYGON")) # MULTIPOLYGON
#	else
#		st_cast(p0, "POLYGON")
# }


#' @name st_as_sf
#' @export
#' @examples
#' if (require(spatstat)) {
#'   g = st_as_sf(gorillas)
#'   # select only the points:
#'   g[st_is(g, "POINT"),]
#' }
st_as_sf.ppp = function(x, ...) {
  if (!requireNamespace("spatstat", quietly = TRUE))
    stop("package spatstat required, please install it first") # nocov
  # window:
  win = st_sf(label = "window", geom = st_as_sfc(spatstat::as.owin(x)))

  # points:
  m = as.matrix(data.frame(x$x, x$y))
  pointwork = st_sfc(lapply(seq_len(NROW(m)), function(i) st_point(m[i,])))
  points_sf = st_sf(label = rep("point", NROW(m)), geom = pointwork)

  # merge window and points:
  ret = rbind(win, points_sf)
  if (spatstat::is.marked(x)) {
	# add marks:
    m = as.data.frame(spatstat::marks(x))
	cbind.sf(ret, m[c(NA, seq_len(nrow(m))),])
  } else
  	ret
}


#' @name st_as_sf
#' @export
st_as_sf.psp = function(x, ...) {
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required, please install it first")
	# line segments:
 	m = as.matrix(x$ends)
	lst1 = lapply(seq_len(NROW(m)), function(i) st_linestring(matrix(m[i,], 2, byrow = TRUE)))

	# window:
	win = st_as_sfc(spatstat::as.owin(x))[[1]]

	label = c("window", rep("segment", NROW(m)))
	ret = st_sf(label = label, geom = st_sfc(c(list(win), lst1)))
	if (spatstat::is.marked(x)) { # add marks:
		m = as.data.frame(spatstat::marks(x))
		cbind.sf(ret, m[c(NA, seq_len(nrow(m))),])
	} else
		ret
}

# 111117 from psp to SpatialLines, Rolf Turner, Adrian Baddeley, Mathieu Rajerison
#' @export
st_as_sfc.psp <- function(x, ...) {

#	ends2line <- function(x) matrix(x, ncol=2, byrow=TRUE)
#	munch <- function(z) { list(ends2line(as.numeric(z[1:4]))) }
#	ends <- as.data.frame(x)[,1:4]
#	y <- lapply(seq_len(nrow(ends)), function(i) munch(ends[i,]))
#	st_sfc(st_multilinestring(y))
	st_geometry(st_as_sf(x, ...))
}


#' @name st_as_sf
#' @export
#' @examples
#' if (require(spatstat)) {
#'  data(chicago)
#'  plot(st_as_sf(chicago)["label"])
#'  plot(st_as_sf(chicago)[-1,"label"])
#' }
st_as_sf.lpp = function(x, ...) {
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required, please install it first")
	# lines, polygon:
	linework_sf = st_as_sf(spatstat::as.psp(spatstat::domain(x)))
	# points:
	m = as.matrix(as.data.frame(x$data)[1:2])
	pointwork = st_sfc(lapply(seq_len(NROW(m)), function(i) st_point(m[i,])))
	sf = rbind(linework_sf, st_sf(label = rep("point", NROW(m)), geom = pointwork))
	# de-select point coordinates
	m = as.data.frame(x$data)[c(rep(NA,nrow(linework_sf)),seq_len(nrow(m))), -(1:2)]
	structure(cbind.sf(sf, m), row.names = seq_len(nrow(m)))
}

# as.ppp etc methods: from maptools/pkg/R/spatstat1.R

as.ppp.sfc = function(X) {
	# require(spatstat)
	if (isTRUE(st_is_longlat(X)))
		stop("Only projected coordinates may be converted to spatstat class objects")
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required: install first?")
	d = st_dimension(X)
	if (d[1] == 2 && all(d[-1] == 0)) {
		W = spatstat::as.owin(X[1])
		X = X[-1]
		check = TRUE
	} else if (all(d == 0)) { # no window in first feature geometry:
		bb <- st_bbox(X)
		W = spatstat::owin(bb[c("xmin", "xmax")], bb[c("ymin", "ymax")])
		check = FALSE
	} else
		stop("sfc object does not consist of points, or a window followed by points")
	cc = st_coordinates(X)
	spatstat::ppp(cc[,1], cc[,2], window = W, marks = NULL, check = check)
}

as.ppp.sf = function(X) {
	if (isTRUE(st_is_longlat(X)))
		stop("Only projected coordinates may be converted to spatstat class objects")
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required: install first?")
	pp = spatstat::as.ppp(st_geometry(X))
	if (st_dimension(X[1,]) == 2)
		X = X[-1,]
	st_geometry(X) = NULL # remove geometry column
	if (ncol(X) > 1)
		warning("only first attribute column is used for marks")

	if (ncol(X) == 0)
		pp
	else 
		spatstat::setmarks(pp, X[1])
}

as.owin.POLYGON = function(W, ..., fatal, check_polygons = TRUE) {
	if (isTRUE(st_is_longlat(W)))
		stop("Only projected coordinates may be converted to spatstat class objects")
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required: install first?")
	if (check_polygons)
		W = check_ring_dir(W)
	bb = st_bbox(W)
	spatstat::owin(bb[c("xmin", "xmax")], bb[c("ymin", "ymax")], poly = W)
}

as.owin.MULTIPOLYGON = function(W, ..., fatal, check_polygons = TRUE) {
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required: install first?")
	if (check_polygons)
		W = check_ring_dir(W)
	bb = st_bbox(W)
	spatstat::owin(bb[c("xmin", "xmax")], bb[c("ymin", "ymax")], 
		poly = unlist(W, recursive = FALSE))
}

as.owin.sfc_POLYGON = function(W, ..., fatal, check_polygons = TRUE) {
	if (isTRUE(st_is_longlat(W)))
		stop("Only projected coordinates may be converted to spatstat class objects")
	if (check_polygons)
		W = check_ring_dir(W)
	as.owin.MULTIPOLYGON(W, check_polygons = FALSE)
	# I know, this looks wrong, but isn't: sfc_POLYGON is a logically a MULTIPOLYGON
}

as.owin.sfc_MULTIPOLYGON = function(W, ..., fatal, check_polygons = TRUE) {
	if (isTRUE(st_is_longlat(W)))
		stop("Only projected coordinates may be converted to spatstat class objects")
	if (check_polygons)
		W = check_ring_dir(W)
	as.owin.sfc_POLYGON(st_cast(W, "POLYGON"), check_polygons = FALSE)
}

as.owin.sfc = function(W, ...) {
	if (!all(st_dimension(W) == 2))
		stop("as.owin.sfc needs polygonal geometries")
	as.owin.sfc_MULTIPOLYGON(st_cast(W, "MULTIPOLYGON"), ...)
}

as.owin.sf = function(W, ...) {
	as.owin.sfc(st_geometry(W), ...)
}

#' @export
st_as_sfc.owin = function(x, ...) {
# FROM: methods for coercion to Spatial Polygons by Adrian Baddeley, pkg maptools
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required: install first?")
	if (!requireNamespace("spatstat.utils", quietly = TRUE))
		stop("package spatstat.utils required: install first?")
	x <- spatstat::as.polygonal(x)
	closering <- function(df) { df[c(seq(nrow(df)), 1), ] }
	pieces <- lapply(x$bdry,
		function(p) st_polygon(list(closering(cbind(p$x,p$y)))))
	h = sapply(x$bdry, spatstat.utils::is.hole.xypolygon)   # holes
	holes = do.call(st_sfc, pieces[h])
	exteriors = pieces = do.call(st_sfc, pieces[!h])
	# assign each hole to the smallest exterior it is covered by:
	cb = st_covered_by(holes, pieces)
	for (i in seq_along(cb)) {
		w = which.min(st_area(exteriors[ cb[[i]] ]))
		pieces[[w]] = st_polygon(c(unclass(pieces[[w]]), unclass(holes[[i]])))
	}
	if (length(pieces) > 1) # multiple POLYGONs, collapse:
		st_sfc(do.call(c, pieces))
	else
		pieces
}

#' @export
st_as_sf.owin = function(x, ...) {
	st_sf(geom = st_as_sfc(x, ...))
}


#' @export
st_as_sfc.tess <- function(x, ...) {
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required: install first?")
	stopifnot(spatstat::is.tess(x))
	y <- spatstat::tiles(x)
	nam <- names(y)
	z <- list()
	for(i in seq_along(y)) {
		zi <- try(st_as_sfc(y[[i]], nam[i]), silent=TRUE)
		if (inherits(zi, "try-error"))
			warning(paste("tile", i, "defective\n", as.character(zi)))
		else
			z[[i]] <- zi
    }
	do.call(c, z)
}

# methods for 'as.psp' for sp classes by Adrian Baddeley
as.psp.LINESTRING <- function(from, ..., window=NULL, marks=NULL, fatal) {
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required: install first?")
	xy <- unclass(from)
	df <- as.data.frame(cbind(xy[-nrow(xy), , drop=FALSE], xy[-1, , drop=FALSE]))
	if (is.null(window)) {
		xrange <- range(xy[,1])
		yrange <- range(xy[,2])
		window <- spatstat::owin(xrange, yrange)
	}
	spatstat::as.psp(df, window=window, marks=marks)
}

as.psp.MULTILINESTRING <- function(from, ..., window=NULL, marks=NULL, fatal) {
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required: install first?")
	y <- lapply(from, as.psp.LINESTRING, window=window)
    z <- do.call(spatstat::superimpose,c(y,list(W=window)))
	if(!is.null(marks))
		spatstat::setmarks(z, marks)
	else
		z
}

as.psp.sfc_MULTILINESTRING <- function(from, ..., window=NULL, marks=NULL,
                                 characterMarks=FALSE, fatal) {

	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required: install first?")
	if (isTRUE(st_is_longlat(from)))
		stop("Only projected coordinates may be converted to spatstat class objects")

	if(is.null(window)) {
		bb = st_bbox(from)
		window = spatstat::owin(bb[c("xmin", "xmax")], bb[c("ymin", "ymax")]) 
	}
	lin <- unclass(from)
	y <- lapply(lin, as.psp.MULTILINESTRING, window=window)
    z <- do.call(spatstat::superimpose, c(y, list(W = window)))
	if(!is.null(marks))
		spatstat::setmarks(z, marks)
	else
		z
}

as.psp.sfc = function(from, ...) {
	as.psp.sfc_MULTILINESTRING(st_cast(from, "MULTILINESTRING"))
}

as.psp.sf <- function(from, ..., window=NULL, marks=NULL, fatal) {
	if (!requireNamespace("spatstat", quietly = TRUE))
		stop("package spatstat required: install first?")
	if (isTRUE(st_is_longlat(from)))
		stop("Only projected coordinates may be converted to spatstat class objects")

	y <- st_geometry(from)
	if (!inherits(y, "sfc_MULTILINESTRING"))
		stop("geometries should be of type LINESTRING")
	z <- spatstat::as.psp(y, window=window, marks=marks)
	if(is.null(marks)) {
		# extract marks from first column of data frame
		st_geometry(from) = NULL # remove geometry column
		nseg.LINESTRING  <- function(x) { nrow(x) - 1 }
		nseg.MULTILINESTRING <- function(x) { sum(unlist(lapply(x, nseg.LINESTRING))) }
		nrep <- unlist(lapply(y, nseg.MULTILINESTRING))
		spatstat::setmarks(z, from[rep(seq_len(nrow(from)), nrep),])
	} else
		z
}