# Log-ratio transformations: clr, alr and ilr
# https://tidyecology.com/posts/log-ratio-transformations-clr-ilr/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-11-14

## ---- setup ----
library(ggplot2)
clr <- function(x) { lx <- log(x); lx - mean(lx) }          # centred log-ratio
alr <- function(x, ref = length(x)) log(x[-ref] / x[ref])   # additive log-ratio
C   <- function(x) x / sum(x)                                # closure
ilr_basis <- function(D) {                                  # orthonormal contrast matrix
  V <- matrix(0, D, D - 1)
  for (i in seq_len(D - 1)) {
    a <- sqrt(1 / (i * (i + 1))); b <- sqrt(i / (i + 1))
    V[1:i, i] <- a; V[i + 1, i] <- -b
  }
  V
}
te_ink <- "#16241d"; te_forest <- "#275139"; te_faint <- "#5d6b61"
te_paper <- "#f5f4ee"; te_line <- "#dad9ca"; te_red <- "#b5534e"
theme_te <- function(base = 12) theme_minimal(base_size = base) + theme(
  plot.background = element_rect(fill = te_paper, colour = NA),
  panel.background = element_rect(fill = te_paper, colour = NA),
  panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
  panel.grid.minor = element_blank(),
  axis.text = element_text(colour = "#2c3a31"), axis.title = element_text(colour = te_ink),
  plot.title = element_text(colour = te_ink, face = "bold"),
  plot.subtitle = element_text(colour = te_faint, size = rel(0.9)), legend.position = "top")
theme_set(theme_te())

set.seed(3390)
D <- 5L; n <- 300L
mu <- c(2.8, 2.4, 2.0, 1.6, 2.2); sdlog <- c(0.5, 0.6, 0.55, 0.7, 0.5)
X <- sapply(1:D, function(j) rlnorm(n, mu[j], sdlog[j]))
P <- X / rowSums(X)
V <- ilr_basis(D)

## ---- clr ----
CLR <- t(apply(P, 1, clr))
max(abs(rowSums(CLR)))       # rows sum to zero

## ---- clr-singular ----
ev <- eigen(cov(CLR), only.values = TRUE)$values
c(smallest_eigenvalue = min(abs(ev)), rank = qr(cov(CLR))$rank, parts = D)

## ---- fig-simplex ----
set.seed(11)
A3 <- sapply(1:3, function(j) rlnorm(9, c(2.2, 2.0, 1.6)[j], 0.5)); T3 <- A3 / rowSums(A3)
tern <- function(m) data.frame(tx = m[,2] + 0.5 * m[,3], ty = (sqrt(3)/2) * m[,3])
pts <- tern(T3)
vert <- data.frame(tx = c(0, 1, 0.5), ty = c(0, 0, sqrt(3)/2), lab = c("part A", "part B", "part C"))
edge <- data.frame(x = c(0, 1, 0.5), y = c(0, 0, sqrt(3)/2),
                   xend = c(1, 0.5, 0), yend = c(0, sqrt(3)/2, 0))
xstar <- C(T3[1,]); yv <- C(c(1.8, 1.0, 1.0)); xp <- C(xstar * yv)
pth <- tern(rbind(xstar, xp))
p_simplex <- ggplot() +
  geom_segment(data = edge, aes(x, y, xend = xend, yend = yend), colour = te_line, linewidth = 0.6) +
  geom_point(data = pts, aes(tx, ty), colour = te_forest, size = 2.2, alpha = 0.8) +
  geom_segment(data = data.frame(x = pth$tx[1], y = pth$ty[1], xend = pth$tx[2], yend = pth$ty[2]),
               aes(x, y, xend = xend, yend = yend), colour = te_red, linewidth = 0.9,
               arrow = arrow(length = unit(0.18, "cm"), type = "closed")) +
  geom_text(data = vert, aes(tx, ty, label = lab), vjust = c(1.6, 1.6, -0.8), colour = te_ink, size = 3.4) +
  coord_equal() + theme_void() +
  theme(plot.background = element_rect(fill = te_paper, colour = NA),
        plot.title = element_text(colour = te_ink, face = "bold"),
        plot.subtitle = element_text(colour = te_faint, size = rel(0.9))) +
  labs(title = "The simplex: sample space of compositions",
       subtitle = "Points are three-part compositions; the arrow is a perturbation")
p_simplex

## ---- thumb ----
thumb_title <- paste(strwrap("The simplex: sample space of compositions", 46), collapse = "\n")
ggsave("thumbnail.png",
       p_simplex + labs(title = thumb_title) +
         scale_y_continuous(expand = expansion(mult = 0.12)) +
         theme(plot.title = element_text(size = 13, face = "bold"),
               plot.subtitle = element_text(size = 9.5),
               plot.margin = margin(8, 14, 8, 8)),
       width = 7.5, height = 5.4, dpi = 100, bg = te_paper)

## ---- geometry ----
y <- P[3, ]; a <- 2.3; xa <- P[1, ]
c(perturbation = max(abs(clr(C(xa * y)) - (clr(xa) + clr(y)))),
  powering     = max(abs(clr(C(xa^a)) - a * clr(xa))))

## ---- distance ----
xa <- P[1, ]; xb <- P[2, ]
d_clr <- sqrt(sum((clr(xa) - clr(xb))^2))                 # Euclidean on clr
d_ilr <- sqrt(sum(((clr(xa) - clr(xb)) %*% V)^2))         # Euclidean on ilr
Lr <- function(x) outer(1:D, 1:D, function(i, j) log(x[i] / x[j]))
d_lr <- sqrt(sum((Lr(xa) - Lr(xb))^2) / (2 * D))          # pairwise log-ratio form
round(c(clr = d_clr, ilr = d_ilr, pairwise = d_lr), 5)

## ---- fig-distance ----
CLRfull <- t(apply(P, 1, clr))
Draw <- as.matrix(dist(P)); Dait <- as.matrix(dist(CLRfull)); ut <- upper.tri(Draw)
rho <- cor(Draw[ut], Dait[ut], method = "spearman")
set.seed(9); s <- sample(which(ut), 3000)
ggplot(data.frame(euc = Draw[s], ait = Dait[s]), aes(euc, ait)) +
  geom_point(colour = te_forest, alpha = 0.25, size = 0.9) +
  labs(title = "Naive Euclidean distance is not Aitchison distance",
       subtitle = sprintf("Spearman rank agreement %.2f over all pairs", rho),
       x = "Euclidean distance on raw proportions", y = "Aitchison distance (Euclidean on clr)")

## ---- alr ----
d_alr <- sqrt(sum((alr(xa, 5) - alr(xb, 5))^2))
round(c(alr_euclidean = d_alr, aitchison = d_clr), 5)

## ---- ilr ----
c(orthonormal = max(abs(crossprod(V) - diag(D - 1))),
  reconstruct = max(abs(CLRfull - (CLRfull %*% V) %*% t(V))))
