forked from kishonylab/TB-diversity-across-organs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanalyze_de_novo_muts.m
1989 lines (1540 loc) · 83.4 KB
/
analyze_de_novo_muts.m
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
close all;
%% Parameter set up
%for genotype identification
min_snp_freq_in_single_sample_for_genotype_placement=.2;
purity_cutoff_for_sample_sorting=.8;
purity_cutoff_for_adding_in_singletons = .8 ;
min_average_coverage_for_genotype_id = 12;
loose_freq_threshold_for_majority = .4;
strict_freq_threshold_for_majority = .6; %strict treshold to avoid false groupings
noise_buffer_for_singletons =.15 ;
min_freq_genotype_in_at_least_one_site = .02;
%for genotype assignment
snp_threshold_for_assigning_to_genotypes = .2;
max_remaining_room_to_add_in_ancestor = .15;
max_unexplained_snps_to_add_in_ancestor = .8;
%for mixed strain infection plotting and analysis
number_dummy_muts_for_mixed_infections = 20;
%for transmission analysis
min_observations_for_transmission_analysis = 2;
min_isolates_per_site = 7;
min_freq_within_site = .03;
% how far upstream of the nearest gene to annotate something a promoter mutation
promotersize=150;
%% Enviornment set up -- probably won't need to change
masterdir=char(pwd);
REFGENOMEFOLDER=[masterdir '/MTB_anc'];
SCRIPTSDIRECTORY = [masterdir '/scripts'];
path(SCRIPTSDIRECTORY,path);
%% Things I need to convert into csv files
subjects=1:44;
subjects_with_multiple_strains=[11 15 28 37];
sites={'Lung1','Lung2','Lung3','Lung4','Lung5','Lung6','Eta','Liver','Spleen','SerousFluid','SerousFluid2','Lymph','LungPus'};
site_colors={'MidnightBlue','CornflowerBlue', 'Blue', 'DarkTurquoise','LightBlue','Teal','Green','DeepPink','Purple','Orange','DeepPink', 'Yellow', 'Maroon','Maroon', 'Maroon', 'Maroon', 'Maroon','Maroon'};
long_site_names={'Top_right_lung','Middle_right_lung','Bottom_right_lung','Top_left_lung','Middle_right_lung','Bottom_right_lung','Endotracheal_aspirate','Liver','Spleen','Serous_Fluid','Serous_Fluid_2','Lymph_node','Lung_pus'};
%% Initialize
NTs='ATCG';
folders={'trees' 'trees/genotypetrees_lung', 'trees/genotypetrees_organs', 'trees/temptreefolder', 'trees/all', 'summary_graphics', 'csvfiles_generated'};
for i=1:numel(folders)
if ~exist(folders{i},'dir')
mkdir(folders{i})
end
end
if ~exist('trees/dnapars','file')
copyfile([SCRIPTSDIRECTORY '/dnapars'],'trees/dnapars')
end
eta_site_number=find(strcmp(sites,'Eta'));
liver_site_number=find(strcmp(sites,'Liver'));
spleen_site_number=find(strcmp(sites,'Spleen'));
fid_tableS1=fopen([masterdir '/csvfiles_generated/forsupptable2.csv'],'w');
fid_tableS2=fopen([masterdir '/csvfiles_generated/forsupptable3.csv'],'w');
fid_tableS3=fopen([masterdir '/csvfiles_generated/forsupptable4.csv'],'w');
fid_Biosample=fopen([masterdir '/csvfiles_generated/forBiosample.csv'],'w');
%% Make empty data structures
observed_matrices={};
de_novo_muts_all=[];
de_novo_muts_placed=[];
adjacent_removed=[];
genotypematrices={};
genotypes_freq_sites_matrices={};
genotype_sites_times_matrices={};
compartment_lists={};
number_mutations_seperating_strains={};
distance_to_subject_MRCA=zeros(length(subjects),1);
observed_matrices_placed={};
observed_matrices_placed_with_multiple_lineages={};
average_coverage_isolates={};
defined_lineages_by_subject={};
genotypematrices_all_mutations={};
proportionlineage1_by_subject={};
genes_mutated_multiple_times_within_a_subject=[];
operons_mutated_multiple_times_within_a_subject=[];
subject_lineages=zeros(numel(subjects),1);
samples_per_subject=zeros(numel(subjects),1);
proprotion_minor_lineage=zeros(length(subjects),1);
average_coverage_subject=zeros(length(subjects),1);
number_specimens=zeros(length(subjects),1);
num_duplicates_removed=zeros(numel(subjects),1);
num_removed_because_name_not_well_formed=zeros(numel(subjects),1);
max_distance_between_genotypes=zeros(numel(subjects),1);
max_distance_between_genotypes_in_eta=nan(numel(subjects),1);
%% load in info about subjects
load([masterdir '/tools/prev_HIV_dx'])
load([masterdir '/tools/collection_dates'])
load([masterdir '/tools/on_arvs_at_admission'])
load([masterdir '/tools/subject_sex'])
load([masterdir '/tools/subject_age'])
%% Call genotypes by subject
for k=1:numel(subjects)
%% load in
cd([masterdir '/subject_folders/P' num2str(k)])
load('de_novo_muts')
observedmatrix(isnan(observedmatrix))=0;
numsamples=length(SampleNames);
%% categorize samples by locations
isolate_compartments=zeros(numel(SampleNames),1);
for i=1:numel(SampleNames)
splitname=strsplit(SampleNames{i},'-');
isolate_compartments(i)=find(strcmp(splitname{2},sites));
end
%% For Supplementary table 2
for i=1:spleen_site_number
if sum(isolate_compartments==i) > 0
fprintf(fid_tableS2,[num2str(sum(isolate_compartments==i)) ',']);
else
fprintf(fid_tableS2,',');
end
end
for i=(spleen_site_number+1):numel(sites)
if sum(isolate_compartments==i) > 0
fprintf(fid_tableS2,[num2str(sum(isolate_compartments==i)) ',' sites{i} ',']);
end
end
fprintf(fid_tableS2,'\n');
%% For uploading to SRA
for i=1:numel(SampleNames)
fprintf(fid_Biosample,[SampleNames{i} ',PRJNA323744,Mycobacterium tuberculosis,' SampleNames{i} ...
',Douglas Wilson,' collection_date{k} ',South Africa: Kwazulu-Natal,Homo sapiens,Tuberculosis,Morgue,29.6483 S 30.3318 E,'...
num2str(subject_age(k)) ',Postmortem,']);
if prev_HIV_dx(k)==0
fprintf(fid_Biosample,'Negative,No,');
elseif prev_HIV_dx(k)==-1
fprintf(fid_Biosample,'Positive,No,');
else
fprintf(fid_Biosample,'Positive,Yes,');
end
fprintf(fid_Biosample,[on_arvs_at_admission{k} ',' sex{k} ',P' num2str(k) ',' long_site_names{isolate_compartments(i)} '\n']);
end
%% save basic stats
average_coverage_subject(k)=mean(averagecoverage);
samples_per_subject(k)=numel(SampleNames);
number_specimens(k)=numel(unique(isolate_compartments));
if ~isempty(de_novo_muts)
%Sanity check for adjacent nucleotides
gp=[de_novo_muts(:).pos];
adjacent_starts=find(gp(2:end)-gp(1:end-1) < 2);
if ~isempty(adjacent_starts)
error('Error: Directly adjacent mutations found in single patient. Probably includes false positives. ')
end
%add this field to make things easier later
for i=1:numel(de_novo_muts)
de_novo_muts(i).subject=k;
end
%% Add in lineage info
if mean(proportionlineage1)~=1
observedmatrix=[observedmatrix; repmat(proportionlineage1,20,1); repmat(1-proportionlineage1,20,1)];
end
%% Find genotypes
[genotypematrix, sample_that_defined_each_genotype,orderbycoverage] = find_genotypes(observedmatrix, averagecoverage, ismember(k,subjects_with_multiple_strains), number_dummy_muts_for_mixed_infections,...
min_snp_freq_in_single_sample_for_genotype_placement, purity_cutoff_for_sample_sorting, purity_cutoff_for_adding_in_singletons,...
min_average_coverage_for_genotype_id,loose_freq_threshold_for_majority, strict_freq_threshold_for_majority, noise_buffer_for_singletons);
%% Assign genotypes to samples
[genotypes_freq_sites, genotype_sites_times, calls_for_tree, TreeSampleNames, genotypeOrder] = ...
assign_genotypes(observedmatrix,isolate_compartments,...
genotypematrix,numel(sites),snp_threshold_for_assigning_to_genotypes,...
max_remaining_room_to_add_in_ancestor,max_unexplained_snps_to_add_in_ancestor, SampleNames);
%% Make parsimony tree with all called genotypes called in all samples -- Figure 2C
nts_for_tree=char(calls_for_tree);
nts_for_tree(calls_for_tree==0)='A'; %actually identity doesn't matter -- 0's and 1's is fine
nts_for_tree(calls_for_tree==1)='T';
cd([masterdir '/trees/temptreefolder'])
treefilename=generate_parsimony_tree(nts_for_tree, TreeSampleNames, ['P' num2str(k)]);
TreeColors={}; for i=1:numel(TreeSampleNames); TreeColors{i}='16777216';end;
color_tree(treefilename, [masterdir '/trees/all/P' num2str(k) '.tree'], TreeSampleNames, TreeColors)
cd([masterdir '/subject_folders/P' num2str(k)])
%% Visualize each subject's mutation matrix
h=figure(6); clf; hold on;
%Sort samples and show their names
sites_in_subject=unique(isolate_compartments);
[sortedsites, orderisolates]=sort(isolate_compartments);
for i=1:numel(sites_in_subject)
c=sites_in_subject(i);
plot([-3 numel(de_novo_muts)+1], [find(sortedsites==c,1) find(sortedsites==c,1)]-.5 ,'k-')
numsamplesc=sum(isolate_compartments==c);
text(-3,find(sortedsites==c,1)+(numsamplesc/2 -.5),sites{c}, 'FontSize', 12)
end
plot([-3 numel(de_novo_muts)+1], [numel(SampleNames) numel(SampleNames)]+.5 ,'k-')
%Plot information about multiple strain infection and global
%lineages
if mean(proportionlineage1)==1 %single lineages
title(['P' num2str(k) ' - Lineage ' num2str(find(mean(proportion_global_lineages(1:6,:),2)>.95))],'FontSize',12)
subject_lineages(k)=find(mean(proportion_global_lineages(1:6,:),2)>.95);
else
lineages=find(mean(proportion_global_lineages(1:6,:),2)>.05);
t=['P' num2str(k) ' - mixed Lineage ' num2str(lineages(1))];
if numel(lineages)>1
t=[t ' & Lineage ' num2str(lineages(2))];
end
title(t,'FontSize',12)
for s=1:numel(proportionlineage1)
y=find(orderisolates==s);
proportionlineage1(isnan(proportionlineage1))=0;
patch([-2 -2 -1 -1],[y-.5 y+.5 y+.5 y-.5],'r', 'FaceAlpha', proportionlineage1(s), 'FaceColor', rgb('Red'))
patch([-1 -1 0 0],[y-.5 y+.5 y+.5 y-.5],'r', 'FaceAlpha', 1-proportionlineage1(s), 'FaceColor', rgb('Blue'))
end
end
for i=1:numel(de_novo_muts)
%Plot information about the location of each mutation
if isempty(de_novo_muts(i).locustag)
positionlabel=[de_novo_muts(i).gene1 '-' de_novo_muts(i).gene2]; %Intragenic
else
if ~isempty(de_novo_muts(i).gene)
genename=de_novo_muts(i).gene;
else
genename=de_novo_muts(i).locustag;
end
if ~isempty(de_novo_muts(i).muts) %Nonsynonymous
positionlabel=[genename '-' de_novo_muts(i).muts{1}];
else %Synonymous
positionlabel=[genename '(S)'];
end
end
%Show mutation frequency matrix
samples_p=find(observedmatrix(i,:)>.08);
for s=samples_p
y=find(orderisolates==s);
patch([i i i+1 i+1],[y-.5 y+.5 y+.5 y-.5],'r', 'FaceAlpha', observedmatrix(i,s), 'FaceColor', rgb('Black'))
end
text(i+.5,-.15*(numel(SampleNames)),positionlabel, 'FontSize', 6, 'Color',rgb('Black'), 'Rotation', 90)
end
%Plot information about which samples defined which genotypes
for i=1:numel(sample_that_defined_each_genotype)
if sample_that_defined_each_genotype(i) > 0 %important for multiple strain infections
y=find(orderisolates==sample_that_defined_each_genotype(i));
snps_i=find(genotypematrix(i,:)>0);
for j=snps_i
patch([j j j+1 j+1],[y-.5 y+.5 y+.5 y-.5],'r', 'FaceAlpha', 0, 'FaceColor', rgb('Black'), 'EdgeColor', rgb('Red'), 'LineWidth', 2)
end
end
end
set(gca, 'Ytick',[]); xlim([-3 numel(de_novo_muts)+1]); ylim([-.15*(numel(SampleNames)) numel(SampleNames)+1])
saveas(h,[masterdir '/summary_graphics/P' num2str(k) 'summary.jpg'],'jpg');close(h)
%% make a supplementary figure 1 illustrating genotype calling in subject 20
if k==20;
colors_for_fig2={'Thistle','FireBrick','DeepPink','Red','Coral','Wheat','Goldenrod','Gold'...
'MediumVioletRed','DeepPink','FireBrick','Red','Coral','Orange','SandyBrown','Yellow','Goldenrod'...
'MediumVioletRed','DeepPink','FireBrick','Red','Coral','Orange','SandyBrown','Yellow','Goldenrod'};
figure; clf; hold on;
title(['P' num2str(k)])
j=0;
for s=1:numel(orderbycoverage)
y=numel(orderbycoverage)-s+.5;
if ismember(orderbycoverage(s),sample_that_defined_each_genotype)
defineslineage=1;
[~,lineagedefined]=ismember(orderbycoverage(s),sample_that_defined_each_genotype);
j=j+1;
else
defineslineage=0;
end
plot([0 size(observedmatrix,1)+2],[y y],':', 'Color', rgb(site_colors{isolate_compartments(orderbycoverage(s))}),'LineWidth',2)
for p=1:size(observedmatrix,1);
if observedmatrix(p,orderbycoverage(s)) >= .05 %min(.08,max(omatrix(p,:)))
x=p; %(1- min(omatrix(p,orderbycoverage(s))+.2,1))*[1 1 1]
patch([x x x+.9 x+.9],[y-.4 y+.4 y+.4 y-.4],'r','FaceColor', (1- observedmatrix(p,orderbycoverage(s)))*[1 1 1],'EdgeColor', 'none')
if defineslineage & genotypematrix(lineagedefined,p)>0
plot([x x],[y-.4 y+.4],'Color', rgb(colors_for_fig2{j}),'LineWidth',2)
plot([x+.9 x+.9],[y-.5 y+.4],'Color', rgb(colors_for_fig2{j}),'LineWidth',2)
plot([x x+.9],[y+.4 y+.4],'Color', rgb(colors_for_fig2{j}),'LineWidth',2)
plot([x x+.9],[y-.4 y-.4],'Color', rgb(colors_for_fig2{j}),'LineWidth',2)
else
patch([x x x+.9 x+.9],[y-.4 y+.4 y+.4 y-.4],'r', 'FaceColor', (1-observedmatrix(p,orderbycoverage(s)))*[1 1 1],'EdgeColor', 'none')
end
end
end
end
set(gca,'Xtick',[])
set(gca,'Ytick',[])
xlim([-1 inf])
ylim([0 numel(orderbycoverage)+1])
end
%% average distance to MRCA
distance_to_MRCA_by_site=zeros(size(sites_in_subject));
for y=1:numel(sites_in_subject)
distance_to_MRCA_by_site(y)=mean(sum(observedmatrix(:,isolate_compartments==sites_in_subject(y))));
end
%% max distance between genotypes
maxdist = find_max_distance_between_genotypes(genotypematrix);
if ismember(k,subjects_with_multiple_strains)
maxdist=maxdist-(2*number_dummy_muts_for_mixed_infections)+sum(num_muts_seperating_strains);
end
max_distance_between_genotypes(k)=maxdist;
%repeat analysis within endotracheal aspirate only
found_in_eta=genotypes_freq_sites(:,strcmp(sites,'Eta'))>0;
max_distance_between_genotypes_in_eta(k)=find_max_distance_between_genotypes(genotypematrix(found_in_eta(1:end-1),:));
%don't include ancestor in case every sample in eta shares a mutation
%% save everything
compartment_lists{k}=isolate_compartments;
observed_matrices{k}=observedmatrix;
average_coverage_isolates{k}=averagecoverage;
observed_matrices_only_de_novo_mutations{k}=observedmatrix;
genotypematrix=genotypematrix(genotypeOrder,:); %first sort to match, because times and freqs already sorted
genotypes_freq_sites_normalized=genotypes_freq_sites./repmat(sum(genotypes_freq_sites),size(genotypes_freq_sites,1),1); %normalize this
%remove genotypes at very low frequency, unclassified mutations
genotypestoremove=sum(genotypes_freq_sites_normalized(1:end-1,:)>min_freq_genotype_in_at_least_one_site,2)==0;
mutationstoremove=sum(genotypematrix(~genotypestoremove,:),1)==0;
genotypes_freq_sites(genotypestoremove,:)=[];
genotypes_freq_sites_matrices{k}=genotypes_freq_sites;
genotype_sites_times(genotypestoremove,:)=[];
genotype_sites_times_matrices{k}=genotype_sites_times;
genotypematrix(genotypestoremove,:)=[];
genotypematrices_all_mutations{k}=genotypematrix;
genotypematrices{k}=genotypematrix(:,~mutationstoremove);
observed_matrices_placed_with_multiple_lineages{k}=observedmatrix(~mutationstoremove,:);
if ismember(k,subjects_with_multiple_strains)
mutationstoremove=mutationstoremove(1:end-2*number_dummy_muts_for_mixed_infections);
observed_matrices_only_de_novo_mutations{k}=observedmatrix(1:end-(2*number_dummy_muts_for_mixed_infections),:);
proportionlineage1_by_subject{end+1}=proportionlineage1;
if mean(proportionlineage1) > .5
proprotion_minor_lineage(k)=1-mean(proportionlineage1);
proprotion_minor_lineage_isolates=1-proportionlineage1;
else
proprotion_minor_lineage(k)=mean(proportionlineage1);
proprotion_minor_lineage_isolates=proportionlineage1;
end
observed_matrices_only_de_novo_mutations{k}=observedmatrix(~mutationstoremove,:);
end
de_novo_muts_all=[de_novo_muts_all de_novo_muts];
de_novo_muts_placed=[de_novo_muts_placed de_novo_muts(~mutationstoremove)];
observed_matrices_placed{k}=observedmatrix(~mutationstoremove,:);
distance_to_subject_MRCA(k)=mean(distance_to_MRCA_by_site);
if ismember(k,subjects_with_multiple_strains)
distance_to_subject_MRCA(k)=distance_to_subject_MRCA(k)-(2*number_dummy_muts_for_mixed_infections)+mean(num_muts_seperating_strains);
else
defined_lineages=sample_that_defined_each_genotype(genotypeOrder);
defined_lineages(genotypestoremove)=[];
defined_lineages_by_subject{k}=sample_that_defined_each_genotype;
end
number_mutations_seperating_strains{k}=num_muts_seperating_strains;
%% print supplementary table 1
[~,l2]=max(mean(proportion_global_lineages,2));
fprintf(fid_tableS1,[num2str(samples_per_subject(k)) ',' num2str(average_coverage_subject(k)) ',' num2str(mean(maxdist)) ',' num2str(distance_to_subject_MRCA(k)) ',' ...
num2str(l2) ',' num2str(numel(de_novo_muts)) '\n']);
%% print supplementary table 2
fprintf(fid_tableS3,'Subject P%i\n',k);
fprintf(fid_tableS3, 'Position,CDS,Gene Name,Annotation,Ancestral,Mutation,Coding change,');
for i=1:numel(SampleNames)
fprintf(fid_tableS3,[SampleNames{i} ',']);
end
fprintf(fid_tableS3,'\n');
for j=1:numel(de_novo_muts)
m=de_novo_muts(j);
alt=m.nts; alt(alt==m.anc)=[];
if ~isempty(m.muts)
mut=m.muts{1};
else
mut='';
end
if ~isempty(m.locustag)
x=m.annotation;
x(x==',')=':';
fprintf(fid_tableS3, '%i,%s,%s,%s,%s,%s,%s,', m.pos,m.locustag, m.gene,x, m.anc, alt, mut);
else
x=['Intergenic ' m.annotation];
x(x==',')=':';
fprintf(fid_tableS3, '%i,,,%s,%s,%s,,', m.pos,x, m.anc, alt);
end
for i=1:numel(SampleNames)
fprintf(fid_tableS3,'%2.2f,', observedmatrix(j,i));
end
fprintf(fid_tableS3,'\n');
end
fprintf(fid_tableS3, ',,,,,,Coverage,');
for i=1:numel(SampleNames)
fprintf(fid_tableS3,'%3.1f,', averagecoverage(i));
end
fprintf(fid_tableS3,'\n');
if ismember(k,subjects_with_multiple_strains)
fprintf(fid_tableS3, ',,,,,,Proprotion minor lineage,');
for i=1:numel(SampleNames)
fprintf(fid_tableS3,'%2.2f,', proprotion_minor_lineage_isolates(i));
end
end
fprintf(fid_tableS3,'\n\n\n');
else
%% print supplementary table 1
[~,l2]=max(mean(proportion_global_lineages,2));
fprintf(fid_tableS1,[num2str(samples_per_subject(k)) ',' num2str(average_coverage_subject(k)) ',0,0,' num2str(l2) ',0\n']);
%% print supplementary table 2
fprintf(fid_tableS3,'Subject P%i\n',k);
fprintf(fid_tableS3, 'No de novo mutations detected,, ,,,,,');
for i=1:numel(SampleNames)
fprintf(fid_tableS3,[SampleNames{i} ',']);
end
fprintf(fid_tableS3,'\n');
fprintf(fid_tableS3, ',,,,,,Coverage,');
for i=1:numel(SampleNames)
fprintf(fid_tableS3,'%3.1f,', averagecoverage(i));
end
fprintf(fid_tableS3,'\n');
if ismember(k,subjects_with_multiple_strains)
fprintf(fid_tableS3, ',,,,,,Proprotion minor lineage,');
for i=1:numel(SampleNames)
fprintf(fid_tableS3,'%1.2f,', proprotion_minor_lineage(i));
end
end
fprintf(fid_tableS3,'\n\n\n');
end
end
stop
cd(masterdir)
%% make useful structures
genomic_positions=[de_novo_muts_placed(:).pos];
genomic_positions_all=[de_novo_muts_all(:).pos];
subject_each_pos=[de_novo_muts_all(:).subject];
%% Sanity checks
%note if the same mutation was found de novo in multiple subjects
[number_times_found,unique_genomic_positions]=find_count_duplicates(genomic_positions_all);
if sum(ismember(genomic_positions,unique_genomic_positions(number_times_found>1))) > 0
disp('Warning: The following de novo mutations were detected in independent subjects:')
disp(unique_genomic_positions(number_times_found>1))
end
%check that none of the inferred trees violate parsimony -- do this in a sort of exhaustive way
for k=1:numel(subjects)
gmatrix=genotypematrices{k};
if ismember(k,subjects_with_multiple_strains) & size(gmatrix,2)>(2*number_dummy_muts_for_mixed_infections)
gmatrix=gmatrix(:,1:(end-(2*number_dummy_muts_for_mixed_infections)));
end
nonunique=find(sum(gmatrix)>1);
if numel(nonunique)>1
for a=1:numel(nonunique)
%for each mutation, find each mutation it is ever in a genotype with
i=nonunique(a);
comuts=find(sum(gmatrix(gmatrix(:,i)>0 & sum(gmatrix,2)>0,:)) & 1:size(gmatrix,2)>i');
for b=1:numel(comuts)
j=comuts(b);
if ismember([1 0],gmatrix(:,[i j]),'rows') & ismember([0 1],gmatrix(:,[i j]),'rows')
disp(['P' num2str(k)])
disp(gmatrix(sum(gmatrix(:,nonunique),2)>0,:))
error('Two mutations each found in seperate genotypes within the same subject (parsimony violation)')
end
end
end
end
end
%% plot distribution of strains across lung for multiple-strain infection - Fig 3A
figure; clf;
i=1;
fid_F3=fopen([masterdir '/csvfiles_generated/figure3sourcedata.csv'],'w');
fprintf(fid_F3,'#Figure 3A\n#Also see Supplementary Table 4 for Proportion Strain 1 by sample\n');
fprintf(fid_F3,'#Subject,Site,Mean(Proportion Strain 1), SEM(Proportion Strain 1)\n');
for k=1:numel(subjects)
if ismember(k,subjects_with_multiple_strains)
subplot(4,1,i);hold on;
proportionlineage1=proportionlineage1_by_subject{i};
isolate_compartments=compartment_lists{k};
p1=nan(1,7);
sem1=nan(1,7);
p1(1)=mean(proportionlineage1(isolate_compartments==eta_site_number));
sem1(1)=std(proportionlineage1(isolate_compartments==eta_site_number))/sqrt(sum(isolate_compartments==eta_site_number));
fprintf(fid_F3,['P' num2str(k) ',' 'Tracheal aspirate,' num2str(p1(1)) ',' num2str(sem1(1)) '\n']);
for c=1:6
if sum(isolate_compartments==c)>0
p1(c+1)=mean(proportionlineage1(isolate_compartments==c));
sem1(c+1)=std(proportionlineage1(isolate_compartments==c))/sqrt(sum(isolate_compartments==c));
fprintf(fid_F3,['P' num2str(k) ',' sites{c} ',' num2str(p1(c+1)) ',' num2str(sem1(c+1)) '\n']);
end
end
if mean(p1)>.5
p1=1-p1;
end
plot([0 8],[mean(p1(~isnan(p1))) mean(p1(~isnan(p1)))],'k-')
fprintf(fid_F3,['P' num2str(k) ',' 'Mean across samples,' num2str(mean(p1(~isnan(p1)))) '\n']);
bar([p1; 1-p1]','stacked','Edgecolor','None')
colormap(cell2mat(cellfun(@rgb,{'DimGray','LightGray'},'UniformOutput', false)'))
if i > 1
plot([1:numel(p1); 1:numel(p1)], [p1-sem1; p1+sem1], 'k-','LineWidth',2)
end
set(gca,'xtick',[])
set(gca,'ytick',0:.25:1)
set(gca,'yticklabel',{'0', '','.5', '','1'});
i=i+1;
xlim([0 8])
end
end
%% average coverage stats
number_subjects_for_which_samples_are_diverse_scrapes=12;
avgcovscrapes=sum(average_coverage_subject(1:number_subjects_for_which_samples_are_diverse_scrapes).*samples_per_subject(1:number_subjects_for_which_samples_are_diverse_scrapes))/sum(samples_per_subject(1:number_subjects_for_which_samples_are_diverse_scrapes));
avgcovcolonies=sum(average_coverage_subject(number_subjects_for_which_samples_are_diverse_scrapes+1:end).*samples_per_subject(number_subjects_for_which_samples_are_diverse_scrapes+1:end))/sum(samples_per_subject(number_subjects_for_which_samples_are_diverse_scrapes+1:end));
fprintf(1,['Avg cov scrapes ' num2str(avgcovscrapes) '\n']);
fprintf(1,['Avg cov colonies ' num2str(avgcovcolonies) '\n']);
%% compare dMRCA across groups
load([masterdir '/tools/prev_HIV_dx'])
% -1 indicates dx of HIV upon death; 0 indicates HIV negative; 1 indicates HIV positive
dMRCA_prev_HIV_dx=distance_to_subject_MRCA(prev_HIV_dx > 0 & ~ismember(subjects,subjects_with_multiple_strains)');
dMRCA_no_prev_HIV_dx=distance_to_subject_MRCA(prev_HIV_dx <1 & ~ismember(subjects,subjects_with_multiple_strains)');
p_value_different = ranksum(dMRCA_no_prev_HIV_dx,dMRCA_prev_HIV_dx);
%% Figure 2a & 2b
%dMRCA
figure; clf;
subplot(2,1,1)
hold on;
bins=[-1.65:.25:3.5];
plot_distance_to_subject_MRCA=distance_to_subject_MRCA;
plot_distance_to_subject_MRCA(plot_distance_to_subject_MRCA<.08)=.08;
hist(log10(plot_distance_to_subject_MRCA),bins);
xlabel('Average SNP distance to subject MRCA')
ylabel('Number of subjects')
h = findobj(gca,'Type','patch');
set(h,'FaceColor',rgb('Black'))
set(h,'EdgeColor',rgb('White'))
set(gca,'Ytick',0:5:20)
set(gca,'Ytick',0:5:20)
ticks=-1:.5:3.5;
set(gca,'Xtick',ticks(1:2:end))
set(gca,'Xticklabel',10.^ticks(1:2:end))
ylim([-.01 15])
xlim([-1.35 inf])
fid_F2=fopen([masterdir '/csvfiles_generated/figure2sourcedata.csv'],'w');
fprintf(fid_F2,'\n#Figure 2A\n#Also see Supplementary Table 2; Supplementary Table 4; and Supplementary Figure 3\n');
fprintf(fid_F2,'#Subject,Distance to subject MRCA\n');
for i=1:numel(plot_distance_to_subject_MRCA)
fprintf(fid_F2,['P' num2str(i) ',' num2str(plot_distance_to_subject_MRCA(i)) '\n']);
end
% number of de novo mutations per subject
subplot(2,1,2); hold on;
[number_mutations_per_subject_n,subject_i]=find_count_duplicates([de_novo_muts_all.subject]);
number_mutations_per_subject=zeros(numel(subjects),1);
number_mutations_per_subject(subject_i)=number_mutations_per_subject_n;
hist(number_mutations_per_subject,0:1:63);
h = findobj(gca,'Type','patch');
set(h,'FaceColor',rgb('Black'))
set(h,'EdgeColor','white')
xlabel('Number of de novo mutations')
ylabel('Number of subjects')
set(gca,'Ytick',0:2:6)
xlim([-.75 66])
ylim([-.01 7])
fprintf(fid_F2,'\n\n#Figure 2B\n#Also see Supplementary Table 2; Supplementary Table 4; and Supplementary Figure 3\n');
fprintf(fid_F2,'#Subject,Number of de novo mutations per subject\n');
for i=1:numel(number_mutations_per_subject)
fprintf(fid_F2,['P' num2str(i) ',' num2str(number_mutations_per_subject(i)) '\n']);
end
%% suppelemental figure about sampling
figure; clf;
subplot(2,2,1);hold on;
plot(samples_per_subject, number_mutations_per_subject,'ko','MarkerFaceColor',rgb('DarkGray'),'MarkerSize', 6)
plot(samples_per_subject(prev_HIV_dx==-1), number_mutations_per_subject(prev_HIV_dx==-1),'ko','MarkerFaceColor',rgb('Blue'),'MarkerSize', 6)
plot(samples_per_subject(prev_HIV_dx==0), number_mutations_per_subject(prev_HIV_dx==0),'ko','MarkerFaceColor',rgb('Red'),'MarkerSize', 6)
coeff=polyfit(samples_per_subject',number_mutations_per_subject',1);
plot(0:150,(0:150)*coeff(1)+coeff(2),'k-')
xlim([0 150])
set(gca,'Ytick',0:15:75)
a=corrcoef(samples_per_subject',number_mutations_per_subject');
disp(a(1,2)^2);
subplot(2,2,2);hold on;
plot(number_specimens, number_mutations_per_subject,'ko','MarkerFaceColor',rgb('DarkGray'),'MarkerSize', 6)
plot(number_specimens(prev_HIV_dx==-1), number_mutations_per_subject(prev_HIV_dx==-1),'ko','MarkerFaceColor',rgb('Blue'),'MarkerSize', 6)
plot(number_specimens(prev_HIV_dx==0), number_mutations_per_subject(prev_HIV_dx==0),'ko','MarkerFaceColor',rgb('Red'),'MarkerSize', 6)
coeff=polyfit(number_specimens',number_mutations_per_subject',1);
plot(0:11,(0:11)*coeff(1)+coeff(2),'k-')
xlim([2 11])
set(gca,'Ytick',0:15:75)
a=corrcoef(number_specimens',number_mutations_per_subject');
disp(a(1,2)^2);
simpleinf= ~ismember(subjects,subjects_with_multiple_strains)';
subplot(2,2,3);hold on;
plot(samples_per_subject(simpleinf), distance_to_subject_MRCA(simpleinf),'ko','MarkerFaceColor',rgb('Gray'),'MarkerSize', 6)
plot(samples_per_subject(prev_HIV_dx==-1 & simpleinf), distance_to_subject_MRCA(prev_HIV_dx==-1 & simpleinf),'ko','MarkerFaceColor',rgb('Blue'),'MarkerSize', 6)
plot(samples_per_subject(prev_HIV_dx==0 & simpleinf), distance_to_subject_MRCA(prev_HIV_dx==0 & simpleinf),'ko','MarkerFaceColor',rgb('Red'),'MarkerSize', 6)
coeff=polyfit(samples_per_subject(simpleinf)',distance_to_subject_MRCA(simpleinf)',1);
plot(0:150,(0:150)*coeff(1)+coeff(2),'k-')
xlim([0 150])
a=corrcoef(samples_per_subject(simpleinf)',distance_to_subject_MRCA(simpleinf)');
disp(a(1,2)^2);
subplot(2,2,4);hold on;
plot(number_specimens(simpleinf), distance_to_subject_MRCA(simpleinf),'ko','MarkerFaceColor',rgb('Gray'),'MarkerSize', 6)
plot(number_specimens(prev_HIV_dx==-1 & simpleinf), distance_to_subject_MRCA(prev_HIV_dx==-1& simpleinf),'ko','MarkerFaceColor',rgb('Blue'),'MarkerSize', 6)
plot(number_specimens(prev_HIV_dx==0 & simpleinf), distance_to_subject_MRCA(prev_HIV_dx==0 & simpleinf),'ko','MarkerFaceColor',rgb('Red'),'MarkerSize', 6)
coeff=polyfit(number_specimens(simpleinf)',distance_to_subject_MRCA(simpleinf)',1);
plot(0:11,(0:11)*coeff(1)+coeff(2),'k-')
xlim([2 11])
a=corrcoef(number_specimens(simpleinf)',distance_to_subject_MRCA(simpleinf)');
disp(a(1,2)^2);
%% proportion minor lineage
for i=1:numel(proportionlineage1_by_subject)
x=1-mean(proportionlineage1_by_subject{i});
if x > .6
x=1-x;
end
fprintf(['Proportion Lineage 1: ' num2str(x) '\n']);
end
%% supplemental fig 2a legened
k=20;
figure; clf; hold on;
s=0:.1:1;
for i=1:numel(s)
x=1;
y=i;
patch([x x x+1 x+1],[y-.5 y+.5 y+.5 y-.5],'r', 'FaceColor', (1- s(i))*[1 1 1],'EdgeColor', rgb('Black'))
end
set(gca,'Xtick',[])
set(gca,'Ytick',[])
%% colored block labels for supplemental figure 2c
%These orders copied in from .tree file
%P20
treeorder={'Liver-C5-7','Liver-C5-2','Liver-C4-1','Liver-C2-1','Liver-C1-4','Liver-A5-1','Liver-A4-1','Liver-A3-1','Liver-A1-1','Lung6-C4-1','Lung6-B5-1','Lung6-B4-1','Lung6-B2-4','Lung6-B1-1','Lung6-A3-1','Lung5-C4-1','Lung5-C2-3','Lung5-C1-1','Lung5-B5-1','Lung5-A5-1','Lung5-A1-5','Lung4-A4-7','Lung4-A4-2','Lung3-C3-1','Lung3-C2-3','Lung3-B5-4','Liver-C1-5','Lung6-B3-1','Lung6-B2-5','Lung5-C5-1','Lung5-A2-9','Lung5-A1-4','Lung4-C4-1','Lung4-C3-1','Lung4-A5-5','Lung4-A3-3','Lung4-C2-1','Lung4-A5-4','Lung4-A3-6','Lung4-A2-1','Lung4-A1-1','Lung3-C5-2','Lung3-C2-6','Lung3-C1-4','Lung3-B5-3','Lung3-B1-4','Liver-B3-6','Liver-B1-1','Lung5-C3-1','Lung5-C2-6','Lung3-C5-7','Lung3-C4-1','Lung3-C1-5','Lung3-B5-2','Lung3-B4-1','Lung3-B2-1','Lung3-B1-5','Lung3-A1-1','Lung2-C5-3','Lung2-C4-3','Lung2-C1-1','Lung2-B6-7','Lung2-B5-6','Lung2-B2-4','Lung2-A4-2','Lung2-A3-3','Lung2-A2-7','Lung2-A1-7','Lung2-C5-6','Lung2-C4-6','Lung2-B6-2','Lung2-B5-3','Lung2-B4-9','Lung2-B3-9','Lung2-B2-5','Lung2-B1-8','Lung2-A4-7','Lung2-A3-6','Lung2-A2-2','Lung2-A1-2','Lung1-B2-1','Lung1-A4-1','Lung1-A3-1','Lung1-A2-1','Lung1-A1-1','Eta-C4-100','Eta-B5-100','Eta-B4-100','Eta-B1-100','Eta-A5-100','Eta-A4-100','Eta-A3-100','Lung2-A5-9','Eta-B2-100','Eta-A1-90a'};
%P15
treeorder={'Lung6-C2-9','Lung5-C5-7','Lung5-C4-7','Lung5-C3-9','Lung5-C2-6','Lung5-B5-9','Lung5-B4-9','Lung5-B3-7','Lung5-B3-2','Lung5-A4-9','Lung5-A3-3','Lung5-A2-9','Lung4-C5-9','Lung4-C4-9','Lung4-C3-9','Lung4-C2-9','Lung4-C1-9','Lung4-B5-5','Lung4-B5-3','Lung4-B3-9','Lung4-B2-9','Lung4-B1-8','Lung4-A5-9','Lung4-A4-9','Lung4-A3-9','Lung4-A2-3','Lung4-B4-9','Lung4-A2-6','Lung3-C2-8','Lung3-B1-9','Lung3-A5-8','Lung3-A2-9','Lung2-C4-2','Lung2-B5-9','Lung2-B4-7','Lung2-B2-3','Lung5-A3-4','Lung2-A5-2','Lung2-A4-3','Lung2-A3-8','Lung2-A1-5','Eta-C4-98a','Eta-C3-99a','Eta-C1-99a','Eta-B5-98a','Eta-B4-98a','Eta-B2-98a','Eta-B1-98a','Eta-A4-97a','Eta-A3-98a','Eta-A1-97a','Liver-C4-9','Liver-C3-8','Liver-C2-5','Liver-C2-4','Liver-C1-8','Liver-A2-9','Liver-A1-9','Liver-C5-9','Lung6-C5-9','Lung6-C3-9','Lung6-B5-9','Lung6-B4-9','Lung6-B3-9','Lung6-B2-9','Lung6-B1-9','Lung6-A5-8','Lung6-A4-9','Lung6-A3-9','Lung6-C4-9','Lung6-C1-9','Lung6-A1-8','Lung5-C5-2','Lung5-C4-2','Lung5-C2-3','Lung5-A1-9','Lung4-A1-5','Lung4-A1-3','Lung3-C1-9','Lung3-A6-7','Lung3-A4-9','Lung3-A3-6','Lung3-A6-2','Lung3-A3-3','Lung2-C4-7','Lung2-C3-8','Lung2-C2-8','Lung2-C1-6','Lung2-C1-2','Lung2-B4-2','Lung2-B3-9','Lung2-B2-6','Lung2-B1-8','Lung2-A5-6','Lung2-A4-6','Lung2-A2-9','Lung2-A1-4','Lung1-C5-9','Lung1-C4-9','Lung1-C3-9','Lung1-C2-9','Lung1-C1-9','Lung1-B5-9','Lung1-B4-9','Lung1-B3-9','Lung1-B2-9','Lung1-B1-9','Lung1-A5-9','Lung1-A4-9','Lung1-A3-9','Lung1-A2-9','Lung1-A1-9','Eta-C5-98a','Eta-C2-98a','Eta-B3-98a','Eta-A2-98a'};
sitesk=zeros(1,numel(treeorder));
figure; clf; hold on;
for s=1:numel(treeorder)
x=strsplit(treeorder{s},'-');
plot([0 1],[s s], '-', 'Color', rgb(site_colors(strcmp(x{1},sites))),'LineWidth',3);
end
ylim([-2 numel(treeorder)+1])
figure; clf; hold on;
for s=1:numel(sites)
plot([0 1],[s s], '-', 'Color', rgb(site_colors(s)),'LineWidth',10);
end
%% prepare for dNdS analysis
dNdSfilename=[REFGENOMEFOLDER '/dNdStools_' num2str(promotersize) '.mat'];
if exist(dNdSfilename,'file')
load(dNdSfilename)
else
div_mutation_type_probability_matrix(REFGENOMEFOLDER, promotersize);
save(dNdSfilename, 'genomewide_possibilities', 'cds_possibilities')
end
%% load in intersubject muts for compairsion for dNdS
cd([masterdir '/subject_folders/intersubject'])
load('de_novo_muts')
interpatient_genomic_positions=[de_novo_muts(:).pos];
interpatient_snps=interpatient_genomic_positions(~ismember(interpatient_genomic_positions,genomic_positions_all));
interpatient_types=[de_novo_muts(:).type];
Ni=sum(interpatient_types=='N');
Si=sum(interpatient_types=='S');
intersubject_typecounts=zeros(4,1);
intersubject_mutationmatrix=zeros(4,4);
for i=1:numel(interpatient_snps);
anc=find(NTs==de_novo_muts(i).anc);
new=de_novo_muts(i).nts;
if find(new==NTs(anc) & numel(new)>1)
new(new==NTs(anc))=[];
new(new=='N')=[];
new=find('ATCG'==new(1));
intersubject_mutationmatrix(anc,new)=intersubject_mutationmatrix(anc,new)+1;
if de_novo_muts(i).type=='N'
intersubject_typecounts(1)=intersubject_typecounts(1)+1;
elseif de_novo_muts(i).type=='S'
intersubject_typecounts(2)=intersubject_typecounts(2)+1;
elseif de_novo_muts(i).type=='P'
intersubject_typecounts(3)=intersubject_typecounts(3)+1;
elseif de_novo_muts(i).type=='I'
intersubject_typecounts(4)=intersubject_typecounts(4)+1;
else
error('unrecognized type')
end
end
end
%% dndS different number of mutations
categories={find(~cellfun(@isempty,{de_novo_muts_all.locustag}))} ;
mutationmatrix=zeros(4,4,numel(categories)); %last dimension is context
typecounts=zeros(numel(categories),4); %NSPI %first dimension is context
for context=1:numel(categories)
muts_in_category=categories{context};
for j=1:numel(muts_in_category);
i=muts_in_category(j);
anc=find(NTs==de_novo_muts_all(i).anc);
new=de_novo_muts_all(i).nts;
if find(new==NTs(anc))
new(new==NTs(anc))=[];
new(new=='N')=[];
new=find('ATCG'==new);
mutationmatrix(anc,new,context)=mutationmatrix(anc,new,context)+1;
if de_novo_muts_all(i).type=='N'
typecounts(context,1)=typecounts(context,1)+1;
elseif de_novo_muts_all(i).type=='S'
typecounts(context,2)=typecounts(context,2)+1;
elseif de_novo_muts_all(i).type=='P'
typecounts(context,3)=typecounts(context,3)+1;
elseif de_novo_muts_all(i).type=='I'
typecounts(context,4)=typecounts(context,4)+1;
else
error('unrecognized type')
end
end
end
end
typecounts=[intersubject_typecounts'; typecounts];
mutationmatrix=cat(3,intersubject_mutationmatrix, mutationmatrix);
mutO = div_matrix2_6types(mutationmatrix);
percentN_matrix=(genomewide_possibilities(:,:,1)./(genomewide_possibilities(:,:,1)+genomewide_possibilities(:,:,2)));
percentN_types=div_matrix2_6types(percentN_matrix)./2;
No=typecounts(:,1);
So=typecounts(:,2);
expectedN=mutO'*percentN_types;
expectedS=sum(mutO)'-expectedN;
NSe=expectedN./expectedS;
NSo=typecounts(:,1)./typecounts(:,2);
mycolors=([rgb('green'); rgb('purple'); rgb('yellow'); rgb('red'); rgb('blue'); rgb('black'); rgb('gray')]);
%Indidiviudal
[upperCI,lowerCI]=binomialCIdNdS(No,So,NSe(1));
figure; clf; hold on;
for i=1:numel(NSo)
h=bar(i,NSo(i)/NSe(i));
set(h,'FaceColor',mycolors(i,:));
% h(1).BaseValue = 1;
end
plot([1:numel(NSo);1:numel(NSo)],[lowerCI';upperCI'],'k');
ylim([.4 2])
set(gca,'Ytick',[0.25 .5 1 2])
set(gca,'Yticklabel',{'0.25', '.5' '1' '2' '4'})
set(gca,'YScale','log')
set(gca,'Xtick',1:numel(NSo))
set(gca,'Xticklabel',{'Intersubject SNPs', 'Intrasubject SNPS', 'Genes mutated more than once', 'Genes mutated three times', 'Genes mutated twice within a subject'})
p_purifying_selection=binocdf(typecounts(:,1),typecounts(:,1)+typecounts(:,2),expectedN./(expectedN+expectedS));
figure; clf; hold on;
h=bar(1,NSo(2)/NSe(2));
set(h,'FaceColor',rgb('gray'));
plot([1 1],[lowerCI(2) upperCI(2)],'k');
h=bar(2,NSo(1)/NSe(1));
set(h,'FaceColor',rgb('white'));
plot([2 2],[lowerCI(1) upperCI(1)],'k');
ylim([.6 1.5])
xlim([0 3])
set(gca,'Ytick',[0.25 .5 .75 1 1.5 2 4])
set(gca,'Xtick',[4])
set(gca,'YScale','log')
%% show mutation spectra
mutationmatrix_all=zeros(4,4);
for i=1:numel(de_novo_muts_placed)
anc=find(NTs==de_novo_muts_placed(i).anc);
new=de_novo_muts_placed(i).nts;
if find(new==NTs(anc))
new(new==NTs(anc))=[];
new(new=='N')=[];
new=find('ATCG'==new);
mutationmatrix_all(anc,new)=mutationmatrix_all(anc,new)+1;
end
end
mutO_interpateint=div_matrix2_6types(intersubject_mutationmatrix)/sum(intersubject_mutationmatrix(:));
mutO_intrasubject=div_matrix2_6types(mutationmatrix_all)/sum(mutationmatrix_all(:));
%build expecation based on %normalize for GC content
ATCGpercentongenome=sum(sum(genomewide_possibilities,3),2)/sum(genomewide_possibilities(:));
GCcontent=ATCGpercentongenome(3)+ATCGpercentongenome(4);
ATcontent=1-GCcontent;
%expectation based on transitions being twice as likely as transversions
expectation=[ATcontent/4 ATcontent/4 GCcontent/4 GCcontent/4 ATcontent/2 GCcontent/2];
figure; clf; hold on;
bar([mutO_intrasubject([1 2 4 5 3 6]) mutO_interpateint([1 2 4 5 3 6])], 'grouped'); colormap([rgb('Gray'); rgb('White');]);
plot([(1:6)-.25; (1:6)+.3],[expectation; expectation], 'k--', 'LineWidth', 2);
ylabel('Percent of SNPs')
set(gca,'Ytick',0:.1:.5)
set(gca,'Xtick',1:6)
set(gca,'Xticklabel',{'AT->TA', 'AT->CG', 'GC->CG', 'GC->TA', 'AT->GC', 'GC->AT'})
%legend({'Intrasubject SNPs', 'Intersubject SNPs'})
ylim([0 .5])
a=div_matrix2_6types(intersubject_mutationmatrix);
b=div_matrix2_6types(mutationmatrix_all);
pvalue_for_intra_vs_inter_spectrum=fexact([b(5) b(6); a(5) a(6);]);
% show probability amino acid changing
figure; clf; hold on;
bar(percentN_types); colormap('Gray');
set(gca,'Xtick',1:6)
set(gca,'Xticklabel',{}) %{'AT->TA', 'AT->CG', 'GC->CG', 'GC->TA', 'AT->GC', 'GC->AT'})
set(gca,'Ytick',.5:.1:1)
ylim([.5 .9])
ylabel('Probability amino acid changing')
%% show how diveristy within lung is distributed, include eta -- Figure 3C
fprintf(fid_F3,'\n\n#Figure 3C\n#Also see Supplementary Table 4 for more information on each mutated position and distribution across samples\n');