Created
October 23, 2015 13:00
-
-
Save nutterb/727755cf2a0568760556 to your computer and use it in GitHub Desktop.
Speed comparisons for different methods of comparing rectangles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#* A broader experiment on this stack overflow question | |
#* http://stackoverflow.com/questions/33298196/how-to-avoid-a-double-for-loop-when-accessing-all-combinations-of-colums-of-a-ma/33301080?noredirect=1#comment54403634_33301080 | |
#* I really need to find something better to do with my Friday mornings | |
#* Change n to make a larger experiment | |
n <- 1000 | |
#* Change reps to run more cycles in 'microbenchmark' | |
reps <- 10 | |
#* Peer review: is this a fair way to make arbitrary rectangles? | |
random_rectangle <- function(){ | |
x <- sort(sample(1:25, 2, replace = TRUE)) | |
y <- sort(sample(1:25, 2, replace = TRUE)) | |
c(x, y) | |
} | |
D <- do.call("cbind", | |
lapply(1:n, | |
function(i) random_rectangle())) | |
library(sp) | |
library(rgeos) | |
library(microbenchmark) | |
intersecting_rects <- function(edge1, edge2){ | |
#* index 1 is left edge, index 2 is right edge | |
#* index 3 is lower edge, index 4 is upper edge | |
(edge1[1] < edge2[2] && edge1[2] > edge2[1] && | |
edge1[3] < edge2[4] && edge1[4] > edge2[3]) | |
} | |
D1 <- t(D) | |
D1 <- D1[, c(1, 3, 2, 3, 2, 4, 1, 4)] | |
ID <- paste0('rect', seq_len(nrow(D1))) | |
# Create SP | |
#http://stackoverflow.com/a/26620550/1412059 | |
polys <- SpatialPolygons(mapply(function(poly, id) { | |
xy <- matrix(poly, ncol=2, byrow=TRUE) | |
Polygons(list(Polygon(xy)), ID=id) | |
}, split(D1, row(D1)), ID)) | |
# Create SPDF | |
polys.df <- SpatialPolygonsDataFrame(polys, data.frame(id=ID, row.names=ID)) | |
microbenchmark( | |
poly = { | |
res <- gOverlaps(polys.df, byid = TRUE) | | |
gContains(polys.df, byid = TRUE) | | |
gWithin(polys.df, byid = TRUE) | | |
gCovers(polys.df, byid = TRUE) | |
diag(res) <- 0 | |
}, | |
full_loop = { | |
E <- mat.or.vec(nr=n, nc=n) | |
for (i in 1:n){ | |
for (j in 1:n){ | |
E[i, j] <- as.numeric(intersecting_rects(D[, i], D[, j])) | |
} | |
} | |
}, | |
partial_loop = { | |
E <- mat.or.vec(nr=n, nc=n) | |
for (i in 1:n){ | |
for (j in (i:n)[-1]){ | |
E[i, j] <- as.numeric(intersecting_rects(D[, i], D[, j])) | |
} | |
} | |
E[lower.tri(E)] <- t(E)[lower.tri(E)] | |
}, | |
times = 10 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment