|
a |
|
b/R/calc.llk.tree.R |
|
|
1 |
#' Function to calculate integrated likelihood for set of variants up tree |
|
|
2 |
#' |
|
|
3 |
#' @param pars A list object as returned by the function set.parameters |
|
|
4 |
#' @param data.sub A 3-dimension array (N. SNPs x N. phenotypes x 3) with state likelihoods. |
|
|
5 |
#' @param returnForwardMatrix Boolean |
|
|
6 |
#' @param returnGMatrix Boolean |
|
|
7 |
#' |
|
|
8 |
#' @return Either a numeric object with the Tree likelihood or a list with FWD and G matrices |
|
|
9 |
|
|
|
10 |
calc.llk.tree <- function( |
|
|
11 |
pars, |
|
|
12 |
data.sub, |
|
|
13 |
returnForwardMatrix = FALSE, |
|
|
14 |
returnGMatrix = FALSE |
|
|
15 |
) { |
|
|
16 |
|
|
|
17 |
## Get integrated likelihood at nodes - will be overwritten for internal nodes |
|
|
18 |
mx <- apply(data.sub, 1, max); |
|
|
19 |
d <- exp(data.sub-mx); |
|
|
20 |
llk.integrated <- log(d %*% pars$stat.dist)+mx; |
|
|
21 |
if (returnGMatrix) g <- array(0, dim(d)); |
|
|
22 |
|
|
|
23 |
for (i in pars$t.path) { |
|
|
24 |
## Emissions at node |
|
|
25 |
emiss.node<-data.sub[i,]; |
|
|
26 |
data.sub[i,]<-0; |
|
|
27 |
for (j in pars$ontology[[i]]) { |
|
|
28 |
tmp1 <- cbind( |
|
|
29 |
data.sub[j,]-pars$theta.tree, |
|
|
30 |
llk.integrated[j]+pars$lp.switch |
|
|
31 |
); |
|
|
32 |
mx1 <- apply(tmp1, 1, max); |
|
|
33 |
tmp2 <- mx1+log(rowSums(exp(tmp1-mx1))); |
|
|
34 |
data.sub[i,] <- data.sub[i,]+tmp2; |
|
|
35 |
if (returnGMatrix) g[j,] <- tmp2; |
|
|
36 |
} |
|
|
37 |
data.sub[i,] <- data.sub[i,]+emiss.node; |
|
|
38 |
mx <- max(data.sub[i,]); |
|
|
39 |
llk.integrated[i] <- mx+log(sum(exp(data.sub[i,]-mx)*pars$stat.dist)); |
|
|
40 |
} |
|
|
41 |
if (returnForwardMatrix) { |
|
|
42 |
if (!returnGMatrix) { |
|
|
43 |
return(data.sub); |
|
|
44 |
} else { |
|
|
45 |
return(list(f=data.sub, g=g)); |
|
|
46 |
} |
|
|
47 |
} else { |
|
|
48 |
return(llk.integrated[i]); |
|
|
49 |
} |
|
|
50 |
} |