# Conspecific negative density dependence
# https://tidyecology.com/posts/conspecific-negative-density-dependence/
#
# 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-10-07

## ---- setup ----
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dpi = 120, fig.path = "figures/",
                      fig.width = 7, fig.height = 4.4)
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 12))
theme_set(theme_te)
col_con <- "#b5651d"; col_het <- "#3a6b52"; col_ref <- "#555555"

set.seed(416)
n <- 2000
con <- rpois(n, 4); het <- rpois(n, 8)
b_con <- -0.45; b_het <- -0.08
surv <- rbinom(n, 1, plogis(1.2 + b_con*con + b_het*het))
fit <- glm(surv ~ con + het, family = binomial)
cf <- coef(fit)

r0 <- 0.4; K <- 100
sim2 <- function(a, N0 = c(90, 10), T = 200) { N <- N0; for (t in 1:T) { r <- r0*(1 - (N + a*rev(N))/K); N <- pmax(N + N*r, 0) }; round(N) }

## ---- glm ----
set.seed(416); n <- 2000
con <- rpois(n, 4); het <- rpois(n, 8)                       # conspecific and heterospecific neighbours
surv <- rbinom(n, 1, plogis(1.2 - 0.45*con - 0.08*het))      # survival: hurt more by own kind
fit <- glm(surv ~ con + het, family = binomial)
round(coef(fit), 3)

## ---- fig-survival ----
grid <- data.frame(d = 0:15)
pc <- rbind(data.frame(d = grid$d, p = plogis(cf[1] + cf["con"]*grid$d + cf["het"]*8), nb = "conspecific"),
            data.frame(d = grid$d, p = plogis(cf[1] + cf["con"]*4 + cf["het"]*grid$d), nb = "heterospecific"))
ggplot(pc, aes(d, p, colour = nb)) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("conspecific" = col_con, "heterospecific" = col_het)) +
  labs(x = "Number of neighbours", y = "Survival probability", colour = NULL,
       title = "Own-species neighbours are far more dangerous")

## ---- coexist ----
r0 <- 0.4; K <- 100
sim2 <- function(a, N0 = c(90, 10), T = 200) {
  N <- N0; for (t in 1:T) { r <- r0*(1 - (N + a*rev(N))/K); N <- pmax(N + N*r, 0) }; round(N)
}
rbind(strong_cndd_a0.6 = sim2(0.6), weak_a1.4 = sim2(1.4))

## ---- fig-coexist ----
traj <- function(a) { N <- c(90, 10); out <- data.frame(t = 0, sp1 = 90, sp2 = 10)
  for (t in 1:120) { r <- r0*(1 - (N + a*rev(N))/K); N <- pmax(N + N*r, 0); out <- rbind(out, data.frame(t = t, sp1 = N[1], sp2 = N[2])) }; out }
dd <- rbind(cbind(traj(0.6), case = "strong CNDD: coexist"), cbind(traj(1.4), case = "weak CNDD: exclude"))
dl <- reshape(dd, varying = c("sp1", "sp2"), v.names = "N", timevar = "species", direction = "long")
ggplot(dl, aes(t, N, colour = factor(species))) +
  geom_line(linewidth = 0.9) + facet_wrap(~case) +
  scale_colour_manual(values = c("1" = col_con, "2" = col_het), labels = c("species 1", "species 2")) +
  labs(x = "Time", y = "Abundance", colour = NULL, title = "Strong self-limitation is what lets both persist") +
  theme(strip.text = element_text(size = 9))
