-
Notifications
You must be signed in to change notification settings - Fork 10
/
Tree.cpp
1684 lines (1514 loc) · 71 KB
/
Tree.cpp
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
#include <random>
#include <cmath>
#include <cfloat>
#include <vector>
#include <stack>
#include <iostream>
#include <fstream>
#include "Tree.h"
#include "Node.h"
#include "Scores.h"
#include "input.h"
#include <assert.h>
//global variables
extern int n_cells;
extern int n_loci;
extern int n_regions;
extern std::vector<Cell> cells;
extern Data data;
extern Params parameters;
Tree::Tree(Scores* cache, bool use_CNA):
hastings_ratio(-1.0),
use_CNA(use_CNA)
{
cache_scores = cache;
n_nodes = 3+ (std::rand()%8);
dropout_rates = std::vector<double>(n_loci,0.05);
dropout_rates_ref = std::vector<double>(n_loci,0.05);
dropout_rates_alt = std::vector<double>(n_loci,0.05);
//Generate a random tree
parents.resize(n_nodes);
parents[0]=-1; //root
for (int i=1;i<n_nodes;i++){
parents[i]=std::rand()%i; // new node attached randomly to one of the existing nodes.
}
children.resize(n_nodes);
compute_children();
//Initialize the nodes.
nodes.resize(n_nodes);
node_probabilities.resize(n_nodes);
for (int i=0;i<n_nodes;i++){
nodes[i] = new Node(cache_scores);
node_probabilities[i] = 1.0/n_nodes;
}
//randomly assign each somatic mutation to a node and compute the genotypes
for (int i=0;i<n_loci;i++){
nodes[std::rand()%n_nodes]->add_mutation(i);
}
compute_nodes_genotypes();
// Initialize utils
cells_attach_loglik.resize(n_cells);
cells_loglik.resize(n_cells);
cells_attach_prob.resize(n_cells);
best_attachments.resize(n_cells);
compute_likelihood();
compute_prior_score();
update_full_score();
}
Tree::Tree(){
//nodes.clear();
//doublets.clear();
cells_attach_loglik.resize(n_cells);
cells_loglik.resize(n_cells);
cells_attach_prob.resize(n_cells);
best_attachments.resize(n_cells);
}
Tree::Tree(const Tree& source):
// copy constructor
use_CNA(source.use_CNA),
n_nodes(source.n_nodes),
parents(source.parents),
children(source.children),
DFT_order(source.DFT_order),
node_probabilities(source.node_probabilities),
dropout_rates(source.dropout_rates),
dropout_rates_ref(source.dropout_rates_ref),
dropout_rates_alt(source.dropout_rates_alt),
region_probabilities(source.region_probabilities),
candidate_regions(source.candidate_regions),
regions_successor(source.regions_successor),
log_prior_score(source.log_prior_score),
log_likelihood(source.log_likelihood),
log_score(source.log_score),
cache_scores(source.cache_scores)
{
// Deep copy of the nodes
for (Node* node: source.nodes){
nodes.push_back(new Node(*node));
}
// Initialize utils
//cells_attach_loglik.resize(n_cells);
//cells_loglik.resize(n_cells);
//cells_attach_prob.resize(n_cells);
cells_attach_loglik = source.cells_attach_loglik;
cells_loglik = source.cells_loglik;
cells_attach_prob = source.cells_attach_prob;
best_attachments = source.best_attachments;
}
Tree::~Tree(){
for (Node* node: nodes){
delete node;
}
for (Node* doublet: doublets){
delete doublet;
}
}
Tree& Tree::operator=(const Tree& source){
// delete the old nodes
for (Node* n: nodes){
delete n;
}
nodes.clear();
if (parameters.use_doublets){
for (Node* doublet: doublets){
delete doublet;
}
doublets.clear();
}
use_CNA = source.use_CNA;
cache_scores = source.cache_scores;
n_nodes = source.n_nodes;
parents = source.parents;
children = source.children;
DFT_order=source.DFT_order;
node_probabilities = source.node_probabilities;
dropout_rates = source.dropout_rates;
dropout_rates_ref = source.dropout_rates_ref;
dropout_rates_alt = source.dropout_rates_alt;
region_probabilities = source.region_probabilities;
candidate_regions = source.candidate_regions;
regions_successor = source.regions_successor;
log_prior_score = source.log_prior_score;
log_likelihood = source.log_likelihood;
log_score = source.log_score;
best_attachments = source.best_attachments;
cells_attach_loglik = source.cells_attach_loglik;
cells_loglik = source.cells_loglik;
cells_attach_prob = source.cells_attach_prob;
for (int i=0;i<n_nodes;i++){
nodes.push_back(new Node(*source.nodes[i]));
}
return *this;
}
void Tree::compute_children(){
// Compute the list of children of each node, from the parent vector.
children.resize(n_nodes);
for (int i=0; i <n_nodes; i++){
children[i].clear();
}
for (int i=1; i <n_nodes; i++){ //start from 1 because the root has no parent
children[parents[i]].push_back(i);
}
// Also compute the DFT order
std::stack<int> stk;
DFT_order.clear();
stk.push(0);
while (!stk.empty()) {
int top = stk.top();
DFT_order.push_back(top);
stk.pop();
for (int child: children[top]) {
stk.push(child);
};
}
}
bool Tree::is_ancestor(int potential_ancestor, int potential_descendant){
if (potential_ancestor==0) return true;
int ancestor = potential_descendant;
while (ancestor!=0){
if (ancestor==potential_ancestor) return true;
ancestor = parents[ancestor];
}
return false;
}
void Tree::compute_nodes_genotypes(){
// Perform a depth-first traversal and compute the genotype of each node, based on the genotype of its parent.
std::stack<int> stk;
stk.push(0);
while (!stk.empty()) {
int top = stk.top();
stk.pop();
for (int child: children[top]) {
stk.push(child);
};
if (top!=0) nodes[top]->update_genotype(nodes[parents[top]]);
else nodes[top]->update_genotype(nullptr);
}
if (parameters.use_doublets){
for (Node* doublet: doublets){
delete doublet;
}
doublets.clear();
for (int k=0;k<n_nodes;k++){ //k: first node in the doublet
for (int l=k;l<n_nodes;l++){ //l: second node in the doublet
// the first node in the doublet should be the one which is earlier is the DFT order
// when we compute the scores of the doublet from its parent, we only update the updated loci of the second node
int i=0;
while (DFT_order[i]!=k && DFT_order[i]!=l) i++;
if (DFT_order[i]==k) doublets.push_back(new Node(*nodes[k],*nodes[l]));
else doublets.push_back(new Node(*nodes[l],*nodes[k]));
}
}
}
}
void Tree::compute_attachment_scores(bool use_doublets_local, bool recompute_CNA_scores){
// Compute the attachment scores of the nodes below node_index (including node_index) by performing a DFT
std::stack<int> stk;
stk.push(0);
while (!stk.empty()) {
int top = stk.top();
stk.pop();
for (int child: children[top]) {
stk.push(child);
};
if (top==0) // root: compute score from scratch
nodes[top]->compute_attachment_scores(use_CNA,dropout_rates_ref,dropout_rates_alt,region_probabilities);
else // start from the parent score, and only compute the difference on loci/regions affected by events
nodes[top]->compute_attachment_scores_parent(use_CNA,nodes[parents[top]], dropout_rates_ref,dropout_rates_alt,region_probabilities,recompute_CNA_scores);
}
if (use_doublets_local){
for (int k=0;k<n_nodes;k++){
for (int l=k;l<n_nodes;l++){
// traverse in DFT order, so that the scores of the parent are always already computed
int n1 = DFT_order[k]; // first node of the doublet
int n2 = DFT_order[l]; // second node of the doublet
int idx; // index in the doublets vector. The vector only contains pairs (k,l) with k<=l
if (n2>n1) idx = n_nodes * n1 - (n1*(n1-1))/2 + n2-n1;
else idx = n_nodes * n2 - (n2*(n2-1))/2 + n1-n2;
// compute doublet (0,0) from scratch
if (n1==0 && n2==0) doublets[idx]->compute_attachment_scores(use_CNA,dropout_rates_ref,dropout_rates_alt,region_probabilities);
// compute doublet (n1,n1) from (parent(n1),n1) (or (n1,parent(n1) )
else if (n1==n2){
int idx_parent;
if (parents[n1]>n1) idx_parent = n_nodes * n1 - (n1*(n1-1))/2 + parents[n1]-n1;
else idx_parent = n_nodes * parents[n1] - (parents[n1]*(parents[n1]-1))/2 + n1- parents[n1];
doublets[idx]->compute_attachment_scores_parent(use_CNA,doublets[idx_parent],dropout_rates_ref,dropout_rates_alt,region_probabilities,recompute_CNA_scores);
}
// compute doublet (n1,n2) from (n1,parent(n2)) (or (parent(n2),n1) )
else {
int idx_parent;
if (parents[n2]>n1) idx_parent = n_nodes * n1 - (n1*(n1-1))/2 + parents[n2]-n1;
else idx_parent = n_nodes * parents[n2] - (parents[n2]*(parents[n2]-1))/2 + n1- parents[n2];
doublets[idx]->compute_attachment_scores_parent(use_CNA,doublets[idx_parent],dropout_rates_ref,dropout_rates_alt,region_probabilities,recompute_CNA_scores);
}
}
}
}
}
void Tree::compute_likelihood(bool allow_diff_dropoutrates){
// Compute the likelihood by marginalizing over the attachment points
// Remove empty nodes
int n=1;
while (n<n_nodes){
if (nodes[n]->is_empty()){
delete_node(n);
n=1;
}
else{
n+=1;
}
}
compute_nodes_genotypes();
cache_scores->clear_cache_if_too_large();
// EM algorithm to find best node probabilities and dropout rates
// start with uniform node probabilities and the previous dropout rates
for (int k=0;k<n_nodes;k++) node_probabilities[k]=1.0/n_nodes;
avg_diff_nodeprob=10.0; // how much the node probabilities changed between 2 EM steps
avg_diff_dropoutrates=10.0; // how much the dropout rates changed between 2 EM steps
bool use_doublets_EM = false;
bool recompute_CNA_scores=true; // Compute CNA scores only once, because they do not depend on the dropout rates.
int n_loops=0;
while((avg_diff_nodeprob>0.0005|| avg_diff_dropoutrates>0.0001) && n_loops<100){
if (avg_diff_dropoutrates>0.0005) compute_attachment_scores(use_doublets_EM,recompute_CNA_scores); // attachment scores of cells to nodes do not depend on node probabilities
compute_cells_likelihoods(use_doublets_EM);
EM_step(use_doublets_EM,false);
recompute_CNA_scores=false;
n_loops++;
}
// See if likelihood can be improved by allowing, for some loci, the 2 alleles to have different dropout rates
if (allow_diff_dropoutrates){
EM_step(use_doublets_EM,true);
n_loops=0;
while((avg_diff_nodeprob>0.0005|| avg_diff_dropoutrates>0.0001) && n_loops<40){
if (avg_diff_dropoutrates>0.0005) compute_attachment_scores(use_doublets_EM,recompute_CNA_scores); // attachment scores of cells to nodes do not depend on node probabilities
compute_cells_likelihoods(use_doublets_EM);
EM_step(use_doublets_EM,true);
n_loops++;
}
}
if (parameters.use_doublets && !use_doublets_EM){
// if we did not use doublets for the EM algorithm, we need to recompute the scores with the doublets
compute_attachment_scores(parameters.use_doublets,true);
compute_cells_likelihoods(parameters.use_doublets);
}
log_likelihood=0;
for (int j=0;j<n_cells;j++){
log_likelihood+=cells_loglik[j];
}
}
void Tree::compute_cells_likelihoods(bool use_doublets_local){
int n_attachment_points = n_nodes;
if (use_doublets_local) n_attachment_points = (n_nodes*(n_nodes+3)) / 2; //can attach to a node or to a doublet
for (int j=0; j<n_cells; j++){
double max_loglik=-DBL_MAX;
int best_attach=-1;
cells_attach_loglik[j].resize(n_attachment_points);
for (int k=0; k<n_nodes;k++){
cells_attach_loglik[j][k] = nodes[k]->attachment_scores[j] + std::log(node_probabilities[k]);
if (use_doublets_local) cells_attach_loglik[j][k]+=std::log(1-parameters.doublet_rate);
if (cells_attach_loglik[j][k] > max_loglik){
max_loglik=cells_attach_loglik[j][k];
best_attach=k;
}
}
if (use_doublets_local){
int idx=0;
for (int k=0;k<n_nodes;k++){
for (int l=k;l<n_nodes;l++){
cells_attach_loglik[j][n_nodes+idx] = doublets[idx]->attachment_scores[j] + std::log(node_probabilities[k])
+ std::log(node_probabilities[l]) +std::log(parameters.doublet_rate);
if (k!=l) cells_attach_loglik[j][n_nodes+idx] += std::log(2); // the doublet (l,k) has the same probability as (k,l)
if ( cells_attach_loglik[j][n_nodes+idx] > max_loglik){
max_loglik = cells_attach_loglik[j][n_nodes+idx];
best_attach = n_nodes+idx;
}
idx++;
}
}
}
cells_loglik[j] = Scores::log_sum_exp(cells_attach_loglik[j]);
best_attachments[j] = best_attach;
}
}
void Tree::EM_step(bool use_doublets_local, bool allow_diff_dropoutrates){
int n_attachment_points = n_nodes;
if (use_doublets_local) n_attachment_points = (n_nodes*(n_nodes+3)) / 2; //can attach to a node or to a doublet
nodes_attachment_counts.resize(n_nodes);
for (int k=0;k<n_nodes;k++) nodes_attachment_counts[k]=0.0;
//E-step: compute probabilities that cell j is attached to node k, number of cells attached to each node and number of dropouts
for (int j=0; j<n_cells; j++){
cells_attach_prob[j].resize(n_attachment_points);
for (int k=0;k<n_nodes;k++){
cells_attach_prob[j][k] = std::exp(cells_attach_loglik[j][k]-cells_loglik[j]);
nodes_attachment_counts[k]+=cells_attach_prob[j][k]; // add posterior probability that cell j is attached to node k
}
if (use_doublets_local){
int idx=0;
for (int k=0;k<n_nodes;k++){
for (int l=k;l<n_nodes;l++){
cells_attach_prob[j][n_nodes+idx] = std::exp(cells_attach_loglik[j][n_nodes+idx]-cells_loglik[j]);
nodes_attachment_counts[k] += cells_attach_prob[j][n_nodes+idx]/2.0;
nodes_attachment_counts[l] += cells_attach_prob[j][n_nodes+idx]/2.0;
idx++;
}
}
}
}
// count dropouts
double doublet_rate_local = parameters.doublet_rate;
if (!use_doublets_local) doublet_rate_local=0.0;
std::vector<double> dropoutref_counts(n_loci,0.0);
std::vector<double> dropoutalt_counts(n_loci,0.0);
std::vector<double> nrefalleles(n_loci,0.0);
std::vector<double> naltalleles(n_loci,0.0);
for (int i=0;i<n_loci;i++){
std::map<std::pair<int,int>,std::vector<double>> genotypes_prob; // for each cell, probability that it is attached to a node with a given genotype for locus i
// First, group nodes depending on their genotype at locus i
for (int k=0;k<n_nodes;k++){
int n_ref=nodes[k]->get_n_ref_allele(i);
int n_alt=nodes[k]->get_n_alt_allele(i);
std::pair<int,int> p= std::make_pair(n_ref,n_alt); //p: genotype at locus i for node k
if (!genotypes_prob.count(p)){
genotypes_prob[p]=std::vector<double>(n_cells,0.0);
}
for (int j=0;j<n_cells;j++){
genotypes_prob[p][j]+=cells_attach_prob[j][k] / (1.0-doublet_rate_local); // do not use doublets for inferring dropout rates (faster)
}
}
// Count dropouts for each genotype at locus i
for (const auto& m: genotypes_prob){
std::pair<int,int> p=m.first;
int n_ref=p.first;
int n_alt=p.second;
if (n_ref>0 && n_alt>0){ // only consider dropouts for heterozygous genotypes.
const std::vector<double>& dropoutsref= cache_scores->get_dropoutref_counts_genotype(n_ref,n_alt,i,dropout_rates_ref[i],
dropout_rates_alt[i]);
const std::vector<double>& dropoutsalt= cache_scores->get_dropoutalt_counts_genotype(n_ref,n_alt,i,dropout_rates_ref[i],
dropout_rates_alt[i]);
for (int j=0;j<n_cells;j++){
// if we have no reads at this position in this cell, we can't tell if a dropout occurred.
if (cells[j].ref_counts[i]+cells[j].alt_counts[i]>4){
dropoutref_counts[i]+=genotypes_prob[p][j] * dropoutsref[j];
dropoutalt_counts[i]+=genotypes_prob[p][j] * dropoutsalt[j];
nrefalleles[i]+=genotypes_prob[p][j] * n_ref;
naltalleles[i]+=genotypes_prob[p][j] * n_alt;
}
}
}
}
}
//M-step: optimize the node probabilities and dropout rates
avg_diff_nodeprob=0.0;
for (int k=0;k<n_nodes;k++){ // update node probabilities
double prev = node_probabilities[k];
node_probabilities[k] = nodes_attachment_counts[k] / n_cells;
avg_diff_nodeprob+=std::abs(node_probabilities[k]-prev) / n_nodes;
}
avg_diff_dropoutrates=0.0;
for (int i=0;i<n_loci;i++){ // update dropout rates
double prev_ref = dropout_rates_ref[i];
double prev_alt = dropout_rates_alt[i];
dropout_rates[i] = ((parameters.prior_dropoutrate_mean*parameters.prior_dropoutrate_omega-1)*2 + dropoutref_counts[i]+dropoutalt_counts[i])
/ ((parameters.prior_dropoutrate_omega-2)*2+nrefalleles[i]+naltalleles[i]);
if (allow_diff_dropoutrates){
// See if likelihood can be improved by allowing 2 different dropout rates
dropout_rates_ref[i] = (parameters.prior_dropoutrate_mean*parameters.prior_dropoutrate_omega-1+dropoutref_counts[i])
/ (parameters.prior_dropoutrate_omega-2+nrefalleles[i]);
dropout_rates_alt[i] = (parameters.prior_dropoutrate_mean*parameters.prior_dropoutrate_omega-1+dropoutalt_counts[i])
/ (parameters.prior_dropoutrate_omega-2+naltalleles[i]);
double diff_dropoutrates_lik = dropoutref_counts[i] * std::log(dropout_rates_ref[i]) + (nrefalleles[i] - dropoutref_counts[i]) * std::log(1-dropout_rates_ref[i])
+ dropoutalt_counts[i] * std::log(dropout_rates_alt[i]) + (naltalleles[i] - dropoutalt_counts[i]) * std::log(1-dropout_rates_alt[i])
+(parameters.prior_dropoutrate_mean * parameters.prior_dropoutrate_omega-1) * (std::log(dropout_rates_ref[i]) + std::log(dropout_rates_alt[i]))
+((1.0-parameters.prior_dropoutrate_mean) * parameters.prior_dropoutrate_omega-1) * (std::log(1.0-dropout_rates_ref[i]) + std::log(1.0-dropout_rates_alt[i]));
double same_dropoutrate_lik = (dropoutref_counts[i]+dropoutalt_counts[i]) * std::log(dropout_rates[i])
+ (nrefalleles[i] + naltalleles[i] - dropoutref_counts[i] - dropoutalt_counts[i]) * std::log(1-dropout_rates[i])
+ (parameters.prior_dropoutrate_mean * parameters.prior_dropoutrate_omega-1) * 2*std::log(dropout_rates[i])
+ ((1.0-parameters.prior_dropoutrate_mean) * parameters.prior_dropoutrate_omega-1) * 2*std::log(1.0-dropout_rates[i]);
if (same_dropoutrate_lik>diff_dropoutrates_lik-60){
dropout_rates_ref[i] = dropout_rates[i];
dropout_rates_alt[i] = dropout_rates[i];
}
}
else{
dropout_rates_ref[i] = dropout_rates[i];
dropout_rates_alt[i] = dropout_rates[i];
}
// Set minimum and maximum dropout rate
if (dropout_rates[i]<0.01) dropout_rates[i]=0.01;
if (dropout_rates_ref[i]<0.01) dropout_rates_ref[i]=0.01;
if (dropout_rates_alt[i]<0.01) dropout_rates_alt[i]=0.01;
if (dropout_rates[i]>0.50) dropout_rates[i]=0.50;
if (dropout_rates_ref[i]>0.50) dropout_rates_ref[i]=0.50;
if (dropout_rates_alt[i]>0.50) dropout_rates_alt[i]=0.50;
avg_diff_dropoutrates+= (std::abs(dropout_rates_ref[i] - prev_ref) + std::abs(dropout_rates_alt[i] - prev_alt)) / n_loci;
}
}
bool Tree::rec_check_max_one_event_per_region_per_lineage(int node, std::vector<int> n_events_in_regions){
// check that each region is affected, in one lineage, by at most one CNA.
for (auto CNA: nodes[node]->get_CNA_events()){
n_events_in_regions[std::get<0>(CNA)]+=1;
if (n_events_in_regions[std::get<0>(CNA)]>1) return false;
}
bool valid=true;
for (int child: children[node]){
valid = valid && rec_check_max_one_event_per_region_per_lineage(child,n_events_in_regions);
}
return valid;
}
void Tree::compute_prior_score(){
// Penalize number of nodes
log_prior_score=-n_nodes*(4+n_loci)*parameters.node_cost;
// Forbid empty nodes and penalize nodes with only CNAs (since the order of CNAs is generally less reliable)
for (int i=1;i<n_nodes;i++){
if (nodes[i]->get_number_mutations()==0 && nodes[i]->get_number_CNA()==0) log_prior_score-=100000;
if (nodes[i]->get_number_mutations()==0) log_prior_score-=(8+n_loci)*parameters.node_cost;
if (nodes[i]->get_number_mutations()==0 && nodes[i]->get_number_effective_LOH(nodes[parents[i]])==0) log_prior_score-=2*(8+n_loci)*parameters.node_cost;
}
// Penalize mutations which are not at the root
log_prior_score+=nodes[0]->get_number_mutations() * parameters.mut_notAtRoot_cost;
// Particularly penalize mutations with a high pop frequency which are not at the root
for (int k=1;k<n_nodes;k++){
for (int mut : nodes[k]->get_mutations()){
if (data.locus_to_freq[mut]>0.0001) log_prior_score-= data.locus_to_freq[mut] *parameters.mut_notAtRoot_freq_cost;
}
}
// Higher penalty when there are more cells
double ncells_coef = 0.2 + 1.0*n_cells/8000.0;
// Penalize CNA events
log_prior_score-= ncells_coef* (parameters.LOH_cost+parameters.CNA_cost) /10.0 * nodes[0]->get_number_CNA(); // Smaller penalty for CNLOH events at the root
for (int n=1;n<n_nodes;n++){
log_prior_score-= ncells_coef*parameters.CNA_cost * nodes[n]->get_number_disjoint_CNA(regions_successor);
// Higher penalty for CNAs resulting in LOH, because they have a bigger impact on the likelihood
log_prior_score-= ncells_coef*parameters.LOH_cost * nodes[n]->get_number_disjoint_LOH(regions_successor);
}
// Cannot have a CNA event at the root.
if (nodes[0]->get_number_CNA_noncopyneutral()>0) log_prior_score-= 100000;
// One lineage cannot have more than one CNA affecting each region (but it is still possible to have events affecting the same region in parallel branches)
if (!rec_check_max_one_event_per_region_per_lineage(0,std::vector<int>(n_regions,0))) log_prior_score-=1000000;
// Dropout rates
// with probability lambda, both alleles have the same dropout rate. With probability 1-lambda, they have the same dropout rate
for (int i=0;i<n_loci;i++){
if (std::abs(dropout_rates_ref[i]-dropout_rates_alt[i])>0.001){
log_prior_score-=70;
}
// Dropout rates are sampled from a beta distribution.
log_prior_score+= (parameters.prior_dropoutrate_mean * parameters.prior_dropoutrate_omega-1)
* (std::log(dropout_rates_ref[i]) + std::log(dropout_rates_alt[i]))
+ ((1.0-parameters.prior_dropoutrate_mean) * parameters.prior_dropoutrate_omega-1)
* (std::log(1.0-dropout_rates_ref[i]) + std::log(1.0-dropout_rates_alt[i]));
}
}
void Tree::update_full_score(){
log_score = log_likelihood + log_prior_score;
}
void Tree::to_dot(std::string filename, bool simplified){
// Save the tree structure in dot format (for visualization)
std::vector<std::string> colors{"lightcoral","skyblue3","sandybrown","paleturquoise3","thistle","darkolivegreen3","lightpink","mediumpurple",
"darkseagreen3","navajowhite","gold"};
// If filename ends with .gv: only output the tree in graphviz format. Otherwise output tree and cell assignments to nodes.
bool full_output = true;
if (filename.size()>3 && filename.substr(filename.size()-3)==".gv"){
full_output = false;
}
std::string basename(filename);
if (full_output){
filename = filename + "_tree.gv";
}
else{
basename = filename.substr(0,filename.size()-3);
}
std::ofstream out_file(filename);
out_file <<"digraph G{"<<std::endl;
out_file <<"node [color=dimgray fontsize=24 fontcolor=black fontname=Helvetica penwidth=5];"<<std::endl;
for (int i=1;i<n_nodes;i++){
if (parameters.verbose) std::cout<<i<< " is a child of "<<parents[i]<<std::endl;
out_file<<parents[i]<<" -> "<<i<<" [color=dimgray penwidth=4 weight=2];"<<std::endl;
}
// Identify mutations at the root which are not affected by a CNA
std::set<int> excluded_mutations{};
if (simplified){
if (n_nodes>0){
for (int m: nodes[0]->get_mutations()){
bool affected_by_event=false;
for (int n=0;n<n_nodes;n++){
for (auto CNA: nodes[n]->get_CNA_events()){
if (data.locus_to_region[m]==std::get<0>(CNA)) affected_by_event = true;
}
}
if (!affected_by_event) excluded_mutations.insert(m);
}
}
}
for (int i=0;i<n_nodes;i++){
if (simplified) out_file<<i<<"[label=<"<<nodes[i]->get_label_simple(excluded_mutations)<<">];"<<std::endl;
else out_file<<i<<"[label=<"<<nodes[i]->get_label()<<">];"<<std::endl;
}
for (int k=0;k<n_nodes;k++){
out_file<<k<<" -> "<<k+n_nodes<<" [dir=none style=dashed weight=1 penwidth=5 color="<<colors[k%colors.size()]<<"];"<<std::endl;
}
std::vector<int> count_nodes(n_nodes,0);
int total=0;
for (int j=0;j<n_cells;j++){
if (best_attachments[j]>=0 && best_attachments[j]<n_nodes){
count_nodes[best_attachments[j]]++;
total++;
}
}
for (int k=0;k<n_nodes;k++){
double size = std::sqrt(100.0*count_nodes[k]/total) /3.0;
out_file<<k+n_nodes<<"[label=\""<<count_nodes[k]<<" cells\\n"<<std::round(100.0*count_nodes[k]/total)<<"\\%\""<<" style = filled width="<<size
<<" height="<<size<<" color="<<colors[k%colors.size()]<<"];"<<std::endl;
}
out_file <<"}"<<std::endl;
out_file.close();
if (parameters.verbose) std::cout<<"Node probabilities"<<std::endl;
for (int n=0;n<n_nodes;n++){
if (parameters.verbose) std::cout<<n<<": "<<node_probabilities[n]<<std::endl;
}
if (parameters.verbose) std::cout<<"Dropout rates"<<std::endl;
for (int i=0;i<n_loci;i++){
if (parameters.verbose) std::cout<<i<<" ("<<data.locus_to_name[i]<<"): "<<dropout_rates[i]<<" (ref:" <<dropout_rates_ref[i]<<", alt:"<<dropout_rates_alt[i]<<")"<<std::endl;
}
if (full_output){
// Recompute assignment probabilities, only taking singlets into account
std::vector<std::vector<double>> cells_attach_loglik_singlet;
std::vector<double> cells_loglik_singlet;
std::vector<int> best_attachments_singlet;
cells_attach_loglik_singlet.resize(n_cells);
cells_loglik_singlet.resize(n_cells);
best_attachments_singlet.resize(n_cells);
for (int j=0;j<n_cells;j++){
cells_attach_loglik_singlet[j].resize(n_nodes);
double best_attach_score=-DBL_MAX;
for (int k=0;k<n_nodes;k++){
cells_attach_loglik_singlet[j][k] = cells_attach_loglik[j][k];
if (cells_attach_loglik_singlet[j][k]>best_attach_score){
best_attach_score = cells_attach_loglik_singlet[j][k];
best_attachments_singlet[j] = k;
}
}
cells_loglik_singlet[j] = Scores::log_sum_exp(cells_attach_loglik_singlet[j]);
}
// Assignments of cells to nodes
std::ofstream out_file_cell_assignments(basename+"_cellAssignments.tsv");
std::ofstream out_file_cell_assignment_probs(basename+"_cellAssignmentProbs.tsv");
//Header
out_file_cell_assignments <<"cell\tnode\tdoublet"<<std::endl;
out_file_cell_assignment_probs <<"cell";
for (int k=0; k < n_nodes;k++){
out_file_cell_assignment_probs<<"\tNode "<<k;
}
/*if (parameters.use_doublets){
std::cout<<cells_attach_loglik[0].size()<<std::endl;
for (int k=0;k<n_nodes;k++){
for (int l=k;l<n_nodes;l++){
out_file_cell_assignment_probs << "\tDoublet "<<k<<","<<l;
}
}
}*/
out_file_cell_assignment_probs<<std::endl;
// Content
for (int j=0;j<n_cells;j++){
out_file_cell_assignments << cells[j].name<<"\t"<<best_attachments_singlet[j];
if (best_attachments[j]>=n_nodes) out_file_cell_assignments<<"\tyes"<<std::endl;
else out_file_cell_assignments<<"\tno"<<std::endl;
out_file_cell_assignment_probs<<cells[j].name;
for (int k=0; k < n_nodes;k++){
out_file_cell_assignment_probs<<"\t"<<std::exp(cells_attach_loglik_singlet[j][k]-cells_loglik_singlet[j]);
}
/*if (parameters.use_doublets){
int idx=0;
for (int k=0;k<n_nodes;k++){
for (int l=k;l<n_nodes;l++){
out_file_cell_assignment_probs << "\t"<<std::exp(cells_attach_loglik[j][n_nodes+idx]-cells_loglik[j]);
idx++;
}
}
}*/
out_file_cell_assignment_probs<<std::endl;
}
out_file_cell_assignments.close();
out_file_cell_assignment_probs.close();
// ----------------------------------
// Tree in json format
std::ofstream out_file_json(basename+"_tree.json");
out_file_json<<"{"<<std::endl;
out_file_json<<"\"nodes\":["<<std::endl;
for (int k=0;k<n_nodes;k++){
out_file_json<<"\t{"<<std::endl;
out_file_json<<"\t\t\"name\": \"Node "<<k<<"\","<<std::endl;
if (parents[k]>=0){
out_file_json<<"\t\t\"parent\": \"Node "<<parents[k]<<"\","<<std::endl;
}
else{
out_file_json<<"\t\t\"parent\": \"-\","<<std::endl;
}
//SNV
out_file_json<<"\t\t\"SNV\": [";
std::vector<int> SNVs = nodes[k]->get_mutations();
if (SNVs.size()>0){
out_file_json<<"\""<<data.locus_to_name[SNVs[0]]<<"\"";
for (int i=1;i<SNVs.size();i++){
out_file_json<<",\""<<data.locus_to_name[SNVs[i]]<<"\"";
}
}
out_file_json<<"],"<<std::endl;
//CNA
out_file_json<<"\t\t\"CNA\": [";
std::set<std::tuple<int,int,std::vector<int>>> CNAs = nodes[k]->get_CNA_events();
if (CNAs.size()>0){
bool first=true;
for (auto CNA: CNAs){
if (!first) {
out_file_json<<",";
}
out_file_json<<"\"";
if (std::get<1>(CNA)>0){
out_file_json<<"Gain ";
}
else if (std::get<1>(CNA)<0){
out_file_json<<"Loss ";
}
else{
out_file_json<<"CNLOH ";
}
out_file_json<<data.region_to_name[std::get<0>(CNA)];
out_file_json<<"\"";
first=false;
}
}
out_file_json<<"]"<<std::endl;
out_file_json<<"\t}";
if (k<n_nodes-1){
out_file_json<<",";
}
out_file_json<<std::endl;
}
out_file_json<<"]"<<std::endl;
out_file_json<<"}"<<std::endl;
out_file_json.close();
// ----------------------------------
// Node genotypes
std::ofstream out_file_genotypes(basename+"_nodes_genotypes.tsv");
// Header
out_file_genotypes<<"node";
for (std::string name : data.locus_to_name){
out_file_genotypes << "\t"<<name;
}
out_file_genotypes<<std::endl;
// Content
for (int k=0;k<n_nodes;k++){
out_file_genotypes<<"Node "<<k;
for (int i=0;i<n_loci;i++){
if (nodes[k]->get_n_alt_allele(i)==0){
out_file_genotypes<<"\t0";
}
else if (nodes[k]->get_n_ref_allele(i)>0 ){
out_file_genotypes<<"\t1";
}
else{
out_file_genotypes<<"\t2";
}
}
out_file_genotypes<<std::endl;
}
out_file_genotypes.close();
// ----------------------------------
// Node copy numbers
if (use_CNA){
std::ofstream out_file_copynumbers(basename+"_nodes_copynumbers.tsv");
// Header
out_file_copynumbers<<"node";
for (std::string name : data.region_to_name){
out_file_copynumbers << "\t"<<name;
}
out_file_copynumbers<<std::endl;
// Content
for (int k=0;k<n_nodes;k++){
out_file_copynumbers<<"Node "<<k;
for (int i=0;i<n_regions;i++){
out_file_copynumbers<<"\t"<<nodes[k]->get_cn_region(i);
}
out_file_copynumbers<<std::endl;
}
out_file_copynumbers.close();
}
}
}
Tree::Tree(std::string gv_file, bool use_CNA_arg): //Create tree from a graphviz file
hastings_ratio(-1.0)
{
for (int i=0;i<n_loci;i++){
dropout_rates.push_back(0.05);
dropout_rates_ref.push_back(0.05);
dropout_rates_alt.push_back(0.05);
}
cache_scores = new Scores();
std::ifstream file(gv_file);
std::string line;
//skip first 2 lines
getline (file, line);
getline (file, line);
n_nodes=1;
parents.resize(1);
parents[0]=-1;
// Read parents
bool finished_reading_parents=false;
while (!finished_reading_parents) {
getline (file, line);
if (line.find("->")==std::string::npos) finished_reading_parents=true;
else{
int idx=1;
while (line[idx]!=' ') idx++;
int parent = stoi(line.substr(0,idx));
idx++;
while (line[idx]!=' ') idx++;
idx++;
int idx2=idx+1;
while (line[idx2]!=' '&& line[idx]!=';') idx2++;
int child = stoi(line.substr(idx,idx2-idx));
if (child+1 >n_nodes) n_nodes = child+1;
if (parent+1 > n_nodes) n_nodes = parent+1;
parents.resize(n_nodes);
parents[child] = parent;
}
}
// Create nodes
for (int i=0;i<n_nodes;i++){
nodes.push_back(new Node(cache_scores));
}
node_probabilities.resize(n_nodes);
// Read labels (events) and fill the nodes with the events
bool finished_reading_labels=false;
while (!finished_reading_labels){
int idx=1;
while (idx < line.size() && line[idx]!='[') idx++;
if (idx>=line.size() || line[idx+1]!='l') finished_reading_labels=true; //empty line
else{
int node = stoi(line.substr(0,idx));
while (line[idx]!='<') idx++;
idx++;
while (line[idx]==' ') idx++;
bool finished_reading_line=false;
if (line[idx]=='>') finished_reading_line=true;
while (!finished_reading_line){
if (line[idx]=='<') idx+=3; // remove <B>
if ((line[idx]=='C' && line[idx+2]=='L')){ // CNLOH event
idx+=6;
int idx2 = idx+1;
while (line[idx2]!=':') idx2++;
int region = stoi(line.substr(idx,idx2-idx));
idx2++;
while (line[idx2]!=':') idx2++; // skip region name
idx = idx2+1;
std::vector<int> lost_alleles{};
while (line[idx]!='<' && line[idx]!='b' && line[idx]!='/'){
if (line[idx]=='0') lost_alleles.push_back(0);
else lost_alleles.push_back(1);
idx+=2;
}
idx--;
nodes[node]->add_CNA(std::make_tuple(region,0,lost_alleles));
}
else if (line[idx]=='L' && line[idx+1]=='o'){ // Loss
idx+=5;
int idx2 = idx+1;
while (line[idx2]!=':') idx2++;
int region = stoi(line.substr(idx,idx2-idx));
idx = idx2+1;
while (line[idx]!=':') idx++;
std::vector<int>alleles{};
idx++;
while (line[idx]!='<' && line[idx]!='b' && line[idx]!='/'){
if (line[idx]=='0') alleles.push_back(0);
else alleles.push_back(1);
idx+=2;
}
idx--;
nodes[node]->add_CNA(std::make_tuple(region,-1,alleles));
}
else if (line[idx]=='G' && line[idx+1]=='a'){ // Gain
idx+=5;
int idx2 = idx+1;
while (line[idx2]!=':') idx2++;
int region = stoi(line.substr(idx,idx2-idx));
idx = idx2+1;
while (line[idx]!=':') idx++;
std::vector<int>alleles{};
idx++;
while (line[idx]!='<' && line[idx]!='b' && line[idx]!='/'){
if (line[idx]=='0') alleles.push_back(0);
else alleles.push_back(1);
idx+=2;
}
idx--;
nodes[node]->add_CNA(std::make_tuple(region,1,alleles));
}
else{ // somatic mutation
int idx2= idx+1;
while (line[idx2]!=':') idx2++;
int locus = stoi(line.substr(idx,idx2-idx));
nodes[node]->add_mutation(locus);
}
while (line[idx]!='<') idx++;
//HTML tags: events separated by <br/>
if (line[idx+1]=='/') idx+=4; // </B>
idx+=5;
if (line[idx]=='>') finished_reading_line=true;
}
}
if (!std::getline (file, line)) finished_reading_labels=true;
}
// Initialize utils
cells_attach_loglik.resize(n_cells);
cells_loglik.resize(n_cells);
cells_attach_prob.resize(n_cells);
best_attachments.resize(n_cells);
use_CNA=false;
compute_children();
compute_likelihood(true);
if(use_CNA_arg && select_regions()){
use_CNA=true;
compute_likelihood(true);
}
compute_prior_score();
update_full_score();
// Close the file
file.close();
}
bool Tree::select_regions(int index){
// Find regions which might contain a non-copy-neutral CNA event. Return true if it was possible to estimate node regions (if the node contains enough cells), false otherwise.
candidate_regions.clear();
region_probabilities.resize(n_regions);
int root=0;
// Compute number of cells attached to each node and make sure that there is a sufficient number of cells attached to the root
std::vector<int> nodes_nbcells(n_cells,0);
for (int j=0;j<n_cells;j++){
if (best_attachments[j]<n_nodes && best_attachments[j]>=0){
nodes_nbcells[best_attachments[j]]++;
}
}
// Either used predetermined region weights or estimate them using cells attached to the root.
if (data.predetermined_region_weights.size()>0){
for (int k=0;k<n_regions;k++) region_probabilities[k] = data.predetermined_region_weights[k];
}
else{
if (nodes_nbcells[0]<std::max(40.0,0.015*n_cells)){ // not enough cells attached to the root
// If some nodes have CNLOH, try to use one node without CNLOH in its ancestors as the root.