# The theta-logistic model in R
# https://tidyecology.com/posts/theta-logistic-model/
#
# 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-08

## ---- setup ----
suppressPackageStartupMessages({library(ggplot2); library(dplyr)})
ink<-"#16241d"; body<-"#2c3a31"; forest<-"#275139"; gold<-"#c9b458"
paper<-"#f5f4ee"; line<-"#dad9ca"; faint<-"#5d6b61"; aban<-"#b5534e"; mown<-"#2f8f63"
theme_te <- function(){
  theme_minimal(base_size=12)+
  theme(plot.background=element_rect(fill=paper,colour=NA),
        panel.background=element_rect(fill=paper,colour=NA),
        panel.grid.minor=element_blank(),
        panel.grid.major=element_line(colour=line,linewidth=.3),
        axis.title=element_text(colour=ink), axis.text=element_text(colour=faint),
        plot.title=element_text(colour=ink,size=12,face="bold"),
        strip.text=element_text(colour=ink,face="bold"),
        legend.position="bottom", legend.title=element_text(colour=ink),
        legend.text=element_text(colour=body))
}

## ---- helpers ----
sim_theta <- function(T,r,K,theta,sigma,N1){ N<-numeric(T); N[1]<-N1
  for(t in 1:(T-1)){ pgr<-r*(1-(N[t]/K)^theta)+rnorm(1,0,sigma)
    N[t+1]<-N[t]*exp(pgr); if(N[t+1]<1) N[t+1]<-1 }
  N }
## process-only negative log-likelihood (sigma profiled out); optional fixed theta
nll <- function(par, pgr, dens, theta_fix=NA){
  r<-exp(par[1]); K<-exp(par[2]); theta<-if(is.na(theta_fix)) exp(par[3]) else theta_fix
  mu<-r*(1-(dens/K)^theta); s2<-mean((pgr-mu)^2); n<-length(pgr)
  0.5*n*(log(2*pi*s2)+1) }
fit_full <- function(N){ pgr<-diff(log(N)); dens<-N[-length(N)]
  op<-optim(c(log(0.3),log(max(N)*1.05),log(1)), nll, pgr=pgr, dens=dens,
            method="BFGS", control=list(maxit=2000))
  s2<-mean((pgr-exp(op$par[1])*(1-(dens/exp(op$par[2]))^exp(op$par[3])))^2)
  list(r=exp(op$par[1]), K=exp(op$par[2]), theta=exp(op$par[3]), sigma=sqrt(s2),
       ll=-op$value, conv=op$convergence) }
fit_theta <- function(N,theta){ pgr<-diff(log(N)); dens<-N[-length(N)]
  op<-optim(c(log(0.3),log(max(N)*1.05)), nll, pgr=pgr, dens=dens, theta_fix=theta,
            method="BFGS", control=list(maxit=2000))
  list(r=exp(op$par[1]), K=exp(op$par[2]), ll=-op$value) }

## ---- simulate ----
r_true<-0.40; K_true<-1000; theta_true<-2.5; sigma_true<-0.10; N1<-250; Tlen<-40
set.seed(12); N <- sim_theta(Tlen, r_true, K_true, theta_true, sigma_true, N1)

## ---- fit ----
ff <- fit_full(N)
c(r=round(ff$r,2), K=round(ff$K,0), theta=round(ff$theta,2), sigma=round(ff$sigma,3))

## ---- altfits ----
fR  <- fit_theta(N, 1)      # Ricker: theta fixed at 1
fHi <- fit_theta(N, 3.3)    # a sharply concave shape
c(ricker_ll=round(fR$ll,2), theta3.3_ll=round(fHi$ll,2), ml_ll=round(ff$ll,2),
  ricker_gap=round(ff$ll-fR$ll,2), theta3.3_gap=round(ff$ll-fHi$ll,2))

## ---- fig-shapes ----
pgr<-diff(log(N)); dens<-N[-length(N)]
gx <- seq(min(dens)*0.9, max(dens)*1.02, length.out=250)
curve_df <- rbind(
  data.frame(N=gx, pgr=fR$r*(1-(gx/fR$K)^1),    model="theta = 1 (Ricker)"),
  data.frame(N=gx, pgr=fHi$r*(1-(gx/fHi$K)^3.3), model="theta = 3.3"))
ggplot()+
  geom_hline(yintercept=0, colour=faint, linewidth=.3)+
  geom_point(data=data.frame(N=dens,pgr=pgr), aes(N, pgr), colour=ink, size=1.9, alpha=.8)+
  geom_line(data=curve_df, aes(N, pgr, colour=model), linewidth=1)+
  scale_colour_manual(values=c("theta = 1 (Ricker)"=forest,"theta = 3.3"=aban))+
  labs(x="density N", y="population growth rate", colour=NULL,
       title="Two very different shapes against the same data")+
  theme_te()

## ---- profile ----
tg <- seq(0.3, 6, length.out=80)
pl <- lapply(tg, function(x) fit_theta(N, x))
llp <- sapply(pl, function(z) z$ll); rp <- sapply(pl, function(z) z$r)
dev <- 2*(max(llp) - llp)
c(theta_lo=round(min(tg[dev<3.84]),1), theta_hi=round(max(tg[dev<3.84]),1),
  r_lo=round(min(rp[dev<3.84]),2), r_hi=round(max(rp[dev<3.84]),2))

## ---- fig-profile ----
d2 <- data.frame(theta=tg, dev=dev)
ggplot(d2, aes(theta, dev))+
  geom_hline(yintercept=3.84, colour=faint, linetype="22", linewidth=.4)+
  geom_line(colour=forest, linewidth=1)+
  geom_vline(xintercept=ff$theta, colour=aban, linewidth=.7)+
  geom_vline(xintercept=theta_true, colour=gold, linewidth=.7, linetype="22")+
  annotate("text", x=ff$theta, y=8, label=" MLE", hjust=0, colour=aban, size=3.3)+
  annotate("text", x=theta_true, y=6, label="truth ", hjust=1, colour="#8a7a1e", size=3.3)+
  annotate("text", x=5.4, y=3.84, label="95%", vjust=-0.5, colour=faint, size=3)+
  coord_cartesian(ylim=c(0,10))+
  labs(x="shape parameter theta (fixed)", y="profile deviance, relative to minimum",
       title="The shape parameter is barely identified")+
  theme_te()
