## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  tidy = FALSE
)

## ----setup--------------------------------------------------------------------
library(osbng)
library(sf)

## -----------------------------------------------------------------------------
list_bng_bounds()

## -----------------------------------------------------------------------------
list_bng_prefixes()

## -----------------------------------------------------------------------------
list_bng_resolution(lbl = TRUE)

## -----------------------------------------------------------------------------
list_bng_resolution(lbl = FALSE)

## -----------------------------------------------------------------------------
# Convert a BNG reference string into a `BNGReference` object
bng_ref <- as_bng_reference("SU 372 155")

bng_ref

## -----------------------------------------------------------------------------
# The BNG reference string as a compact string
print(bng_ref, compact = TRUE)

## -----------------------------------------------------------------------------
# The BNG reference string as a formatted string (default behaviour)
print(bng_ref, compact = FALSE)

## -----------------------------------------------------------------------------
# The BNG resolution expressed in metres
get_bng_resolution(bng_ref)

## -----------------------------------------------------------------------------
# The BNG resolution expressed as a descriptive label
get_bng_resolution_string(bng_ref)

## -----------------------------------------------------------------------------
# Easting and northing coordinates
x <- 437293
y <- 115543

# Convert easting and northing to BNGReference at 1km resolution
bng_ref <- xy_to_bng(x, y, resolution = "1km")

bng_ref

## -----------------------------------------------------------------------------
# Decode BNGReference back into coordinates
# Default "position" is "lower-left"
bng_to_xy(bng_ref)

## -----------------------------------------------------------------------------
# Decode BNGRefernece back into coordinates
# Centroid of the grid square
# "position" can be one of "lower-left", "upper-left", "lower-right", "upper-right", "centre"
bng_to_xy(bng_ref, position = "centre")

## -----------------------------------------------------------------------------
# Return the grid square bounding box coordinates for the BNGRference object
bng_to_bbox(bng_ref)

## -----------------------------------------------------------------------------
# Return the grid square as a geos geometry object for the BNGReference object
# Alternatively return the geometry as WKT or `sf` object
bng_to_grid_geom(bng_ref)

## -----------------------------------------------------------------------------
# Easting and northing coordinates
x <- 437293
y <- 115543

# Construct a geos Point geometry from easting and northing coordinates
geom <- geos::geos_make_point(x, y)

# Return the BNGReference object for the geometry at a 5km resolution
geom_to_bng(geom = geom, resolution = "5km")

## -----------------------------------------------------------------------------
# Return the indexed results for the geometry at a 5km resolution
# For a Point geometry, the intersection geometry is the same as the original geometry
# The is_core property will always be False for a Point geometry
geom_to_bng_intersection(geom = geom, resolution = "5km")

## -----------------------------------------------------------------------------
# Create a geos LineString geometry from Well Known Text (WKT)
geom <- geos::geos_read_wkt("LINESTRING (436171.8 114893.7, 437861.3 116130.0)")

# Return a list of the BNGReference object(s) intersected by the geometry at a 1km resolution
geom_to_bng(geom = geom, resolution = "1km")

## -----------------------------------------------------------------------------
# Return a nested list of the indexing results for the geometry at a 1km resolution
# The is_core property will always be False for a LineString geometry
geom_to_bng_intersection(geom = geom, resolution = "1km")

## ----tidy=FALSE---------------------------------------------------------------
# Return the indexed results
bng_idx_geoms <- geom_to_bng_intersection(geom = geom, 
                                          resolution = "1km", 
                                          format = "sf")

# Store the indexed results as a spatial data frame
bng_idx_geoms <- st_sf(data.frame(bng_idx_geoms))

# Store the intersected BNGReference grid squares for context
bng_grid_geoms <- bng_to_grid_geom(bng_idx_geoms$bng_reference, 
                                   format = "sf")

## ----tidy=FALSE, fig.height=6.5, fig.width=6.5--------------------------------
# Categorical colours
# https://github.com/OrdnanceSurvey/GeoDataViz-Toolkit/blob/master/Colours/GDV%20colour%20palettes_v0.9.1.pdf
catcols <- c("#FF1F5B", "#009ADE", "#FFC61E", "#AF58BA")

# Plot geometries representing the intersection between the geometry and the BNG grid squares
plot(st_geometry(bng_idx_geoms),
     col = catcols,
     lwd = 3,
     extent = st_bbox(bng_grid_geoms),
     main = "Decomposition of LineString Geometry into BNG Grid Squares at a 1km Resolution",
     cex.main = .8,
     axes = TRUE,
     xlab = "Easting",
     ylab = "Northing")

