Last updated: 2020-03-26

Checks: 6 1

Knit directory: misc/

This reproducible R Markdown analysis was created with workflowr (version 1.6.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(20191122) 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.

Using absolute paths to the files within your workflowr project makes it difficult for you and others to run your code on a different machine. Change the absolute path(s) below to the suggested relative path(s) to make your code more reproducible.

absolute relative
~/misc/data/deconv/GSE50244bulkeset.rds data/deconv/GSE50244bulkeset.rds
~/misc/data/deconv/Mousebulkeset.rds data/deconv/Mousebulkeset.rds
~/misc/data/scde/scCD14.RData data/scde/scCD14.RData
~/misc/data/scde/scCD4.RData data/scde/scCD4.RData
~/misc/data/scde/scCD8.RData data/scde/scCD8.RData
~/misc/data/scde/scCDT.RData data/scde/scCDT.RData
~/misc/data/scde/scMB.RData data/scde/scMB.RData

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:    .Rhistory
    Ignored:    .Rproj.user/

Untracked files:
    Untracked:  analysis/contrainedclustering.Rmd
    Untracked:  analysis/gsea.Rmd
    Untracked:  analysis/ideas.Rmd
    Untracked:  analysis/methylation.Rmd
    Untracked:  analysis/susie.Rmd
    Untracked:  code/sccytokines.R
    Untracked:  code/scdeCalibration.R
    Untracked:  data/bart/
    Untracked:  data/cytokine/DE_controls_output_filter10.RData
    Untracked:  data/cytokine/DE_controls_output_filter10_addlimma.RData
    Untracked:  data/cytokine/README
    Untracked:  data/cytokine/test.RData
    Untracked:  data/cytokine_normalized.RData
    Untracked:  data/deconv/
    Untracked:  data/scde/

Unstaged changes:
    Modified:   analysis/binomthinultimate.Rmd
    Deleted:    data/mout_high.RData
    Deleted:    data/scCDT.RData
    Deleted:    data/sva_sva_high.RData

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 2ab0aa9 DongyueXie 2020-03-26 wflow_publish(“analysis/deconvolution.Rmd”)
html a617635 DongyueXie 2020-03-13 Build site.
Rmd 73933a7 DongyueXie 2020-03-13 wflow_publish(“analysis/deconvolution.Rmd”)
html 53cef0f Dongyue Xie 2019-12-10 Build site.
Rmd af20c49 Dongyue Xie 2019-12-10 wflow_publish(“analysis/deconvolution.Rmd”)

Introduction

check bulk data library size: vary from few hundred(100-200) to few thousands(1600). Here

GSE50244bulkeset <- readRDS("~/misc/data/deconv/GSE50244bulkeset.rds")
GSE50244bulkeset
ExpressionSet (storageMode: lockedEnvironment)
assayData: 32581 features, 89 samples 
  element names: exprs 
protocolData: none
phenoData
  sampleNames: Sub1 Sub2 ... Sub89 (89 total)
  varLabels: sampleID SubjectName ... tissue (7 total)
  varMetadata: labelDescription
featureData: none
experimentData: use 'experimentData(object)'
Annotation:  
summary(as.numeric(apply(exprs(GSE50244bulkeset),2,mean)))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  376.3   506.4   605.8   587.1   664.4   793.6 
Mousebulkeset <- readRDS("~/misc/data/deconv/Mousebulkeset.rds")
summary(as.numeric(apply(exprs(Mousebulkeset),2,mean)))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1431    1546    1608    1625    1729    1805 

We have scRNA-seq data from Segerstolpe et al. (2016) including the 1097 cells from 6 healthy subjects, taken from here. This dataset is non-UMI so the read counts are huge. In the following simulation study, 4 cell types - acinar, alpha, beta, and ductal cells are included.

EMTAB.eset = readRDS('data/deconv/EMTABesethealthy.rds')
EMTAB.eset
ExpressionSet (storageMode: lockedEnvironment)
assayData: 25453 features, 1097 samples 
  element names: exprs 
protocolData: none
phenoData
  sampleNames: AZ_A10 AZ_A11 ... HP1509101_P9 (1097 total)
  varLabels: sampleID SubjectName cellTypeID cellType
  varMetadata: labelDescription
featureData: none
experimentData: use 'experimentData(object)'
Annotation:  
table(EMTAB.eset$cellType)

                acinar                  alpha                   beta 
                   112                    443                    171 
         co-expression                  delta                 ductal 
                    26                     59                    135 
           endothelial                epsilon                  gamma 
                    13                      5                     75 
                  mast           MHC class II                    PSC 
                     4                      1                     23 
          unclassified unclassified endocrine 
                     1                     29 

Now obtain the true gene relative expression in each cell type.

Preprocess the data: 1. remove genes appearing in less than 10 cells; 2. remove top \(5\%\) expressed genes

cell_types = c('acinar','alpha','beta','ductal')

###remove genes appeared in too few cells
###remove genes that are overly expressed
#rm.idx = which(rowSums((exprs(EMTAB.eset)[,which(EMTAB.eset$cellType%in%cell_types)])!=0)<10)
#rr = rowSums((exprs(EMTAB.eset)[,which(EMTAB.eset$cellType%in%cell_types)]))
###rm.idx = which(rr==0)
###rm.idx1 = which(rr<=quantile(rr[-rm.idx],0.01))
#rm.idx2 = which(rr>=quantile(rr[-rm.idx],0.99))
#rm.idx = unique(c(rm.idx,rm.idx2))

acinar = exprs(EMTAB.eset)[,which(EMTAB.eset$cellType=='acinar')]
alpha = exprs(EMTAB.eset)[,which(EMTAB.eset$cellType=='alpha')]
beta = exprs(EMTAB.eset)[,which(EMTAB.eset$cellType=='beta')]
ductal = exprs(EMTAB.eset)[,which(EMTAB.eset$cellType=='ductal')]

rm.idx1 = which(((rowSums(acinar!=0)<=10)|(rowSums(acinar)>=quantile(rowSums(acinar),0.95))))
rm.idx2 = which(((rowSums(alpha!=0)<=10)|(rowSums(alpha)>=quantile(rowSums(alpha),0.95))))
rm.idx3 = which(((rowSums(beta!=0)<=10)|(rowSums(beta)>=quantile(rowSums(beta),0.95))))
rm.idx4 = which(((rowSums(ductal!=0)<=10)|(rowSums(ductal)>=quantile(rowSums(ductal),0.95))))

rm.idx = unique(c(rm.idx1,rm.idx2,rm.idx3,rm.idx4))

acinar = acinar[-rm.idx,]
alpha = alpha[-rm.idx,]
beta = beta[-rm.idx,]
ductal = ductal[-rm.idx,]

Check cell library size: cell library sizes are big

summary(colSums(acinar))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   2686   40757   75941  129023  186640  553802 
summary(colSums(alpha))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   3523   40465   83358  113020  159609  690603 
summary(colSums(beta))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   2970   47179  100240  124888  190024  537763 
summary(colSums(ductal))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   6405   38504   86323  135121  191832  739986 
# cell type specific gene relative expression
Theta = cbind(rowSums(acinar)/sum(acinar),
              rowSums(alpha)/sum(alpha),
              rowSums(beta)/sum(beta),
              rowSums(ductal)/sum(ductal))

cor(Theta)
          [,1]      [,2]      [,3]      [,4]
[1,] 1.0000000 0.6653738 0.5972479 0.8288408
[2,] 0.6653738 1.0000000 0.8156478 0.6819325
[3,] 0.5972479 0.8156478 1.0000000 0.6363127
[4,] 0.8288408 0.6819325 0.6363127 1.0000000
kappa(t(Theta)%*%Theta)
[1] 34.74529
# cell library size
S = c(sum(acinar)/ncol(acinar),
      sum(alpha)/ncol(alpha),
      sum(beta)/ncol(beta),
      sum(ductal)/ncol(ductal))

#S=S/100 

Generate reference data: 1. obtain \(\tilde{\theta}_{gk}\) by summing up read counts and normalize; 2. obtain \(y_{k}^{r,+}\) by multiple cell library size and number of cells(set to 100); 3. Generate reference data using the Poisson model

Generate bulk data: 1. simulate library size \(y^{b,+}\) from Poisson\((300G)\); 2. generate \(x^b_g\) by multiplying \(N=400\), \(\beta = (0.1,0.2,0.3,0.4)\), and \(S\) cell library size then normalize to \(\theta^b_g\). 3. generate bulk data using Poisson distribution.

G = nrow(Theta)
K = ncol(Theta)

set.seed(12345)
# bulk data library size: 300*number of genes.
# bulk_ls = rpois(1,300*nrow(Theta))
# total number of cells in bulk data
bulk_ncell = 400
# cell proportions
bulk_beta = c(1,2,3,4)
bulk_beta = bulk_beta/sum(bulk_beta)
bulk_p = (bulk_beta * (S))/sum(bulk_beta * (S))
# bulk data gene relative expression.
bulk_X = bulk_ncell*Theta%*%diag(S)%*%bulk_beta
bulk_theta = bulk_X/sum(bulk_X)

ref_ncell = 100
ref_X = Theta%*%diag(S)*ref_ncell

w = rep(1,G)


p_tilde_est = c()
p_tilde_var = c()
p_est = c()
p_var = c()

nrep = 100
for(rep in 1:nrep){
  if(rep%%200==0){print(rep)}
  bulk_ls = rpois(1,300*nrow(Theta))
  Z = matrix(rpois(G*K,ref_X),ncol=K)
  y = rpois(G,bulk_ls*bulk_theta)

  #W = diag(w)
  #beta_hat = solve(t(Z)%*%W%*%Z - diag(colSums(W%*%Z)))%*%t(Z)%*%W%*%y

  U = diag(colSums(Z))
  Zu = Z%*%(solve(U))
  Zuu = Zu%*%solve(U)
  p_tilde_hat = solve(t(Zu)%*%Zu - diag(colSums(Zuu)))%*%t(Zu)%*%y
  p_tilde_est = rbind(p_tilde_est,c(p_tilde_hat))
  #beta_hat = solve(t(Z)%*%Z)%*%t(Z)%*%y

  #beta_hat
  #beta_hat/sum(beta_hat)

  Q = 0
  Sigma=0
  deltas = c()
  for(i in 1:length(y)){ 
    ag = Zu[i,]%*%t(Zu[i,])-diag(Zuu[i,])
    Q = Q + ag
    Delta = (ag%*%p_tilde_hat-y[i]*Zu[i,])
    Sigma = Sigma + Delta%*%t(Delta)
  }
  Q = Q/G
  Sigma = Sigma/G

  J = matrix(nrow = K,ncol=K)
  for(i in 1:K){
    for(j in 1:K){
      if(i==j){
        J[i,j] = sum(p_tilde_hat)-p_tilde_hat[i]
      }else{
        J[i,j] = -p_tilde_hat[i]
      }
    }
  }

  J = J/sum(p_tilde_hat)^2

  asyV = (t(J)%*%solve(Q)%*%Sigma%*%solve(Q)%*%J)/G

  p_hat = p_tilde_hat/sum(p_tilde_hat)
  p_est = rbind(p_est,c(p_hat))
  
  p_tilde_var = rbind(p_tilde_var,diag(solve(Q)%*%Sigma%*%solve(Q)))
  
  p_var = rbind(p_var,diag(asyV))

}


#### coverage before delta method:

#ci_l = p_tilde_est - qnorm(0.975)*sqrt(p_tilde_var)
#ci_r = p_tilde_est + qnorm(0.975)*sqrt(p_tilde_var)

#coverage

#coverage = ((rep(1,100)%*%t(bulk_p))>=ci_l) & ((rep(1,100)%*%t(bulk_p))<=ci_r)
#apply(coverage,2,mean)

#### converage after delta method

ci_l = p_est - qnorm(0.975)*sqrt(p_var)
ci_r = p_est + qnorm(0.975)*sqrt(p_var)

#coverage

coverage = ((rep(1,100)%*%t(bulk_p))>=ci_l) & ((rep(1,100)%*%t(bulk_p))<=ci_r)
apply(coverage,2,mean)
[1] 0.98 0.98 0.94 0.84
#for(i in 1:4){
#  plot(ci_l[,i],type='l',ylim=range(c(ci_l[,i],ci_r[,i])))
#  lines(ci_r[,i],col='grey80')
#  lines(rep(bulk_p[i],100),lty = 2)
#}

how about decrease bulk library size to \(50G\)?

G = nrow(Theta)
K = ncol(Theta)

set.seed(12345)
# bulk data library size: 300*number of genes.
# bulk_ls = rpois(1,300*nrow(Theta))
# total number of cells in bulk data
bulk_ncell = 400
# cell proportions
bulk_beta = c(1,2,3,4)
bulk_beta = bulk_beta/sum(bulk_beta)
bulk_p = (bulk_beta * (S))/sum(bulk_beta * (S))
# bulk data gene relative expression.
bulk_X = bulk_ncell*Theta%*%diag(S)%*%bulk_beta
bulk_theta = bulk_X/sum(bulk_X)

ref_ncell = 100
ref_X = Theta%*%diag(S)*ref_ncell

w = rep(1,G)


p_tilde_est = c()
p_tilde_var = c()
p_est = c()
p_var = c()

nrep = 100
for(rep in 1:nrep){
  if(rep%%200==0){print(rep)}
  bulk_ls = rpois(1,50*nrow(Theta))
  Z = matrix(rpois(G*K,ref_X),ncol=K)
  y = rpois(G,bulk_ls*bulk_theta)

  #W = diag(w)
  #beta_hat = solve(t(Z)%*%W%*%Z - diag(colSums(W%*%Z)))%*%t(Z)%*%W%*%y

  U = diag(colSums(Z))
  Zu = Z%*%(solve(U))
  Zuu = Zu%*%solve(U)
  p_tilde_hat = solve(t(Zu)%*%Zu - diag(colSums(Zuu)))%*%t(Zu)%*%y
  p_tilde_est = rbind(p_tilde_est,c(p_tilde_hat))
  #beta_hat = solve(t(Z)%*%Z)%*%t(Z)%*%y

  #beta_hat
  #beta_hat/sum(beta_hat)

  Q = 0
  Sigma=0
  deltas = c()
  for(i in 1:length(y)){ 
    ag = Zu[i,]%*%t(Zu[i,])-diag(Zuu[i,])
    Q = Q + ag
    Delta = (ag%*%p_tilde_hat-y[i]*Zu[i,])
    Sigma = Sigma + Delta%*%t(Delta)
  }
  Q = Q/G
  Sigma = Sigma/G

  J = matrix(nrow = K,ncol=K)
  for(i in 1:K){
    for(j in 1:K){
      if(i==j){
        J[i,j] = sum(p_tilde_hat)-p_tilde_hat[i]
      }else{
        J[i,j] = -p_tilde_hat[i]
      }
    }
  }

  J = J/sum(p_tilde_hat)^2

  asyV = (t(J)%*%solve(Q)%*%Sigma%*%solve(Q)%*%J)/G

  p_hat = p_tilde_hat/sum(p_tilde_hat)
  p_est = rbind(p_est,c(p_hat))
  
  p_tilde_var = rbind(p_tilde_var,diag(solve(Q)%*%Sigma%*%solve(Q)))
  
  p_var = rbind(p_var,diag(asyV))

}

ci_l = p_est - qnorm(0.975)*sqrt(p_var)
ci_r = p_est + qnorm(0.975)*sqrt(p_var)

#coverage

coverage = ((rep(1,100)%*%t(bulk_p))>=ci_l) & ((rep(1,100)%*%t(bulk_p))<=ci_r)
apply(coverage,2,mean)
[1] 0.96 0.98 0.95 0.77
#for(i in 1:4){
#  plot(ci_l[,i],type='l',ylim=range(c(ci_l[,i],ci_r[,i])))
#  lines(ci_r[,i],col='grey80')
#  lines(rep(bulk_p[i],100),lty = 2)
#}

how about change \(beta\) to be \((0.4,0.3,0.2,0.1)\)?

G = nrow(Theta)
K = ncol(Theta)

set.seed(12345)
# bulk data library size: 300*number of genes.
# bulk_ls = rpois(1,300*nrow(Theta))
# total number of cells in bulk data
bulk_ncell = 400
# cell proportions
bulk_beta = c(4,3,2,1)
bulk_beta = bulk_beta/sum(bulk_beta)
bulk_p = (bulk_beta * (S))/sum(bulk_beta * (S))
# bulk data gene relative expression.
bulk_X = bulk_ncell*Theta%*%diag(S)%*%bulk_beta
bulk_theta = bulk_X/sum(bulk_X)

ref_ncell = 100
ref_X = Theta%*%diag(S)*ref_ncell

w = rep(1,G)


p_tilde_est = c()
p_tilde_var = c()
p_est = c()
p_var = c()

nrep = 100
for(rep in 1:nrep){
  if(rep%%200==0){print(rep)}
  bulk_ls = rpois(1,300*nrow(Theta))
  Z = matrix(rpois(G*K,ref_X),ncol=K)
  y = rpois(G,bulk_ls*bulk_theta)

  #W = diag(w)
  #beta_hat = solve(t(Z)%*%W%*%Z - diag(colSums(W%*%Z)))%*%t(Z)%*%W%*%y

  U = diag(colSums(Z))
  Zu = Z%*%(solve(U))
  Zuu = Zu%*%solve(U)
  p_tilde_hat = solve(t(Zu)%*%Zu - diag(colSums(Zuu)))%*%t(Zu)%*%y
  p_tilde_est = rbind(p_tilde_est,c(p_tilde_hat))
  #beta_hat = solve(t(Z)%*%Z)%*%t(Z)%*%y

  #beta_hat
  #beta_hat/sum(beta_hat)

  Q = 0
  Sigma=0
  deltas = c()
  for(i in 1:length(y)){ 
    ag = Zu[i,]%*%t(Zu[i,])-diag(Zuu[i,])
    Q = Q + ag
    Delta = (ag%*%p_tilde_hat-y[i]*Zu[i,])
    Sigma = Sigma + Delta%*%t(Delta)
  }
  Q = Q/G
  Sigma = Sigma/G

  J = matrix(nrow = K,ncol=K)
  for(i in 1:K){
    for(j in 1:K){
      if(i==j){
        J[i,j] = sum(p_tilde_hat)-p_tilde_hat[i]
      }else{
        J[i,j] = -p_tilde_hat[i]
      }
    }
  }

  J = J/sum(p_tilde_hat)^2

  asyV = (t(J)%*%solve(Q)%*%Sigma%*%solve(Q)%*%J)/G

  p_hat = p_tilde_hat/sum(p_tilde_hat)
  p_est = rbind(p_est,c(p_hat))
  
  p_tilde_var = rbind(p_tilde_var,diag(solve(Q)%*%Sigma%*%solve(Q)))
  
  p_var = rbind(p_var,diag(asyV))

}

ci_l = p_est - qnorm(0.975)*sqrt(p_var)
ci_r = p_est + qnorm(0.975)*sqrt(p_var)

#coverage

coverage = ((rep(1,100)%*%t(bulk_p))>=ci_l) & ((rep(1,100)%*%t(bulk_p))<=ci_r)
apply(coverage,2,mean)
[1] 0.88 0.96 0.95 1.00
#for(i in 1:4){
#  plot(ci_l[,i],type='l',ylim=range(c(ci_l[,i],ci_r[,i])))
#  lines(ci_r[,i],col='grey80')
#  lines(rep(bulk_p[i],100),lty = 2)
#}

The bigger the beta, the lower the coverage??

pbmc DATA

load("~/misc/data/scde/scCD14.RData")
load("~/misc/data/scde/scCD4.RData")
load("~/misc/data/scde/scCD8.RData")
#load("~/misc/data/scde/scCDT.RData")
load("~/misc/data/scde/scMB.RData")

# remove genes 
CD14 = as.matrix(CD14)
CD4 = as.matrix(CD4)
CD8 = as.matrix(CD8)
#CDT = as.matrix(CDT)
MB = as.matrix(MB)
rm.idx1 = which(((rowSums(CD14!=0)<=10)|(rowSums(CD14)>=quantile(rowSums(CD14),0.95))))
rm.idx2 = which(((rowSums(CD4!=0)<=10)|(rowSums(CD4)>=quantile(rowSums(CD4),0.95))))
rm.idx3 = which(((rowSums(CD8!=0)<=10)|(rowSums(CD8)>=quantile(rowSums(CD8),0.95))))
#rm.idx4 = which(((rowSums(CDT!=0)<=10)|(rowSums(CDT)>=quantile(rowSums(CDT),0.95))))
rm.idx5 = which(((rowSums(MB!=0)<=10)|(rowSums(MB)>=quantile(rowSums(MB),0.95))))

rm.idx = unique(c(rm.idx1,rm.idx2,rm.idx3,rm.idx5))

CD14 = CD14[-rm.idx,]
CD4 = CD4[-rm.idx,]
CD8 = CD8[-rm.idx,]
#CDT = CDT[-rm.idx,]
MB = MB[-rm.idx,]

Theta = cbind(rowSums(CD14)/sum(CD14),
              rowSums(CD4)/sum(CD4),
              rowSums(CD8)/sum(CD8),
              #rowSums(CDT)/sum(CDT),
              rowSums(MB)/sum(MB))

cor(Theta)
          [,1]      [,2]      [,3]      [,4]
[1,] 1.0000000 0.8534940 0.7874808 0.6553133
[2,] 0.8534940 1.0000000 0.7390032 0.6612358
[3,] 0.7874808 0.7390032 1.0000000 0.5953219
[4,] 0.6553133 0.6612358 0.5953219 1.0000000
kappa(t(Theta)%*%Theta)
[1] 57.73301
# cell library size
S = c(sum(CD14)/ncol(CD14),
      sum(CD4)/ncol(CD4),
      sum(CD8)/ncol(CD8),
      sum(MB)/ncol(MB))
G = nrow(Theta)
K = ncol(Theta)

set.seed(12345)
# bulk data library size: 300*number of genes.
# bulk_ls = rpois(1,300*nrow(Theta))
# total number of cells in bulk data
bulk_ncell = 400
# cell proportions
bulk_beta = c(1,2,3,4)
bulk_beta = bulk_beta/sum(bulk_beta)
bulk_p = (bulk_beta * (S))/sum(bulk_beta * (S))
# bulk data gene relative expression.
bulk_X = bulk_ncell*Theta%*%diag(S)%*%bulk_beta
bulk_theta = bulk_X/sum(bulk_X)

ref_ncell = 100
ref_X = Theta%*%diag(S)*ref_ncell

w = rep(1,G)


p_tilde_est = c()
p_tilde_var = c()
p_est = c()
p_var = c()

nrep = 100
for(rep in 1:nrep){
  if(rep%%200==0){print(rep)}
  bulk_ls = rpois(1,300*nrow(Theta))
  Z = matrix(rpois(G*K,ref_X),ncol=K)
  y = rpois(G,bulk_ls*bulk_theta)

  #W = diag(w)
  #beta_hat = solve(t(Z)%*%W%*%Z - diag(colSums(W%*%Z)))%*%t(Z)%*%W%*%y

  U = diag(colSums(Z))
  Zu = Z%*%(solve(U))
  Zuu = Zu%*%solve(U)
  p_tilde_hat = solve(t(Zu)%*%Zu - diag(colSums(Zuu)))%*%t(Zu)%*%y
  p_tilde_est = rbind(p_tilde_est,c(p_tilde_hat))
  #beta_hat = solve(t(Z)%*%Z)%*%t(Z)%*%y

  #beta_hat
  #beta_hat/sum(beta_hat)

  Q = 0
  Sigma=0
  deltas = c()
  for(i in 1:length(y)){ 
    ag = Zu[i,]%*%t(Zu[i,])-diag(Zuu[i,])
    Q = Q + ag
    Delta = (ag%*%p_tilde_hat-y[i]*Zu[i,])
    Sigma = Sigma + Delta%*%t(Delta)
  }
  Q = Q/G
  Sigma = Sigma/G

  J = matrix(nrow = K,ncol=K)
  for(i in 1:K){
    for(j in 1:K){
      if(i==j){
        J[i,j] = sum(p_tilde_hat)-p_tilde_hat[i]
      }else{
        J[i,j] = -p_tilde_hat[i]
      }
    }
  }

  J = J/sum(p_tilde_hat)^2

  asyV = (t(J)%*%solve(Q)%*%Sigma%*%solve(Q)%*%J)/G

  p_hat = p_tilde_hat/sum(p_tilde_hat)
  p_est = rbind(p_est,c(p_hat))
  
  p_tilde_var = rbind(p_tilde_var,diag(solve(Q)%*%Sigma%*%solve(Q)))
  
  p_var = rbind(p_var,diag(asyV))

}

ci_l = p_est - qnorm(0.975)*sqrt(p_var)
ci_r = p_est + qnorm(0.975)*sqrt(p_var)

#coverage

coverage = ((rep(1,100)%*%t(bulk_p))>=ci_l) & ((rep(1,100)%*%t(bulk_p))<=ci_r)
apply(coverage,2,mean)
[1] 0.99 0.98 0.91 0.95

how about change \(beta\) to be \((0.4,0.3,0.2,0.1)\)?

G = nrow(Theta)
K = ncol(Theta)

set.seed(12345)
# bulk data library size: 300*number of genes.
# bulk_ls = rpois(1,300*nrow(Theta))
# total number of cells in bulk data
bulk_ncell = 400
# cell proportions
bulk_beta = c(4,3,2,1)
bulk_beta = bulk_beta/sum(bulk_beta)
bulk_p = (bulk_beta * (S))/sum(bulk_beta * (S))
# bulk data gene relative expression.
bulk_X = bulk_ncell*Theta%*%diag(S)%*%bulk_beta
bulk_theta = bulk_X/sum(bulk_X)

ref_ncell = 100
ref_X = Theta%*%diag(S)*ref_ncell

w = rep(1,G)


p_tilde_est = c()
p_tilde_var = c()
p_est = c()
p_var = c()

nrep = 100
for(rep in 1:nrep){
  if(rep%%200==0){print(rep)}
  bulk_ls = rpois(1,300*nrow(Theta))
  Z = matrix(rpois(G*K,ref_X),ncol=K)
  y = rpois(G,bulk_ls*bulk_theta)

  #W = diag(w)
  #beta_hat = solve(t(Z)%*%W%*%Z - diag(colSums(W%*%Z)))%*%t(Z)%*%W%*%y

  U = diag(colSums(Z))
  Zu = Z%*%(solve(U))
  Zuu = Zu%*%solve(U)
  p_tilde_hat = solve(t(Zu)%*%Zu - diag(colSums(Zuu)))%*%t(Zu)%*%y
  p_tilde_est = rbind(p_tilde_est,c(p_tilde_hat))
  #beta_hat = solve(t(Z)%*%Z)%*%t(Z)%*%y

  #beta_hat
  #beta_hat/sum(beta_hat)

  Q = 0
  Sigma=0
  deltas = c()
  for(i in 1:length(y)){ 
    ag = Zu[i,]%*%t(Zu[i,])-diag(Zuu[i,])
    Q = Q + ag
    Delta = (ag%*%p_tilde_hat-y[i]*Zu[i,])
    Sigma = Sigma + Delta%*%t(Delta)
  }
  Q = Q/G
  Sigma = Sigma/G

  J = matrix(nrow = K,ncol=K)
  for(i in 1:K){
    for(j in 1:K){
      if(i==j){
        J[i,j] = sum(p_tilde_hat)-p_tilde_hat[i]
      }else{
        J[i,j] = -p_tilde_hat[i]
      }
    }
  }

  J = J/sum(p_tilde_hat)^2

  asyV = (t(J)%*%solve(Q)%*%Sigma%*%solve(Q)%*%J)/G

  p_hat = p_tilde_hat/sum(p_tilde_hat)
  p_est = rbind(p_est,c(p_hat))
  
  p_tilde_var = rbind(p_tilde_var,diag(solve(Q)%*%Sigma%*%solve(Q)))
  
  p_var = rbind(p_var,diag(asyV))

}

ci_l = p_est - qnorm(0.975)*sqrt(p_var)
ci_r = p_est + qnorm(0.975)*sqrt(p_var)

#coverage

coverage = ((rep(1,100)%*%t(bulk_p))>=ci_l) & ((rep(1,100)%*%t(bulk_p))<=ci_r)
apply(coverage,2,mean)
[1] 0.90 0.98 0.97 0.98

sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Scientific Linux 7.4 (Nitrogen)

Matrix products: default
BLAS/LAPACK: /software/openblas-0.2.19-el7-x86_64/lib/libopenblas_haswellp-r0.2.19.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

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

other attached packages:
[1] Matrix_1.2-15       Biobase_2.42.0      BiocGenerics_0.28.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.2      knitr_1.20      whisker_0.3-2   magrittr_1.5   
 [5] workflowr_1.6.0 lattice_0.20-38 R6_2.3.0        stringr_1.3.1  
 [9] highr_0.7       tools_3.5.1     grid_3.5.1      git2r_0.26.1   
[13] htmltools_0.3.6 yaml_2.2.0      rprojroot_1.3-2 digest_0.6.18  
[17] later_0.7.5     promises_1.0.1  fs_1.3.1        glue_1.3.0     
[21] evaluate_0.12   rmarkdown_1.10  stringi_1.2.4   compiler_3.5.1 
[25] backports_1.1.2 httpuv_1.4.5