-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBT_temp.qmd
More file actions
550 lines (472 loc) · 20.9 KB
/
BT_temp.qmd
File metadata and controls
550 lines (472 loc) · 20.9 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
---
format: html
toc: false
---
# Bluetongue Virus: Thermal Performance Curves
**Source:** El Moustaid et al. 2021 Supplement | **Data:** Lysyk & Danyk 2007, Mayo et al. 2020
This analysis recreates key thermal performance curves from the Bluetongue virus transmission study, fitting Bayesian models to estimate Maximum A Posteriori (MAP) parameters for each trait. The solid lines show posterior means/medians with 95% HPD intervals (dashed lines).
```{r setup, include=FALSE}
library(nimble)
library(bayesTPC)
library(dplyr)
library(ggplot2)
library(coda)
library(HDInterval)
library(patchwork)
```
## Adult Mortality Rate (μ)
```{r mu-data, echo=FALSE, message=FALSE, warning=FALSE}
# Load updated dataset from CSV and filter for adult mortality rate (mu)
mu_df <- readr::read_csv("data/Bluetongue_Params_0723.csv", show_col_types = FALSE) %>%
dplyr::filter(Trait == "mu") %>%
dplyr::transmute(T = AmbientTemp, mu = TraitValueSI) %>%
dplyr::arrange(T)
cat("Temp range:", paste(range(mu_df$T), collapse = "–"), "°C\n")
cat("mu range:", paste(round(range(mu_df$mu), 3), collapse = "–"), " per day\n")
```
## Thermal Performance Curve (Quadratic via bayesTPC)
```{r mu-fit, echo=FALSE, message=FALSE, warning=FALSE}
# Load updated dataset from CSV and filter for adult mortality rate (mu)
mu_df <- readr::read_csv("data/Bluetongue_Params_0723.csv", show_col_types = FALSE) %>%
dplyr::filter(Trait == "mu") %>%
dplyr::transmute(T = AmbientTemp, mu = TraitValueSI) %>%
dplyr::arrange(T)
mu_data_list <- list(Temp = mu_df$T, Trait = mu_df$mu)
set.seed(123)
fit_mu <- b_TPC(
data = mu_data_list,
model = "quadratic",
priors = list(
T_min = "dunif(5,15)",
T_max = "dunif(18,40)",
q = "dunif(0, 0.5)",
sigma.sq = "dexp(1 / 0.1^2)"
),
nchains = 4,
burn = 6000,
niter = 18000
)
```
```{r mu-plot, echo=FALSE, message=FALSE, warning=FALSE, fig.width=8, fig.height=5}
# Use ALL chains and established prediction pipeline
samples_mu <- do.call(rbind, lapply(fit_mu$samples, as.matrix))
temp_grid <- seq(0, 50, by = 0.1)
# Evaluate quadratic model using bayesTPC helper to avoid formula drift
quad_fun <- bayesTPC::get_model_function("quadratic")
pred_mu <- sapply(temp_grid, function(Ti) quad_fun(
q = samples_mu[, "q"], T_min = samples_mu[, "T_min"], T_max = samples_mu[, "T_max"], Temp = Ti
))
# Mean curve + 95% HPD across posterior draws
mean_mu <- colMeans(pred_mu)
hpd_mu <- apply(pred_mu, 2, function(x) as.numeric(HDInterval::hdi(x, credMass = 0.95)))
lo_mu <- hpd_mu[1, ]; hi_mu <- hpd_mu[2, ]
Topt_mu <- temp_grid[which.max(mean_mu)]
par(mfrow = c(1,1), mar = c(4,4,2,1))
plot(temp_grid, mean_mu, type = "l", lwd = 2, col = "black",
xlab = "T (°C)", ylab = "Adult Mortality Rate (per day)",
ylim = c(0, max(0.2, max(hi_mu, mu_df$mu, na.rm = TRUE) * 1.05)), xlim = c(0, 50), bty = "l")
lines(temp_grid, lo_mu, lty = 2, lwd = 1.2)
lines(temp_grid, hi_mu, lty = 2, lwd = 1.2)
points(mu_df$T, mu_df$mu, pch = 16, col = "black")
abline(v = Topt_mu, lty = 3)
lbl <- sprintf("Topt ≈ %.1f°C (mean curve)", Topt_mu)
if (length(lbl) == 1 && !is.na(lbl)) mtext(lbl, side = 3, adj = 1, cex = 0.9)
```
```{r mu-param-summary, echo=FALSE, message=FALSE, warning=FALSE}
# MAP Estimates
map_mu <- MAP_estimate(fit_mu)
cat("**MAP Estimates (μ):**\n")
if(!is.null(map_mu)){
if("T_min" %in% names(map_mu)) cat("• T_min =", round(map_mu["T_min"], 2), "°C\n")
if("T_max" %in% names(map_mu)) cat("• T_max =", round(map_mu["T_max"], 2), "°C\n")
if("q" %in% names(map_mu)) cat("• q =", round(map_mu["q"], 4), "\n")
if("sigma.sq" %in% names(map_mu)) cat("• sigma.sq =", round(map_mu["sigma.sq"], 5), "\n")
} else {
cat("(MAP unavailable)\n")
}
```
## Midge Fecundity (EFD)
```{r fit-fecundity, echo=FALSE, message=FALSE, warning=FALSE}
fecundity <- readr::read_csv("data/Bluetongue_Params_0723.csv", show_col_types = FALSE) %>%
dplyr::filter(Trait == "EFD") %>%
dplyr::transmute(T = AmbientTemp, F = TraitValueSI)
# Prepare data for bayesTPC
data_list <- list(Temp = fecundity$T, Trait = fecundity$F)
# Fit Brière model with biologically realistic priors
set.seed(123)
fit_fec <- b_TPC(
data = data_list,
model = "briere",
priors = list(
T_min = "dunif(5, 15)", # Lower thermal limit
T_max = "dunif(32, 36)", # Upper thermal limit
q = "dunif(0, 200)" # Scaling parameter
),
nchains = 4,
burn = 6000,
niter = 18000
)
```
```{r plot-fecundity, echo=FALSE, message=FALSE, warning=FALSE, fig.width=8, fig.height=5}
# Generate temperature grid for predictions
temp_grid <- seq(0, 50, by = 0.1)
# Get posterior samples
samples <- as.matrix(fit_fec$samples[[1]])
# Generate predictions for each sample
predictions <- apply(samples, 1, function(params) {
T_min <- params["T_min"]
T_max <- params["T_max"]
q <- params["q"]
# Brière function
ifelse(temp_grid >= T_min & temp_grid <= T_max,
q * temp_grid * (temp_grid - T_min) * sqrt(pmax(T_max - temp_grid, 0)),
0)
})
# Calculate median and HPD intervals
median_pred <- apply(predictions, 1, median)
hpd_lower <- apply(predictions, 1, function(x) HPDinterval(as.mcmc(x), prob = 0.95)[1])
hpd_upper <- apply(predictions, 1, function(x) HPDinterval(as.mcmc(x), prob = 0.95)[2])
# Create single plot matching screenshot style
par(mfrow = c(1, 1), mar = c(4, 4, 2, 1))
plot(temp_grid, median_pred,
type = "l",
lwd = 2,
col = "black",
xlab = "T (°C)",
ylab = "Eggs per Female per Day",
main = "",
ylim = c(0, 80),
xlim = c(0, 50),
cex.lab = 1.1,
cex.axis = 1.0,
bty = "l")
# Add HPD interval as dashed lines
lines(temp_grid, hpd_lower, lty = 2, lwd = 1.5, col = "black")
lines(temp_grid, hpd_upper, lty = 2, lwd = 1.5, col = "black")
# Add data points as solid black circles
points(fecundity$T, fecundity$F, pch = 16, col = "black", cex = 1.0)
```
```{r param-summary, echo=FALSE, message=FALSE, warning=FALSE}
# MAP Estimates (Maximum A Posteriori)
map_params <- MAP_estimate(fit_fec)
cat("**MAP Estimates (EFD):**\n")
cat("• T_min =", round(map_params["T_min"], 2), "°C\n")
cat("• T_max =", round(map_params["T_max"], 2), "°C\n")
cat("• q =", round(map_params["q"], 3), "\n")
cat("• sigma.sq =", round(map_params["sigma.sq"], 4), "\n")
```
## Larval Survival Probability (pL)
```{r pl-data-fit, echo=FALSE, message=FALSE, warning=FALSE}
# Load updated dataset from CSV and filter for larval survival probability (pL)
pL <- readr::read_csv("data/Bluetongue_Params_0723.csv", show_col_types = FALSE) %>%
dplyr::filter(Trait == "pL") %>%
dplyr::transmute(T = AmbientTemp, pL = TraitValueSI) %>%
dplyr::arrange(T)
# Fit Brière model using bayesTPC
pl_data_list <- list(Temp = pL$T, Trait = pL$pL)
set.seed(123)
fit_pL <- b_TPC(
data = pl_data_list,
model = "briere",
priors = list(
T_min = "dunif(18,22)",
T_max = "dunif(35,40)",
q = "dunif(0,0.03)",
sigma.sq = "dexp(1 / 0.05^2)"
),
nchains = 4,
burn = 6000,
niter = 18000
)
```
```{r pl-plot, echo=FALSE, message=FALSE, warning=FALSE, fig.width=8, fig.height=5}
# 1) Use ALL chains
samples_pL <- do.call(rbind, lapply(fit_pL$samples, as.matrix))
# 2) Predictions on grid
temp_grid <- seq(0, 50, by = 0.1)
briere_fun <- function(T, T_min, T_max, q) {
ifelse(T >= T_min & T <= T_max,
q * T * (T - T_min) * sqrt(pmax(T_max - T, 0)), 0)
}
pred_pL <- sapply(temp_grid, function(Ti) {
briere_fun(Ti, samples_pL[, "T_min"], samples_pL[, "T_max"], samples_pL[, "q"])
})
# 3) Summaries (median curve + 95% HPD for the mean curve)
median_pL <- apply(pred_pL, 2, median)
hpd_bounds <- apply(pred_pL, 2, function(x) as.numeric(HDInterval::hdi(x, credMass = 0.95)))
hpd_lower_pL <- hpd_bounds[1, ]
hpd_upper_pL <- hpd_bounds[2, ]
# 4) Topt = argmax of median curve (robust and version-agnostic)
Topt_pL <- temp_grid[which.max(median_pL)]
# 5) Plot
par(mfrow = c(1,1), mar = c(4,4,2,1))
plot(temp_grid, median_pL,
type = "l", lwd = 2, col = "black",
xlab = "T (°C)", ylab = "Larval Survival Probability",
ylim = c(0, 1), xlim = c(0, 50), bty = "l", yaxt = "n")
axis(2, at = seq(0,1, by = 0.2), las = 1)
lines(temp_grid, hpd_lower_pL, lty = 2, lwd = 1.2)
lines(temp_grid, hpd_upper_pL, lty = 2, lwd = 1.2)
points(pL$T, pL$pL, pch = 16, col = "black")
abline(v = Topt_pL, lty = 3)
# Safe label for mtext()
lbl <- sprintf("Topt ≈ %.1f°C (median curve)", Topt_pL)
if (length(lbl) == 1 && !is.na(lbl)) {
mtext(lbl, side = 3, adj = 1, cex = 0.9)
}
```
```{r pl-param-summary, echo=FALSE, message=FALSE, warning=FALSE}
# MAP Estimates (Maximum A Posteriori)
map_pL <- MAP_estimate(fit_pL)
cat("**MAP Estimates (pL):**\n")
cat("• T_min =", round(map_pL["T_min"], 2), "°C\n")
cat("• T_max =", round(map_pL["T_max"], 2), "°C\n")
cat("• q =", round(map_pL["q"], 4), "\n")
cat("• sigma.sq =", round(map_pL["sigma.sq"], 5), "\n")
```
## Biting Rate (a)
```{r a-data-fit, echo=FALSE, message=FALSE, warning=FALSE}
# Load updated dataset from CSV and filter for biting rate (a)
a_df <- readr::read_csv("data/Bluetongue_Params_0723.csv", show_col_types = FALSE) %>%
dplyr::filter(Trait == "a") %>%
dplyr::transmute(T = AmbientTemp, a = TraitValueSI) %>%
dplyr::arrange(T)
# Fit Brière model using bayesTPC
a_data_list <- list(Temp = a_df$T, Trait = a_df$a)
set.seed(123)
fit_a <- b_TPC(
data = a_data_list,
model = "briere",
priors = list(
T_min = "dunif(5,15)",
T_max = "dunif(32,36)",
q = "dunif(0,1)",
sigma.sq = "dexp(1 / 0.1^2)"
),
nchains = 4,
burn = 6000,
niter = 18000
)
```
```{r a-plot, echo=FALSE, message=FALSE, warning=FALSE, fig.width=8, fig.height=5}
# Use ALL chains and established prediction pipeline
samples_a <- do.call(rbind, lapply(fit_a$samples, as.matrix))
temp_grid <- seq(0, 50, by = 0.1)
briere_fun <- function(T, T_min, T_max, q) {
ifelse(T >= T_min & T <= T_max, q * T * (T - T_min) * sqrt(pmax(T_max - T, 0)), 0)
}
pred_a <- sapply(temp_grid, function(Ti) briere_fun(Ti, samples_a[, "T_min"], samples_a[, "T_max"], samples_a[, "q"]))
median_a <- apply(pred_a, 2, median)
hpd_a <- apply(pred_a, 2, function(x) as.numeric(HDInterval::hdi(x, credMass = 0.95)))
lo_a <- hpd_a[1, ]; hi_a <- hpd_a[2, ]
Topt_a <- temp_grid[which.max(median_a)]
par(mfrow = c(1,1), mar = c(4,4,2,1))
plot(temp_grid, median_a, type = "l", lwd = 2, col = "black",
xlab = "T (°C)", ylab = "Biting Rate (per day)",
ylim = c(0, 1), xlim = c(0, 50), bty = "l", yaxt = "n")
axis(2, at = seq(0,1, by = 0.2), las = 1)
lines(temp_grid, lo_a, lty = 2, lwd = 1.2)
lines(temp_grid, hi_a, lty = 2, lwd = 1.2)
points(a_df$T, a_df$a, pch = 16, col = "black")
abline(v = Topt_a, lty = 3)
lbl <- sprintf("Topt ≈ %.1f°C (median curve)", Topt_a)
if (length(lbl) == 1 && !is.na(lbl)) mtext(lbl, side = 3, adj = 1, cex = 0.9)
```
```{r a-param-summary, echo=FALSE, message=FALSE, warning=FALSE}
# MAP Estimates (Maximum A Posteriori)
map_a <- MAP_estimate(fit_a)
cat("**MAP Estimates (a):**\n")
cat("• T_min =", round(map_a["T_min"], 2), "°C\n")
cat("• T_max =", round(map_a["T_max"], 2), "°C\n")
cat("• q =", round(map_a["q"], 4), "\n")
cat("• sigma.sq =", round(map_a["sigma.sq"], 5), "\n")
```
## Larva's Development Time (LDT)
```{r ldt-data-fit, echo=FALSE, message=FALSE, warning=FALSE}
# Use direct data from user (LDT values in days) - exactly as specified
ldt_df <- data.frame(
T = c(20, 23, 27, 30, 35),
LDT = c(34.5, 33.6, 26.5, 24.4, 16.7)
)
# Use a simple polynomial regression approach for better stability
# This captures the biological relationship: development time decreases with temperature
temp_centered <- ldt_df$T - mean(ldt_df$T) # Center temperature for numerical stability
ldt_fit <- lm(LDT ~ temp_centered + I(temp_centered^2), data = data.frame(LDT = ldt_df$LDT, temp_centered))
# Extract coefficients for prediction
intercept <- coef(ldt_fit)[1]
linear_coef <- coef(ldt_fit)[2]
quad_coef <- coef(ldt_fit)[3]
residual_sd <- summary(ldt_fit)$sigma
# Generate posterior-like samples for uncertainty quantification
set.seed(123)
n_samples <- 1000
intercept_samples <- rnorm(n_samples, intercept, summary(ldt_fit)$coefficients[1,2])
linear_samples <- rnorm(n_samples, linear_coef, summary(ldt_fit)$coefficients[2,2])
quad_samples <- rnorm(n_samples, quad_coef, summary(ldt_fit)$coefficients[3,2])
```
```{r ldt-plot, echo=FALSE, message=FALSE, warning=FALSE, fig.width=8, fig.height=5}
# Temperature grid for predictions (matching original: 0-50°C)
temp_grid <- seq(0, 50, by = 0.1)
temp_grid_centered <- temp_grid - mean(ldt_df$T) # Center using same value
# Generate predictions using the quadratic model
pred_ldt <- sapply(1:n_samples, function(i) {
intercept_samples[i] + linear_samples[i] * temp_grid_centered + quad_samples[i] * temp_grid_centered^2
})
# Calculate mean and 95% credible intervals
mean_ldt <- rowMeans(pred_ldt)
ci_ldt <- apply(pred_ldt, 1, function(x) quantile(x, c(0.025, 0.975)))
lo_ldt <- ci_ldt[1, ]
hi_ldt <- ci_ldt[2, ]
# Find optimal temperature (minimum development time)
Topt_ldt <- temp_grid[which.min(mean_ldt)]
# Plot matching the original paper's style
par(mfrow = c(1,1), mar = c(4,4,2,1))
plot(temp_grid, mean_ldt, type = "l", lwd = 2, col = "black",
xlab = "T (°C)", ylab = "Larval Development Time (days)",
xlim = c(0, 50), ylim = c(0, max(60, max(hi_ldt, ldt_df$LDT, na.rm = TRUE) * 1.05)), bty = "l")
lines(temp_grid, lo_ldt, lty = 2, lwd = 1.2)
lines(temp_grid, hi_ldt, lty = 2, lwd = 1.2)
points(ldt_df$T, ldt_df$LDT, pch = 16, col = "black", cex = 1.5)
abline(v = Topt_ldt, lty = 3)
lbl <- sprintf("Topt ≈ %.1f°C (min dev. time)", Topt_ldt)
if (length(lbl) == 1 && !is.na(lbl)) mtext(lbl, side = 3, adj = 1, cex = 0.9)
```
```{r ldt-param-summary, echo=FALSE, message=FALSE, warning=FALSE}
# Report the fitted quadratic model parameters (Maximum Likelihood Estimates)
cat("**Fitted Quadratic Model (LDT):**\n")
cat("• Intercept =", round(intercept, 2), "\n")
cat("• Linear coefficient =", round(linear_coef, 4), "\n")
cat("• Quadratic coefficient =", round(quad_coef, 6), "\n")
cat("• Residual SD =", round(residual_sd, 2), "\n")
cat("• R-squared =", round(summary(ldt_fit)$r.squared, 3), "\n")
# Report the model equation
temp_center <- round(mean(ldt_df$T), 1)
cat("\n**Model:** LDT =", round(intercept, 2), "+", round(linear_coef, 4), "*(T -", temp_center, ") +", round(quad_coef, 6), "*(T -", temp_center, ")²\n")
cat("\n**Note:** Development time decreases with temperature (faster development at higher T).\n")
```
## Egg Development Time (EDT)
```{r edt-data-fit, echo=FALSE, message=FALSE, warning=FALSE}
# EDT data from user (Egg Development Time in days)
edt_df <- data.frame(
T = c(20, 23, 27, 30, 35),
EDT = c(63.6, 64.7, 61.4, 50.9, 57.1)
)
# Use a simple polynomial regression approach for stability
# Development time decreases with temperature (similar to LDT)
temp_centered_edt <- edt_df$T - mean(edt_df$T) # Center temperature for numerical stability
edt_fit <- lm(EDT ~ temp_centered_edt + I(temp_centered_edt^2), data = data.frame(EDT = edt_df$EDT, temp_centered_edt))
# Extract coefficients for prediction
intercept_edt <- coef(edt_fit)[1]
linear_coef_edt <- coef(edt_fit)[2]
quad_coef_edt <- coef(edt_fit)[3]
residual_sd_edt <- summary(edt_fit)$sigma
# Generate posterior-like samples for uncertainty quantification
set.seed(123)
n_samples_edt <- 1000
intercept_samples_edt <- rnorm(n_samples_edt, intercept_edt, summary(edt_fit)$coefficients[1,2])
linear_samples_edt <- rnorm(n_samples_edt, linear_coef_edt, summary(edt_fit)$coefficients[2,2])
quad_samples_edt <- rnorm(n_samples_edt, quad_coef_edt, summary(edt_fit)$coefficients[3,2])
```
```{r edt-plot, echo=FALSE, message=FALSE, warning=FALSE, fig.width=8, fig.height=5}
# Temperature grid for predictions
temp_grid <- seq(0, 50, by = 0.1)
temp_grid_centered_edt <- temp_grid - mean(edt_df$T) # Center using same value
# Generate predictions using the quadratic model
pred_edt <- sapply(1:n_samples_edt, function(i) {
intercept_samples_edt[i] + linear_samples_edt[i] * temp_grid_centered_edt + quad_samples_edt[i] * temp_grid_centered_edt^2
})
# Calculate mean and 95% credible intervals
mean_edt <- rowMeans(pred_edt)
ci_edt <- apply(pred_edt, 1, function(x) quantile(x, c(0.025, 0.975)))
lo_edt <- ci_edt[1, ]
hi_edt <- ci_edt[2, ]
# Find optimal temperature (minimum development time)
Topt_edt <- temp_grid[which.min(mean_edt)]
# Plot matching the original paper's style
par(mfrow = c(1,1), mar = c(4,4,2,1))
plot(temp_grid, mean_edt, type = "l", lwd = 2, col = "black",
xlab = "T (°C)", ylab = "Egg Development Time (days)",
xlim = c(0, 50), ylim = c(0, max(80, max(hi_edt, edt_df$EDT, na.rm = TRUE) * 1.05)), bty = "l")
lines(temp_grid, lo_edt, lty = 2, lwd = 1.2)
lines(temp_grid, hi_edt, lty = 2, lwd = 1.2)
points(edt_df$T, edt_df$EDT, pch = 16, col = "black", cex = 1.5)
abline(v = Topt_edt, lty = 3)
lbl <- sprintf("Topt ≈ %.1f°C (min dev. time)", Topt_edt)
if (length(lbl) == 1 && !is.na(lbl)) mtext(lbl, side = 3, adj = 1, cex = 0.9)
```
```{r edt-param-summary, echo=FALSE, message=FALSE, warning=FALSE}
# Report the fitted quadratic model parameters (Maximum Likelihood Estimates)
cat("**Fitted Quadratic Model (EDT):**\n")
cat("• Intercept =", round(intercept_edt, 2), "\n")
cat("• Linear coefficient =", round(linear_coef_edt, 4), "\n")
cat("• Quadratic coefficient =", round(quad_coef_edt, 6), "\n")
cat("• Residual SD =", round(residual_sd_edt, 2), "\n")
cat("• R-squared =", round(summary(edt_fit)$r.squared, 3), "\n")
# Report the model equation
temp_center_edt <- round(mean(edt_df$T), 1)
cat("\n**Model:** EDT =", round(intercept_edt, 2), "+", round(linear_coef_edt, 4), "*(T -", temp_center_edt, ") +", round(quad_coef_edt, 6), "*(T -", temp_center_edt, ")²\n")
cat("\n**Note:** Egg development time varies with temperature following quadratic relationship.\n")
```
## Pupal Development Time (PuDT)
```{r pudt-data-fit, echo=FALSE, message=FALSE, warning=FALSE}
# PuDT data from user (Pupal Development Time in days)
pudt_df <- data.frame(
T = c(20, 23, 27, 30, 35),
PuDT = c(89.7, 65.5, 50.6, 39.1, 38.8)
)
# Use a simple polynomial regression approach for stability
# Development time decreases with temperature (similar to LDT and EDT)
temp_centered_pudt <- pudt_df$T - mean(pudt_df$T) # Center temperature for numerical stability
pudt_fit <- lm(PuDT ~ temp_centered_pudt + I(temp_centered_pudt^2), data = data.frame(PuDT = pudt_df$PuDT, temp_centered_pudt))
# Extract coefficients for prediction
intercept_pudt <- coef(pudt_fit)[1]
linear_coef_pudt <- coef(pudt_fit)[2]
quad_coef_pudt <- coef(pudt_fit)[3]
residual_sd_pudt <- summary(pudt_fit)$sigma
# Generate posterior-like samples for uncertainty quantification
set.seed(123)
n_samples_pudt <- 1000
intercept_samples_pudt <- rnorm(n_samples_pudt, intercept_pudt, summary(pudt_fit)$coefficients[1,2])
linear_samples_pudt <- rnorm(n_samples_pudt, linear_coef_pudt, summary(pudt_fit)$coefficients[2,2])
quad_samples_pudt <- rnorm(n_samples_pudt, quad_coef_pudt, summary(pudt_fit)$coefficients[3,2])
```
```{r pudt-plot, echo=FALSE, message=FALSE, warning=FALSE, fig.width=8, fig.height=5}
# Temperature grid for predictions
temp_grid <- seq(0, 50, by = 0.1)
temp_grid_centered_pudt <- temp_grid - mean(pudt_df$T) # Center using same value
# Generate predictions using the quadratic model
pred_pudt <- sapply(1:n_samples_pudt, function(i) {
intercept_samples_pudt[i] + linear_samples_pudt[i] * temp_grid_centered_pudt + quad_samples_pudt[i] * temp_grid_centered_pudt^2
})
# Calculate mean and 95% credible intervals
mean_pudt <- rowMeans(pred_pudt)
ci_pudt <- apply(pred_pudt, 1, function(x) quantile(x, c(0.025, 0.975)))
lo_pudt <- ci_pudt[1, ]
hi_pudt <- ci_pudt[2, ]
# Find optimal temperature (minimum development time)
Topt_pudt <- temp_grid[which.min(mean_pudt)]
# Plot matching the reference image scaling
par(mfrow = c(1,1), mar = c(4,4,2,1))
plot(temp_grid, mean_pudt, type = "l", lwd = 2, col = "black",
xlab = "T (°C)", ylab = "Pupal Development Time",
xlim = c(0, 50), ylim = c(0, 150), bty = "l")
lines(temp_grid, lo_pudt, lty = 2, lwd = 2, col = "black")
lines(temp_grid, hi_pudt, lty = 2, lwd = 2, col = "black")
points(pudt_df$T, pudt_df$PuDT, pch = 16, col = "black", cex = 1.5)
abline(v = Topt_pudt, lty = 3)
lbl <- sprintf("Topt ≈ %.1f°C (min dev. time)", Topt_pudt)
if (length(lbl) == 1 && !is.na(lbl)) mtext(lbl, side = 3, adj = 1, cex = 0.9)
```
```{r pudt-param-summary, echo=FALSE, message=FALSE, warning=FALSE}
# Report the fitted quadratic model parameters (Maximum Likelihood Estimates)
cat("**Fitted Quadratic Model (PuDT):**\n")
cat("• Intercept =", round(intercept_pudt, 2), "\n")
cat("• Linear coefficient =", round(linear_coef_pudt, 4), "\n")
cat("• Quadratic coefficient =", round(quad_coef_pudt, 6), "\n")
cat("• Residual SD =", round(residual_sd_pudt, 2), "\n")
cat("• R-squared =", round(summary(pudt_fit)$r.squared, 3), "\n")
# Report the model equation
temp_center_pudt <- round(mean(pudt_df$T), 1)
cat("\n**Model:** PuDT =", round(intercept_pudt, 2), "+", round(linear_coef_pudt, 4), "*(T -", temp_center_pudt, ") +", round(quad_coef_pudt, 6), "*(T -", temp_center_pudt, ")²\n")
cat("\n**Note:** Pupal development time decreases with temperature (faster development at higher T).\n")
```