-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfastGLOBETROTTER.R
2305 lines (2105 loc) · 123 KB
/
fastGLOBETROTTER.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
## This software is licenced under the "Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License" (http://creativecommons.org/licenses/by/4.0/)
## TAKE CHROMOPAINTER OUTPUT AND, FOR A SPECIFIED "RECIPIENT" POPULATION:
## (1) INFERS DATES, PROPORTIONS AND SOURCES OF ADMIXTURE EVENT(S) IN ANCESTRAL HISTORY OF "RECIPIENT" POPULATION (IN PARTICULAR INFERRING THE ADMIXING SOURCES AS A LINEAR COMBINATION OF OTHER "DONOR" POPULATIONS)
## (2) USING BOOTSTRAP RE-SAMPLING, INFERS CONFIDENCE INTERVAL AROUND ADMIXTURE DATES
## !!!! NOTE: MUST HAVE PACKAGE "nnls" INSTALLED !!!!
## usage: (1) R CMD SHLIB -o fastGLOBETROTTERCompanion.so fastGLOBETROTTERCompanion.c -lz (do only once)
## then: (2) R < fastGLOBETROTTER.R parameter.infile.list samplefiles.infile.list recomratefiles.infile.list option --no-save > output.out
## example -- SOURCE/DATE/PROPORTION ESTIMATION: R < fastGLOBETROTTER.R tutorial/paramfile.txt tutorial/samplefile.txt tutorial/recomfile.txt 1 --no-save > output.out
########################################
## COMMAND LINE INPUT:
ptm = proc.time()
usage=function()
{
print(noquote("run using: R < GLOBETROTTER.R parameter_infile painting_samples_filelist_infile recom_rate_filelist_infile --no-save > screen_output"))
print(noquote("parameter input file format (NO defaults, all fields must be entered, even if not used):"))
print(noquote("prop.ind: [0,1]"))
print(noquote("bootstrap.date.ind: [0,1,2]"))
print(noquote("null.ind: [0,1]"))
#print(noquote("contrasts.ind: [0,1]"))
print(noquote("input.file.ids: [input.filename1]"))
print(noquote("input.file.copyvectors: [input.filename2]"))
print(noquote("save.file.main: [output.filename1]"))
print(noquote("save.file.bootstraps: [output.filename2]"))
print(noquote("copyvector.popnames: [pop_1 pop_2 ... pop_j]"))
print(noquote("surrogate.popnames: [pop_1 pop_2 ... pop_k]"))
print(noquote("target.popname: [pop_rec]"))
print(noquote("num.mixing.iterations: [0,1,...,5,...]"))
print(noquote("props.cutoff: [0.0,...,1.0]"))
print(noquote("bootstrap.num: [0,1,...]"))
print(noquote("num.admixdates.bootstrap: [1,2]"))
print(noquote("num.surrogatepops.perplot: [1,...]"))
print(noquote("curve.range: [lower.lim upper.lim (in cM)]"))
print(noquote("bin.width: [e.g. 0.1]"))
print(noquote("xlim.plot: [lower.lim upper.lim (in cM)]"))
print(noquote("prop.continue.ind: [0,1]"))
print(noquote("haploid.ind: [0,1]"))
}
temp=commandArgs()
param.infile=as.character(temp[2])
if (param.infile=="help"){usage();q(save='no')}
######################################
## COMMAND LINE CHECK AND READ IN:
weightmin=0 ## a chunk must have > weightmin SNPs to be considered in the coancestry curves
gridweightMAXcutoff=1 ## any chunk's weighted contribution (i.e. the cM length of the chunk) to the coancestry curves cannot be bigger than this (in cM)
null.calc=0
error.input.message=function(file.name)
{
print(paste("Something wrong with input file ",file.name,". See below. Exiting...",sep=''))
usage()
q(save='no')
}
line.check=function(file.name,skip.val,match.val)
{
if (as.character(read.table(file.name,skip=skip.val,nrows=1,as.is=TRUE)[1]) != as.character(match.val))
{
error.input.message(file.name)
}
if (as.character(read.table(file.name,skip=skip.val,nrows=1,as.is=TRUE)[1]) == as.character(match.val))
return(read.table(file.name,skip=skip.val,nrows=1,as.is=TRUE)[2:length(read.table(file.name,skip=skip.val,nrows=1,as.is=TRUE))])
}
## line read in and checks:
prop.ind=as.integer(line.check(param.infile,0,"prop.ind:"))
if ((length(prop.ind)!=1)||(prop.ind!=0 && prop.ind!=1)) error.input.message(param.infile)
admix.curves.ind=as.integer(line.check(param.infile,1,"bootstrap.date.ind:"))
if ((length(admix.curves.ind)!=1)||(admix.curves.ind!=0 && admix.curves.ind!=1 && admix.curves.ind!=2 )) error.input.message(param.infile)
null.ind=as.integer(line.check(param.infile,2,"null.ind:"))
if ((length(null.ind)!=1)||(null.ind!=0 && null.ind!=1)) error.input.message(param.infile)
#contrasts.ind=as.integer(line.check(param.infile,3,"contrasts.ind:"))
#if ((length(contrasts.ind)!=1)||(contrasts.ind!=0 && contrasts.ind!=1)) error.input.message(param.infile)
id.file=as.character(line.check(param.infile,3,"input.file.ids:"))
if (length(id.file)!=1) error.input.message(param.infile)
copyvector.file=as.character(line.check(param.infile,4,"input.file.copyvectors:"))
if (length(copyvector.file)!=1) error.input.message(param.infile)
save.file.props=as.character(line.check(param.infile,5,"save.file.main:"))
if (length(save.file.props)!=1) error.input.message(param.infile)
save.file.bootstraps=as.character(line.check(param.infile,6,"save.file.bootstraps:"))
if (length(save.file.props)!=1) error.input.message(param.infile)
donor.pops.all=unique(as.character(line.check(param.infile,7,"copyvector.popnames:")))
if (length(donor.pops.all)<2) error.input.message(param.infile)
newnames=as.character(line.check(param.infile,8,"surrogate.popnames:"))
if (length(unique(newnames))<2) error.input.message(param.infile)
recipient.pops=as.character(line.check(param.infile,9,"target.popname:"))
if (length(recipient.pops)!=1) error.input.message(param.infile)
popvec.admixcurves=recipient.pops
num.iterations = as.integer(line.check(param.infile,10,"num.mixing.iterations:"))
if ((length(num.iterations)>1) || (num.iterations < 0)) error.input.message(param.infile)
prop.cutoff = as.double(line.check(param.infile,11,"props.cutoff:"))
if ((length(prop.cutoff)>1) || (prop.cutoff < 0) || (prop.cutoff>=1)) error.input.message(param.infile)
bootstrap.samp = as.integer(line.check(param.infile,12,"bootstrap.num:"))
if ((length(bootstrap.samp)!=1) || (bootstrap.samp < 0)) error.input.message(param.infile)
nparam.toplot = as.integer(line.check(param.infile,13,"num.admixdates.bootstrap:")) ## plot results from fitting one or two events?
if ((length(bootstrap.samp)!=1) || ((nparam.toplot!=1) && (nparam.toplot!=2))) error.input.message(param.infile)
numpops.toplot = as.integer(line.check(param.infile,14,"num.surrogatepops.perplot:")) ## number of donor pops to include in plots
grid.range=as.integer(line.check(param.infile,15,"curve.range:")) ## integer values for where to start and end fitting on the admixture copying grid
if ((length(grid.range)!=2)||(grid.range[1]<0)||(grid.range[2]<0)||(grid.range[1]>=grid.range[2])) error.input.message(param.infile)
bin.width=as.double(line.check(param.infile,16,"bin.width:")) ## width of bins for tabulating chunk-pair counts when generating coancestry curves
if ((length(bin.width)!=1)||(bin.width[1]<=0)) error.input.message(param.infile)
xlim.plot=as.double(line.check(param.infile,17,"xlim.plot:")) ## range of x-axis for admixture plots
if (((length(xlim.plot)==1) && (xlim.plot[1]>0)) || (xlim.plot[1]>=xlim.plot[2]) || (xlim.plot[2]<=0) || (length(xlim.plot)>2)) error.input.message(param.infile)
prop.continue.ind=as.integer(line.check(param.infile,18,"prop.continue.ind:"))
if ((length(prop.continue.ind)!=1)||(prop.continue.ind!=0 && prop.continue.ind!=1)) error.input.message(param.infile)
haploid.ind=as.integer(line.check(param.infile,19,"haploid.ind:"))
if ((length(haploid.ind)!=1)||(haploid.ind!=0 && haploid.ind!=1)) error.input.message(param.infile)
ploidy=2-haploid.ind
prop.save.post=".txt"
if (prop.continue.ind==0) prop.save.addon = ""
if (prop.continue.ind==1) prop.save.addon = "_continue"
if (prop.continue.ind==1 && prop.ind==1)
{
print(paste("YOU HAVE SPECIFIED BOTH 'prop.ind' AND 'prop.continue.ind' TO BE EQUAL TO 1 IN ",param.infile,". IF THERE IS AN EXISTING 'save.file.main', WHICH YOU WISH TO USE AS STARTING VALUES FOR YOUR ESTIMATION, THEN YOU WANT 'prop.continue.ind' TO BE 1. IF THERE IS NO EXISTING 'save.file.main', THEN YOU WANT 'prop.ind' TO BE 1. Exiting...",sep=''))
q(save='no')
}
if (max(c(prop.ind,prop.continue.ind,admix.curves.ind))==0)
{
print(paste("YOU HAVE SPECIFIED NO ACTION IN ",param.infile,", WITH 'prop.ind', 'bootstrap.date.ind' and 'prop.continue.ind' ALL EQUAL TO 0. Exiting...",sep=''))
q(save='no')
}
if (admix.curves.ind==1 && bootstrap.samp==0)
{
print(paste("YOU HAVE SPECIFIED TO BOOTSTRAP DATES IN ",param.infile," BUT HAVE REQUESTED 0 BOOTSTRAPS. Exiting...",sep=''))
q(save='no')
}
#######################################
## PROGRAM:
dists=seq(grid.range[1],grid.range[2],bin.width)
num.bins=length(dists)
if (length(dists)<=1) {print(paste("Something wrong with bin.width and curve.range specification in ",param.infile,"! Exiting....",sep='')); q(save='no')}
#num.bins=ceiling((grid.range[2]-grid.range[1])/bin.width)
#############################################################
##############################################################
## (0) FUNCTIONS:
##############################################################
#############################################################
#install.packages("nnls") ## IF THE FOLLOWING LINE DOESN'T WORK, USE THIS!
library(nnls)
options(scipen=999)
dyn.load("fastGLOBETROTTERCompanion.so")
findpeak = function (ourmix,means,bin.width)
{
dom = which(ourmix ==max(ourmix))
new = means[length(ourmix)*(dom-1)+dom,]
##if (dim(means)[2] > 100) {wsize = 100 ## !!!!! pongsakorn orig !!!!!!!!
##} else {wsize = round(dim(means)[2]/4)} ## !!!!! pongsakorn orig !!!!!!!!
wsize = round(dim(means)[2]/2) ## !!!!! garrett change (now can remove up to half the original -- fitted -- x-axis) !!!!!!!!
lrange = c(3,5,7,9,11,13)
mid = c(2,3,4,5,6,7)
keep_max = NULL
c = 1
for(i in lrange){
slope = NULL
j = 1
##while (j < wsize) ## !!!!! pongsakorn orig !!!!!!!!
while (j < wsize && ((j+i)<(dim(means)[2]-10))) ## !!!!! garrett change (now must keep the last 10 gridpoints at least) !!!!!!!!
{
temp = lm(new[j:(j+i)]~c(j:(j+i)))
temp = temp$coefficients[2]
slope = append(slope,temp)
j = j + 1
}
index.val=which(slope<0) ## !!!!! garrett change !!!!!!!!
if (sum(index.val)==0) keep_max = append(keep_max, length(slope)) ## !!!!! garrett change !!!!!!!!
if (sum(index.val)>0) keep_max = append(keep_max, min(index.val)) ## !!!!! garrett change !!!!!!!!
##keep_max = append(keep_max, min(which(slope<0))) ## !!!!! pongsakorn orig !!!!!!!!
c = c+1
}
#print(new)
#print(keep_max)
#print(max(keep_max+mid))
#plot(new[max(keep_max+mid):200])
#print(keep_max[which(keep_max == max(keep_max))]-1+mid[which(keep_max == max(keep_max))])
if (mean(keep_max) == 1) {return(0)}
#else return(1)
#else return(max(keep_max+mid))
else return(max(keep_max[which(keep_max == max(keep_max))]-1+mid[which(keep_max == max(keep_max))]))
}
coancestry.curves.mode3=function(ploidy,ind.id.vec,infile.samples,infile.recom,bin.width,num.bins,grid.start,unique.pops,pop.label.vecII,rec.labels,weightmin,gridweightMAXcutoff,temp.weights,num.surrogates)
{
means=matrix(0,nrow=num.surrogates^2,ncol=num.bins)
out=.C("data_read_mode3",ploidy=as.integer(ploidy),ind_id_vec=as.integer(ind.id.vec),filenameSAMPread=as.character(infile.samples),filenameRECOMread=as.character(infile.recom),binwidth=as.double(bin.width),num_bins=as.integer(num.bins),grid_start=as.integer(grid.start),num_donors=as.integer(length(unique.pops)),donor_label_vec=as.integer(pop.label.vecII),num_inds_rec=as.integer(length(rec.labels)),recipient_label_vec=as.character(rec.labels),weight_min=as.double(weightmin),gridweightMAX_cutoff=as.double(gridweightMAXcutoff),num_surrogates=as.integer(num.surrogates),temp_weights=as.double(temp.weights),means=as.double(means))
return(out$means)
}
coancestry.curves=function(ploidy,ind.id.vec,infile.samples,infile.recom,bin.width,num.bins,grid.start,unique.pops,pop.label.vecII,rec.labels,weightmin,gridweightMAXcutoff,temp.weights,num.surrogates)
{
means=matrix(0,nrow=num.surrogates^2,ncol=num.bins)
out=.C("data_read",ploidy=as.integer(ploidy),ind_id_vec=as.integer(ind.id.vec),filenameSAMPread=as.character(infile.samples),filenameRECOMread=as.character(infile.recom),binwidth=as.double(bin.width),num_bins=as.integer(num.bins),grid_start=as.integer(grid.start),num_donors=as.integer(length(unique.pops)),donor_label_vec=as.integer(pop.label.vecII),num_inds_rec=as.integer(length(rec.labels)),recipient_label_vec=as.character(rec.labels),weight_min=as.double(weightmin),gridweightMAX_cutoff=as.double(gridweightMAXcutoff),num_surrogates=as.integer(num.surrogates),temp_weights=as.double(temp.weights),means=as.double(means))
return(out$means)
}
mutiply.temp.weight=function(unique.pops,num.surrogates,weights.mat)
{
tempweights=matrix(0,nrow=num.surrogates*num.surrogates,ncol=unique.pops*unique.pops)
out=.C("mutiply_temp_weight",tempweights = as.double(tempweights),weights_mat = as.double(weights.mat),num_surrogates = as.integer(num.surrogates),num_donors = as.integer(unique.pops))
return(out$tempweights)
}
coancestry.curves.null=function(ploidy,infile.samples,infile.recom,bin.width,num.bins,grid.start,target.pop,unique.pops,pop.label.vecII,rec.labels,weightmin,gridweightMAXcutoff)
{
chrom.ind.res=matrix(0,nrow=length(unique.pops)^2,ncol=num.bins)
out=.C("data_read_null",ploidy=as.integer(ploidy),filenameSAMPread=as.character(infile.samples),filenameRECOMread=as.character(infile.recom),binwidth=as.double(bin.width),num_bins=as.integer(num.bins),grid_start=as.integer(grid.start),num_donors=as.integer(length(unique.pops)),donor_label_vec=as.integer(pop.label.vecII),num_inds_rec=as.integer(length(rec.labels)),recipient_label_vec=as.character(rec.labels),weight_min=as.double(weightmin),gridweightMAX_cutoff=as.double(gridweightMAXcutoff),chrom_ind_res=as.double(chrom.ind.res))
if (is.element(target.pop,unique.pops))
{
target.ind=(1:length(unique.pops))[unique.pops==target.pop]
to.remove=sort(unique(c(seq(target.ind,length(unique.pops)^2,length(unique.pops)),((target.ind-1)*length(unique.pops)+1):(target.ind*length(unique.pops)))))
out$chrom_ind_res=c(t(matrix(out$chrom_ind_res,byrow=TRUE,ncol=num.bins)[-to.remove,]))
}
return(out$chrom_ind_res)
}
corr.find=function(x,vec.tocheck)
{
return(cor(x,vec.tocheck))
}
#####function to more efficiently fit an initial mixture, essentially same as stepwise regression results but much faster.
getfit=function(predmat,fitdata,restrict=1){
temp=matrix(predmat[-restrict,],ncol=dim(predmat)[2])
for(i in 1:nrow(temp)) temp[i,]=temp[i,]-predmat[restrict,]
fitdata2=fitdata-predmat[restrict,]
v=nnls(t(temp),fitdata2)
x=v$x
newx=1:nrow(predmat)
newx[!((1:nrow(predmat))==restrict)]=x
newx[restrict]=1-sum(x)
v$x=newx
names(v$x)=rownames(predmat)
return(v)
}
#####the following does an initial linear model fit quicker than before...
getoverallfit=function(predmat,fitdata){
restrict=1
rep=1
i=1
while(rep==1){
q=getfit(predmat,fitdata,restrict=i)
if(q$x[i]>0) rep=0
i=i+1
}
return(q)
}
#####need to require sums to equal 1
getfitfull=function(newpredmat,target,restrict){
temp=newpredmat[,-restrict]
for(i in 1:(ncol(temp)/2)) temp[,i]=temp[,i]-newpredmat[,restrict[1]]
for(i in (ncol(temp)/2+1):(ncol(temp))) temp[,i]=temp[,i]-newpredmat[,restrict[2]]
target2=target-newpredmat[,restrict[1]]-newpredmat[,restrict[2]]
v=nnls(temp,target2)
x=v$x
newx=1:ncol(newpredmat)
newx[!((1:ncol(newpredmat))%in%restrict)]=x
newx[restrict[1]]=1-sum(x[1:(length(x)/2)])
newx[restrict[2]]=1-sum(x[(length(x)/2+1):(length(x))])
v$x=newx
return(v)
}
####two populations, need
getoverallfitfull=function(newpredmat,target){
ourguess=nnls(newpredmat,target)$x
####use as a ranking
guess=matrix(ourguess,nrow=2,byrow=T)
orderi=order(guess[1,],decreasing=T)
orderj=order(guess[2,],decreasing=T)+length(orderi)
maxi=ncol(newpredmat)/2
minj=ncol(newpredmat)/2+1
maxj=ncol(newpredmat)
finish=0;
for(i in orderi){
for(j in orderj){
q=getfitfull(newpredmat,target,restrict=c(i,j))
if(q$x[i]>0 & q$x[j]>0) finish=1;
if(finish==1) break;
}
if(finish==1) break;
}
return(q)
}
getafit=function(alpha,mu,weights.mat, predmat, intercepts, fitdata){
test=weights.mat%*%t(predmat)
temppredmat=predmat
vals=colSums(weights.mat)
######deal with lack of self copying
for(i in 1:nrow(predmat)) temppredmat[i,]=temppredmat[i,]*vals
for(i in 1:nrow(predmat)) temppredmat[i,]=temppredmat[i,]/sum(temppredmat[i,])
newpredmat=cbind(mu*sqrt(alpha)*sqrt(1-alpha)*test,-mu*sqrt(alpha)*sqrt(1-alpha)*test)
newpredmat=rbind(newpredmat,cbind((1-mu)*alpha*t(predmat), (1-mu)*(1-alpha)*t(predmat)))
target=c(mu*intercepts,(1-mu)*fitdata)
r=getoverallfitfull(newpredmat,target)
names(r$x)=colnames(newpredmat)
return(r)
}
########function that uses the above functions to obtain information on fitted values and likelihoods
fitwhoadmixed=function(weights.mat,predmat,intercepts,fitdata){
alpha.vec=seq(0.01,0.99,0.01)
mu=0.5
tol=1e-5
results=vector(length=0)
for(alpha in alpha.vec){
mu=sqrt(length(fitdata)*mean(fitdata^2))/(sqrt(length(fitdata)*mean(fitdata^2))+sqrt(length(intercepts)*mean(intercepts^2)))
####this is close to 1 if fitdata is long compared to intercepts
####so intercepts get upweighted in resids if there are few of them, which seems right
####also small if intercepts are large, in which case accept reasonable error level given large values
q=getafit(alpha,mu,weights.mat,predmat,intercepts,fitdata)
munew1=mean(q$res[1:length(intercepts)]^2)/mu^2
munew2=mean(q$res[(length(intercepts)+1):length(q$res)]^2)/(1-mu)^2
lhood=-nrow(weights.mat)*log(munew1)/2-nrow(predmat)*log(munew2)/2
####q is all we need
mufitted=mu
lhood=lhood
errors1=q$res[1:length(intercepts)]
errors2=q$res[(length(intercepts)+1):length(q$res)]
###think about model
errors1=errors1/mu
errors2=errors2/(1-mu)
resids=c(errors1,errors2)
curverelmse=mean(errors1^2)/mean(intercepts^2)
proprelmse=mean(errors2^2)/mean(fitdata^2)
avrelmse=(curverelmse+proprelmse)/2
fittedintercepts=intercepts-errors1
fittedprops=fitdata-errors2
curvecor=cor(fittedintercepts,intercepts)
propcor=cor(fittedprops,fitdata)
avcor=(curvecor+propcor)/2
pop1=q$x[1:(length(q$x)/2)]
pop2=q$x[(length(q$x)/2+1):length(q$x)]
pop1fit=pop1[pop1>0]
names(pop1fit)=names(pop1)[pop1>0]
pop2fit=pop2[pop2>0]
names(pop2fit)=names(pop2)[pop2>0]
mixturefit=alpha*pop1+(1-alpha)*pop2
mixturefit=mixturefit[mixturefit>0]
####explore correlations
z=q$x[1:(length(q$x)/2)]
if(length(pop1fit)){
that=t(matrix(predmat[names(pop1fit),],ncol=ncol(predmat))) %*%matrix(pop1fit,ncol=1)
msevec=1:nrow(predmat);
for(i in 1:nrow(predmat)) msevec[i]=mean((predmat[i,]-that)^2)
bestpop1mse=min(msevec)
optimalpop1group=rownames(predmat)[which(msevec==bestpop1mse)]
}
else{ bestpop1mse=1;optimalpop1group=NA;}
if(length(pop2fit)){
that=t(matrix(predmat[names(pop2fit),],ncol=ncol(predmat))) %*%matrix(pop2fit,ncol=1)
msevec=1:nrow(predmat);
for(i in 1:nrow(predmat)) msevec[i]=mean((predmat[i,]-that)^2)
bestpop2mse=min(msevec)
optimalpop2group=rownames(predmat)[which(msevec==bestpop2mse)]
}
else{ bestpop2mse=1;optimalpop2group=NA;}
avbestmse=(bestpop1mse+bestpop2mse)/2
curresults=list(alpha=alpha,pop1fit=pop1fit,pop2fit=pop2fit,mixturefit=mixturefit,lhood=lhood,curverelmse=curverelmse,proprelmse=proprelmse,avrelmse=avrelmse,curvecor=curvecor,propcor=propcor,avcor=avcor,bestpop1mse=bestpop1mse,optimalpop1group=optimalpop1group,bestpop2mse=bestpop2mse, optimalpop2group=optimalpop2group,avbestmse=avbestmse,resids=resids,mufitted=mufitted)
results=c(results,curresults)
}
return(results)
}
######new approach to get intercepts - need a matrix "weights.mat" to tell us dimensions, and fitvec to get rid of frequencies
getfitted=function(weights.mat,fitvec,interceptmat,minval=0,pcnum=1){
d=matrix(1:nrow(weights.mat),nrow=1)
colnames(d)=rownames(weights.mat)
#####make a matrix
interceptmat[is.na(interceptmat)]=0
interceptmat[fitvec<minval,]=0
interceptmat[,fitvec<minval]=0
#####start with raw matrix
propvals=interceptmat*2
ourmix=matrix(fitvec,nrow=length(fitvec))
propvals=(propvals)*(ourmix %*% t(ourmix))
###make sums all zero
test=propvals
for(i in 1:ncol(test)){
for(j in 1:ncol(test)){
propvals[i,j]=test[i,j]-colMeans(test)[j]-rowMeans(test)[i]+mean(test);
}
}
qfitted=eigen(propvals)$vectors[,pcnum]*sqrt(eigen(propvals)$values[pcnum])
quality=1-sum((qfitted %*% t(qfitted)-propvals)^2)/sum(propvals^2)
return(c(quality,qfitted))
}
## for inferring dates:
getlhood=function(means,times,admixtimes,popfracs,likpenalty=likpenalty){
###treat each row of means separately
###filtering of times done already
pred=matrix(nrow=length(times),ncol=length(admixtimes))
for(i in 1:length(admixtimes)){
vec=exp(-times*admixtimes[i]/100)
pred[,i]=vec
}
lhood=0.0
## fits means (i.e. admix curves) as a function of 1 or two times (i.e. pred is either a length(times) vector or a length(times)x2 matrix)
lhoodnegind=0
to.sum=rep(0,length(admixtimes))
seq.to.capture=seq(1,nrow(means),by=sqrt(nrow(means)))+0:(sqrt(nrow(means))-1)
for(i in 1:nrow(means)){
temp=lm(means[i,]~pred)
curlhood=-length(temp$res)/2*log(mean((temp$res)^2))
if (sum(is.element(i,seq.to.capture))==1)
{
mean.plus.3sd=3*sd(abs(temp$res[floor(length(temp$res)/2):length(temp$res)]))
if (length(admixtimes)==2)
{
if (admixtimes[1] != admixtimes[2] && !is.na(temp$coeff[3]))
{
if ((sign(temp$coeff[2]) != sign(temp$coeff[3])) && (min(temp$coeff[2:3]) < -1*mean.plus.3sd)) lhoodnegind=1
for (j in 1:length(admixtimes))
to.sum[j]=to.sum[j]+popfracs[((i-1)/sqrt(nrow(means))+1)]*abs(temp$coeff[(j+1)])
}
if (is.na(temp$coeff[3])) lhoodnegind=1
}
if (length(admixtimes)==1)
{
for (j in 1:length(admixtimes))
to.sum[j]=to.sum[j]+popfracs[((i-1)/sqrt(nrow(means))+1)]*abs(temp$coeff[(j+1)])
}
}
lhood=lhood+curlhood
}
if (is.na(max(to.sum)))
{
to.sum=0
lhoodnegind=1
}
if (lhoodnegind==1 || max(to.sum)>2.0) return(lhood/likpenalty)
else return(lhood)
return(lhood)
}
getmax=function(means,times,ourpops="",nparam,popfracs,returnall=F,method="Nelder-Mead"){
###start with 5 but transform
x=10^seq(0,3,.25)
param.mat=matrix(x,ncol=1)
to.remove=NULL
for (i in 1:length(x))
to.remove=c(to.remove,(length(x)*i+1):(length(x)*i+i))
if (nparam == 2)
param.mat=cbind(rep(x,length(x):1),rep(x,length(x))[-to.remove])
maxlik=0
initnew=sqrt(param.mat[1,])
likpenalty=getlhood(means,times,param.mat[1,],popfracs,1)
# Longest time
for (i in 1:dim(param.mat)[1])
{
likval=getlhood(means,times,param.mat[i,],popfracs,likpenalty)
if (likval>maxlik)
{
initnew=sqrt(param.mat[i,])
maxlik=likval
}
}
init=initnew
ourlhood=function(params){
newparams=1+params^2
return(-getlhood(means,times,newparams,popfracs,likpenalty))
}
this=optim(init,ourlhood,method=method)
likval=this$value
##transform
this$par=1+this$par^2 ## maximum parameter value (i.e. date)
if(returnall==T){ ## (just returns coefficients of linear regression of observed admix times versus expected admix times for date=this$par, in additon to this$par and the "residudal fit" of this linear regression)
admixtimes=this$par
pred=matrix(nrow=length(times),ncol=length(admixtimes))
for(i in 1:length(admixtimes)){
vec=exp(-times*admixtimes[i]/100)
pred[,i]=vec
}
lhood=0.0
lhoodFULL=0.0
nulllhood=0.0
lhood1=1:nrow(means)*0
lhood2=lhood1
lhood3=lhood1
news=matrix(nrow=nrow(means),ncol=(nparam+1))
y.intercept=matrix(NA,nrow=nrow(means),ncol=nparam)
for(i in 1:nrow(means)){
temp=lm(means[i,]~pred)
y.intercept[i,]=round(temp$coeff[2:length(temp$coeff)],10)
news[i,]=temp$coeff
ourpar=admixtimes
lhood2[i]=getlhood(matrix(means[i,],nrow=1),times,ourpar,popfracs[((i-1)/sqrt(nrow(means))+1)],likpenalty)
quan.val=.1
fac.val=10
if ((temp$fitted[length(temp$fitted)] == min(temp$fitted)) && (temp$fitted[1] == max(temp$fitted))) cutoff.val=max((1:length(temp$fitted))[temp$fitted>(temp$fitted[length(temp$fitted)]+(max(temp$fitted)-min(temp$fitted))/fac.val)])
if ((temp$fitted[length(temp$fitted)] == max(temp$fitted)) && (temp$fitted[1] == min(temp$fitted))) cutoff.val=max((1:length(temp$fitted))[temp$fitted<(temp$fitted[length(temp$fitted)]-(max(temp$fitted)-min(temp$fitted))/fac.val)])
if (((temp$fitted[length(temp$fitted)] == min(temp$fitted)) && (temp$fitted[1] != max(temp$fitted))) || ((temp$fitted[length(temp$fitted)] != min(temp$fitted)) && (temp$fitted[1] == max(temp$fitted))) || ((temp$fitted[length(temp$fitted)] == max(temp$fitted)) && (temp$fitted[1] != min(temp$fitted))) || ((temp$fitted[length(temp$fitted)] != max(temp$fitted)) && (temp$fitted[1] == min(temp$fitted)))) cutoff.val=length(temp$fitted)
lhood1[i]=summary(lm(means[i,]~pred))$r.squared/nrow(means)
lhood=lhood+lhood1[i];
lhoodFULL=lhoodFULL+lhood2[i];
lhood3[i]=getlhood(matrix(means[i,],nrow=1),times,rep(0,length(ourpar)),popfracs,likpenalty)
nulllhood=nulllhood+lhood3[i];
}
if(ourpops[1] !=""){
indices=(1:length(means))[order(-lhood1+lhood2)][1:min(25,nrow(news))]
par(mfrow=c(5,5))
for(i in 1:length(indices)){
predline=news[indices[i],1]
for(j in 1:nparam) predline=predline+pred[,j]*news[indices[i],(j+1)]
}
}
return(list(par=admixtimes,y.intercept=y.intercept,coeffs=news,lhood=lhood,lhoodFULL=lhoodFULL,lhoodall=nrow(means)*lhood1))
}
else return(this)
}
prerun=function(temp,donor.pops.all2,num.bins,id.file,copyvector.file){
id.mat=read.table(id.file,as.is=TRUE)
num_target = length(intersect(which(id.mat[,2]==recipient.pops),which(id.mat[,3]=='1')))
## assign labels (in painting) to each donor group:
donor.label.vec=rep(-9,ploidy*length(id.mat[,1]))
donor.pops.all.temp=donor.pops.all
if (length((1:length(donor.pops.all))[donor.pops.all==simname])>0)
donor.pops.all.temp=donor.pops.all.temp[-(1:length(donor.pops.all))[donor.pops.all==simname]]
for (i in 1:length(donor.pops.all.temp))
{
id.labels.i=(1:length(id.mat[,1]))[id.mat[,2]==donor.pops.all.temp[i] & id.mat[,3]!=0]
if (ploidy==2) id.labels.i=sort(c(2*id.labels.i,2*id.labels.i-1))
donor.label.vec[id.labels.i]=i
}
id.labels.i=(1:length(id.mat[,1]))[id.mat[,2]==simname & id.mat[,3]!=0]
if (ploidy==2) id.labels.i=sort(c(2*id.labels.i,2*id.labels.i-1))
donor.label.vec[id.labels.i]=0
to.remove.id=(1:dim(id.mat)[1])[as.character(id.mat[,3])=='0']
if (length(to.remove.id)>0) id.mat=id.mat[-to.remove.id,]
if (length(dim(id.mat))==0)
{
print(paste("SOMETHING WRONG WITH ",id.file," -- NO NON-EXCLUDED INDS? Exiting....",sep=''))
q(save='no')
}
recipient.label.vec=id.mat[,1][id.mat[,2]==simname]
## GET RAW COPY PROPS FOR ALL DONORS:
probs=read.table(copyvector.file,header=TRUE)
rownames.copyvector=as.character(probs[,1])
colnames.copyvector=as.character(read.table(copyvector.file,as.is=TRUE,nrows=1)[-1])
for (i in 1:length(donor.pops.all))
{
if (!is.element(donor.pops.all[i],as.character(id.mat[,2])) && !is.element(donor.pops.all[i],colnames.copyvector))
{
print(paste("COPY VECTOR COLUMN LABEL ",donor.pops.all[i]," NOT FOUND IN DONORS/RECIPIENTS OF ",id.file," OR COLUMNS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
}
for (i in 1:length(donor.pops.all2))
{
if (!is.element(donor.pops.all2[i],as.character(id.mat[,2])) && !is.element(donor.pops.all2[i],rownames.copyvector))
{
print(paste("DONOR POPULATION ",donor.pops.all2[i]," NOT FOUND IN DONORS/RECIPIENTS OF ",id.file," OR ROWS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
}
if (!is.element(simname,as.character(id.mat[,2])) && !is.element(simname,rownames.copyvector))
{
print(paste("RECIPIENT POPULATION ",simname," NOT FOUND IN DONORS/RECIPIENTS OF ",id.file," OR ROWS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
## combine columns across copy-vector pops:
predmat.orig=NULL
for (i in 1:length(donor.pops.all))
{
id.labels.i=c(donor.pops.all[i],as.character(id.mat[,1])[as.character(id.mat[,2])==donor.pops.all[i]])
match.i=NULL
for (j in 1:length(id.labels.i)) match.i=c(match.i,which(as.character(colnames.copyvector)==id.labels.i[j]))
#match.i=match(id.labels.i,as.character(colnames.copyvector))
#match.i=match.i[!is.na(match.i)]
if (length(match.i)==0)
{
print(paste("NO INDS OF ",donor.pops.all[i]," FOUND AMONG COLUMNS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
predmat.orig=cbind(predmat.orig,apply(matrix(as.matrix(probs[,2:dim(probs)[2]][,match.i]),nrow=dim(probs)[1]),1,sum))
}
rownames(predmat.orig)=rownames.copyvector
colnames(predmat.orig)=donor.pops.all
## combine rows across donor pops:
predmat=NULL
for (i in 1:length(donor.pops.all2))
{
id.labels.i=c(donor.pops.all2[i],as.character(id.mat[,1])[as.character(id.mat[,2])==donor.pops.all2[i]])
match.i=NULL
for (j in 1:length(id.labels.i)) match.i=c(match.i,which(as.character(rownames.copyvector)==id.labels.i[j]))
#match.i=match(id.labels.i,as.character(rownames.copyvector))
#match.i=match.i[!is.na(match.i)]
if (length(match.i)==0)
{
#print(id.labels.i[j])
print(paste("NO INDS OF ",donor.pops.all2[i]," FOUND AMONG ROWS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
predmat=rbind(predmat,apply(matrix(as.matrix(predmat.orig[match.i,]),ncol=dim(predmat.orig)[2]),2,mean))
}
rownames(predmat)=donor.pops.all2
colnames(predmat)=donor.pops.all
## GET RAW COPY PROPS FOR RECIPIENT:
id.labels.rec=c(simname,as.character(id.mat[,1])[as.character(id.mat[,2])==simname])
match.rec=NULL
for (j in 1:length(id.labels.rec)) match.rec=c(match.rec,which(as.character(rownames.copyvector)==id.labels.rec[j]))
#match.rec=match(id.labels.rec,as.character(rownames.copyvector))
#match.rec=match.rec[!is.na(match.rec)]
if (length(match.rec)==0)
{
print(paste("NO INDS OF ",simname," FOUND AMONG ROWS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
raw.copyprops.all=apply(matrix(as.matrix(predmat.orig[match.rec,]),ncol=dim(predmat.orig)[2]),2,mean)
names(raw.copyprops.all)=donor.pops.all
## remove self and standardize:
donor.pops.all.orig=donor.pops.all
donor.pops.all=donor.pops.all[!(colnames(predmat) %in% simname)]
donor.pops.all2=donor.pops.all2[!(rownames(predmat) %in% simname)]
predmat=predmat[,!(colnames(predmat) %in% simname)]
predmat=predmat[!(rownames(predmat) %in% simname),]
for(i in 1:nrow(predmat)) predmat[i,]=predmat[i,]/sum(predmat[i,])
raw.copyprops.all=raw.copyprops.all[!(names(raw.copyprops.all) %in% simname)]
raw.copyprops.all=raw.copyprops.all/sum(raw.copyprops.all)
ndonor = length(predmat[1,])
euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))
cor_col=matrix(0,nrow=dim(predmat)[2],ncol=dim(predmat)[2])
for (i in 1:dim(predmat)[2])
{
for (j in 1:dim(predmat)[2])
{
cor_col[i,j] = euc.dist(predmat[,i],predmat[,j])
}
}
temp_keep = NULL
for (i in 1:dim(predmat)[2])
{
temp_keep = append(temp_keep, list(donor.pops.all[which(abs(scale(cor_col[,i])- min(scale(cor_col[,i]))) < 0.2)]))
}
to_skip = NULL
final_col = NULL
for (i in 1:dim(predmat)[2])
{
if (i %in% to_skip){next}
if (length(unlist(temp_keep[i]))>=2)
{
final_col = append(final_col,list(unlist(temp_keep[i])[which(!(which(donor.pops.all %in% unlist(temp_keep[i])) %in% to_skip) == TRUE)]))
to_skip = append(to_skip,which(donor.pops.all %in% unlist(temp_keep[i]))[2:length(unlist(temp_keep[i]))])
}
else
{
final_col = append(final_col,temp_keep[i])
}
}
final_col = unique(final_col)
keep = final_col
col_temp_keep = keep
donor.label.vec_old = donor.label.vec
ref = unique(keep)
for (i in 1:length(ref))
{
pop_temp = unlist(ref[i])
temp = which(donor.pops.all %in% pop_temp)
for (j in 1:length(temp))
{
donor.label.vec[donor.label.vec_old == temp[j]] = rep(i, length(donor.label.vec_old[donor.label.vec_old == temp[j]]))
}
}
for (i in 1:length(ref)){
ref[i] = paste(unlist(ref[i]), collapse = '_')
}
## combine rows across donor pops:
predmat_newcol = NULL
raw.copyprops.all_newcol =NULL
for (i in 1:length(keep))
{
col_temp = NULL
for (j in 1:length(unlist(keep[i])))
{
col_temp = c(col_temp,which(donor.pops.all == unlist(keep[i])[j]))
}
predmat_newcol = cbind(predmat_newcol, rowMeans(as.matrix(predmat[,col_temp])))
raw.copyprops.all_newcol = c(raw.copyprops.all_newcol, colMeans(as.matrix(raw.copyprops.all[col_temp])))
}
raw.copyprops.all = raw.copyprops.all_newcol
predmat = predmat_newcol
colnames(predmat)=ref
names(raw.copyprops.all)=ref
print(ref)
mem1 = num_target*ndonor*(ndonor*num.bins*8/10^9)
ndonor2 = length(predmat[1,])
mem2 = num_target*ndonor2*(ndonor2*num.bins*8/10^9)
print(paste("number of targets:",num_target))
if (num.bins<= 300) {print(paste("number of bins:",num.bins))}
if (num.bins>300) {print(paste0("number of bins:",num.bins,". ***In the parameter file, we suggest to use 'curve.range: 1 30' which is enough for making inference."))}
print(paste("number of donors in mode1:",ndonor))
print(paste("number of donors after merging in mode2:",ndonor2))
print(paste('Mode 1 requires memory of',round(mem1+1,1), 'G.'))
print(paste('Mode 2 requires memory of',round(mem2+1,1), 'G (may provide less precise inference).'))
print(paste('Mode 3 generally requires much less memory but can take longer time.'))
print(paste('(Note that, for larger estimated memory usage, these estimates may be off by 1G or so.)'))
quit()
}
##############################################################
#############################################################
### (I)-(a) START READING IN DATA:
##############################################################
#############################################################
donor.pops.all2=unique(newnames)
simname=recipient.pops
if (temp[5] == 'mem'){prerun(temp,donor.pops.all2,num.bins,id.file,copyvector.file)}
if (length(temp) < 5)
{
print('Please specify running mode whether 1,2 or 3. Now using default as mode 1.')
temp[5] = '1'
}
if (temp[5] != '1' && temp[5] != '2' && temp[5] != '3')
{
print('Please specify running mode whether 1,2 or 3. Now using default as mode 1.')
temp[5] = '1'
}
mode = temp[5]
## GET IDS FILE:
id.mat=read.table(id.file,as.is=TRUE)
#to.remove.id=(1:dim(id.mat)[1])[as.character(id.mat[,3])!='R' | as.character(id.mat[,3])!='r' | as.character(id.mat[,3])!='D' | as.character(id.mat[,3])!='d']
## assign labels (in painting) to each donor group:
donor.label.vec=rep(-9,ploidy*length(id.mat[,1]))
donor.pops.all.temp=donor.pops.all
if (length((1:length(donor.pops.all))[donor.pops.all==simname])>0)
donor.pops.all.temp=donor.pops.all.temp[-(1:length(donor.pops.all))[donor.pops.all==simname]]
for (i in 1:length(donor.pops.all.temp))
{
id.labels.i=(1:length(id.mat[,1]))[id.mat[,2]==donor.pops.all.temp[i] & id.mat[,3]!=0]
if (ploidy==2) id.labels.i=sort(c(2*id.labels.i,2*id.labels.i-1))
donor.label.vec[id.labels.i]=i
}
id.labels.i=(1:length(id.mat[,1]))[id.mat[,2]==simname & id.mat[,3]!=0]
if (ploidy==2) id.labels.i=sort(c(2*id.labels.i,2*id.labels.i-1))
donor.label.vec[id.labels.i]=0
to.remove.id=(1:dim(id.mat)[1])[as.character(id.mat[,3])=='0']
if (length(to.remove.id)>0) id.mat=id.mat[-to.remove.id,]
if (length(dim(id.mat))==0)
{
print(paste("SOMETHING WRONG WITH ",id.file," -- NO NON-EXCLUDED INDS? Exiting....",sep=''))
q(save='no')
}
recipient.label.vec=id.mat[,1][id.mat[,2]==simname]
## GET RAW COPY PROPS FOR ALL DONORS:
probs=read.table(copyvector.file,header=TRUE)
rownames.copyvector=as.character(probs[,1])
colnames.copyvector=as.character(read.table(copyvector.file,as.is=TRUE,nrows=1)[-1])
for (i in 1:length(donor.pops.all))
{
if (!is.element(donor.pops.all[i],as.character(id.mat[,2])) && !is.element(donor.pops.all[i],colnames.copyvector))
{
print(paste("COPY VECTOR COLUMN LABEL ",donor.pops.all[i]," NOT FOUND IN DONORS/RECIPIENTS OF ",id.file," OR COLUMNS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
}
for (i in 1:length(donor.pops.all2))
{
if (!is.element(donor.pops.all2[i],as.character(id.mat[,2])) && !is.element(donor.pops.all2[i],rownames.copyvector))
{
print(paste("DONOR POPULATION ",donor.pops.all2[i]," NOT FOUND IN DONORS/RECIPIENTS OF ",id.file," OR ROWS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
}
if (!is.element(simname,as.character(id.mat[,2])) && !is.element(simname,rownames.copyvector))
{
print(paste("RECIPIENT POPULATION ",simname," NOT FOUND IN DONORS/RECIPIENTS OF ",id.file," OR ROWS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
#match.colnames=match(as.character(colnames.copyvector),as.character(id.mat[,1]))
#match.colnamesII=match(as.character(colnames.copyvector),as.character(id.mat[,2]))
#for (i in 1:length(colnames.copyvector))
#{
# if (is.na(match.colnames[i]) && is.na(match.colnamesII[i]))
# {
# print(paste("COLUMN LABEL ",colnames.copyvector[i]," IN ",copyvector.file," IS NOT FOUND IN EITHER COLUMN OF ",id.file,"! Exiting....",sep=''))
# q(save='no')
# }
#}
#match.rownames=match(as.character(rownames.copyvector),as.character(id.mat[,1]))
#if (sum(is.na(match.rownames))!=0)
#{
# print(paste("SOME ROW LABELS IN ",copyvector.file," ARE NOT FOUND IN THE FIRST COLUMN OF ",id.file,"! Exiting....",sep=''))
# q(save='no')
#}
#for (i in 1:length(donor.pops.all2))
#{
# if (!is.element(donor.pops.all2[i],as.character(id.mat[,2][match.rownames])))
# {
# print(paste("DONOR POPULATION LABEL ",donor.pops.all[i]," NOT FOUND IN ROWS OF",copyvector.file,"! Exiting....",sep=''))
# q(save='no')
# }
#}
## combine columns across copy-vector pops:
predmat.orig=NULL
for (i in 1:length(donor.pops.all))
{
id.labels.i=c(donor.pops.all[i],as.character(id.mat[,1])[as.character(id.mat[,2])==donor.pops.all[i]])
match.i=NULL
for (j in 1:length(id.labels.i)) match.i=c(match.i,which(as.character(colnames.copyvector)==id.labels.i[j]))
#match.i=match(id.labels.i,as.character(colnames.copyvector))
#match.i=match.i[!is.na(match.i)]
if (length(match.i)==0)
{
print(paste("NO INDS OF ",donor.pops.all[i]," FOUND AMONG COLUMNS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
predmat.orig=cbind(predmat.orig,apply(matrix(as.matrix(probs[,2:dim(probs)[2]][,match.i]),nrow=dim(probs)[1]),1,sum))
}
rownames(predmat.orig)=rownames.copyvector
colnames(predmat.orig)=donor.pops.all
## combine rows across donor pops:
predmat=NULL
for (i in 1:length(donor.pops.all2))
{
id.labels.i=c(donor.pops.all2[i],as.character(id.mat[,1])[as.character(id.mat[,2])==donor.pops.all2[i]])
match.i=NULL
for (j in 1:length(id.labels.i)) match.i=c(match.i,which(as.character(rownames.copyvector)==id.labels.i[j]))
#match.i=match(id.labels.i,as.character(rownames.copyvector))
#match.i=match.i[!is.na(match.i)]
if (length(match.i)==0)
{
#print(id.labels.i[j])
print(paste("NO INDS OF ",donor.pops.all2[i]," FOUND AMONG ROWS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
predmat=rbind(predmat,apply(matrix(as.matrix(predmat.orig[match.i,]),ncol=dim(predmat.orig)[2]),2,mean))
}
rownames(predmat)=donor.pops.all2
colnames(predmat)=donor.pops.all
## GET RAW COPY PROPS FOR RECIPIENT:
id.labels.rec=c(simname,as.character(id.mat[,1])[as.character(id.mat[,2])==simname])
match.rec=NULL
for (j in 1:length(id.labels.rec)) match.rec=c(match.rec,which(as.character(rownames.copyvector)==id.labels.rec[j]))
#match.rec=match(id.labels.rec,as.character(rownames.copyvector))
#match.rec=match.rec[!is.na(match.rec)]
if (length(match.rec)==0)
{
print(paste("NO INDS OF ",simname," FOUND AMONG ROWS OF ",copyvector.file,"! Exiting....",sep=''))
q(save='no')
}
raw.copyprops.all=apply(matrix(as.matrix(predmat.orig[match.rec,]),ncol=dim(predmat.orig)[2]),2,mean)
names(raw.copyprops.all)=donor.pops.all
## remove self and standardize:
donor.pops.all.orig=donor.pops.all
donor.pops.all=donor.pops.all[!(colnames(predmat) %in% simname)]
donor.pops.all2=donor.pops.all2[!(rownames(predmat) %in% simname)]
predmat=predmat[,!(colnames(predmat) %in% simname)]
predmat=predmat[!(rownames(predmat) %in% simname),]
for(i in 1:nrow(predmat)) predmat[i,]=predmat[i,]/sum(predmat[i,])
raw.copyprops.all=raw.copyprops.all[!(names(raw.copyprops.all) %in% simname)]
raw.copyprops.all=raw.copyprops.all/sum(raw.copyprops.all)
##############################################################
#############################################################
### (I)-(b) IF REQUESTED, ONLY INFER PROPORTIONS OF ANCESTRY: (I.E. AS IN LESLIE ET AL 2015, NATURE)
##############################################################
#############################################################
if ((prop.ind==1 || prop.continue.ind==1) && num.iterations==0)
{
ourmix=getoverallfit(predmat,raw.copyprops.all)$x
ourmix=ourmix[ourmix>0]
ourmix=ourmix[ourmix>prop.cutoff]
#ourmix=ourmix/sum(ourmix)
donor.pops=names(ourmix)
donor.pops=donor.pops[sort(ourmix,index.return=TRUE)$ix]
ourmix=ourmix[sort(ourmix,index.return=TRUE)$ix]
write("### INFERRED ANCESTRY PROPORTIONS (MIXING COEFFICIENTS), WITHOUT INFERRING ANY ADMIXTURE EVENTS:",file=paste(save.file.props,prop.save.addon,prop.save.post,sep=''),ncolumns=1)
write.table(rbind(donor.pops,ourmix),file=paste(save.file.props,prop.save.addon,prop.save.post,sep=''),row.names=FALSE,col.names=FALSE,quote=FALSE,append=TRUE)
print("Finished!")
q(save='no')
}
##############################################################
#############################################################
### (I)-(c) OTHERWISE CONTINUE READING IN:
##############################################################
#############################################################
samples.filein=as.character(temp[3])
recomrates.filein=as.character(temp[4])
## find number of samples files:
num.samplefiles=0
readfile=file(samples.filein,open="r")
line2=1
while(!is.na(line2[1]))
{
line2=scan(readfile,nlines=1,what='char',quiet=TRUE)
if (!is.na(line2[1])) num.samplefiles=num.samplefiles+1
}
if (num.samplefiles==0)
{
print(paste("SOMETHING WRONG WITH INPUT FILE ",samples.filein," (PERHAPS EMPTY?). Exiting....",sep=''))
q(save='no')
}
close(readfile)
## find number of recom files:
num.recomfiles=0
readfile=file(recomrates.filein,open="r")
line2=1
while(!is.na(line2[1]))
{
line2=scan(readfile,nlines=1,what='char',quiet=TRUE)
if (!is.na(line2[1])) num.recomfiles=num.recomfiles+1
}
if (num.recomfiles==0)