# Plot intersected BNGReference grid squares for context
plot(st_geometry(bng_grid_geoms),
     col = NA,
     border = "#00000075",
     lty = "dashed",
     add = TRUE)

## -----------------------------------------------------------------------------
# Create a geos Polygon geometry from Well Known Text (WKT)
geom <- geos::geos_read_wkt("POLYGON ((436661.45305455 115784.01571607, 437629.10896848 116112.11767069, 438229.486575 115953.45344189, 437990.51082297 114935.84767816, 436630.11197232 115085.69722758, 436661.45305455 115784.01571607))")

## -----------------------------------------------------------------------------
# Return a list of the BNGRefernce objects intersected by the geometry at a 500m resolution
geom_to_bng(geom, resolution = 500)

## -----------------------------------------------------------------------------
# Return a nested list of the indexed geometry and BNGReference objects for the geometry at 500m resolution
geom_to_bng_intersection(geom, resolution = 500)

## -----------------------------------------------------------------------------
# Return the indexed results
bng_idx_geoms <- geom_to_bng_intersection(geom = geom, 
                                          resolution = 500, 
                                          format = "sf")

# Store the indexed results as a spatial data frame
bng_idx_geoms <- st_sf(data.frame(bng_idx_geoms))

# Store the intersected BNGReference grid squares for context
bng_grid_geoms <- bng_to_grid_geom(bng_idx_geoms$bng_reference, 
                                   format = "sf")

## ----tidy=FALSE, fig.height=6.5, fig.width=6.5--------------------------------
# Plot core and edge geoemtries
plot(bng_idx_geoms["is_core"],
     border = "#fff",
     col = c("#009ade", "#ff1f5b")[bng_idx_geoms$is_core + 1],
     main = "Decomposition of Polygon Geometry into BNG Grid Squares at a 500m Resolution",
     cex.main = .8,
     axes = TRUE,
     xlab = "Easting",
     ylab = "Northing")

legend(0.05, 1, 
       title = "is_core",
       legend = c("True", "False"),  
       fill = c("#ff1f5b", "#009ade"))

## -----------------------------------------------------------------------------
# Convert a BNG reference string into a BNGReference object
bng_ref <- as_bng_reference("SU 372 155")

# The resolution of the BNGReference object as a descriptive label
get_bng_resolution_string(bng_ref)

## -----------------------------------------------------------------------------
# Return the parent BNGReference object at the next higher resolution
bng_to_parent(bng_ref)

## -----------------------------------------------------------------------------
# Return the parent BNGReference object at a custom higher resolution
bng_to_parent(bng_ref, resolution = "50km")

## ----tidy=FALSE, fig.height=6.5, fig.width=6.5--------------------------------
# Return the parent BNGReference object
bng_ref_parent <- bng_to_parent(bng_ref)

# Store the BNGReference grid squares
bng_geom <- bng_to_grid_geom(bng_ref, format = "sf")
bng_parent_geom <- bng_to_grid_geom(bng_ref_parent, format = "sf")

# Plot the parent BNGReference grid square
plot(st_geometry(bng_parent_geom),
     col = "gray80",
     border = "#00000075",
     lty = "dashed",
     lwd = 2,
     main = "500m Resolution Parent of a 100m Resolution BNG Grid Square",
     cex.main = .9,
     axes = TRUE,
     xlab = "Easting",
     ylab = "Northing")

# Plot the original BNGReference grid square
plot(st_geometry(bng_geom),
     col = "#AF58BA",
     add = TRUE)

## -----------------------------------------------------------------------------
# Return the children of the BNGReference object at the next lower resolution
bng_to_children(bng_ref)

## -----------------------------------------------------------------------------
# Return the children of the BNGReference object at a custom lower resolution
bng_to_children(bng_ref, resolution = "10m")

## ----tidy=FALSE, fig.height=6.5, fig.width=6.5--------------------------------
# Return the BNGReference object for the children at 10m resolution
bng_refs_children <- bng_to_children(bng_ref, resolution = "10m")

# Store the BNGReference grid squares
bng_geom <- bng_to_grid_geom(bng_ref, format = "sf")
bng_children_geom <- bng_to_grid_geom(bng_refs_children[[1]], format = "sf")

