Last updated: 2019-11-12

Checks: 7 0

Knit directory: SMF/

This reproducible R Markdown analysis was created with workflowr (version 1.5.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20190719) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility. The version displayed above was the version of the Git repository at the time these results were generated.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .DS_Store
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    analysis/.DS_Store
    Ignored:    data/.DS_Store

Untracked files:
    Untracked:  analysis/SMFrealdata.Rmd
    Untracked:  analysis/poissonmeanscle.Rmd
    Untracked:  data/external_data/

Unstaged changes:
    Modified:   analysis/index.Rmd
    Modified:   analysis/poissonmean.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the R Markdown and HTML files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view them.

File Version Author Date Message
Rmd d2212af Dongyue Xie 2019-11-12 wflow_publish(“analysis/poissonmean3.Rmd”)
html aa9093f Dongyue Xie 2019-11-12 Build site.
Rmd 019676d Dongyue Xie 2019-11-12 wflow_publish(“analysis/poissonmean3.Rmd”)

Introduction

ebpm_gamma_mixture <- function(x,s = 1, shape=c(0.1,10),rate = c(1e3,1e-3), point_mass=F,
                             nullweight=1, weight = rep(1,length(x)),
                             g_init = NULL, fix_g = FALSE,
                             m = 2, control =  NULL, low = NULL,d=NULL){
  n=length(x)
  if(length(s) == 1){s = replicate(length(x),s)}
  if(is.null(control)){control = mixsqp_control_defaults()}
  if(is.null(g_init)){
    fix_g = FALSE ## then automatically unfix g if specified so
    rate = list(rate=rate,shape=shape)
    g_init = scale2gammamix_init(rate,point_mass)
  }
  
  if(!fix_g){ ## need to estimate g_init
    b = g_init$rate ##  from here use gamma(shape = a, rate = b)  where E = a/b
    a = g_init$shape
    tmp <-  compute_L(x,s,a, b,point_mass)
    L =  tmp$L
    l_rowmax = tmp$l_rowmax
    if(point_mass){x0 = c(g_init$pi0,g_init$pi)}else{x0 = g_init$pi}
    if(!is.null(nullweight)){
      Lnull = rbind(c(1,rep(0,ncol(L)-1)),L)
      weight = c(nullweight-1,weight)
      fit <- mixsqp(Lnull, weight,x0 = x0, control = control)
    }else{
      fit <- mixsqp(L, weight,x0 = x0, control = control)
    }
    pi = fit$x
    pi = pi/sum(pi) ## seems that some times pi does not sum to one
  }
  else{
    if(point_mass){
      pi = c(g_init$pi0,g_init$pi)
    }else{
      pi = g_init$pi
    }
    a = g_init$shape
    b = g_init$rate
    ## compute loglikelihood
    tmp <-  compute_L(x,s,a, b,point_mass)
    L =  tmp$L
    l_rowmax = tmp$l_rowmax
  }
  fitted_g = gammamix(pi = pi, shape = a,  rate  = b,point_mass)
  
  log_likelihood = sum(log(exp(l_rowmax) * L %*%  pi))
  
  cpm = outer(x,a,  "+")/outer(s, b, "+")
  if(point_mass){cpm = cbind(rep(0,n),cpm)}
  Pi_tilde = t(t(L) * pi)
  Pi_tilde = Pi_tilde/rowSums(Pi_tilde)
  lam_pm = rowSums(Pi_tilde * cpm)
  
  c_log_pm = digamma(outer(x,a,  "+")) - log(outer(s, b, "+"))
  if(point_mass){
    lam_log_pm = rowSums(Pi_tilde[,-1] * c_log_pm)
    lam_log_pm[x==0] = -Inf
  }else{
    lam_log_pm = rowSums(Pi_tilde * c_log_pm)
  }
  posterior = data.frame(mean = lam_pm, mean_log = lam_log_pm)
  return(list(fitted_g = fitted_g,
              posterior = posterior,
              log_likelihood = log_likelihood,
              Pi_tilde=Pi_tilde,
              tmp=tmp))
}


prune_fitted_g_ebpm = function(fitted_g,thresh=1e-10){
  rm_idx = which(fitted_g$pi<thresh)
  fitted_g$pi = fitted_g$pi[-rm_idx]
  fitted_g$shape = fitted_g$shape[-rm_idx]
  fitted_g$scale = fitted_g$scale[-rm_idx]
  fitted_g
}


## compute L matrix from data and selected grid
## L_ik = NB(x_i; a_k, b_k/b_k + s_i)
## but for computation in mixsqr, we can simplyfy it for numerical stability
compute_L <- function(x, s, a, b,point_mass){
  prob = 1 - s/outer(s,b, "+")
  l = dnbinom_cts_log(x,a,prob = prob) ##
  l_rowmax  = apply(l,1,max)
  if(point_mass){
    l0 = cbind(log(c(x==0)),l)
    L = exp(l0 -  l_rowmax)
  }else{
    L = exp(l -  l_rowmax)
  }
  
  return(list(L = L, l_rowmax = l_rowmax))
}


# it is equivalent to dnbinom in R wiht log = T when X is integer; I allow  it  to compute when x is not integer
dnbinom_cts_log <- function(x, a, prob){
  tmp = x*log(1-prob)
  tmp[x == 0] = 0 ## R says 0*-Inf = NaN
  out = t(t(log(prob)) * a) + tmp + lgamma(outer(x, a, "+")) - lgamma(x+1)
  out = t(t(out) - lgamma(a))
  return(out)
}

