Skip to content

Instantly share code, notes, and snippets.

@JosiahParry
Created January 27, 2024 17:28
Show Gist options
  • Save JosiahParry/beb367246617ab99ea0190fb2557dd36 to your computer and use it in GitHub Desktop.
Save JosiahParry/beb367246617ab99ea0190fb2557dd36 to your computer and use it in GitHub Desktop.
# Positive Slope Scenario
x <- wk::wkt(
  c(
    "LINESTRING(0.0 0.0, 2.0 2.0)", # target line
    "LINESTRING(0.5 0.75, 2.5 2.75)", # one we've deemed parallel
    # desribes the overlap range (2D)
    "POLYGON((0.5 0.75, 2.0 0.75, 2.0 2.0, 0.5 2.0, 0.5 0.75))" 
  )
) 
plot(x[1:2])
plot(x[3], lwd = 3, lty = 1, border = "red", add = TRUE)

# Negative Slope Scenario
x <- wk::wkt(
  c(
    "LINESTRING(0 2, 2 0)", # target line
    "LINESTRING(1 0.5, 3 -1.5)", # deemed parallel
    # overlap range (2D)
    "POLYGON((1.0 0.0, 2.0 0.0, 2.0 0.5, 1.0 0.5, 1.0 0.0))"
  )
)

plot(x[1:2])
plot(x[3], lwd = 3, lty = 1, border = "red", add = TRUE)

# Undefined Slope Scenario
x <- wk::wkt(
  c(
    "LINESTRING(2 1.5, 2 2.5)", # the target line 
    "LINESTRING(1 1, 1 2)", # deemed parallel
    "LINESTRING(2 1.5, 2 2)" # overlap range (1D)
  )
)

plot(x[1:2])
plot(x[3], lwd = 3, lty = 1, col = "red", add = TRUE)

# No slope scenario
x <- wk::wkt(
  c(
    "LINESTRING(0 1, 2 1)", # target feature
    "LINESTRING(1 2, 3 2)", # deemed parallel
    "LINESTRING(1 1, 2 1)" # overlap range (1D)
  )
)
plot(x[1:2])
plot(x[3], lwd = 3, lty = 1, col = "red", add = TRUE)


# calculate range of x values 
x_range <- function(x) {
  bbox <- sf::st_bbox(x)
  return(c(bbox$xmin, bbox$xmax))
}

# calculate range of y values 
y_range <- function(x) {
  bbox <- sf::st_bbox(x)
  return(c(bbox$ymin, bbox$ymax))
}

# calcualte overlappying range between two ranges
overlap_range <- function(r1, r2) {
  if (r1[2] < r2[1] || r2[2] < r1[1]) {
    return(NA)
  } else {
    return(c(max(r1[1], r2[1]), min(r1[2], r2[2])))
  }
}

# example usage
overlap_range(x_range(x[1]), x_range(x[2]))

#> [1] 1 2
overlap_range(y_range(x[1]), y_range(x[2]))
#> [1] NA

Created on 2024-01-27 with reprex v2.0.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment