tests/testthat/test_get_pts_coords.R

skip_if_not_installed("scales")
skip_if_not_installed("sf")

library(testthat)
library(sf)

# -----------------------------------------------------------------------------
# Shared synthetic dataset
# -----------------------------------------------------------------------------

# A genuine 2D grid of known lon/lat locations.
# These are used as GCPs.
lon_grid <- seq(-3.2, -3.0, length.out = 5)
lat_grid <- seq(55.8, 56.0, length.out = 4)

gcp_ll <- expand.grid(
  longitude = lon_grid,
  latitude = lat_grid
)

gcp_ll$id <- seq_len(nrow(gcp_ll))

sf_gcp_ll <- st_as_sf(
  gcp_ll,
  coords = c("longitude", "latitude"),
  crs = 4326
)

# -----------------------------------------------------------------------------
# Project GCPs to a projected CRS
# -----------------------------------------------------------------------------

sf_gcp_proj <- st_transform(sf_gcp_ll, 3857)

gcp_proj_coords <- st_coordinates(sf_gcp_proj)

# -----------------------------------------------------------------------------
# Create synthetic pixel coordinates for GCPs
# -----------------------------------------------------------------------------

gcp_px <- scales::rescale(gcp_proj_coords[, 1], to = c(100, 1000))
gcp_py <- scales::rescale(gcp_proj_coords[, 2], to = c(100, 1000))

pixel_gcp <- data.frame(
  id = gcp_ll$id,
  x = gcp_px,
  y = gcp_py,
  longitude = st_coordinates(sf_gcp_ll)[, 1],
  latitude = st_coordinates(sf_gcp_ll)[, 2]
)

# -----------------------------------------------------------------------------
# Create a separate set of target points that lie BETWEEN grid nodes
# -----------------------------------------------------------------------------

# Midpoints in each direction, so all target points lie inside the GCP grid
lon_mid <- (lon_grid[-length(lon_grid)] + lon_grid[-1]) / 2
lat_mid <- (lat_grid[-length(lat_grid)] + lat_grid[-1]) / 2

target_ll <- expand.grid(
  longitude = lon_mid,
  latitude = lat_mid
)

target_ll$id <- seq_len(nrow(target_ll))

sf_target_ll <- st_as_sf(
  target_ll,
  coords = c("longitude", "latitude"),
  crs = 4326
)

sf_target_proj <- st_transform(sf_target_ll, 3857)

target_proj_coords <- st_coordinates(sf_target_proj)

# Rescale the target points using the SAME scaling derived from the GCP extent
x_rng <- range(gcp_proj_coords[, 1])
y_rng <- range(gcp_proj_coords[, 2])

target_px <- scales::rescale(target_proj_coords[, 1], to = c(100, 1000), from = x_rng)
target_py <- scales::rescale(target_proj_coords[, 2], to = c(100, 1000), from = y_rng)

target_pixel_df <- data.frame(
  id = target_ll$id,
  x = target_px,
  y = target_py,
  longitude = st_coordinates(sf_target_ll)[, 1],
  latitude = st_coordinates(sf_target_ll)[, 2]
)

# -----------------------------------------------------------------------------
# Create a mildly nonlinear warped version for TPS testing
# -----------------------------------------------------------------------------

pixel_gcp_tps <- data.frame(
  id = pixel_gcp$id,
  x = pixel_gcp$x + 8 * sin(pixel_gcp$y / 250) + 4 * cos(pixel_gcp$x / 300),
  y = pixel_gcp$y + 6 * cos(pixel_gcp$x / 220) - 3 * sin(pixel_gcp$y / 260),
  longitude = pixel_gcp$longitude,
  latitude = pixel_gcp$latitude
)

target_pixel_df_tps <- data.frame(
  id = target_pixel_df$id,
  x = target_pixel_df$x + 8 * sin(target_pixel_df$y / 250) + 4 * cos(target_pixel_df$x / 300),
  y = target_pixel_df$y + 6 * cos(target_pixel_df$x / 220) - 3 * sin(target_pixel_df$y / 260),
  longitude = target_pixel_df$lon,
  latitude = target_pixel_df$lat
)


# -----------------------------------------------------------------------------
# Small helper datasets for validation/error tests
# -----------------------------------------------------------------------------

basic_gcp <- data.frame(
  id = 1:3,
  x = c(0, 100, 0),
  y = c(0, 0, 100),
  longitude = c(-3.0, -2.9, -3.0),
  latitude = c(55.0, 55.0, 55.1)
)

basic_target <- data.frame(
  id = 1,
  x = 50,
  y = 50
)

# GCPs spread 1000 px across but only 100 px down, with a non-affine
# longitude, so that the tps result depends on how distances are measured
wide_gcp <- data.frame(
  id = 1:5,
  x = c(0, 1000, 0, 1000, 300),
  y = c(0, 0, 100, 100, 40),
  longitude = c(0, 10, 0, 10, 4),
  latitude = c(0, 0, 1, 1, 0.4)
)

# target points between the GCPs
wide_target <- data.frame(
  id = 1:8,
  x = rep(c(100, 500, 700, 900), 2),
  y = rep(c(20, 70), each = 4)
)

