-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis.R
More file actions
73 lines (62 loc) · 2.38 KB
/
analysis.R
File metadata and controls
73 lines (62 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
library(R2OpenBUGS)
library(coda) # Load the coda package
# Get the data from Python
Y <- data$Y
pvID <- data$pvID
cropID <- data$cropID
blockID <- data$blockID
mainplotID <- data$mainplotID
N <- length(Y)
nPV <- length(unique(pvID))
nCrops <- length(unique(cropID))
nBlocks <- length(unique(blockID))
nMainPlots <- length(unique(mainplotID))
# BUGS model data
bugs_data <- list("N", "Y", "pvID", "cropID", "blockID", "mainplotID",
"nPV", "nCrops", "nBlocks", "nMainPlots")
# BUGS model parameters to monitor
bugs_params <- c("alpha", "beta.pv", "beta.crop", "beta.inter",
"sigma.within", "sigma.block", "sigma.mainplot")
# BUGS model initial values
inits <- function() {
list(
alpha = rnorm(1, 0, 1),
beta.pv = c(NA, rnorm(nPV - 1, 0, 1)),
beta.crop = c(NA, rnorm(nCrops - 1, 0, 1)),
beta.inter = matrix(rnorm(nPV * nCrops, 0, 1), nrow = nPV, ncol = nCrops),
tau.within = rgamma(1, 1, 1),
tau.block = rgamma(1, 1, 1),
tau.mainplot = rgamma(1, 1, 1)
)
}
# Create a directory for CODA output if it doesn't exist
if (!dir.exists("coda_output")) {
dir.create("coda_output")
}
# Run OpenBUGS, requesting CODA-compatible output
# The result 'bugs_coda' will be an mcmc.list object
bugs_coda <- bugs(data = bugs_data,
inits = inits,
parameters.to.save = bugs_params,
model.file = "agrivoltaic_lognormal.txt",
n.chains = 3,
n.iter = 2000,
n.burnin = 1000,
n.thin = 1,
codaPkg = TRUE, # Return an mcmc.list object
debug = TRUE,
OpenBUGS.pgm = "C:\\OpenBUGS323\\OpenBUGS.exe")
# --- CODA Output Analysis ---
# 1. Save the summary statistics and quantiles to text files
summary_stats <- summary(bugs_coda)
write.table(summary_stats$statistics, file = "coda_summary_stats.txt", sep = "\t", col.names = NA)
write.table(summary_stats$quantiles, file = "coda_summary_quantiles.txt", sep = "\t", col.names = NA)
# 2. Save the raw MCMC chains to CODA-formatted text files
# This creates coda_output/chain.INDEX and coda_output/chain1.txt, chain2.txt, etc.
write.coda(bugs_coda, stem = "coda_output/chain")
# 3. Generate and save diagnostic plots to a PDF
pdf("coda_diagnostic_plots.pdf")
plot(bugs_coda)
dev.off()
# 4. Print the summary to the R console
print(summary_stats)