---
title: "FW 536 — Day 4 afternoon lab (Bayesian I · Nimble) — 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)
```

# Day 4 afternoon lab — Bayesian modeling problem set 1

> **Topic scope.** These are the *afternoon* problems and use **Bayesian methods** (priors, posteriors, conjugacy, MCMC). Every fitted model is written in **Nimble** (`nimbleCode` + `nimbleMCMC`), not JAGS. The morning problems (maximum likelihood only) live in `morning_lab_template.Rmd`.

This template matches Problems 5–10 of [`problem_set.html`](problem_set.html). Write your work below, **Knit** to HTML, and upload the `.html` to the matching Canvas assignment.

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

---

# Setup

```{r}
# Packages for the afternoon (Bayesian / Nimble) session.
library(nimble)      # nimbleCode() + nimbleMCMC()
library(MCMCvis)     # MCMCsummary(), MCMCchains(), MCMCtrace()
library(coda)        # mcmc.list class; needed by MCMCvis
library(HDInterval)  # hdi() for highest-posterior-density intervals

# Problem 7 loads the real course dataset from the data/ folder:
#   data/Logistic.csv  (Bayesian logistic r/K growth, with derived MSY)
# The Nimble scaffold for that problem is Logistic_BayesianGrowth_Nimble.R.
```

---

# Problem 5 — Bayesian survival with an informative prior

> 50 animals marked, 38 re-encountered alive. Prior Beta(11, 9) on annual survival $\phi$. Fit $y \sim \text{Binomial}(50, \phi)$ in Nimble with 3 chains; report posterior mean/median/BCI/HPDI and $\Pr(\phi > 0.7 \mid \text{data})$; verify against the closed-form Beta(49, 21) posterior.

**My work:**

```{r}
# Your Nimble code here (nimbleCode + nimbleMCMC, samplesAsCodaMCMC = TRUE)
```

**Answer / biological interpretation:**


---

# Problem 6 — Bayesian detection rate for a species of concern

> 25 point counts, `y = c(0,1,0,2,0,1,0,0,3,1,0,0,1,2,0,1,0,1,0,0,2,0,1,1,0)`, Poisson($\lambda$) with a Gamma(1, 1) prior. Fit in Nimble; report the posterior mean and 95% BCI; compute $\Pr(\lambda < 1 \mid y)$; verify against the closed-form Gamma$(1 + \sum y, 1 + n)$ posterior.

**My work:**

```{r}
# Your Nimble code here
```

**Answer / biological interpretation:**


---

# Problem 7 — Bayesian logistic (r/K) growth with derived quantities (Logistic.csv)

> Refit the per-capita logistic model from morning Problem 4 in Nimble with priors $K \sim U(0, 4000)$, $r \sim U(0, 2)$, $\sigma \sim U(0, 2)$. Report posteriors for $r$, $K$, $\sigma$; add derived quantities MSY $= rK/4$ and $N_{\max} = K/2$; compute $\Pr(r > 0.22 \mid y)$ and compare the BCI vs HPDI for $\sigma$. Scaffold: `Logistic_BayesianGrowth_Nimble.R`.

```{r}
# Load exactly as in the lab:
# Logistic <- read.csv("data/Logistic.csv", header = TRUE)
# Logistic <- Logistic[order(Logistic$PopulationSize), ]
```

**My work:**

```{r}
# Your Nimble code here
```

**Answer / biological interpretation:**


---

# Problem 8 — Prior sensitivity in a data-poor problem

> 3 detections in 20 surveys. Compare posteriors under Beta(1,1), Beta(1,9), Beta(20,30), Beta(100,100). Which is closest to the MLE $\hat p = 0.15$? Which prior most plausibly produced a reported posterior mean of 0.49, and what would you raise as a reviewer? (Closed-form Beta–Binomial; no MCMC needed.)

**My work:**

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

**Answer / biological interpretation:**


---

# Problem 9 — BCI vs HPDI for a skewed posterior

> Posterior Gamma(40, 13). Compute mean, mode, median, 95% BCI, 95% HPDI (`HDInterval::hdi()`); plot the density with both intervals; explain when BCI and HPDI separate.

**My work:**

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

**Answer / biological interpretation:**


---

# Problem 10 — Identifiability and label switching in a Bayesian mixture

> Refit the whale-blow mixture (morning Problem 3) in Nimble. (a) Explain geometrically why $\hat R$ explodes even though each chain has converged. (b) Reproduce the pathology: run the unconstrained model with chain 2 started from the mirrored labeling, and record $\hat R$ for `lam[1]`. (c) Add the ordering constraint $\lambda_1 < \lambda_2$, rerun, and confirm the fix. (d) Discuss the bias of post hoc relabeling and when it is justified. **Both runs are required — report $\hat R$ for $\lambda_1$ before and after the constraint.**

**My work:**

```{r}
# (b) Unconstrained "before" run — Rhat for lam[1] should be enormous

```

```{r}
# (c) Constrained "after" run (lam1 < lam2 by construction) — Rhat should drop to ~1

```

**Answer / biological interpretation:**


---

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

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

---

# Submission checklist

- [ ] Answered every afternoon problem (5–10) from `problem_set.html`.
- [ ] Used **Bayesian methods only**; all fitted models written in **Nimble** (`nimbleCode` + `nimbleMCMC`).
- [ ] Checked convergence ($\hat R \approx 1$, adequate effective sample size) before interpreting.
- [ ] Loaded `Logistic.csv` from the `data/` folder for Problem 7.
- [ ] Knitted to HTML without errors.
- [ ] Photos (if any) embedded with `self_contained: true` in the YAML.
- [ ] Uploaded the `.html` to the matching Canvas assignment.
