]> nmode's Git Repositories - Rnaught/blob - R/WP_unknown.R
Include required functions from 'stats' package
[Rnaught] / R / WP_unknown.R
1 #' WP method background function WP_unknown
2 #'
3 #' This is a background/internal function called by \code{WP}. It computes the maximum likelihood estimator
4 #' of R0 assuming that the serial distribution is unknown but comes from a discretized gamma distribution.
5 #' The function then implements a simple grid search algorithm to obtain the maximum likelihood estimator
6 #' of R0 as well as the gamma parameters.
7 #'
8 #' @param NT Vector of case counts.
9 #' @param B Length of grid for shape and scale (grid search parameter).
10 #' @param shape.max Maximum shape value (grid \code{search} parameter).
11 #' @param scale.max Maximum scale value (grid \code{search} parameter).
12 #' @param tol cutoff value for cumulative distribution function of the serial distribution (defaults to 0.999).
13 #'
14 #' @return The function returns \code{Rhat}, the maximum likelihood estimator of R0, as well as the maximum
15 #' likelihood estimator of the discretized serial distribution given by \code{p} (the probability mass
16 #' function) and \code{range.max} (the distribution has support on the integers one to \code{range.max}).
17 #' The function also returns \code{resLL} (all values of the log-likelihood) at \code{shape} (grid for
18 #' shape parameter) and at \code{scale} (grid for scale parameter), as well as \code{resR0} (the full
19 #' vector of maximum likelihood estimators), \code{JJ} (the locations for the likelihood for these), and
20 #' \code{J0} (the location for the maximum likelihood estimator \code{Rhat}). If \code{JJ} and \code{J0}
21 #' are not the same, this means that the maximum likelihood estimator is not unique.
22 #'
23 #' @importFrom stats pgamma qgamma
24 #'
25 #' @keywords internal
26 WP_unknown <- function(NT, B=100, shape.max=10, scale.max=10, tol=0.999) {
27 shape <- seq(0, shape.max, length.out=B+1)
28 scale <- seq(0, scale.max, length.out=B+1)
29 shape <- shape[-1]
30 scale <- scale[-1]
31
32 resLL <- matrix(0,B,B)
33 resR0 <- matrix(0,B,B)
34
35 for (i in 1:B) {
36 for (j in 1:B) {
37 range.max <- ceiling(qgamma(tol, shape=shape[i], scale=scale[j]))
38 p <- diff(pgamma(0:range.max, shape=shape[i], scale=scale[j]))
39 p <- p / sum(p)
40 mle <- WP_known(NT, p)
41 resLL[i,j] <- computeLL(p, NT, mle)
42 resR0[i,j] <- mle
43 }
44 }
45
46 J0 <- which.max(resLL)
47 R0hat <- resR0[J0]
48 JJ <- which(resLL == resLL[J0], arr.ind=TRUE)
49 range.max <- ceiling(qgamma(tol, shape=shape[JJ[1]], scale=scale[JJ[2]]))
50 p <- diff(pgamma(0:range.max, shape=shape[JJ[1]], scale=scale[JJ[2]]))
51 p <- p / sum(p)
52
53 return(list(Rhat=R0hat, J0=J0, ll=resLL, Rs=resR0, scale=scale, shape=shape, JJ=JJ, p=p, range.max=range.max))
54 }