gammamix <- function(pi, shape, rate,point_mass) {
  if(point_mass){
    structure(list(pi = pi[-1], shape = shape, rate = rate, pi0 = pi[1]), class="gammamix")
  }else{
    structure(list(pi = pi, shape = shape, rate = rate), class="gammamix")
  }
}

scale2gammamix_init <- function(rate,point_mass){
  n = length(rate$shape) + point_mass
  pi_init = replicate(n, 1)/n
  return(gammamix(pi = pi_init, shape = rate$shape, rate =  rate$rate,point_mass))
}

mixsqp_control_defaults <- function() {
  return(list(verbose = F))
}

I tried the mixture of two gamma distributions. For now, we specify the true prior distribution.

library(mixsqp)
set.seed(12345)
pi0=0.8
lamda=c()
n=100
for(i in 1:100){
  idx = rbinom(1,1,pi0)
  if(idx){
    lamda[i] = rgamma(1,0.1,1)
  }else{
    lamda[i]=rgamma(1,50,1)
  }
}

lamda = sort(lamda)

hist(lamda,breaks =20)

Version Author Date
aa9093f Dongyue Xie 2019-11-12
s=1
x = rpois(n,s*lamda)

fit = ebpm_gamma_mixture(x,s,shape = c(0.1,50), rate=c(1,1),nullweight = 20)

plot(x/s,fit$posterior$mean,xlab = 'MLE',ylab = 'Posterior mean',pch=16)
abline(0,1)

Version Author Date
aa9093f Dongyue Xie 2019-11-12
plot(x/s,col='grey80',pch=16)
lines(fit$posterior$mean,type='p',pch=3,col=2)
legend('topleft',c('MLE','Posterior mean'),col=c(1,2),pch=c(16,3))

Version Author Date
aa9093f Dongyue Xie 2019-11-12
fit$fitted_g
$pi
[1] 0.7983193 0.2016807

$shape
[1]  0.1 50.0

$rate
[1] 1 1

attr(,"class")
[1] "gammamix"
tt = rbind((x/s)[70:80],
round((fit$posterior$mean)[70:80],3),round(exp(fit$posterior$mean_log),2)[70:80])
rownames(tt) = c('MLE',c('PosteriorMean','Exp(Elog)'))
colnames(tt) = 70:80
tt
                70   71   72   73   74   75   76    77    78    79    80
MLE           0.00 1.00 0.00 2.00 1.00 3.00 4.00 38.00 38.00 38.00 47.00
PosteriorMean 0.05 0.55 0.05 1.05 0.55 1.55 2.05 44.00 44.00 44.00 48.50
Exp(Elog)     0.00 0.33 0.00 0.81 0.33 1.31 1.81 43.75 43.75 43.75 48.25
set.seed(12345)
s=100
x = rpois(n,s*lamda)

fit = ebpm_gamma_mixture(x,s,shape = c(0.1,50), rate=c(1,1),nullweight = 20)

plot(x/s,fit$posterior$mean,xlab = 'MLE',ylab = 'Posterior mean',pch=16)
abline(0,1)

Version Author Date
aa9093f Dongyue Xie 2019-11-12
plot(x/s,col='grey80',pch=16)
lines(fit$posterior$mean,type='p',pch=3,col=2)
legend('topleft',c('MLE','Posterior mean'),col=c(1,2),pch=c(16,3))

Version Author Date
aa9093f Dongyue Xie 2019-11-12
fit$fitted_g
$pi
[1] 0.7983193 0.2016807

$shape
[1]  0.1 50.0

$rate
[1] 1 1

attr(,"class")
[1] "gammamix"
tt = rbind((x/s)[60:70],
round((fit$posterior$mean)[60:70],3),round(exp(fit$posterior$mean_log),2)[60:70])
rownames(tt) = c('MLE',c('PosteriorMean','Exp(Elog)'))
colnames(tt) = 60:70
tt
                60    61    62    63   64    65    66   67    68    69
MLE           0.08 0.200 0.190 0.180 0.14 0.180 0.160 0.14 0.330 0.310
PosteriorMean 0.08 0.199 0.189 0.179 0.14 0.179 0.159 0.14 0.328 0.308
Exp(Elog)     0.08 0.190 0.180 0.170 0.13 0.170 0.150 0.13 0.320 0.300
                 70
MLE           0.730
PosteriorMean 0.724
Exp(Elog)     0.720

sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.6

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] mixsqp_0.1-97

loaded via a namespace (and not attached):
 [1] workflowr_1.5.0 Rcpp_1.0.2      rprojroot_1.3-2 digest_0.6.21  
 [5] later_1.0.0     R6_2.4.0        backports_1.1.5 git2r_0.26.1   
 [9] magrittr_1.5    evaluate_0.14   stringi_1.4.3   rlang_0.4.0    
[13] fs_1.3.1        promises_1.1.0  whisker_0.4     rmarkdown_1.16 
[17] tools_3.6.1     stringr_1.4.0   glue_1.3.1      httpuv_1.5.2   
[21] xfun_0.10       yaml_2.2.0      compiler_3.6.1  htmltools_0.4.0
[25] knitr_1.25