-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathACEplus.C
608 lines (523 loc) · 19.9 KB
/
ACEplus.C
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
/****************************************************************
ACEplus.C
Copyright (C)2017 William H. Majoros ([email protected]).
This is OPEN SOURCE SOFTWARE governed by the Gnu General Public
License (GPL) version 3, as described at www.opensource.org.
****************************************************************/
#include <iostream>
#include "ACEplus.H"
#include "GraphBuilder.H"
#include "TranscriptPaths.H"
#include "GeometricDistribution.H"
#include "EmpiricalDistribution.H"
using namespace std;
using namespace BOOM;
/****************************************************************
Globals
****************************************************************/
static bool VERBOSE=true;
static const char *PROGRAM_NAME="ACEplus";
static const char *VERSION="1.0";
/****************************************************************
ACEplus::ACEplus()
****************************************************************/
ACEplus::ACEplus()
{
// ctor
}
/****************************************************************
ACEplus::main()
****************************************************************/
int ACEplus::main(int argc,char *argv[])
{
// Process command line
CommandLine cmd(argc,argv,"ce:l:qx:v");
parseCommandLine(cmd);
// Read some data from files
if(VERBOSE) cerr<<"loading inputs"<<endl;
loadInputs(configFile,refGffFile,refFasta,altFasta);
// Check that the reference gene is well-formed
if(VERBOSE) cerr<<"checking reference gene"<<endl;
status=new Essex::CompositeNode("status");
bool referenceIsOK=checkRefGene();
if(!referenceIsOK && quiet)
{ cout<<"ACE terminated successfully"<<endl; return 0; }
// Build prefix-sum arrays for fast scoring
buildPSAs(contentSensors,altSeqLen,altSeq,altSeqStr);
// Set up to generate structured output in Essex/XML
if(VERBOSE) cerr<<"preparing output"<<endl;
ofstream osACE(outACE.c_str());
initEssex(osACE,cmd);
// Compute the reference labeling
if(VERBOSE) cerr<<"computing reference labeling"<<endl;
Labeling refLab(refSeqLen);
computeLabeling(*refTrans,refLab);
// Make CIGAR alignment
if(VERBOSE) cerr<<"building alignment"<<endl;
buildAlignment();
// Project the reference GFF over to an alternate GFF
if(VERBOSE) cerr<<"mapping transcript"<<endl;
mapTranscript(outGff);
// Generate labeling file
if(VERBOSE) cerr<<"projecting the labeling"<<endl;
Labeling projectedLab(altSeqLen);
mapLabeling(refLab,projectedLab,labelingFile);
// Check the projection to see if the gene might be broken
if(VERBOSE) cerr<<"checking projection"<<endl;
bool mapped=false;
if(referenceIsOK)
checkProjection(outGff,mapped,refLab,projectedLab,osACE);
// Flush output
if(VERBOSE) cerr<<"cleaning up"<<endl;
flushOutput(osACE,mapped);
cout<<"ACE terminated successfully"<<endl;
return 0;
}
/****************************************************************
ACEplus::parseCommandLine()
****************************************************************/
void ACEplus::parseCommandLine(const CommandLine &cmd)
{
if(cmd.option('v')) { cout<<"version "<<VERSION<<endl; exit(0); }
if(cmd.numArgs()!=6)
throw String("\n\
aceplus <ace.config> <ref.gff> <ref.fasta> <alt.fasta> <out.gff> <out.essex>\n\
-c = sequence has been reversed, but cigar string has not\n\
-e N = abort if vcf errors >N\n\
-l <file> = emit a per-nucleotide labeling for the alt sequence\n\
-q = quiet (only report transcripts with mapping issues)\n\
-x <file> = also emit xml\n\
alt.fasta must have a cigar string: >ID ... /cigar=1045M3I10M7D4023M ...\n\
\n");
configFile=cmd.arg(0);
refGffFile=cmd.arg(1);
refFasta=cmd.arg(2);
altFasta=cmd.arg(3);
outGff=cmd.arg(4);
outACE=cmd.arg(5);
commandLineOpts(cmd);
}
/****************************************************************
ACEplus::processConfig()
****************************************************************/
void ACEplus::processConfig(const String &filename)
{
ACE::processConfig(filename);
// Handle paths
const String path=File::getPath(filename);
char *oldPath=new char[PATH_MAX];
getcwd(oldPath,PATH_MAX);
chdir(path.c_str());
// Load the config file
ConfigFile config(filename);
// Misc initialization
model.signalSensors=&sensors;
model.contentSensors=&contentSensors;
model.MAX_SPLICE_SHIFT=MAX_SPLICE_SHIFT;
model.MIN_EXON_LEN=MIN_EXON_LEN;
model.MIN_INTRON_LEN=MIN_INTRON_LEN;
model.NMD_DISTANCE_PARM=NMD_DISTANCE_PARM;
//if(config.isDefined("exon-strengthening-threshold"))
model.EXON_STRENGTHENING_THRESHOLD=
config.getFloatOrDie("exon-strengthening-threshold");
//else model.EXON_STRENGTHENING_THRESHOLD=2.0;
//if(config.isDefined("exon-weakening-threshold"))
model.EXON_WEAKENING_THRESHOLD=
config.getFloatOrDie("exon-weakening-threshold");
//else model.EXON_WEAKENING_THRESHOLD=0.5;
model.MIN_EXON_INTRON_RATIO=
config.getFloatOrDie("min-exon-definition-score");
model.allowExonSkipping=allowExonSkipping;
model.allowIntronRetention=allowIntronRetention;
model.allowCrypticSites=allowCrypticSites;
model.allowDeNovoSites=config.getBoolOrDie("allow-denovo-sites");
if(config.isDefined("allow-cryptic-exons"))
model.allowCrypticExons=config.getBoolOrDie("allow-cryptic-exons");
else model.allowCrypticExons=false;
if(config.isDefined("allow-regulatory-changes"))
model.allowRegulatoryChanges=
config.getBoolOrDie("allow-regulatory-changes");
else model.allowRegulatoryChanges=false;
model.MIN_SCORE=config.getFloatOrDie("min-path-score");
model.MAX_ALT_STRUCTURES=config.getIntOrDie("max-alt-structures");
if(config.isDefined("coef-denovo-exon"))
model.coefDenovoExon=config.getFloatOrDie("coef-denovo-exon");
if(config.isDefined("max-intron-retention-length"))
model.maxIntronRetentionLen=
config.getIntOrDie("max-intron-retention-length");
if(config.isDefined("min-intron-retention-LLR"))
model.minIntronRetentionLLR= // ### fixed 5/5/2017
config.getFloatOrDie("min-intron-retention-LLR");
if(config.isDefined("max-denovo-exon-length"))
model.maxDeNovoExonLen=config.getIntOrDie("max-denovo-exon-length");
if(config.isDefined("min-denovo-exon-LLR"))
model.minDeNovoExonLLR=config.getFloatOrDie("min-denovo-exon-LLR");
if(config.isDefined("sensor-scale"))
model.sensorScale=config.getFloatOrDie("sensor-scale");
if(config.isDefined("exon-intercept"))
model.exonIntercept=config.getFloatOrDie("exon-intercept");
// Use LLR for splice site signal sensors
if(config.isDefined("splice-background-model")) {
ContentSensor *bg=loadContentSensor("splice-background-model",config);
model.contentSensors->setSpliceBackgroundModel(bg);}
// Load content sensors
contentSensors.setSensor(EXON,loadContentSensor("exon-model",config));
contentSensors.setSensor(INTRON,loadContentSensor("intron-model",config));
contentSensors.setSensor(INTERGENIC,
loadContentSensor("intergenic-model",config));
// Load duration distributions
if(config.isDefined("mean-intergenic-length"))
model.intergenicLengthDistr=
new GeometricDistribution(config.lookupOrDie("mean-intergenic-length").
asInt());
if(config.isDefined("mean-intron-length"))
model.intronLengthDistr=
new GeometricDistribution(config.lookupOrDie("mean-intron-length").
asInt());
if(config.isDefined("exon-length-distr"))
model.exonLengthDistr=
new EmpiricalDistribution(config.lookupOrDie("exon-length-distr"));
/*model.spliceShiftDistr=
new EmpiricalDistribution(config.lookupOrDie("splice-shift-distr"));*/
// Load transition probabilities
if(config.isDefined("transitions")) {
String transitionFile=config.lookupOrDie("transitions");
ifstream is(transitionFile.c_str());
model.transitions=new Transitions(numSignalTypes(),is,0,0);
is.close(); }
chdir(oldPath);
delete [] oldPath;
}
/****************************************************************
ACEplus::loadContentSensor()
****************************************************************/
ContentSensor *ACEplus::loadContentSensor(const String &label,
ConfigFile &config)
{
String filename=config.lookupOrDie(label);
return ContentSensor::load(filename);
}
/****************************************************************
ACEplus::buildPSAs()
****************************************************************/
void ACEplus::buildPSAs(ContentSensors &contentSensors,int seqLen,
Sequence &seq,String &str)
{
buildPSA(EXON,contentSensors,seqLen,seq,str);
buildPSA(INTRON,contentSensors,seqLen,seq,str);
buildPSA(INTERGENIC,contentSensors,seqLen,seq,str);
}
/****************************************************************
ACEplus::buildPSA()
****************************************************************/
void ACEplus::buildPSA(ContentType type,ContentSensors &contentSensors,
int seqLen,Sequence &seq,String &str)
{
PrefixSumArray &psa=contentSensors.getPSA(type);
psa.resize(seqLen);
ContentSensor *sensor=contentSensors.getSensor(type);
psa.compute(*sensor,seq,str);
}
/****************************************************************
ACEplus::getRefLikelihood()
****************************************************************/
double ACEplus::getRefLikelihood(const Labeling &refLab,
GffTranscript *altTrans)
{
buildPSAs(contentSensors,refSeqLen,refSeq,refSeqStr); // ###
ProjectionChecker checker(*altTrans,*refTrans,altSeqStr,altSeq,
refSeqStr,refSeq,refLab,sensors);
TranscriptSignals *signals=checker.findBrokenSpliceSites();
//cout<<"building graph for ref"<<endl;
GraphBuilder graphBuilder(*refTrans,*signals,model,altSeq,altSeqStr,
refSeq,refSeqStr,*alignment,true);
//cout<<"done building graph for ref"<<endl;
LightGraph *G=graphBuilder.getGraph();
if(!G) return NEGATIVE_INFINITY;
TranscriptPaths paths(*G,model.MAX_ALT_STRUCTURES,refSeq.getLength(),model);
if(paths.numPaths()!=1) {
//throw String("Wrong number of reference paths: ")+paths.numPaths();
cout<<"number of ref paths = "<<paths.numPaths()<<endl;
return NEGATIVE_INFINITY; }
TranscriptPath *path=paths[0];
path->computeScore(model);
//path->dumpScores();
double score=path->getScore();
delete signals; delete G;
const double L=double(refSeq.getLength());
return score/L; // == Lth root in log space
}
/****************************************************************
ACEplus::checkProjection()
****************************************************************/
void ACEplus::checkProjection(const String &outGff,bool &mapped,
const Labeling &refLab,
const Labeling &projectedLab,
ostream &osACE)
{
// Convert to essex and add variants
GffTranscript *altTrans=loadGff(outGff);
altTrans->loadSequence(altSeqStr);
altTrans->computePhases();
Essex::CompositeNode *altTransEssex=
altTrans->toEssex(reverseStrand,altSeqLen);
altTransEssex->getTag()="mapped-transcript";
VariantClassifier classifier(variants,VariantClassifier::ALT,*altTrans,
altSeqLen,reverseStrand);
altTransEssex->append(classifier.makeVariantsNode());
root->append(altTransEssex);
// Decompose transcript into signals
cout<<"ProjectionChecker"<<endl;
ProjectionChecker checker(*refTrans,*altTrans,refSeqStr,refSeq,
altSeqStr,altSeq,projectedLab,sensors);
String altProtein;
if(refTrans->isCoding())
checker.translate(*refTrans,*altTrans,refProtein,altProtein);
TranscriptSignals *signals=checker.findBrokenSpliceSites();
if(!signals) {
status->prepend("unequal-numbers-of-exons");
delete altTrans;
return; }
bool isCoding=altTrans->numExons()>0;
if(isCoding) {
int start=altTrans->getIthExon(0).getBegin();
signals->setStartCodon(start);
}
// Build graph
cout<<"building alt graph"<<endl;
GraphBuilder graphBuilder(*altTrans,*signals,model,refSeq,refSeqStr,
altSeq,altSeqStr,*revAlignment);
cout<<"done building alt graph"<<endl;
LightGraph *G=graphBuilder.getGraph();
if(!G) {
status->prepend("exon-too-short");
status->prepend("bad-annotation");
delete altTrans; delete signals;
return; }
//cout<<*G<<endl;
// Extract paths
cout<<"extracting paths"<<endl;
cout<<G->getNumVertices()<<" vertices, "<<G->getNumEdges()<<" edge"<<endl;
TranscriptPaths paths(*G,model.MAX_ALT_STRUCTURES,altSeq.getLength(),model);
cout<<paths.numPaths()<<" paths"<<endl;
// Compute posteriors
cout<<"scoring paths"<<endl;
/* if(paths.numPaths()==0) {
status->prepend("no-transcript");
delete altTrans;
delete G;
delete signals;
return; }*/
paths.computePosteriors();
paths.filter(model.MIN_SCORE);
// Handle cases
cout<<"handling cases: "<<paths.numPaths()<<" paths"<<endl;
//if(graphBuilder.mapped() && paths.numPaths()==1) {
if(paths.numPaths()==1 && paths[0]->isFullyAnnotated()) {
if(signals->anyWeakened()) appendBrokenSignals(signals);
status->prepend("mapped");
mapped=true;
//altTransEssex->setAttribute("score","1");
if(refTrans->isCoding())
handleCoding(altTrans,checker,projectedLab);
else
handleNoncoding(altTrans);
}
else { // Enumerate alternative structures
//altTransEssex->setAttribute("score","0");
enumerateAlts(paths,altTransEssex,signals,altTrans,osACE,refLab,
projectedLab);
}
delete G;
delete signals;
delete altTrans;
}
/****************************************************************
ACEplus::enumerateAlts()
****************************************************************/
void ACEplus::enumerateAlts(TranscriptPaths &paths,
Essex::CompositeNode *altTransEssex,
TranscriptSignals *signals,
GffTranscript *altTrans,
ostream &osACE,
const Labeling &refLab,
const Labeling &projectedLab)
{
altTransEssex->deleteChild("translation");
appendBrokenSignals(signals);
int numPaths=paths.numPaths();
//cout<<numPaths<<" paths"<<endl;
if(numPaths==0) {
status->prepend("no-transcript");
return; }
status->prepend("splicing-changes");
Essex::CompositeNode *altStructNode=
new Essex::CompositeNode("alternate-structures");
status->append(altStructNode);
// Sort paths by their scores
paths.sort();
// Process each path
for(int i=0 ; i<numPaths && i<model.MAX_ALT_STRUCTURES ; ++i) {
TranscriptPath *path=paths[i];
processAltStructure(*path,altStructNode,projectedLab,i,*signals);
}
}
void ACEplus::processAltStructure(TranscriptPath &path,
Essex::CompositeNode *altStructNode,
const Labeling &projectedLab,
int whichStructure,
TranscriptSignals &signals)
{
//cout<<"PATH="<<path<<endl;
// Make a GffTranscript object
String transcriptID=
String("ALT")+whichStructure+"_"+refTrans->getTranscriptId();
GffTranscript *transcript=path.toTranscript(transcriptID,
refTrans->getGeneId(),
substrate,refTrans->getStrand(),
"ACE+");
// Identify reading frame
Essex::CompositeNode *startMsg=NULL;
if(refTrans->isCoding())
refineStartCodon(signals.getStartCodon(),*transcript,startMsg);
// Check for NMD
transcript->loadSequence(altSeqStr);
int ejcDistance;
ProteinFate fate=nmd.predict(*transcript,altSeqStr,ejcDistance);
// Convert to AlternativeStructure object
AlternativeStructure alt(transcript,fate);
alt.structureChange=path.getChange();
// Check for NMD
alt.proteinFate=nmd.predict(*transcript,altSeqStr,alt.ejcDistance);
// Add any cryptic signals for reporting in output
Vector<ACEplus_Vertex*> vertices;
path.getVertices(vertices);
for(Vector<ACEplus_Vertex*>::iterator cur=vertices.begin(),
end=vertices.end() ; cur!=end ; ++cur) {
ACEplus_Vertex *vertex=*cur;
if(!vertex->isAnnotated()) {
TranscriptSignal signal(vertex->getType(),vertex->getBegin(),
vertex->getRawScore());
if(vertex->isDeNovo()) signal.denovo=true;
else signal.cryptic=true;
signal.cutoff=vertex->getThreshold();
signal.seq=vertex->getSeq();
alt.crypticSignals.push_back(signal);
}
}
// Check for coding change, annotate with variants
Essex::CompositeNode *node=
processAltStructure(alt,altStructNode,projectedLab);
if(startMsg) node->prepend(startMsg);
}
Essex::CompositeNode *ACEplus::processAltStructure(AlternativeStructure &s,
Essex::CompositeNode *altStructNode,
const Labeling &projectedLab)
{
Essex::CompositeNode *node=
ACE::processAltStructure(s,altStructNode,projectedLab);
return node;
}
void ACEplus::refineStartCodon(int start,GffTranscript &transcript,
Essex::CompositeNode *&msg)
{
int newStart=StartCodonFinder::findStartCodon(transcript,
transcript.peekExons(),
altSeqStr,
start,
sensors);
if(newStart!=start)
if(newStart>0) {
msg=new Essex::CompositeNode("start-codon-change");
if(transcript.getStrand()==FORWARD_STRAND) {
msg->append("from",start);
msg->append("to",newStart); }
else {
msg->append("from",altSeqLen-start);
msg->append("to",altSeqLen-newStart); }
}
else msg=new Essex::CompositeNode("start-codon-lost");
if(newStart>=0)
transcript.splitUTRandCDS(altSeqStr,newStart,sensors.stopCodons);
}
int ACEplus::analyzeExonDefinition(int argc,char *argv[])
{
// Process command line
CommandLine cmd(argc,argv,"e:");
if(cmd.option('v')) { cout<<"version "<<VERSION<<endl; exit(0); }
if(cmd.numArgs()!=4)
throw String("\n\
analyze-exon-def <ace.config> <ref.gff> <ref.fasta> <LLR-threshold>\n\
-e N = abort if vcf errors >N\n\
\n");
configFile=cmd.arg(0);
refGffFile=cmd.arg(1);
refFasta=cmd.arg(2);
const float threshold=cmd.arg(3).asFloat();
// Read some data from files
processConfig(configFile);
refSeqStr=loadSeq(refFasta);
refSeq.copyFrom(refSeqStr,alphabet);
refSeqLen=refSeqStr.length();
refTrans=loadGff(refGffFile);
refTrans->loadSequence(refSeqStr);
// Build prefix-sum arrays for fast scoring
buildPSAs(contentSensors,refSeqLen,refSeq,refSeqStr);
// Check that the reference gene is well-formed
status=new Essex::CompositeNode("status");
bool referenceIsOK=checkRefGene();
if(!referenceIsOK) return;
// Analyze exon definition scores
PrefixSumArray &psa=model.contentSensors->getPSA(EXON);
if(true) {
const int numExons=refTrans->numExons();
for(int i=1 ; i+1<numExons ; ++i) {
const GffExon &exon=refTrans->getIthExon(i);
float score=psa.getInterval(exon.getBegin(),exon.getEnd());
score/=exon.length();
cout<<score<<"\t1"<<endl; }
Vector<Interval> introns;
refTrans->getIntrons(introns);
for(Vector<Interval>::const_iterator cur=introns.begin(),
end=introns.end() ; cur!=end ; ++cur) {
const Interval intron=*cur;
float score=psa.getInterval(intron.getBegin(),intron.getEnd());
score/=intron.length();
cout<<score<<"\t0"<<endl; }
}
// Analyze score intervals
if(false) {
const int numExons=refTrans->numExons();
for(int i=1 ; i+1<numExons ; ++i) {
const GffExon &exon=refTrans->getIthExon(i);
Vector<Interval> intervals;
exonDefIntervalsBelow(exon.getInterval(),threshold,intervals);
cout<<Interval::longest(intervals)<<"\t0"<<endl; }
Vector<Interval> introns;
refTrans->getIntrons(introns);
for(Vector<Interval>::const_iterator cur=introns.begin(),
end=introns.end() ; cur!=end ; ++cur) {
Vector<Interval> intervals;
exonDefIntervalsBelow(*cur,threshold,intervals);
cout<<Interval::longest(intervals)<<"\t1"<<endl; }
}
}
void ACEplus::exonDefIntervalsBelow(const Interval &exon,float threshold,
Vector<Interval> &into)
{
const int begin=exon.getBegin(), end=exon.getEnd();
PrefixSumArray &psa=model.contentSensors->getPSA(EXON);
Vector<float> scores;
for(int pos=begin ; pos<end ; ++pos)
scores.push_back(psa.getInterval(pos,pos+1));
const int L=scores.size();
int start=-1;
for(int pos=0 ; pos<L ; ++pos) {
if(scores[pos]<threshold)
{ if(pos==0 || scores[pos-1]>=threshold) start=pos; }
else
if(pos>0 && scores[pos-1]>=threshold)
into.push_back(Interval(start,pos));
}
if(start>=0 && scores[L-1]<threshold) into.push_back(Interval(start,L));
}