---
title: "FW 536 — Day 5 morning problem set (Hierarchical & Latent-State Bayesian Models) — Your Name"
author: "Your Name Here"
date: "`r Sys.Date()`"
output:
  html_document:
    self_contained: true
    toc: true
    toc_depth: 3
    toc_float: true
    code_folding: show
    theme: cosmo
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
library(nimble)
library(MCMCvis)
library(coda)
library(ggplot2)
# Optional but handy for a few problems:
# library(HDInterval)  # hdi() for highest-density intervals
# library(dplyr)       # site-level summaries for Problem 4
# library(MASS)        # rnegbin() for the overdispersed sim in Problem 9
```

# Day 5 morning problem set — Hierarchical & latent-state Bayesian inference

This template matches [`problem_set.html`](problem_set.html). Read each problem
statement there, write your work below, **Knit** to HTML, and upload the `.html`
to the matching Canvas assignment. All models are fit in **NIMBLE**; set
`samplesAsCodaMCMC = TRUE` so `coda` diagnostics work.

For setup help see the [R Markdown tutorial](../rmarkdown_tutorial.html).

---

# Loading the data

Six problems use the real datasets in this Day's `data/` folder. Load them once
here (or inside each problem's chunk — your choice). Keep your `.Rmd` in the
`Day5_BayesII/` folder so these relative paths resolve.

```{r load-data}
ants <- read.csv("data/ants.csv")            # Problems 1–2
N2O  <- read.csv("data/N2OEmission.csv")     # Problems 3–4
liz  <- read.csv("data/IslandsLizards.csv")  # Problems 5–6
# Problems 7–10 simulate their own data (see each problem statement).
```

---

# Problem 1 — Overdispersed ant richness with a bog-level random effect

> Load `ants.csv`, scale the three predictors, and fit a Poisson regression of
> richness on forest, latitude, and elevation with a bog-level (observation-level)
> random effect on the log mean. Report the coefficient and $\sigma_\epsilon$
> posteriors, judge whether overdispersion is present, and compare to `glm()`.

**My work:**

```{r p1}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 2 — What does a "vague" log-scale prior actually do?

> Refit the `ants.csv` Poisson regression (a) raw predictors + N(0, 10000) prior,
> (b) scaled predictors + same prior, (c) scaled + N(0, 4) prior. Compare mixing,
> R-hat, and posteriors, and use a prior-predictive draw to justify a weakly
> informative default.

**My work:**

```{r p2}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 3 — The pooling spectrum for soil N₂O emissions

> Model log(emission) ~ centred log(n.input) with sites indexed by `group.index`.
> Fit complete-pooling, no-pooling, and partial-pooling versions; make the
> shrinkage plot; interpret $\beta$ and $\sigma_\alpha$.

**My work:**

```{r p3}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 4 — Modeling the random intercept with a site-level covariate

> Extend Problem 3 so $\alpha_j \sim \mathcal{N}(\kappa + \eta\,w_j,\ \sigma_\alpha^2)$
> with a site-level covariate $w_j$ built from the data, and let the N-input slope
> vary by fertilizer type (`fert.index`). Is $\eta$ credibly nonzero? Which
> fertilizer has the steepest slope?

**My work:**

```{r p4}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 5 — Island lizard occupancy vs. perimeter:area ratio

> Fit logistic regression of presence on scaled perimeter:area ratio with the
> weakly informative prior dnorm(0, 1/2.71). Report diagnostics, the posterior
> probability that the slope is negative, and compare to a vague-prior refit.

**My work:**

```{r p5}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 6 — A management-relevant probability difference

> Add derived nodes y10, y20, and diff = y20 − y10 (scaled versions of PA = 10 and
> PA = 20) inside your Problem 5 model. Report the posterior of diff and explain
> why computing it inside `nimbleCode` gives correct uncertainty.

**My work:**

```{r p6}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 7 — Beverton-Holt fit with management quantities

> Simulate 25 years of spawner-recruit data, fit Beverton-Holt in NIMBLE, and
> define Neq, Smsy, Hmsy as deterministic nodes. Report posteriors, check CI
> coverage of truth, and contrast the derived-node Smsy with plug-in Smsy.

**My work:**

```{r p7}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 8 — The 5th-percentile ("precautionary") harvest rate

> Using the Problem 7 posterior of Hmsy, report its 5th percentile and interpret
> it. Refit with Nyears = 100 and check the CI-width shrinkage against a √N rule.
> Contrast with how a frequentist fit would produce this number.

**My work:**

```{r p8}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 9 — Repeat-count abundance and a goodness-of-fit check

> Simulate overdispersed repeat counts, fit the basic Royle N-mixture in NIMBLE
> (remember `dbinom(prob, size)` and `N = apply(y, 1, max)`), add posterior
> predictive replicates, and compute a Bayesian p-value. Propose a fix.

**My work:**

```{r p9}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 10 — Multi-season occupancy: recover persistence and colonization

> Simulate a dynamic occupancy dataset with rising colonization, fit it in NIMBLE
> using the z-init trick, plot posterior-median gamma against year, and explain
> why the persistence posteriors are wide.

**My work:**

```{r p10}
# Your R code here
```

**Answer / biological interpretation:**


---

# (Optional) Embed a photo of hand-written work

For any derivation easier to do on paper, photograph and embed it:

```{r embed-photo, echo=FALSE, eval=FALSE, out.width="60%", fig.cap="Hand-derivation for Problem N"}
knitr::include_graphics("images/problemN_derivation.jpg")
```

(Change `eval=FALSE` to `eval=TRUE` after saving an image. With
`self_contained: true` the image is embedded in the knitted HTML. See the
[R Markdown tutorial](../rmarkdown_tutorial.html) for details.)

---

# Submission checklist

- [ ] Loaded `ants.csv`, `N2OEmission.csv`, and `IslandsLizards.csv` from `data/`.
- [ ] Answered every problem (1–10) from `problem_set.html`.
- [ ] Reported at least one convergence diagnostic (R-hat / effective size) per fitted model.
- [ ] Used `samplesAsCodaMCMC = TRUE` in every `nimbleMCMC()` call.
- [ ] Knitted to HTML without errors.
- [ ] Photos (if any) embedded with `self_contained: true` in the YAML.
- [ ] Uploaded the `.html` to the matching Canvas assignment.
