# Fit South America to Africa with a rigid rotation on the sphere
# (shape and area are preserved) and apply the same rotation to a DEM.
# Africa stays fixed; South America is rotated.
# Load packages
library(terra)
library(rnaturalearth)
library(sf)
library(elevatr)
library(ggplot2)
library(tidyterra)
library(ggnewscale)
library(showtext)
library(ggtext)
# 1. Rotation on the sphere (Euler pole + angle, Rodrigues' formula) -----------
to_cart <- function(xy) { # lon/lat (deg) -> unit vectors
lo <- xy[, 1] * pi / 180
la <- xy[, 2] * pi / 180
cbind(cos(la) * cos(lo), cos(la) * sin(lo), sin(la))
}
to_lonlat <- function(P) { # unit vectors -> lon/lat (deg)
cbind(atan2(P[, 2], P[, 1]) * 180 / pi,
asin(pmax(pmin(P[, 3], 1), -1)) * 180 / pi)
}
rot_matrix <- function(pole_lat, pole_lon, angle) {
k <- to_cart(cbind(pole_lon, pole_lat))[1, ]
th <- angle * pi / 180
K <- matrix(c(0, -k[3], k[2],
k[3], 0, -k[1],
-k[2], k[1], 0), 3, byrow = TRUE)
diag(3) + sin(th) * K + (1 - cos(th)) * (K %*% K)
}
rotate_xy <- function(xy, R) to_lonlat(to_cart(xy) %*% t(R))
# inverse rotation: rotate_xy(xy, t(R))
rotate_vect <- function(v, R) { # rotate a terra polygon layer
g <- geom(v)
xy <- rotate_xy(g[, c("x", "y")], R)
g[, "x"] <- xy[, 1]
g[, "y"] <- xy[, 2]
vect(g, type = "polygons", crs = "EPSG:4326")
}
# 2. Outlines ------------------------------------------------------------------
# Better than the coastline: the continental-shelf edge, e.g. the 500 m
# isobath (Bullard et al. 1965), from GEBCO/ETOPO via as.contour().
get_continent <- function(name, d_int = 20000) {
x <- ne_countries(continent = name, returnclass = "sf")
v <- aggregate(vect(x)) # dissolve countries into one multipolygon
parts <- disagg(v) # split into single polygons
parts <- parts[which.max(expanse(parts)), ] # keep the largest (drops islands)
return(densify(parts, interval = d_int)) # Densify so that edges are represented by enough vertices
}
sa <- get_continent("South America")
af <- get_continent("Africa")
# Facing margins only (adjust the boxes to your data): east coast of South
# America and west coast of Africa
sa_pts <- crds(as.lines(sa))
sa_pts <- sa_pts[sa_pts[, 1] > -55 & sa_pts[, 2] > -40, ]
af_pts <- crds(as.lines(af))
af_pts <- af_pts[af_pts[, 1] < 15 & af_pts[, 2] > -35 & af_pts[, 2] < 38, ]
A_cart <- to_cart(af_pts)
# 3. Misfit: symmetric mean nearest distance between both margins (km) ---------
# (small when gaps and overlaps are small)
misfit <- function(par) {
R <- rot_matrix(par[1], par[2], par[3])
B <- to_cart(rotate_xy(sa_pts, R))
S <- B %*% t(A_cart) # cosines between all pairs
d_ab <- sqrt(pmax(2 - 2 * apply(S, 1, max), 0)) # chord lengths (unit sphere)
d_ba <- sqrt(pmax(2 - 2 * apply(S, 2, max), 0))
6371 * (mean(d_ab) + mean(d_ba))
}
# Starting values near the classic Bullard et al. (1965) fit (check the sign!)
start <- c(pole_lat = 44, pole_lon = -31, angle = 57)
fit <- optim(start, misfit, method = "Nelder-Mead",
control = list(maxit = 2000, reltol = 1e-10))
fit$par
fit$value
R <- rot_matrix(fit$par[1], fit$par[2], fit$par[3])
# 4. Check ---------------------------------------------------------------------
sa_rot <- rotate_vect(sa, R)
plot(af, col = "grey80", ext = ext(-80, 60, -45, 45))
plot(sa_rot, col = adjustcolor("red", 0.4), add = TRUE)
# 5. Apply the same rotation to the DEM (inverse mapping, no holes) ------------
# A lon/lat raster cannot be rotated by changing its extent, so every
# cell of the new grid is traced back to the original DEM.
# Load DEMs
dem_sa = sa |>
st_as_sf() |>
get_elev_raster(locations = _, z = 4, clip = "locations") |>
rast()
dem_af = af |>
st_as_sf() |>
get_elev_raster(locations = _, z = 4, clip = "locations") |>
rast()
tgt <- rast(ext(sa_rot), resolution = res(dem_sa), crs = "EPSG:4326")
xy_tgt <- xyFromCell(tgt, 1:ncell(tgt))
xy_src <- rotate_xy(xy_tgt, t(R)) # inverse rotation
vals <- extract(dem_sa, xy_src, method = "bilinear") # "near" for categories
tgt[] <- vals[[ncol(vals)]]
dem_sa_rot <- mask(tgt, sa_rot) # keep only the rotated outline
# extent covering both rasters, with Africa's resolution and CRS
ext_all <- union(ext(dem_af), ext(dem_sa_rot))
template <- rast(ext_all, resolution = res(dem_af), crs = crs(dem_af))
af_t <- resample(dem_af, template, method = "bilinear")
sa_t <- resample(dem_sa_rot, template, method = "bilinear")
pantropia <- merge(af_t, sa_t) # cells where af_t is NA are taken from sa_t
land <- as.polygons(ifel(is.na(pantropia), NA, 1), dissolve = TRUE) |>
fillHoles()
inside <- rasterize(land, pantropia, field = 1, background = 0)
pantropia_f <- ifel(is.na(pantropia) & inside == 1, 5, pantropia)
# Check the result
plot(pantropia_f)
# New rotation for final display -----------------------------------------------
rotate_raster <- function(r, angle = 22) { # angle in degrees, clockwise
th <- angle * pi / 180
e <- ext(r)
cx <- mean(c(e$xmin, e$xmax)); cy <- mean(c(e$ymin, e$ymax))
# new extent: bounding box of the rotated corners
cn <- cbind(c(e$xmin, e$xmax, e$xmax, e$xmin),
c(e$ymin, e$ymin, e$ymax, e$ymax))
dx <- cn[, 1] - cx; dy <- cn[, 2] - cy
xr <- cx + dx * cos(th) + dy * sin(th)
yr <- cy - dx * sin(th) + dy * cos(th)
tmpl <- rast(ext(min(xr), max(xr), min(yr), max(yr)),
resolution = res(r), crs = crs(r))
# for each new cell, find its source position (inverse rotation)
xy <- xyFromCell(tmpl, seq_len(ncell(tmpl)))
dx <- xy[, 1] - cx; dy <- xy[, 2] - cy
src <- cbind(cx + dx * cos(th) - dy * sin(th),
cy + dx * sin(th) + dy * cos(th))
values(tmpl) <- extract(r, src, method = "bilinear")[, 1]
names(tmpl) <- "elev"
tmpl
}
island <- rotate_raster(pantropia_f, angle = 150) |>
trim()
# Check
plot(island)
# Calculating hill shades
exag <- 5
slope <- terrain(island * exag, "slope", unit = "radians")
aspect <- terrain(island * exag, "aspect", unit = "radians")
hill <- shade(slope, aspect, angle = 40, direction = 315)
names(hill) <- "hill"
# coastline polygon from the valid cells
coast <- as.polygons(ifel(is.na(island), NA, 1), dissolve = TRUE)
# The Plot ---------------------------------------------------------------------
# Colors
bg_col <- "#c7dff0"
title_col = "#663303"
text_col <- "#4f4f4f"
coast_col <- "#8ca9be"
# Loading fonts
font_add_google("Limelight", "title_font")
# font_add_google("Inter", "body_font")
showtext_auto()
the_island <- ggplot() +
# hillshade (grey)
geom_spatraster(data = hill, aes(fill = hill), show.legend = FALSE) +
scale_fill_gradientn(colours = grey.colors(100, start = 0.2, end = 1),
na.value = NA, guide = "none") +
new_scale_fill() +
# terrain colours on top, semi-transparent so the shading shows through
geom_spatraster(data = island, aes(fill = elev), alpha = 0.65,
show.legend = FALSE) +
scale_fill_hypso_c(palette = "dem_print", na.value = NA, guide = "none") +
# scale_fill_hypso_c(palette = "wiki-2.0_hypso", na.value = NA, guide = "none") +
# scale_fill_hypso_c(palette = "wiki-schwarzwald-cont", na.value = NA, guide = "none") +
# scale_fill_whitebox_c(palette = "atlas", na.value = NA, guide = "none") +
# contours
geom_spatraster_contour(
data = island,
breaks = seq(0, 6000, by = 500)[-1],
colour = "grey20", linewidth = 0.1, alpha = 0.6
) +
# coastline
geom_spatvector(data = coast, fill = NA, colour = coast_col, linewidth = 0.3) +
coord_sf(expand = FALSE, datum = NA) +
labs(title = "Welcome to Pantropia!") +
theme_void() +
theme(
plot.background = element_rect(fill = bg_col, colour = NA),
plot.margin = margin(20, 30, 20, 30), # top, right, bottom, left (pt)
plot.title = element_text(
family = "title_font",
face = "bold",
colour = title_col,
size = 110,
hjust = 0,
margin = margin(t = 0, b = 10) # t shifts it down, b = gap to the ridges
),
plot.title.position = "plot" # align to the plot edge, not the panel
)
ggsave(
"08-utopia.png", the_island,
width = 7,
height = 8,
dpi = 300,
bg = bg_col)