# -----------------------------------------------------------------------------
# poly_1 recovery test
# -----------------------------------------------------------------------------

test_that("get_pts_coords correctly recovers lon/lat coordinates using poly_1", {
  gcp <- pixel_gcp
  target_pts <- target_pixel_df[, c("id", "x", "y")]
  truth <- target_pixel_df[, c("longitude", "latitude")]

  recovered <- get_pts_coords(
    gcp = gcp,
    target_pts = target_pts,
    transform_method = "poly_1"
  )

  expect_true(all(c("longitude", "latitude") %in% names(recovered)))
  expect_equal(nrow(recovered), nrow(target_pts))

  expect_equal(
    recovered$longitude,
    truth$longitude,
    tolerance = 1e-6
  )

  expect_equal(
    recovered$latitude,
    truth$latitude,
    tolerance = 1e-6
  )
})

# -----------------------------------------------------------------------------
# TPS recovery test
# -----------------------------------------------------------------------------

test_that("get_pts_coords correctly recovers lon/lat coordinates using tps", {
  skip_if_not_installed("fields")

  gcp <- pixel_gcp_tps
  target_pts <- target_pixel_df_tps[, c("id", "x", "y")]
  truth <- target_pixel_df_tps[, c("longitude", "latitude")]

  recovered <- get_pts_coords(
    gcp = gcp,
    target_pts = target_pts,
    transform_method = "tps",
    lambda = 1e-6
  )

  expect_true(all(c("longitude", "latitude") %in% names(recovered)))
  expect_equal(nrow(recovered), nrow(target_pts))

  expect_equal(
    recovered$longitude,
    truth$longitude,
    tolerance = 1e-3
  )

  expect_equal(
    recovered$latitude,
    truth$latitude,
    tolerance = 1e-3
  )
})

# -----------------------------------------------------------------------------
# TPS matches GDAL
# -----------------------------------------------------------------------------

test_that("get_pts_coords tps matches GDAL tps between the GCPs", {
  skip_if_not_installed("fields")

  # reference values from GDAL 3.13.3, obtained with:
  # gdaltransform -tps -output_xy -gcp 0 0 0 0 -gcp 1000 0 10 0
  #   -gcp 0 100 0 1 -gcp 1000 100 10 1 -gcp 300 40 4 0.4
  gdal_lon <- c(
    1.35588676861892, 5.97573649140131, 7.63351020967065, 9.19506385170972,
    1.35314249748361, 5.97147040850824, 7.63060700093157, 9.19353289121228
  )
  gdal_lat <- rep(c(0.2, 0.7), each = 4)

  result <- get_pts_coords(
    gcp = wide_gcp,
    target_pts = wide_target,
    transform_method = "tps"
  )

  expect_equal(result$longitude, gdal_lon, tolerance = 1e-8)
  expect_equal(result$latitude, gdal_lat, tolerance = 1e-8)

  # confirm that scaling each axis independently (the default of fields::Tps)
  # would not match GDAL
  lon_range <- fields::Tps(
    x = as.matrix(wide_gcp[, c("x", "y")]),
    Y = wide_gcp$longitude,
    lambda = 0
  )
  lon_range <- as.numeric(stats::predict(
    lon_range,
    as.matrix(wide_target[, c("x", "y")])
  ))
  expect_false(isTRUE(all.equal(lon_range, gdal_lon, tolerance = 1e-3)))
})

# -----------------------------------------------------------------------------
# TPS does not depend on the orientation of the image
# -----------------------------------------------------------------------------

test_that("get_pts_coords tps gives the same result on a rotated image", {
  skip_if_not_installed("fields")

  # rotate pixel coordinates by 30 degrees, as if the map was scanned at an
  # angle
  rotate_px <- function(df, angle = pi / 6) {
    new_x <- df$x * cos(angle) - df$y * sin(angle)
    new_y <- df$x * sin(angle) + df$y * cos(angle)
    df$x <- new_x
    df$y <- new_y
    df
  }

  result <- get_pts_coords(
    gcp = wide_gcp,
    target_pts = wide_target,
    transform_method = "tps"
  )
  result_rot <- get_pts_coords(
    gcp = rotate_px(wide_gcp),
    target_pts = rotate_px(wide_target),
    transform_method = "tps"
  )

  expect_equal(result_rot$longitude, result$longitude, tolerance = 1e-8)
  expect_equal(result_rot$latitude, result$latitude, tolerance = 1e-8)
})

# -----------------------------------------------------------------------------
# cx/cy support
# -----------------------------------------------------------------------------

test_that("get_pts_coords accepts cx/cy columns", {
  gcp <- pixel_gcp
  target_pts <- target_pixel_df[, c("id", "x", "y")]
  names(target_pts) <- c("id", "cx", "cy")

  result <- get_pts_coords(
    gcp = gcp,
    target_pts = target_pts,
    transform_method = "poly_1"
  )

  expect_true(all(c("longitude", "latitude") %in% names(result)))
  expect_equal(nrow(result), nrow(target_pts))
})

# -----------------------------------------------------------------------------
# Invalid transform method
# -----------------------------------------------------------------------------

