# \dontshow{
## for R_DEFAULT_PACKAGES=NULL
library( stats, pos = "package:base", verbose = FALSE)
library(graphics, pos = "package:base", verbose = FALSE)
library( utils, pos = "package:base", verbose = FALSE)
# }
##
## Example 1: simulation
##
set.seed(2L)
n <- 200L
d <- 50L
p <- 0.1
prob <- plogis(rlogis(d + n, location = qlogis(p), scale = 0.1))
delay <- c(0, diff(pgamma(0L:d, 12, 0.4)))
h <- function (x, a = 1, b = 1, c = 0) a * exp(-b * (x - c)^2)
ans <- floor(h(seq(-60, 60, length.out = d + n), a = 1000, b = 0.001))
x0 <- rbinom(d + n, ans, prob)
x <- tabulate(rep(1L:(d + n), x0) +
sample(0L:d, size = sum(x0), replace = TRUE, prob = delay),
d + n)[-(1L:d)]
str(D0 <- deconvolve(x, prob, delay, complete = FALSE))
str(D1 <- deconvolve(x, prob, delay, complete = TRUE))
matplot(-(d - 1L):n,
cbind(x0, c(rep(NA, d), x), prob * D0[["value"]], p * ans),
type = c("p", "p", "p", "l"),
col = c(1L, 1L, 2L, 4L), pch = c(16L, 1L, 16L, NA),
lty = c(0L, 0L, 0L, 1L), lwd = c(NA, NA, NA, 3),
xlab = "Time", ylab = "Count")
legend("topleft", NULL,
c("actual", "actual+delay", "actual+delay+deconvolution", "p*h"),
col = c(1L, 1L, 2L, 4L), pch = c(16L, 1L, 16L, NA),
lty = c(0L, 0L, 0L, 1L), lwd = c(NA, NA, NA, 3),
bty = "n")
plot(0L:D1[["iter"]], D1[["chisq"]],
xlab = "Iterations", ylab = quote(chi^2))
abline(h = 1, lty = 2L)
##
## Example 2: application to pneumonia and influenza
##
data(pneumonia, package = "fastbeta")
x <- pneumonia[["series"]][["deaths"]]
delay <- pneumonia[["delay"]][["gpg"]]
n <- length(x)
d <- length(delay) - 1L
r <- 30L
D2 <- deconvolve(x = x, delay = delay, tol = 0, iter.max = r,
complete = TRUE)
stopifnot(D2[["iter"]] == r,
identical(dim(D2[["value"]]), c(d + n, 1L + r)),
length(D2[["chisq"]]) == 1L + r,
min(D2[["chisq"]]) < 1)
## Subscript for the first, critical, and last values:
j2 <- c(1L, which.max(D2[["chisq"]] < 1), 1L + r)
matplot(x = seq(from = pneumonia[["series"]][1L, "date"] - d,
by = 1, length.out = d + n),
y = cbind(c(rep(NA, d), x), D2[["value"]][, j2]),
type = "o",
col = c(1L, 4L, 2L, 3L), pch = 1L, lty = 1L, lwd = 1,
xlab = "1918", ylab = "deaths")
legend("topleft", NULL,
c("observed", sprintf("after %d iterations", j2 - 1L)),
col = c(1L, 4L, 2L, 3L), pch = 1L, lty = 1L, lwd = 1,
bty = "n")
Run the code above in your browser using DataLab