-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSTAGR.cpp
561 lines (438 loc) · 14.5 KB
/
STAGR.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
// Copyright 2012 Egor Dolzhenko
//
// This file is a part of STAGR.
//
// STAGR is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <QtGui>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include "STAGR.h"
//Constructor
StagrMainWindow::StagrMainWindow(QWidget *parent)
:QMainWindow(parent)
{
hsps = NULL;
hspsStats = NULL;
multipleMatchesDialog = NULL;
//Creates main toolbar and initializes it with actions
createToolBar();
createMenus();
mainTabWidget = new QTabWidget;
numAlignments = 0;
//The default filenames
precursorFilename = "";//"MIC.fasta";
productFilename = "";//"MAC.fasta";
querySequenceInformationLayout = new QHBoxLayout;
querySequenceLabel = new QLabel("Precursor sequences:");
querySequenceFilenameLabel = new QLabel(precursorFilename);
querySequenceInformationLayout->addWidget(querySequenceLabel);
querySequenceInformationLayout->addWidget(querySequenceFilenameLabel);
referenceSequenceInformationLayout = new QHBoxLayout;
referenceSequenceLabel = new QLabel("Product sequences:");
referenceSequenceFilenameLabel = new QLabel(productFilename);
referenceSequenceInformationLayout = new QHBoxLayout;
referenceSequenceInformationLayout->addWidget(referenceSequenceLabel);
referenceSequenceInformationLayout->addWidget(referenceSequenceFilenameLabel);
mainLayout = new QVBoxLayout;
mainLayout->addLayout(querySequenceInformationLayout);
mainLayout->addLayout(referenceSequenceInformationLayout);
mainLayout->addWidget(mainTabWidget);
setCentralWidget(new QWidget);
centralWidget()->setLayout(mainLayout);
//create blastn settings dialog (modal)
blastnSettingsDialog = new BlastnSettingsDialog(this);
blatSettingsDialog = new BlatSettingsDialog(this);
scriptEditDialog = new ScriptEditDialog(this);
pathSettingsDialog = new PathSettingsDialog(this);
runBlastnAction = new QAction(this);
runBlatAction = new QAction(this);
//blast is used by default
currentAligner = BLASTN;
//table for storing the alignment summary
table = NULL;
connect(settingsAction, SIGNAL(triggered()), this,
SLOT(openSettingsDialog()));
//blastn is the default local alignment algorithm
connect(startAction, SIGNAL(triggered()), this,
SLOT(runStagr()));
connect(stagrSettingsAction, SIGNAL(triggered()), this,
SLOT(openMDialogMultipleMatches()));
connect(startEditorAction, SIGNAL(triggered()), this,
SLOT(openScriptEditor()));
}
//Creates main toolbar and initializes it with actions
void StagrMainWindow::createToolBar()
{
startAction = new QAction("Start", this);
settingsAction = new QAction("Blastn settings", this);
stagrSettingsAction = new QAction("STAGR settings", this);
filteringAction = new QAction("Filtering Script",this);
startEditorAction = new QAction("Script Editor", this);
startAction->setIcon(QIcon(":icons/startIcon.png"));
settingsAction->setIcon(QIcon(":icons/settingsIcon.png"));
startEditorAction->setIcon(QIcon(":icons/pythonIcon.png"));
stagrSettingsAction->setIcon(QIcon(":icons/stagrSettingsIcon.png"));
toolBar = addToolBar("mainToolBar");
toolBar->addAction(startAction);
toolBar->addAction(settingsAction);
toolBar->addAction(startEditorAction);
toolBar->addAction(stagrSettingsAction);
}
//Run blastn and initialize alignments and numAlignments
//with alignments discovered by blastn
QString StagrMainWindow::runBlastn(QString queryFilename, QString referenceFilename)
{
QProcess *blastn = new QProcess(this);
blastnArguments = blastnSettingsDialog->blastSettingsPatrameterString(queryFilename, referenceFilename);
QString result = "";
blastn->start(pathSettingsDialog->blastnPath(), blastnArguments);
blastn->waitForFinished(-1);
if( blastn->error() == QProcess::FailedToStart )
{
alert("Blastn failed to start. Please specify the correct path in the settings menu.");
return "";
}
result = blastn->readAll();
return result;
}
QString StagrMainWindow::runBlat(QString queryFilename, QString referenceFilename)
{
QProcess *blat = new QProcess(this);
blatArguments = blatSettingsDialog->blatSettingsPatrameterString(queryFilename, referenceFilename);
blat->start(pathSettingsDialog->blatPath(), blatArguments);
blat->waitForFinished(-1);
if( blat->error() == QProcess::FailedToStart )
{
alert("Blat failed to start. Please specify the correct path in the settings menu.");
return "";
}
QFile file("out");
if(!file.exists())
{
alert("error: the file with blat output is missing");
return "";
}
if(!file.open( QIODevice::ReadOnly | QIODevice::Text ))
{
alert("error: couldn't open the file with blat output");
return "";
}
QString result = "";
QTextStream blatOutputStream( &file );
result = blatOutputStream.readAll();
QFile::remove("out");
return result;
}
void StagrMainWindow::alert(QString text)
{
QMessageBox msgBox;
msgBox.setText(text);
msgBox.exec();
}
bool StagrMainWindow::runFilteringAlgorithm(QString input, QString script)
{
//initialize Python interpreter
Py_Initialize();
PyObject *argument = PyString_FromString( input.toStdString().c_str() );
PyObject *list;
PyObject *output;
list = NULL;
QString aligner;
switch(currentAligner)
{
case BLASTN:
aligner = "blastn";
break;
case BLAT:
aligner = "blat";
break;
}
QFile file(":/output2dict.py");
if(!file.exists())
{
alert("Error: the file with blat output is missing.");
return false;
}
if(!file.open( QIODevice::ReadOnly | QIODevice::Text ))
{
alert("Error: couldn't open the file with blat output.");
return false;
}
QString converter = "";
QTextStream converterOutputStream( &file );
converter = converterOutputStream.readAll();
list = runPythonFunction(converter, aligner, argument);
if(list == NULL)
{
alert("Couldn't convert the output of a local-alignment heuristic results into a list.");
return false;
}
//run the annotation script
output = runPythonFunction(script, QString("annotate"), list);
if(output == NULL)
{
alert("The annotation script produced no results");
return false;
}
if( hsps != NULL ) delete hsps;
hsps = new HSPs;
//save the annotation in hsps object
QString loadStatus = hsps->loadData(output);
if( loadStatus != "" )
{
alert(loadStatus);
return false;
}
PyErr_Clear();
Py_Finalize();
return true;
}
bool StagrMainWindow::runStagr()
{
if( (precursorFilename == "")||(productFilename == "") )
{
alert("please specify input files");
}
QString result = "";
switch(currentAligner)
{
case BLASTN:
result = runBlastn(precursorFilename, productFilename);
break;
case BLAT:
result = runBlat(precursorFilename, productFilename);
break;
}
if( runFilteringAlgorithm(result, scriptEditDialog->getScript()) == NULL ) return false;
createTable();
return true;
}
PyObject *StagrMainWindow::runPythonFunction(QString script, QString functionname, PyObject *argument)
{
PyObject *pValue;
//redirect output to file
PyRun_SimpleString("import sys");
PyObject* mainModule = PyImport_AddModule("__main__");
char const* redirectErrorOutput = "class StdoutCatcher:\n def __init__(self):\n self.data = ''\n def write(self, stuff):\n self.data = self.data + stuff\ncatcher = StdoutCatcher()\nsys.stderr = catcher";
PyRun_SimpleString(redirectErrorOutput);
PyObject* mainDict = PyModule_GetDict(mainModule);
PyObject* mainDictCopy = PyDict_Copy(mainDict);
PyRun_String(script.toStdString().c_str(), Py_file_input, mainDict, mainDict);
PyObject *pFunc = PyDict_GetItemString(mainDict, functionname.toStdString().c_str());
if (PyCallable_Check(pFunc))
{
PyObject *pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs, 0, argument);
pValue = PyObject_CallObject(pFunc, pArgs);
}
else
{
PyErr_Print();
PyObject* catcher = PyObject_GetAttrString(mainModule, "catcher");
PyObject* output = PyObject_GetAttrString(catcher, "data");
alert(PyString_AsString(output));
return NULL;
}
return pValue;
}
void StagrMainWindow::openSettingsDialog()
{
switch(currentAligner)
{
case BLASTN:
openBlastnSettingsDialog();
break;
case BLAT:
openBlatSettingsDialog();
break;
}
}
void StagrMainWindow::openMDialogMultipleMatches()
{
if(table == NULL) return;
//Table
const QModelIndexList list = table->selectionModel()->selectedRows();
if( list.count() == 0 )
return;
QString precursorId = "";
QString productId = "";
QSet<QString> precursorIds;
QSet<QString> productIds;
for (unsigned i = 0; i < list.count(); i++)
{
QModelIndex index = list.at(i);
unsigned row = index.row();
precursorIds.insert(hspsStats->at(row)[qseqid]);
productIds.insert(hspsStats->at(row)[sseqid]);
}
if( precursorIds.size() == 1 ) precursorId = precursorIds.toList()[0];
if( productIds.size() == 1 ) productId = productIds.toList()[0];
if(multipleMatchesDialog != NULL)
delete multipleMatchesDialog;
multipleMatchesDialog = new MultipleMatchesDialog(this, hsps, precursorIds, productIds,
pullOutFastaSequence(precursorFilename, precursorId),
pullOutFastaSequence(productFilename, productId)
);
multipleMatchesDialog->show();
multipleMatchesDialog->raise();
multipleMatchesDialog->activateWindow();
}
void StagrMainWindow::openBlastnSettingsDialog()
{
blastnSettingsDialog->exec();
}
void StagrMainWindow::openBlatSettingsDialog()
{
blatSettingsDialog->exec();
}
void StagrMainWindow::openScriptEditor()
{
scriptEditDialog->exec();
}
void StagrMainWindow::openPathSettingsDialog()
{
pathSettingsDialog->exec();
}
void StagrMainWindow::getAlignmentsSummary()
{
if( hspsStats != NULL) delete hspsStats;
hspsStats = new QVector<QStringList>;
QString precursorId;
QString productId;
QSet<QString> *precursorIds = hsps->getAllValues("precursorId");
QSet<QString> *productIds = hsps->getAllValues("productId");
QSetIterator<QString> precursorIdIterator(*precursorIds);
while(precursorIdIterator.hasNext())
{
precursorId = precursorIdIterator.next();
QSetIterator<QString> productIdIterator(*productIds);
while(productIdIterator.hasNext())
{
productId = productIdIterator.next();
unsigned numHSPs = hsps->numHSPs(precursorId, productId);
if( numHSPs != 0 )
{
float aveLength = hsps->getAverage(precursorId, productId, "length");
float aveGaps = hsps->getAverage(precursorId, productId, "gapopen");
float aveMismatch = hsps->getAverage(precursorId, productId, "mismatch");
QStringList stats;
stats << precursorId << productId << QString::number(numHSPs) << QString::number(aveLength, 'f', 1)
<< QString::number(aveMismatch, 'f', 1) << QString::number(aveGaps, 'f', 1);
hspsStats->append(stats);
}
}
}
}
void StagrMainWindow::getPrecursorFilename()
{
precursorFilename = QFileDialog::getOpenFileName(this, "Specify file with precursor contigs", QDir::currentPath(), "FASTA files (*.fa *.fasta);;All files (*.*)");
if( !precursorFilename.isNull() ) querySequenceFilenameLabel->setText(precursorFilename.toAscii());
}
void StagrMainWindow::getProductFilename()
{
productFilename = QFileDialog::getOpenFileName(this, "Specify file with product contigs", QDir::currentPath(), "FASTA files (*.fa *.fasta);;All files (*.*)" );
if( !productFilename.isNull() ) referenceSequenceFilenameLabel->setText(productFilename.toAscii());
}
void StagrMainWindow::createTable()
{
getAlignmentsSummary();
if(mainTabWidget != NULL)
{
mainLayout->removeWidget(mainTabWidget);
delete mainTabWidget;
mainTabWidget = NULL;
}
else
{
mainLayout->removeWidget(table);
delete table;
table = NULL;
}
QStringList header;
header << "Precursor" << "Product" << "Number of HSPs" << "Ave. Length" << "Ave. Mismatch" << "Ave. Gap";
table = new Table(NULL, header, hspsStats);
table->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
mainLayout->addWidget(table);
connect(table, SIGNAL(doubleClicked(QModelIndex)), this,
SLOT(openMDialogMultipleMatches()));
}
void StagrMainWindow::createMenus()
{
fileMenu = menuBar()->addMenu("File");
alignmentMenu = menuBar()->addMenu("Alignment");
setPathsMenu = menuBar()->addMenu("Set Paths");
getPrecursorFilenameAction = new QAction("Load Precursor Contigs", this);
getProductFilenameAction = new QAction("Load Product Contigs", this);
selectBlastnAction = new QAction("Blastn", this);
selectBlastnAction->setCheckable(true);
selectBlatAction = new QAction("Blat", this);
selectBlatAction->setCheckable(true);
openPathSettingsAction = new QAction("Set Paths", this);
connect(getPrecursorFilenameAction, SIGNAL(triggered()), this,
SLOT(getPrecursorFilename()));
connect(getProductFilenameAction, SIGNAL(triggered()), this,
SLOT(getProductFilename()));
connect(selectBlastnAction, SIGNAL(triggered()), this,
SLOT(selectBlastn()));
connect(selectBlatAction, SIGNAL(triggered()), this,
SLOT(selectBlat()));
connect(openPathSettingsAction, SIGNAL(triggered()), this,
SLOT(openPathSettingsDialog()));
fileMenu->addAction(getPrecursorFilenameAction);
fileMenu->addAction(getProductFilenameAction);
alignmentGroup = new QActionGroup(this);
alignmentGroup->addAction(selectBlastnAction);
alignmentGroup->addAction(selectBlatAction);
selectBlastnAction->setChecked(true);
alignmentMenu->addAction(selectBlastnAction);
alignmentMenu->addAction(selectBlatAction);
setPathsMenu->addAction(openPathSettingsAction);
}
void StagrMainWindow::selectBlastn()
{
currentAligner = BLASTN;
}
void StagrMainWindow::selectBlat()
{
currentAligner = BLAT;
}
QString StagrMainWindow::pullOutFastaSequence(QString filename, QString id)
{
QFile fastaFile(filename);
QTextStream stream(&fastaFile);
if(!fastaFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
alert("error opening file");
return "";
}
QString line = "";
QString sequence = "";
bool foundId = false;
while( !stream.atEnd() )
{
line = stream.readLine();
if( (foundId == true) && (line[0] == '>'))
{
return sequence;
}
if(foundId == true)
{
sequence = sequence + line;
}
if(line == ">" + id) foundId = true;
}
fastaFile.close();
return sequence;
}