## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = requireNamespace("arrow", quietly = TRUE) &&
    requireNamespace("tibble", quietly = TRUE)
)

## ----setup, eval = TRUE-------------------------------------------------------
library(a5R)

## ----naive, message = FALSE---------------------------------------------------
library(arrow)
library(tibble)

# A real A5 cell: Edinburgh at resolution 20
cell <- a5_lonlat_to_cell(-3.19, 55.95, resolution = 20)
a5_u64_to_hex(cell)

# Write to Parquet as uint64 (the standard interchange format)
tf <- tempfile(fileext = ".parquet")
arrow::write_parquet(
  arrow::arrow_table(cell_id = a5_cell_to_arrow(cell)),
  tf
)

# Read it back naively: arrow silently converts uint64 to double
(naive <- tibble(arrow::read_parquet(tf)))

cell_as_dbl <- naive$cell_id

# The double can't distinguish this cell from nearby ids
cell_as_dbl == cell_as_dbl + 1   # TRUE: silent corruption
cell_as_dbl == cell_as_dbl + 100 # still TRUE

## ----bridge-------------------------------------------------------------------
# Six cities across the globe. Tokyo and Sydney have bit 63 set: a signed
# int64 would make them negative.
cities <- tibble(
  name = c("Edinburgh", "Tokyo", "São Paulo", "Nairobi", "Anchorage", "Sydney"),
  lon  = c(   -3.19,     139.69,     -46.63,     36.82,    -149.90,    151.21),
  lat  = c(   55.95,      35.69,     -23.55,     -1.29,      61.22,    -33.87)
)

cities$cell <- a5_lonlat_to_cell(cities$lon, cities$lat, resolution = 10)
cities

## ----enrich-------------------------------------------------------------------
edinburgh <- cities$cell[1]

cities$resolution <- a5_get_resolution(cities$cell)
cities$dist_from_edinburgh_km <- as.numeric(
  a5_cell_distance(cities$cell, rep(edinburgh, nrow(cities)), units = "km")
)

cities

## ----parquet_write------------------------------------------------------------
tf <- tempfile(fileext = ".parquet")
arrow::write_parquet(a5_to_arrow_table(cities), tf)

## ----parquet_read-------------------------------------------------------------
pq <- arrow::read_parquet(tf, as_data_frame = FALSE)
pq$schema
result <- a5_from_arrow_table(pq)
identical(result$cell, cities$cell)

## ----covering_write-----------------------------------------------------------
cities$within_50km <- a5_spherical_cap(cities$cell, radius = 50000)
cities[c("name", "within_50km")]

tf <- tempfile(fileext = ".parquet")
arrow::write_parquet(a5_to_arrow_table(cities[c("name", "cell", "within_50km")]), tf)
pq <- arrow::read_parquet(tf, as_data_frame = FALSE)
pq$schema

## ----covering_read------------------------------------------------------------
back <- a5_from_arrow_table(pq)
identical(back$within_50km, cities$within_50km)

## ----migrate, eval = TRUE-----------------------------------------------------
# A resolution-8 cell id written by a5R 0.6
v0 <- a5_cell("59c4780000000000")
a5_migrate(v0)

