-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphBuilder.C
More file actions
1913 lines (1629 loc) · 60.5 KB
/
GraphBuilder.C
File metadata and controls
1913 lines (1629 loc) · 60.5 KB
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
/****************************************************************
GraphBuilder.C
Copyright (C)2017 William H. Majoros (martiandna@gmail.com).
This is OPEN SOURCE SOFTWARE governed by the Gnu General Public
License (GPL) version 3, as described at www.opensource.org.
****************************************************************/
#include <iostream>
#include "GraphBuilder.H"
#include "BOOM/Constants.H"
#include "BOOM/Interval.H"
#include "ACEplus_Edge.H"
#include "ACEplus_Vertex.H"
#include "SignalPrinter.H"
#include "LogisticSensor.H"
#include "BOOM/Stack.H"
using namespace std;
using namespace BOOM;
/* NOTES:
1. For vertices, the begin and end positions delimit the consensus,
not the full scoring window ("context window").
2. For edges, the begin and end coordinates delimit the boundaries of the
context windows of the incident vertices, not their consensuses.
3. Thus, the coordinates of a vertex are not the same as the coordinates
of its incident edges.
*/
#define SANITY_CHECKS
GraphBuilder::GraphBuilder(const GffTranscript &projected,
const TranscriptSignals &signals,
Model &model,
const Sequence &refSeq,const String &refSeqStr,
const Sequence &altSeq,const String &altSeqStr,
CigarAlignment &altToRef,bool strict)
: projected(projected), signals(signals), model(model), refSeq(refSeq),
refSeqStr(refSeqStr), altSeq(altSeq), altSeqStr(altSeqStr), G(NULL),
changes(false), altToRef(altToRef)
{
if(!buildGraph(strict)) G=NULL;
}
ACEplus_Vertex *GraphBuilder::newVertex(const String &substrate,
SignalType type,int begin,int end,
double score,Strand strand,int ID,
bool denovo)
{
LightVertex *exists=G->vertexExists(substrate,strand,begin,end,type);
if(exists) {
if(denovo) dynamic_cast<ACEplus_Vertex*>(exists)->setDeNovo();
return NULL;
}
SignalSensor *sensor=model.signalSensors->findSensor(type);
double rawScore=score;
String signalStr;
if(sensor) {
int offset=sensor->getConsensusOffset();
int contextLen=sensor->getContextWindowLength();
int windowBegin=begin-offset;
ContentSensor *bg=model.contentSensors->getSpliceBackground();
if(bg) {
double bgScore=bg->scoreSubsequence(altSeq,altSeqStr,windowBegin,
contextLen,0);
score-=bgScore; }
signalStr=SignalPrinter::print(*sensor,windowBegin,altSeqStr);
}
ACEplus_Vertex *v=
new ACEplus_Vertex(substrate,type,begin,end,score,strand,ID);
/*
LogisticSensor *logSensor=dynamic_cast<LogisticSensor*>(sensor);
if(logSensor)
rawScore=logSensor->getRawScore(altSeq,altSeqStr,//### not ref?
begin-sensor->getConsensusOffset());
*/
v->setRawScore(rawScore);
v->setSeq(signalStr);
if(denovo) v->setDeNovo();
return v;
}
ACEplus_Edge *GraphBuilder::newEdge(const String &substrate,ContentType type,
LightVertex *from,LightVertex *to,
int begin,int end,Strand strand,int ID)
{
//cout<<"newEdge("<<type<<")"<<endl;
if(end-begin<1) {
//cout<<*G<<endl;
//cout<<"edge length < 1 : "<<begin<<"-"<<end<<" "<<substrate<<" "
//<<type<<endl;
return NULL;
//INTERNAL_ERROR
}
if(G->edgeExists(substrate,strand,begin,end,type)) {
//cout<<"edge exists -- ignoring: "<<begin<<"-"<<end<<" "<<type<<endl;
return NULL;
}
//cout<<"returning new edge"<<endl;
ACEplus_Edge *edge=
new ACEplus_Edge(substrate,type,from,to,begin,end,strand,ID);
edge->setScore(0);
return edge;
}
LightGraph *GraphBuilder::getGraph()
{
return G;
}
double GraphBuilder::scoreSignal(SignalType type,int pos,const Sequence &seq,
const String &str)
{
SignalSensor *sensor=model.signalSensors->findSensor(type);
if(!sensor) return 0.0; // TSS and TES
if(!sensor->consensusOccursAt(str,pos)) return NEGATIVE_INFINITY;
int contextLen=sensor->getContextWindowLength();
int offset=sensor->getConsensusOffset();
int consensusLen=sensor->getConsensusLength();
int begin=pos-offset;
double score=sensor->getLogP(seq,str,begin);
return score;
}
void GraphBuilder::inspectEdgeScore(ACEplus_Edge *edge,const String &label)
{
//if(edge->getLength()<0) throw String("negative ")+edge->getLength()+"="+edge->getBegin()+"-"+edge->getEnd();
const String id=projected.getGeneId();
const PrefixSumArray &psa=model.contentSensors->getPSA(edge->getType());
cout<<"EDGE\t"<<label<<"\t"<<id<<"\tL="<<edge->getLength()<<"\tLLR="
<<psa.getInterval(edge->getBegin(),edge->getEnd())<<"\t";
//for(int i=edge->getBegin() ; i<edge->getEnd() ; ++i)
// cout<<psa.getInterval(i,i+1)<<"\t";
cout<<endl;
}
double GraphBuilder::scoreEdge(ACEplus_Edge *edge)
{
// Get emission probability
if(edge->getLength()<1) {
edge->setScore(NEGATIVE_INFINITY);
return;
}
//###
const int OFFSET=6;
//const int OFFSET=0;
//###
double score=model.contentSensors->score(edge->getType(),
edge->getBegin()+OFFSET,
edge->getEnd());
if(!isFinite(score)) {
cerr<<*edge<<endl;
cerr<<"edge emission score = "<<score<<" begin="<<edge->getBegin()<<
" end="<<edge->getEnd()<<" type="<<edge->getType()<<endl;
INTERNAL_ERROR; }
const StructureChange change=edge->getChange();
/*if(change.intronRetention || change.crypticExon)
inspectEdgeScore(edge,change.intronRetention ? "intron-retention" :
"denovo-exon");*/
// Apply scaling factor if one is set (defaults to 1.0)
score*=model.sensorScale;
// Get duration probability
/*
const int L=edge->getLength();
DiscreteDistribution *distr=NULL;
if(edge->isExon()) distr=model.exonLengthDistr;
else if(edge->isIntron()) distr=model.intronLengthDistr;
else if(edge->isIntergenic()) distr=model.intergenicLengthDistr;
else throw "Unknown edge type in GraphBuilder::scoreEdge()";
const double durationScore=distr->getLogP(L);
if(!isFinite(durationScore)) {
cerr<<*edge<<endl;
cerr<<"length="<<L<<", duration score="<<durationScore<<endl;
INTERNAL_ERROR;
}
score+=durationScore; // ###
*/
// Get transition probability
const int numChoices=edge->getLeft()->getEdgesOut().size();
/*
SignalType fromType=edge->getLeft()->getSignalType();
SignalType toType=edge->getRight()->getSignalType();
const double transProb=model.transitions->getLogP(fromType,toType);
if(!isFinite(transProb)) {
cerr<<*edge<<endl;
cerr<<"trans="<<transProb<<" from="<<fromType<<" to="<<toType<<endl;
INTERNAL_ERROR;
}
score+=transProb; // ###
*/
if(numChoices==0) {
cout<<*edge->getLeft()<<endl;
cout<<*edge<<endl;
cerr<<"Zero edges out!"<<endl;
INTERNAL_ERROR; }
// Apply hard filter to reduce false positives
if(change.intronRetention && score<model.minIntronRetentionLLR)
score=NEGATIVE_INFINITY;
else if(change.crypticExon && score<model.minDeNovoExonLLR)
score=NEGATIVE_INFINITY;
// Store score in edge
edge->setScore(score);
}
void GraphBuilder::getContextWindow(LightVertex *v,int &begin,int &end)
{
SignalSensor *sensor=model.signalSensors->findSensor(v->getType());
if(!sensor) { begin=v->getBegin(); end=v->getEnd(); return; }
int consensusPos=v->getBegin();
begin=consensusPos-sensor->getConsensusOffset();
end=begin+sensor->getContextWindowLength();
}
void GraphBuilder::getSignalWindow(SignalType type,int consensusPos,
int &windowBegin,int &windowEnd,
int &consensusLen)
{
if(type==TSS || type==TES) {
windowBegin=windowEnd=consensusPos;
consensusLen=0;
return; }
SignalSensor *sensor=model.signalSensors->findSensor(type);
if(!sensor) INTERNAL_ERROR;
int contextLen=sensor->getContextWindowLength();
int offset=sensor->getConsensusOffset();
consensusLen=sensor->getConsensusLength();
windowBegin=consensusPos-offset;
windowEnd=windowBegin+contextLen;
}
ContentType GraphBuilder::getContentType(SignalType from,SignalType to)
{
switch(from) {
case LEFT_TERMINUS: return INTERGENIC;
case TSS: return EXON;
case GT: return INTRON;
case AG: return EXON;
case TES: return INTERGENIC;
}
INTERNAL_ERROR;
}
bool GraphBuilder::buildTranscriptGraph()
{
Strand strand=projected.getStrand();
if(strand!=FORWARD_STRAND) INTERNAL_ERROR;
const String &substrate=projected.getSubstrate();
G=new LightGraph(substrate,altSeq.getLength());
int numSignals=signals.numSignals();
// Create vertices
ACEplus_Vertex *v=newVertex(substrate,LEFT_TERMINUS,0,0,0.0,strand,0);
v->setAnnotated(true); v->setBroken(false);
ACEplus_Vertex *leftTerminus=v;
G->addVertex(v);
for(int i=0 ; i<numSignals ; ++i) {
const TranscriptSignal &signal=signals[i];
SignalType type=signal.getType();
int pos=signal.getPos();
bool broken=signal.isBroken();
double score=scoreSignal(type,pos,altSeq,altSeqStr);
int begin, end, consensusLen;
getSignalWindow(type,pos,begin,end,consensusLen);
ACEplus_Vertex *v=newVertex(substrate,type,pos,pos+consensusLen,score,
strand,i+1);
#ifdef SANITY_CHECKS
if(!v) INTERNAL_ERROR;
#endif
v->setBroken(signal.isBroken());
v->setAnnotated(true);
G->addVertex(v);
}
int L=altSeq.getLength();
v=newVertex(substrate,RIGHT_TERMINUS,L,L,0.0,strand,numSignals+1);
#ifdef SANITY_CHECKS
if(!v) INTERNAL_ERROR;
#endif
v->setAnnotated(true); v->setBroken(false);
ACEplus_Vertex *rightTerminus=v;
G->addVertex(v);
// Create edges
const int numVertices=G->getNumVertices();
for(int i=0 ; i+1<numVertices ; ++i) {
LightVertex *prev=G->getVertex(i), *next=G->getVertex(i+1);
int begin, end, dummy;
getContextWindow(prev,dummy,begin); getContextWindow(next,end,dummy);
ContentType type=getContentType(prev->getType(),next->getType());
#ifdef SANITY_CHECKS
if(prev->getType()==next->getType()) INTERNAL_ERROR;
#endif
LightEdge *edge=newEdge(substrate,type,prev,next,begin,end,strand,i);
if(!edge) {
//ACEplus_Edge *edge=
//GraphBuilder::linkVertices(leftTerminus,rightTerminus);
return false;
//INTERNAL_ERROR;
}
edge->setBroken(false);
edge->setAnnotated(true);
prev->addEdgeOut(edge); next->addEdgeIn(edge);
G->addEdge(edge);
}
return true;
}
void GraphBuilder::handleBrokenSites()
{
// For each broken site, scan for cryptic sites nearby
int numVertices=G->getNumVertices();
for(int i=0 ; i<numVertices ; ++i) {
LightVertex *v=G->getVertex(i);
if(v->isBroken()) handleBrokenSite(v);
}
// Delete broken sites
Set<LightVertex*> verticesToDelete;
Set<LightEdge*> edgesToDelete;
for(int i=0 ; i<numVertices ; ++i) {
LightVertex *v=G->getVertex(i);
if(!v->isBroken()) continue;
verticesToDelete+=v;
Vector<LightEdge*> &in=v->getEdgesIn(), &out=v->getEdgesOut();
for(Vector<LightEdge*>::iterator cur=in.begin(), end=in.end() ;
cur!=end ; ++cur) edgesToDelete+=*cur;
for(Vector<LightEdge*>::iterator cur=out.begin(), end=out.end() ;
cur!=end ; ++cur) edgesToDelete+=*cur;
G->dropVertex(i);
}
for(Set<LightEdge*>::iterator cur=edgesToDelete.begin(), end=
edgesToDelete.end() ; cur!=end ; ++cur) {
LightEdge *e=*cur;
e->getLeft()->dropEdgeOut(e); e->getRight()->dropEdgeIn(e);
G->dropEdge(e->getID());
delete e;
}
for(Set<LightVertex*>::iterator cur=verticesToDelete.begin(), end=
verticesToDelete.end() ; cur!=end ; ++cur) delete *cur;
G->deleteNullVertices(); G->deleteNullEdges();
}
void GraphBuilder::handleBrokenSite(LightVertex *v)
{
if(model.allowExonSkipping) handleBrokenSite_skipping(v);
if(model.allowIntronRetention) handleBrokenSite_retention(v);
if(model.allowCrypticSites) handleBrokenSite_cryptic(v);
}
void GraphBuilder::handleBrokenSite_cryptic(LightVertex *v)
{
// Prepare to do the scan
SignalType type=v->getType();
const String &substrate=v->getSubstrate();
const Strand strand=v->getStrand();
SignalSensor *sensor=model.signalSensors->findSensor(type);
const double cutoff=sensor->getCutoff();
const int contextWindowLen=sensor->getContextWindowLength();
const int consensusOffset=sensor->getConsensusOffset();
const int consensusLen=sensor->getConsensusLength();
int scanBegin=v->getBegin()-model.MAX_SPLICE_SHIFT-consensusOffset;
int scanEnd=v->getEnd()+model.MAX_SPLICE_SHIFT-consensusLen-consensusOffset;
if(scanBegin<0) scanBegin=0;
if(scanEnd>altSeq.getLength()-contextWindowLen)
scanEnd=altSeq.getLength()-contextWindowLen;
#ifdef SANITY_CHECKS
if(scanEnd<0) INTERNAL_ERROR;
#endif
Vector<LightEdge*> &in=v->getEdgesIn(), &out=v->getEdgesOut();
int nextVertexID=G->getNumVertices(), nextEdgeID=G->getNumEdges();
// Scan in a window around the broken site
for(int pos=scanBegin ; pos<scanEnd ; ++pos) {
const int consensusPos=pos+consensusOffset;
if(consensusPos==v->getBegin()) continue;
if(sensor->consensusOccursAt(altSeqStr,consensusPos)) {
double score=sensor->getLogP(altSeq,altSeqStr,pos);
//cout<<"XXX "<<score<<" vs "<<cutoff<<"\t"<<substrate<<"\t"<<consensusPos<<endl; // ###
if(score<cutoff) continue;
ACEplus_Vertex *v=newVertex(substrate,type,consensusPos,
consensusPos+consensusLen,score,
strand,nextVertexID++);
if(!v) continue;
v->setBroken(false); v->setAnnotated(false);
v->setThreshold(sensor->getCutoff());
v->setRefScore(0); // ###
String signalStr=SignalPrinter::print(*sensor,pos,altSeqStr);
v->setSeq(signalStr);
G->addVertex(v);
for(Vector<LightEdge*>::iterator cur=in.begin(), end1=in.end() ;
cur!=end1 ; ++cur) {
LightEdge *edge=*cur; LightVertex *left=edge->getLeft();
int begin, end, dummy;
getContextWindow(left,dummy,begin); getContextWindow(v,end,dummy);
#ifdef SANITY_CHECKS
if(left->getType()==v->getType()) INTERNAL_ERROR;
#endif
ACEplus_Edge *new_Edge=newEdge(substrate,edge->getType(),left,v,
begin,end,strand,nextEdgeID++);
if(!new_Edge) continue;
new_Edge->getChange().crypticSite=true;
new_Edge->setBroken(false);
left->addEdgeOut(new_Edge);
v->addEdgeIn(new_Edge); G->addEdge(new_Edge);
}
for(Vector<LightEdge*>::iterator cur=out.begin(), end1=out.end() ;
cur!=end1 ; ++cur) {
LightEdge *edge=*cur; LightVertex *right=edge->getRight();
int begin, end, dummy;
getContextWindow(v,dummy,begin); getContextWindow(right,end,dummy);
#ifdef SANITY_CHECKS
if(v->getType()==right->getType()) INTERNAL_ERROR;
#endif
ACEplus_Edge *new_Edge=newEdge(substrate,edge->getType(),v,right,
begin,end,strand,nextEdgeID++);
if(!new_Edge) continue;
new_Edge->getChange().crypticSite=true;
new_Edge->setBroken(false);
right->addEdgeIn(new_Edge);
v->addEdgeOut(new_Edge); G->addEdge(new_Edge);
}
}
}
}
LightEdge *GraphBuilder::getAnnotatedEdge(Vector<LightEdge*> &edges)
{
for(Vector<LightEdge*>::iterator cur=edges.begin(), end=edges.end() ;
cur!=end ; ++cur) {
LightEdge *edge=*cur;
if(edge->isAnnotated()) return edge; }
INTERNAL_ERROR;
}
void GraphBuilder::handleBrokenSite_skipping(LightVertex *v)
{
Vector<LightEdge*> &in=v->getEdgesIn(), &out=v->getEdgesOut();
if(in.size()==0 || out.size()==0) return;
//if(in[0]->getType()==EXON) { handleSkippingLeft(v); return; }
//if(out[0]->getType()==EXON) { handleSkippingRight(v); return; }
if(getAnnotatedEdge(in)->getType()==EXON) handleSkippingLeft(v);
else if(getAnnotatedEdge(out)->getType()==EXON) handleSkippingRight(v);
}
void GraphBuilder::handleSkippingLeft(LightVertex *v)
{
Vector<LightEdge*> &in=v->getEdgesIn(), &out=v->getEdgesOut();
//LightEdge *leftEdge=in[0], *rightEdge=out[0];
LightEdge *leftEdge=getAnnotatedEdge(in), *rightEdge=getAnnotatedEdge(out);
#ifdef SANITY_CHECKS
if(!leftEdge || !rightEdge) INTERNAL_ERROR;
#endif
const String &substrate=leftEdge->getSubstrate();
Strand strand=leftEdge->getStrand();
if(rightEdge->getType()!=INTRON) return;
LightVertex *to=rightEdge->getRight();
Vector<LightEdge*> &leftIntrons=leftEdge->getLeft()->getEdgesIn();
if(leftIntrons.size()==0 || leftIntrons[0]->getType()!=INTRON) return;
for(Vector<LightEdge*>::iterator cur=leftIntrons.begin(),
end1=leftIntrons.end() ; cur!=end1 ; ++cur) {
LightVertex *from=(*cur)->getLeft();
int begin, end, dummy;
getContextWindow(from,dummy,begin); getContextWindow(to,end,dummy);
#ifdef SANITY_CHECKS
if(from->getType()==to->getType()) INTERNAL_ERROR;
#endif
ACEplus_Edge *new_Edge=
newEdge(substrate,INTRON,from,to,begin,end,strand,
G->getNumEdges());
if(!new_Edge) continue;
new_Edge->getChange().exonSkipping=true;
new_Edge->setBroken(false);
from->addEdgeOut(new_Edge); to->addEdgeIn(new_Edge);
G->addEdge(new_Edge);
}
}
void GraphBuilder::handleSkippingRight(LightVertex *v)
{
Vector<LightEdge*> &in=v->getEdgesIn(), &out=v->getEdgesOut();
LightEdge *leftEdge=getAnnotatedEdge(in), *rightEdge=getAnnotatedEdge(out);
#ifdef SANITY_CHECKS
if(!leftEdge || !rightEdge) INTERNAL_ERROR;
#endif
const String &substrate=leftEdge->getSubstrate();
Strand strand=leftEdge->getStrand();
if(leftEdge->getType()!=INTRON) return;
LightVertex *from=leftEdge->getLeft();
Vector<LightEdge*> &rightIntrons=rightEdge->getRight()->getEdgesOut();
if(rightIntrons.size()==0 || rightIntrons[0]->getType()!=INTRON) return;
for(Vector<LightEdge*>::iterator cur=rightIntrons.begin(),
end1=rightIntrons.end() ; cur!=end1 ; ++cur) {
LightVertex *to=(*cur)->getRight();
int begin, end, dummy;
getContextWindow(from,dummy,begin); getContextWindow(to,end,dummy);
#ifdef SANITY_CHECKS
if(from->getType()==to->getType()) INTERNAL_ERROR;
#endif
ACEplus_Edge *new_Edge=
newEdge(substrate,INTRON,from,to,begin,end,strand,
G->getNumEdges());
if(!new_Edge) continue;
new_Edge->getChange().exonSkipping=true;
new_Edge->setBroken(false);
from->addEdgeOut(new_Edge); to->addEdgeIn(new_Edge);
G->addEdge(new_Edge);
}
}
void GraphBuilder::handleBrokenSite_retention(LightVertex *v)
{
Vector<LightEdge*> &in=v->getEdgesIn(), &out=v->getEdgesOut();
if(in.size()==0 || out.size()==0) return;
if(getAnnotatedEdge(in)->getType()==INTRON) handleRetentionLeft(v);
else if(getAnnotatedEdge(out)->getType()==INTRON) handleRetentionRight(v);
}
void GraphBuilder::handleRetentionLeft(LightVertex *v)
{
Vector<LightEdge*> &in=v->getEdgesIn(), &out=v->getEdgesOut();
LightEdge *leftEdge=getAnnotatedEdge(in), *rightEdge=getAnnotatedEdge(out);
#ifdef SANITY_CHECKS
if(!leftEdge || !rightEdge) INTERNAL_ERROR;
#endif
const String &substrate=leftEdge->getSubstrate();
Strand strand=leftEdge->getStrand();
LightVertex *to=rightEdge->getRight();
Vector<LightEdge*> &leftExons=leftEdge->getLeft()->getEdgesIn();
for(Vector<LightEdge*>::iterator cur=leftExons.begin(),
end1=leftExons.end() ; cur!=end1 ; ++cur) {
LightVertex *from=(*cur)->getLeft();
int begin, end, dummy;
getContextWindow(from,dummy,begin); getContextWindow(to,end,dummy);
#ifdef SANITY_CHECKS
if(from->getType()==to->getType()) INTERNAL_ERROR;
#endif
if(end-begin>model.maxIntronRetentionLen) continue;
ACEplus_Edge *new_Edge=
newEdge(substrate,EXON,from,to,begin,end,strand,G->getNumEdges());
if(!new_Edge) continue;
new_Edge->getChange().intronRetention=true;
from->addEdgeOut(new_Edge); to->addEdgeIn(new_Edge);
new_Edge->setBroken(false);
G->addEdge(new_Edge);
}
}
void GraphBuilder::handleRetentionRight(LightVertex *v)
{
Vector<LightEdge*> &in=v->getEdgesIn(), &out=v->getEdgesOut();
LightEdge *leftEdge=getAnnotatedEdge(in), *rightEdge=getAnnotatedEdge(out);
#ifdef SANITY_CHECKS
if(!leftEdge || !rightEdge) INTERNAL_ERROR;
#endif
const String &substrate=leftEdge->getSubstrate();
Strand strand=leftEdge->getStrand();
LightVertex *from=leftEdge->getLeft();
Vector<LightEdge*> &rightExons=rightEdge->getRight()->getEdgesOut();
for(Vector<LightEdge*>::iterator cur=rightExons.begin(),
end1=rightExons.end() ; cur!=end1 ; ++cur) {
LightVertex *to=(*cur)->getRight();
int begin, end, dummy;
getContextWindow(from,dummy,begin); getContextWindow(to,end,dummy);
#ifdef SANITY_CHECKS
if(from->getType()==to->getType()) INTERNAL_ERROR;
#endif
if(end-begin>model.maxIntronRetentionLen) continue;
ACEplus_Edge *new_Edge=
newEdge(substrate,EXON,from,to,begin,end,strand,G->getNumEdges());
if(!new_Edge) continue;
new_Edge->getChange().intronRetention=true;
from->addEdgeOut(new_Edge); to->addEdgeIn(new_Edge);
new_Edge->setBroken(false);
G->addEdge(new_Edge);
}
}
void GraphBuilder::leftSweep(LightGraph &G,
Array1D<int> &vertexCounts,
Array1D<int> &edgeCounts)
{
if(G.getNumVertices()==0) throw "empty graph";
LightVertex *left=G.getVertex(0);
Stack<LightVertex*> todo;
todo.push(left);
while(!todo.isEmpty()) {
LightVertex *v=todo.pop();
++vertexCounts[v->getID()];
Vector<LightEdge*> &edges=v->getEdgesOut();
for(Vector<LightEdge*>::iterator cur=edges.begin(), end=edges.end() ;
cur!=end ; ++cur) {
LightEdge *edge=*cur;
++edgeCounts[edge->getID()];
if(edge->getRight()->getBegin()<v->getBegin()) {
cout<<*v<<"\n"<<*edge->getRight()<<endl;
INTERNAL_ERROR;
}
if(vertexCounts[edge->getRight()->getID()]==0)
todo.push(edge->getRight());
}
}
}
void GraphBuilder::rightSweep(LightGraph &G,
Array1D<int> &vertexCounts,
Array1D<int> &edgeCounts)
{
const int numVertices=G.getNumVertices();
if(numVertices==0) throw "empty graph";
LightVertex *right=G.getVertex(numVertices-1);
Stack<LightVertex*> todo;
todo.push(right);
while(!todo.isEmpty()) {
LightVertex *v=todo.pop();
++vertexCounts[v->getID()];
Vector<LightEdge*> &edges=v->getEdgesIn();
for(Vector<LightEdge*>::iterator cur=edges.begin(), end=edges.end() ;
cur!=end ; ++cur) {
LightEdge *edge=*cur;
++edgeCounts[edge->getID()];
if(vertexCounts[edge->getLeft()->getID()]==0)
todo.push(edge->getLeft());
}
}
}
void GraphBuilder::deleteUnreachable(LightGraph &G,
Array1D<int> &vertexLeftCounts,
Array1D<int> &vertexRightCounts,
Array1D<int> &edgeLeftCounts,
Array1D<int> &edgeRightCounts)
{
for(int i=0 ; i<vertexLeftCounts.size() ; ++i)
if(vertexLeftCounts[i]==0 || vertexRightCounts[i]==0) G.dropVertex(i);
for(int i=0 ; i<edgeLeftCounts.size() ; ++i)
if(edgeLeftCounts[i]==0 || edgeRightCounts[i]==0) {
LightEdge *edge=G.getEdge(i);
edge->getLeft()->dropEdgeOut(edge);
edge->getRight()->dropEdgeIn(edge);
G.dropEdge(i);
}
}
void GraphBuilder::pruneUnreachable(LightGraph &G)
{
G.sort();
Array1D<int> vertexLeftCounts(G.getNumVertices());
Array1D<int> edgeLeftCounts(G.getNumEdges());
Array1D<int> vertexRightCounts(G.getNumVertices());
Array1D<int> edgeRightCounts(G.getNumEdges());
vertexLeftCounts.setAllTo(0);
vertexRightCounts.setAllTo(0);
edgeLeftCounts.setAllTo(0);
edgeRightCounts.setAllTo(0);
leftSweep(G,vertexLeftCounts,edgeLeftCounts);
rightSweep(G,vertexRightCounts,edgeRightCounts);
deleteUnreachable(G,vertexLeftCounts,vertexRightCounts,
edgeLeftCounts,edgeRightCounts);
G.deleteNullVertices();
G.deleteNullEdges();
G.sort();
}
bool GraphBuilder::mapped() const
{
return !changes;
}
void GraphBuilder::findVariants(Vector<Interval> &variants)
{
Vector<int> positions;
const int L=altSeq.getLength();
for(int pos=0 ; pos<L ; ++pos) {
const int to=altToRef[pos];
if(to==CIGAR_UNDEFINED || // Insertion
pos+1<L && altToRef[pos+1]!=to+1 || // Deletion
altSeqStr[pos]!=refSeqStr[to]) // Substitution
positions.push_back(pos); }
const int N=positions.size();
int begin=-1, end=-1;
for(int i=0 ; i<N ; ++i) {
const int pos=positions[i];
if(begin<0) { begin=pos; end=pos+1; }
else if(pos==end) ++end;
else {
variants.push_back(Interval(begin,end));
begin=end=-1; }
}
if(begin>=0) variants.push_back(Interval(begin,end));
}
void GraphBuilder::handleDeNovoSites()
{
// First, find all variants
if(variants.isEmpty()) findVariants(variants);
//cout<<variants.size()<<" variants found"<<endl;
// Now scan for de novo sites overlapping any variant
Vector<ACEplus_Vertex*> newVertices;
scanDeNovo(*model.signalSensors->donorSensor,variants,newVertices);
//cout<<newVertices.size()<<" new vertices after scanning for donors"<<endl;
scanDeNovo(*model.signalSensors->acceptorSensor,variants,newVertices);
//cout<<newVertices.size()<<" after scanning for acceptors"<<endl;
// Now link the new vertices to other vertices
//cout<<G->getNumVertices()<<" vertices before linking"<<endl;
linkDeNovoVertices(newVertices);
// If cryptic exons are enabled, scan for partner signals to complete
// new exons
//cout<<G->getNumVertices()<<" vertices before adding cryptic exons"<<endl;
if(model.allowCrypticExons) addCrypticExons(newVertices);
//cout<<newVertices.size()<<" after scanning for cryptic exons"<<endl;
//cout<<G->getNumVertices()<<" vertices after adding cryptic exons"<<endl;
}
void dumpIntervals(const Vector<Interval> &windows)
{
for(Vector<Interval>::const_iterator cur=windows.begin(), end=windows.end() ;
cur!=end ; ++cur)
cout<<*cur<<endl;
}
void GraphBuilder::scanDeNovo(SignalSensor &sensor,Vector<Interval> &variants,
Vector<ACEplus_Vertex*> &newVertices)
{
// PRECONDITION: variants are sorted by increasing absolute position
// First, get a set of windows to run the sensor on
Vector<Interval> windows;
getVariantWindows(windows,sensor,variants);
//cout<<windows.size()<<" variant windows before coalescing:"<<endl;
//dumpIntervals(windows);
// Coalesce windows, in case any overlap
coalesceWindows(windows);
//cout<<windows.size()<<" variant windows after coalescing:"<<endl;
//dumpIntervals(windows);
// Perform signal sensing in all windows
deNovoSignalSensing(sensor,windows,newVertices);
}
void GraphBuilder::getVariantWindows(Vector<Interval> &windows,
SignalSensor &sensor,
Vector<Interval> &variants)
{
const int sensorLen=sensor.getContextWindowLength();
for(Vector<Interval>::iterator cur=variants.begin(), end1=variants.end() ;
cur!=end1 ; ++cur) {
const Interval &variant=*cur;
int begin=variant.getBegin()-sensorLen+1;
if(begin<0) begin=0;
int end=variant.getEnd();
windows.push_back(Interval(begin,end));
}
}
void GraphBuilder::coalesceWindows(Vector<Interval> &windows)
{
int numWindows=windows.size();
for(int i=0 ; i+1<numWindows ; ++i) {
if(windows[i].overlaps(windows[i+1])) {
windows[i].setEnd(windows[i+1].getEnd());
windows.cut(i+1);
--i; --numWindows;
}
}
}
void GraphBuilder::deNovoSignalSensing(SignalSensor &sensor,
Vector<Interval> &windows,
Vector<ACEplus_Vertex*> &newVertices)
{
const double threshold=sensor.getCutoff();
const int consensusOffset=sensor.getConsensusOffset();
const int consensusLen=sensor.getConsensusLength();
const String &substrate=projected.getSubstrate();
const SignalType signalType=sensor.getSignalType();
const Strand strand=projected.getStrand();
const int numWindows=windows.size();
const int sensorLen=sensor.getContextWindowLength();
for(int i=0 ; i<numWindows ; ++i) {
const Interval &scanWindow=windows[i];
for(int pos=scanWindow.getBegin() ; pos<scanWindow.getEnd() ; ++pos) {
if(pos+sensorLen>altSeq.getLength()) continue;
if(sensor.consensusOccursAt(altSeqStr,pos+consensusOffset)) {
const double altScore=sensor.getLogP(altSeq,altSeqStr,pos);
//cout<<"XXX1 "<<altScore<<" vs "<<threshold<<"\t"<<substrate<<"\t"<<pos+consensusOffset<<endl; // ###
if(altScore<threshold) continue;
const int refPos=altToRef[pos];
if(refPos!=CIGAR_UNDEFINED && refPos+sensorLen<=refSeq.getLength() &&
sensor.consensusOccursAt(refSeqStr,refPos+consensusOffset)) {
const double refScore=sensor.getLogP(refSeq,refSeqStr,refPos);
//cout<<"XXX2 "<<refScore<<" vs "<<threshold<<"\t"<<substrate<<"\t"<<refPos+consensusOffset<<endl; // ###
if(refScore>=threshold) continue; // ref already had a signal there
if(altScore-refScore<log(2)) continue; // less than a 2-fold increase
}
if(altScore<threshold+log(2)) continue; // must be >= 2*threshold
//cout<<"XXX "<<altScore<<" vs "<<threshold<<"\t"<<substrate<<"\t"<<pos+consensusOffset<<endl; // ###
ACEplus_Vertex *v=newVertex(substrate,signalType,pos+consensusOffset,
pos+consensusOffset+consensusLen,
altScore,strand,G->getNumVertices(),
true);
if(!v) continue;
G->addVertex(v);
newVertices.push_back(v);
v->setThreshold(threshold);
}
}
}
}
void GraphBuilder::linkDeNovoVertices(Vector<ACEplus_Vertex*> &newVertices)
{
G->sort();
LightGraph &graph=*G;
for(Vector<ACEplus_Vertex*>::iterator cur=newVertices.begin(),
end=newVertices.end() ; cur!=end ; ++cur) {
ACEplus_Vertex *v=*cur;
const int id=v->getID();
#ifdef SANITY_CHECKS
if(graph.getVertex(id)!=v) INTERNAL_ERROR;
#endif
linkDeNovoLeft(v,id);
linkDeNovoRight(v,id);
}
}
void GraphBuilder::getLinkTypes(SignalType t,Direction dir,
Set<SignalType> &types)
{
switch(dir) {
case DIR_LEFT:
switch(t) {
case GT: types.insert(TSS); types.insert(AG); break;
case AG: types.insert(GT); break; }
break;
case DIR_RIGHT:
switch(t) {
case GT: types.insert(AG); break;
case AG: types.insert(GT); types.insert(TES); break; }
break;
default: INTERNAL_ERROR;
}
}
void GraphBuilder::linkDeNovoLeft(ACEplus_Vertex *v,int id)
{
const String &substrate=projected.getSubstrate();
Strand strand=projected.getStrand();
LightGraph &graph=*G;
Set<SignalType> linkTypes;
getLinkTypes(v->getType(),DIR_LEFT,linkTypes);
for(int i=id-1 ; i>=0 ; --i) {
LightVertex *w=graph.getVertex(i);
if(linkTypes.isMember(w->getType())) {
const int edgeID=graph.getNumEdges();
int begin, end, dummy;
getContextWindow(w,dummy,begin); getContextWindow(v,end,dummy);
ContentType type=getContentType(w->getType(),v->getType());
#ifdef SANITY_CHECKS
if(w->getType()==v->getType()) INTERNAL_ERROR;
#endif
//if(::isExon(type) && v->distanceTo(*w)>model.maxDeNovoExonLen) break;
ACEplus_Edge *edge=
newEdge(substrate,type,w,v,begin,end,strand,edgeID);
if(!edge) continue;
edge->getChange().deNovoSite=true;
edge->setBroken(false);
graph.addEdge(edge);
w->addEdgeOut(edge); v->addEdgeIn(edge);
if(w->isAnnotated()) break;
}
}
}
void GraphBuilder::linkDeNovoRight(ACEplus_Vertex *v,int id)
{
const String &substrate=projected.getSubstrate();
Strand strand=projected.getStrand();
LightGraph &graph=*G;
Set<SignalType> linkTypes;
getLinkTypes(v->getType(),DIR_RIGHT,linkTypes);
const int numVertices=graph.getNumVertices();
for(int i=id+1 ; i<numVertices ; ++i) {
LightVertex *w=graph.getVertex(i);
if(linkTypes.isMember(w->getType())) {
const int edgeID=graph.getNumEdges();
int begin, end, dummy;
getContextWindow(v,dummy,begin); getContextWindow(w,end,dummy);
ContentType type=getContentType(v->getType(),w->getType());
#ifdef SANITY_CHECKS
if(v->getType()==w->getType()) INTERNAL_ERROR;
#endif
//if(::isExon(type) && v->distanceTo(*w)>model.maxDeNovoExonLen) break;
ACEplus_Edge *edge=
newEdge(substrate,type,v,w,begin,end,strand,edgeID);
if(!edge) continue;
edge->getChange().deNovoSite=true;
edge->setBroken(false);
graph.addEdge(edge);
v->addEdgeOut(edge); w->addEdgeIn(edge);
if(w->isAnnotated()) break;
}
}
}
bool GraphBuilder::allVerticesAreAnnotated()
{
LightGraph &graph=*G;
const int numVertices=graph.getNumVertices();
//cout<<numVertices<<" vertices"<<endl;
for(int i=0 ; i<numVertices ; ++i) {
LightVertex *v=graph.getVertex(i);
if(!v->isAnnotated()) return false;
}
//cout<<"returning true"<<endl;