-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFinestructureLibrary.R
executable file
·2122 lines (1938 loc) · 70.1 KB
/
FinestructureLibrary.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
##################################################################
## Finestructure R Library
## Author: Daniel Lawson ([email protected])
## For more details see www.paintmychromosomes.com ("R Library" page)
## Date: 04/12/2016
## Notes:
## These functions are provided for help working with fineSTRUCTURE output files
## but are not a fully fledged R package for a reason: they are not robust
## and may be expected to work only in some very specific cases! USE WITH CAUTION!
## SEE FinestrictureExample.R FOR USAGE
##
## Licence: GPL V3
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## THESE ARE REQUIRED LIBRARIES
require(ape)
require(XML)
################################################
## Beginning of functions
## Standard data file reading
readIds<-function(idfile){
## Reads a chromopainter ID table
read.table(idfile,as.is=T)
}
makeMap<-function(ids){
## Makes a map between individual IDs and standardized population-based IDs, which are guaranteed to be unique and play well with the finestructurelibrary.
labelmap<-list()
for(i in 1:dim(ids)[1]) labelmap[[ids[i,1]]] <-paste0(ids[i,2],i)
}
readCP<-function(dataroot,lengths=TRUE,norm=FALSE,
relabelx=function(x)x,
relabely=relabelx,ending=NULL){
## Read a chromopainter output file, either lengths or chunkcounts.
## norm : whether to normalise the rows to have sum 1
## relabelx,y: a function to map to standardized labels. function(x)labelmap[[x]] is a good choice.
if(lengths){
if(is.null(ending)) ending<-".chunklengths.out"
skip=0
}else{
if(is.null(ending)) ending<-".chunkcounts.out"
skip=1
}
datafile=paste0(dataroot,ending)
dataraw<-as.matrix(read.table(datafile,row.names=1,header=T,skip=skip))
rownames(dataraw)<-sapply(rownames(dataraw),relabelx)
colnames(dataraw)<-sapply(colnames(dataraw),relabely)
if(norm) dataraw<-dataraw/rowSums(dataraw)
dataraw
}
readAdmix<-function(admixfile,ids=NULL,row.names=NULL,header=FALSE,relabelx=function(x)x,sep=" "){
## Read an admixture output file
## optionally rename to the first column of ids
## optionally relabel with a relabelling function
if(is.null(row.names)) admixres<-as.matrix(read.table(admixfile,header=header,
sep=sep))
else admixres<-as.matrix(read.table(admixfile,header=header,
row.names=row.names,sep=sep))
if(!is.null(ids)) rownames(admixres)<-ids[,1]
rownames(admixres)<-sapply(rownames(admixres),relabelx)
admixres
}
########################
## XML reading
simplelabels<-function(x,labmode="mcmc",oneminus=TRUE){
## Utility function for tree extraction
if(x=="")return("");
if(labmode=="mcmc"){
x<-strsplit(x,"-")[[1]][1];
}else if (labmode=="pop"){
x<-strsplit(x,"-")[[1]];
if(length(x)>1){ x<-x[2] }else {return("")}
}else {return(x);}
if(oneminus){return(1-as.numeric(x))}
return(as.numeric(x))
}
extractTree<-function(txml,labmode="mcmc",oneminus=TRUE,hidecertain=FALSE){
## extracts the tree from the MAP/Tree file xml
tmptree<-txml$doc$children$outputFile[[length(txml$doc$children$outputFile)]]
t<-read.tree(text=xmlValue(tmptree))
t$node.label<-as.vector(sapply(t$node.label,simplelabels,labmode=labmode,oneminus=oneminus))
if(hidecertain) t$node.label[which(t$node.label=="1")]<-""
return(t)
}
extractPop<-function(txml){# ONLY for iterationless outputfiles, such as the MAP/Tree file
## (for extracting states from iterations, use extractValue)
as.character(xmlChildren(txml$doc$children$Pop)$text)[6]
}
getV<-function(it,v){
## extract element v from iteration it
return(xmlValue(xmlChildren(it)[[v]]))
}
extractValue<-function(txml,v,getNames=FALSE){
## Important utility function for extracting element v from the xml
tmpits<-txml$doc$children$outputFile[which(names(txml$doc$children$outputFile)=="Iteration")]
if(getNames) num<-sapply(tmpits,getV,v="Number")
res<-sapply(tmpits,getV,v=v)
if(!getNames) names(res)<-NULL
else names(res)<-num
return(res)
}
as.data.frame.myres<-function(txml){
## Converts our xml file format into a matrix, one row per iteration
tmpits<-txml$doc$children$outputFile[which(names(txml$doc$children$outputFile)=="Iteration")]
# xmlChildren(tmpits[[1]])
cnames<-names(tmpits[[1]])
res<-as.data.frame(matrix(nrow=length(tmpits),ncol=length(cnames)))
for(i in 1:length(cnames)) {
res[,i]<-extractValue(txml,cnames[i])
}
colnames(res)<-cnames
res[,which(!names(res) %in% c("Pop","P","Q"))] <-apply(res[,which(!names(res) %in% c("Pop","P","Q"))],2,as.numeric)
res
}
popAsList<-function(s) {
## convert bracketed population string into population list
s<-gsub(")","",s)
s<-strsplit(s,c("(",")"),fixed=TRUE)[[1]]
s<-s[sapply(s,nchar)>0]
sapply(s,strsplit,",",fixed=TRUE)
}
popCor<-function(pop1,pop2){ ## Correlation between discrete states (individuals contained in populations)
# ((sum(sapply(pop1,function(x){x %in% pop2})) + sum(sapply(pop2,function(x){x %in% pop1})))/(length(pop1)+length(pop2)))^2
m<-sum(sapply(pop1,function(x){x %in% pop2}))
(m/(length(pop1)+length(pop2)-m))^2
}
popCorAd<-function(pop1,pop2){ ## Correlation between admixture states (vectors of probabilities)
m<-sum(pop1* pop2)
(m/(sum(pop1)+sum(pop2)-m))^2
}
popCorMat<-function(state1,state2,fn="popCor"){
## correlation matrix of the populations between two states
if(fn=="popCor") {
r<-sapply(state1,function(x){sapply(state2,popCor,x)})
}else if(fn=="popCorAd"){
r<-apply(state1,2,function(x){apply(state2,2,fn,x)})
}else{
stop("Unimplemented population comparison function")
}
dimnames(r)<-NULL
r
}
popCorMatDiag<-function(state1,state2,fn="popCor"){
## diagonalise the population correlation matrix by finding the best population for each
#rmat<-popCorMat(state2,state1) # do it this way around to allow state2 to be a "reference state"
rmat<-popCorMat(state1,state2,fn=fn)
rmat2<-(rmat)
if(length(state1)==1) {return(rmat)
}else bestmatch<-apply(rmat,1,function(x){y<-which(x==max(x)); if(length(y)>1) y<-sample(y,1); y})
for(i in 1:length(bestmatch)) rmat2[,i]<-rmat[,bestmatch[i]]
rmat2
}
stateCor<-function(state1,state2,fn="popCorMat",corfn="popCor"){
## Correlation between states
rmat<-get(fn)(state2,state1) # do it this way around to allow state2 to be a "reference state"
if(length(state1)==1) return(rmat[1])
else bestmatch<-apply(rmat,1,function(x){y<-which(x==max(x)); if(length(y)>1) y<-sample(y,1); y})
corvec<-rep(0,length(bestmatch))
for(i in 1:length(bestmatch)) corvec[i]<-rmat[i,bestmatch[i]]
lens<-as.vector(sapply(state1,length))
sum(corvec*lens/sum(lens))
}
stateForceMatch<-function(rmat){
### Return the best matching column for each row, conditional on it not having been used already. So every match is made only once
ret<-rep(0,dim(rmat)[1])
ret[1]<-which(rmat[1,]==max(rmat[1,]))
for(i in 2:dim(rmat)[1]){
ret[i]<-which(rmat[i,]==max(rmat[i,-ret[1:i]]));
}
ret
}
groupingAsMatrix<-function(pg,res=NULL)
{
tmp<-unlist(pg)
names(tmp)<-NULL
if(is.null(res)){
res<-matrix(0,ncol=length(tmp),nrow=length(tmp))
colnames(res)<-rownames(res)<-tmp
}else res[]<-0
for(i in 1:length(pg)) {
tdat<-expand.grid(pg[[i]],pg[[i]], KEEP.OUT.ATTRS = FALSE)
for(j in 1:dim(tdat)[1]) res[as.character(tdat[j,1]),as.character(tdat[j,2])]<-res[as.character(tdat[j,1]),as.character(tdat[j,2])]+1
}
res
}
matrixAsPopList<-function(mat)
{
if(any((mat!=0) * (mat!=1)>0)) stop("Must be binary matrix")
if(is.null(colnames(mat))) colnames(mat)<-paste0("Pop",1:dim(mat)[2])
if(is.null(rownames(mat))) rownames(mystate)<-paste0("Ind",1:dim(mat)[1])
ret<-lapply(1:dim(mat)[2],function(i){
rownames(mat)[which(mat[,i]>0)]
})
names(ret)<-colnames(mat)
ret
}
## matrixAsPopList<-function(mat)
## {
## if(any((mat!=0) * (mat!=1)>0)) stop("Must be binary matrix")
## namlist<-dimnames(mat)[[1]]
## res<-list(namlist[length(namlist)])
## namlist<-namlist[-length(namlist)]
## while(1){
## if(length(namlist)<1) break;
## i<-tail(namlist,1)
## found<-FALSE
## for(j in 1:length(res)) {
## if(any(mat[i,res[[j]]]==1)) {
## res[[j]]<-c(res[[j]],i)
## found<-TRUE
## break
## }
## }
## if(!found) res<-c(res,i)
## namlist<-namlist[-length(namlist)]
## }
## res
## }
aveMat<-function(pophist) {
## Compute pairwise coincidence from the population history vector
phl<-lapply(pophist,popAsList)
for(i in 1:length(pophist)){cat("-")};cat("\n");
res<-groupingMatrix(pophist[1])
cat(".")
for(i in 2:length(pophist)){
tp<-groupingMatrix(pophist[i])
res<-res+tp
cat(".")
}
cat("\n")
res<-res/length(pophist)
res
}
matColMeans<-function(mat,poplist)
## Sums over columns in a matrix, by grouping all columns listed in poplist
## e.g. if mat is M*N matrix and poplist is length K, returns a M*K matrix
## the names of poplist are used to assign names to the returned matrix
{
res<-matrix(0,nrow=dim(mat)[1],ncol=length(poplist))
colindex<-lapply(poplist,function(x){which(colnames(mat)%in%x)})
res<-t(apply(mat,1,function(x){
sapply(colindex,function(y){mean(x[y])})
}))
colnames(res)<-names(poplist)
rownames(res)<-rownames(mat)
res
}
matColSums<-function(mat,poplist)
## Sums over columns in a matrix, by grouping all columns listed in poplist
## e.g. if mat is M*N matrix and poplist is length K, returns a M*K matrix
## the names of poplist are used to assign names to the returned matrix
{
res<-matrix(0,nrow=dim(mat)[1],ncol=length(poplist))
colindex<-lapply(poplist,function(x){which(colnames(mat)%in%x)})
res<-t(apply(mat,1,function(x){
sapply(colindex,function(y){sum(x[y])})
}))
# if(dim(res)[1]==1) res<-t(res)
colnames(res)<-names(poplist)
rownames(res)<-rownames(mat)
res
}
popDendRelabelMembers<-function(popdend,ids){
## Look at each tip of popdend, and find all individuals in the ids structure that have this population. Replace labels with a ; separated character string of the individuals in that population
tdend<-dendrapply(popdend,function(x){
if(is.leaf(x)){
attr(x,"label")<-paste(
relabel(ids[ids[,2]==attr(x,"label"),1]),
collapse=";")
}
x
})
tdend
}
aggregrateDataForK<-function(popdataraw,popdend,K, combine=matColMeans,simplify=TRUE){
## Cut a tree for the rows of a matrix to get K tips
## Make the popdata that has this new set of rows by taking row means (or whatever combine is set to do)
uch<-uniqueCutHeights(popdend)
tcutdend<-cut(popdend,uch[as.character(K)])
tcutlabels<-lapply(tcutdend$lower,labels)
if(simplify){
tcutlabels<-sapply(tcutlabels,
function(x)strsplit(x,";")[[1]])
}else{
names(tcutlabels)=sapply(tcutlabels,
function(x)paste(x,collapse=";"))
}
popdataraw.cut<-t(combine(t(popdataraw),tcutlabels))
popdataraw.cut
}
avgDist<-function(avgmat,poplist)
{
res<-vector("numeric",length(poplist))
for(i in 1:length(poplist)){cat("-")};cat("\n");
for(i in 1:length(poplist)){
tp<-groupingMatrix(poplist[i])
res[i]<-sum(abs(tp-avgmat))
cat(".")
}
cat("\n")
res
}
gelman.diag<-function (x, confidence = 0.95, transform = FALSE, autoburnin = TRUE)
{# MODIFY THIS (from coda) TO WORK WITH MY DATA?
x <- as.mcmc.list(x)
if (nchain(x) < 2)
stop("You need at least two chains")
if (autoburnin && start(x) < end(x)/2)
x <- window(x, start = end(x)/2 + 1)
Niter <- niter(x)
Nchain <- nchain(x)
Nvar <- nvar(x)
xnames <- varnames(x)
if (transform)
x <- gelman.transform(x)
x <- lapply(x, as.matrix)
S2 <- array(sapply(x, var, simplify = TRUE), dim = c(Nvar,
Nvar, Nchain))
W <- apply(S2, c(1, 2), mean)
xbar <- matrix(sapply(x, apply, 2, mean, simplify = TRUE),
nrow = Nvar, ncol = Nchain)
B <- Niter * var(t(xbar))
if (Nvar > 1) {
if (is.R()) {
CW <- chol(W)
emax <- eigen(backsolve(CW, t(backsolve(CW, B, transpose = TRUE)),
transpose = TRUE), symmetric = TRUE, only.values = TRUE)$values[1]
}
else {
emax <- eigen(qr.solve(W, B), symmetric = FALSE,
only.values = TRUE)$values
}
mpsrf <- sqrt((1 - 1/Niter) + (1 + 1/Nvar) * emax/Niter)
}
else mpsrf <- NULL
w <- diag(W)
b <- diag(B)
s2 <- matrix(apply(S2, 3, diag), nrow = Nvar, ncol = Nchain)
muhat <- apply(xbar, 1, mean)
var.w <- apply(s2, 1, var)/Nchain
var.b <- (2 * b^2)/(Nchain - 1)
cov.wb <- (Niter/Nchain) * diag(var(t(s2), t(xbar^2)) - 2 *
muhat * var(t(s2), t(xbar)))
V <- (Niter - 1) * w/Niter + (1 + 1/Nchain) * b/Niter
var.V <- ((Niter - 1)^2 * var.w + (1 + 1/Nchain)^2 * var.b +
2 * (Niter - 1) * (1 + 1/Nchain) * cov.wb)/Niter^2
df.V <- (2 * V^2)/var.V
df.adj <- (df.V + 3)/(df.V + 1)
B.df <- Nchain - 1
W.df <- (2 * w^2)/var.w
R2.fixed <- (Niter - 1)/Niter
R2.random <- (1 + 1/Nchain) * (1/Niter) * (b/w)
R2.estimate <- R2.fixed + R2.random
R2.upper <- R2.fixed + qf((1 + confidence)/2, B.df, W.df) *
R2.random
psrf <- cbind(sqrt(df.adj * R2.estimate), sqrt(df.adj * R2.upper))
dimnames(psrf) <- list(xnames, c("Point est.", paste(50 *
(1 + confidence), "% quantile", sep = "")))
out <- list(psrf = psrf, mpsrf = mpsrf)
class(out) <- "gelman.diag"
out
}
## matrixAsPopList<-function(mat)
## {
## if(any((mat!=0) * (mat!=1)>0)) stop("Must be binary matrix")
## namlist<-dimnames(mat)[[1]]
## res<-list(namlist[length(namlist)])
## namlist<-namlist[-length(namlist)]
## while(1){
## if(length(namlist)<1) break;
## i<-tail(namlist,1)
## found<-FALSE
## for(j in 1:length(res)) {
## if(any(mat[i,res[[j]]]==1)) {
## res[[j]]<-c(res[[j]],i)
## found<-TRUE
## break
## }
## }
## if(!found) res<-c(res,i)
## namlist<-namlist[-length(namlist)]
## }
## res
## }
popListAsPop<-function(pl)
{
tf<-function(x){paste("(",paste(x,collapse=","),")",sep="")}
pl2<-sapply(pl,tf)
paste(pl2,collapse="")
}
writePopFile<-function(pop,file)
{
cat(paste("<Pop>",pop,"</Pop>\n",sep=""),file=file)
invisible(NULL)
}
pairwiseCoincidence<-function(pl)
{
pl2<-popAsList(pl)
pl2<-sapply(pl2,function(x){gsub("[0-9]","",x)})
pcft<-function(x){sapply(x,function(y){sum(x==y)/length(x)})}
tmp<-unlist(sapply(pl2,pcft))
mean(tmp)
}## Penalises merges of different labels
pairwiseEfficiency<-function(pl){pairwiseCoincidence(pl)}
pairwiseSplit<-function(pl)
{
pl2<-popAsList(pl)
pl2<-sapply(pl2,function(x){paste("a",x,sep="")})# cope with numbers only
pl2<-sapply(pl2,function(x){gsub("[0-9]","",x)})
plistall<-unlist(pl2)
pcounts<-sapply(unique(plistall),function(x){sum(x==plistall)})
pcft<-function(x){sapply(x,function(y){sum(y==x)/pcounts[y]})}
tmp<-unlist(sapply(pl2,pcft),use.names = FALSE)
mean(tmp)
}## Penalises splitting of labels, allows merges of different labels
pairwiseAccuracy<-function(pl)
{
pl2<-popAsList(pl)
pl2<-sapply(pl2,function(x){paste("a",x,sep="")})# cope with numbers only
pl2<-sapply(pl2,function(x){gsub("[0-9]","",x)})
plistall<-unlist(pl2)
pcounts<-sapply(unique(plistall),function(x){sum(x==plistall)})
pcft<-function(x){sapply(x,function(y){sum(y!=x)/length(x)*(1-sum(x==y)/pcounts[y])})}
tmp<-unlist(sapply(pl2,pcft),use.names = FALSE)
1-mean(tmp)
}## For each non-pop indiv in your group, get a penalty of the proportion of your pop NOT in this group
## i.e. penalise only when correct labelling as a population becomes impossible
# i.e. no penalty for mixing two populations, no penalty for splitting a population
# Get a penalty when you share a group with another pop and are also present in another group
getPop<-function(str,half=TRUE,n=100)
{
txml<-xmlTreeParse(str)
tres<-as.data.frame.myres(txml)
if(half) tres<-tres[(dim(tres)[1]/2):dim(tres)[1],]
if(n>0) mys<-trunc(seq(floor(length(tres$Pop)/n),length(tres$Pop),length.out=n))
else mys<-1:length(tres$Pop)
tres$Pop[mys]
}
testMCMC<-function(poplist)
{
r1<-sapply(poplist,pairwiseCoincidence)
r2<-sapply(poplist,pairwiseAccuracy)
ret<-c(mean(r1),mean(r2),quantile(r1,c(0.025,0.975)),quantile(r2,c(0.025,0.975)))
names(ret)<-c("meanPc","meanPa","2.5%Pc","97.5%Pc","2.5%Pa","97.5%Pa")
ret
}
###########################
## Obtaining the population-averaged chunkcount matrix
getPopCountMatrix<-function(datamatrix,mapstatelist,remdiag=TRUE){
## Takes the chunkcount matrix and the list of which individuals are in which population
## Returns a matrix of the number of individuals in each population pair
## ASSUMES THAT WE EXCLUDE THE DIAGONAL, AND NOTHING ELSE, FROM THE COMPARISONS
popnmatrix<-datamatrix
popnmatrix[]<-1
if(remdiag) diag(popnmatrix)<-0
popcountmatrix<-matColSums(popnmatrix,mapstatelist)
popcountmatrix<-matColSums(t(popcountmatrix),mapstatelist)
popcountmatrix
}
getPopMatrix<-function(datamatrix,mapstatelist,correction=1,remdiag=TRUE){
## Takes the chunkcount matrix and the list of which individuals are in which population
## Returns a matrix of the chunkcount average for each population pair
datamatrix[is.nan(datamatrix[])]<-0
popcountmatrix<-getPopCountMatrix(datamatrix,mapstatelist,remdiag=remdiag)
popmatrix<-matColSums(datamatrix,mapstatelist)
popmatrix<-t(matColSums(t(popmatrix),mapstatelist))
popmatrix<-popmatrix/popcountmatrix
popmatrix[is.nan(popmatrix[])]<-0
(popmatrix/correction)
}
getPopIndices<-function(indnames,mapstatelist){
# takes a list of individual names, for example as rownames(datamatrix), and the list of individuals in each population
# returns a list of which population each individual is in
popindices<-sapply(indnames,function(x){
which(sapply(mapstatelist,function(y){x %in%y}))
})
popindices
}
getOrderedPopMatrix<-function(datamatrix,mapstatelist,tlabels=NULL){
# takes the chunkcount matrix and the list of individuals in each population
# returns a matrix of the dimension of each population pair
if(is.null(tlabels)) tlabels<-names(mapstatelist)
popmeanmatrix<-datamatrix
popindices<-getPopIndices(rownames(datamatrix),mapstatelist)
popmatrix<-getPopMatrix(datamatrix,mapstatelist)
popmatrix<-popmatrix[unique(popindices),unique(popindices)]
rownames(popmatrix)<-colnames(popmatrix)<-tlabels
(popmatrix)
}
getPopMeanMatrix<-function(datamatrix,mapstatelist){
# takes the chunkcount matrix and the list of individuals in each population
# returns a matrix of the same dimension, where x[i,j] has been replaced by the average x[i,j] for each population pair
popmeanmatrix<-datamatrix
popindices<-getPopIndices(rownames(datamatrix),mapstatelist)
popmatrix<-getPopMatrix(datamatrix,mapstatelist)
for(i in 1:dim(popmeanmatrix)[1]) for(j in 1:dim(popmeanmatrix)[2]){
popmeanmatrix[i,j]<-popmatrix[popindices[i],popindices[j]]
}
(popmeanmatrix)
}
matToList=function(x){
## Converts a matrix into a list of vectors
ret=list()
for(i in 1:dim(x)[2]) ret[[i]]=x[,i,drop=T]
names(ret)=colnames(x)
ret
}
bootstrapListOfMatrices=function(flist,tw=NULL){
## Takes a list of matrices and returns a bootstrap of their mean, weighted by total sums.
allsums=sapply(flist,sum)
if(is.null(tw))tw=sample(1:length(flist),replace=TRUE,size=length(flist))
ret=flist[[1]]
ret[]=0
for(i in 1:length(tw)) ret= ret + flist[[tw[i]]] * allsums[i]/allsums[tw[i]]
as.matrix(ret)
}
###########################
## Start of dendrogram functions
fixMidpointMembers<-function(x)
{
## Fixes the midpoint of a dendrogram node (dendrapply and removing midpoints on tips needed)
attr(x, "x.member")<-NULL
attr(x, "value")<-NULL
if(is.leaf(x)) {
attr(x, "label")<-attr(x, "label")[[1]]
attr(x, "midpoint")<-NULL
attr(x, "members")<-1
}
if(!is.leaf(x)) {
attr(x, "members")<-length(labels(x))
}
x
}
cutdend<- function(tdend,height,summary="NameSummary") {
## Cuts the dendrogram at a given height and returns the corresponding dendrogram. This is invertible with summary="NameSummary" or otherwise simplified in summary="NameMoreSummary"
testj<-cut(tdend,height)
newdend<-testj$upper
newdend<-dendrapply(newdend,function(x){
if(is.leaf(x)) {
attr(x,"height")<-0
tbranch<-as.numeric(gsub("Branch","",attr(x,"label")))
attr(x,"label")<-get(summary)(labels(testj$lower[[tbranch]]))
}
x
})
## Fixing the mid points
newdend <- dendrapply(newdend, fixMidpointMembers)
## tdend <- fix_members_attr.dendrogram(tdend)
newdend <- suppressWarnings(midcache.dendrogram(newdend)) # fixing the middle point thing
newdend
}
relabelDend<-function(tdend,namemap=NULL){
## Relabel a dendrogram (which must have unique labels)
## Either (default) generate the relabelling from NameMoreSummary,
## Or use a map provide (in named list format)
if(is.null(namemap)) {
namemap<-sapply(NameExpand(labels(tdend)),NameMoreSummary)
}
dendrapply(tdend,function(x){
if(!is.null(attr(x,"label")) && attr(x,"label")%in%names(namemap)){
attr(x,"label")<-namemap[[attr(x,"label")]]
}
x
})
}
makemydend<- function(tdend,lablist,summary="NameSummary",retainmembers=FALSE) {
mmd<-function(x){
test<-which(sapply(lablist,function(y){all(labels(x) %in% y)}))
if(length(test)>0){
ret<-numeric()
attr(ret,"height")<-0 # attr(x,"height")
attr(ret,"label")<-get(summary)(labels(x))
if(retainmembers) attr(ret,"members")<-attr(x,"members")
attr(ret,"leaf")<-TRUE
class(ret)<-"dendrogram"
return(ret)
}
x[[1]]<-mmd(x[[1]])
x[[2]]<-mmd(x[[2]])
return(x)
}
tdend<-mmd(tdend)
## Fixing the mid points
if(!retainmembers) tdend <- dendrapply(tdend, fixMidpointMembers)
## tdend <- fix_members_attr.dendrogram(tdend)
tdend <- suppressWarnings(midcache.dendrogram(tdend)) # fixing the middle point thing
tdend
}
scoreMatrixDtimesM<-function(m){
distm<-sapply(1:dim(m)[1],function(i){
tmp<-abs((1:dim(m)[1])-i)
# tmp[tmp>dim(m)[1]/2]<-dim(m)[1]-tmp[tmp>dim(m)[1]/2]
tmp
})
sum(distm*m)
}
rotateDendrogramDiagonalize<-function(d,m,score=scoreMatrixDtimesM){
## Try to swap every node to minimize the score; this will "diagonalize" the matrix
fullorder<-labels(d)
m<-m[fullorder,fullorder]
tswap<-function(x){
if(!is.leaf(x)) {
t1<-labels(x[[1]])
t2<-labels(x[[2]])
tw<-which(fullorder==t1[1])
testorder<-fullorder
testorder[tw -1 + 1:(length(t1)+length(t2))]<-c(t2,t1)
tm<-m[testorder,testorder]
if(score(m)> score(tm)){
tmp<-x[[1]]
x[[1]]<-x[[2]]
x[[2]]<-tmp
m<<-tm
fullorder<<-testorder
}
x[[1]]<-tswap(x[[1]])
x[[2]]<-tswap(x[[2]])
}
x
}
newdend <- dendrapply(tswap(d), fixMidpointMembers)
## tdend <- fix_members_attr.dendrogram(tdend)
newdend <- suppressWarnings(midcache.dendrogram(newdend)) # fixing the middle point thing
newdend
}
popIn<-function(x){
tlab2<-gsub("[0-9]","",x)
unique(tlab2)
}
popIn2<-function(x){
tlab2<-gsub("[0-9,-]","",x)
unique(tlab2)
}
popUnder<-function(x){
tlab2<-gsub("[0-9]","",labels(x))
unique(tlab2)
}
getTip1<-function(x){
while(!is.leaf(x)) x<-getTip1(x[[1]])
x
}
relabel<-function(x,l1,l2){
if(!is.null(attributes(x)$label)) attributes(x)$label<-l2[which(l1==attributes(x)$label)]
x
}
dend.relabel<-function(x,l1,l2)
{
dendrapply(x,relabel,l1=l1,l2=l2)
}
## Reversing the above (as much as possible)
## is only possible for dendrograms with *binary* splits
.memberDend <- function(x) {
r <- attr(x,"x.member")
if(is.null(r)) {
r <- attr(x,"members")
if(is.null(r)) r <- 1L
}
r
}
.midDend <- function(x)
if(is.null(mp <- attr(x, "midpoint"))) 0 else mp
midcache.dendrogram <- function (x, type = "hclust", quiet=FALSE)
{
## Recompute "midpoint" attributes of a dendrogram, e.g. after reorder().
type <- match.arg(type) ## currently only "hclust"
stopifnot( inherits(x, "dendrogram") )
setmid <- function(d, type) {
if(is.leaf(d))# no "midpoint"
return(d)
k <- length(d)
if(k < 1)
stop("dendrogram node with non-positive #{branches}")
r <- d # incl. attributes!
midS <- 0
for(j in 1L:k) {
r[[j]] <- unclass(setmid(d[[j]], type))
midS <- midS + .midDend(r[[j]])
}
if(!quiet && type == "hclust" && k != 2)
warning("midcache() of non-binary dendrograms only partly implemented")
## compatible to as.dendrogram.hclust() {MM: doubtful if k > 2}
attr(r, "midpoint") <- (.memberDend(d[[1L]]) + midS) / 2
r
}
setmid(x, type=type)
}
as.hclust.dendrogram.orig <- function(x, ...)
{
stopifnot(is.list(x), length(x) == 2)
n <- length(ord <- unlist(x))
stopifnot(n == attr(x, "members"))
n.h <- n - 1L
## labels: not sure, if we'll use this; there should be a faster way!
labsu <- unlist(labels(x))
labs <- labsu[sort.list(ord)]
x <- .add.dendrInd(x)
SIMP <- function(d) {
if(is.leaf(d)) {
- as.vector(d)# dropping attributes
} else {
j <<- j + 1L
height[j] <<- attr(d, "height")
inds[[j]] <<- attr(d, ".indx.")
attributes(d) <- NULL # drop all, incl. class
## recursively apply to components:
d[] <- lapply(d, SIMP)
d
}
}
height <- numeric(n.h); inds <- vector("list",n.h); j <- 0L
xS <- SIMP(x)
ii <- sort.list(height)
merge <- matrix(NA_integer_, 2L, n.h)
for(k in seq_len(n.h)) {
if(k < n.h) { in.k <- inds[[ ii[k] ]] ; s <- xS[[in.k]] } else s <- xS
##cat(sprintf("ii[k=%2d]=%2d -> s=xS[[in.k]]=", k, ii[k])); str(s)
s<-lapply(s, as.integer)
stopifnot(length(s) == 2L, all( vapply(s, is.integer, NA) ))# checking..
merge[,k] <- unlist(s)
if(k < n.h)
xS[[in.k]] <- + k
}
r <- list(merge = t(merge),
height = height[ii],
order = ord,
labels = labs,
call = match.call(),
method = NA_character_,
dist.method = NA_character_)
class(r) <- "hclust"
r
}
##' add the c(i1,i2,..) list indices to each non-leaf of a dendrogram
##' --> allowing "random access" into the dendrogram
.add.dendrInd <- function(x)
{
add.I <- function(x, ind) {
if(!is.leaf(x)) {
for(i in seq_along(x))
x[[i]] <- add.I(x[[i]], c(ind, i))
attr(x, ".indx.") <- ind
}
x
}
## apply recursively:
add.I(x, integer(0))
}
plot.node.labels<-function(x,m=0)
{
if(!is.leaf(x)) {
text(attr(x,"height")+0.5,m+attr(x,"midpoint"),attr(x,"edgetext"))
plot.node.labels(x[[1]],m+attr(x,"midpoint"))
plot.node.labels(x[[2]],m)
}
}
simpledend<-function(x) {
print(x)
if(length(popUnder(x[[1]]))>1){
# print(paste("PopUnder1:",popUnder(x[[1]])))
# print(x[[1]])
r1<-simpledend(x[[1]])
attributes(r1)$members<-length(labels(r1))
}else {
r1<-getTip1(x[[1]])
attributes(r1)$label<- paste(popUnder(x[[1]]),length(labels(x[[1]])),sep="")
# attributes(r1)$height<-attributes(x[[1]])$height
}
if(length(popUnder(x[[2]]))>1){
# print(paste("PopUnder2:",popUnder(x[[2]])))
# print(x[[2]])
r2<-simpledend(x[[2]])
attributes(r2)$members<-length(labels(r2))
}else {
r2<-getTip1(x[[2]])
attributes(r2)$label<- paste(popUnder(x[[2]]),length(labels(x[[2]])),sep="")
# attributes(r2)$height<-attributes(x[[2]])$height
}
x[[1]]<-r1
x[[2]]<-r2
attributes(x)$members <- length(labels(x))
x<-midcache.dendrogram(x)
return(x)
}
my.as.hclust.phylo<-function (x,tol=0.01, ...)
{
if (!is.ultrametric(x,tol))
stop("the tree is not ultrametric")
if (!is.binary.tree(x))
stop("the tree is not binary")
n <- length(x$tip.label)
bt <- rev(branching.times(x))
N <- length(bt)
nm <- as.numeric(names(bt))
merge <- matrix(NA, N, 2)
for (i in 1:N) {
ind <- which(x$edge[, 1] == nm[i])
for (k in 1:2) merge[i, k] <- if (x$edge[ind[k], 2] <=
n)
-x$edge[ind[k], 2]
else which(nm == x$edge[ind[k], 2])
}
names(bt) <- NULL
obj <- list(merge = merge, height = bt, order = 1:(N + 1),
labels = x$tip.label, call = match.call(), method = "unknown")
class(obj) <- "hclust"
obj
}# Adds tolerance to the function
positiveheights<-function(x){
if(attributes(x)$height<0){attributes(x)$height<-0.0001;}
x}
flattenheights<-function(x,factor=0.25){
if(attributes(x)$height>0){attributes(x)$height<-attributes(x)$height^factor;}
x}
myapetodend<-function(ttree,simplify=FALSE,tol=0.1,factor=0.25){
nodelab<-ttree$node.label
ttree$node.label<-NULL
htree<-my.as.hclust.phylo(ttree,tol)
dend<-as.dendrogram(htree)
# if(!is.null(nodelab))dend<-setNodeLabels(dend,nodelab)
dend<-dendrapply(dend,positiveheights)
if(simplify) dend<-simpledend(dend)
dend<-dendrapply(dend,flattenheights,factor=factor)
if(!is.null(nodelab))dend<-setNodeLabels(dend,nodelab)
dend
}
findsplits<-function(tdend,tol=0.75){
i<-0
tlist<-list()
popExt <<- function(n,tol=0.75) {
if(!is.leaf(n)) {
myval<-as.numeric(attr(n, "edgetext"))
if(length(myval)>0) {if(myval>tol) {
i<<-i+1
tlist[[i]]<<-labels(n)
}}
}
n
}
tmp<-dendrapply(tdend, popExt,tol=tol)
tlist
}
findsplitsNoText<-function(tdend){
i<-0
tlist<-list()
popExt <<- function(n) {
if(!is.leaf(n)) {
i<<-i+1
tlist[[i]]<<-labels(n)
}
n
}
tmp<-dendrapply(tdend, popExt)
tlist
}
checkPops<-function(l1,l2) {
res<-rep(FALSE,length(l1))
for( pon in 1:length(l1)) {
p<-l1[[pon]]
plist<-lapply(p,function(x){grep(x,l2)})
tvec<-rep(FALSE,length(plist[[1]]))
if(length(plist[[1]])>0){
for(pop in 1:length(plist[[1]])) tvec[pop]<-all(sapply(plist,function(x){plist[[1]][pop] %in% x}))
}
for(pon2 in which(tvec)) {
p2<-l2[[plist[[1]][pon2]]]
if(all(sapply(p2,function(x){x %in% p}))) res[[pon]]<-TRUE
}
# res[[pon]]<-any(tvec)
}
return(sum(res)/length(res))
}
###################################
## DENDROGRAM MANIPULATION - probably worth ignoring this
setCols<-function(n,lab.cex=0.5,cex=0,cols=1:5,collist){
if(is.leaf(n)){
a <- attributes(n)
label<-gsub("[0-9]","",labels(n))
area<-which(sapply(lapply(collist,function(x,pattern){which(x==pattern)},pattern=label),length)>0)
thiscol=cols[area]
attr(n, "nodePar") <-
c(a$nodePar, list(cex=cex,lab.cex=lab.cex,lab.col = thiscol))
}
n
}
setCols2<-function(n,lab.cex=0.5,cex=0,cols=1:5,collist){
if(is.leaf(n)){
a <- attributes(n)
labeltmp<-gsub("[0-9,-]","",labels(n))
label<-strsplit(labeltmp,";")[[1]]
area<-which(sapply(lapply(collist,function(x,pattern){which(x%in%pattern)},pattern=label),length)>0)
print(paste(labels(n),":::",area))