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