# Module 4.1: Competition
# Simulation of competition between whitetip and blacktip sharks

# 1. Time and parameters

delta_t <- 0.01
end_time <- 5
time <- seq(0, end_time, by = delta_t)

whitetip_birth_fraction <- 1
blacktip_birth_fraction <- 1
whitetip_competition_constant <- 0.27
blacktip_competition_constant <- 0.20

# 2. Stock variables and initial conditions

whitetips <- numeric(length(time))
blacktips <- numeric(length(time))

whitetips[1] <- 20
blacktips[1] <- 15

# 3. Simulation

for (i in 2:length(time)) {
  whitetips_old <- whitetips[i - 1]
  blacktips_old <- blacktips[i - 1]

  whitetip_births <- whitetip_birth_fraction * whitetips_old
  blacktip_births <- blacktip_birth_fraction * blacktips_old

  whitetip_competition_deaths <- whitetip_competition_constant *
    whitetips_old * blacktips_old
  blacktip_competition_deaths <- blacktip_competition_constant *
    blacktips_old * whitetips_old

  whitetips[i] <- whitetips_old +
    (whitetip_births - whitetip_competition_deaths) * delta_t
  blacktips[i] <- blacktips_old +
    (blacktip_births - blacktip_competition_deaths) * delta_t
}

# 4. Organize and verify results

shark_results <- data.frame(
  time,
  whitetips,
  blacktips
)

head(shark_results)

# 5. Graph both populations

plot(
  time,
  whitetips,
  type = "l",
  lwd = 3,
  col = "purple",
  ylim = c(0, max(whitetips, blacktips)),
  xlab = "Time (months)",
  ylab = "Shark population",
  main = "Competition between two shark species"
)
lines(time, blacktips, lwd = 3, lty = 2, col = "blue")
legend(
  "topright",
  legend = c("Whitetip sharks", "Blacktip sharks"),
  col = c("purple", "blue"),
  lty = c(1, 2),
  lwd = c(3, 3),
  bty = "n"
)

# 6. When do whitetips fall below one shark?

below_one <- which(shark_results$whitetips < 1)[1]
shark_results[c(below_one - 1, below_one), ]

# 7. Inspect the end of the simulation

tail(shark_results)

# 8. Calculate the nonzero equilibrium

equilibrium_blacktips <- whitetip_birth_fraction /
  whitetip_competition_constant
equilibrium_whitetips <- blacktip_birth_fraction /
  blacktip_competition_constant

equilibrium_whitetips
equilibrium_blacktips
