Skip to content

Commit d15a9b7

Browse files
committed
Speed up algorithm by only calculating the intersections of vectors that hit land
1 parent 9071584 commit d15a9b7

File tree

2 files changed

+22
-17
lines changed

2 files changed

+22
-17
lines changed

DESCRIPTION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
Package: fetchR
22
Type: Package
33
Title: Calculate fetch in New Zealand
4-
Version: 1.2-2
4+
Version: 1.3-0
55
Date: 2017-02-16
66
Authors@R: person("Blake", "Seers", role = c("aut", "cre"),
77
email = "blake.seers@gmail.com")

R/fetch.R

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,9 @@ fetch = function(lat, lon, max_dist = 300, n_bearings = 9,
9393
if (any(!is.na(over(coastal_nz, centre_point_proj))))
9494
stop("coordinate is on land")
9595

96+
if (!quiet)
97+
message("calculating fetch")
98+
9699
max_dist = max_dist * 1000
97100
bearings = head(seq(0, 360, by = 360 / (n_bearings * 4)), -1)
98101
# Rearrange sequence order to start at 90 degrees to match up with the output
@@ -108,26 +111,28 @@ fetch = function(lat, lon, max_dist = 300, n_bearings = 9,
108111
coastal_nz_subset = coastal_nz[which(!is.na(over(coastal_nz, d_bff))), ]
109112

110113
# Calculate end points at the maximum distances.
111-
max_dist_endpoints = head(coordinates(d_bff@polygons[[1]]@Polygons[[1]]), -1)
114+
fetch_ends = head(coordinates(d_bff@polygons[[1]]@Polygons[[1]]), -1)
112115

113116
# Create spatialLines object
114-
fetch_sp_lines = create_sp_lines(centre_point_proj, max_dist_endpoints, bearings)
117+
fetch_sp_lines = create_sp_lines(centre_point_proj, fetch_ends, bearings)
115118

116119
# Which fetch bearings hit land?
117-
hit_land = !sapply(gIntersects(fetch_sp_lines, coastal_nz_subset,
118-
byid = c(TRUE, FALSE), returnDense = FALSE),
119-
is.null)
120-
121-
# Calculate intersections and identify closest shoreline
122-
123-
if (!quiet)
124-
message("calculating fetch")
125-
ints = gIntersection(fetch_sp_lines, coastal_nz_subset, byid = c(TRUE, FALSE))
126-
127-
fetch_ends = max_dist_endpoints
128-
fetch_ends[hit_land, ] = t(sapply(ints@lines, function(x){
129-
coordinates(x)[[1]][1, ]
130-
}))
120+
if (length(coastal_nz_subset) > 0){
121+
hit_land = !sapply(gIntersects(fetch_sp_lines, coastal_nz_subset,
122+
byid = c(TRUE, FALSE), returnDense = FALSE),
123+
is.null)
124+
125+
## Calculate intersections and identify closest shoreline for those vectors
126+
## that hit land
127+
128+
ints = gIntersection(fetch_sp_lines[hit_land], coastal_nz_subset,
129+
byid = c(TRUE, FALSE))
130+
131+
fetch_ends[hit_land, ] = t(sapply(ints@lines, function(x){
132+
coordinates(x)[[1]][1, ]
133+
}))
134+
135+
}
131136

132137
# Return the Fetch object
133138

0 commit comments

Comments
 (0)