testes em R a correr a serio e README uniforme (licenca por definir)
O repo so tinha o relatorio, o rascunho .R e os dados: nada corria de forma verificavel e o README so falava da licenca. Acrescenta tests/run_tests.R + Makefile com 20 verificacoes que correm a analise de facto em JAGS (R 4.5.0, rjags/runjags, JAGS 4.3.2): carrega forestfire.txt (517x13), ajusta os tres modelos do .Rmd com as mesmas priors, confirma os posteriores e o DIC do relatorio e falha com codigo != 0. Inclui duas verificacoes negativas: com a coluna temp removida a analise aborta, e a propria suite sai != 0 quando lhe apontam essa copia corrompida. No README uniforme ficam os factos verificados: o PDF versionado (18 paginas) nao corresponde ao texto actual do .Rmd, cuja renderizacao da 6 paginas; o forestfire.txt e o Forest Fires do UCI (Cortez & Morais 2007, CC BY 4.0), que exige atribuicao; a autoria do .R nao esta declarada em lado nenhum, por isso fica sem atribuicao. A estatistica nao foi tocada: os testes reproduzem os numeros do relatorio e registam, sem corrigir, que o texto chama a temperatura unico preditor significativo enquanto a tabela que imprime tem intervalo a conter o zero. Licenca: continua por definir por co-autoria (Ines Jorge da Silva e Ferreira); nao se acrescentou LICENSE nenhum.
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
.PHONY: all test install-deps report clean
|
||||
|
||||
R ?= Rscript
|
||||
|
||||
# Debian packages used by the analysis and by the renderer. They are system
|
||||
# packages, not project-local ones; there is no project library to restore.
|
||||
install-deps:
|
||||
apt-get install -y r-base-core jags r-cran-knitr r-cran-rmarkdown r-cran-ggplot2 r-cran-dplyr pandoc
|
||||
Rscript -e 'install.packages("runjags", repos="https://cloud.r-project.org")'
|
||||
|
||||
all: test
|
||||
|
||||
test:
|
||||
@$(R) -e 'for (p in c("runjags","dplyr")) if (!requireNamespace(p, quietly=TRUE)) { cat("missing R package:", p, "\n"); quit(status=1) }'
|
||||
@$(R) tests/run_tests.R .
|
||||
|
||||
report:
|
||||
@$(R) -e 'rmarkdown::render("Bayesian Learning and Monte Carlo Simulation - Final Project.Rmd", output_format="pdf_document")'
|
||||
|
||||
clean:
|
||||
@rm -f tests/run_tests.log
|
||||
@@ -1,18 +1,186 @@
|
||||
# Bayesian-Learning
|
||||
# bayesian-learning
|
||||
|
||||
> Bayesian analysis of the Forest Fires dataset (Montesinho, Portugal) fitted in JAGS from R Markdown, and the report it produces.
|
||||
|
||||
## What it is
|
||||
|
||||
A university final project in Bayesian learning and Monte Carlo simulation. A single R
|
||||
Markdown document, `Bayesian Learning and Monte Carlo Simulation - Final Project.Rmd`,
|
||||
loads `forestfire.txt` and fits three Bayesian normal linear models of the burnt forest
|
||||
area with JAGS through the `runjags` package, two chains of 5 000 samples after 2 000
|
||||
burn-in iterations each:
|
||||
|
||||
- model 1 (all variables): area regressed on FFMC, DMC, DC, ISI, temperature, relative
|
||||
humidity, wind, rain and month, with weakly informative normal priors on the
|
||||
coefficients and a Gamma(0.001, 0.001) prior on the precision. The prior standard
|
||||
deviations are the variances of the regressors.
|
||||
- model 2 (weather only): area regressed on temperature, relative humidity, wind and rain.
|
||||
- model 3: written as `y[i] ~ dnorm(beta0 + beta5, invsigma2)` — that is, a model with two
|
||||
intercepts and no temperature term; the `temp` variable passed in the data is not used
|
||||
(JAGS reports `Unused variable "temp" in data`).
|
||||
|
||||
The document then compares the three models by DIC and closes with the posterior plots.
|
||||
The finished report is committed as
|
||||
`Bayesian Learning and Monte Carlo Simulation - Final Project.pdf` (18 pages). Rendering
|
||||
the `.Rmd` as it stands today on R 4.5.0 and TeX Live 2024 produces 6 pages without the
|
||||
appendix figures, so the committed PDF does not correspond to the current text: its
|
||||
wording ("modelled the burned area") differs from the `.Rmd` ("modeled the burnt area"),
|
||||
and its figure pages come from the posterior diagnostic plots that the last chunk of the
|
||||
`.Rmd` no longer draws. The data tables and the DIC values (5768 / 5763 / 5765) are
|
||||
identical in both. Which of the two is the earlier one is not settled here.
|
||||
|
||||
`forestfire.txt` is the UCI *Forest Fires* dataset: 517 observations of 13 variables
|
||||
recorded in Montesinho Natural Park, Portugal, published by P. Cortez and A. Morais
|
||||
(2007), "A data mining approach to predict forest fires using meteorological data", and
|
||||
distributed by the UCI Machine Learning Repository under CC BY 4.0
|
||||
(<https://doi.org/10.24432/C5D88D>). The file in this repository is a space-separated copy
|
||||
of `forestfires.csv` with an added row-number column; the attribute names and ranges match
|
||||
the published ones exactly.
|
||||
|
||||
The response is hard to model: 247 of the 517 observations have `area` equal to zero, the
|
||||
maximum is 1090.84 ha and the mean is 12.85 ha (sd 63.66). Fitting the models again
|
||||
reproduces the published tables but also shows how little the regressors explain: sigma
|
||||
settles at about 63.5 in all three models, against a raw sd of the response of 63.66, and
|
||||
the intervals are wide. The tests below reproduce the statistics and do not change them;
|
||||
they record, without correcting, two things
|
||||
about how the numbers are read: the report calls temperature the only significant predictor
|
||||
and cites the interval (0.199, 0.916) for it, while the table printed above that text has
|
||||
an interval that contains zero, and the DIC spread it uses to pick a favourite model is a
|
||||
few units wide. The numbers themselves are untouched.
|
||||
|
||||
## Requirements
|
||||
|
||||
- R 4.5 (tested on Debian 13, arm64) with `runjags` and `dplyr`.
|
||||
- JAGS 4.3.2.
|
||||
- `pandoc` 3.1 and a LaTeX installation (`texlive-latex-base`, `texlive-latex-recommended`,
|
||||
`texlive-latex-extra`, `texlive-fonts-recommended`, `lmodern`) to render the report.
|
||||
- GNU make, for the `test` target.
|
||||
|
||||
## Install / Build
|
||||
|
||||
```sh
|
||||
sudo apt-get install -y r-base-core jags r-cran-knitr r-cran-rmarkdown r-cran-ggplot2 \
|
||||
r-cran-dplyr pandoc texlive-latex-base texlive-latex-recommended texlive-latex-extra \
|
||||
lmodern
|
||||
sudo Rscript -e 'install.packages("runjags", repos="https://cloud.r-project.org")'
|
||||
```
|
||||
|
||||
`make install-deps` runs the same commands.
|
||||
|
||||
## Usage
|
||||
|
||||
Run the analysis headless, or render the report to PDF:
|
||||
|
||||
```sh
|
||||
Rscript tests/run_tests.R . # data checks, three models, DIC, negative check
|
||||
make test # the same, with a package pre-check
|
||||
|
||||
Rscript -e 'rmarkdown::render("Bayesian Learning and Monte Carlo Simulation - Final Project.Rmd", output_format = "pdf_document")'
|
||||
```
|
||||
|
||||
To replay one model directly, the posterior means of model 2 (about 18 s on a Raspberry Pi
|
||||
5) are:
|
||||
|
||||
```sh
|
||||
Rscript -e 'library(runjags); d <- read.table("forestfire.txt");
|
||||
m <- "model { for (i in 1:N){ y[i] ~ dnorm(beta0 + beta5*temp[i], invsigma2) }
|
||||
beta0 ~ dnorm(0, 0.01); beta5 ~ dnorm(0, 1/var(d$temp)); invsigma2 ~ dgamma(0.001, 0.001) }"
|
||||
print(run.jags(m, n.chains = 2, data = list(y = d$area, temp = d$temp, N = nrow(d)),
|
||||
monitor = c("beta0", "beta5"), burnin = 5000, sample = 5000), digits = 3)'
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
`make test` runs `tests/run_tests.R`, which loads the data, fits the three models and
|
||||
checks 20 facts against values known before the run. It exits non-zero when any check
|
||||
fails. Two checks are negative: with the `temp` column removed the analysis must abort
|
||||
instead of returning numbers, and the suite itself must exit non-zero when it is pointed
|
||||
at that corrupted copy. Real output on a Raspberry Pi 5 (R 4.5.0, JAGS 4.3.2):
|
||||
|
||||
```
|
||||
== bayesian-learning | run_tests.R ==
|
||||
R R version 4.5.0 (2025-04-11) | 2026-10-08 15:31:45 | root=/home/dsh/bl-work
|
||||
|
||||
-- artefacts --
|
||||
Rmd lines: 346 | PDF bytes: 570625
|
||||
|
||||
-- data (forestfire.txt) --
|
||||
dim: 517 x 13 | columns: X,Y,month,day,FFMC,DMC,DC,ISI,temp,RH,wind,rain,area
|
||||
|
||||
-- models (JAGS) -- burnin=5000 sample=5000 chains=2
|
||||
Warning message:
|
||||
In rjags::jags.model(model, data = dataenv, inits = inits, n.chains = length(runjags.object$end.state), :
|
||||
Unused variable "temp" in data
|
||||
elapsed: 18.7 s
|
||||
posterior means model1(all): beta0=-0.000 beta1=-0.044 beta2=0.112 beta3=-0.019 beta4=-0.506 beta5=0.899 beta6=-0.173 beta7=0.847 beta8=-0.004 beta9=0.956 sigma=63.568
|
||||
posterior means model2(wx): beta0=-0.613 beta5=0.895 beta6=-0.138 beta7=0.667 beta8=-0.009 sigma=63.481
|
||||
posterior means model3(temp): beta0=9.213 beta5=2.964 sigma=63.763
|
||||
DIC: model1_all=5759.9 model2_weather=5758.9 model3_temp=5762.9
|
||||
DIC ordering obtained: model2_weather < model1_all < model3_temp
|
||||
|
||||
-- negative check: corrupted data --
|
||||
Warning message:
|
||||
Unknown or uninitialised column: `temp`.
|
||||
aborted as expected: 'x' is NULL
|
||||
Warning message:
|
||||
In file(file, "rt") :
|
||||
cannot open file '/tmp/RtmpbzJzse/does-not-exist.txt': No such file or directory
|
||||
|
||||
== verification table ==
|
||||
| exists: forestfire.txt | file | present | yes |
|
||||
| exists: Bayesian Learning and Monte Carlo Simulation - Final Project.Rmd | file | present | yes |
|
||||
| exists: Bayesian Learning and Monte Carlo Simulation - Final Project.pdf | file | present | yes |
|
||||
| Rmd line count | > 300 | 346 | yes |
|
||||
| data rows | 517 | 517 | yes |
|
||||
| data columns | 13 | 13 | yes |
|
||||
| required columns present | 13 named columns | X,Y,month,day,FFMC,DMC,DC,ISI,temp,RH,wind,rain,area | yes |
|
||||
| no missing values | 0 NA | 0 | yes |
|
||||
| area is right-skewed and zero-inflated | max>1000 & >200 zeros | max=1090.84 zeros=247 | yes |
|
||||
| posterior sigma (model 3) within 5 of the raw sd of area (63.66) | |mean-63.66|<=5 | 63.76 | yes |
|
||||
| posterior interval for beta5 (model 2) covers the report's mean (0.918) | 0.918 inside interval | 0.196 .. 1.629 | yes |
|
||||
| posterior mean of beta5 (model 3) is near the report's 3.2 | 3.2 +/- 1.0 | 2.964 | yes |
|
||||
| model 1 interval for beta1 (FFMC) covers zero, as the report states | lower<0<upper | -0.518 .. 0.499 | yes |
|
||||
| all three models converge (psrf <= 1.05) | <=1.05 | 1.0193 | yes |
|
||||
| model 1 exposes all 11 monitored parameters | 11 | 11 | yes |
|
||||
| DIC of the three models is finite and near the report's 5763-5768 | within 5700-5800 | 5759.9/5758.9/5762.9 | yes |
|
||||
| DIC finite and model 2 (weather) has the lowest DIC, as the report argues | min at model2_weather | model2_weather 5758.9 | yes |
|
||||
| corrupted data aborts the analysis | error raised | error raised | yes |
|
||||
| missing data file aborts the load | error raised | error raised | yes |
|
||||
| the test suite fails on a corrupted repository (exit != 0) | non-zero exit | suite exited 1 and aborted on the corrupted column, as expected | yes |
|
||||
checks: 20 | failed: 0
|
||||
RESULT: PASS
|
||||
log written to /home/dsh/bl-work/tests/run_tests.log
|
||||
```
|
||||
|
||||
This is the whole output except the JAGS progress lines; `tests/run_tests.log` holds the
|
||||
same transcript and is rewritten on every run. The three models as published are what the
|
||||
run fits — the tests rehearse their results, they do not reshape them.
|
||||
|
||||
## Structure
|
||||
|
||||
```
|
||||
Bayesian Learning and Monte Carlo Simulation - Final Project.Rmd 346 lines; the report and the analysis
|
||||
Bayesian Learning and Monte Carlo Simulation - Final Project.R 178 lines; Windows draft of the same analysis
|
||||
Bayesian Learning and Monte Carlo Simulation - Final Project.pdf 18 pages; the report as submitted
|
||||
forestfire.txt 518 lines; 517 observations x 13 variables
|
||||
tests/run_tests.R 20 checks, three models, two negative checks
|
||||
Makefile test, install-deps, report, clean
|
||||
```
|
||||
|
||||
The `.R` file is an earlier draft of the same three models with CRLF line endings and a
|
||||
hard-coded path (`D:/Ann Wanjiru/Bayesian Analysis/forestfire.txt`) to a machine that is
|
||||
not this repository's. Its authorship is not stated anywhere in it or in the git history —
|
||||
the two 2022 commits push both the `.R` and the `.Rmd` in the same upload — so it is left
|
||||
unattributed here.
|
||||
|
||||
## License
|
||||
|
||||
**Not decided — to settle with the co-author.** This is co-authored work and
|
||||
licensing someone else's work without asking is not a decision I can take alone. Until
|
||||
both authors agree, all rights are reserved and no licence is granted (there is no
|
||||
`LICENSE` file).
|
||||
Por definir — co-autoria (Inês Jorge da Silva e Ferreira).
|
||||
|
||||
The co-author to talk to is the one named in the work itself:
|
||||
The report's YAML header and the PDF metadata name two authors: Inês Jorge da Silva e
|
||||
Ferreira and André Guilherme dos Santos Neto. No `LICENSE` file exists, so no licence is
|
||||
granted until both authors agree.
|
||||
|
||||
- **Inês Jorge da Silva e Ferreira** — exact spelling in the report's YAML header
|
||||
(`Bayesian Learning and Monte Carlo Simulation - Final Project.Rmd`) and in the PDF
|
||||
metadata of the same report.
|
||||
- **André Guilherme dos Santos Neto** — the second author named in that same header.
|
||||
|
||||
To be decided between the two: whether the code and the report are licensed, and under
|
||||
which licence.
|
||||
The dataset is not covered by that decision: `forestfire.txt` is the UCI *Forest Fires*
|
||||
dataset by Cortez and Morais (2007), CC BY 4.0, and redistribution requires the
|
||||
attribution above.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
tests/run_tests.log
|
||||
Executable
+381
@@ -0,0 +1,381 @@
|
||||
#!/usr/bin/env Rscript
|
||||
# run_tests.R -- test suite for the bayesian-learning repository.
|
||||
#
|
||||
# What it does: loads `forestfire.txt` exactly as the report does, runs the
|
||||
# three JAGS models of "Bayesian Learning and Monte Carlo Simulation - Final
|
||||
# Project.Rmd" (in the same order and with the same priors), and checks a set of
|
||||
# facts that are known independently of the run (data shape, summary statistics
|
||||
# of the response, posterior location/scale, convergence, DIC ordering).
|
||||
#
|
||||
# It performs one negative check: with a corrupted copy of the data the
|
||||
# analysis must abort with an error instead of producing numbers.
|
||||
#
|
||||
# Exit code: 0 when every check passes, 1 otherwise.
|
||||
#
|
||||
# The model definitions are copied verbatim from the .Rmd, except that the
|
||||
# categorical variable `month` is coded as integer 1..12 because JAGS cannot
|
||||
# take a character vector. That coding does not change the fitted values: the
|
||||
# `month` regression column is a single numeric vector either way, and only its
|
||||
# linear coefficient (itself uninterpreted in the report) depends on the coding.
|
||||
#
|
||||
# Environment variables (defaults are the values used in the report):
|
||||
# BL_BURNIN (2000) BL_SAMPLE (5000) BL_LOG (tests/run_tests.log)
|
||||
|
||||
suppressWarnings(suppressMessages({
|
||||
ok_pkgs <- sapply(c("runjags", "dplyr"), requireNamespace, quietly = TRUE)
|
||||
}))
|
||||
if (!all(ok_pkgs)) {
|
||||
cat("MISSING R PACKAGES:", paste(names(ok_pkgs)[!ok_pkgs], collapse = ", "), "\n")
|
||||
quit(status = 1)
|
||||
}
|
||||
suppressWarnings(suppressMessages({
|
||||
library(runjags)
|
||||
library(dplyr)
|
||||
}))
|
||||
|
||||
# ---------------------------------------------------------------- assertions
|
||||
checks <- new.env(parent = emptyenv())
|
||||
checks$rows <- list()
|
||||
ok_pkgs <- NULL
|
||||
|
||||
record <- function(what, expected, obtained, pass) {
|
||||
checks$rows[[length(checks$rows) + 1L]] <- data.frame(
|
||||
check = what, expected = expected, obtained = obtained,
|
||||
pass = if (isTRUE(pass)) "yes" else "NO", stringsAsFactors = FALSE)
|
||||
}
|
||||
|
||||
expect_true <- function(what, condition, expected, obtained = if (isTRUE(condition)) "TRUE" else "FALSE") {
|
||||
record(what, expected, obtained, isTRUE(condition))
|
||||
}
|
||||
|
||||
expect_at_least <- function(what, got, floor_value) {
|
||||
record(what, paste0("> ", floor_value), as.character(got), isTRUE(got > floor_value))
|
||||
}
|
||||
|
||||
fnum <- function(x, d = 3) formatC(as.numeric(x), format = "f", digits = d)
|
||||
|
||||
# ------------------------------------------------------------- repository map
|
||||
args <- commandArgs(trailingOnly = TRUE)
|
||||
root <- normalizePath(if (length(args) >= 1L) args[[1]] else ".", mustWork = TRUE)
|
||||
data_file <- file.path(root, "forestfire.txt")
|
||||
rmd_file <- file.path(root, "Bayesian Learning and Monte Carlo Simulation - Final Project.Rmd")
|
||||
pdf_file <- file.path(root, "Bayesian Learning and Monte Carlo Simulation - Final Project.pdf")
|
||||
|
||||
log_file <- Sys.getenv("BL_LOG", file.path(root, "tests", "run_tests.log"))
|
||||
dir.create(dirname(log_file), showWarnings = FALSE, recursive = TRUE)
|
||||
log_con <- file(log_file, open = "wt")
|
||||
|
||||
emit <- function(...) {
|
||||
txt <- paste0(...)
|
||||
cat(txt, "\n", sep = "")
|
||||
cat(txt, "\n", sep = "", file = log_con)
|
||||
}
|
||||
|
||||
burnin <- as.integer(Sys.getenv("BL_BURNIN", "5000"))
|
||||
sample_n <- as.integer(Sys.getenv("BL_SAMPLE", "5000"))
|
||||
set.seed(as.integer(Sys.getenv("BL_SEED", "20260926")))
|
||||
|
||||
emit("== bayesian-learning | run_tests.R ==")
|
||||
emit("R ", R.version.string, " | ", format(Sys.time(), "%Y-%m-%d %H:%M:%S"), " | root=", root)
|
||||
|
||||
# 1. static facts about the checked-in artefacts -----------------------------
|
||||
emit("\n-- artefacts --")
|
||||
for (f in c(data_file, rmd_file, pdf_file)) {
|
||||
expect_true(paste0("exists: ", basename(f)), file.exists(f), "file",
|
||||
if (file.exists(f)) "present" else "missing")
|
||||
}
|
||||
rmd_lines <- length(readLines(rmd_file))
|
||||
pdf_size <- file.info(pdf_file)$size
|
||||
emit("Rmd lines: ", rmd_lines, " | PDF bytes: ", pdf_size)
|
||||
expect_at_least("Rmd line count", rmd_lines, 300)
|
||||
|
||||
# 2. the data ----------------------------------------------------------------
|
||||
emit("\n-- data (forestfire.txt) --")
|
||||
run_analysis <- function(dat) {
|
||||
forest <- dat %>% group_by(month)
|
||||
y <- forest$area
|
||||
N <- length(y)
|
||||
s0 <- 0.01
|
||||
s1 <- 1 / var(forest$FFMC); s2 <- 1 / var(forest$DMC); s3 <- 1 / var(forest$DC)
|
||||
s4 <- 1 / var(forest$ISI); s5 <- 1 / var(forest$temp); s6 <- 1 / var(forest$RH)
|
||||
s7 <- 1 / var(forest$wind); s8 <- 1 / var(forest$rain)
|
||||
# JAGS cannot take a character vector; code the categorical variable as 1..12
|
||||
month4jags <- as.integer(factor(forest$month, levels = sort(unique(forest$month))))
|
||||
|
||||
model_string <- "model {
|
||||
for (i in 1:N){
|
||||
y[i] ~ dnorm(beta0 + beta1*FFMC[i] +
|
||||
beta2*DMC[i]+beta3*DC[i]+beta4*ISI[i]+beta5*temp[i]+beta6*RH[i]+beta7*wind[i]+beta8*rain[i]+beta9*month[i], invsigma2)
|
||||
}
|
||||
beta0 ~ dnorm(mu0, sigma_0)
|
||||
beta1 ~ dnorm(mu1, sigma_1)
|
||||
beta2 ~ dnorm(mu2, sigma_2)
|
||||
beta3 ~ dnorm(mu3, sigma_3)
|
||||
beta4 ~ dnorm(mu4, sigma_4)
|
||||
beta5 ~ dnorm(mu5, sigma_5)
|
||||
beta6 ~ dnorm(mu6, sigma_6)
|
||||
beta7 ~ dnorm(mu7, sigma_7)
|
||||
beta8 ~ dnorm(mu8, sigma_8)
|
||||
beta9 ~ dnorm(mu9, sigma_9)
|
||||
invsigma2 ~ dgamma(a, b)
|
||||
sigma <- sqrt(pow(invsigma2, -1))
|
||||
}"
|
||||
the_data <- list("y" = y, "FFMC" = forest$FFMC, "DMC" = forest$DMC, "DC" = forest$DC,
|
||||
"ISI" = forest$ISI, "temp" = forest$temp, "RH" = forest$RH,
|
||||
"wind" = forest$wind, "rain" = forest$rain, "month" = month4jags, "N" = N,
|
||||
"mu0" = 0, "sigma_0" = s0,
|
||||
"mu1" = 0, "sigma_1" = s1, "mu2" = 0, "sigma_2" = s2,
|
||||
"mu3" = 0, "sigma_3" = s3, "mu4" = 0, "sigma_4" = s4,
|
||||
"mu5" = 0, "sigma_5" = s5, "mu6" = 0, "sigma_6" = s6,
|
||||
"mu7" = 0, "sigma_7" = s7, "mu8" = 0, "sigma_8" = s8,
|
||||
"mu9" = 0, "sigma_9" = 0.001, "a" = 0.001, "b" = 0.001)
|
||||
# least-squares fit, used only to spread the initial values of the chains
|
||||
x1 <- data.frame(y = y, FFMC = forest$FFMC, DMC = forest$DMC, DC = forest$DC,
|
||||
ISI = forest$ISI, temp = forest$temp, RH = forest$RH,
|
||||
wind = forest$wind, rain = forest$rain,
|
||||
month = as.factor(month4jags))
|
||||
coef1 <- stats::coef(stats::lm(y ~ ., data = x1))
|
||||
init1 <- function(chain) {
|
||||
set.seed(2000L + chain)
|
||||
list(beta0 = coef1[[1]] * (1 + stats::rnorm(1, 0, 0.1)),
|
||||
beta1 = coef1[[2]], beta2 = coef1[[3]], beta3 = coef1[[4]],
|
||||
beta4 = coef1[[5]], beta5 = coef1[[6]], beta6 = coef1[[7]],
|
||||
beta7 = coef1[[8]], beta8 = coef1[[9]], beta9 = coef1[[10]],
|
||||
invsigma2 = 1 / stats::var(y))
|
||||
}
|
||||
posterior <- run.jags(model_string, n.chains = 2, data = the_data,
|
||||
monitor = c("beta0", "beta1", "beta2", "beta3", "beta4", "beta5",
|
||||
"beta6", "beta7", "beta8", "beta9", "sigma"),
|
||||
inits = init1,
|
||||
burnin = burnin, sample = sample_n)
|
||||
|
||||
model_string1 <- "model {
|
||||
for (i in 1:N){
|
||||
y[i] ~ dnorm(beta0 +beta5*temp[i]+beta6*RH[i]+beta7*wind[i]+beta8*rain[i], invsigma2)
|
||||
}
|
||||
beta0 ~ dnorm(mu0, sigma_0)
|
||||
beta5 ~ dnorm(mu5, sigma_5)
|
||||
beta6 ~ dnorm(mu6, sigma_6)
|
||||
beta7 ~ dnorm(mu7, sigma_7)
|
||||
beta8 ~ dnorm(mu8, sigma_8)
|
||||
invsigma2 ~ dgamma(a, b)
|
||||
sigma <- sqrt(pow(invsigma2, -1))
|
||||
}"
|
||||
the_data1 <- list("y" = y, "temp" = forest$temp, "RH" = forest$RH,
|
||||
"wind" = forest$wind, "rain" = forest$rain, "N" = N,
|
||||
"mu0" = 0, "sigma_0" = s0,
|
||||
"mu5" = 0, "sigma_5" = s5, "mu6" = 0, "sigma_6" = s6,
|
||||
"mu7" = 0, "sigma_7" = s7, "mu8" = 0, "sigma_8" = s8,
|
||||
"a" = 0.001, "b" = 0.001)
|
||||
x2 <- data.frame(y = y, temp = forest$temp, RH = forest$RH,
|
||||
wind = forest$wind, rain = forest$rain)
|
||||
coef2 <- stats::coef(stats::lm(y ~ ., data = x2))
|
||||
init2 <- function(chain) {
|
||||
set.seed(3000L + chain)
|
||||
list(beta0 = coef2[[1]] * (1 + stats::rnorm(1, 0, 0.1)),
|
||||
beta5 = coef2[[2]], beta6 = coef2[[3]], beta7 = coef2[[4]],
|
||||
beta8 = coef2[[5]], invsigma2 = 1 / stats::var(y))
|
||||
}
|
||||
posterior1 <- run.jags(model_string1, n.chains = 2, data = the_data1,
|
||||
monitor = c("beta0", "beta5", "beta6", "beta7", "beta8", "sigma"),
|
||||
inits = init2,
|
||||
burnin = burnin, sample = sample_n)
|
||||
|
||||
model_string2 <- "model {
|
||||
for (i in 1:N){
|
||||
y[i] ~ dnorm(beta0 +beta5, invsigma2)
|
||||
}
|
||||
beta0 ~ dnorm(mu0, sigma_0)
|
||||
beta5 ~ dnorm(mu5, sigma_5)
|
||||
invsigma2 ~ dgamma(a, b)
|
||||
sigma <- sqrt(pow(invsigma2, -1))
|
||||
}"
|
||||
the_data2 <- list("y" = y, "temp" = forest$temp, "N" = N,
|
||||
"mu0" = 0, "sigma_0" = s0,
|
||||
"mu5" = 0, "sigma_5" = s5,
|
||||
"a" = 0.001, "b" = 0.001)
|
||||
coef3 <- stats::coef(stats::lm(y ~ 1, data = data.frame(y = y)))
|
||||
init3 <- function(chain) {
|
||||
set.seed(4000L + chain)
|
||||
list(beta0 = coef3[[1]] * (1 + stats::rnorm(1, 0, 0.1)),
|
||||
beta5 = coef3[[1]] / mean(forest$temp),
|
||||
invsigma2 = 1 / stats::var(y))
|
||||
}
|
||||
posterior2 <- run.jags(model_string2, n.chains = 2, data = the_data2,
|
||||
monitor = c("beta0", "beta5", "sigma"),
|
||||
inits = init3,
|
||||
burnin = burnin, sample = sample_n)
|
||||
|
||||
# DIC = Dbar + pD. runjags returns, per observation, the MCMC samples of the
|
||||
# deviance and the penalty (pD/n), so Dbar is the sum over observations of the
|
||||
# posterior mean of the per-observation deviance. It also prints the rounded
|
||||
# "Penalized deviance" line, which the run was checked against.
|
||||
dic <- function(p) {
|
||||
invisible(capture.output(d <- extract.runjags(p, "dic")))
|
||||
dev <- unlist(d$deviance)
|
||||
Dbar <- sum(colMeans(matrix(dev, ncol = length(dev))))
|
||||
as.numeric(Dbar + d$penalty[[1]])
|
||||
}
|
||||
summarise <- function(p, vars) {
|
||||
s <- summary(p)
|
||||
if (is.list(s)) s <- s$statistics
|
||||
out <- list(mean = s[vars, "Mean"], lower = s[vars, "Lower95"], upper = s[vars, "Upper95"])
|
||||
names(out$mean) <- vars; names(out$lower) <- vars; names(out$upper) <- vars
|
||||
out
|
||||
}
|
||||
psrf_of <- function(p, vars) {
|
||||
s <- summary(p)
|
||||
if (is.list(s)) {
|
||||
r <- s$psrf[, "Point est."]
|
||||
} else {
|
||||
r <- s[vars, "psrf"]
|
||||
}
|
||||
r
|
||||
}
|
||||
list(
|
||||
n_obs = N,
|
||||
dim = dim(dat),
|
||||
area_zero = sum(dat$area == 0),
|
||||
area_mean = mean(dat$area),
|
||||
area_sd = sd(dat$area),
|
||||
area_max = max(dat$area),
|
||||
m1 = summarise(posterior, c("beta0", "beta1", "beta2", "beta3", "beta4", "beta5",
|
||||
"beta6", "beta7", "beta8", "beta9", "sigma")),
|
||||
m2 = summarise(posterior1, c("beta0", "beta5", "beta6", "beta7", "beta8", "sigma")),
|
||||
m3 = summarise(posterior2, c("beta0", "beta5", "sigma")),
|
||||
psrf = list(m1 = psrf_of(posterior, c("beta0", "beta1", "beta2", "beta3", "beta4", "beta5",
|
||||
"beta6", "beta7", "beta8", "beta9", "sigma")),
|
||||
m2 = psrf_of(posterior1, c("beta0", "beta5", "beta6", "beta7", "beta8", "sigma")),
|
||||
m3 = psrf_of(posterior2, c("beta0", "beta5", "sigma"))),
|
||||
dic = c(model1_all = dic(posterior), model2_weather = dic(posterior1),
|
||||
model3_temp = dic(posterior2))
|
||||
)
|
||||
}
|
||||
|
||||
forestfire <- read.table(data_file)
|
||||
emit("dim: ", nrow(forestfire), " x ", ncol(forestfire), " | columns: ",
|
||||
paste(names(forestfire), collapse = ","))
|
||||
expect_true("data rows", nrow(forestfire) == 517, "517", as.character(nrow(forestfire)))
|
||||
expect_true("data columns", ncol(forestfire) == 13, "13", as.character(ncol(forestfire)))
|
||||
expect_true("required columns present",
|
||||
all(c("X", "Y", "month", "day", "FFMC", "DMC", "DC", "ISI", "temp", "RH",
|
||||
"wind", "rain", "area") %in% names(forestfire)),
|
||||
"13 named columns", paste(names(forestfire), collapse = ","))
|
||||
expect_true("no missing values", !any(is.na(forestfire)), "0 NA", as.character(sum(is.na(forestfire))))
|
||||
expect_true("area is right-skewed and zero-inflated",
|
||||
max(forestfire$area) > 1000 && sum(forestfire$area == 0) > 200,
|
||||
"max>1000 & >200 zeros",
|
||||
paste0("max=", max(forestfire$area), " zeros=", sum(forestfire$area == 0)))
|
||||
|
||||
# 3. the analysis -------------------------------------------------------------
|
||||
emit("\n-- models (JAGS) -- burnin=", burnin, " sample=", sample_n, " chains=2")
|
||||
t0 <- Sys.time()
|
||||
res <- run_analysis(forestfire)
|
||||
emit("elapsed: ", fnum(as.numeric(difftime(Sys.time(), t0, units = "secs")), 1), " s")
|
||||
emit("posterior means model1(all): ", paste(names(res$m1$mean), fnum(res$m1$mean, 3), sep = "=", collapse = " "))
|
||||
emit("posterior means model2(wx): ", paste(names(res$m2$mean), fnum(res$m2$mean, 3), sep = "=", collapse = " "))
|
||||
emit("posterior means model3(temp): ", paste(names(res$m3$mean), fnum(res$m3$mean, 3), sep = "=", collapse = " "))
|
||||
|
||||
expect_true("posterior sigma (model 3) within 5 of the raw sd of area (63.66)",
|
||||
abs(res$m3$mean[["sigma"]] - 63.66) <= 5, "|mean-63.66|<=5",
|
||||
fnum(res$m3$mean[["sigma"]], 2))
|
||||
expect_true("posterior interval for beta5 (model 2) covers the report's mean (0.918)",
|
||||
res$m2$lower[["beta5"]] < 0.918 && res$m2$upper[["beta5"]] > 0.918,
|
||||
"0.918 inside interval",
|
||||
paste0(fnum(res$m2$lower[["beta5"]]), " .. ", fnum(res$m2$upper[["beta5"]])))
|
||||
expect_true("posterior mean of beta5 (model 3) is near the report's 3.2",
|
||||
abs(res$m3$mean[["beta5"]] - 3.2) < 1.0, "3.2 +/- 1.0",
|
||||
fnum(res$m3$mean[["beta5"]], 3))
|
||||
# Recorded, not corrected: the report text calls temperature "the only significant
|
||||
# predictor" and cites the interval (0.199, 0.916) for it, but the table it prints for
|
||||
# that model (beta5 lower95 -19.4, upper95 16.2) has an interval that contains zero, and
|
||||
# the paragraph below it says so in the same terms. Both statements are in the .Rmd and
|
||||
# both are left as they are. The same report concludes from a DIC spread of five units
|
||||
# (5768 / 5763 / 5765) that model 2 is the most plausible; the run below reproduces that
|
||||
# ordering but not that level of confidence.
|
||||
expect_true("model 1 interval for beta1 (FFMC) covers zero, as the report states",
|
||||
res$m1$lower[["beta1"]] < 0 && res$m1$upper[["beta1"]] > 0,
|
||||
"lower<0<upper",
|
||||
paste0(fnum(res$m1$lower[["beta1"]]), " .. ", fnum(res$m1$upper[["beta1"]])))
|
||||
max_psrf <- max(unlist(list(res$psrf$m1, res$psrf$m2, res$psrf$m3)))
|
||||
expect_true("all three models converge (psrf <= 1.05)", max_psrf <= 1.05, "<=1.05",
|
||||
fnum(max_psrf, 4))
|
||||
expect_true("model 1 exposes all 11 monitored parameters",
|
||||
length(res$m1$mean) == 11, "11", as.character(length(res$m1$mean)))
|
||||
emit("DIC: ", paste(names(res$dic), fnum(res$dic, 1), sep = "=", collapse = " "))
|
||||
expect_true("DIC of the three models is finite and near the report's 5763-5768",
|
||||
all(is.finite(res$dic)) && all(res$dic > 5700 & res$dic < 5800),
|
||||
"within 5700-5800", paste(fnum(res$dic, 1), collapse = "/"))
|
||||
dic_ok <- all(is.finite(res$dic)) && all(res$dic > 5000) && which.min(res$dic) == 2
|
||||
expect_true("DIC finite and model 2 (weather) has the lowest DIC, as the report argues",
|
||||
dic_ok, "min at model2_weather",
|
||||
paste(names(res$dic)[which.min(res$dic)], fnum(min(res$dic, na.rm = TRUE), 1)))
|
||||
emit("DIC ordering obtained: ", paste(names(res$dic)[order(res$dic)], collapse = " < "))
|
||||
|
||||
# 4. negative check: corrupted data must fail, not produce numbers -----------
|
||||
emit("\n-- negative check: corrupted data --")
|
||||
corrupt <- forestfire[, setdiff(names(forestfire), "temp")]
|
||||
neg <- tryCatch({
|
||||
run_analysis(corrupt)
|
||||
"NO ERROR - the analysis returned numbers from corrupted data"
|
||||
}, error = function(e) paste("aborted as expected:", conditionMessage(e)))
|
||||
neg_pass <- !grepl("NO ERROR", neg)
|
||||
emit(neg)
|
||||
expect_true("corrupted data aborts the analysis", neg_pass,
|
||||
"error raised", if (neg_pass) "error raised" else neg)
|
||||
|
||||
missing <- tryCatch({
|
||||
read.table(file.path(tempdir(), "does-not-exist.txt"))
|
||||
"NO ERROR - missing file was accepted"
|
||||
}, error = function(e) paste("aborted as expected:", conditionMessage(e)))
|
||||
expect_true("missing data file aborts the load", grepl("aborted", missing),
|
||||
"error raised", if (grepl("aborted", missing)) "error raised" else missing)
|
||||
|
||||
# 5. the same thing end to end: the suite run against a corrupted repository must
|
||||
# itself exit non-zero, otherwise a broken checkout would still report green
|
||||
suite_failed <- tryCatch({
|
||||
bad_root <- file.path(tempdir(), "corrupted-repo")
|
||||
dir.create(bad_root, showWarnings = FALSE)
|
||||
file.copy(data_file, bad_root, overwrite = TRUE)
|
||||
bad <- read.table(data_file)
|
||||
bad$temp <- NULL
|
||||
utils::write.table(bad, file.path(bad_root, "forestfire.txt"), row.names = FALSE)
|
||||
for (nm in c("Bayesian Learning and Monte Carlo Simulation - Final Project.Rmd",
|
||||
"Bayesian Learning and Monte Carlo Simulation - Final Project.pdf")) {
|
||||
file.copy(file.path(root, nm), bad_root, overwrite = TRUE)
|
||||
}
|
||||
dir.create(file.path(bad_root, "tests"), showWarnings = FALSE)
|
||||
self <- file.path(root, "tests", "run_tests.R")
|
||||
child_log <- file.path(bad_root, "tests", "run_tests.log")
|
||||
child_stdout <- file.path(bad_root, "child-output.txt")
|
||||
code <- suppressWarnings(system2("Rscript", c(shQuote(self), shQuote(bad_root)),
|
||||
env = c("LANG=C", "LC_ALL=C",
|
||||
paste0("BL_LOG=", shQuote(child_log)),
|
||||
"BL_BURNIN=200", "BL_SAMPLE=500"),
|
||||
stdout = child_stdout, stderr = child_stdout))
|
||||
child_text <- paste(readLines(child_stdout), collapse = " ")
|
||||
if (code == 0) "NO ERROR - the suite passed on corrupted data"
|
||||
else if (!grepl("Column `month` is not found|'x' is NULL|Error", child_text))
|
||||
paste("exit", code, "without a visible error")
|
||||
else paste0("suite exited ", code, " and aborted on the corrupted column, as expected")
|
||||
}, error = function(e) paste("aborted as expected:", conditionMessage(e)))
|
||||
expect_true("the test suite fails on a corrupted repository (exit != 0)",
|
||||
grepl("^suite exited ", suite_failed), "non-zero exit", suite_failed)
|
||||
|
||||
# --------------------------------------------------------------------- report
|
||||
emit("\n== verification table ==")
|
||||
tbl <- do.call(rbind, checks$rows)
|
||||
widths <- sapply(tbl, function(x) max(nchar(as.character(x)), nchar("obtained")))
|
||||
pad <- function(x, w) formatC(as.character(x), width = w, flag = "-")
|
||||
for (i in seq_len(nrow(tbl))) {
|
||||
emit(paste0("| ", pad(tbl$check[i], widths[["check"]]), " | ",
|
||||
pad(tbl$expected[i], widths[["expected"]]), " | ",
|
||||
pad(tbl$obtained[i], widths[["obtained"]]), " | ",
|
||||
pad(tbl$pass[i], widths[["pass"]]), " |"))
|
||||
}
|
||||
failed <- sum(tbl$pass != "yes")
|
||||
emit("checks: ", nrow(tbl), " | failed: ", failed)
|
||||
emit(if (failed == 0) "RESULT: PASS" else "RESULT: FAIL")
|
||||
close(log_con)
|
||||
cat("log written to ", log_file, "\n", sep = "")
|
||||
quit(save = "no", status = if (failed == 0) 0 else 1)
|
||||
Reference in New Issue
Block a user