# Plot the parent BNGReference grid square
plot(st_geometry(bng_children_geom),
     col = "gray80",
     border = "#00000075",
     lty = "dashed",
     main = "10m Resolution Children of a 100m Resolution BNG Grid Square",
     cex.main = .9,
     axes = TRUE,
     xlab = "Easting",
     ylab = "Northing")

# Plot the original BNGReference grid square
plot(st_geometry(bng_geom),
     col = NA,
     border = "#AF58BA",
     lwd = 3,
     add = TRUE)

## -----------------------------------------------------------------------------
# Convert a BNG reference string into a BNGReference object
bng_ref <- as_bng_reference("SU 372 155")

## -----------------------------------------------------------------------------
# Return a list of BNGReference objects representing a filled disc around the BNGReference object
#  up to a grid distance k, including the given central BNGReference object
bng_kdisc(bng_ref, k = 2)

## ----tidy=FALSE, fig.height=6.5, fig.width=6.5--------------------------------
# Return a k-disc of the BNGReference object at a grid distance of k=2
bng_ref_kdisc = bng_kdisc(bng_ref, k = 2)

# Store the BNGReference grid squares
bng_geom <- bng_to_grid_geom(bng_ref, format = "sf")
bng_kdisc_geoms <- bng_to_grid_geom(bng_ref_kdisc[[1]], format = "sf")

# Plot the BNGReference grid squares in the k-disc
plot(st_geometry(bng_kdisc_geoms),
     col = "gray80",
     border = "#00000075",
     lty = "dashed",
     main = "K-Disc Around a BNG Grid Square Where k=2",
     cex.main = .9,
     axes = TRUE,
     xlab = "Easting",
     ylab = "Northing")

# Plot the original BNGReference grid square for context
plot(st_geometry(bng_geom),
     col = "#009ade",
     add = TRUE)

## -----------------------------------------------------------------------------
# Return a list of BNGReference objects representing a hollow ring around around 
#  the BNGReference object at a grid distance k
bng_kring(bng_ref, k = 1)

## ----tidy=FALSE, fig.height=6.5, fig.width=6.5--------------------------------
# Return a k-ring of the BNGReference object at a grid distance of k=2
bng_ref_kring = bng_kring(bng_ref, k = 3)

# Store the BNGReference grid squares
bng_geom <- bng_to_grid_geom(bng_ref, format = "sf")
bng_kring_geoms <- bng_to_grid_geom(bng_ref_kring[[1]], format = "sf")

# Plot the BNGReference grid squares in the k-disc
plot(st_geometry(bng_kring_geoms),
     col = "gray80",
     border = "#00000075",
     lty = "dashed",
     main = "K-Ring Around a BNG Grid Square Where k=3",
     cex.main = .9,
     axes = TRUE,
     xlab = "Easting",
     ylab = "Northing")

# Plot the original BNGReference grid square for context
plot(st_geometry(bng_geom),
     col = "#009ade",
     add = TRUE)

## -----------------------------------------------------------------------------
# Convert BNG reference strings into BNGReference objects
bng_ref1 <- as_bng_reference("SU 372 155")
bng_ref2 <- as_bng_reference("SU 371 155")

## -----------------------------------------------------------------------------
# Check if the two BNGReference objects are neighbours
bng_is_neighbour(bng_ref1, bng_ref2)

## -----------------------------------------------------------------------------
# Convert BNG reference strings into BNGReference objects
bng_ref1 <- as_bng_reference("SX")
bng_ref2 <- as_bng_reference("SU 1 2")

# Return the distance between two BNGReference objects in metres
# The default distance is calculated as the Euclidean distance between the centroids of the grid squares
bng_distance(bng_ref1, bng_ref2)

## -----------------------------------------------------------------------------
# Return the distance between two BNGReference objects in metres
# edge_to_edge=True calculates the distance between the edges of the grid squares
bng_distance(bng_ref1, bng_ref2, edge_to_edge = TRUE)

## -----------------------------------------------------------------------------
# Convert BNG reference stringsinto a BNGReference object
bng_ref <- as_bng_reference("ST 3 8")

# Return all BNGReference objects within a given distance d of the input BNGReference object
bng_dwithin(bng_ref, d = 1000)

## -----------------------------------------------------------------------------
# Create an sf data frame of 100km resolution BNGReference object features
gdf <- bng_grid_100km()

gdf

## -----------------------------------------------------------------------------
# Create an sf data frame of 1km resolution BNGReference object features within a bunding box

# Custom bounding box coordinates
# (xmin, ymin, xmax, ymax)
gdf <- bng_grid_1km(529476, 179654, 532170, 181116)

gdf

