File: mzCalculationDlg.cpp

package info (click to toggle)
massxpert 2.3.6-1squeeze1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 20,736 kB
  • ctags: 3,541
  • sloc: cpp: 44,108; xml: 7,381; sh: 604; makefile: 108; ansic: 7
file content (617 lines) | stat: -rw-r--r-- 16,006 bytes parent folder | download
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
/* massXpert - the true massist's program.
   --------------------------------------
   Copyright(C) 2006,2007 Filippo Rusconi

   http://www.massxpert.org/massXpert

   This file is part of the massXpert project.

   The massxpert project is the successor to the "GNU polyxmass"
   project that is an official GNU project package(see
   www.gnu.org). The massXpert project is not endorsed by the GNU
   project, although it is released ---in its entirety--- under the
   GNU General Public License. A huge part of the code in massXpert
   is actually a C++ rewrite of code in GNU polyxmass. As such
   massXpert was started at the Centre National de la Recherche
   Scientifique(FRANCE), that granted me the formal authorization to
   publish it under this Free Software License.

   This software is free software; you can redistribute it and/or
   modify it under the terms of the GNU  General Public
   License version 3, as published by the Free Software Foundation.
   

   This software 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 software; if not, write to the

   Free Software Foundation, Inc.,

   51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/


/////////////////////// Qt includes
#include <QMessageBox>


/////////////////////// Local includes
#include "mzCalculationDlg.hpp"
#include "application.hpp"
#include "polChemDef.hpp"


namespace massXpert
{

  MzCalculationDlg::MzCalculationDlg(QWidget *parent,
				     const PolChemDef *polChemDef,
				     const IonizeRule *ionizeRule,
				     double mono, double avg)
    : QDialog(parent), mp_polChemDef(polChemDef)
  {
    Q_ASSERT(parent);
    Q_ASSERT(polChemDef);
    Q_ASSERT(ionizeRule);
  
    Application *application = static_cast<Application *>(qApp);
    QLocale locale = application->locale();

    m_ionizeRule = *ionizeRule;

    m_ui.setupUi(this);

    setupTreeView();

    if (mono != 0)
      m_ui.monoLineEdit->setText(locale.toString(mono, 'f', 
						 MXP_OLIGOMER_DEC_PLACES));

    if (avg != 0)
      m_ui.avgLineEdit->setText(locale.toString(avg, 'f', 
						MXP_OLIGOMER_DEC_PLACES));
    
    m_ui.srcIonizeRuleChargeSpinBox->setRange(1, 1000000000);
    m_ui.srcIonizeRuleLevelSpinBox->setRange(0, 1000000000);
  
    m_ui.destIonizeRuleChargeSpinBox->setRange(1, 1000000000);
    m_ui.destIonizeRuleStartLevelSpinBox->setRange(0, 1000000000);
    m_ui.destIonizeRuleEndLevelSpinBox->setRange(0, 1000000000);


    m_ui.srcIonizeRuleFormulaLineEdit->setText(m_ionizeRule.formula());
    m_ui.srcIonizeRuleChargeSpinBox->setValue(m_ionizeRule.charge());
    m_ui.srcIonizeRuleLevelSpinBox->setValue(m_ionizeRule.level());
    
    m_ui.destIonizeRuleFormulaLineEdit->setText(m_ionizeRule.formula());
    m_ui.destIonizeRuleChargeSpinBox->setValue(m_ionizeRule.charge());
    m_ui.destIonizeRuleStartLevelSpinBox->setValue(m_ionizeRule.level());
    m_ui.destIonizeRuleEndLevelSpinBox->setValue(m_ionizeRule.level());


    // The results-exporting menus. ////////////////////////////////

    QStringList comboBoxItemList;

    comboBoxItemList 
      << tr("To Clipboard") 
      << tr("To File")
      << tr("Select File");
  
    m_ui.exportResultsComboBox->addItems(comboBoxItemList);
  
    connect(m_ui.exportResultsComboBox,
	     SIGNAL(activated(int)),
	     this,
	     SLOT(exportResults(int)));

    mpa_resultsString = new QString();
  
    //////////////////////////////////// The results-exporting menus.
  

    QSettings settings 
     (static_cast<Application *>(qApp)->configSettingsFilePath(), 
       QSettings::IniFormat);
  
    settings.beginGroup("mz_calculation_dlg");

    restoreGeometry(settings.value("geometry").toByteArray());

    m_ui.ponderableSplitter->
      restoreState(settings.value("ponderableSplitter").toByteArray());
  
    settings.endGroup();

    connect(m_ui.calculatePushButton,
	     SIGNAL(clicked()),
	     this,
	     SLOT(calculate()));
  }


  MzCalculationDlg::~MzCalculationDlg()
  {
    delete mpa_resultsString;
  
    delete mpa_mzTreeViewModel;
  
    delete mpa_mzProxyModel;

    freeIonizableList();
  }


  void 
  MzCalculationDlg::closeEvent(QCloseEvent *event)
  {
    if (event)
      printf("%s", "");
  
    QSettings settings 
     (static_cast<Application *>(qApp)->configSettingsFilePath(), 
       QSettings::IniFormat);
  
    settings.beginGroup("mz_calculation_dlg");

    settings.setValue("geometry", saveGeometry());
  
    settings.setValue("ponderableSplitter", 
		       m_ui.ponderableSplitter->saveState());

    settings.endGroup();
  }


  void
  MzCalculationDlg::setupTreeView()
  {
    // Model stuff all thought for sorting.
    mpa_mzTreeViewModel = 
      new MzCalculationTreeViewModel(&m_ionizableList, this);
  
    mpa_mzProxyModel = new MzCalculationTreeViewSortProxyModel(this);
    mpa_mzProxyModel->setSourceModel(mpa_mzTreeViewModel);
  
    m_ui.mzTreeView->setModel(mpa_mzProxyModel);
    m_ui.mzTreeView->setParentDlg(this);
    mpa_mzTreeViewModel->setTreeView(m_ui.mzTreeView);
  }


  void
  MzCalculationDlg::calculate()
  {
    // First get all the data for the source ionizable.

    // The source ionizeRule.
    IonizeRule srcIonizeRule;
    if (!getSrcIonizeRuleData(&srcIonizeRule))
      return;
    
    Ponderable *ponderable = getSourcePonderable();
    if (!ponderable)
      return;
    
    // Create an Ionizable with empty masses but with proper
    // IonizeRule. Note that we check if the IonizeRule has a non-0
    // level, in which case we tell so to the caller with a true
    // boolean.
    Ionizable ionizable(mp_polChemDef, "NOT_SET", *ponderable,
			 srcIonizeRule,
			(srcIonizeRule.level() ? true : false));
    
    // At this point the ionizable is fully qualified.

    // No longer in use.
    delete ponderable;
    
    // At this point, the source ionizable is filled with data. And we
    // know the data are correct because everything was validated.

    // The destination ionizeRule(note that the m_level member datum
    // is not set as it will be generated during the for loop later;
    // this does not impede validation of the IonizeRule).
    IonizeRule destIonizeRule;
    if (!getDestIonizeRuleData(&destIonizeRule))
      return;
    
    // Get the destination start/end ionization levels and make sure
    // they are in an increasing order.
    int startLevel = m_ui.destIonizeRuleStartLevelSpinBox->value();
    int endLevel = m_ui.destIonizeRuleEndLevelSpinBox->value();
    
    if (startLevel > endLevel)
      {
	int temp = endLevel;
	endLevel = startLevel;
	startLevel = temp;
      }

    // Empty the treeView model, so that we can put fresh data in it.
    mpa_mzTreeViewModel->removeAll();
  
    for (int level = startLevel ; level < endLevel + 1; ++level)
      {
	destIonizeRule.setLevel(level);
	
	// Reionize the ionizable.
	if(ionizable.ionize(destIonizeRule) == -1)
	  {
	    QMessageBox::warning 
	     (this, 
	       tr("massXpert - m/z Ratio Calculator"),
	       tr("%1@%2\n"
		   "Failed to perform reionization.")
	       .arg(__FILE__)
	       .arg(__LINE__),
	       QMessageBox::Ok);
	    
	    return;
	  }
	else
	  {
	    Ionizable *newIonizable = 
	      new Ionizable(ionizable);
	    
	    mpa_mzTreeViewModel->addIonizable(newIonizable);
	  }
      }
  }


  bool
  MzCalculationDlg::getSrcIonizeRuleData(IonizeRule *ionizeRule)
  {
    Q_ASSERT(ionizeRule);

    ionizeRule->setFormula(m_ui.srcIonizeRuleFormulaLineEdit->text());
    ionizeRule->setCharge(m_ui.srcIonizeRuleChargeSpinBox->value());
    ionizeRule->setLevel(m_ui.srcIonizeRuleLevelSpinBox->value());

    if (!ionizeRule->validate(mp_polChemDef->atomList()))
      {
	QMessageBox::warning 
	 (this, 
	   tr("massXpert - m/z Ratio Calculator"),
	   tr("%1@%2\n"
	       "Failed to validate initial ionization rule.")
	   .arg(__FILE__)
	   .arg(__LINE__),
	   QMessageBox::Ok);

	return false;
      }
  
    return true;
  }


  bool
  MzCalculationDlg::getDestIonizeRuleData(IonizeRule *ionizeRule)
  {
    Q_ASSERT(ionizeRule);
    
    ionizeRule->setFormula(m_ui.destIonizeRuleFormulaLineEdit->text());
    ionizeRule->setCharge(m_ui.destIonizeRuleChargeSpinBox->value());
    // The level is dealt with in another function, as it might
    // encompass more than one single value(see calculate()). Note
    // that if level is 0, this does not invalidate the ionizeRule.

    if (!ionizeRule->validate(mp_polChemDef->atomList()))
      {
	QMessageBox::warning 
	 (this, 
	   tr("massXpert - m/z Ratio Calculator"),
	   tr("%1@%2\n"
	       "Failed to validate target ionization rule.")
	   .arg(__FILE__)
	   .arg(__LINE__),
	   QMessageBox::Ok);

	return false;
      }
    
    return true;
  }


  Ponderable *
  MzCalculationDlg::getSourcePonderable()
  {
    Application *application = static_cast<Application *>(qApp);
    QLocale locale = application->locale();
    
    QString text;
    
    double mono = 0;
    double avg = 0;

    bool ok = false;
    
    // Mono mass
    text = m_ui.monoLineEdit->text();
    
    if (text.isEmpty())
      mono = 0;
    else
      {
	mono = locale.toDouble(text, &ok);

	if(!mono && !ok)
	  {
	    QMessageBox::warning 
	     (this, 
	       tr("massXpert - m/z Ratio Calculator"),
	       tr("%1@%2\n"
		   "Failed to read mono mass.")
	       .arg(__FILE__)
	       .arg(__LINE__),
	       QMessageBox::Ok);
	    
	    return 0;
	  }
      }

    // Avg mass
    text = m_ui.avgLineEdit->text();
    
    if (text.isEmpty())
      avg = 0;
    else
      {
	avg = locale.toDouble(text, &ok);

	if(!avg && !ok)
	  {
	    QMessageBox::warning 
	     (this, 
	       tr("massXpert - m/z Ratio Calculator"),
	       tr("%1@%2\n"
		   "Failed to read mono mass.")
	       .arg(__FILE__)
	       .arg(__LINE__),
	       QMessageBox::Ok);
	    
	    return 0;
	  }
      }

    // At this point we can allocate the Ponderable:
    return new Ponderable(mono, avg);
  }
  

  void 
  MzCalculationDlg::freeIonizableList()
  {
    while(!m_ionizableList.isEmpty())
      delete m_ionizableList.takeFirst();
  }


  // The results-exporting functions. ////////////////////////////////
  // The results-exporting functions. ////////////////////////////////
  // The results-exporting functions. ////////////////////////////////
  void
  MzCalculationDlg::exportResults(int index)
  {
    // Remember that we had set up the combobox with the following strings:
    // << tr("To &Clipboard") 
    // << tr("To &File")
    // << tr("&Select File");

    if (index == 0)
      {
	exportResultsClipboard();
      }
    else if (index == 1)
      {
	exportResultsFile();
      }
    else if (index == 2)
      {
	selectResultsFile();
      }
    else 
      Q_ASSERT(0);
  
  }


  void
  MzCalculationDlg::prepareResultsTxtString()
  {
    Application *application = static_cast<Application *>(qApp);
    QLocale locale = application->locale();

    mpa_resultsString->clear();
  
    *mpa_resultsString += QObject::tr("\n---------------------------\n"
				       "m/z Calculations: \n"
				       "---------------------------\n");
  
    QString value;
  
    *mpa_resultsString += QObject::tr("\nSource conditions:\n"
				       "------------------\n");
  
    *mpa_resultsString += QObject::tr("Mono mass: %1")
      .arg(m_ui.monoLineEdit->text());
  
    *mpa_resultsString += QObject::tr(" - Avg mass: %1\n")
      .arg(m_ui.avgLineEdit->text());
    
    *mpa_resultsString += QObject::tr("Ionization formula: %1\n")
      .arg(m_ui.srcIonizeRuleFormulaLineEdit->text());
  
    *mpa_resultsString += QObject::tr("Ionization charge: %1 - ")
      .arg(m_ui.srcIonizeRuleChargeSpinBox->value());
  
    *mpa_resultsString += QObject::tr("Ionization level: %1\n")
      .arg(m_ui.srcIonizeRuleLevelSpinBox->value());
  
    *mpa_resultsString += QObject::tr("\nDestination conditions:\n"
				       "-----------------------\n");

    *mpa_resultsString += QObject::tr("Ionization formula: %1\n")
      .arg(m_ui.destIonizeRuleFormulaLineEdit->text());
  
    *mpa_resultsString += QObject::tr("Ionization charge: %1 - ")
      .arg(m_ui.destIonizeRuleChargeSpinBox->value());
  
    *mpa_resultsString += QObject::tr("Start level: %1 - ")
      .arg(m_ui.destIonizeRuleStartLevelSpinBox->value());

    *mpa_resultsString += QObject::tr("End level: %1\n\n\n")
      .arg(m_ui.destIonizeRuleEndLevelSpinBox->value());
  
    MzCalculationTreeViewModel *model = 
      static_cast<MzCalculationTreeViewModel *>(m_ui.mzTreeView->model());
    Q_ASSERT(model);
  
    int rowCount = model->rowCount();
    //   qDebug() << __FILE__ << __LINE__ << "rowCount" << rowCount;
    if (!rowCount)
      return;

    QString mzString;

    for (int iter = 0; iter < rowCount; ++iter)
      {
	QModelIndex currentIndex = model->index(iter,
						 MZ_CALC_LEVEL_COLUMN,
						 QModelIndex());
	Q_ASSERT(currentIndex.isValid());

	// We have to make sure we translate correctly from
	// locale-based textual representation of double numbers
	// to real double numbers.
	
	bool ok = false;
	
	QString valueString = 
	  model->data(currentIndex, Qt::DisplayRole).toString();
	
	double value = locale.toDouble(valueString, &ok);
	
	if (!value && !ok)
	  qFatal("Fatal error at %s@%d. Program aborted.",
		 __FILE__, __LINE__);
	
	mzString += QObject::tr("Level: %1 -- ")
	  .arg(locale.toString(value, 'f', MXP_PH_PKA_DEC_PLACES));
	
	currentIndex = model->index(iter,
				     MZ_CALC_MONO_COLUMN,
				     QModelIndex());
	Q_ASSERT(currentIndex.isValid());
      
	ok = false;
	
	valueString = 
	  model->data(currentIndex, Qt::DisplayRole).toString();
	
	value = locale.toDouble(valueString, &ok);
	
	if (!value && !ok)
	  qFatal("Fatal error at %s@%d. Program aborted.",
		 __FILE__, __LINE__);
	
	mzString += QObject::tr("Mono: %1 -- ")
	  .arg(locale.toString(value, 'f', MXP_OLIGOMER_DEC_PLACES));
      
	currentIndex = model->index(iter,
				     MZ_CALC_AVG_COLUMN,
				     QModelIndex());
	Q_ASSERT(currentIndex.isValid());

	ok = false;
	
	valueString = 
	  model->data(currentIndex, Qt::DisplayRole).toString();
	
	value = locale.toDouble(valueString, &ok);
	
	if (!value && !ok)
	  qFatal("Fatal error at %s@%d. Program aborted.",
		 __FILE__, __LINE__);
	
	mzString += QObject::tr("Avg: %1")
	  .arg(locale.toString(value, 'f', MXP_OLIGOMER_DEC_PLACES));

	mzString += ("\n");
      }

    *mpa_resultsString += mzString;
  }


  bool 
  MzCalculationDlg::exportResultsClipboard()
  {
    prepareResultsTxtString();
  
    QClipboard *clipboard = QApplication::clipboard();

    clipboard->setText(*mpa_resultsString, QClipboard::Clipboard);
  
    return true;
  }


  bool 
  MzCalculationDlg::exportResultsFile()
  {
    if (m_resultsFilePath.isEmpty())
      {
	if(!selectResultsFile())
	  return false;
      }
  
    QFile file(m_resultsFilePath);
  
    if (!file.open(QIODevice::WriteOnly | QIODevice::Append))
      {
	QMessageBox::information(this, 
				  tr("massXpert - Export Data"),
				  tr("Failed to open file in append mode."),
				  QMessageBox::Ok);
	return false;
      }
  
    QTextStream stream(&file);
    stream.setCodec("UTF-8");

    prepareResultsTxtString();
  
    stream << *mpa_resultsString;
  
    file.close();

    return true;
  }


  bool 
  MzCalculationDlg::selectResultsFile()
  {
    m_resultsFilePath = 
      QFileDialog::getSaveFileName(this, tr("Select File To Export Data To"),
				    QDir::homePath(),
				    tr("Data files(*.dat *.DAT)"));
  
    if (m_resultsFilePath.isEmpty())
      return false;

    return true;
  }
  //////////////////////////////////// The results-exporting functions.
  //////////////////////////////////// The results-exporting functions.
  //////////////////////////////////// The results-exporting functions.

} // namespace massXpert