-
Notifications
You must be signed in to change notification settings - Fork 2
/
HMMploidy.R
executable file
·1617 lines (1376 loc) · 62.3 KB
/
HMMploidy.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
library(pracma) #strcmp function library
library(data.table) #fread function library
library(Rcpp)
##############################
### script input interface ###
##############################
l<-commandArgs(TRUE)
getArgs<-function(x,l)
unlist(strsplit(grep(paste("^",x,"=",sep=""),l,val=T),"="))[2]
Args<-function(l,args){
if(! all(sapply(strsplit(l,"="),function(x)x[1])%in%names(args))){
cat("Error -> ",l[!sapply(strsplit(l,"="),function(x)x[1])%in%names(args)]," is not a valid argument")
q("no")
}
arguments<-list()
for(a in names(args))
arguments[[a]]<-getArgs(a,l)
if(any(!names(args)%in%names(arguments)&sapply(args,is.null))){
cat("Error -> ",names(args)[!names(args)%in%names(arguments)&sapply(args,is.null)]," is not optional!\n")
q("no")
}
for(a in names(args))
if(is.null(arguments[[a]]))
arguments[[a]]<-args[[match(a,names(args))]]
arguments
}
print.args<-function(args,des){
if(missing(des)){
des<-as.list(rep("",length(args)))
names(des)<-names(args)
}
cat("-> Needed arguments:\n")
mapply(function(x)cat("\t",x,":",des[[x]],"\n"),cbind(names(args)[sapply(args,is.null)]))
cat("-> Optional arguments (defaults):\n")
mapply(function(x)cat("\t",x," (",args[[x]],")",":",des[[x]],"\n"),cbind(names(args)[!sapply(args,is.null)]))
q("no")
}
## choose your parameters and defaults
## NULL is an non-optional argument, NA is an optional argument with no default, others are the default arguments
args<-list(file = NA, #single basename of file to analize (does not need the list 'filelist' for multiple files)
fileList = NA, #list of basenames for GUNZIPPED .genolike files
nameList = NA, #bed file to choose chromosomes and sites
useGeno = "yes", #use genotype likelihoods
SNPtrim = "0.1,0.9",
wind = NA, #size of window for depth and genotype likelihoods. we work on a chromosome-basis.
maxPloidy = 4, #maximum ploidy. Must change with choice of potential ploidies (e.g. haploid might be excluded a priori by users)
minInd = 1, #min ind having reads
minDepth=1,
maxDepth=Inf,
chosenInd = NA, #which Individual to consider (one at the time for now)
#Must implement option for: all ind together or one at the time ?
#isSims = FALSE, #data is simulated. if TRUE fileList will also refer to file(s) with true ploidies
truePl = NA, #true ploidy for a ploidy simulation
alpha = NA, #alpha parameters comma separated
beta = NA, #beta parameters comma separated
quantileTrim ="0.02,0.98", #quantiles for trimming
outSuffix = NA,#path + prefix for output filename
eps = .0005 #effect of sequencing and mapping error
)
#if no argument aree given prints the need arguments and the optional ones with default
des<-list(fileList="[string] list of .genolike files",
wind="[integer] Size of window for depth and genotype likelihoods (NA)",
nameList = "[NA] List of names for the samples",
SNPtrim = "[integers] comma-separated freq for SNP trimming (0.1,0.9)",
useGeno = "yes=use genotype likelihoods, otherwise not",
minInd="[integer] min Nr of individuals per locus having data (1)",
minDepth="min average depth per window (1)",
maxDepth="max average depth per window (Inf)",
maxPloidy="[integer] Maximum ploidy allowed (6)", #have to implement case where ploidies are chosen
chosenInd ="[integers] which Individual to consider (NA=all)",
isSims="[bool] data is simulated using the simulation script (FALSE)",
alpha ="[numerics] alpha parameters comma separated (NA, read from .par file)",
beta="[numerics] beta parameters comma separated (NA, read from .par file)",
quantileTrim="[integers] comma-separated quantiles for trimming (0,1)",
eps="sequencing/mapping error rate ",
outSuffix="suffix for the output file (Default: empty name)"
)
##get arguments and add to workspace
##do not change
if(length(l)==0) print.args(args,des)
attach(Args(l,args))
args <- commandArgs(TRUE)
if(length(args)==0){
cat(" Arguments: output prefix\n")
q("no")
}
##read file names from the prefix list and create inputs/outputs
if(is.na(file) & is.na(fileList)){
cat("You MUST input either file= or fileList= when using the R script\n")
q("no")
}
if(!is.na(file))
filez <- file
if(is.na(file))
filez <- unlist( read.table(fileList, header=FALSE, as.is=T) )
angsdVector <- c(); fileVector <- c(); outPdf <- c(); outTxt <- c(); outRate <- c()
BASENAMEFILE <- c();
for(i in 1:length(filez)){
fileVector[i] <- paste(filez[i],".genolikes",sep="")
angsdVector[i] <- paste(filez[i],".mafs",sep="")
splittedName <- unlist(strsplit(filez[i],split="/"))
BASENAMEFILE[i] <- splittedName[length(splittedName)]
outPdf[i] <- paste(filez[i],".pdf",sep="")
if(is.na(outSuffix)){
outTxt[i] <- paste(filez[i],"HMMploidy",sep=".")
outRate[i] <- paste(filez[i],".testRate",sep="")}
if(!is.na(outSuffix)){
outTxt[i] <- paste(filez[i],outSuffix,"HMMploidy",sep=".")
outRate[i] <- paste(filez[i],outSuffix,".testRate",sep="")}
}
##numeric conversion of inputs
if(!is.na(truePl))
truePl = as.numeric(truePl)
wind <- as.numeric(wind)
minInd <- as.numeric(minInd)
maxPloidy <- as.numeric(maxPloidy)
eps <- as.numeric(eps)
#flags
isNumericChosenInd <- all(!is.na(chosenInd)) #check for choice of individuals
##individuals chosen for analysis (one by one at the moment)
##if chosenInd id NA it will be assigned as all individuals later
if(isNumericChosenInd)
chosenInd <- eval( parse( text=paste("c(",chosenInd,")",sep="") ) )
##print Rscript input
cat("----------\nfileList: ", fileList, " wind: ", wind," minInd: ", minInd, " chosenInd: ", chosenInd ," maxPloidy: ", maxPloidy, " alpha: ", alpha, " beta: ", beta, " quantileTrim: ", quantileTrim, " eps: ", eps, "\n-----------\n" )
############################
### Supporting functions ###
############################
hmmPlotting <- function(hmm, V, axLabel=TRUE, truePl=NA, main="Inferred ploidies", propStates, CNV){
options(warn=-1)
loci <- hmm$lociSNP
chrName <- unique(hmm$chrSNP)
chr <- hmm$chrSNP
if(length(chrName)==1)
borderVal <- round( seq(min(loci), max(loci), length.out=min(30,length(V$y)) ) )
if(length(chrName)>1){
lth <- max(2,round(30/length(chrName)))
borderVal <- round( seq(min(loci[chr==chrName[1]]), max(loci[chr==chrName[1]]), length.out=lth ) )
for(nn in chrName[-1])
borderVal <- c(borderVal, round( seq(min(loci[chr==nn]), max(loci[chr==nn]), length.out=lth ) ))
}
xlabels=c()
if(max(loci)>=1e+6){
XLAB="Position (Mb)"
for(i in 1:(length(borderVal)))
xlabels[i] <- sprintf("%.1f", borderVal[i]/(1e+6))
}
if(max(loci)<1e+6){
XLAB="Position (Kb)"
for(i in 1:(length(borderVal)))
xlabels[i] <- sprintf("%.1f", borderVal[i]/(1e+3))
}
layout(matrix(c(1,1,1,1,2,2), nrow = 3, ncol = 2, byrow = TRUE))
oldTruePl <- truePl
if(any(is.na(V$y)))
V$y[is.na(V$y)] = 0
if(is.na(truePl))
truePl <- V$y
plot( x=1:length(c(V$y)) ,c(V$y), pch=15, lwd=.75, col="navyblue", main=main, xaxt="n", yaxt="n", bty="n", ylab="ploidy", xlab=XLAB, ylim=c(min(V$y,truePl)-.5, max(V$y,truePl)+1 ), cex=.75, cex.main=1.4, cex.lab=1.2)
#print(CNV)
#print(V$y[CNV])
#points( x=which(CNV), y = V$y[CNV] -.075 , pch=24, lwd=.75, col='coral', cex=.75)
if(!is.na(oldTruePl))
points( c(truePl)-.075 , pch=15, lwd=.75, col="coral", cex=.75)
abline( h=seq( min(V$y,truePl), max(V$y,truePl) ), col="gray" )
if( length(borderVal)<50 )
axis( side=1, at=seq(1,length(V$y),length.out=length(borderVal)), labels=xlabels, las=2, cex=.8 )
axis( side=2, at=seq(min(V$y), max(V$y)) )
postProb <- hmm$postprob
counter=1
for(yValue in intersect(hmm$states,seq(min(V$y,truePl), max(V$y,truePl)))){
polygon( x=c( length(V$y),1, seq(1,length(V$y)), length(V$y) ), y= yValue + 0.025 + c( 0, 0, postProb[,counter], 0 )/2, col="deepskyblue1", border=NA)
lines( x=c(length(V$y)+.4,length(V$y)+.4), y=c(yValue+.025,yValue+0.525), col="deepskyblue1" )
text(labels="0", x=length(V$y)+.4, y=yValue-.1)
text(labels="1", x=length(V$y)+.4, y=yValue+.6)
mtext(text=rep("Posterior",length(yValue)), side=4, at=yValue+.25, cex=.6)
lines( x=rep(length(V$y)+1,2), y=c(yValue+.025,yValue+propStates[counter]/2), col="deepskyblue1", lwd=6 )
counter=counter+1
}
legendCol = c("navyblue","deepskyblue1")
legendPch = c(15,NA)
legendTxt = c( "Inferred Ploidy", "Posterior Prob.")
if(is.null(truePl)){
legendCol = c("navyblue","deepskyblue1")
legendPch = c(15,NA)
legendTxt = c( "Inferred Ploidy", "Posterior Prob.")
}
legend(x=1, y = max(V$y,truePl)+1, legend=legendTxt, col = legendCol, lwd = c(NA,10,NA), pch = legendPch, bty = "n", ncol = length(legendPch), cex=1.4)
##PLOT DEPTH
plot(hmm$count[,1], type="p", lwd=2, col="deepskyblue1", xlab=XLAB, main="Window-Mean Depth", xaxt="n", ylab="depth", bg=3, ylim=c(min(hmm$count[,1])-.1*min(hmm$count[,1]),max(hmm$count[,1])+.2*max(hmm$count[,1])), cex.lab=1.2, cex.main=1.3)
if( length(borderVal)<50 )
axis( side=1, at=seq(1,length(V$y),length.out=length(borderVal)), labels=xlabels, las=2, cex=1 )
abline(h=hmm$mu, col="coral")
legend(x=1, y = max(hmm$count[,1])+.25*max(hmm$count[,1]), legend=c("Mean Depth", "Neg.Bin. Mean"), col = c("deepskyblue1","coral"), lwd = rep(3,3), lty=c(NA,1), pch = c(20,NA), bty = "n", ncol = 2, cex=1.4)
options(warn=0)
}
cppFunction('NumericVector alleleFrequencies(NumericVector major, NumericVector minor, int nInd, int minInd, double eps){
int totCountsNorm = 0;
int sites = major.size()/nInd;
NumericVector out( sites );
int indWithData;
NumericVector pis( nInd );
NumericVector wis( nInd );
int ni = 0;
int nt = 0;
int normC;
for(int s=0;s<sites;s++){
totCountsNorm = 0;
indWithData = nInd;
normC = 0;
for(int i=0;i<nInd;i++){
totCountsNorm += major[s*nInd+i] + minor[s*nInd+i];
}
//if the site is variable
for(int i=0;i<nInd;i++){
ni = minor[s*nInd+i];
nt = major[s*nInd+i] + minor[s*nInd+i];
if(nt==0){//if we dont have any reads for individual i
indWithData--;
pis[i] = 0;
wis[i] = 0;
continue;
}
pis[i] = (ni-eps*nt)/(nt*(1-2*eps));
wis[i] = (double)nt/totCountsNorm; //weights infinite ploidy
}
if(indWithData < minInd){
out[s] = -1;
}
else{
out[s] = 0;
for(int i=0;i<nInd;i++)
out[s] += wis[i]*pis[i];
}
}
return(out);
}'
)
# nbh_init Initalize parameters for nbh_em
# Function nbm_em (NB mixture model) is used to find alpha,
# beta, and wght (mixprop); wght (1xN) is repeated N times row-wise
# to represent the initial TRANS for the subsequent nbh_em training
# Use: nbh0 <- nbh_init(count, K)
# nbh0: list(TRANS, alpha, beta)
nbm_em <- function(count, alpha, beta, wght, NBM_NIT_MAX=250, NBM_TOL=1e-2){
# Data length
Total <- length(count)
count <- matrix(count, nrow=Total, 1)
# Number of mixture components
N <- length(alpha)
wght <- matrix(wght, 1, N)
alpha <- matrix(alpha, 1, N)
beta <- matrix(beta, 1, N)
# Save initial alpha and beta in case error occurs in the first EM
wght0 <- wght
alpha0 <- alpha
beta0 <- beta
# Compute log(count!), the second solution is usually much faster
# except if max(count) is very large
cm <- max(count)
if(cm > 50000){
dnorm <- as.matrix(lgamma(count + 1))
} else {
tmp <- cumsum(rbind(0, log(as.matrix(1:max(count)))))
dnorm <- as.matrix(tmp[count+1])
}
# Variables
logl <- matrix(0, ncol=NBM_NIT_MAX)
postprob <- matrix(0, Total, N)
# Main loop of the EM algorithm
for(nit in 1:NBM_NIT_MAX){
# 1: E-Step, compute density values
postprob <- exp( matrix(1, nrow=Total) %*% (alpha * log(beta/(1+beta)) - lgamma(alpha))
- count %*% log(1+beta) + lgamma(count %*% matrix(1, ncol=N) + matrix(1, nrow=Total) %*% alpha)
- dnorm %*% matrix(1, ncol=N) )
# set zero value to the minimum double to avoid -inf when applying log
# due to large dnorm (or essential large count)
postprob <- apply(postprob, 2, function(x) {x[x==0] <- .Machine$double.xmin; x})
postprob <- postprob * (matrix(1, Total, 1) %*% wght)
# Compute log-likelihood
logl[nit] <- sum(log(apply(postprob, 1, sum)))
postprob <- postprob / (apply(postprob, 1, sum) %*% matrix(1, ncol=N))
# 4: M-Step, reestimation of the mixture weights
wght <- apply(postprob, 2, sum)
wght <- wght / sum(wght)
# 5: CM-Step 1, reestimation of the inverse scales beta with alpha fixed
eq_count <- apply(postprob, 2, sum)
mu <- (t(count) %*% postprob) / eq_count
beta <- alpha / mu
# 5: CM-Step 2, reestimation of the shape parameters with beta fixed
# Use digamma and trigamma function to perfom a Newton step on
# the part of the intermediate quantity of EM that depends on alpha
# Compute first derivative for all components
# Use a Newton step for updating alpha
# Compute first derivative
grad <- eq_count * (log(beta / (1+beta)) - digamma(alpha)) +
apply(postprob * digamma(count %*% matrix(1,ncol=N) +
matrix(1,nrow=Total) %*% alpha), 2, sum)
# and second derivative
hess <- -eq_count * trigamma(alpha) +
apply(postprob * trigamma(count %*% matrix(1,ncol=N) +
matrix(1, nrow=Total) %*% alpha), 2, sum)
# Newton step
tmp_step <- - grad / hess
tmp <- alpha + tmp_step
# erroneous update occurs, give up and return the previous trained parameters
if(any(is.na(tmp))) {
warning("Updated alpha becomes NA probably due to bad initial alpha or insuff. data")
return(list(wght=wght0, alpha=alpha0, beta=beta0,
logl=logl, postprob=postprob))
}
# When performing the Newton step, one should check that the intermediate
# quantity of EM indeed increases and that alpha does not become negative. In
# practise this is almost never needed but the code below may help in some
# cases (when using real bad initialization values for the parameters for
# instance)
while (any(tmp <= 0)){
warning(sprintf("Alpha (%.4f) became negative! Try smaller (10%s) Newton step ...\n", tmp_step,"%"))
tmp_step <- tmp_step/10
tmp <- alpha + tmp_step
}
alpha <- tmp
# stop iteration if improvement in logl is less than TOL (default 10^-5)
if(nit > 1 && abs((logl[nit] - logl[nit-1])/logl[nit-1]) < NBM_TOL){
logl <- logl[1:nit]
break
}
}
list(wght=wght, alpha=alpha, beta=beta,
logl=logl, postprob=postprob)
}
##Estep for the conditional EM optimization
EStep <- function(count,delta,TRANS,alpha,beta,genolike){
N <- nrow(TRANS)
Total <- dim(count)[1]
forwrd <- matrix(0, Total, N)
forwrd2 <- matrix(0, Total, N)
bckwrd <- matrix(0, Total, N)
bckwrd2 <- matrix(0, Total, N)
dens <- matrix(0, Total, N)
scale <- rbind(1, matrix(0, nrow=Total-1))
scale2 <- rbind(1, matrix(0, nrow=Total-1))
cm <- max(count)
if(cm > 50000){
dnorm <- as.matrix(lgamma(count + 1))
} else {
tmp <- cumsum(rbind(0, log(as.matrix(1:max(count)))))
dnorm <- as.matrix(tmp[count+1])
}
densLog <- matrix(1, nrow=Total) %*% (alpha * log(beta/(1+beta)) - lgamma(alpha)) - count %*% log(1+beta) + lgamma(count %*% matrix(1, ncol=N) + matrix(1, nrow=Total) %*% alpha) - dnorm %*% matrix(1, ncol=N)
dens2 <- matrix(0,nrow=nrow(densLog),ncol=dim(genolike)[2])
for(ii in 1:dim(genolike)[2]) dens2[,ii] <- densLog[,ii] + genolike[,ii]
dens2 <- exp( dens2 )
dens2 <- apply(dens2, 2, function(x) {x[x==0 | is.na(x) | is.nan(x)] <- .Machine$double.xmin; x})
forwrd2[1,] <- delta*dens2[1,]
for(t in 2:Total){
forwrd2[t,] <- (forwrd2[t-1,] %*% TRANS) * dens2[t,]
scale2[t] <- sum(forwrd2[t,])
forwrd2[t,] <- forwrd2[t,] / scale2[t]
}
llk <- log(sum(forwrd2[Total,])) + sum(log(scale2))
bckwrd2[Total,] <- matrix(1, ncol=N)
for(t in (Total-1):1) {
bckwrd2[t,] <- (bckwrd2[t+1,] * dens2[t+1,]) %*% t(TRANS)
bckwrd2[t,] <- bckwrd2[t,] / scale2[t]
}
bckwrd2[ is.nan(bckwrd2) | is.infinite(bckwrd2) | is.na(bckwrd2)] = .0001
forwrd2[ is.nan(forwrd2) | is.infinite(forwrd2) | is.na(forwrd2)] = .0001
ni <- forwrd2 * bckwrd2
ni <- ni / ( apply(ni, 1, sum) %*% matrix(1,ncol=N) )
return(list(forwrd=forwrd,bckwrd=bckwrd,ni=ni,llk=llk,dens=dens,forwrd2=forwrd2,bckwrd2=bckwrd2,dens2=dens2))
}
##Mstep for the conditional EM optimization
MStep <- function(E,count,TRANS,alpha,beta){
remStates = FALSE
N <- nrow(TRANS)
Total <- dim(count)[1]
bckwrd <- E$bckwrd; bckwrd2 <- E$bckwrd2
forwrd <- E$forwrd; forwrd2 <- E$forwrd2
ni <- E$ni
dens <- E$dens; dens2 <- E$dens2
TRANS0=TRANS
delta <- ni[1,]
TRANS <- TRANS * (t(forwrd2[1:(Total-1),]) %*% (dens2[2:Total,] * bckwrd2[2:Total,]))
TRANS <- TRANS / (apply(TRANS, 1, sum) %*% matrix(1,ncol=N))
for(j in 1:nrow(TRANS)){
if(sum(is.nan(TRANS[j,]))>1){
remStates = TRUE
break;
}
}
if(remStates)
return(list(delta=delta,TRANS=TRANS0,alpha=alpha,beta=beta,remStates=remStates))
eq_count <- apply(ni, 2, sum)
beta <- alpha / ( (t(count) %*% ni) / eq_count )
grad <- eq_count * (log(beta / (1+beta)) - digamma(alpha)) + apply(ni * digamma(count %*% matrix(1,ncol=N) + matrix(1,nrow=Total) %*% alpha), 2, sum)
hess <- -eq_count * trigamma(alpha) + apply(ni * trigamma(count %*% matrix(1,ncol=N) + matrix(1, nrow=Total) %*% alpha), 2, sum)
tmp_step <- - grad / hess
tmp <- alpha + tmp_step
if(any(is.na(tmp)))
return(list(delta=delta,TRANS=TRANS,alpha=alpha,beta=beta,remStates=remStates))
countTooMany <- 1
while (any(tmp <= 0) & countTooMany<50){
warning(sprintf("Alpha (%.4f)<0 ! Try smaller (10%s) Newton step ...\n", tmp_step,"%"))
tmp_step <- tmp_step/10
tmp <- alpha + tmp_step
countTooMany <- countTooMany + 1
}
alpha <- tmp
return(list(delta=delta,TRANS=TRANS,alpha=alpha,beta=beta,remStates=remStates))
}
##EM algorithm for HMM optimization
nbHMM <- function(count, delta, TRANS, alpha, beta, genolike=0, ws=1, PLOIDYMAX=maxPloidy, NBH_NIT_MAX=10000, NBH_TOL=1e-5, MAXALPHA=1e7, MAXBETA=1e7, keepStates=NULL){
L <- length(delta)
stateVec <- 1:PLOIDYMAX
if(!is.null(keepStates))
stateVec <- keepStates
geno <- matrix(genolike[,stateVec], ncol=L)
bicIter <- 0
Total <- dim(count)[1]
if(any(count < 0)) stop("Data contains values <0")
N <- nrow(TRANS)
alpha <- matrix(alpha, 1, N)
beta <- matrix(beta, 1, N)
logl <- matrix(0, ncol=NBH_NIT_MAX)
alpha0 <- alpha
beta0 <- beta
TRANS0 <- TRANS
postprob0 <- matrix(1, Total, N)/N
logl0 <- logl
dens0 <- matrix(0, Total, N)
rate <- +Inf
checkBIC <- TRUE
##Main loop of the EM algorithm
for(nit in 1:NBH_NIT_MAX) {
bicIter <- bicIter + 1
##check after some steps for some convergence and try to remove 1 state
if(rate<=.0001 && bicIter>=30 && checkBIC && length(alpha)>1){
if(length(alpha)==2){ #if removing one state leaves only one ploidy
alpha=matrix(alpha,ncol=length(alpha))
beta=matrix(beta,ncol=length(beta))
cat("\t==>reduction to 1 state start\n")
compLL <- c()
LLtest <- c()
for(kk in 1:length(stateVec)){#try out one state at a time
diff <- +Inf
contDiff <- 0
gg <- geno[,kk]
aa <- alpha[,kk]; aa <- matrix(aa,ncol=length(aa))
bb <- beta[,kk]; bb <- matrix(bb,ncol=length(bb))
nanFlag <- FALSE
while(diff >= 0.0001 & contDiff < 150){
contDiff <- contDiff + 1
resSingle1 <- MStepSingle(count,aa,bb,gg)
llk1 <- resSingle1$llk
if(is.nan(llk1)){
nanFlag=TRUE
break
}
aa <- resSingle1$alpha
bb <- resSingle1$beta
contDiff <- contDiff + 1
resSingle2 <- MStepSingle(count,aa,bb,gg)
llk2 <- resSingle2$llk
if(is.nan(llk2)){
nanFlag=TRUE
break
}
aa <- resSingle2$alpha
bb <- resSingle2$beta
diff <- abs( (llk1 - llk2)/llk1 )
}
if(nanFlag==TRUE)
compLL <- c( compLL, -Inf )#models' AIC
if(nanFlag==FALSE)
compLL <- c( compLL, 2*llk2 )#models' AIC
}
compLL[is.nan(compLL)] = min(compLL[!is.nan(compLL)]) - 1
diff=+Inf
LLtestOld=c(+Inf,+Inf)
contDiff <- 0
nanFlag=FALSE
##get the AIC using 2 states
while(diff >= 0.0001 & contDiff < 150){
contDiff = contDiff + 1
E1 <- EStep(count,delta,TRANS,alpha,beta,geno)
if(is.nan(E1$llk)){
nanFlag=TRUE
break
}
LLtestOld[1] <- E$llk
M1 <- MStep(E1,count,TRANS,alpha,beta)
E2 <- EStep(count,M1$delta,M1$TRANS,M1$alpha,M1$beta,geno)
if(is.nan(E2$llk)){
nanFlag=TRUE
break
}
LLtestOld[2] <- E2$llk
M2 <- MStep(E2,count,M1$TRANS,M1$alpha,M1$beta)
TRANS <- M2$TRANS; alpha <- M2$alpha; beta <- M2$beta
diff <- abs( (LLtestOld[1] - LLtestOld[2])/LLtestOld[1] )
if(is.nan(diff))
diff=0
}
K <- length(alpha)
if(nanFlag==TRUE)
oldBIC <- -Inf
if(nanFlag==FALSE)
oldBIC <- 2*E2$llk - 2*((K+1)*K - 1)
newBIC <- max(compLL)
whichBIC <- which.max( compLL )
if(is.nan(newBIC))
newBIC <- -Inf
#cat("\tBest new BIC ", newBIC," old BIC", oldBIC, "reduce states ", (newBIC>oldBIC), "\n")
cat("\t reduce states:", (newBIC>oldBIC), "\t",sep="")
if(oldBIC > newBIC){
checkBIC <- FALSE
cat("States: ", stateVec,"\n")
break
}
else{
geno <- geno[,whichBIC ]
alpha <- alpha[,whichBIC]
beta <- beta[,whichBIC]
stateVec <- stateVec[ whichBIC ]
bckwrd <- matrix(1,nrow(count),1)
TRANS <- matrix(TRANS[whichBIC, whichBIC], 1, 1)
}
cat("States: ", stateVec,"\n")
#cat("\talpha: ", alpha, " beta: ", beta," mu: ", alpha/beta, "\n")
break
}
alpha <- matrix(alpha,ncol=length(alpha))
beta <- matrix(beta,ncol=length(beta))
K <- dim(alpha)[2]
##if removing one state leaves at least other two, then what follows will happen
#cat("\t==>reduction to ",K-1,"states start\n\t\talpha: ", as.vector(alpha),"\n\t\tbeta: ",as.vector(beta),"\n",sep=" ")
cat("\t==>reduction to ",K-1,"states start\n")
bicIter <- 0
viterbiIter <- 0
combMat <- combs( 1:K, K-1 )
#sortIdx <- apply(combMat,1,is.sorted)
#combIdx <- which(sortIdx)#
combIdx <- 1:(dim(combMat)[1])
compLL <- c()
Lcomb = length(combIdx)
TRANS2 <- TRANS; delta2 <- delta; alpha2 <- alpha; beta2 <- beta; geno2 <- geno;
##try each combination of states and genotype likelihoods on ploidies
for( kk1 in combIdx ){
for( kk2 in combIdx ){
geno <- geno2[ ,combMat[kk1,] ]
delta <- delta2[ combMat[kk2,] ]
alpha <- matrix(alpha2[ ,combMat[kk2,] ], nrow=1)
beta <- matrix(beta2[ ,combMat[kk2,] ], nrow=1)
diff=+Inf
LLtest=c(+Inf,+Inf)
#cat("states: ",stateVec[ combMat[kk1,] ]," -- ","alpha: ",alpha," beta: ",beta,"\n",sep="")
TRANS <- TRANS2[ combMat[kk2,], ]
TRANS <- TRANS[ ,combMat[kk2,] ]
contDiff = 0
nanFlag=FALSE
#optimize when one state is removed and get the AIC.
#nan check useful for messy real data.
while(diff >= 0.001 & contDiff < 250){
contDiff = contDiff + 1
E1 <- EStep(count,delta,TRANS,alpha,beta,geno)
if(is.nan(E1$llk)){
nanFlag=TRUE
break
}
LLtest[1] <- E$llk
M1 <- MStep(E1,count,TRANS,alpha,beta)
E2 <- EStep(count,M1$delta,M1$TRANS,M1$alpha,M1$beta,geno)
if(is.nan(E2$llk)){
nanFlag=TRUE
break
}
LLtest[2] <- E2$llk
M2 <- MStep(E2,count,M1$TRANS,M1$alpha,M1$beta)
TRANS <- M2$TRANS; alpha <- M2$alpha; beta <- M2$beta
diff <- abs( (LLtest[1] - LLtest[2])/LLtest[1] )
if(is.nan(diff))
diff=0
contDiff = contDiff+1
}
if(nanFlag==TRUE)
compLL <- c( compLL, -Inf )
if(nanFlag==FALSE)
compLL <- c( compLL, 2*E2$llk - ((K-1)*K - 1)*2 )
geno <- geno2
delta <- delta2
alpha <- alpha2
TRANS <- TRANS2
}
}
compLL[is.nan(compLL)] = min(compLL[!is.nan(compLL)]) - 1
geno <- geno2
delta <- delta2
alpha <- alpha2
beta <- beta2
diff=+Inf
LLtestOld=c(+Inf,+Inf)
contDiff <- 0
while(diff >= 0.0001 & contDiff < 250){
contDiff = contDiff + 1
E1 <- EStep(count,delta,TRANS,alpha,beta,geno)
if(is.nan(E1$llk))
break
LLtestOld[1] <- E$llk
M1 <- MStep(E1,count,TRANS,alpha,beta)
E2 <- EStep(count,M1$delta,M1$TRANS,M1$alpha,M1$beta,geno)
if(is.nan(E2$llk))
break
LLtestOld[2] <- E2$llk
M2 <- MStep(E2,count,M1$TRANS,M1$alpha,M1$beta)
TRANS <- M2$TRANS; alpha <- M2$alpha; beta <- M2$beta
diff <- abs( (LLtest[1] - LLtest[2])/LLtest[1] )
if(is.nan(diff))
diff=0
}
oldBIC <- 2*E2$llk - 2*((K+1)*K - 1)
newBIC <- max(compLL)
whichBIC <- which.max( compLL )
if(is.nan(newBIC))
newBIC <- -Inf
if(is.nan(oldBIC))
oldBIC <- -Inf
#cat("\t\tBest new BIC ", newBIC," old BIC", oldBIC, "reduce states:", (newBIC>oldBIC), "\n")
cat("\t reduce states:", (newBIC>oldBIC), "\t",sep="")
if(oldBIC > newBIC){
checkBIC <- FALSE
delta <- delta2
TRANS <- TRANS2
alpha <- alpha2
beta <- beta2
geno <- geno2
}
else{
comb1 <- whichBIC %/% Lcomb + 1
comb2 <- whichBIC %% Lcomb
if( (whichBIC %% Lcomb) == 0 )
comb1 = (comb1-1)
if( comb2==0 )
comb2 = Lcomb
geno <- geno2[ ,combMat[combIdx[comb1],] ]
if( (K-1) > 1){
delta <- delta2[ combMat[ combIdx[comb2] ,] ]
TRANS <- TRANS2[ combMat[combIdx[comb2],], ]
TRANS <- TRANS[ ,combMat[combIdx[comb2],] ]
}
alpha <- alpha2[ ,combMat[combIdx[comb2],] ]
beta <- beta2[ ,combMat[combIdx[comb2],] ]
stateVec <- stateVec[ combMat[combIdx[comb1],] ]
sortIdx <- sort(alpha/beta, index.return=TRUE)$ix
alpha=alpha[sortIdx]
beta=beta[sortIdx]
}
cat("States Relation : ", stateVec,"\n")
#cat("\t==>alpha: ", alpha, "\n\t\tbeta: ", beta, "\n\t\tmu: ", alpha/beta, "\n")
#alpha <- matrix(alpha,ncol=length(alpha))
}
N <- nrow(TRANS)
E <- EStep(count,delta,TRANS,alpha,beta,geno)
logl[nit] <- E$llk
#message( sprintf( 'Iter %d:\tLLK=%.3f\tploidies=%d', (nit-1), logl[nit], dim(alpha)[2] ) )
if(is.nan(logl[nit])) {
warning("NaN logl data detected. Returning the previous training results")
logl[nit] <- 0; TRANS=TRANS0; alpha=alpha0; beta=beta0; logl=logl0; bckwrd=postprob0; dens=dens0
#break
}
M <- MStep(E,count,TRANS,alpha,beta)
alphaPrev <- alpha #backup
betaPrev <- beta
TRANSprev <- TRANS
deltaPrev <- delta
TRANS <- M$TRANS #new values
alpha <- M$alpha
beta <- M$beta
bckwrd <- E$ni
dens <- E$dens2
delta <- M$delta
if(any(is.na(M$alpha))) {
warning(sprintf("Updated alpha becomes NA probably %s","due to bad initial alpha or insuff. data"))
return(list(count=count, delta=deltaPrev, TRANS=TRANSprev, alpha=alphaPrev, beta=betaPrev, logl=logl, postprob=bckwrd, dens=dens, mu = alphaPrev/betaPrev, sigma=alphaPrev/betaPrev+alphaPrev/betaPrev^2, states=stateVec) )
}
if(any(is.na(M$beta))) {
warning(sprintf("Updated beta becomes NA probably %s","due to bad initial alpha orE$dens2 insuff. data"))
return(list(count=count, delta=deltaPrev, TRANS=TRANSprev, alpha=alphaPrev, beta=betaPrev, logl=logl, postprob=bckwrd, dens=dens, mu = alphaPrev/betaPrev, sigma=alphaPrev/betaPrev+alphaPrev/betaPrev^2, states=stateVec) )
}
if(any(M$alpha > MAXALPHA) || any(M$beta > MAXBETA)) {
warning(sprintf("Updated alpha (%f) or beta (%f) becomes too large probably %s",alpha, beta, "due to bad initial alpha or large count"))
TRANS=TRANS0; alpha=alpha0; beta=beta0; logl=logl0; bckwrd=postprob0; dens=dens0
break
}
############ Check END ############
if(nit > 1)
if(logl[nit] < logl[nit-1])
bicIter <- 30
rate <- abs((logl[nit] - logl[nit-1])/logl[nit-1])
if(nit > 1 && rate < NBH_TOL && !checkBIC){
logl <- logl[1:nit]
break
}
TRANS0 <- TRANS
alpha0 <- alpha
beta0 <- beta
postprob0 <- bckwrd
dens0 <- dens
logl0 <- logl
}
list(count=count, delta=delta, TRANS=TRANS, alpha=alpha, beta=beta, logl=logl[logl<0], postprob=bckwrd, dens=dens, mu = alpha/beta, sigma=alpha/beta+alpha/beta^2, states=stateVec, geno=geno)
}
MStepSingle <- function(count,alpha,beta,geno){
N <- 1
Total <- dim(count)[1]
bckwrd <- rep(1,Total)
forwrd <- rep(1,Total)
ni <- rep(1,Total)
dens <- matrix(0, Total, N)
scale <- rbind(1, matrix(0, nrow=Total-1))
cm <- max(count)
if(cm > 50000){
dnorm <- as.matrix(lgamma(count + 1))
} else {
tmp <- cumsum(rbind(0, log(as.matrix(1:max(count)))))
dnorm <- as.matrix(tmp[count+1])
}
densLog <- matrix(1, nrow=Total) %*% (alpha * log(beta/(1+beta)) - lgamma(alpha)) - count %*% log(1+beta) + lgamma(count + matrix(1,nrow=Total) %*% alpha) - dnorm + geno
dens <- exp( densLog )
dens <- apply(dens, 2, function(x) {x[x==0 | is.na(x) | is.nan(x)] <- .Machine$double.xmin; x})
delta <- 1
TRANS <- 1
eq_count <- sum(ni)
beta <- alpha / ( sum(count) / eq_count)
grad <- eq_count * (log(beta / (1+beta)) - digamma(alpha)) + apply(ni * digamma(count %*% matrix(1,ncol=N) + matrix(1,nrow=Total) %*% alpha), 2, sum)
hess <- -eq_count * trigamma(alpha) + apply(ni * trigamma(count %*% matrix(1,ncol=N) + matrix(1, nrow=Total) %*% alpha), 2, sum)
tmp_step <- - grad / hess
tmp <- alpha + tmp_step
if(any(is.na(tmp)))
return(list(delta=delta,TRANS=TRANS,alpha=alpha,beta=beta,llk=NaN))
while (any(tmp <= 0)){
warning(sprintf("Alpha (%.4f)<0 ! Try smaller (10%s) Newton step ...\n", tmp_step,"%"))
tmp_step <- tmp_step/10
tmp <- alpha + tmp_step
}
alpha <- tmp
return(list(delta=1,TRANS=1,alpha=alpha,beta=beta,llk=sum(densLog)))
}
##logarithmic normalization of a vector
logRescale <- function(v){
L <- length(v)
m <- max(v)
w <- which.max(v)
diffVec <- v[-w] - m
if(any(diffVec < -700)){
idx <- which(diffVec < -700)
tooSmall <- diffVec[idx]
sortVec <- sort(tooSmall, index.return=TRUE)
rescaled <- seq(-700, -800, length.out=length(tooSmall))
tooSmall[sortVec$ix] <- rescaled
diffVec[idx] <- tooSmall
}
res <- m + log( 1 + sum( exp( diffVec ) ) )
return( v - res )
}
##sum of values in a windows. When lociSNP=loci all values in the windows are used.
##avg=TRUE performs average instead of sum. ws=window size and dp=vector of data.
sumGeno <- function(dp,ws,loci,lociSNP=loci,findSNP=1:length(loci),avg=FALSE){ #useless?
L <- length(dp)
S <- seq(loci[1],loci[length(loci)],ws)
S <- c(S, loci[length(loci)] )
res <- sapply(1:(length(S)-1), function(ll){
if(ll<(length(S)-1))
idx <- which(lociSNP>=S[ll] & lociSNP<S[ll+1])
if(ll==(length(S)-1))
idx <- which(lociSNP>=S[ll] & lociSNP<=S[ll+1])
if(length(idx)==0)
return(c())
v <- dp[idx]
if(!avg)
return( median( v ) )
if(avg)
return( mean(v) )
})
return(unlist(res))
}
sumGenoAll <- function(dp,ws=1,loci,lociSNP=loci,avg=FALSE){ #useless?
L <- length(dp)
S <- c( seq(loci[1],loci[length(loci)-1],ws), loci[length(loci)] )
res <- sapply(1:(length(S)-1), function(ll){
idx <- which(lociSNP>S[ll] & lociSNP<S[ll+1])
v <- dp[idx]
if(!avg)
return( sum( v ) )
if(avg)
return( mean(v) )
})
return(res)
}
#########WINDOWIZED FUNCTIONS
sumGeno <- function(g,wind,lociSNP){ #at least a SNP is present in each window with our windowBuilder function
L <- length(g)
res <- sapply(1:dim(wind)[1], function(ll){
idx <- which(lociSNP>=wind[ll,1] & lociSNP<=wind[ll,2])
v <- g[idx]
return( sum(v, na.rm=TRUE) )
})
return(res)
}
meanGeno <- function(dp,wind,loci){ #NO SNPS USED ON DEPTH AVERAGE
L <- length(dp)
res <- sapply(1:dim(wind)[1], function(ll){
idx <- which(loci>=wind[ll,1] & loci<=wind[ll,2])
v <- dp[idx]
return( mean(v, na.rm=TRUE) )
})
return(res)
}
windowsBuilder <- function(minSize, loci, lociSNP){ #do windows and merge them when one is empty
if(length(loci)>2)
S <- c( seq(loci[1], loci[length(loci)-1], minSize), loci[length(loci)] )
if(length(loci)==2)
S <- c( loci[1], loci[2] )
if( max(loci) - min(loci) < minSize)
S <- c( min(loci), max(loci) )
res <- sapply(1:(length(S)-1), function(ll){
idx <- which(lociSNP>S[ll] & lociSNP<=S[ll+1])
if(length(idx)==0 && ll<(length(S)-1))
return(ll+1)
if(length(idx)==0 && ll==(length(S)-1))
return(ll)