test_that("get_pts_coords throws error for invalid transform method", {
  expect_error(
    get_pts_coords(
      gcp = basic_gcp,
      target_pts = basic_target,
      transform_method = "banana"
    ),
    "Invalid 'transform_method'"
  )
})

# -----------------------------------------------------------------------------
# Missing GCP columns
# -----------------------------------------------------------------------------

test_that("get_pts_coords throws error for missing GCP columns", {
  bad_gcp <- basic_gcp[, c("id", "x", "y", "longitude")]

  expect_error(
    get_pts_coords(
      gcp = bad_gcp,
      target_pts = basic_target
    ),
    "Missing required columns in 'gcp'"
  )
})

# -----------------------------------------------------------------------------
# Invalid target columns
# -----------------------------------------------------------------------------

test_that("get_pts_coords throws error for invalid target point columns", {
  bad_target <- data.frame(
    id = 1,
    px = 50,
    py = 50
  )

  expect_error(
    get_pts_coords(
      gcp = basic_gcp,
      target_pts = bad_target
    ),
    "target_pts must contain either columns"
  )
})

# -----------------------------------------------------------------------------
# poly_1 minimum GCP count
# -----------------------------------------------------------------------------

test_that("get_pts_coords validates minimum GCP count for poly_1", {
  small_gcp <- basic_gcp[1:2, ]

  expect_error(
    get_pts_coords(
      gcp = small_gcp,
      target_pts = basic_target,
      transform_method = "poly_1"
    ),
    "At least 3 GCPs are required"
  )
})

# -----------------------------------------------------------------------------
# poly_2 minimum GCP count
# -----------------------------------------------------------------------------

test_that("get_pts_coords validates minimum GCP count for poly_2", {
  gcp <- data.frame(
    id = 1:5,
    x = runif(5),
    y = runif(5),
    longitude = runif(5),
    latitude = runif(5)
  )

  expect_error(
    get_pts_coords(
      gcp = gcp,
      target_pts = basic_target,
      transform_method = "poly_2"
    ),
    "At least 6 GCPs are required"
  )
})

# -----------------------------------------------------------------------------
# poly_3 minimum GCP count
# -----------------------------------------------------------------------------

test_that("get_pts_coords validates minimum GCP count for poly_3", {
  gcp <- data.frame(
    id = 1:9,
    x = runif(9),
    y = runif(9),
    longitude = runif(9),
    latitude = runif(9)
  )

  expect_error(
    get_pts_coords(
      gcp = gcp,
      target_pts = basic_target,
      transform_method = "poly_3"
    ),
    "At least 10 GCPs are required"
  )
})


# -----------------------------------------------------------------------------
# Lambda validation
# -----------------------------------------------------------------------------

test_that("get_pts_coords validates lambda", {
  expect_error(
    get_pts_coords(
      gcp = basic_gcp,
      target_pts = basic_target,
      transform_method = "tps",
      lambda = "a"
    ),
    "'lambda' must be a single numeric value"
  )

  expect_error(
    get_pts_coords(
      gcp = basic_gcp,
      target_pts = basic_target,
      transform_method = "tps",
      lambda = -1
    ),
    "'lambda' must be >= 0"
  )
})

# -----------------------------------------------------------------------------
# Missing values in GCPs
# -----------------------------------------------------------------------------

test_that("get_pts_coords errors if GCPs contain NA values", {
  gcp_na <- pixel_gcp
  gcp_na$longitude[1] <- NA
  for (method in c("auto", "poly_1", "poly_2", "tps")) {
    expect_error(
      get_pts_coords(
        gcp = gcp_na,
        target_pts = basic_target,
        transform_method = method
      ),
      "'gcp' contains NA values"
    )
  }
  gcp_na <- pixel_gcp
  gcp_na$x[2] <- NA
  expect_error(
    get_pts_coords(gcp = gcp_na, target_pts = basic_target),
    "'gcp' contains NA values"
  )
})

# -----------------------------------------------------------------------------
# Collinear GCPs
# -----------------------------------------------------------------------------

test_that("get_pts_coords errors if GCPs are collinear", {
  gcp_line <- data.frame(
    id = 1:4,
    x = c(0, 50, 100, 150),
    y = c(0, 50, 100, 150),
    longitude = c(-3.0, -2.95, -2.9, -2.85),
    latitude = c(55.0, 55.05, 55.1, 55.15)
  )
  basic_target_2 <- data.frame(
    id = 1,
    x = 150,
    y = 0
  )
  # within diagonal
  expect_error(
    get_pts_coords(
      gcp = gcp_line,
      target_pts = basic_target,
      transform_method = "poly_1"
    ),
    "not sufficiently spread to fit a polynomial of order 1"
  )
  # outside diagonal
  expect_error(
    get_pts_coords(
      gcp = gcp_line,
      target_pts = basic_target_2,
      transform_method = "poly_1"
    ),
    "not sufficiently spread to fit a polynomial of order 1"
  )
})

Try the crstools package in your browser

Any scripts or data that you put into this service are public.

crstools documentation built on Nov. 28, 2026, 1:08 a.m.