keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/PeptideIdentificationVisualizer.cpp | .cpp | 2,714 | 90 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/PeptideIdentificationVisualizer.h>
#include <OpenMS/DATASTRUCTURES/DateTime.h>
#include <OpenMS/VISUAL/MetaDataBrowser.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QValidator>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QComboBox>
#include <iostream>
using namespace std;
namespace OpenMS
{
PeptideIdentificationVisualizer::PeptideIdentificationVisualizer(bool editable, QWidget * parent, MetaDataBrowser * caller) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<PeptideIdentification>()
{
pidv_caller_ = caller;
addLineEdit_(identifier_, "Identifier<br>(of corresponding ProteinIdentification)");
addSeparator_();
addLineEdit_(score_type_, "Score type");
addBooleanComboBox_(higher_better_, "Higher score is better");
addDoubleLineEdit_(identification_threshold_, "Peptide significance threshold");
addSeparator_();
addLabel_("Show peptide hits with score equal or better than a threshold.");
QPushButton * button;
addLineEditButton_("Score threshold", filter_threshold_, button, "Filter");
connect(button, SIGNAL(clicked()), this, SLOT(updateTree_()));
finishAdding_();
}
void PeptideIdentificationVisualizer::load(PeptideIdentification & s, int tree_item_id)
{
ptr_ = &s;
temp_ = s;
// id of the item in the tree
tree_id_ = tree_item_id;
identifier_->setText(temp_.getIdentifier().toQString());
identification_threshold_->setText(QString::number(temp_.getSignificanceThreshold()));
score_type_->setText(temp_.getScoreType().toQString());
higher_better_->setCurrentIndex(temp_.isHigherScoreBetter());
}
void PeptideIdentificationVisualizer::updateTree_()
{
if (filter_threshold_->text() != "")
{
pidv_caller_->filterHits_(filter_threshold_->text().toDouble(), temp_.isHigherScoreBetter(), tree_id_);
}
else
{
pidv_caller_->showAllHits_(tree_id_);
}
}
void PeptideIdentificationVisualizer::store()
{
ptr_->setIdentifier(identifier_->text());
ptr_->setSignificanceThreshold(identification_threshold_->text().toFloat());
ptr_->setScoreType(score_type_->text());
ptr_->setHigherScoreBetter(higher_better_->currentIndex());
temp_ = (*ptr_);
}
void PeptideIdentificationVisualizer::undo_()
{
load(*ptr_, tree_id_);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/PrecursorVisualizer.cpp | .cpp | 3,226 | 110 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/PrecursorVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QListWidget>
//STL
#include <iostream>
using namespace std;
namespace OpenMS
{
PrecursorVisualizer::PrecursorVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<Precursor>()
{
addLabel_("Modify processing method information.");
addSeparator_();
addDoubleLineEdit_(mz_, "m/z");
addDoubleLineEdit_(int_, "intensity");
addIntLineEdit_(charge_, "charge");
addDoubleLineEdit_(window_low_, "Lower offset from target m/z");
addDoubleLineEdit_(window_up_, "Upper offset from target m/z");
addListView_(activation_methods_, "Activation methods");
addDoubleLineEdit_(activation_energy_, "Activation energy");
finishAdding_();
}
void PrecursorVisualizer::update_()
{
mz_->setText(String(temp_.getMZ()).c_str());
int_->setText(String(temp_.getIntensity()).c_str());
charge_->setText(String(temp_.getCharge()).c_str());
window_low_->setText(String(temp_.getIsolationWindowLowerOffset()).c_str());
window_up_->setText(String(temp_.getIsolationWindowUpperOffset()).c_str());
//actions
activation_methods_->clear();
for (Size i = 0; i < static_cast<Size>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD); ++i)
{
QListWidgetItem * item = new QListWidgetItem(activation_methods_);
item->setText(QString::fromStdString(Precursor::NamesOfActivationMethod[i]));
if (temp_.getActivationMethods().count(Precursor::ActivationMethod(i)) == 1)
{
item->setCheckState(Qt::Checked);
}
else
{
item->setCheckState(Qt::Unchecked);
}
if (isEditable())
{
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
}
else
{
item->setFlags(Qt::ItemIsEnabled);
}
activation_methods_->addItem(item);
}
activation_energy_->setText(String(temp_.getActivationEnergy()).c_str());
}
void PrecursorVisualizer::store()
{
ptr_->setMZ(mz_->text().toFloat());
ptr_->setIntensity(int_->text().toFloat());
ptr_->setCharge(charge_->text().toInt());
ptr_->setIsolationWindowLowerOffset(window_low_->text().toFloat());
ptr_->setIsolationWindowUpperOffset(window_up_->text().toFloat());
ptr_->getActivationMethods().clear();
for (UInt i = 0; i < static_cast<UInt>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD); ++i)
{
if (activation_methods_->item(i)->checkState() == Qt::Checked)
{
ptr_->getActivationMethods().insert(Precursor::ActivationMethod(i));
}
}
ptr_->setActivationEnergy(activation_energy_->text().toFloat());
temp_ = (*ptr_);
}
void PrecursorVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/ProteinIdentificationVisualizer.cpp | .cpp | 5,895 | 158 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer:Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/VISUALIZER/ProteinIdentificationVisualizer.h>
#include <OpenMS/DATASTRUCTURES/DateTime.h>
#include <OpenMS/VISUAL/MetaDataBrowser.h>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QValidator>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QComboBox>
// STL
#include <iostream>
using namespace std;
namespace OpenMS
{
ProteinIdentificationVisualizer::ProteinIdentificationVisualizer(bool editable, QWidget * parent, MetaDataBrowser * caller) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<ProteinIdentification>()
{
pidv_caller_ = caller;
addLineEdit_(identifier_, "Identifier<br>(of corresponding PeptideIdentifications)");
addSeparator_();
addLineEdit_(engine_, "Search engine");
addLineEdit_(engine_version_, "Search engine version");
addLineEdit_(identification_date_, "Date of search");
addLineEdit_(score_type_, "Score type");
addBooleanComboBox_(higher_better_, "Higher score is better");
addDoubleLineEdit_(identification_threshold_, "Protein significance threshold");
addSeparator_();
addLabel_("Search Parameters:");
addLineEdit_(db_, "Database name");
addLineEdit_(db_version_, "Database version");
addLineEdit_(taxonomy_, "Taxonomy restriction");
addLineEdit_(charges_, "Allowed charges");
addIntLineEdit_(missed_cleavages_, "Missed Cleavages");
addDoubleLineEdit_(peak_tolerance_, "Fragment ion mass tolerance");
addDoubleLineEdit_(precursor_tolerance_, "Precursor ion mass tolerance");
addComboBox_(mass_type_, "Mass type");
addLineEdit_(enzyme_, "Digestion enzyme");
addSeparator_();
addLabel_("Show protein hits with score equal or better than a threshold.");
QPushButton * button;
addLineEditButton_("Score threshold", filter_threshold_, button, "Filter");
connect(button, SIGNAL(clicked()), this, SLOT(updateTree_()));
finishAdding_();
}
void ProteinIdentificationVisualizer::load(ProteinIdentification & s, int tree_item_id)
{
ptr_ = &s;
temp_ = s;
// id of the item in the tree
tree_id_ = tree_item_id;
identification_date_->setText(temp_.getDateTime().get().toQString());
identification_threshold_->setText(QString::number(temp_.getSignificanceThreshold()));
identifier_->setText(temp_.getIdentifier().toQString());
engine_->setText(temp_.getSearchEngine().toQString());
engine_version_->setText(temp_.getSearchEngineVersion().toQString());
score_type_->setText(temp_.getScoreType().toQString());
higher_better_->setCurrentIndex(temp_.isHigherScoreBetter());
db_->setText(temp_.getSearchParameters().db.toQString());
db_version_->setText(temp_.getSearchParameters().db_version.toQString());
taxonomy_->setText(temp_.getSearchParameters().taxonomy.toQString());
charges_->setText(temp_.getSearchParameters().charges.toQString());
missed_cleavages_->setText(QString::number(temp_.getSearchParameters().missed_cleavages));
peak_tolerance_->setText(QString::number(temp_.getSearchParameters().fragment_mass_tolerance));
precursor_tolerance_->setText(QString::number(temp_.getSearchParameters().precursor_mass_tolerance));
enzyme_->setText(temp_.getSearchParameters().digestion_enzyme.getName().toQString());
if (!isEditable())
{
fillComboBox_(mass_type_, &ProteinIdentification::NamesOfPeakMassType[static_cast<size_t>(temp_.getSearchParameters().mass_type)], 1);
}
else
{
fillComboBox_(mass_type_, ProteinIdentification::NamesOfPeakMassType, static_cast<int>(ProteinIdentification::PeakMassType::SIZE_OF_PEAKMASSTYPE));
mass_type_->setCurrentIndex(static_cast<int>(temp_.getSearchParameters().mass_type));
}
}
void ProteinIdentificationVisualizer::updateTree_()
{
if (filter_threshold_->text() != "")
{
pidv_caller_->filterHits_(filter_threshold_->text().toDouble(), temp_.isHigherScoreBetter(), tree_id_);
}
else
{
pidv_caller_->showAllHits_(tree_id_);
}
}
void ProteinIdentificationVisualizer::store()
{
ptr_->setSearchEngine(engine_->text());
ptr_->setSearchEngineVersion(engine_version_->text());
ptr_->setIdentifier(identifier_->text());
ptr_->setSignificanceThreshold(identification_threshold_->text().toFloat());
ptr_->setScoreType(score_type_->text());
ptr_->setHigherScoreBetter(higher_better_->currentIndex());
//date
DateTime date;
try
{
date.set(identification_date_->text());
ptr_->setDateTime(date);
}
catch (exception & /*e*/)
{
if (date.isNull())
{
std::string status = "Format of date in PROTEINIDENTIFICATION is not correct.";
emit sendStatus(status);
}
}
//search parameters
ProteinIdentification::SearchParameters tmp = ptr_->getSearchParameters();
tmp.db = db_->text();
tmp.db_version = db_version_->text();
tmp.taxonomy = taxonomy_->text();
tmp.charges = charges_->text();
tmp.missed_cleavages = missed_cleavages_->text().toInt();
tmp.fragment_mass_tolerance = peak_tolerance_->text().toFloat();
tmp.precursor_mass_tolerance = precursor_tolerance_->text().toFloat();
tmp.digestion_enzyme = *(ProteaseDB::getInstance()->getEnzyme(enzyme_->text()));
tmp.mass_type = (ProteinIdentification::PeakMassType)(mass_type_->currentIndex());
ptr_->setSearchParameters(tmp);
temp_ = (*ptr_);
}
void ProteinIdentificationVisualizer::undo_()
{
load(*ptr_, tree_id_);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/ProductVisualizer.cpp | .cpp | 1,606 | 60 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer:Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/ProductVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QComboBox>
//STL
#include <iostream>
using namespace std;
namespace OpenMS
{
ProductVisualizer::ProductVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<Product>()
{
addLabel_("Modify processing method information.");
addSeparator_();
addDoubleLineEdit_(product_mz_, "m/z");
addDoubleLineEdit_(product_window_low_, "Lower offset from target m/z");
addDoubleLineEdit_(product_window_up_, "Upper offset from target m/z");
finishAdding_();
}
void ProductVisualizer::update_()
{
product_mz_->setText(String(temp_.getMZ()).c_str());
product_window_low_->setText(String(temp_.getIsolationWindowLowerOffset()).c_str());
product_window_up_->setText(String(temp_.getIsolationWindowUpperOffset()).c_str());
}
void ProductVisualizer::store()
{
ptr_->setMZ(product_mz_->text().toFloat());
ptr_->setIsolationWindowLowerOffset(product_window_low_->text().toFloat());
ptr_->setIsolationWindowUpperOffset(product_window_up_->text().toFloat());
temp_ = (*ptr_);
}
void ProductVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/MetaInfoVisualizer.cpp | .cpp | 7,011 | 273 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/VISUALIZER/MetaInfoVisualizer.h>
//QT
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QButtonGroup>
//STL
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
namespace OpenMS
{
MetaInfoVisualizer::MetaInfoVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<MetaInfoInterface>()
{
buttongroup_ = new QButtonGroup();
nextrow_ = 0;
viewlayout_ = new QGridLayout();
addLabel_("Modify MetaData information.");
addSeparator_();
mainlayout_->addLayout(viewlayout_, row_, 0, 1, 3);
//increase row counter for mainlayout_.
row_++;
}
void MetaInfoVisualizer::load(MetaInfoInterface & m)
{
ptr_ = &m;
temp_ = m;
//keys_ is a vector of indices of type UInt
temp_.getKeys(keys_);
//Load actual metaInfo Data into viewLayout_
for (Size i = 0; i < keys_.size(); ++i)
{
loadData_(keys_[i]);
}
addSeparator_();
addLabel_("Add new MetaInfo entry.");
addLineEdit_(newkey_, "Key");
addLineEdit_(newdescription_, "Description");
addLineEdit_(newvalue_, "Value");
add2Buttons_(addbutton_, "Add", clearbutton_, "Clear");
if (!isEditable())
{
addbutton_->setEnabled(false);
clearbutton_->setEnabled(false);
}
finishAdding_();
connect(buttongroup_, SIGNAL(buttonClicked(int)), this, SLOT(remove_(int)));
connect(addbutton_, SIGNAL(clicked()), this, SLOT(add_()));
connect(clearbutton_, SIGNAL(clicked()), this, SLOT(clear_()));
}
//----------------------------------------------------------------------------
// SLOTS
//----------------------------------------------------------------------------
void MetaInfoVisualizer::remove_(int index)
{
UInt id = (UInt)index;
//Remove label
std::vector<std::pair<UInt, QLabel *> >::iterator iter;
for (iter = metalabels_.begin(); iter < metalabels_.end(); ++iter)
{
if ((*iter).first == id)
{
viewlayout_->removeWidget((*iter).second);
(*iter).second->hide();
(*iter).second = 0;
delete(*iter).second;
// cppcheck-suppress eraseDereference
metalabels_.erase(iter);
}
}
//Remove QLineEdit
std::vector<std::pair<UInt, QLineEdit *> >::iterator iter2;
for (iter2 = metainfoptr_.begin(); iter2 < metainfoptr_.end(); ++iter2)
{
if ((*iter2).first == id)
{
viewlayout_->removeWidget((*iter2).second);
(*iter2).second->hide();
(*iter2).second = 0;
delete(*iter2).second;
// cppcheck-suppress eraseDereference
metainfoptr_.erase(iter2);
}
}
//Remove QButton
std::vector<std::pair<UInt, QAbstractButton *> >::iterator iter3 = metabuttons_.begin();
while (iter3 != metabuttons_.end())
{
if ((*iter3).first == id)
{
viewlayout_->removeWidget((*iter3).second);
(*iter3).second->hide();
(*iter3).second = 0;
delete(*iter3).second;
iter3 = metabuttons_.erase(iter3);
}
else
{
++iter3;
}
}
//Remove entry from metainfointerface
temp_.removeMetaValue(id);
temp_.getKeys(keys_);
}
void MetaInfoVisualizer::loadData_(UInt index)
{
//----------------------------------------------------------------------------
// All metainfo goes into the viewlayout_
//----------------------------------------------------------------------------
QLabel * lab;
QLineEdit * ptr;
QPushButton * button;
lab = new QLabel(temp_.metaRegistry().getName(index).c_str(), this);
viewlayout_->addWidget(lab, nextrow_, 0);
ptr = new QLineEdit(this);
ptr->setText(temp_.getMetaValue(index).toString().c_str());
viewlayout_->addWidget(ptr, nextrow_, 1);
button = new QPushButton("Remove", this);
if (!isEditable())
{
button->setEnabled(false);
}
viewlayout_->addWidget(button, nextrow_, 2);
//Store information about ID(index) and QWidget
metalabels_.emplace_back(index, lab);
metainfoptr_.emplace_back(index, ptr);
metabuttons_.emplace_back(index, button);
//Insert new button with ID into buttongroup
buttongroup_->addButton(button, index);
nextrow_++;
lab->show();
ptr->show();
button->show();
}
void MetaInfoVisualizer::add_()
{
String name(newkey_->text());
String description(newdescription_->text());
String value(newvalue_->text());
if (name.trim().length() == 0) //Must have a name
{
return;
}
//Register new entry and update metainfointerface object
UInt newindex = temp_.metaRegistry().registerName(name, description, "");
//Store new data in temporary metainfo object
temp_.setMetaValue(newindex, value);
temp_.getKeys(keys_);
//Update viewlayout_
try
{
//check whether there is already an entry in GUI for added metainfo.
//If index already exists, return and do nothing.
if (buttongroup_->button(newindex) != nullptr)
{
return;
}
loadData_(newindex);
}
catch (exception & e)
{
std::cout << "Error while trying to create new meta info data. " << e.what() << endl;
}
}
void MetaInfoVisualizer::clear_()
{
newkey_->clear();
newdescription_->clear();
newvalue_->clear();
}
void MetaInfoVisualizer::store()
{
//Store QLineEdit information
std::vector<std::pair<UInt, QLineEdit *> >::iterator iter2;
for (iter2 = metainfoptr_.begin(); iter2 < metainfoptr_.end(); ++iter2)
{
UInt index = (*iter2).first;
String value(((*iter2).second)->text());
temp_.setMetaValue(index, value);
}
//copy temporary stored data into metainfo object
(*ptr_) = temp_;
}
void MetaInfoVisualizer::undo_()
{
try
{
//Delete all data in GUI
std::vector<UInt> keys_temp = keys_;
for (Size i = 0; i < keys_temp.size(); ++i)
{
remove_(keys_temp[i]);
}
metalabels_.clear();
metainfoptr_.clear();
metabuttons_.clear();
//Restore original data and refill GUI
temp_ = (*ptr_);
nextrow_ = 0;
keys_.clear();
ptr_->getKeys(keys_);
for (Size i = 0; i < keys_.size(); ++i)
{
loadData_(keys_[i]);
}
}
catch (exception & e)
{
cout << "Error while trying to restore original metainfo data. " << e.what() << endl;
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/SampleVisualizer.cpp | .cpp | 2,602 | 85 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer:Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/SampleVisualizer.h>
//QT
#include <QtWidgets/QTextEdit>
#include <QValidator>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QComboBox>
#include <iostream>
using namespace std;
namespace OpenMS
{
SampleVisualizer::SampleVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<Sample>()
{
addLabel_("Modify Sample information");
addSeparator_();
addLineEdit_(samplename_, "Name");
addLineEdit_(samplenumber_, "Number");
addLineEdit_(sampleorganism_, "Organism");
addTextEdit_(samplecomment_, "Comment");
addComboBox_(samplestate_, "State");
addDoubleLineEdit_(samplemass_, "Mass (in gram)");
addDoubleLineEdit_(samplevolume_, "Volume (in ml)");
addDoubleLineEdit_(sampleconcentration_, "Concentration (in g/l)");
finishAdding_();
}
void SampleVisualizer::update_()
{
if (!isEditable())
{
fillComboBox_(samplestate_, &temp_.NamesOfSampleState[static_cast<size_t>(temp_.getState())], 1);
}
else
{
fillComboBox_(samplestate_, temp_.NamesOfSampleState, static_cast<size_t>(Sample::SampleState::SIZE_OF_SAMPLESTATE));
samplestate_->setCurrentIndex(static_cast<int>(temp_.getState()));
}
samplename_->setText(temp_.getName().c_str());
samplenumber_->setText(temp_.getNumber().c_str());
sampleorganism_->setText(temp_.getOrganism().c_str());
samplecomment_->setText(temp_.getComment().c_str());
samplemass_->setText(String(temp_.getMass()).c_str());
samplevolume_->setText(String(temp_.getVolume()).c_str());
sampleconcentration_->setText(String(temp_.getConcentration()).c_str());
}
void SampleVisualizer::store()
{
ptr_->setName(samplename_->text());
ptr_->setNumber(samplenumber_->text());
ptr_->setOrganism(sampleorganism_->text());
ptr_->setComment(samplecomment_->toPlainText());
ptr_->setState((Sample::SampleState)samplestate_->currentIndex());
ptr_->setMass(samplemass_->text().toFloat());
ptr_->setVolume(samplevolume_->text().toFloat());
ptr_->setConcentration(sampleconcentration_->text().toFloat());
temp_ = (*ptr_);
}
void SampleVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/AcquisitionInfoVisualizer.cpp | .cpp | 1,235 | 53 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/VISUALIZER/AcquisitionInfoVisualizer.h>
// QT
#include <QValidator>
#include <QtWidgets/QLineEdit>
// STL
#include <iostream>
using namespace std;
namespace OpenMS
{
AcquisitionInfoVisualizer::AcquisitionInfoVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<AcquisitionInfo>()
{
addLabel_("Show AcquisitionInfo information");
addSeparator_();
addIntLineEdit_(acquisitioninfo_method_, "Method of combination");
finishAdding_();
}
void AcquisitionInfoVisualizer::update_()
{
acquisitioninfo_method_->setText(temp_.getMethodOfCombination().c_str());
}
void AcquisitionInfoVisualizer::store()
{
ptr_->setMethodOfCombination(acquisitioninfo_method_->text());
temp_ = (*ptr_);
}
void AcquisitionInfoVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/ContactPersonVisualizer.cpp | .cpp | 1,856 | 66 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/VISUALIZER/ContactPersonVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
using namespace std;
namespace OpenMS
{
ContactPersonVisualizer::ContactPersonVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<ContactPerson>()
{
addLabel_("Modify ContactPerson information");
addSeparator_();
addLineEdit_(firstname_, "First name");
addLineEdit_(lastname_, "Last name");
addLineEdit_(institution_, "Institution");
addLineEdit_(address_, "Address");
addLineEdit_(email_, "Email");
addLineEdit_(url_, "URL");
addLineEdit_(contact_info_, "Contact info");
finishAdding_();
}
void ContactPersonVisualizer::update_()
{
firstname_->setText(temp_.getFirstName().c_str());
lastname_->setText(temp_.getLastName().c_str());
institution_->setText(temp_.getInstitution().c_str());
email_->setText(temp_.getEmail().c_str());
contact_info_->setText(temp_.getContactInfo().c_str());
url_->setText(temp_.getURL().c_str());
address_->setText(temp_.getAddress().c_str());
}
void ContactPersonVisualizer::store()
{
ptr_->setLastName(lastname_->text());
ptr_->setInstitution(institution_->text());
ptr_->setEmail(email_->text());
ptr_->setContactInfo(contact_info_->text());
ptr_->setURL(url_->text());
ptr_->setAddress(address_->text());
temp_ = (*ptr_);
}
void ContactPersonVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/SoftwareVisualizer.cpp | .cpp | 1,254 | 54 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer:Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/SoftwareVisualizer.h>
//QT
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QLineEdit>
#include <iostream>
using namespace std;
namespace OpenMS
{
SoftwareVisualizer::SoftwareVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<Software>()
{
addLabel_("Modify software information.");
addSeparator_();
addLineEdit_(software_name_, "Name");
addLineEdit_(software_version_, "Version");
finishAdding_();
}
void SoftwareVisualizer::update_()
{
software_name_->setText(temp_.getName().c_str());
software_version_->setText(temp_.getVersion().c_str());
}
void SoftwareVisualizer::store()
{
ptr_->setName(software_name_->text());
ptr_->setVersion(software_version_->text());
temp_ = (*ptr_);
}
void SoftwareVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/HPLCVisualizer.cpp | .cpp | 1,927 | 66 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/VISUALIZER/HPLCVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QTextEdit>
#include <QValidator>
#include <iostream>
using namespace std;
namespace OpenMS
{
HPLCVisualizer::HPLCVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<HPLC>()
{
addLabel_("Modify HPLC information");
addSeparator_();
addLineEdit_(hplcinstrument_, "Instrument");
addLineEdit_(hplccolumn_, "Column");
addIntLineEdit_(hplctemperature_, "Temperature (in deg. C)");
addIntLineEdit_(hplcpressure_, "Pressure (in bar)");
addIntLineEdit_(hplcflux_, "Flux (in ul/sec)");
addTextEdit_(hplccomment_, "Comment");
finishAdding_();
}
void HPLCVisualizer::update_()
{
hplcinstrument_->setText(temp_.getInstrument().c_str());
hplccolumn_->setText(temp_.getColumn().c_str());
hplctemperature_->setText(String(temp_.getTemperature()).c_str());
hplcpressure_->setText(String(temp_.getPressure()).c_str());
hplcflux_->setText(String(temp_.getFlux()).c_str());
hplccomment_->setText(temp_.getComment().c_str());
}
void HPLCVisualizer::store()
{
ptr_->setInstrument(hplcinstrument_->text());
ptr_->setColumn(hplccolumn_->text());
ptr_->setTemperature(hplctemperature_->text().toInt());
ptr_->setPressure(hplcpressure_->text().toInt());
ptr_->setFlux(hplcflux_->text().toInt());
ptr_->setComment(hplccomment_->toPlainText());
temp_ = (*ptr_);
}
void HPLCVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/MetaInfoDescriptionVisualizer.cpp | .cpp | 1,238 | 50 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/VISUALIZER/MetaInfoDescriptionVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QTextEdit>
using namespace std;
namespace OpenMS
{
MetaInfoDescriptionVisualizer::MetaInfoDescriptionVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<MetaInfoDescription>()
{
addLabel_("Modify MetaInfoDescription information");
addSeparator_();
addLineEdit_(metainfodescription_name_, "Name of peak annotations");
finishAdding_();
}
void MetaInfoDescriptionVisualizer::update_()
{
metainfodescription_name_->setText(temp_.getName().c_str());
}
void MetaInfoDescriptionVisualizer::store()
{
ptr_->setName(metainfodescription_name_->text().toStdString());
temp_ = (*ptr_);
}
void MetaInfoDescriptionVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/MassAnalyzerVisualizer.cpp | .cpp | 5,288 | 117 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/MassAnalyzerVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QComboBox>
//STL
#include <iostream>
using namespace std;
namespace OpenMS
{
MassAnalyzerVisualizer::MassAnalyzerVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<MassAnalyzer>()
{
addLabel_("Modify massanalyzer information.");
addSeparator_();
addIntLineEdit_(order_, "Order");
addComboBox_(type_, "Type");
addComboBox_(res_method_, "Resolution method");
addComboBox_(res_type_, "Resolution type");
addComboBox_(scan_dir_, "Scan direction");
addComboBox_(scan_law_, "Scan law");
addComboBox_(reflectron_state_, "Reflectron state");
addDoubleLineEdit_(res_, "Resolution");
addDoubleLineEdit_(acc_, "Accuracy");
addDoubleLineEdit_(scan_rate_, "Scan rate (in s)");
addDoubleLineEdit_(scan_time_, "Scan time (in s)");
addDoubleLineEdit_(TOF_, "TOF Total path length (in meter)");
addDoubleLineEdit_(iso_, "Isolation width (in m/z)");
addDoubleLineEdit_(final_MS_, "Final MS exponent");
addDoubleLineEdit_(magnetic_fs_, "Magnetic field strength (in T)");
finishAdding_();
}
void MassAnalyzerVisualizer::update_()
{
if (!isEditable())
{
fillComboBox_(type_, &temp_.NamesOfAnalyzerType[static_cast<size_t>(temp_.getType())], 1);
fillComboBox_(res_method_, &temp_.NamesOfResolutionMethod[static_cast<size_t>(temp_.getResolutionMethod())], 1);
fillComboBox_(res_type_, &temp_.NamesOfResolutionType[static_cast<size_t>(temp_.getResolutionType())], 1);
fillComboBox_(scan_dir_, &temp_.NamesOfScanDirection[static_cast<size_t>(temp_.getScanDirection())], 1);
fillComboBox_(scan_law_, &temp_.NamesOfScanLaw[static_cast<size_t>(temp_.getScanLaw())], 1);
fillComboBox_(reflectron_state_, &temp_.NamesOfReflectronState[static_cast<size_t>(temp_.getReflectronState())], 1);
}
else
{
fillComboBox_(type_, temp_.NamesOfAnalyzerType, static_cast<int>(MassAnalyzer::AnalyzerType::SIZE_OF_ANALYZERTYPE));
fillComboBox_(res_method_, temp_.NamesOfResolutionMethod, static_cast<int>(MassAnalyzer::ResolutionMethod::SIZE_OF_RESOLUTIONMETHOD));
fillComboBox_(res_type_, temp_.NamesOfResolutionType, static_cast<int>(MassAnalyzer::ResolutionType::SIZE_OF_RESOLUTIONTYPE));
fillComboBox_(scan_dir_, temp_.NamesOfScanDirection, static_cast<int>(MassAnalyzer::ScanDirection::SIZE_OF_SCANDIRECTION));
fillComboBox_(scan_law_, temp_.NamesOfScanLaw, static_cast<int>(MassAnalyzer::ScanLaw::SIZE_OF_SCANLAW));
fillComboBox_(reflectron_state_, temp_.NamesOfReflectronState, static_cast<int>(MassAnalyzer::ReflectronState::SIZE_OF_REFLECTRONSTATE));
type_->setCurrentIndex(static_cast<int>(temp_.getType()));
res_method_->setCurrentIndex(static_cast<int>(temp_.getResolutionMethod()));
res_type_->setCurrentIndex(static_cast<int>(temp_.getResolutionType()));
scan_dir_->setCurrentIndex(static_cast<int>(temp_.getScanDirection()));
scan_law_->setCurrentIndex(static_cast<int>(temp_.getScanLaw()));
reflectron_state_->setCurrentIndex(static_cast<int>(temp_.getReflectronState()));
}
order_->setText(String(temp_.getOrder()).c_str());
res_->setText(String(temp_.getResolution()).c_str());
acc_->setText(String(temp_.getAccuracy()).c_str());
scan_rate_->setText(String(temp_.getScanRate()).c_str());
scan_time_->setText(String(temp_.getScanTime()).c_str());
TOF_->setText(String(temp_.getTOFTotalPathLength()).c_str());
iso_->setText(String(temp_.getIsolationWidth()).c_str());
final_MS_->setText(String(temp_.getFinalMSExponent()).c_str());
magnetic_fs_->setText(String(temp_.getMagneticFieldStrength()).c_str());
}
void MassAnalyzerVisualizer::store()
{
ptr_->setOrder(order_->text().toInt());
ptr_->setType((MassAnalyzer::AnalyzerType)type_->currentIndex());
ptr_->setResolutionMethod((MassAnalyzer::ResolutionMethod)res_method_->currentIndex());
ptr_->setResolutionType((MassAnalyzer::ResolutionType)res_type_->currentIndex());
ptr_->setScanDirection((MassAnalyzer::ScanDirection)scan_dir_->currentIndex());
ptr_->setScanLaw((MassAnalyzer::ScanLaw)scan_law_->currentIndex());
ptr_->setReflectronState((MassAnalyzer::ReflectronState)reflectron_state_->currentIndex());
ptr_->setResolution(res_->text().toDouble());
ptr_->setAccuracy(acc_->text().toDouble());
ptr_->setScanRate(scan_rate_->text().toDouble());
ptr_->setScanTime(scan_time_->text().toDouble());
ptr_->setTOFTotalPathLength(TOF_->text().toDouble());
ptr_->setIsolationWidth(iso_->text().toDouble());
ptr_->setFinalMSExponent(final_MS_->text().toInt());
ptr_->setMagneticFieldStrength(magnetic_fs_->text().toDouble());
temp_ = (*ptr_);
}
void MassAnalyzerVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/InstrumentVisualizer.cpp | .cpp | 1,984 | 74 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/InstrumentVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QComboBox>
//STL
#include <iostream>
#include <string>
using namespace std;
namespace OpenMS
{
InstrumentVisualizer::InstrumentVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<Instrument>()
{
addLabel_("Modify instrument information.");
addSeparator_();
addLineEdit_(name_, "Name");
addLineEdit_(vendor_, "Vendor");
addLineEdit_(model_, "Model");
addTextEdit_(customizations_, "Customizations");
addComboBox_(ion_optics_, "Ion optics");
finishAdding_();
}
void InstrumentVisualizer::update_()
{
name_->setText(temp_.getName().c_str());
vendor_->setText(temp_.getVendor().c_str());
model_->setText(temp_.getModel().c_str());
customizations_->setText(temp_.getCustomizations().c_str());
if (!isEditable())
{
fillComboBox_(ion_optics_, &temp_.NamesOfIonOpticsType[static_cast<size_t>(temp_.getIonOptics())], 1);
}
else
{
fillComboBox_(ion_optics_, temp_.NamesOfIonOpticsType, static_cast<int>(Instrument::IonOpticsType::SIZE_OF_IONOPTICSTYPE));
}
}
void InstrumentVisualizer::store()
{
ptr_->setName(name_->text());
ptr_->setVendor(vendor_->text());
ptr_->setModel(model_->text());
ptr_->setCustomizations(customizations_->toPlainText());
ptr_->setIonOptics((Instrument::IonOpticsType)ion_optics_->currentIndex());
temp_ = (*ptr_);
}
void InstrumentVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/InstrumentSettingsVisualizer.cpp | .cpp | 2,295 | 71 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/InstrumentSettingsVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QComboBox>
//STL
#include <iostream>
using namespace std;
namespace OpenMS
{
InstrumentSettingsVisualizer::InstrumentSettingsVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<InstrumentSettings>()
{
addLabel_("Modify the settings of the instrument.");
addSeparator_();
addComboBox_(instrumentsettings_scan_mode_, "Scan mode");
addBooleanComboBox_(zoom_scan_, "Zoom scan");
addComboBox_(instrumentsettings_polarity_, "Polarity");
finishAdding_();
}
void InstrumentSettingsVisualizer::update_()
{
if (!isEditable())
{
fillComboBox_(instrumentsettings_scan_mode_, &temp_.NamesOfScanMode[static_cast<size_t>(temp_.getScanMode())], 1);
fillComboBox_(instrumentsettings_polarity_, &IonSource::NamesOfPolarity[static_cast<size_t>(temp_.getPolarity())], 1);
}
else
{
fillComboBox_(instrumentsettings_scan_mode_, InstrumentSettings::NamesOfScanMode, static_cast<int>(InstrumentSettings::ScanMode::SIZE_OF_SCANMODE));
fillComboBox_(instrumentsettings_polarity_, IonSource::NamesOfPolarity, static_cast<int>(IonSource::Polarity::SIZE_OF_POLARITY));
instrumentsettings_scan_mode_->setCurrentIndex(static_cast<int>(temp_.getScanMode()));
zoom_scan_->setCurrentIndex(temp_.getZoomScan());
instrumentsettings_polarity_->setCurrentIndex(static_cast<int>(temp_.getPolarity()));
}
}
void InstrumentSettingsVisualizer::store()
{
ptr_->setScanMode((InstrumentSettings::ScanMode)instrumentsettings_scan_mode_->currentIndex());
ptr_->setZoomScan(zoom_scan_->currentIndex());
ptr_->setPolarity((IonSource::Polarity)instrumentsettings_polarity_->currentIndex());
temp_ = (*ptr_);
}
void InstrumentSettingsVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/SourceFileVisualizer.cpp | .cpp | 2,394 | 76 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/VISUALIZER/SourceFileVisualizer.h>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QComboBox>
#include <iostream>
using namespace std;
namespace OpenMS
{
SourceFileVisualizer::SourceFileVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<SourceFile>()
{
addLabel_("Modify source file information");
addSeparator_();
addLineEdit_(name_of_file_, "Name of file");
addLineEdit_(path_to_file_, "Path to file");
addLineEdit_(file_size_, "File size (in MB)");
addLineEdit_(file_type_, "File type");
addLineEdit_(checksum_, "Checksum");
addComboBox_(checksum_type_, "Checksum type");
addLineEdit_(native_id_type_, "Native ID type of spectra");
finishAdding_();
}
void SourceFileVisualizer::update_()
{
name_of_file_->setText(temp_.getNameOfFile().c_str());
path_to_file_->setText(temp_.getPathToFile().c_str());
file_size_->setText(String(temp_.getFileSize()).c_str());
file_type_->setText(temp_.getFileType().c_str());
checksum_->setText(temp_.getChecksum().c_str());
native_id_type_->setText(temp_.getNativeIDType().c_str());
if (!isEditable())
{
fillComboBox_(checksum_type_, &temp_.NamesOfChecksumType[static_cast<size_t>(temp_.getChecksumType())], 1);
}
else
{
fillComboBox_(checksum_type_, temp_.NamesOfChecksumType, static_cast<int>(SourceFile::ChecksumType::SIZE_OF_CHECKSUMTYPE));
checksum_type_->setCurrentIndex(static_cast<int>(temp_.getChecksumType()));
}
}
void SourceFileVisualizer::store()
{
ptr_->setNameOfFile(name_of_file_->text());
ptr_->setPathToFile(path_to_file_->text());
ptr_->setFileSize(file_size_->text().toFloat());
ptr_->setFileType(file_type_->text());
ptr_->setChecksum(checksum_->text(), (SourceFile::ChecksumType)checksum_type_->currentIndex());
ptr_->setNativeIDType(native_id_type_->text());
temp_ = (*ptr_);
}
void SourceFileVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/ExperimentalSettingsVisualizer.cpp | .cpp | 1,938 | 75 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/ExperimentalSettingsVisualizer.h>
#include <OpenMS/DATASTRUCTURES/Date.h>
#include <OpenMS/VISUAL/MetaDataBrowser.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QComboBox>
//STL
#include <iostream>
using namespace std;
namespace OpenMS
{
ExperimentalSettingsVisualizer::ExperimentalSettingsVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<ExperimentalSettings>()
{
addLabel_("Modify the settings of the experiment.");
addSeparator_();
addLineEdit_(datetime_, "Date and time of experiment");
addTextEdit_(comment_, "Comment");
addLineEdit_(fraction_identifier_, "Fraction identifier");
finishAdding_();
}
void ExperimentalSettingsVisualizer::update_()
{
datetime_->setText(temp_.getDateTime().get().c_str());
comment_->setText(temp_.getComment().c_str());
fraction_identifier_->setText(temp_.getFractionIdentifier().c_str());
}
void ExperimentalSettingsVisualizer::store()
{
DateTime date;
try
{
date.set(datetime_->text());
ptr_->setDateTime(date);
}
catch (exception & /*e*/)
{
if (date.isNull())
{
std::string status = "Format of date in EXPERIMENTALSETTINGS is not correct.";
emit sendStatus(status);
}
}
ptr_->setComment(comment_->toPlainText());
ptr_->setFractionIdentifier(fraction_identifier_->text());
temp_ = (*ptr_);
}
void ExperimentalSettingsVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/BaseVisualizer.cpp | .cpp | 425 | 15 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/VISUALIZER/BaseVisualizer.h>
namespace OpenMS
{
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/DataProcessingVisualizer.cpp | .cpp | 2,515 | 102 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/VISUALIZER/DataProcessingVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QListWidget>
//STL
#include <iostream>
using namespace std;
namespace OpenMS
{
DataProcessingVisualizer::DataProcessingVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<DataProcessing>()
{
addLabel_("Modify data processing information.");
addSeparator_();
addLineEdit_(completion_time_, "Completion time");
addListView_(actions_, "Processing actions");
finishAdding_();
}
void DataProcessingVisualizer::update_()
{
//time
completion_time_->setText(temp_.getCompletionTime().get().c_str());
//actions
actions_->clear();
for (Size i = 0; i < DataProcessing::SIZE_OF_PROCESSINGACTION; ++i)
{
QListWidgetItem * item = new QListWidgetItem(actions_);
item->setText(QString::fromStdString(DataProcessing::NamesOfProcessingAction[i]));
if (temp_.getProcessingActions().count(DataProcessing::ProcessingAction(i)) == 1)
{
item->setCheckState(Qt::Checked);
}
else
{
item->setCheckState(Qt::Unchecked);
}
if (isEditable())
{
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
}
else
{
item->setFlags(Qt::ItemIsEnabled);
}
actions_->addItem(item);
}
}
void DataProcessingVisualizer::store()
{
DateTime date;
try
{
date.set(completion_time_->text());
ptr_->setCompletionTime(date);
}
catch (exception & /*e*/)
{
if (date.isNull())
{
std::string status = "Format of date in DATAPROCESSING is not correct.";
emit sendStatus(status);
}
}
//actions
ptr_->getProcessingActions().clear();
for (UInt i = 0; i < DataProcessing::SIZE_OF_PROCESSINGACTION; ++i)
{
if (actions_->item(i)->checkState() == Qt::Checked)
{
ptr_->getProcessingActions().insert(DataProcessing::ProcessingAction(i));
}
}
temp_ = (*ptr_);
}
void DataProcessingVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/IonSourceVisualizer.cpp | .cpp | 2,500 | 76 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/VISUALIZER/IonSourceVisualizer.h>
//QT
#include <QtWidgets/QComboBox>
#include <QtWidgets/QLineEdit>
//STL
#include <iostream>
using namespace std;
namespace OpenMS
{
IonSourceVisualizer::IonSourceVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<IonSource>()
{
addLabel_("Modify ionsource information.");
addSeparator_();
addIntLineEdit_(order_, "Order");
addComboBox_(inlet_type_, "Inlet type");
addComboBox_(ionization_method_, "Ionization method");
addComboBox_(polarity_, "Polarity");
finishAdding_();
}
void IonSourceVisualizer::update_()
{
if (!isEditable())
{
fillComboBox_(inlet_type_, &temp_.NamesOfInletType[static_cast<size_t>(temp_.getInletType())], 1);
fillComboBox_(ionization_method_, &temp_.NamesOfIonizationMethod[static_cast<size_t>(temp_.getIonizationMethod())], 1);
fillComboBox_(polarity_, &temp_.NamesOfPolarity[static_cast<size_t>(temp_.getPolarity())], 1);
}
else
{
fillComboBox_(inlet_type_, temp_.NamesOfInletType, static_cast<int>(IonSource::InletType::SIZE_OF_INLETTYPE));
fillComboBox_(ionization_method_, temp_.NamesOfIonizationMethod, static_cast<int>(IonSource::IonizationMethod::SIZE_OF_IONIZATIONMETHOD));
fillComboBox_(polarity_, temp_.NamesOfPolarity, static_cast<int>(IonSource::Polarity::SIZE_OF_POLARITY));
inlet_type_->setCurrentIndex(static_cast<int>(temp_.getInletType()));
ionization_method_->setCurrentIndex(static_cast<int>(temp_.getIonizationMethod()));
polarity_->setCurrentIndex(static_cast<int>(temp_.getPolarity()));
}
order_->setText(String(temp_.getOrder()).c_str());
}
void IonSourceVisualizer::store()
{
ptr_->setOrder(order_->text().toInt());
ptr_->setInletType((IonSource::InletType)inlet_type_->currentIndex());
ptr_->setIonizationMethod((IonSource::IonizationMethod)ionization_method_->currentIndex());
ptr_->setPolarity((IonSource::Polarity)polarity_->currentIndex());
temp_ = (*ptr_);
}
void IonSourceVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/DocumentIdentifierVisualizer.cpp | .cpp | 1,507 | 56 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/VISUALIZER/DocumentIdentifierVisualizer.h>
#include <OpenMS/FORMAT/FileHandler.h>
//QT
#include <QtWidgets/QLineEdit>
using namespace std;
namespace OpenMS
{
DocumentIdentifierVisualizer::DocumentIdentifierVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<DocumentIdentifier>()
{
addLabel_("Modify DocumentIdentifier information");
addSeparator_();
addLineEdit_(identifier_, "Identifier");
addSeparator_();
addLineEdit_(file_path_, "Loaded from file");
addLineEdit_(file_type_, "File type");
finishAdding_();
}
void DocumentIdentifierVisualizer::update_()
{
identifier_->setText(temp_.getIdentifier().c_str());
file_path_->setText(temp_.getLoadedFilePath().c_str());
file_type_->setText(FileTypes::typeToName(temp_.getLoadedFileType()).c_str());
file_path_->setReadOnly(true);
file_type_->setReadOnly(true);
}
void DocumentIdentifierVisualizer::store()
{
ptr_->setIdentifier(identifier_->text());
temp_ = (*ptr_);
}
void DocumentIdentifierVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/PeptideHitVisualizer.cpp | .cpp | 1,564 | 60 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/VISUALIZER/PeptideHitVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QTextEdit>
// STL
#include <iostream>
using namespace std;
namespace OpenMS
{
PeptideHitVisualizer::PeptideHitVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<PeptideHit>()
{
addLineEdit_(peptidehit_score_, "Score");
addLineEdit_(peptidehit_charge_, "Charge");
addLineEdit_(peptidehit_rank_, "Rank");
addTextEdit_(peptidehit_sequence_, "Sequence");
finishAdding_();
}
void PeptideHitVisualizer::update_()
{
peptidehit_score_->setText(String(temp_.getScore()).c_str());
peptidehit_score_->setReadOnly(true);
peptidehit_charge_->setText(String(temp_.getCharge()).c_str());
peptidehit_charge_->setReadOnly(true);
peptidehit_rank_->setText(String(temp_.getRank()).c_str());
peptidehit_rank_->setReadOnly(true);
peptidehit_sequence_->setText(temp_.getSequence().toString().c_str());
peptidehit_sequence_->setReadOnly(true);
}
void PeptideHitVisualizer::store()
{
//TODO?
(*ptr_) = temp_;
}
void PeptideHitVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/BaseVisualizerGUI.cpp | .cpp | 5,500 | 200 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/VISUALIZER/BaseVisualizerGUI.h>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLayout>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QListWidget>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QWidget>
#include <utility>
namespace OpenMS
{
BaseVisualizerGUI::BaseVisualizerGUI(bool editable, QWidget * parent) :
QWidget(parent),
undo_button_(nullptr),
mainlayout_(nullptr),
row_(0),
editable_(editable)
{
mainlayout_ = new QGridLayout(this);
mainlayout_->setContentsMargins(0, 0, 0, 0);
}
bool BaseVisualizerGUI::isEditable() const
{
return editable_;
}
void BaseVisualizerGUI::finishAdding_()
{
if (isEditable())
{
addSeparator_();
addButton_(undo_button_, "Undo");
connect(undo_button_, SIGNAL(clicked()), this, SLOT(undo_()));
}
addVSpacer_();
}
void BaseVisualizerGUI::addLabel_(const QString& label, UInt row)
{
QLabel * label_item = new QLabel(label, this);
mainlayout_->addWidget(label_item, row, 0);
}
void BaseVisualizerGUI::addLabel_(const QString& label)
{
QLabel * label_item = new QLabel(label, this);
mainlayout_->addWidget(label_item, row_, 0, 1, 3);
row_++;
}
void BaseVisualizerGUI::addLineEdit_(QLineEdit * & ptr, QString label)
{
ptr = new QLineEdit(this);
ptr->setMinimumWidth(180);
addLabel_(std::move(label), row_);
mainlayout_->addWidget(ptr, row_, 1, 1, 2);
ptr->setReadOnly(!isEditable());
row_++;
}
void BaseVisualizerGUI::addIntLineEdit_(QLineEdit * & ptr, QString label)
{
ptr = new QLineEdit(this);
ptr->setMinimumWidth(180);
QIntValidator * vali = new QIntValidator(ptr);
ptr->setValidator(vali);
addLabel_(std::move(label), row_);
mainlayout_->addWidget(ptr, row_, 1, 1, 2);
ptr->setReadOnly(!isEditable());
row_++;
}
void BaseVisualizerGUI::addDoubleLineEdit_(QLineEdit * & ptr, QString label)
{
ptr = new QLineEdit(this);
ptr->setMinimumWidth(180);
QDoubleValidator * vali = new QDoubleValidator(ptr);
ptr->setValidator(vali);
addLabel_(std::move(label), row_);
mainlayout_->addWidget(ptr, row_, 1, 1, 2);
ptr->setReadOnly(!isEditable());
row_++;
}
void BaseVisualizerGUI::addLineEditButton_(const QString& label, QLineEdit * & ptr1, QPushButton * & ptr2, const QString& buttonlabel)
{
QLabel * label_item = new QLabel(label, this);
ptr1 = new QLineEdit(this);
ptr1->setMinimumWidth(180);
ptr2 = new QPushButton(buttonlabel, this);
mainlayout_->addWidget(label_item, row_, 0);
mainlayout_->addWidget(ptr1, row_, 1);
mainlayout_->addWidget(ptr2, row_, 2);
ptr1->setReadOnly(!isEditable());
ptr2->setEnabled(isEditable());
row_++;
}
void BaseVisualizerGUI::addTextEdit_(QTextEdit * & ptr, QString label)
{
ptr = new QTextEdit(this);
addLabel_(std::move(label), row_);
mainlayout_->addWidget(ptr, row_, 1, 1, 2);
ptr->setReadOnly(!isEditable());
row_++;
}
void BaseVisualizerGUI::addComboBox_(QComboBox * & ptr, QString label)
{
ptr = new QComboBox(this);
addLabel_(std::move(label), row_);
mainlayout_->addWidget(ptr, row_, 1, 1, 2);
ptr->blockSignals(true);
row_++;
}
void BaseVisualizerGUI::addBooleanComboBox_(QComboBox * & ptr, QString label)
{
ptr = new QComboBox(this);
ptr->insertItem(0, "false");
ptr->insertItem(1, "true");
addLabel_(std::move(label), row_);
mainlayout_->addWidget(ptr, row_, 1, 1, 2);
ptr->blockSignals(true);
row_++;
}
void BaseVisualizerGUI::fillComboBox_(QComboBox * & ptr, const std::string * items, int agr)
{
for (int i = 0; i < agr; ++i)
{
ptr->insertItem(i, QString(items[i].c_str()));
}
}
void BaseVisualizerGUI::addButton_(QPushButton * & ptr, const QString& label)
{
ptr = new QPushButton(label, this);
QHBoxLayout * box = new QHBoxLayout();
box->addStretch(1);
box->addWidget(ptr);
mainlayout_->addLayout(box, row_, 0, 1, 3);
ptr->setEnabled(isEditable());
row_++;
}
void BaseVisualizerGUI::addVSpacer_()
{
mainlayout_->setRowStretch(row_, 1);
row_++;
}
void BaseVisualizerGUI::add2Buttons_(QPushButton * & ptr1, const QString& label1, QPushButton * & ptr2, const QString& label2)
{
ptr1 = new QPushButton(label1, this);
ptr2 = new QPushButton(label2, this);
QHBoxLayout * box = new QHBoxLayout();
box->addStretch(1);
box->addWidget(ptr1);
box->addWidget(ptr2);
mainlayout_->addLayout(box, row_, 0, 1, 3);
row_++;
}
void BaseVisualizerGUI::addSeparator_()
{
QLabel * pLabel = new QLabel(this);
pLabel->setFrameShape(QFrame::HLine);
mainlayout_->addWidget(pLabel, row_, 0, 1, 3);
row_++;
}
void BaseVisualizerGUI::addListView_(QListWidget * & ptr, QString label)
{
ptr = new QListWidget(this);
addLabel_(std::move(label), row_);
mainlayout_->addWidget(ptr, row_, 1, 1, 2);
row_++;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/IonDetectorVisualizer.cpp | .cpp | 2,347 | 77 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/IonDetectorVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QComboBox>
//STL
#include <iostream>
using namespace std;
namespace OpenMS
{
IonDetectorVisualizer::IonDetectorVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<IonDetector>()
{
addLabel_("Modify iondetector information.");
addSeparator_();
addIntLineEdit_(order_, "Order");
addComboBox_(type_, "Type");
addComboBox_(ac_mode_, "Acquisition mode");
addDoubleLineEdit_(res_, "Resolution (in ns)");
addDoubleLineEdit_(freq_, "ADC sampling frequency (in Hz)");
finishAdding_();
}
void IonDetectorVisualizer::update_()
{
if (!isEditable())
{
fillComboBox_(type_, &temp_.NamesOfType[static_cast<size_t>(temp_.getType())], 1);
fillComboBox_(ac_mode_, &temp_.NamesOfAcquisitionMode[static_cast<size_t>(temp_.getAcquisitionMode())], 1);
}
else
{
fillComboBox_(type_, temp_.NamesOfType, static_cast<int>(IonDetector::Type::SIZE_OF_TYPE));
fillComboBox_(ac_mode_, temp_.NamesOfAcquisitionMode, static_cast<int>(IonDetector::AcquisitionMode::SIZE_OF_ACQUISITIONMODE));
type_->setCurrentIndex(static_cast<int>(temp_.getType()));
ac_mode_->setCurrentIndex(static_cast<int>(temp_.getAcquisitionMode()));
}
order_->setText(String(temp_.getOrder()).c_str());
res_->setText(String(temp_.getResolution()).c_str());
freq_->setText(String(temp_.getADCSamplingFrequency()).c_str());
}
void IonDetectorVisualizer::store()
{
ptr_->setOrder(order_->text().toInt());
ptr_->setResolution(res_->text().toDouble());
ptr_->setADCSamplingFrequency(freq_->text().toDouble());
ptr_->setType((IonDetector::Type)type_->currentIndex());
ptr_->setAcquisitionMode((IonDetector::AcquisitionMode)ac_mode_->currentIndex());
temp_ = (*ptr_);
}
void IonDetectorVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/GradientVisualizer.cpp | .cpp | 7,241 | 266 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/VISUALIZER/GradientVisualizer.h>
#include <OpenMS/DATASTRUCTURES/String.h>
//QT
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QValidator>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QGridLayout>
//STL
#include <iostream>
#include <vector>
using namespace std;
namespace OpenMS
{
GradientVisualizer::GradientVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<Gradient>()
{
nextrow_ = 0;
}
void GradientVisualizer::load(Gradient & g)
{
ptr_ = &g;
temp_ = g;
addLabel_("Modify Gradient information");
addSeparator_();
viewlayout_ = new QGridLayout();
mainlayout_->addLayout(viewlayout_, row_, 0, 1, 3);
row_++;
//Get the actuall eluent, timepoint and percentage values.
loadData_();
addSeparator_();
addLineEditButton_("Add new Eluent", new_eluent_, add_eluent_button_, "Add Eluent");
addLineEditButton_("Add new Timepoint", new_timepoint_, add_timepoint_button_, "Add Timepoint");
addLabel_("Attention: All percentage values at a certain timepoint must add up to 100.");
addSeparator_();
addLabel_("Remove all eluents, timepoints and percentage values.");
addButton_(removebutton_, "Remove");
finishAdding_();
addSeparator_();
connect(add_timepoint_button_, SIGNAL(clicked()), this, SLOT(addTimepoint_()));
connect(add_eluent_button_, SIGNAL(clicked()), this, SLOT(addEluent_()));
connect(removebutton_, SIGNAL(clicked()), this, SLOT(deleteData_()));
//Input validator
timepoint_vali_ = new QIntValidator(new_timepoint_);
new_timepoint_->setValidator(timepoint_vali_);
}
//----------------------------------------------------------------------------
// SLOTS
//----------------------------------------------------------------------------
void GradientVisualizer::deleteData_()
{
//Remove entries from Gradient
temp_.clearEluents();
temp_.clearTimepoints();
temp_.clearPercentages();
update_();
}
void GradientVisualizer::addTimepoint_()
{
//Check whether new timepoint is in range
String m(new_timepoint_->text());
if (timepoints_.empty() && m.trim().length() != 0)
{
temp_.addTimepoint(m.toInt());
update_();
}
else
{
if (m.trim().length() != 0 && timepoints_.back() < m.toInt())
{
temp_.addTimepoint(m.toInt());
update_();
}
}
}
void GradientVisualizer::addEluent_()
{
String m(new_eluent_->text());
std::vector<String>::iterator iter;
//check if eluent name is empty
if (m.trim().length() != 0)
{
//check if eluent name already exists
for (iter = eluents_.begin(); iter < eluents_.end(); ++iter)
{
if (*iter == m)
{
return;
}
}
temp_.addEluent(m);
update_();
}
}
void GradientVisualizer::store()
{
//Check, whether sum is 100
Size time_size = timepoints_.size();
Size elu_size = eluents_.size();
Size count = 0;
Size elu_count = 0;
int sum_check = 0;
for (Size i = 0; i < time_size; ++i)
{
elu_count = i;
for (Size j = 0; j < elu_size; ++j)
{
String value((gradientdata_[elu_count])->text());
elu_count = elu_count + time_size;
sum_check = sum_check + value.toInt();
if (j == elu_size - 1 && sum_check != 100)
{
cout << "The sum does not add up to 100 !" << endl;
cout << "Please check your values." << endl;
return;
}
}
sum_check = 0;
}
//Store all values into the gradient object
for (Size i = 0; i < eluents_.size(); ++i)
{
for (Size j = 0; j < timepoints_.size(); ++j)
{
String value((gradientdata_[count + j])->text());
temp_.setPercentage(eluents_[i], timepoints_[j], value.toInt());
}
count = count + time_size;
}
//copy temporary stored data into metainfo object
(*ptr_) = temp_;
}
//----------------------------------------------------------------------------
// private
//----------------------------------------------------------------------------
void GradientVisualizer::loadData_()
{
nextrow_ = 0;
eluents_ = temp_.getEluents();
timepoints_ = temp_.getTimepoints();
//Add labels to display eluent-timepoint-percentage-triplets.
QLabel * label = new QLabel("Eluent names\\Timepoints", this);
viewlayout_->addWidget(label, 0, 0, 1, (int)temp_.getTimepoints().size());
label->show();
nextrow_++;
gradientlabel_.push_back(label);
//----------------------------------------------------------------------
// Actual data
//----------------------------------------------------------------------
for (Size i = 0; i < timepoints_.size(); ++i)
{
//Add labels to display eluent-timepoint-percentage-triplets.
QLabel * label1 = new QLabel(String(timepoints_[i]).c_str(), this);
viewlayout_->addWidget(label1, 1, (int)(i + 1));
label1->show();
gradientlabel_.push_back(label1);
}
nextrow_++;
//Add the percentage values for the eluents and their timepoint.
for (Size i = 0; i < eluents_.size(); ++i)
{
QLabel * eluent = new QLabel(eluents_[i].c_str(), this);
viewlayout_->addWidget(eluent, nextrow_, 0);
eluent->show();
gradientlabel_.push_back(eluent);
for (Size j = 0; j < timepoints_.size(); ++j)
{
percentage_ = new QLineEdit(this);
percentage_->setText(String(temp_.getPercentage(eluents_[i], timepoints_[j])).c_str());
viewlayout_->addWidget(percentage_, nextrow_, (int)(j + 1));
//Store pointers to the QLineEdits
gradientdata_.push_back(percentage_);
percentage_->show();
}
nextrow_++;
}
}
void GradientVisualizer::removeData_()
{
//Remove QLineEdits
std::vector<QLineEdit *>::iterator iter2;
for (iter2 = gradientdata_.begin(); iter2 < gradientdata_.end(); ++iter2)
{
//Delete QLineEdit field from viewlayout_
viewlayout_->removeWidget((*iter2));
(*iter2)->hide();
//Set pointer to 0
(*iter2) = 0;
//Free memory of the pointer
delete(*iter2);
}
//Remove QLabels
std::vector<QLabel *>::iterator iter_label;
for (iter_label = gradientlabel_.begin(); iter_label < gradientlabel_.end(); ++iter_label)
{
viewlayout_->removeWidget((*iter_label));
(*iter_label)->hide();
(*iter_label) = 0;
delete(*iter_label);
}
gradientdata_.clear();
gradientlabel_.clear();
}
void GradientVisualizer::update_()
{
removeData_();
loadData_();
}
void GradientVisualizer::undo_()
{
removeData_();
temp_ = (*ptr_);
loadData_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/ProteinHitVisualizer.cpp | .cpp | 1,553 | 59 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer:Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/VISUALIZER/ProteinHitVisualizer.h>
//QT
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QLineEdit>
#include <iostream>
using namespace std;
namespace OpenMS
{
ProteinHitVisualizer::ProteinHitVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<ProteinHit>()
{
addLineEdit_(proteinhit_score_, "Score");
addLineEdit_(proteinhit_rank_, "Rank");
addLineEdit_(proteinhit_accession_, "Accession");
addTextEdit_(proteinhit_sequence_, "Sequence");
finishAdding_();
}
void ProteinHitVisualizer::update_()
{
proteinhit_score_->setText(String(temp_.getScore()).c_str());
proteinhit_score_->setReadOnly(true);
proteinhit_rank_->setText(String(temp_.getRank()).c_str());
proteinhit_rank_->setReadOnly(true);
proteinhit_accession_->setText(temp_.getAccession().c_str());
proteinhit_accession_->setReadOnly(true);
proteinhit_sequence_->setText(temp_.getSequence().c_str());
proteinhit_sequence_->setReadOnly(true);
}
void ProteinHitVisualizer::store()
{
//TODO?
(*ptr_) = temp_;
}
void ProteinHitVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/SpectrumSettingsVisualizer.cpp | .cpp | 1,801 | 68 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer:Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/SpectrumSettingsVisualizer.h>
//QT
#include <QtWidgets/QComboBox>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QLineEdit>
//STL
#include <iostream>
using namespace std;
namespace OpenMS
{
SpectrumSettingsVisualizer::SpectrumSettingsVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<SpectrumSettings>()
{
addLabel_("Modify the settings of the spectrum.");
addSeparator_();
addComboBox_(type_, "Type of spectrum");
addLineEdit_(native_id_, "Native ID");
addTextEdit_(comment_, "Comment");
finishAdding_();
}
void SpectrumSettingsVisualizer::update_()
{
if (!isEditable())
{
fillComboBox_(type_, &temp_.NamesOfSpectrumType[static_cast<size_t>(temp_.getType())], 1);
}
else
{
fillComboBox_(type_, temp_.NamesOfSpectrumType, static_cast<int>(SpectrumSettings::SpectrumType::SIZE_OF_SPECTRUMTYPE));
type_->setCurrentIndex(static_cast<int>(temp_.getType()));
}
native_id_->setText(temp_.getNativeID().c_str());
comment_->setText(temp_.getComment().c_str());
}
void SpectrumSettingsVisualizer::store()
{
ptr_->setType((SpectrumSettings::SpectrumType)type_->currentIndex());
ptr_->setNativeID(native_id_->text());
ptr_->setComment(comment_->toPlainText());
temp_ = (*ptr_);
}
void SpectrumSettingsVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/ScanWindowVisualizer.cpp | .cpp | 1,232 | 54 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------s
#include <OpenMS/VISUAL/VISUALIZER/ScanWindowVisualizer.h>
//QT
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QLineEdit>
#include <iostream>
using namespace std;
namespace OpenMS
{
ScanWindowVisualizer::ScanWindowVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<ScanWindow>()
{
addLabel_("Modify scan window information.");
addSeparator_();
addIntLineEdit_(begin_, "Begin");
addIntLineEdit_(end_, "End");
finishAdding_();
}
void ScanWindowVisualizer::update_()
{
begin_->setText(QString::number(temp_.begin));
end_->setText(QString::number(temp_.end));
}
void ScanWindowVisualizer::store()
{
ptr_->begin = begin_->text().toDouble();
ptr_->end = end_->text().toDouble();
temp_ = (*ptr_);
}
void ScanWindowVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISUALIZER/AcquisitionVisualizer.cpp | .cpp | 1,218 | 55 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//OpenMS
#include <OpenMS/VISUAL/VISUALIZER/AcquisitionVisualizer.h>
//QT
#include <QtWidgets/QLineEdit>
#include <QValidator>
// STL
#include <iostream>
using namespace std;
namespace OpenMS
{
AcquisitionVisualizer::AcquisitionVisualizer(bool editable, QWidget * parent) :
BaseVisualizerGUI(editable, parent),
BaseVisualizer<Acquisition>()
{
addLabel_("Show Acquisition information");
addSeparator_();
addIntLineEdit_(acquisitionnumber_, "Identifier of the scan");
acquisitionnumber_->setReadOnly(true);
finishAdding_();
}
void AcquisitionVisualizer::update_()
{
acquisitionnumber_->setText(temp_.getIdentifier().toQString());
}
void AcquisitionVisualizer::store()
{
ptr_->setIdentifier(acquisitionnumber_->text());
temp_ = (*ptr_);
}
void AcquisitionVisualizer::undo_()
{
update_();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISITORS/LayerStatistics.cpp | .cpp | 11,057 | 307 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/MetaInfo.h>
using namespace std;
namespace OpenMS
{
// helper for visitor pattern with std::visit
template<class... Ts>
struct overload : Ts... {
using Ts::operator()...;
};
template<class... Ts>
overload(Ts...) -> overload<Ts...>;
struct MinMax {
double min;
double max;
};
/// extract min,max from a statistic (or throw Exception if stats is not present in @p overview_data)
MinMax getMinMax(const StatsMap& overview_data, const RangeStatsType& which, const std::string& error_message_container)
{
auto overview_stat = overview_data.find(which);
if (overview_stat == overview_data.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Statistic is not valid for this " + error_message_container,
which.name);
}
// getMin/Max from variant
MinMax result = std::visit(overload {[](const auto& stats) -> MinMax {
return {(double)stats.getMin(), (double)stats.getMax()};
}},
overview_stat->second);
return result;
}
/// Computes the statistics of all meta data contained in the FloatDataArray or IntegerDataArray of an MSSpectrum
template<typename SSType, typename DataArrayType>
void computeMetaDataArrayStats(const DataArrayType& arrays, StatsMap& stats)
{
using VarType = RangeStats<SSType>;
for (const auto& mda : arrays)
{
const RangeStatsType mda_name = {RangeStatsSource::ARRAYINFO, mda.getName()};
auto it_var = stats.find(mda_name);
if (it_var == stats.end()) // missing, create it
{
it_var = stats.emplace(mda_name, VarType()).first;
}
RangeStatsVariant& meta_stats_value = it_var->second;
auto& target = std::get<VarType>(meta_stats_value);
for (const auto& value : mda)
{
target.addDataPoint(value);
}
}
}
/// Update the histogram for data of a certain FloatDataArray or IntegerDataArray
/// of an MSSpectrum
template<typename DataArrayType>
void updateHistFromDataArray(const DataArrayType& arrays, const std::string& name, Math::Histogram<>& hist)
{
for (const auto& mda : arrays)
{
if (name != mda.getName()) continue;
for (const auto& value : mda)
{
hist.inc(value);
}
}
}
LayerStatisticsPeakMap::LayerStatisticsPeakMap(const PeakMap& pm)
: pm_(&pm)
{
computeStatistics_();
}
void LayerStatisticsPeakMap::computeStatistics_()
{
RangeStats<double> stat_intensity;
for (const auto& spec : *pm_)
{
for (const auto& peak : spec)
{
stat_intensity.addDataPoint(peak.getIntensity());
}
// collect stats about the meta data arrays of this spectrum
computeMetaDataArrayStats<double>(spec.getFloatDataArrays(), overview_range_data_);
computeMetaDataArrayStats<int>(spec.getIntegerDataArrays(), overview_range_data_);
}
overview_range_data_.emplace(RangeStatsType {RangeStatsSource::CORE, "intensity"}, stat_intensity);
}
Math::Histogram<> LayerStatisticsPeakMap::getDistribution(const RangeStatsType& which, const UInt number_of_bins) const
{
auto mm = getMinMax(overview_range_data_, which, "PeakMap"); // may throw if unknown statistic
Math::Histogram<> result(mm.min, mm.max, (mm.max - mm.min) / number_of_bins);
if (which == RangeStatsType{ RangeStatsSource::CORE, "intensity" })
{
for (const auto& spec : *pm_)
{
for (const auto& peak : spec)
{
result.inc(peak.getIntensity());
}
}
}
else if (which.src == RangeStatsSource::ARRAYINFO)
{
for (const auto& spec : *pm_)
{
std::visit(overload {[&](const RangeStatsInt& /*int_range*/) { updateHistFromDataArray(spec.getIntegerDataArrays(), which.name, result); },
[&](const RangeStatsDouble& /*double_range*/) { updateHistFromDataArray(spec.getFloatDataArrays(), which.name, result); }}
, overview_range_data_.at(which));
}
}
return result;
}
LayerStatisticsFeatureMap::LayerStatisticsFeatureMap(const FeatureMap& fm) : fm_(&fm)
{
computeStatistics_();
}
void addMetaDistributionValue(Math::Histogram<>& result, const string& name, const MetaInfoInterface& mi)
{
if (mi.metaValueExists(name))
{
result.inc(mi.getMetaValue(name));
}
}
Math::Histogram<> LayerStatisticsFeatureMap::getDistribution(const RangeStatsType& which,
const UInt number_of_bins) const
{
auto mm = getMinMax(overview_range_data_, which, "FeatureMap"); // may throw if unknown statistic
Math::Histogram<> result(mm.min, mm.max, (mm.max-mm.min) / number_of_bins);
if (which.src == RangeStatsSource::CORE)
{
if (which.name == "intensity") for (const auto& f : *fm_) result.inc(f.getIntensity());
else if (which.name == "charge") for (const auto& f : *fm_) result.inc(f.getCharge());
else if (which.name == "quality") for (const auto& f : *fm_) result.inc(f.getOverallQuality());
}
else if (which.src == RangeStatsSource::METAINFO)
{
for (const auto& f : *fm_) addMetaDistributionValue(result, which.name, f);
}
return result;
}
void LayerStatisticsFeatureMap::computeStatistics_()
{
RangeStats<double> stat_intensity;
RangeStats<int> stat_charge;
RangeStats<double> stat_quality;
for (const auto& f : *fm_)
{
stat_intensity.addDataPoint(f.getIntensity());
stat_charge.addDataPoint(f.getCharge());
stat_quality.addDataPoint(f.getOverallQuality());
bringInMetaStats_(&f);
}
overview_range_data_.emplace(RangeStatsType {RangeStatsSource::CORE, "intensity"}, stat_intensity);
overview_range_data_.emplace(RangeStatsType {RangeStatsSource::CORE, "charge"}, stat_charge);
overview_range_data_.emplace(RangeStatsType {RangeStatsSource::CORE, "quality"}, stat_quality);
}
LayerStatisticsConsensusMap::LayerStatisticsConsensusMap(const ConsensusMap& cm) : cm_(&cm)
{
computeStatistics_();
}
Math::Histogram<> LayerStatisticsConsensusMap::getDistribution(const RangeStatsType& which,
const UInt number_of_bins) const
{
auto mm = getMinMax(overview_range_data_, which, "ConsensusMap"); // may throw if unknown statistic
Math::Histogram<> result(mm.min, mm.max, (mm.max - mm.min) / number_of_bins);
if (which.src == RangeStatsSource::CORE)
{
if (which.name == "intensity") for (const auto& cf : *cm_) result.inc(cf.getIntensity());
else if (which.name == "charge") for (const auto& cf : *cm_) result.inc(cf.getCharge());
else if (which.name == "quality") for (const auto& cf : *cm_) result.inc(cf.getQuality());
else if (which.name == "sub-elements") for (const auto& cf : *cm_) result.inc(cf.size());
}
else if (which.src == RangeStatsSource::METAINFO)
{
for (const auto& f : *cm_) addMetaDistributionValue(result, which.name, f);
}
return result;
}
void LayerStatisticsConsensusMap::computeStatistics_()
{
RangeStats<double> stat_intensity;
RangeStats<int> stat_charge;
RangeStats<double> stat_quality;
RangeStats<int> stat_elements;
for (const auto& cf : *cm_)
{
stat_intensity.addDataPoint(cf.getIntensity());
stat_charge.addDataPoint(cf.getCharge());
stat_quality.addDataPoint(cf.getQuality());
stat_elements.addDataPoint(cf.size());
bringInMetaStats_(&cf);
}
overview_range_data_.emplace(RangeStatsType {RangeStatsSource::CORE, "intensity"}, stat_intensity);
overview_range_data_.emplace(RangeStatsType {RangeStatsSource::CORE, "charge"}, stat_charge);
overview_range_data_.emplace(RangeStatsType {RangeStatsSource::CORE, "quality"}, stat_quality);
overview_range_data_.emplace(RangeStatsType {RangeStatsSource::CORE, "sub-elements"},
stat_quality);
}
// IDENT
LayerStatisticsIdent::LayerStatisticsIdent(const IPeptideIds::PepIds& ids) : ids_(&ids)
{
computeStatistics_();
}
Math::Histogram<> LayerStatisticsIdent::getDistribution(const RangeStatsType& which,
const UInt number_of_bins) const
{
auto mm =
getMinMax(overview_range_data_, which, "vector<PepIDs>"); // may throw if unknown statistic
Math::Histogram<> result(mm.min, mm.max, (mm.max - mm.min) / number_of_bins);
if (which.src == RangeStatsSource::METAINFO)
{
for (const auto& pep : *ids_)
addMetaDistributionValue(result, which.name, pep);
}
return result;
}
void LayerStatisticsIdent::computeStatistics_()
{
for (const auto& pep : *ids_)
{
bringInMetaStats_(&pep);
}
}
void LayerStatistics::bringInMetaStats_(const MetaInfoInterface* meta_interface)
{
vector<String> new_meta_keys;
meta_interface->getKeys(new_meta_keys);
for (const auto& idx : new_meta_keys)
{
const DataValue& meta_dv = meta_interface->getMetaValue(idx);
if (meta_dv.valueType() == DataValue::INT_VALUE ||
meta_dv.valueType() == DataValue::DOUBLE_VALUE)
{ // range data
RangeStatsType key = {RangeStatsSource::METAINFO, idx};
auto itr = overview_range_data_.find(key);
// create correct type, if not present
if (itr == overview_range_data_.end())
{
auto empty_value = [&]() -> RangeStatsVariant {
if (meta_dv.valueType() == DataValue::INT_VALUE)
{
return RangeStatsInt();
}
else if (meta_dv.valueType() == DataValue::DOUBLE_VALUE)
{
return RangeStatsDouble();
}
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Metavalue has unsupported valuetype", "??");}();// immediately evaluated lambda
itr = overview_range_data_.emplace(key, empty_value).first;
}
// update the value
std::visit(overload {[&](auto&& stats) { stats.addDataPoint(meta_dv); }}, itr->second);
}
else
{ // just count data
++overview_count_data_[idx].counter;
}
}
}
} // namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/VISITORS/LayerStoreData.cpp | .cpp | 9,554 | 272 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/MetaInfo.h>
#include <OpenMS/SYSTEM/File.h>
using namespace std;
namespace OpenMS
{
FileTypes::Type LayerStoreData::getSupportedExtension_(const String& filename) const
{
auto type = FileHandler::getTypeByFileName(filename);
if (type == FileTypes::UNKNOWN)
return storage_formats_.getTypes().front();
if (!storage_formats_.contains(type))
throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename, "Format is not supported.");
return type;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// helper for saving a peakmap to a file
void savePeakMapToFile(const String& path, const PeakMap& pm, const ProgressLogger::LogType lt, const FileTypes::Type /*ext*/)
{
FileHandler().storeExperiment(path, pm, {}, lt);
}
void LayerStoreDataPeakMapVisible::saveToFile(const String& path, const ProgressLogger::LogType lt) const
{
savePeakMapToFile(path, pm_, lt, getSupportedExtension_(path));
}
// helper to filter a single MS1 spectrum
// Returns true if filtered spectrum contains data
bool filterSpectrum(const MSSpectrum& in, MSSpectrum& out, const RangeAllType& visible_range, const DataFilters& layer_filters)
{
out = in;
out.clear(false); // keep metadata
auto it_end = in.MZEnd(visible_range.getMaxMZ());
for (auto it = in.MZBegin(visible_range.getMinMZ()); it != it_end; ++it)
{
if (layer_filters.passes(in, it - in.begin()))
{
out.push_back(*it);
}
}
return !out.empty();
}
void LayerStoreDataPeakMapVisible::storeVisibleSpectrum(const MSSpectrum& spec, const RangeAllType& visible_range, const DataFilters& layer_filters)
{
pm_.clear(true);
MSSpectrum filtered;
if (filterSpectrum(spec, filtered, visible_range, layer_filters))
{
pm_.addSpectrum(filtered);
}
}
// helper to filter a single MSChromatogram
// Returns true if filtered chromatogram contains data
bool filterChrom(const MSChromatogram& in, MSChromatogram& out, const RangeAllType& visible_range, const DataFilters& layer_filters)
{
out = in;
out.clear(false); // keep metadata
auto it_end = in.RTEnd(visible_range.getMaxRT());
for (auto it = in.RTBegin(visible_range.getMinRT()); it != it_end; ++it)
{
if (layer_filters.passes(in, it - in.begin()))
{
out.push_back(*it);
}
}
return !out.empty();
}
void LayerStoreDataPeakMapVisible::storeVisibleChromatogram(const MSChromatogram& chrom, const RangeAllType& visible_range, const DataFilters& layer_filters)
{
pm_.clear(true);
MSChromatogram filtered;
if (filterChrom(chrom, filtered, visible_range, layer_filters))
{
pm_.addChromatogram(filtered);
}
}
void LayerStoreDataPeakMapVisible::storeVisibleExperiment(const PeakMap& exp, const RangeAllType& visible_range, const DataFilters& layer_filters)
{
pm_.clear(true);
// copy experimental settings
pm_.ExperimentalSettings::operator=(exp);
// get begin / end of the range
auto peak_start = exp.begin();
auto begin = exp.RTBegin(visible_range.getMinRT());
auto end = exp.RTEnd(visible_range.getMaxRT());
Size begin_idx = std::distance(peak_start, begin);
Size end_idx = std::distance(peak_start, end);
// reserve space for the correct number of spectra in RT range
pm_.reserve(end - begin);
// copy spectra
for (Size idx = begin_idx; idx < end_idx; ++idx)
{
const MSSpectrum& spectrum_ref = exp[idx];
// MS^n (n>1) spectra are copied if their precursor is in the m/z range
if (spectrum_ref.getMSLevel() > 1 && !spectrum_ref.getPrecursors().empty())
{
if (visible_range.containsMZ(spectrum_ref.getPrecursors()[0].getMZ()))
{
pm_.addSpectrum(spectrum_ref);
}
}
else
{
// MS1 spectra are cropped to the m/z range
MSSpectrum filtered;
if (filterSpectrum(spectrum_ref, filtered, visible_range, layer_filters))
{
pm_.addSpectrum(filtered);
}
}
// do not use map.addSpectrum() here, otherwise empty spectra which did not pass the filters above will be added
}
}
void LayerStoreDataPeakMapAll::saveToFile(const String& path, const ProgressLogger::LogType lt) const
{
savePeakMapToFile(path, *full_exp_, lt, getSupportedExtension_(path));
}
void LayerStoreDataPeakMapAll::storeFullExperiment(const PeakMap& exp)
{
full_exp_ = &exp;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// helper for saving a FeatureMap to a file
void saveFeatureMapToFile(const String& path, const FeatureMap& fm, const ProgressLogger::LogType lt, const FileTypes::Type /*ext*/)
{
FileHandler().storeFeatures(path, fm, {FileTypes::FEATUREXML}, lt);
}
void LayerStoreDataFeatureMapVisible::saveToFile(const String& path, const ProgressLogger::LogType lt) const
{
saveFeatureMapToFile(path, fm_, lt, this->getSupportedExtension_(path));
}
void LayerStoreDataFeatureMapVisible::storeVisibleFM(const FeatureMap& fm, const RangeAllType& visible_range, const DataFilters& layer_filters)
{
// clear output experiment
fm_.clear(true);
// copy meta data
fm_.setIdentifier(fm.getIdentifier());
fm_.setProteinIdentifications(fm.getProteinIdentifications());
// copy features
for (auto it = fm.begin(); it != fm.end(); ++it)
{
if (layer_filters.passes(*it) && visible_range.containsRT(it->getRT()) && visible_range.containsMZ(it->getMZ()))
{
fm_.push_back(*it);
}
}
}
void LayerStoreDataFeatureMapAll::saveToFile(const String& path, const ProgressLogger::LogType lt) const
{
saveFeatureMapToFile(path, *full_fm_, lt, this->getSupportedExtension_(path));
}
void LayerStoreDataFeatureMapAll::storeFullFM(const FeatureMap& fm)
{
full_fm_ = &fm;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// helper for saving a ConsensusMap to a file
void saveConsensusMapToFile(const String& path, const ConsensusMap& fm, const ProgressLogger::LogType lt, const FileTypes::Type /*ext*/)
{
FileHandler().storeConsensusFeatures(path, fm, {FileTypes::CONSENSUSXML}, lt);
}
void LayerStoreDataConsensusMapVisible::saveToFile(const String& path, const ProgressLogger::LogType lt) const
{
return saveConsensusMapToFile(path, cm_, lt, this->getSupportedExtension_(path));
}
void LayerStoreDataConsensusMapVisible::storeVisibleCM(const ConsensusMap& cm, const RangeAllType& visible_range, const DataFilters& layer_filters)
{
// clear output experiment
cm_.clear(true);
// copy file descriptions
cm_.getColumnHeaders() = cm.getColumnHeaders();
// copy features
for (auto it = cm.begin(); it != cm.end(); ++it)
{
if (layer_filters.passes(*it) && visible_range.containsRT(it->getRT()) && visible_range.containsMZ(it->getMZ()))
{
cm_.push_back(*it);
}
}
}
void LayerStoreDataConsensusMapAll::saveToFile(const String& path, const ProgressLogger::LogType lt) const
{
return saveConsensusMapToFile(path, *full_cm_, lt, this->getSupportedExtension_(path));
}
void LayerStoreDataConsensusMapAll::storeFullCM(const ConsensusMap& cm)
{
full_cm_ = &cm;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// helper for saving a PepIDs to a file
void savePepIdsToFile(const String& path, const IPeptideIds::PepIds& ids, const ProgressLogger::LogType lt, const FileTypes::Type /*ext*/)
{
FileHandler().storeIdentifications(path, {}, ids, {FileTypes::IDXML}, lt);
}
void LayerStoreDataIdentVisible::saveToFile(const String& path, const ProgressLogger::LogType lt) const
{
return savePepIdsToFile(path, ids_, lt, this->getSupportedExtension_(path));
}
void LayerStoreDataIdentVisible::storeVisibleIdent(const IPeptideIds::PepIds& ids, const RangeAllType& visible_range, const DataFilters& /*layer_filters*/)
{
ids_.clear();
// copy peptides, if visible
for (const auto& p : ids)
{
double rt = p.getRT();
double mz = p.getMZ();
// TODO: if (layer.filters.passes(*it) && ...)
if (visible_range.containsRT(rt) && visible_range.containsMZ(mz))
{
ids_.push_back(p);
}
}
}
void LayerStoreDataIdentAll::saveToFile(const String& path, const ProgressLogger::LogType lt) const
{
return savePepIdsToFile(path, *full_ids_, lt, this->getSupportedExtension_(path));
}
void LayerStoreDataIdentAll::storeFullIdent(const IPeptideIds::PepIds& ids)
{
full_ids_ = &ids;
}
} // namespace OpenMS | C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/ANNOTATION/Annotation1DCaret.cpp | .cpp | 439 | 15 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DCaret.h>
namespace OpenMS
{
} // Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/ANNOTATION/Annotation1DPeakItem.cpp | .cpp | 574 | 22 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <QColor>
namespace OpenMS
{
namespace
{
Annotation1DPeakItem<Peak1D> p(Peak1D(0, 0), "test", QColor());
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/ANNOTATION/Annotation1DItem.cpp | .cpp | 2,304 | 84 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DItem.h>
#include <QtWidgets/QInputDialog>
#include <QPainter>
namespace OpenMS
{
Annotation1DItem::Annotation1DItem(const QString & text) :
bounding_box_(),
selected_(true),
text_(text)
{
}
Annotation1DItem::Annotation1DItem(const Annotation1DItem & rhs)
{
bounding_box_ = rhs.boundingBox();
selected_ = rhs.isSelected();
text_ = rhs.getText();
}
Annotation1DItem::~Annotation1DItem() = default;
void Annotation1DItem::drawBoundingBox_(QPainter & painter)
{
// draw additional filled rectangles to highlight bounding box of selected distance_item
painter.fillRect((int)(bounding_box_.topLeft().x()) - 3, (int)(bounding_box_.topLeft().y()) - 3, 3, 3, painter.pen().color());
painter.fillRect((int)(bounding_box_.topRight().x()), (int)(bounding_box_.topRight().y()) - 3, 3, 3, painter.pen().color());
painter.fillRect((int)(bounding_box_.bottomRight().x()), (int)(bounding_box_.bottomRight().y()), 3, 3, painter.pen().color());
painter.fillRect((int)(bounding_box_.bottomLeft().x()) - 3, (int)(bounding_box_.bottomLeft().y()), 3, 3, painter.pen().color());
}
const QRectF& Annotation1DItem::boundingBox() const
{
return bounding_box_;
}
void Annotation1DItem::setSelected(bool selected)
{
selected_ = selected;
}
bool Annotation1DItem::isSelected() const
{
return selected_;
}
void Annotation1DItem::setText(const QString & text)
{
text_ = text;
}
const QString & Annotation1DItem::getText() const
{
return text_;
}
bool Annotation1DItem::editText()
{
bool ok;
QString text = QInputDialog::getText(nullptr, "Edit text", "Enter text:", QLineEdit::Normal, this->getText(), &ok);
if (ok && !text.isEmpty())
{
if (text == getText())
{
return false;
}
this->setText(text);
return true;
}
return false;
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/ANNOTATION/Annotation1DVerticalLineItem.cpp | .cpp | 4,180 | 114 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Jihyung Kim, Timo Sachsenberg $
// $Authors: Jihyung Kim, Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DVerticalLineItem.h>
#include <OpenMS/VISUAL/Plot1DCanvas.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <QtCore/QPoint>
#include <QtGui/QPainter>
using namespace std;
namespace OpenMS
{
Annotation1DVerticalLineItem::Annotation1DVerticalLineItem(const PointXYType& center_pos, const QColor& color, const QString& text) :
Annotation1DItem(text), pos_(center_pos),
color_(color)
{
}
Annotation1DVerticalLineItem::Annotation1DVerticalLineItem(const PointXYType& center_pos, const float width, const int alpha255, const bool dashed_line, const QColor& color, const QString& text)
: Annotation1DItem(text), pos_(center_pos),
width_(width),
alpha255_(alpha255),
dashed_(dashed_line),
color_(color)
{
}
void Annotation1DVerticalLineItem::ensureWithinDataRange(Plot1DCanvas* const canvas, const int layer_index)
{
canvas->pushIntoDataRange(pos_, layer_index);
}
void Annotation1DVerticalLineItem::draw(Plot1DCanvas* const canvas, QPainter& painter, bool flipped)
{
painter.save();
auto pen = painter.pen();
QColor col = pen.color();
if (color_.isValid())
{
col = color_;
}
col.setAlpha(alpha255_);
// if you try this for larger widths, the dash pattern will scale up automatically (which might look ugly)
// (if you now think of using { 5 / width_, ... }, to counter the scaling: this only works if width_ < 5, since internally Qt seems to use integer arithmetic...)
if (dashed_)
{
pen.setDashPattern({ 5, 5, 1, 5 });
}
// get left/right corner points of the rectangle (line + width); names are as if the line is vertical, but depending on gravity, it could be horizontal as well
QPoint start_px_left;
canvas->dataToWidget(pos_, start_px_left, flipped);
start_px_left = canvas->getGravitator().gravitateMax(start_px_left, canvas->canvasPixelArea());
QPoint end_px_right = canvas->getGravitator().gravitateMin(start_px_left, canvas->canvasPixelArea());
QPoint px_width;
canvas->dataToWidgetDistance(width_, width_, px_width);
px_width = canvas->getGravitator().gravitateZero(px_width); // make sure that 'height' is 0
// get width in NON-gravity (=swapped) dimension
int width = canvas->getGravitator().swap().gravityValue(px_width);
// if width_==0, only make a 1px line; in any case, it should be 1 px at least
pen.setWidth(std::max(1, width));
pen.setColor(col);
painter.setPen(pen);
painter.drawLine(start_px_left, end_px_right);
// compute bounding box on the specified painter
bounding_box_ = QRectF(QPointF(start_px_left - px_width/2), QPointF(end_px_right + px_width/2)).normalized();
if (!text_.isEmpty())
{
auto top_left_px = bounding_box_.topLeft() + QPoint(5,5);
// shift gravity axis by text_offset_
auto final = canvas->getGravitator().gravitateTo(top_left_px.toPoint(), QPoint(text_offset_, text_offset_));
GUIHelpers::drawText(painter, text_.split('\n'), final, Qt::black);
}
painter.restore();
}
void Annotation1DVerticalLineItem::move(PointXYType delta, const Gravitator& gr, const DimMapper<2>& /*dim_mapper*/)
{
pos_ = gr.swap().gravitateWith(pos_, delta); // only change the non-gravity axis
}
void Annotation1DVerticalLineItem::setPosition(const PointXYType& pos)
{
pos_ = pos;
}
const PointXYType& Annotation1DVerticalLineItem::getPosition() const
{
return pos_;
}
QRectF Annotation1DVerticalLineItem::getTextRect() const
{
int dummy;
return GUIHelpers::getTextDimension(getText().split('\n'), QFont("Courier"), dummy);
}
void Annotation1DVerticalLineItem::setTextOffset(int offset)
{
text_offset_ = offset;
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/ANNOTATION/Annotation1DDistanceItem.cpp | .cpp | 3,774 | 100 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit, Chris Bielow $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DDistanceItem.h>
#include <OpenMS/VISUAL/Plot1DCanvas.h>
#include <cmath>
using namespace std;
namespace OpenMS
{
namespace
{
Annotation1DDistanceItem p("test", {0, 0}, {0, 0});
}
Annotation1DDistanceItem::Annotation1DDistanceItem(const QString& text, const PointXYType& start_point, const PointXYType& end_point, const bool swap_ends_if_negative) :
Annotation1DItem(text), start_point_(start_point), end_point_(end_point)
{
if (swap_ends_if_negative && start_point_ > end_point_)
{
{ // make sure the distance is positive when creating the distance item
start_point_.swap(end_point_);
}
}
}
void Annotation1DDistanceItem::ensureWithinDataRange(Plot1DCanvas* const canvas, const int layer_index)
{
canvas->pushIntoDataRange(start_point_, layer_index);
canvas->pushIntoDataRange(end_point_, layer_index);
}
void Annotation1DDistanceItem::draw(Plot1DCanvas* const canvas, QPainter& painter, bool flipped)
{
// translate mz/intensity to pixel coordinates
QPoint start_p, end_p;
canvas->dataToWidget(start_point_, start_p, flipped);
canvas->dataToWidget(end_point_, end_p, flipped);
// draw arrow heads and the ends if they won't overlap
const auto arrow = ((start_p - end_p).manhattanLength() > 10) ? Painter1DBase::getClosedArrow(4) : QPainterPath();
auto line_bb = Painter1DBase::drawLineWithArrows(&painter, painter.pen(), start_p, end_p, arrow, arrow).toRect();
// find out how much additional space is needed for the text:
QRect text_bb = painter.boundingRect(QRect(), Qt::AlignCenter, text_);
// place text in the center of the line's bb, but gravitate it up
auto new_text_center = canvas->getGravitator().gravitateWith(line_bb.center(), {line_bb.width() / 2 + text_bb.width()/2, line_bb.height() / 2 + text_bb.height()/2});
text_bb.translate(new_text_center - text_bb.center());
painter.drawText(text_bb, Qt::AlignHCenter, text_);
// draw ticks
if (!ticks_.empty())
{
for (auto tick_xy : ticks_)
{
tick_xy = canvas->getGravitator().gravitateTo(tick_xy, start_point_); // move to same level as line
QPoint tick_px;
canvas->dataToWidget(tick_xy, tick_px, flipped);
QPoint tick_px_start = canvas->getGravitator().gravitateWith(tick_px, {4, 4});
QPoint tick_px_end = canvas->getGravitator().gravitateWith(tick_px, {-8, -8});
painter.drawLine(tick_px_start, tick_px_end);
}
}
// overall bounding box
bounding_box_ = text_bb.united(line_bb);
if (selected_)
{
drawBoundingBox_(painter);
}
}
void Annotation1DDistanceItem::move(const PointXYType delta, const Gravitator& gr, const DimMapper<2>& /*dim_mapper*/)
{
start_point_ = gr.gravitateWith(start_point_, delta); // only change the gravity axis
end_point_ = gr.gravitateWith(end_point_, delta); // only change the gravity axis
}
double Annotation1DDistanceItem::getDistance() const
{
const auto delta = end_point_ - start_point_;
const auto dist = std::sqrt(delta.getX() * delta.getX() + delta.getY() * delta.getY());
return std::copysign(1, delta.getX() + delta.getY()) * dist;
}
void Annotation1DDistanceItem::setTicks(const std::vector<PointXYType>& ticks)
{
ticks_ = ticks;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/ANNOTATION/Annotation1DTextItem.cpp | .cpp | 1,391 | 45 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Johannes Junker, Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DTextItem.h>
#include <OpenMS/VISUAL/Plot1DCanvas.h>
namespace OpenMS
{
namespace
{
Annotation1DTextItem p({0, 0}, "test");
}
void Annotation1DTextItem::ensureWithinDataRange(Plot1DCanvas* const canvas, const int layer_index)
{
canvas->pushIntoDataRange(position_, layer_index);
}
void Annotation1DTextItem::draw(Plot1DCanvas* const canvas, QPainter& painter, bool flipped)
{
// translate units to pixel coordinates
QPoint pos_text;
canvas->dataToWidget(position_, pos_text, flipped);
// compute bounding box of text_item on the specified painter
bounding_box_ = painter.boundingRect(QRectF(pos_text, pos_text), flags_, text_);
painter.drawText(bounding_box_, flags_, text_);
if (selected_)
{
drawBoundingBox_(painter);
}
}
void Annotation1DTextItem::move(const PointXYType delta, const Gravitator& /*gr*/, const DimMapper<2>& /*dim_mapper*/)
{
position_ += delta;
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/ANNOTATION/Annotations1DContainer.cpp | .cpp | 3,028 | 135 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/ANNOTATION/Annotations1DContainer.h>
#include <OpenMS/VISUAL/ANNOTATION/Annotation1DItem.h>
namespace OpenMS
{
Annotations1DContainer::Annotations1DContainer() = default;
Annotations1DContainer::Annotations1DContainer(const Annotations1DContainer& rhs)
: Base() // do not copy items here. They need cloning!
{
// copy annotations
for (auto item : rhs)
{
push_back(item->clone());
}
}
Annotations1DContainer& Annotations1DContainer::operator=(const Annotations1DContainer & rhs)
{
if (this != &rhs)
{
deleteAllItems_();
// clear list
clear();
// copy annotations
for (auto ptr_item : rhs)
{
push_back(ptr_item->clone());
}
}
return *this;
}
Annotations1DContainer::~Annotations1DContainer()
{
deleteAllItems_();
}
Annotation1DItem * Annotations1DContainer::getItemAt(const QPoint & pos) const
{
for (const auto ptr_item : *this)
{
if (ptr_item->boundingBox().contains(pos))
{
return ptr_item;
}
}
return nullptr;
}
void Annotations1DContainer::selectItemAt(const QPoint & pos) const
{
Annotation1DItem* item = getItemAt(pos);
if (item != nullptr)
{
item->setSelected(true);
}
}
void Annotations1DContainer::deselectItemAt(const QPoint & pos) const
{
Annotation1DItem* item = getItemAt(pos);
if (item != nullptr)
{
item->setSelected(false);
}
}
void Annotations1DContainer::selectAll()
{
for (const auto ptr_item : *this)
{
ptr_item->setSelected(true);
}
}
void Annotations1DContainer::deselectAll()
{
for (const auto ptr_item : *this)
{
ptr_item->setSelected(false);
}
}
void Annotations1DContainer::removeSelectedItems()
{
for (auto it = begin(); it != end();)
{
if ((*it)->isSelected())
{
delete (*it);
it = erase(it);
}
else
{
++it;
}
}
}
std::vector<Annotation1DItem*> Annotations1DContainer::getSelectedItems()
{
// initialize with maximal possible size
std::vector<Annotation1DItem*> annotation_items(size());
// copy if is selected
auto it = std::copy_if(begin(), end(), annotation_items.begin(), [](Annotation1DItem* anno){return anno->isSelected();});
// resize to number of actually copied items
annotation_items.resize(std::distance(annotation_items.begin(), it));
return annotation_items;
}
void Annotations1DContainer::deleteAllItems_() const
{
for (const auto ptr_item : *this)
{
delete ptr_item;
}
}
} //Namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/FLASHDeconvWizardBase.cpp | .cpp | 2,442 | 80 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Jihyung Kim $
// $Authors: Jihyung Kim $
// --------------------------------------------------------------------------
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/APPLICATIONS/ToolHandler.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/VISUAL/APPLICATIONS/FLASHDeconvWizardBase.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
#include <OpenMS/VISUAL/DIALOGS/FLASHDeconvTabWidget.h>
#include <ui_FLASHDeconvWizardBase.h>
// Qt
#include <QDesktopServices>
#include <QMessageBox>
#include <QSettings>
using namespace std;
using namespace OpenMS;
namespace OpenMS
{
using namespace Internal;
FLASHDeconvWizardBase::FLASHDeconvWizardBase(QWidget* parent) :
QMainWindow(parent), DefaultParamHandler("FLASHDeconvWizardBase"),
ui(new Ui::FLASHDeconvWizardBase)
{
ui->setupUi(this);
QSettings settings("OpenMS", "FLASHDeconvWizard");
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("windowState").toByteArray());
setWindowTitle("FLASHDeconvWizard");
setWindowIcon(QIcon(":/FLASHDeconvWizard.png"));
FLASHDeconvTabWidget* cwidget = new FLASHDeconvTabWidget(this);
setCentralWidget(cwidget);
}
FLASHDeconvWizardBase::~FLASHDeconvWizardBase()
{
delete ui;
}
void FLASHDeconvWizardBase::showAboutDialog()
{
QApplicationTOPP::showAboutDialog(this, "FLASHDeconvWizard");
}
void OpenMS::FLASHDeconvWizardBase::on_actionExit_triggered()
{
QApplicationTOPP::exit();
}
void OpenMS::FLASHDeconvWizardBase::on_actionVisit_FLASHDeconv_homepage_triggered()
{
const char* url = "https://openms.de/applications/flashdeconv/";
if (!QDesktopServices::openUrl(QUrl(url)))
{
QMessageBox::warning(nullptr, "Cannot open browser. Please check your default browser settings.", QString(url));
}
}
void OpenMS::FLASHDeconvWizardBase::on_actionReport_new_issue_triggered()
{
const char* url = "https://github.com/OpenMS/OpenMS/issues";
if (!QDesktopServices::openUrl(QUrl(url)))
{
QMessageBox::warning(nullptr, "Cannot open browser. Please check your default browser settings.", QString(url));
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/TOPPViewBase.cpp | .cpp | 98,184 | 2,638 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg, Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h>
#include <OpenMS/CONCEPT/EnumHelpers.h>
#include <OpenMS/CONCEPT/RAIICleanup.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/FORMAT/HANDLERS/IndexedMzMLHandler.h>
#include <OpenMS/IONMOBILITY/IMDataConverter.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/OnDiscMSExperiment.h>
#include <OpenMS/METADATA/Precursor.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/FileWatcher.h>
#include <OpenMS/VISUAL/AxisWidget.h>
#include <OpenMS/VISUAL/DataSelectionTabs.h>
#include <OpenMS/VISUAL/DIALOGS/SpectrumAlignmentDialog.h>
#include <OpenMS/VISUAL/DIALOGS/TheoreticalSpectrumGenerationDialog.h>
#include <OpenMS/VISUAL/DIALOGS/ToolsDialog.h>
#include <OpenMS/VISUAL/DIALOGS/TOPPViewOpenDialog.h>
#include <OpenMS/VISUAL/DIALOGS/TOPPViewPrefDialog.h>
#include <OpenMS/VISUAL/INTERFACES/IPeptideIds.h>
#include <OpenMS/VISUAL/LayerListView.h>
#include <OpenMS/VISUAL/LayerDataChrom.h>
#include <OpenMS/VISUAL/LayerDataConsensus.h>
#include <OpenMS/VISUAL/LayerDataFeature.h>
#include <OpenMS/VISUAL/LayerDataPeak.h>
#include <OpenMS/VISUAL/LogWindow.h>
#include <OpenMS/VISUAL/MetaDataBrowser.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/Plot1DCanvas.h>
#include <OpenMS/VISUAL/Plot1DWidget.h>
#include <OpenMS/VISUAL/Plot2DCanvas.h>
#include <OpenMS/VISUAL/Plot2DWidget.h>
#include <OpenMS/VISUAL/Plot3DCanvas.h>
#include <OpenMS/VISUAL/Plot3DOpenGLCanvas.h>
#include <OpenMS/VISUAL/Plot3DWidget.h>
#include <OpenMS/VISUAL/SpectraIDViewTab.h>
#include <OpenMS/VISUAL/SpectraTreeTab.h>
#include <OpenMS/VISUAL/VISITORS/LayerStoreData.h>
// Qt
#include <QCloseEvent>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QUrl>
#include <QGuiApplication>
#include <QtWidgets/QDockWidget>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QSplashScreen>
#include <QtWidgets/QToolButton>
#include <cmath>
#include <utility>
#include <boost/make_shared.hpp>
using namespace std;
namespace OpenMS
{
using namespace Internal;
using namespace Math;
const std::string user_section = "preferences:user:";
/// supported types which can be opened with File-->Open
const FileTypeList supported_types({ FileTypes::MZML, FileTypes::MZXML, FileTypes::MZDATA, FileTypes::SQMASS,
FileTypes::FEATUREXML, FileTypes::CONSENSUSXML, FileTypes::IDXML,
FileTypes::DTA, FileTypes::DTA2D, FileTypes::MGF, FileTypes::MS2,
FileTypes::MSP, FileTypes::BZ2, FileTypes::GZ });
TOPPViewBase::TOPPViewBase(TOOL_SCAN scan_mode, VERBOSITY verbosity, QWidget* parent) :
QMainWindow(parent),
DefaultParamHandler("TOPPViewBase"),
scan_mode_(scan_mode),
verbosity_(verbosity),
ws_(this),
tab_bar_(this),
recent_files_(),
menu_(this, &ws_, &recent_files_)
{
setWindowTitle("TOPPView");
setWindowIcon(QIcon(":/TOPPView.png"));
setMinimumSize(400, 400); // prevents errors caused by too small width, height values
setAcceptDrops(true); // enable drag-and-drop
// get geometry of first screen
QRect screen_geometry = QGuiApplication::primaryScreen()->geometry();
// center main window
setGeometry(
(int)(0.1 * screen_geometry.width()),
(int)(0.1 * screen_geometry.height()),
(int)(0.8 * screen_geometry.width()),
(int)(0.8 * screen_geometry.height())
);
//################## Main Window #################
// Create main workspace using a QVBoxLayout ordering the items vertically
// (the tab bar and the main workspace). Uses a dummy central widget (to be able to
// have a layout), then adds vertically the tab bar and workspace.
QWidget* dummy_cw = new QWidget(this);
setCentralWidget(dummy_cw);
QVBoxLayout* box_layout = new QVBoxLayout(dummy_cw);
// create empty tab bar and workspace which will hold the main visualization widgets (e.g. spectrawidgets...)
tab_bar_.setWhatsThis("Tab bar<BR><BR>Close tabs through the context menu or by double-clicking them.<BR>The tab bar accepts drag-and-drop from the layer bar.");
tab_bar_.addTab("dummy", 4710);
tab_bar_.setMinimumSize(tab_bar_.sizeHint());
tab_bar_.removeId(4710);
connect(&tab_bar_, &EnhancedTabBar::currentIdChanged, this, &TOPPViewBase::showWindow);
connect(&tab_bar_, &EnhancedTabBar::closeRequested, this, &TOPPViewBase::closeByTab);
connect(&tab_bar_, &EnhancedTabBar::dropOnWidget, [this](const QMimeData* data, QWidget* source){ copyLayer(data, source); });
connect(&tab_bar_, &EnhancedTabBar::dropOnTab, this, &TOPPViewBase::copyLayer);
box_layout->addWidget(&tab_bar_);
// Trigger updates only when the active subWindow changes and update it
connect(&ws_, &EnhancedWorkspace::subWindowActivated, [this](QMdiSubWindow* window) {
if (window && lastActiveSubwindow_ != window) /* 0 upon terminate */ updateBarsAndMenus();
lastActiveSubwindow_ = window;
});
connect(&ws_, &EnhancedWorkspace::dropReceived, this, &TOPPViewBase::copyLayer);
box_layout->addWidget(&ws_);
//################## STATUS #################
// create status bar
message_label_ = new QLabel(statusBar());
statusBar()->addWidget(message_label_, 1);
x_label_ = new QLabel("RT: 12345678", statusBar());
x_label_->setMinimumSize(x_label_->sizeHint());
x_label_->setText("");
statusBar()->addPermanentWidget(x_label_, 0);
y_label_ = new QLabel("m/z: 123456780912", statusBar());
y_label_->setMinimumSize(y_label_->sizeHint());
y_label_->setText("");
statusBar()->addPermanentWidget(y_label_, 0);
//################## TOOLBARS #################
// create toolbars and connect signals
QToolButton* b;
//--Basic tool bar for all views--
tool_bar_ = addToolBar("Basic tool bar");
tool_bar_->setObjectName("tool_bar");
// intensity modes
intensity_button_group_ = new QButtonGroup(tool_bar_);
intensity_button_group_->setExclusive(true);
b = new QToolButton(tool_bar_);
b->setIcon(QIcon(":/lin.png"));
b->setToolTip("Intensity: Normal");
b->setShortcut(Qt::Key_N);
b->setCheckable(true);
b->setWhatsThis("Intensity: Normal<BR><BR>Intensity is displayed unmodified.<BR>(Hotkey: N)");
intensity_button_group_->addButton(b, PlotCanvas::IM_NONE);
tool_bar_->addWidget(b);
b = new QToolButton(tool_bar_);
b->setIcon(QIcon(":/percentage.png"));
b->setToolTip("Intensity: Percentage");
b->setShortcut(Qt::Key_P);
b->setCheckable(true);
b->setWhatsThis("Intensity: Percentage<BR><BR>Intensity is displayed as a percentage of the layer"
" maximum intensity. If only one layer is displayed this mode behaves like the"
" normal mode. If more than one layer is displayed intensities are aligned."
"<BR>(Hotkey: P)");
intensity_button_group_->addButton(b, PlotCanvas::IM_PERCENTAGE);
tool_bar_->addWidget(b);
b = new QToolButton(tool_bar_);
b->setIcon(QIcon(":/snap.png"));
b->setToolTip("Intensity: Snap to maximum displayed intensity");
b->setShortcut(Qt::Key_S);
b->setCheckable(true);
b->setWhatsThis("Intensity: Snap to maximum displayed intensity<BR><BR> In this mode the"
" color gradient is adapted to the maximum currently displayed intensity."
"<BR>(Hotkey: S)");
intensity_button_group_->addButton(b, PlotCanvas::IM_SNAP);
tool_bar_->addWidget(b);
b = new QToolButton(tool_bar_);
b->setIcon(QIcon(":/log.png"));
b->setToolTip("Intensity: Use log scaling for colors");
b->setCheckable(true);
b->setWhatsThis("Intensity: Logarithmic scaling of intensities for color calculation");
intensity_button_group_->addButton(b, PlotCanvas::IM_LOG);
tool_bar_->addWidget(b);
connect(intensity_button_group_, &QButtonGroup::idClicked, this, &TOPPViewBase::setIntensityMode);
tool_bar_->addSeparator();
// common buttons
QAction* reset_zoom_button = tool_bar_->addAction(QIcon(":/reset_zoom.png"), "Reset Zoom", this, &TOPPViewBase::resetZoom);
reset_zoom_button->setWhatsThis("Reset zoom: Zooms out as far as possible and resets the zoom history.<BR>(Hotkey: Backspace)");
tool_bar_->show();
//--1D toolbar--
tool_bar_1d_ = addToolBar("1D tool bar");
tool_bar_1d_->setObjectName("1d_tool_bar");
// draw modes 1D
draw_group_1d_ = new QButtonGroup(tool_bar_1d_);
draw_group_1d_->setExclusive(true);
b = new QToolButton(tool_bar_1d_);
b->setIcon(QIcon(":/peaks.png"));
b->setToolTip("Peak mode");
b->setShortcut(Qt::Key_I);
b->setCheckable(true);
b->setWhatsThis("1D Draw mode: Peaks<BR><BR>Peaks are displayed as sticks.");
draw_group_1d_->addButton(b, Plot1DCanvas::DM_PEAKS);
tool_bar_1d_->addWidget(b);
b = new QToolButton(tool_bar_1d_);
b->setIcon(QIcon(":/lines.png"));
b->setToolTip("Raw data mode");
b->setShortcut(Qt::Key_R);
b->setCheckable(true);
b->setWhatsThis("1D Draw mode: Raw data<BR><BR>Peaks are displayed as a continuous line.");
draw_group_1d_->addButton(b, Plot1DCanvas::DM_CONNECTEDLINES);
tool_bar_1d_->addWidget(b);
connect(draw_group_1d_, &QButtonGroup::idClicked, this, &TOPPViewBase::setDrawMode1D);
tool_bar_->addSeparator();
//--2D peak toolbar--
tool_bar_2d_peak_ = addToolBar("2D peak tool bar");
tool_bar_2d_peak_->setObjectName("2d_tool_bar");
dm_precursors_2d_ = tool_bar_2d_peak_->addAction(QIcon(":/precursors.png"), "Show fragment scan precursors");
dm_precursors_2d_->setCheckable(true);
dm_precursors_2d_->setWhatsThis("2D peak draw mode: Precursors<BR><BR>fragment scan precursor peaks are marked.<BR>(Hotkey: 1)");
dm_precursors_2d_->setShortcut(Qt::Key_1);
connect(dm_precursors_2d_, &QAction::toggled, this, &TOPPViewBase::changeLayerFlag);
projections_2d_ = tool_bar_2d_peak_->addAction(QIcon(":/projections.png"), "Show Projections", this, &TOPPViewBase::toggleProjections);
projections_2d_->setCheckable(true);
projections_2d_->setWhatsThis("Projections: Shows projections of peak data along RT and MZ axis.<BR>(Hotkey: 2)");
projections_2d_->setShortcut(Qt::Key_2);
//--2D feature toolbar--
tool_bar_2d_feat_ = addToolBar("2D feature tool bar");
tool_bar_2d_feat_->setObjectName("2d_feature_tool_bar");
dm_hull_2d_ = tool_bar_2d_feat_->addAction(QIcon(":/convexhull.png"), "Show feature convex hull");
dm_hull_2d_->setCheckable(true);
dm_hull_2d_->setWhatsThis("2D feature draw mode: Convex hull<BR><BR>The convex hull of the feature is displayed.<BR>(Hotkey: 5)");
dm_hull_2d_->setShortcut(Qt::Key_5);
connect(dm_hull_2d_, &QAction::toggled, this, &TOPPViewBase::changeLayerFlag);
dm_hulls_2d_ = tool_bar_2d_feat_->addAction(QIcon(":/convexhulls.png"), "Show feature convex hulls");
dm_hulls_2d_->setCheckable(true);
dm_hulls_2d_->setWhatsThis("2D feature draw mode: Convex hulls<BR><BR>The convex hulls of the feature are displayed: One for each mass trace.<BR>(Hotkey: 6)");
dm_hulls_2d_->setShortcut(Qt::Key_6);
connect(dm_hulls_2d_, &QAction::toggled, this, &TOPPViewBase::changeLayerFlag);
// feature labels:
dm_label_2d_ = new QToolButton(tool_bar_2d_feat_);
dm_label_2d_->setPopupMode(QToolButton::MenuButtonPopup);
QAction* action2 = new QAction(QIcon(":/labels.png"), "Show feature annotation", dm_label_2d_);
action2->setCheckable(true);
action2->setWhatsThis("2D feature draw mode: Labels<BR><BR>Display different kinds of annotation next to features.<BR>(Hotkey: 7)");
action2->setShortcut(Qt::Key_7);
dm_label_2d_->setDefaultAction(action2);
tool_bar_2d_feat_->addWidget(dm_label_2d_);
connect(dm_label_2d_, &QToolButton::triggered, this, &TOPPViewBase::changeLabel);
// button menu
group_label_2d_ = new QActionGroup(dm_label_2d_);
QMenu* menu = new QMenu(dm_label_2d_);
for (Size i = 0; i < LayerDataBase::SIZE_OF_LABEL_TYPE; ++i)
{
QAction* temp = group_label_2d_->addAction(
QString(LayerDataBase::NamesOfLabelType[i].c_str()));
temp->setCheckable(true);
if (i == 0) temp->setChecked(true);
menu->addAction(temp);
}
dm_label_2d_->setMenu(menu);
// unassigned peptide identifications:
dm_unassigned_2d_ = new QToolButton(tool_bar_2d_feat_);
dm_unassigned_2d_->setPopupMode(QToolButton::MenuButtonPopup);
QAction* action_unassigned = new QAction(QIcon(":/unassigned.png"), "Show unassigned peptide identifications", dm_unassigned_2d_);
action_unassigned->setCheckable(true);
action_unassigned->setWhatsThis("2D feature draw mode: Unassigned peptide identifications<BR><BR>Show unassigned peptide identifications by precursor m/z or by peptide mass.<BR>(Hotkey: 8)");
action_unassigned->setShortcut(Qt::Key_8);
dm_unassigned_2d_->setDefaultAction(action_unassigned);
tool_bar_2d_feat_->addWidget(dm_unassigned_2d_);
connect(dm_unassigned_2d_, &QToolButton::triggered, this, &TOPPViewBase::changeUnassigned);
// button menu
group_unassigned_2d_ = new QActionGroup(dm_unassigned_2d_);
menu = new QMenu(dm_unassigned_2d_);
StringList options = {"Don't show", "Show by precursor m/z", "Show by peptide mass", "Show label meta data"};
for (const String& opt : options)
{
QAction* temp = group_unassigned_2d_->addAction(opt.toQString());
temp->setCheckable(true);
if (opt == options.front()) temp->setChecked(true);
menu->addAction(temp);
}
dm_unassigned_2d_->setMenu(menu);
//--2D consensus toolbar--
tool_bar_2d_cons_ = addToolBar("2D peak tool bar");
tool_bar_2d_cons_->setObjectName("2d_peak_tool_bar");
dm_elements_2d_ = tool_bar_2d_cons_->addAction(QIcon(":/elements.png"), "Show consensus feature element positions");
dm_elements_2d_->setCheckable(true);
dm_elements_2d_->setWhatsThis("2D consensus feature draw mode: Elements<BR><BR>The individual elements that make up the consensus feature are drawn.<BR>(Hotkey: 9)");
dm_elements_2d_->setShortcut(Qt::Key_9);
connect(dm_elements_2d_, &QAction::toggled, this, &TOPPViewBase::changeLayerFlag);
//--2D identifications toolbar--
tool_bar_2d_ident_ = addToolBar("2D identifications tool bar");
tool_bar_2d_ident_->setObjectName("2d_ident_tool_bar");
dm_ident_2d_ = tool_bar_2d_ident_->addAction(QIcon(":/peptidemz.png"), "Use theoretical peptide mass for m/z positions (default: precursor mass)");
dm_ident_2d_->setCheckable(true);
dm_ident_2d_->setWhatsThis("2D peptide identification draw mode: m/z source<BR><BR>Toggle between precursor mass (default) and theoretical peptide mass as source for the m/z positions of peptide identifications.<BR>(Hotkey: 5)");
dm_ident_2d_->setShortcut(Qt::Key_5);
connect(dm_ident_2d_, &QAction::toggled, this, &TOPPViewBase::changeLayerFlag);
//################## Dock widgets #################
// This creates the dock widgets:
// Layers, Views, Filters, and the Log dock widget on the bottom (by default hidden).
// layer dock widget
layer_dock_widget_ = new QDockWidget("Layers", this);
layer_dock_widget_->setObjectName("layer_dock_widget");
addDockWidget(Qt::RightDockWidgetArea, layer_dock_widget_);
layers_view_ = new LayerListView(layer_dock_widget_);
connect(layers_view_, &LayerListView::layerDataChanged, this, &TOPPViewBase::updateBarsAndMenus);
layer_dock_widget_->setWidget(layers_view_);
menu_.addWindowToggle(layer_dock_widget_->toggleViewAction());
// Views dock widget
views_dockwidget_ = new QDockWidget("Views", this);
views_dockwidget_->setObjectName("views_dock_widget");
addDockWidget(Qt::BottomDockWidgetArea, views_dockwidget_);
selection_view_ = new DataSelectionTabs(views_dockwidget_, this);
views_dockwidget_->setWidget(selection_view_);
// add hide/show option to dock widget
menu_.addWindowToggle(views_dockwidget_->toggleViewAction());
// filter dock widget
filter_dock_widget_ = new QDockWidget("Data filters", this);
filter_dock_widget_->setObjectName("filter_dock_widget");
addDockWidget(Qt::BottomDockWidgetArea, filter_dock_widget_);
filter_list_ = new FilterList(filter_dock_widget_);
connect(filter_list_, &FilterList::filterChanged, [&](const DataFilters& filter) {
getActiveCanvas()->setFilters(filter);
});
filter_dock_widget_->setWidget(filter_list_);
menu_.addWindowToggle(filter_dock_widget_->toggleViewAction());
// log window
QDockWidget* log_bar = new QDockWidget("Log", this);
log_bar->setObjectName("log_bar");
addDockWidget(Qt::BottomDockWidgetArea, log_bar);
log_ = new LogWindow(log_bar);
log_bar->setWidget(log_);
menu_.addWindowToggle(log_bar->toggleViewAction());
// tabify dock widgets so they don't fill up the whole space
QMainWindow::tabifyDockWidget(filter_dock_widget_, log_bar);
QMainWindow::tabifyDockWidget(log_bar, views_dockwidget_);
//################## DEFAULTS #################
initializeDefaultParameters_();
// store defaults in param_
defaultsToParam_();
// load param file
loadPreferences();
// set current path
current_path_ = param_.getValue(user_section + "default_path").toString();
// set plugin search path, create it if it does not already exist
if (verbosity_ == VERBOSITY::VERBOSE)
{
tool_scanner_.setVerbose(1);
}
String plugin_path = String(param_.getValue(user_section + "plugins_path").toString());
tool_scanner_.setPluginPath(plugin_path, true);
// update the menu
updateMenu();
connect(&recent_files_, &RecentFilesMenu::recentFileClicked, this, &TOPPViewBase::openFile);
// restore window positions
QSettings settings("OpenMS", "TOPPView");
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("windowState").toByteArray());
//######################### File System Watcher ###########################################
watcher_ = new FileWatcher(this);
connect(watcher_, &FileWatcher::fileChanged, this, &TOPPViewBase::fileChanged_);
}
void TOPPViewBase::initializeDefaultParameters_()
{
// FIXME: these parameters are declared again in TOPPViewPrefDialog, incl. their allowed values
// There should be one place to do this. E.g. generate the GUI automatically from a Param (or simply use ParamEditor for the whole thing)
// all parameters in preferences:user: can be edited by the user in the preferences dialog
// general
defaults_.setValue(user_section + "default_map_view", "2d", "Default visualization mode for maps.");
defaults_.setValidStrings(user_section + "default_map_view", {"2d","3d"});
defaults_.setValue(user_section + "default_path", ".", "Default path for loading and storing files.");
defaults_.setValue(user_section + "default_path_current", "true", "If the current path is preferred over the default path.");
defaults_.setValidStrings(user_section + "default_path_current", {"true","false"});
defaults_.setValue(user_section + "plugins_path", File::getUserDirectory() + "OpenMS_Plugins", "Default path for loading Plugins");
defaults_.setValue(user_section + "intensity_cutoff", "off", "Low intensity cutoff for maps.");
defaults_.setValidStrings(user_section + "intensity_cutoff", {"on","off"});
defaults_.setValue(user_section + "on_file_change", "ask", "What action to take, when a data file changes. Do nothing, update automatically or ask the user.");
defaults_.setValidStrings(user_section + "on_file_change", {"none","ask","update automatically"});
defaults_.setValue(user_section + "use_cached_ms2", "false", "If possible, only load MS1 spectra into memory and keep MS2 spectra on disk (using indexed mzML).");
defaults_.setValidStrings(user_section + "use_cached_ms2", {"true","false"});
defaults_.setValue(user_section + "use_cached_ms1", "false", "If possible, do not load MS1 spectra into memory spectra into memory and keep MS2 spectra on disk (using indexed mzML).");
defaults_.setValidStrings(user_section + "use_cached_ms1", {"true","false"});
// FIXME: getCanvasParameters() depends on the exact naming of the param sections below!
// 1d view
defaults_.insert(user_section + "1d:", Plot1DCanvas(Param()).getDefaults());
defaults_.setSectionDescription(user_section + "1d", "Settings for single spectrum view.");
// 2d view
defaults_.insert(user_section + "2d:", Plot2DCanvas(Param()).getDefaults());
defaults_.setSectionDescription(user_section + "2d", "Settings for 2D map view.");
// 3d view
defaults_.insert(user_section + "3d:", Plot3DCanvas(Param()).getDefaults());
defaults_.setSectionDescription(user_section + "3d", "Settings for 3D map view.");
// identification view
defaults_.insert(user_section + "idview:", SpectraIDViewTab(Param()).getDefaults());
defaults_.setSectionDescription(user_section + "idview", "Settings for identification view.");
// non-editable parameters
// not in Dialog (yet?)
defaults_.setValue("preferences:topp_cleanup", "true", "If the temporary files for calling of TOPP tools should be removed after the call.");
defaults_.setValidStrings("preferences:topp_cleanup", {"true", "false"});
defaults_.setValue("preferences:version", "none", "OpenMS version, used to check if the TOPPView.ini is up-to-date");
subsections_.emplace_back("preferences:RecentFiles");
// store defaults in param_
defaultsToParam_();
}
void TOPPViewBase::closeEvent(QCloseEvent* event)
{
ws_.closeAllSubWindows();
QSettings settings("OpenMS", "TOPPView");
settings.setValue("geometry", saveGeometry());
settings.setValue("windowState", saveState());
event->accept();
}
void TOPPViewBase::preferencesDialog()
{
Internal::TOPPViewPrefDialog dlg(this);
dlg.setParam(param_.copy(user_section, true));
// --------------------------------------------------------------------
// Execute dialog and update parameter object with user modified values
if (dlg.exec())
{
param_.remove(user_section);
param_.insert(user_section, dlg.getParam());
savePreferences();
}
}
TOPPViewBase::LOAD_RESULT TOPPViewBase::addDataFile(const String& filename, bool show_options, bool add_to_recent, String caption, UInt window_id, Size spectrum_id)
{
String abs_filename = File::absolutePath(filename);
// check if the file exists
if (!File::exists(abs_filename))
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Open file error", String("The file '") + abs_filename + "' does not exist!");
return LOAD_RESULT::FILE_NOT_FOUND;
}
// determine file type
FileHandler fh;
FileTypes::Type file_type = fh.getType(abs_filename);
if (file_type == FileTypes::UNKNOWN)
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Open file error", String("Could not determine file type of '") + abs_filename + "'!");
return LOAD_RESULT::FILETYPE_UNKNOWN;
}
// abort if file type unsupported
if (!supported_types.contains(file_type))
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Open file error", String("The type '") + FileTypes::typeToName(file_type) + "' is not supported in TOPPView!");
return LOAD_RESULT::FILETYPE_UNSUPPORTED;
}
// try to load data and determine if it's 1D or 2D data
// create shared pointer to main data types
FeatureMapType* feature_map = new FeatureMapType();
FeatureMapSharedPtrType feature_map_sptr(feature_map);
ExperimentSharedPtrType peak_map_sptr(new ExperimentType());
ConsensusMapType* consensus_map = new ConsensusMapType();
ConsensusMapSharedPtrType consensus_map_sptr(consensus_map);
PeptideIdentificationList peptides;
// not needed in data but for auto annotation
vector<ProteinIdentification> proteins;
String annotate_path;
LayerDataBase::DataType data_type(LayerDataBase::DT_UNKNOWN);
ODExperimentSharedPtrType on_disc_peaks(new OnDiscMSExperiment);
// lock the GUI - no interaction possible when loading...
GUIHelpers::GUILock glock(this);
bool cache_ms2_on_disc = (param_.getValue(user_section + "use_cached_ms2") == "true");
bool cache_ms1_on_disc = (param_.getValue(user_section + "use_cached_ms1") == "true");
try
{
if (file_type == FileTypes::FEATUREXML)
{
FileHandler().loadFeatures(abs_filename, *feature_map, {FileTypes::FEATUREXML});
data_type = LayerDataBase::DT_FEATURE;
}
else if (file_type == FileTypes::CONSENSUSXML)
{
FileHandler().loadConsensusFeatures(abs_filename, *consensus_map, {FileTypes::CONSENSUSXML});
data_type = LayerDataBase::DT_CONSENSUS;
}
else if (file_type == FileTypes::IDXML || file_type == FileTypes::MZIDENTML)
{
FileHandler().loadIdentifications(abs_filename, proteins, peptides, {FileTypes::IDXML, FileTypes::MZIDENTML});
if (peptides.empty())
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No peptide identifications found");
}
// check if RT (and sequence) information is present:
PeptideIdentificationList peptides_with_rt;
for (PeptideIdentificationList::const_iterator it =
peptides.begin(); it != peptides.end(); ++it)
{
if (!it->getHits().empty() && it->hasRT())
{
peptides_with_rt.push_back(*it);
}
}
Size diff = peptides.size() - peptides_with_rt.size();
if (diff)
{
String msg = String(diff) + " peptide identification(s) without"
" sequence and/or retention time information were removed.\n" +
peptides_with_rt.size() + " peptide identification(s) remaining.";
log_->appendNewHeader(LogWindow::LogState::WARNING, "While loading file:", msg);
}
if (peptides_with_rt.empty())
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No peptide identifications with sufficient information remaining.");
}
peptides.swap(peptides_with_rt);
if (!proteins.empty())
{
StringList paths;
proteins[0].getPrimaryMSRunPath(paths);
for (const String &path : paths)
{
if (File::exists(path) && fh.getType(path) == FileTypes::MZML)
{
annotate_path = path;
}
}
// annotation could not be found in file reference
if (annotate_path.empty())
{
// try to find file with same path & name but with mzML extension
auto target = fh.swapExtension(abs_filename, FileTypes::Type::MZML);
if (File::exists(target))
{
annotate_path = target;
}
}
if (!annotate_path.empty())
{
// open dialog for annotation on load
QMessageBox msg_box;
auto spectra_file_name = File::basename(annotate_path);
msg_box.setText("Spectra data for identification data was found.");
msg_box.setInformativeText(String("Annotate spectra in " + spectra_file_name + "?").toQString());
msg_box.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msg_box.setDefaultButton(QMessageBox::Yes);
auto ret = msg_box.exec();
if (ret == QMessageBox::No)
{ // no annotation performed
annotate_path = "";
}
}
}
data_type = LayerDataBase::DT_IDENT;
}
else
{
bool parsing_success = false;
if (file_type == FileTypes::MZML)
{
// Load index only and check success (is it indexed?)
Internal::IndexedMzMLHandler indexed_mzml_file;
indexed_mzml_file.openFile(filename);
if ( indexed_mzml_file.getParsingSuccess() && cache_ms2_on_disc)
{
// If it has an index, now load index and meta data
on_disc_peaks->openFile(filename, false);
OPENMS_LOG_INFO << "INFO: will use cached MS2 spectra" << std::endl;
if (cache_ms1_on_disc)
{
OPENMS_LOG_INFO << "log INFO: will use cached MS1 spectra" << std::endl;
}
parsing_success = true;
// Caching strategy: peak_map_sptr will contain a MSSpectrum entry
// for each actual spectrum on disk. However, initially these will
// only be populated by the meta data (all data except the actual
// raw data) which will allow us to read out RT, MS level etc.
//
// In a second step (see below), we populate some of these maps
// with actual spectra including raw data (allowing us to only
// populate MS1 spectra with actual data).
peak_map_sptr.get()->getMSExperiment() = *on_disc_peaks->getMetaData();
for (Size k = 0; k < indexed_mzml_file.getNrSpectra() && !cache_ms1_on_disc; k++)
{
if ( peak_map_sptr->getMSExperiment().getSpectrum(k).getMSLevel() == 1)
{
peak_map_sptr->getMSExperiment().getSpectrum(k) = on_disc_peaks->getSpectrum(k);
}
}
for (Size k = 0; k < indexed_mzml_file.getNrChromatograms() && !cache_ms2_on_disc; k++)
{
peak_map_sptr->getMSExperiment().getChromatogram(k) = on_disc_peaks->getChromatogram(k);
}
// Load at least one spectrum into memory (TOPPView assumes that at least one spectrum is in memory)
if (cache_ms1_on_disc
&& peak_map_sptr->getMSExperiment().getNrSpectra() > 0)
{
peak_map_sptr->getMSExperiment().getSpectrum(0) = on_disc_peaks->getSpectrum(0);
}
}
}
// Load all data into memory if e.g. other file type than mzML
if (!parsing_success)
{
fh.loadExperiment(abs_filename, peak_map_sptr->getMSExperiment(), {file_type}, ProgressLogger::GUI, true, true);
}
OPENMS_LOG_INFO << "INFO: done loading all " << std::endl;
// a mzML file may contain both, chromatogram and peak data
// -> this is handled in PlotCanvas::addPeakLayer FIXME: No it's not!
if (peak_map_sptr->getMSExperiment().getNrSpectra() > 0
&& peak_map_sptr->getMSExperiment().getNrChromatograms() > 0)
{
OPENMS_LOG_WARN << "Your input data contains chromatograms and spectra, falling back to display spectra only." << std::endl;
data_type = LayerDataBase::DT_PEAK;
}
else if (peak_map_sptr->getMSExperiment().getNrChromatograms() > 0)
{
data_type = LayerDataBase::DT_CHROMATOGRAM;
}
else if (peak_map_sptr->getMSExperiment().getNrSpectra() > 0)
{
data_type = LayerDataBase::DT_PEAK;
}
else
{
throw Exception::FileEmpty(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "MzML filed doesn't have either spectra or chromatograms.");
}
}
}
catch (Exception::BaseException& e)
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Error while loading file:", e.what());
return LOAD_RESULT::LOAD_ERROR;
}
// sort for m/z and update ranges of newly loaded data
peak_map_sptr->getMSExperiment().sortSpectra(true);
peak_map_sptr->getMSExperiment().updateRanges();
// try to add the data
if (caption == "")
{
caption = FileHandler::stripExtension(File::basename(abs_filename));
}
else
{
abs_filename = "";
}
glock.unlock();
if (!annotate_path.empty())
{ // this opens a new window with raw data + annotation; we want the actual idXML data on top
auto load_res = addDataFile(annotate_path, false, false);
if (load_res == LOAD_RESULT::OK)
{
auto l = getCurrentLayer();
if (l)
{
bool success = l->annotate(peptides, proteins);
if (success)
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "Done", "Annotation finished. Open identification view to see results!");
}
else
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "Error", "Annotation failed.");
}
}
window_id = getActivePlotWidget()->getWindowId(); // add ids on top of raw data
}
}
addData(feature_map_sptr,
consensus_map_sptr,
peptides,
peak_map_sptr,
on_disc_peaks,
data_type,
false, // show as 1D
show_options,
true, // as new window
abs_filename,
caption,
window_id,
spectrum_id);
// add to recent file
if (add_to_recent)
{
addRecentFile_(filename);
}
// watch file contents for changes
watcher_->addFile(abs_filename);
return LOAD_RESULT::OK;
}
void TOPPViewBase::addData(const FeatureMapSharedPtrType& feature_map,
const ConsensusMapSharedPtrType& consensus_map,
PeptideIdentificationList& peptides,
const ExperimentSharedPtrType& peak_map,
const ODExperimentSharedPtrType& on_disc_peak_map,
LayerDataBase::DataType data_type,
bool show_as_1d,
bool show_options,
bool as_new_window,
const String& filename,
const String& caption,
UInt window_id,
Size spectrum_id)
{
// initialize flags with defaults from the parameters
bool maps_as_2d = (param_.getValue(user_section + "default_map_view") == "2d");
bool maps_as_1d = false;
bool use_intensity_cutoff = (param_.getValue(user_section + "intensity_cutoff") == "on");
bool is_dia_data = false;
// feature, consensus feature and identifications can be merged
bool mergeable = ((data_type == LayerDataBase::DT_FEATURE) ||
(data_type == LayerDataBase::DT_CONSENSUS) ||
(data_type == LayerDataBase::DT_IDENT));
// only one peak spectrum? disable 2D as default
if (peak_map->getMSExperiment().size() == 1) { maps_as_2d = false; }
// set the window where (new layer) data could be opened in
// get EnhancedTabBarWidget with given id
EnhancedTabBarWidgetInterface* tab_bar_target = ws_.getWidget(window_id);
// cast to PlotWidget
PlotWidget* target_window = dynamic_cast<PlotWidget*>(tab_bar_target);
if (tab_bar_target == nullptr)
{
target_window = getActivePlotWidget();
}
else
{
as_new_window = false;
}
// create dialog no matter if it is shown or not. It is used to determine the flags.
TOPPViewOpenDialog dialog(caption, as_new_window, maps_as_2d, use_intensity_cutoff, this);
// disable opening in new window when there is no active window or feature/ID data is to be opened, but the current window is a 3D window
if (target_window == nullptr || (mergeable && dynamic_cast<Plot3DWidget*>(target_window)))
{
dialog.disableLocation(true);
}
// for feature/consensus/identification maps
if (mergeable)
{
dialog.disableDimension(true); // disable 1d/2d/3d option
dialog.disableCutoff(false);
// enable merge layers if a feature layer is opened and there are already features layers to merge it to
if (target_window)
{
PlotCanvas* open_canvas = target_window->canvas();
std::map<Size, String> layers;
for (Size i = 0; i < open_canvas->getLayerCount(); ++i)
{
if (data_type == open_canvas->getLayer(i).type)
{
layers[i] = open_canvas->getLayer(i).getName();
}
}
dialog.setMergeLayers(layers); // adds a dropdown
}
}
// show options if requested
if (show_options && !dialog.exec())
{
return;
}
as_new_window = dialog.openAsNewWindow();
maps_as_2d = dialog.viewMapAs2D();
maps_as_1d = dialog.viewMapAs1D();
if (show_as_1d)
{
maps_as_1d = true;
maps_as_2d = false;
}
use_intensity_cutoff = dialog.isCutoffEnabled();
is_dia_data = dialog.isDataDIA();
Int merge_layer = dialog.getMergeLayer();
// If we are dealing with DIA data, store this directly in the peak map
// (ensures we will keep track of this flag from now on).
if (is_dia_data)
{
peak_map->getMSExperiment().setMetaValue("is_dia_data", "true");
}
// determine the window to open the data in
if (as_new_window) // new window
{
if (maps_as_1d) // 2d in 1d window
{
target_window = new Plot1DWidget(getCanvasParameters(1), DIM::Y, &ws_);
}
else if (maps_as_2d || mergeable) // 2d or features/IDs
{
target_window = new Plot2DWidget(getCanvasParameters(2), &ws_);
}
else // 3d
{
target_window = new Plot3DWidget(getCanvasParameters(3), &ws_);
}
}
if (merge_layer == -1) // add new layer to the window
{
if (data_type == LayerDataBase::DT_FEATURE) // features
{
if (!target_window->canvas()->addLayer(feature_map, filename, caption))
{
return;
}
}
else if (data_type == LayerDataBase::DT_CONSENSUS) // consensus features
{
if (! target_window->canvas()->addLayer(consensus_map, filename, caption))
return;
}
else if (data_type == LayerDataBase::DT_IDENT)
{
if (! target_window->canvas()->addLayer(peptides, filename, caption))
return;
}
else // peaks or chrom
{
if (data_type == LayerDataBase::DT_PEAK && ! target_window->canvas()->addPeakLayer(peak_map, on_disc_peak_map, filename, caption, use_intensity_cutoff))
{
return;
}
if (data_type == LayerDataBase::DT_CHROMATOGRAM &&
!target_window->canvas()->addChromLayer(peak_map, on_disc_peak_map, filename, caption))
{
return;
}
Plot1DWidget* open_1d_window = dynamic_cast<Plot1DWidget*>(target_window);
if (open_1d_window)
{
open_1d_window->canvas()->activateSpectrum(spectrum_id);
}
}
}
else // merge feature/ID data into feature layer
{
Plot2DCanvas* canvas = qobject_cast<Plot2DCanvas*>(target_window->canvas());
if (data_type == LayerDataBase::DT_CONSENSUS)
{
canvas->mergeIntoLayer(merge_layer, consensus_map);
}
else if (data_type == LayerDataBase::DT_FEATURE)
{
canvas->mergeIntoLayer(merge_layer, feature_map);
}
else if (data_type == LayerDataBase::DT_IDENT)
{
canvas->mergeIntoLayer(merge_layer, peptides);
}
// combine layer names
canvas->setLayerName(merge_layer, canvas->getLayerName(merge_layer) + " + " + caption);
}
if (as_new_window)
{
showPlotWidgetInWindow(target_window);
}
// enable spectra view tab (not required anymore since selection_view_.update() will decide automatically)
//selection_view_->show(DataSelectionTabs::SPECTRA_IDX);
}
void TOPPViewBase::addRecentFile_(const String& filename)
{
recent_files_.add(filename);
}
void TOPPViewBase::openFile(const String& filename)
{
addDataFile(filename, true, true);
}
void TOPPViewBase::closeByTab(int id)
{
QWidget* w = dynamic_cast<QWidget*>(ws_.getWidget(id));
if (w)
{
QMdiSubWindow* parent = qobject_cast<QMdiSubWindow*>(w->parentWidget());
if (parent->close()) updateBarsAndMenus();
}
}
void TOPPViewBase::showWindow(int id)
{
auto* sw = dynamic_cast<PlotWidget*>(ws_.getWidget(id));
if (!sw) return;
sw->setFocus(); // triggers layerActivated...
}
void TOPPViewBase::closeTab()
{
ws_.activeSubWindow()->close();
}
void TOPPViewBase::editMetadata()
{
PlotCanvas* canvas = getActiveCanvas();
// warn if hidden layer => wrong layer selected...
if (!canvas->getCurrentLayer().visible)
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "The current layer is not visible", "Have you selected the right layer for this action?");
}
// show editable meta data dialog
canvas->showMetaData(true);
}
void TOPPViewBase::layerStatistics() const
{
getActivePlotWidget()->showStatistics();
}
void TOPPViewBase::showStatusMessage(const string& msg, OpenMS::UInt time)
{
if (time == 0)
{
message_label_->setText(msg.c_str());
statusBar()->update();
}
else
{
statusBar()->showMessage(msg.c_str(), time);
}
}
void TOPPViewBase::showCursorStatus(const String& x, const String& y)
{
message_label_->setText("");
x_label_->setText(x.toQString());
y_label_->setText(y.toQString());
statusBar()->update();
}
void TOPPViewBase::resetZoom() const
{
PlotWidget* w = getActivePlotWidget();
if (w != nullptr)
{
w->canvas()->resetZoom();
}
}
void TOPPViewBase::setIntensityMode(int index)
{
PlotWidget* w = getActivePlotWidget();
if (w)
{
intensity_button_group_->button(index)->setChecked(true);
w->setIntensityMode((OpenMS::PlotCanvas::IntensityModes)index);
}
}
void TOPPViewBase::setDrawMode1D(int index) const
{
Plot1DWidget* w = getActive1DWidget();
if (w)
{
w->canvas()->setDrawMode((OpenMS::Plot1DCanvas::DrawModes)index);
}
}
void TOPPViewBase::changeLabel(QAction* action)
{
bool set = false;
// label type is selected
for (Size i = 0; i < LayerDataBase::SIZE_OF_LABEL_TYPE; ++i)
{
if (action->text().toStdString() == LayerDataBase::NamesOfLabelType[i])
{
getActive2DWidget()->canvas()->setLabel(LayerDataBase::LabelType(i));
set = true;
}
}
// button is simply pressed
if (!set)
{
if (getActive2DWidget()->canvas()->getCurrentLayer().label == LayerDataBase::L_NONE)
{
getActive2DWidget()->canvas()->setLabel(LayerDataBase::L_INDEX);
dm_label_2d_->menu()->actions()[1]->setChecked(true);
}
else
{
getActive2DWidget()->canvas()->setLabel(LayerDataBase::L_NONE);
dm_label_2d_->menu()->actions()[0]->setChecked(true);
}
}
updateToolBar();
}
void TOPPViewBase::changeUnassigned(QAction* action)
{
// mass reference is selected
if (action->text().toStdString() == "Don't show")
{
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::F_UNASSIGNED, false);
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::I_PEPTIDEMZ, false);
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::I_LABELS, false);
}
else if (action->text().toStdString() == "Show by precursor m/z")
{
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::F_UNASSIGNED, true);
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::I_PEPTIDEMZ, false);
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::I_LABELS, false);
}
else if (action->text().toStdString() == "Show by peptide mass")
{
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::F_UNASSIGNED, true);
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::I_PEPTIDEMZ, true);
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::I_LABELS, false);
}
else if (action->text().toStdString() == "Show label meta data")
{
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::F_UNASSIGNED, true);
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::I_PEPTIDEMZ, false);
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::I_LABELS, true);
}
else // button is simply pressed
{
bool previous = getActive2DWidget()->canvas()->getLayerFlag(LayerDataBase::F_UNASSIGNED);
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::F_UNASSIGNED,
!previous);
if (previous) // now: don't show
{
dm_unassigned_2d_->menu()->actions()[0]->setChecked(true);
}
else // now: show by precursor
{
dm_unassigned_2d_->menu()->actions()[1]->setChecked(true);
}
getActive2DWidget()->canvas()->setLayerFlag(LayerDataBase::I_PEPTIDEMZ, false);
}
updateToolBar();
}
void TOPPViewBase::changeLayerFlag(bool on)
{
QAction* action = qobject_cast<QAction*>(sender());
if (Plot2DWidget* win = getActive2DWidget())
{
// peaks
if (action == dm_precursors_2d_)
{
win->canvas()->setLayerFlag(LayerDataBase::P_PRECURSORS, on);
}
// features
else if (action == dm_hulls_2d_)
{
win->canvas()->setLayerFlag(LayerDataBase::F_HULLS, on);
}
else if (action == dm_hull_2d_)
{
win->canvas()->setLayerFlag(LayerDataBase::F_HULL, on);
}
// consensus features
else if (action == dm_elements_2d_)
{
win->canvas()->setLayerFlag(LayerDataBase::C_ELEMENTS, on);
}
// identifications
else if (action == dm_ident_2d_)
{
win->canvas()->setLayerFlag(LayerDataBase::I_PEPTIDEMZ, on);
}
}
}
void TOPPViewBase::updateBarsAndMenus()
{
// Update filter bar, spectrum bar and layer bar
layerActivated();
updateMenu();
}
void TOPPViewBase::updateToolBar()
{
tool_bar_1d_->hide();
tool_bar_2d_peak_->hide();
tool_bar_2d_feat_->hide();
tool_bar_2d_cons_->hide();
tool_bar_2d_ident_->hide();
PlotWidget* w = getActivePlotWidget();
if (w)
{
// set intensity mode
if (intensity_button_group_->button(w->canvas()->getIntensityMode()))
{
intensity_button_group_->button(w->canvas()->getIntensityMode())->setChecked(true);
}
else
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, OPENMS_PRETTY_FUNCTION, "Button for intensity mode does not exist");
}
}
// 1D
Plot1DWidget* w1 = getActive1DWidget();
if (w1)
{
// draw mode
draw_group_1d_->button(w1->canvas()->getDrawMode())->setChecked(true);
// show/hide toolbars and buttons
tool_bar_1d_->show();
}
// 2D
Plot2DWidget* w2 = getActive2DWidget();
if (w2)
{
// check if there is a layer before requesting data from it
if (w2->canvas()->getLayerCount() > 0)
{
// peak draw modes
if (w2->canvas()->getCurrentLayer().type == LayerDataBase::DT_PEAK)
{
dm_precursors_2d_->setChecked(w2->canvas()->getLayerFlag(LayerDataBase::P_PRECURSORS));
tool_bar_2d_peak_->show();
}
// feature draw modes
else if (w2->canvas()->getCurrentLayer().type == LayerDataBase::DT_FEATURE)
{
dm_hulls_2d_->setChecked(w2->canvas()->getLayerFlag(LayerDataBase::F_HULLS));
dm_hull_2d_->setChecked(w2->canvas()->getLayerFlag(LayerDataBase::F_HULL));
dm_unassigned_2d_->setChecked(w2->canvas()->getLayerFlag(LayerDataBase::F_UNASSIGNED));
dm_label_2d_->setChecked(w2->canvas()->getCurrentLayer().label != LayerDataBase::L_NONE);
tool_bar_2d_feat_->show();
}
// consensus feature draw modes
else if (w2->canvas()->getCurrentLayer().type == LayerDataBase::DT_CONSENSUS)
{
dm_elements_2d_->setChecked(w2->canvas()->getLayerFlag(LayerDataBase::C_ELEMENTS));
tool_bar_2d_cons_->show();
}
else if (w2->canvas()->getCurrentLayer().type == LayerDataBase::DT_IDENT)
{
dm_ident_2d_->setChecked(w2->canvas()->getLayerFlag(LayerDataBase::I_PEPTIDEMZ));
tool_bar_2d_ident_->show();
}
}
}
// 3D
Plot3DWidget* w3 = getActive3DWidget();
if (w3)
{
// show no toolbars and buttons
}
}
void TOPPViewBase::updateLayerBar()
{
layers_view_->update(getActivePlotWidget());
}
void TOPPViewBase::updateViewBar()
{
selection_view_->callUpdateEntries();
}
void TOPPViewBase::updateMenu()
{
FS_TV fs;
LayerDataBase::DataType layer_type = LayerDataBase::DT_UNKNOWN;
// is there a canvas?
if (getActiveCanvas() != nullptr)
{
fs |= TV_STATUS::HAS_CANVAS;
// is there a layer?
if (getActiveCanvas()->getLayerCount() != 0)
{
fs |= TV_STATUS::HAS_LAYER;
layer_type = getCurrentLayer()->type;
}
}
// is this a 1D view
if (getActive1DWidget() != nullptr) fs |= TV_STATUS::IS_1D_VIEW;
// are we in 1D mirror mode
if (getActive1DWidget() && getActive1DWidget()->canvas()->mirrorModeActive()) fs |= TV_STATUS::HAS_MIRROR_MODE;
// is there a TOPP tool running
if (topp_.process == nullptr) fs |= TV_STATUS::TOPP_IDLE;
menu_.update(fs, layer_type);
}
void TOPPViewBase::updateFilterBar()
{
PlotCanvas* canvas = getActiveCanvas();
if (canvas == nullptr)
return;
if (canvas->getLayerCount() == 0)
return;
filter_list_->set(getActiveCanvas()->getCurrentLayer().filters);
}
void TOPPViewBase::layerFilterVisibilityChange(bool on) const
{
if (getActiveCanvas())
{
getActiveCanvas()->changeLayerFilterState(getActiveCanvas()->getCurrentLayerIndex(), on);
}
}
void TOPPViewBase::layerActivated()
{
updateLayerBar();
updateToolBar();
updateViewBar();
updateCurrentPath();
updateFilterBar();
}
void TOPPViewBase::linkZoom()
{
zoom_together_ = !zoom_together_;
}
void TOPPViewBase::zoomOtherWindows() const
{
if (!zoom_together_) return;
QList<QMdiSubWindow *> windows = ws_.subWindowList();
if (!windows.count()) return;
PlotWidget* w = getActivePlotWidget();
auto new_visible_area = w->canvas()->getVisibleArea();
// only zoom if other window is also (not) a chromatogram
bool sender_is_chrom = w->canvas()->getCurrentLayer().type == LayerDataBase::DT_CHROMATOGRAM;
// go through all windows, adjust the visible area where necessary
for (int i = 0; i < int(windows.count()); ++i)
{
PlotWidget* specwidg = qobject_cast<PlotWidget*>(windows.at(i)->widget());
if (!specwidg) continue;
bool is_chrom = specwidg->canvas()->getCurrentLayer().type == LayerDataBase::DT_CHROMATOGRAM;
if (is_chrom != sender_is_chrom) continue;
// not the same dimensionality (e.g. Plot1DCanvas vs. 2DCanvas)
if (w->canvas()->getName() != specwidg->canvas()->getName()) continue;
specwidg->canvas()->setVisibleArea(new_visible_area);
}
}
void TOPPViewBase::layerDeactivated()
{
}
void TOPPViewBase::showPlotWidgetInWindow(PlotWidget* sw)
{
ws_.addSubWindow(sw);
connect(sw->canvas(), &PlotCanvas::preferencesChange, this, &TOPPViewBase::updateLayerBar);
connect(sw->canvas(), &PlotCanvas::layerActivated, this, &TOPPViewBase::layerActivated);
connect(sw->canvas(), &PlotCanvas::layerModficationChange, this, &TOPPViewBase::updateLayerBar);
connect(sw->canvas(), &PlotCanvas::layerZoomChanged, this, &TOPPViewBase::zoomOtherWindows);
connect(sw, &PlotWidget::sendStatusMessage, this, &TOPPViewBase::showStatusMessage);
connect(sw, &PlotWidget::sendCursorStatus, this, &TOPPViewBase::showCursorStatus);
connect(sw, &PlotWidget::dropReceived, this, &TOPPViewBase::copyLayer);
auto base_name = sw->canvas()->getCurrentLayer().getDecoratedName();
// 1D spectrum specific signals
Plot1DWidget* sw1 = qobject_cast<Plot1DWidget*>(sw);
if (sw1)
{
connect(sw1, &Plot1DWidget::showCurrentPeaksAs2D, this, &TOPPViewBase::showCurrentPeaksAs2D);
connect(sw1, &Plot1DWidget::showCurrentPeaksAs3D, this, &TOPPViewBase::showCurrentPeaksAs3D);
connect(sw1, &Plot1DWidget::showCurrentPeaksAsIonMobility, this, &TOPPViewBase::showCurrentPeaksAsIonMobility);
connect(sw1, &Plot1DWidget::showCurrentPeaksAsDIA, this, &TOPPViewBase::showCurrentPeaksAsDIA);
base_name += " (1D)";
}
// 2D spectrum specific signals
Plot2DWidget* sw2 = qobject_cast<Plot2DWidget*>(sw);
if (sw2)
{
connect(sw2->getProjectionOntoX(), &Plot1DWidget::sendCursorStatus, this, &TOPPViewBase::showCursorStatus);
connect(sw2->getProjectionOntoY(), &Plot1DWidget::sendCursorStatus, this, &TOPPViewBase::showCursorStatus);
connect(sw2, &Plot2DWidget::showSpectrumAsNew1D, selection_view_, &DataSelectionTabs::showSpectrumAsNew1D);
connect(sw2, &Plot2DWidget::showCurrentPeaksAsIonMobility, this, &TOPPViewBase::showCurrentPeaksAsIonMobility);
connect(sw2, &Plot2DWidget::showCurrentPeaksAs3D, this, &TOPPViewBase::showCurrentPeaksAs3D);
base_name += " (2D)";
}
// 3D spectrum specific signals
Plot3DWidget* sw3 = qobject_cast<Plot3DWidget*>(sw);
if (sw3)
{
connect(sw3, &Plot3DWidget::showCurrentPeaksAs2D,this, &TOPPViewBase::showCurrentPeaksAs2D);
base_name += " (3D)";
}
sw->setWindowTitle(base_name.toQString());
sw->addToTabBar(&tab_bar_, base_name, true);
// show first window maximized (only visible windows are in the list)
if (ws_.subWindowList().count() == 1)
{
sw->showMaximized();
}
else
{
sw->show();
}
showWindow(sw->getWindowId());
}
void TOPPViewBase::showGoToDialog() const
{
PlotWidget* w = getActivePlotWidget();
if (w)
{
w->showGoToDialog();
}
}
EnhancedWorkspace* TOPPViewBase::getWorkspace()
{
return &ws_;
}
PlotWidget* TOPPViewBase::getActivePlotWidget() const
{
// If the MDI window that holds all the subwindows for layers/spectra
// is out-of-focus (e.g. because the table below was clicked and you moved out and into TOPPView),
// currentSubWindow returns nullptr (i.e. no window is ACTIVE). In this case we get the one that is active
// in the tabs (which SHOULD in theory be in-sync; due to a bug the way subwindow->tab does not work).
// TODO check if we can reactivate automatically (e.g. double-check when TOPPView reacquires focus)
if (!ws_.currentSubWindow())
{
// TODO think about using lastActivatedSubwindow_
const int id = tab_bar_.currentIndex();
if (id < 0 || id >= ws_.subWindowList().size()) return nullptr;
return qobject_cast<PlotWidget*>(ws_.subWindowList()[id]->widget());
}
return qobject_cast<PlotWidget*>(ws_.currentSubWindow()->widget());
}
PlotCanvas* TOPPViewBase::getActiveCanvas() const
{
PlotWidget* sw = getActivePlotWidget();
if (sw == nullptr)
{
return nullptr;
}
return sw->canvas();
}
Plot1DWidget* TOPPViewBase::getActive1DWidget() const
{
return qobject_cast<Plot1DWidget*>(getActivePlotWidget());
}
Plot2DWidget* TOPPViewBase::getActive2DWidget() const
{
return qobject_cast<Plot2DWidget*>(getActivePlotWidget());
}
Plot3DWidget* TOPPViewBase::getActive3DWidget() const
{
return qobject_cast<Plot3DWidget*>(getActivePlotWidget());
}
void TOPPViewBase::loadPreferences(String filename)
{
// compose default ini file path
String default_ini_file = String(QDir::homePath()) + "/.TOPPView.ini";
bool tool_params_added = false;
if (filename == "") { filename = default_ini_file; }
// load preferences, if file exists
if (File::exists(filename))
{
bool error = false;
Param tmp;
try // the file might be corrupt
{
ParamXMLFile().load(filename, tmp);
}
catch (...)
{
error = true;
}
// apply preferences if they are of the current TOPPView version
if (!error && tmp.exists("preferences:version") &&
tmp.getValue("preferences:version").toString() == VersionInfo::getVersion())
{
try
{
setParameters(tmp.copy("preferences:"));
}
catch (Exception::InvalidParameter& /*e*/)
{
error = true;
}
}
else
{
error = true;
}
// set parameters to defaults when something is fishy with the parameters file
if (error)
{
// reset parameters (they will be stored again when TOPPView quits)
setParameters(Param());
cerr << "The TOPPView preferences files '" << filename << "' was ignored. It is no longer compatible with this TOPPView version and will be replaced." << endl;
}
else
{
// Load tool/util params
if (scan_mode_ != TOOL_SCAN::FORCE_SCAN && tmp.hasSection("tool_params:"))
{
param_.insert("tool_params:", tmp.copy("tool_params:", true));
tool_params_added = true;
}
// If the saved plugin path does not exist
if (!tool_scanner_.setPluginPath(param_.getValue(user_section + "plugins_path").toString()))
{
// reset it to the default
param_.setValue(user_section + "plugins_path", File::getUserDirectory() + "OpenMS_Plugins");
}
}
}
else if (filename != default_ini_file)
{
cerr << "Unable to load INI File: '" << filename << "'" << endl;
}
// Scan for tools if scan_mode is set to FORCE_SCAN or if the tool/util params could not be added for whatever reason
if (!tool_params_added && scan_mode_ != TOOL_SCAN::SKIP_SCAN)
{
tool_scanner_.loadToolParams();
}
param_.setValue("PreferencesFile", filename);
// set the recent files
recent_files_.setFromParam(param_.copy("preferences:RecentFiles"));
}
void TOPPViewBase::savePreferences()
{
// replace recent files
param_.removeAll("preferences:RecentFiles");
param_.insert("preferences:RecentFiles:", recent_files_.getAsParam());
// set version
param_.setValue("preferences:version", VersionInfo::getVersion());
// Make sure TOPP tool/util params have been inserted
if (!param_.hasSection("tool_params:") && scan_mode_ != TOOL_SCAN::SKIP_SCAN)
{
tool_scanner_.waitForToolParams();
param_.insert("tool_params:", tool_scanner_.getToolParams());
}
// check if the plugin path exists
if (!tool_scanner_.setPluginPath(param_.getValue(user_section + "plugins_path").toString()))
{
// reset if it does not
param_.setValue(user_section + "plugins_path", tool_scanner_.getPluginPath());
}
// save only the subsection that begins with "preferences:" and all tool params ("tool_params:")
try
{
Param p;
p.insert("preferences:", param_.copy("preferences:", true));
p.insert("tool_params:", param_.copy("tool_params:", true));
ParamXMLFile().store(string(param_.getValue("PreferencesFile")), p);
}
catch (Exception::UnableToCreateFile& /*e*/)
{
cerr << "Unable to create INI File: '" << string(param_.getValue("PreferencesFile")) << "'" << endl;
}
}
QStringList TOPPViewBase::chooseFilesDialog_(const String& path_overwrite)
{
QString open_path = current_path_.toQString();
if (!path_overwrite.empty())
{
open_path = path_overwrite.toQString();
}
// we use the QT file dialog instead of using QFileDialog::Names(...)
// On Windows and Mac OS X, this static function will use the native file dialog and not a QFileDialog,
// which prevents us from doing GUI testing on it.
QFileDialog dialog(this, "Open file(s)", open_path, supported_types.toFileDialogFilter(FilterLayout::BOTH, true).toQString());
dialog.setFileMode(QFileDialog::ExistingFiles);
if (dialog.exec())
{
return dialog.selectedFiles();
}
return {};
}
void TOPPViewBase::openFilesByDialog(const String& dir)
{
for (const QString& filename : chooseFilesDialog_(dir))
{
addDataFile(filename, true, true);
}
}
void TOPPViewBase::showTOPPDialog()
{
QAction* action = qobject_cast<QAction*>(sender());
showTOPPDialog_(action->data().toBool());
}
void TOPPViewBase::showTOPPDialog_(bool visible_area_only)
{
// warn if hidden layer => wrong layer selected...
const LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
if (!layer.visible)
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "The current layer is not visible", "Have you selected the right layer for this action?");
}
// create and store unique file name prefix for files
topp_.file_name = File::getTempDirectory() + "/TOPPView_" + File::getUniqueName();
// Figure out the correct extension to give the temp file TODO start using OMS and cachedmzml
if (!File::writable(topp_.file_name + "_ini"))
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Cannot create temporary file", String("Cannot write to '") + topp_.file_name + "'_ini!");
return;
}
if (!param_.hasSection("tool_params:"))
{
tool_scanner_.waitForToolParams();
param_.insert("tool_params:", tool_scanner_.getToolParams());
}
ToolsDialog tools_dialog(this, param_,
topp_.file_name + "_ini", current_path_, layer.type,
layer.getName(), &tool_scanner_);
if (tools_dialog.exec() == QDialog::Accepted)
{
// Store tool name, input parameter and output parameter
topp_.tool = tools_dialog.getTool();
topp_.in = tools_dialog.getInput();
topp_.out = tools_dialog.getOutput();
topp_.visible_area_only = visible_area_only;
// Build the input file name
String file_extension;
switch (layer.type)
{
case LayerDataBase::DataType::DT_PEAK:
file_extension = FileTypes::typeToName(FileTypes::MZML);
break;
case LayerDataBase::DataType::DT_CHROMATOGRAM:
file_extension = FileTypes::typeToName(FileTypes::MZML);
break;
case LayerDataBase::DataType::DT_FEATURE:
file_extension = FileTypes::typeToName(FileTypes::FEATUREXML);
break;
case LayerDataBase::DataType::DT_CONSENSUS:
file_extension = FileTypes::typeToName(FileTypes::CONSENSUSXML);
break;
case LayerDataBase::DataType::DT_IDENT:
file_extension = FileTypes::typeToName(FileTypes::IDXML);
break;
default:
file_extension = FileTypes::typeToName(FileTypes::UNKNOWN);
}
topp_.file_name_in = topp_.file_name + "_in." + file_extension;
// Get the output file extension
topp_.file_name_out = topp_.file_name + "_out." + tools_dialog.getExtension();
// run the tool
runTOPPTool_();
}
}
void TOPPViewBase::rerunTOPPTool()
{
if (topp_.tool.empty())
{
QMessageBox::warning(this, "Error", "No TOPP tool was run before. Please run a tool first.");
return;
}
// warn if hidden layer => wrong layer selected...
const LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
if (!layer.visible)
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "The current layer is not visible", "Have you selected the right layer for this action?");
}
// run the tool
runTOPPTool_();
}
void TOPPViewBase::runTOPPTool_()
{
const LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
// delete old input and output file
File::remove(topp_.file_name_in);
File::remove(topp_.file_name_out);
// test if files are writable
if (!File::writable(topp_.file_name_in))
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Cannot create temporary file", String("Cannot write to '") + topp_.file_name_in + "'!");
return;
}
if (!File::writable(topp_.file_name_out))
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Cannot create temporary file", String("Cannot write to '") + topp_.file_name_out + "'!");
return;
}
// store data
topp_.layer_name = layer.getName();
topp_.window_id = getActivePlotWidget()->getWindowId();
if (auto layer_1d = dynamic_cast<const LayerData1DBase*>(&layer))
{
topp_.spectrum_id = layer_1d->getCurrentIndex();
}
{ // just a local scope
auto visitor_data = topp_.visible_area_only
? layer.storeVisibleData(getActiveCanvas()->getVisibleArea().getAreaUnit(), layer.filters)
: layer.storeFullData();
visitor_data->saveToFile(topp_.file_name_in, ProgressLogger::GUI);
}
// compose argument list
QStringList args;
args << "-ini"
<< (topp_.file_name + "_ini").toQString()
<< QString("-%1").arg(topp_.in.toQString())
<< topp_.file_name_in.toQString()
<< "-no_progress";
if (topp_.out != "")
{
args << QString("-%1").arg(topp_.out.toQString())
<< topp_.file_name_out.toQString();
}
// start log and show it
log_->appendNewHeader(LogWindow::LogState::NOTICE, QString("Starting '%1'").arg(topp_.tool.toQString()), "");
// initialize process
topp_.process = new QProcess();
topp_.process->setProcessChannelMode(QProcess::MergedChannels);
// connect slots
connect(topp_.process, &QProcess::readyReadStandardOutput, this, &TOPPViewBase::updateProcessLog);
connect(topp_.process, CONNECTCAST(QProcess, finished, (int, QProcess::ExitStatus)), this, &TOPPViewBase::finishTOPPToolExecution);
QString tool_executable = String(tool_scanner_.findPluginExecutable(topp_.tool)).toQString();
if (tool_executable.isEmpty())
{
try
{
// find correct location of TOPP tool
tool_executable = File::findSiblingTOPPExecutable(topp_.tool).toQString();
}
catch (Exception::FileNotFound & /*ex*/)
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Could not locate executable!",
QString("Finding executable of TOPP tool '%1' failed. Please check your TOPP/OpenMS installation. Workaround: Add the bin/ directory to your PATH").arg(
topp_.tool.toQString()));
return;
}
}
// update menu entries according to new state
updateMenu();
// start the actual process
topp_.timer.restart();
topp_.process->start(tool_executable, args);
topp_.process->waitForStarted();
if (topp_.process->error() == QProcess::FailedToStart)
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, QString("Failed to execute '%1'").arg(topp_.tool.toQString()), QString("Execution of TOPP tool '%1' failed with error: %2").arg(topp_.tool.toQString(), topp_.process->errorString()));
// ensure that all tool output is emitted into log screen
updateProcessLog();
// re-enable Apply TOPP tool menus
delete topp_.process;
topp_.process = nullptr;
updateMenu();
}
}
void TOPPViewBase::finishTOPPToolExecution(int, QProcess::ExitStatus)
{
log_->addNewline();
if (topp_.process->exitStatus() == QProcess::CrashExit)
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, QString("Execution of '%1' not successful!").arg(topp_.tool.toQString()),
QString("The tool crashed during execution. If you want to debug this crash, check the input files in '%1'"
" or enable 'debug' mode in the TOPP ini file.").arg(File::getTempDirectory().toQString()));
}
else if (topp_.process->exitCode() != 0) // NormalExit with non-zero exit code
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, QString("Execution of '%1' not successful!").arg(topp_.tool.toQString()),
QString("The tool ended with a non-zero exit code of '%1'. ").arg(topp_.process->exitCode()) +
QString("If you want to debug this, check the input files in '%1' or"
" enable 'debug' mode in the TOPP ini file.").arg(File::getTempDirectory().toQString()));
}
else if (!topp_.out.empty())
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, QString("'%1' finished successfully").arg(topp_.tool.toQString()),
QString("Execution time: %1 ms").arg(topp_.timer.elapsed()));
if (!File::readable(topp_.file_name_out))
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Cannot read TOPP output", String("Cannot read '") + topp_.file_name_out + "'!");
}
else
{
auto l = getCurrentLayer();
if (l)
{
auto annotator = LayerAnnotatorBase::getAnnotatorWhichSupports(topp_.file_name + "_in");
if (annotator.get() == nullptr)
{ // no suitable annotator? open new layer/window
addDataFile(topp_.file_name + "_out", true, false, topp_.layer_name + " (" + topp_.tool + ")", topp_.window_id, topp_.spectrum_id);
}
else
{ // we have an annotator ... let's annotate the current layer
annotator->annotateWithFilename(*l, *log_, topp_.out + "_out"); // ID tabs are automatically enabled
}
}
}
}
// clean up
delete topp_.process;
topp_.process = nullptr;
updateMenu();
// clean up temporary files
if (param_.getValue("preferences:topp_cleanup") == "true")
{
File::remove(topp_.file_name + "_ini");
File::remove(topp_.file_name_in);
File::remove(topp_.file_name_out);
}
}
const LayerDataBase* TOPPViewBase::getCurrentLayer() const
{
PlotCanvas* canvas = getActiveCanvas();
if (canvas == nullptr)
{
return nullptr;
}
return &(canvas->getCurrentLayer());
}
LayerDataBase* TOPPViewBase::getCurrentLayer()
{
PlotCanvas* canvas = getActiveCanvas();
if (canvas == nullptr)
{
return nullptr;
}
return &(canvas->getCurrentLayer());
}
void TOPPViewBase::toggleProjections()
{
Plot2DWidget* w = getActive2DWidget();
if (w)
{
// update minimum size before
if (!w->projectionsVisible())
{
setMinimumSize(700, 700);
}
else
{
setMinimumSize(400, 400);
}
w->toggleProjections();
}
}
void TOPPViewBase::annotateWithAMS()
{ // this should only be callable if current layer's type is of type DT_PEAK
LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
LayerAnnotatorAMS annotator(this);
assert(log_ != nullptr);
if (!annotator.annotateWithFileDialog(layer, *log_, current_path_))
{
return;
}
}
void TOPPViewBase::annotateWithID()
{ // this should only be callable if current layer's type is one of DT_PEAK, DT_FEATURE, DT_CONSENSUS
LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
LayerAnnotatorPeptideID annotator(this);
assert(log_ != nullptr);
if (!annotator.annotateWithFileDialog(layer, *log_, current_path_))
{
return;
}
selection_view_->setCurrentIndex(DataSelectionTabs::IDENT_IDX); //switch to ID view
selection_view_->currentTabChanged(DataSelectionTabs::IDENT_IDX);
}
void TOPPViewBase::annotateWithOSW()
{ // this should only be callable if current layer's type is of type DT_CHROMATOGRAM
LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
LayerAnnotatorOSW annotator(this);
assert(log_ != nullptr);
if (!annotator.annotateWithFileDialog(layer, *log_, current_path_))
{
return;
}
selection_view_->setCurrentIndex(DataSelectionTabs::DIAOSW_IDX); // switch to DIA view
selection_view_->currentTabChanged(DataSelectionTabs::DIAOSW_IDX);
}
void TOPPViewBase::showSpectrumGenerationDialog()
{
// TheoreticalSpectrumGenerationDialog spec_gen_dialog;
if (spec_gen_dialog_.exec())
{
// spectrum is generated in the dialog, so just receive it here
PeakSpectrum spectrum = spec_gen_dialog_.getSpectrum();
ExperimentSharedPtrType new_exp_sptr = std::make_shared<AnnotatedMSRun>();
new_exp_sptr->getMSExperiment().addSpectrum(spectrum);
new_exp_sptr->getMSExperiment().updateRanges();
FeatureMapSharedPtrType f_dummy(new FeatureMapType());
ConsensusMapSharedPtrType c_dummy(new ConsensusMapType());
ODExperimentSharedPtrType od_dummy(new OnDiscMSExperiment());
PeptideIdentificationList p_dummy;
// open as 1D (since its a single spectrum); 3D view does not support MS2 (yet)
addData(f_dummy, c_dummy, p_dummy, new_exp_sptr, od_dummy, LayerDataBase::DT_PEAK, true, false, true, "", spec_gen_dialog_.getSequence() + " (theoretical)");
// ensure spectrum is drawn as sticks
draw_group_1d_->button(Plot1DCanvas::DM_PEAKS)->setChecked(true);
setDrawMode1D(Plot1DCanvas::DM_PEAKS);
}
}
void TOPPViewBase::showSpectrumAlignmentDialog()
{
Plot1DWidget* active_1d_window = getActive1DWidget();
if (!active_1d_window || !active_1d_window->canvas()->mirrorModeActive())
{
return;
}
Plot1DCanvas* cc = active_1d_window->canvas();
SpectrumAlignmentDialog spec_align_dialog(active_1d_window);
if (spec_align_dialog.exec())
{
Int layer_index_1 = spec_align_dialog.get1stLayerIndex();
Int layer_index_2 = spec_align_dialog.get2ndLayerIndex();
// two layers must be selected:
if (layer_index_1 < 0 || layer_index_2 < 0)
{
QMessageBox::information(this, "Layer selection invalid", "You must select two layers for an alignment.");
return;
}
Param param;
double tolerance = spec_align_dialog.getTolerance();
param.setValue("tolerance", tolerance, "Defines the absolute (in Da) or relative (in ppm) mass tolerance");
String unit_is_ppm = spec_align_dialog.isPPM() ? "true" : "false";
param.setValue("is_relative_tolerance", unit_is_ppm, "If true, the mass tolerance is interpreted as ppm value otherwise in Dalton");
active_1d_window->performAlignment((UInt)layer_index_1, (UInt)layer_index_2, param);
double al_score = cc->getAlignmentScore();
Size al_size = cc->getAlignmentSize();
QMessageBox::information(this, "Alignment performed", QString("Aligned %1 pairs of peaks (Score: %2).").arg(al_size).arg(al_score));
}
}
void TOPPViewBase::showCurrentPeaksAs2D()
{
LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
auto* lp = dynamic_cast<LayerDataPeak*>(&layer);
if (!lp) return;
ExperimentSharedPtrType exp_sptr = lp->getPeakDataMuteable();
ODExperimentSharedPtrType od_exp_sptr = lp->getOnDiscPeakData();
// open new 2D widget
Plot2DWidget* w = new Plot2DWidget(getCanvasParameters(2), &ws_);
// add data
if (!w->canvas()->addPeakLayer(exp_sptr, od_exp_sptr, layer.filename))
{
return;
}
showPlotWidgetInWindow(w);
updateMenu();
}
void TOPPViewBase::showCurrentPeaksAsIonMobility(const MSSpectrum& spec)
{
const LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
ExperimentSharedPtrType exp = std::make_shared<AnnotatedMSRun>();
exp.get()->getMSExperiment() = std::move(IMDataConverter::reshapeIMFrameToMany(spec));
// hack, but currently not avoidable, because 2D widget does not support IM natively yet...
// for (auto& spec : exp->getSpectra()) spec.setRT(spec.getDriftTime());
// open new 2D widget
Plot2DWidget* w = new Plot2DWidget(getCanvasParameters(2), &ws_);
// map to IM + MZ
w->setMapper(DimMapper<2>({IMTypes::fromIMUnit(exp->getMSExperiment().getSpectra()[0].getDriftTimeUnit()), DIM_UNIT::MZ}));
// add data
if (!w->canvas()->addPeakLayer(exp, PlotCanvas::ODExperimentSharedPtrType(new OnDiscMSExperiment()), layer.filename + " (IM Frame)"))
{
return;
}
showPlotWidgetInWindow(w);
updateMenu();
}
void TOPPViewBase::showCurrentPeaksAsDIA(const Precursor& pc, const MSExperiment& exp)
{
const LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
auto* lp = dynamic_cast<const LayerDataPeak*>(&layer);
if (!lp || !lp->isDIAData())
{
std::cout << "Layer does not contain DIA / SWATH-MS data" << std::endl;
return;
}
// Add spectra into a MSExperiment, sort and prepare it for display
ExperimentSharedPtrType tmpe = std::make_shared<AnnotatedMSRun>();
// Collect all MS2 spectra with the same precursor as the current spectrum
// (they are in the same SWATH window)
String caption_add = "";
double lower = pc.getMZ() - pc.getIsolationWindowLowerOffset();
double upper = pc.getMZ() + pc.getIsolationWindowUpperOffset();
Size k = 0;
for (const auto& spec : exp)
{
if (spec.getMSLevel() == 2 && !spec.getPrecursors().empty() )
{
if (fabs(spec.getPrecursors()[0].getMZ() - pc.getMZ()) < 1e-4)
{
// Get the spectrum in question (from memory or disk) and add to
// the newly created MSExperiment
if (spec.size() > 0)
{
// Get data from memory - copy data and tell TOPPView that this
// is MS1 data so that it will be displayed properly in 2D and 3D
// view
MSSpectrum t = spec;
t.setMSLevel(1);
tmpe->getMSExperiment().addSpectrum(t);
}
else if (lp->getOnDiscPeakData()->getNrSpectra() > k)
{
// Get data from disk - copy data and tell TOPPView that this is
// MS1 data so that it will be displayed properly in 2D and 3D
// view
MSSpectrum t = lp->getOnDiscPeakData()->getSpectrum(k);
t.setMSLevel(1);
tmpe->getMSExperiment().addSpectrum(t);
}
}
}
k++;
}
caption_add = "(DIA window " + String(lower) + " - " + String(upper) + ")";
tmpe->getMSExperiment().sortSpectra();
tmpe->getMSExperiment().updateRanges();
// open new 2D widget
Plot2DWidget* w = new Plot2DWidget(getCanvasParameters(2), &ws_);
// add data
if (!w->canvas()->addPeakLayer(tmpe, PlotCanvas::ODExperimentSharedPtrType(new OnDiscMSExperiment()), layer.filename))
{
return;
}
String caption = layer.getName();
caption += caption_add;
w->canvas()->setLayerName(w->canvas()->getCurrentLayerIndex(), caption);
showPlotWidgetInWindow(w);
updateMenu();
}
void TOPPViewBase::showCurrentPeaksAs3D()
{
// we first pick the layer with 3D support which is closest (or ideally identical) to the currently active layer
// we might find that there is no compatible layer though...
// if some day more than one type of data is supported, we need to adapt the code below accordingly
const int BIGINDEX = 10000; // some large number which is never reached
const int target_layer = (int) getActiveCanvas()->getCurrentLayerIndex();
int best_candidate = BIGINDEX;
for (int i = 0; i < (int) getActiveCanvas()->getLayerCount(); ++i)
{
if ((LayerDataBase::DT_PEAK == getActiveCanvas()->getLayer(i).type) && // supported type
(std::abs(i - target_layer) < std::abs(best_candidate - target_layer))) // & smallest distance to active layer
{
best_candidate = i;
}
}
if (best_candidate == BIGINDEX)
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "No compatible layer",
"No layer found which is supported by the 3D view.");
return;
}
if (best_candidate != target_layer)
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "Auto-selected compatible layer",
"The currently active layer cannot be viewed in 3D view. The closest layer which is supported by the 3D view was selected!");
}
LayerDataBase& layer = const_cast<LayerDataBase&>(getActiveCanvas()->getLayer(best_candidate));
auto* lp = dynamic_cast<LayerDataPeak*>(&layer);
if (!lp)
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "Wrong layer type", "Something went wrong during layer selection. Please report this problem with a description of your current layers!");
return;
}
// open new 3D widget
Plot3DWidget* w = new Plot3DWidget(getCanvasParameters(3), &ws_);
ExperimentSharedPtrType exp_sptr = lp->getPeakDataMuteable();
if (lp->isIonMobilityData())
{
// Determine ion mobility unit (default is milliseconds)
String unit = "ms";
if (exp_sptr->getMSExperiment().metaValueExists("ion_mobility_unit"))
{
unit = exp_sptr->getMSExperiment().getMetaValue("ion_mobility_unit");
}
String label = "Ion Mobility [" + unit + "]";
w->canvas()->openglwidget()->setYLabel(label.c_str());
}
if (!w->canvas()->addPeakLayer(exp_sptr, PlotCanvas::ODExperimentSharedPtrType(new OnDiscMSExperiment()), layer.filename))
{
return;
}
if (getActive1DWidget()) // switch from 1D to 3D
{
// TODO:
//- doesn't make sense for fragment scan
//- build new Area with mz range equal to 1D visible range
//- rt range either overall MS1 data range or some convenient window
}
else if (getActive2DWidget()) // switch from 2D to 3D
{
w->canvas()->setVisibleArea(getActiveCanvas()->getVisibleArea());
}
showPlotWidgetInWindow(w);
// set intensity mode (after spectrum has been added!)
setIntensityMode(PlotCanvas::IM_SNAP);
updateMenu();
}
void TOPPViewBase::updateProcessLog()
{
log_->appendText(topp_.process->readAllStandardOutput());
}
Param TOPPViewBase::getCanvasParameters(UInt dim) const
{
Param out = param_.copy(String(user_section + "") + dim + "d:", true);
out.setValue("default_path", param_.getValue(user_section + "default_path").toString());
return out;
}
void TOPPViewBase::abortTOPPTool()
{
if (topp_.process)
{
// block signals to avoid error message from finished() signal
topp_.process->blockSignals(true);
// kill and delete the process
topp_.process->terminate();
delete topp_.process;
topp_.process = nullptr;
// finish log with new line
log_->addNewline();
updateMenu();
}
}
void TOPPViewBase::loadFiles(const StringList& list, QSplashScreen* splash_screen)
{
static StringList colors = { "@bw", "@bg", "@b", "@r", "@g", "@m" };
static StringList gradients = { "Linear|0,#ffffff;100,#000000" , "Linear|0,#dddddd;100,#000000" , "Linear|0,#000000;100,#000000",
"Linear|0,#ff0000;100,#ff0000" , "Linear|0,#00ff00;100,#00ff00" , "Linear|0,#ff00ff;100,#ff00ff" };
bool last_was_plus = false;
bool last_was_annotation = false;
for (StringList::const_iterator it = list.begin(); it != list.end(); ++it)
{
if (*it == "+")
{
last_was_plus = true;
continue;
}
if (*it == "!")
{
last_was_annotation = true;
continue;
}
// no matter what the current item is, after we are done with it,
// we need to reset the 'glue' symbols
RAIICleanup reset([&]() {
last_was_plus = false;
last_was_annotation = false;
});
if (std::find(colors.begin(), colors.end(), *it) != colors.end())
{ // its a color!
if ((getActive2DWidget() != nullptr || getActive3DWidget() != nullptr) && getActiveCanvas() != nullptr)
{
Param tmp = getActiveCanvas()->getCurrentLayer().param;
tmp.setValue("dot:gradient", gradients[Helpers::indexOf(colors, *it)]);
getActiveCanvas()->setCurrentLayerParameters(tmp);
}
continue;
}
splash_screen->showMessage((String("Loading file: ") + *it).toQString());
splash_screen->repaint();
QApplication::processEvents();
if (!getActivePlotWidget())
{
if (last_was_annotation)
{
log_->appendNewHeader(LogWindow::LogState::WARNING, "Error", "Cannot annotate without having added layers before.");
continue;
}
// create new tab (also in case of last_was_plus)...
addDataFile(*it, false, true); // add data file but don't show options
continue;
}
// we have an active widget
if (last_was_plus)
{ // add to current tab
addDataFile(*it, false, true, "", getActivePlotWidget()->getWindowId());
continue;
}
else if (last_was_annotation)
{ // try to treat file as annotation file and annotate current layer
auto l = getCurrentLayer();
if (l)
{
auto annotator = LayerAnnotatorBase::getAnnotatorWhichSupports(*it);
if (annotator.get() == nullptr)
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "Error", String("Filename '" + *it + "' has unsupported file type. No annotation performed.").toQString());
}
else
{ // we have an annotator ...
annotator->annotateWithFilename(*l, *log_, *it); // ID tabs are automatically enabled
}
}
}
else
{ // create new tab
addDataFile(*it, false, true); // add data file but don't show options
}
}
}
void TOPPViewBase::saveLayerAll() const
{
getActiveCanvas()->saveCurrentLayer(false);
}
void TOPPViewBase::saveLayerVisible() const
{
getActiveCanvas()->saveCurrentLayer(true);
}
void TOPPViewBase::toggleGridLines() const
{
getActiveCanvas()->showGridLines(!getActiveCanvas()->gridLinesShown());
}
void TOPPViewBase::toggleAxisLegends() const
{
getActivePlotWidget()->showLegend(!getActivePlotWidget()->isLegendShown());
}
void TOPPViewBase::toggleInterestingMZs() const
{
auto w = getActive1DWidget();
if (w == nullptr) return;
w->canvas()->setDrawInterestingMZs(!w->canvas()->isDrawInterestingMZs());
}
void TOPPViewBase::showPreferences() const
{
getActiveCanvas()->showCurrentLayerPreferences();
}
void TOPPViewBase::metadataFileDialog()
{
QStringList files = chooseFilesDialog_();
FileHandler fh;
fh.getOptions().setMetadataOnly(true);
for (QStringList::iterator it = files.begin(); it != files.end(); ++it)
{
ExperimentType exp;
try
{
QMessageBox::critical(this, "Error", "Only raw data files (mzML, DTA etc) are supported to view their meta data.");
}
catch (Exception::BaseException& e)
{
QMessageBox::critical(this, "Error", (String("Error while reading data: ") + e.what()).c_str());
return;
}
MetaDataBrowser dlg(false, this);
dlg.add(exp.getMSExperiment());
dlg.exec();
}
}
void TOPPViewBase::showSpectrumMetaData(int spectrum_index) const
{
getActiveCanvas()->showMetaData(true, spectrum_index);
}
void TOPPViewBase::copyLayer(const QMimeData* data, QWidget* source, int id)
{
SpectraTreeTab* spec_view = (source ? qobject_cast<SpectraTreeTab*>(source->parentWidget()) : nullptr);
try
{
// NOT USED RIGHT NOW, BUT KEEP THIS CODE (it was hard to find out how this is done)
// decode data to get the row
// QByteArray encoded_data = data->data(data->formats()[0]);
// QDataStream stream(&encoded_data, QIODevice::ReadOnly);
// int row, col;
// stream >> row >> col;
// set wait cursor
setCursor(Qt::WaitCursor);
RAIICleanup cl([&]() { setCursor(Qt::ArrowCursor); });
// determine where to copy the data
UInt new_id = (id == -1) ? 0 : id;
if (source == layers_view_)
{
// only the selected row can be dragged => the source layer is the selected layer
LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
// attach feature, consensus and peak data (new OnDiscMSExperiment());
FeatureMapSharedPtrType features(new FeatureMapType());
if (auto* lp = dynamic_cast<LayerDataFeature*>(&layer)) features = lp->getFeatureMap();
ConsensusMapSharedPtrType consensus(new ConsensusMapType());
if (auto* lp = dynamic_cast<LayerDataConsensus*>(&layer)) consensus = lp->getConsensusMap();
ExperimentSharedPtrType peaks(new ExperimentType());
ODExperimentSharedPtrType on_disc_peaks(new OnDiscMSExperiment());
if (auto* lp = dynamic_cast<LayerDataPeak*>(&layer))
{
peaks = lp->getPeakDataMuteable();
on_disc_peaks = lp->getOnDiscPeakData();
}
if (auto* lp = dynamic_cast<LayerDataChrom*>(&layer))
{
peaks = lp->getChromatogramData();
on_disc_peaks = lp->getOnDiscPeakData();
}
// if the layer provides identification data -> retrieve it
PeptideIdentificationList peptides;
if (auto p = dynamic_cast<IPeptideIds*>(&layer); p != nullptr)
{
peptides = p->getPeptideIds();
}
// add the data
addData(features, consensus, peptides, peaks, on_disc_peaks, layer.type, false, false, true, layer.filename, layer.getName(), new_id);
}
else if (spec_view != nullptr)
{
ExperimentSharedPtrType new_exp_sptr(new ExperimentType());
if (LayerDataBase::DataType current_type; spec_view->getSelectedScan(new_exp_sptr->getMSExperiment(), current_type))
{
ODExperimentSharedPtrType od_dummy(new OnDiscMSExperiment());
FeatureMapSharedPtrType f_dummy(new FeatureMapType());
ConsensusMapSharedPtrType c_dummy(new ConsensusMapType());
PeptideIdentificationList p_dummy;
const LayerDataBase& layer = getActiveCanvas()->getCurrentLayer();
addData(f_dummy, c_dummy, p_dummy, new_exp_sptr, od_dummy, current_type, false, false, true, layer.filename, layer.getName(), new_id);
}
}
else if (source == nullptr)
{
// drag source is external
if (data->hasUrls())
{
QList<QUrl> urls = data->urls();
// use a QTimer for external sources to make the source (e.g. Windows Explorer responsive again)
// Using a QueuedConnection for the DragEvent does not solve the problem (Qt 5.15) -- see previous (reverted) commit
QTimer::singleShot(50, [this, urls, new_id]() {
for (const QUrl& url : urls)
{
addDataFile(url.toLocalFile(), false, true, "", new_id);
}
});
}
}
}
catch (Exception::BaseException& e)
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Error while creating layer", e.what());
}
}
void TOPPViewBase::updateCurrentPath()
{
// do not update if the user disabled this feature.
if (param_.getValue(user_section + "default_path_current") != "true")
{
return;
}
// reset
current_path_ = param_.getValue(user_section + "default_path").toString();
// update if the current layer has a path associated
if (getActiveCanvas() && getActiveCanvas()->getLayerCount() != 0 && getActiveCanvas()->getCurrentLayer().filename != "")
{
current_path_ = File::path(getActiveCanvas()->getCurrentLayer().filename);
}
}
void TOPPViewBase::showSpectrumBrowser()
{
views_dockwidget_->show();
updateViewBar();
}
void TOPPViewBase::fileChanged_(const String& filename)
{
// check if file has been deleted
if (!QFileInfo(filename.toQString()).exists())
{
watcher_->removeFile(filename);
return;
}
// iterate over all windows and determine which need an update
std::vector<std::pair<const PlotWidget*, Size> > needs_update;
for (const auto& mdi_window : ws_.subWindowList())
{
const PlotWidget* sw = qobject_cast<const PlotWidget*>(mdi_window);
if (sw == nullptr) return;
Size lc = sw->canvas()->getLayerCount();
// determine if widget stores one or more layers for the given filename (->needs update)
for (Size j = 0; j != lc; ++j)
{
if (sw->canvas()->getLayer(j).filename == filename)
{
needs_update.emplace_back(sw, j);
}
}
}
if (needs_update.empty()) // no layer references data of filename
{
watcher_->removeFile(filename); // remove watcher
return;
}
// std::cout << "Number of Layers that need update: " << needs_update.size() << std::endl;
pair<const PlotWidget*, Size>& slp = needs_update[0];
const PlotWidget* sw = slp.first;
Size layer_index = slp.second;
bool user_wants_update = false;
if (param_.getValue(user_section + "on_file_change") == "update automatically") //automatically update
{
user_wants_update = true;
}
else if (param_.getValue(user_section + "on_file_change") == "ask") // ask the user if the layer should be updated
{
if (watcher_msgbox_ == true) // we already have a dialog for that opened... do not ask again
{
return;
}
// track that we will show the msgbox and we do not need to show it again if file changes once more and the dialog is still open
watcher_msgbox_ = true;
QMessageBox msg_box;
QAbstractButton* ok = msg_box.addButton(QMessageBox::Ok);
msg_box.addButton(QMessageBox::Cancel);
msg_box.setWindowTitle("Layer data changed");
msg_box.setText((String("The data of file '") + filename + "' has changed.<BR>Update layers?").toQString());
msg_box.exec();
watcher_msgbox_ = false;
if (msg_box.clickedButton() == ok)
{
user_wants_update = true;
}
}
if (user_wants_update == false)
{
return;
}
LayerDataBase& layer = sw->canvas()->getLayer(layer_index);
// reload data
if (auto* lp = dynamic_cast<LayerDataPeak*>(&layer)) // peak data
{
try
{
FileHandler().loadExperiment(layer.filename, lp->getPeakDataMuteable()->getMSExperiment(), {}, ProgressLogger::NONE, true, true);
}
catch (Exception::BaseException& e)
{
QMessageBox::critical(this, "Error", (String("Error while loading file") + layer.filename + "\nError message: " + e.what()).toQString());
lp->getPeakDataMuteable()->getMSExperiment().clear(true);
}
lp->getPeakDataMuteable()->getMSExperiment().sortSpectra(true);
lp->getPeakDataMuteable()->getMSExperiment().updateRanges();
}
else if (auto* lp = dynamic_cast<LayerDataFeature*>(&layer)) // feature data
{
try
{
FileHandler().loadFeatures(layer.filename, *lp->getFeatureMap());
}
catch (Exception::BaseException& e)
{
QMessageBox::critical(this, "Error", (String("Error while loading file") + layer.filename + "\nError message: " + e.what()).toQString());
lp->getFeatureMap()->clear(true);
}
lp->getFeatureMap()->updateRanges();
}
else if (auto* lp = dynamic_cast<LayerDataConsensus*>(&layer)) // consensus feature data
{
try
{
FileHandler().loadConsensusFeatures(layer.filename, *lp->getConsensusMap(), {FileTypes::CONSENSUSXML});
}
catch (Exception::BaseException& e)
{
QMessageBox::critical(this, "Error", (String("Error while loading file") + layer.filename + "\nError message: " + e.what()).toQString());
lp->getConsensusMap()->clear(true);
}
lp->getConsensusMap()->updateRanges();
}
else if (auto* lp = dynamic_cast<LayerDataChrom*>(&layer)) // chromatogram
{
// TODO CHROM
try
{
FileHandler().loadExperiment(layer.filename, lp->getChromatogramData()->getMSExperiment(), {}, ProgressLogger::NONE, true, true);
}
catch (Exception::BaseException& e)
{
QMessageBox::critical(this, "Error", (String("Error while loading file") + layer.filename + "\nError message: " + e.what()).toQString());
lp->getChromatogramData()->getMSExperiment().clear(true);
}
lp->getChromatogramData()->getMSExperiment().sortChromatograms(true);
lp->getChromatogramData()->getMSExperiment().updateRanges();
}
// update all layers that need an update
for (Size i = 0; i != needs_update.size(); ++i)
{
sw->canvas()->updateLayer(needs_update[i].second);
}
layerActivated();
// temporarily remove and read filename from watcher_ as a workaround for bug #233
// This might not be a 'bug' but rather unfortunate behaviour (even in Qt5) if the file was actually deleted and recreated by an external tool
// (some TextEditors seem to do this), see https://stackoverflow.com/a/30076119;
watcher_->removeFile(filename);
watcher_->addFile(filename);
}
TOPPViewBase::~TOPPViewBase()
{
savePreferences();
abortTOPPTool();
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/TOPPASBase.cpp | .cpp | 51,026 | 1,525 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/APPLICATIONS/TOPPASBase.h>
#include <OpenMS/APPLICATIONS/ToolHandler.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/DATASTRUCTURES/DateTime.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
#include <OpenMS/VISUAL/EnhancedWorkspace.h>
#include <OpenMS/VISUAL/EnhancedTabBar.h>
#include <OpenMS/VISUAL/MISC/GUIHelpers.h>
#include <OpenMS/VISUAL/TOPPASInputFileListVertex.h>
#include <OpenMS/VISUAL/LogWindow.h>
#include <OpenMS/VISUAL/TOPPASMergerVertex.h>
#include <OpenMS/VISUAL/TOPPASOutputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASResources.h>
#include <OpenMS/VISUAL/TOPPASScene.h>
#include <OpenMS/VISUAL/TOPPASSplitterVertex.h>
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <OpenMS/VISUAL/TOPPASWidget.h>
#include <map>
//Qt
#include <QApplication>
#include <QCloseEvent>
#include <QDesktopServices>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QNetworkProxyFactory>
#include <QNetworkReply>
#include <QSvgGenerator>
#include <QTextStream>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QMap>
#include <QtCore/QSet>
#include <QtCore/QSettings>
#include <QtCore/QUrl>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QDockWidget>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QInputDialog>
#include <QtWidgets/QLabel>
#include <QtWidgets/QListWidget>
#include <QtWidgets/QListWidgetItem>
#include <QtWidgets/QMdiSubWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSplashScreen>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QToolTip>
#include <QtWidgets/QTreeWidget>
#include <QtWidgets/QTreeWidgetItem>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWhatsThis>
#include <utility>
#include <OpenMS/VISUAL/TOPPASOutputFolderVertex.h>
using namespace std;
using namespace OpenMS;
namespace OpenMS
{
using namespace Internal;
int TOPPASBase::node_offset_ = 0;
qreal TOPPASBase::z_value_ = 42.0;
TOPPASBase::TOPPASBase(QWidget* parent) :
QMainWindow(parent),
DefaultParamHandler("TOPPASBase"),
clipboard_scene_(nullptr)
{
setWindowTitle("TOPPAS");
setWindowIcon(QIcon(":/TOPPAS.png"));
//prevents errors caused by too small width,height values
setMinimumSize(400, 400);
// center main window
setGeometry(
(int)(0.1 * QGuiApplication::primaryScreen()->geometry().width()),
(int)(0.1 * QGuiApplication::primaryScreen()->geometry().height()),
(int)(0.8 * QGuiApplication::primaryScreen()->geometry().width()),
(int)(0.8 * QGuiApplication::primaryScreen()->geometry().height())
);
// create dummy widget (to be able to have a layout), Tab bar and workspace
QWidget* dummy = new QWidget(this);
setCentralWidget(dummy);
QVBoxLayout* box_layout = new QVBoxLayout(dummy);
tab_bar_ = new EnhancedTabBar(dummy);
tab_bar_->setWhatsThis("Tab bar<BR><BR>Close tabs through the context menu or by double-clicking them.");
tab_bar_->addTab("dummy", 1336);
tab_bar_->setMinimumSize(tab_bar_->sizeHint());
tab_bar_->removeId(1336);
//connect slots and signals for selecting spectra
connect(tab_bar_, &EnhancedTabBar::currentIdChanged, this, &TOPPASBase::focusByTab);
connect(tab_bar_, &EnhancedTabBar::closeRequested, this, &TOPPASBase::closeByTab);
box_layout->addWidget(tab_bar_);
ws_ = new EnhancedWorkspace(dummy);
connect(ws_, &EnhancedWorkspace::subWindowActivated, this, &TOPPASBase::updateTabBar);
connect(ws_, &EnhancedWorkspace::subWindowActivated, this, &TOPPASBase::updateMenu);
box_layout->addWidget(ws_);
//################## MENUS #################
// File menu
QMenu* file = new QMenu("&File", this);
menuBar()->addMenu(file);
file->addAction("&New", this, &TOPPASBase::newPipeline)->setShortcut(Qt::CTRL | Qt::Key_N);
file->addAction("&Open", this, &TOPPASBase::openFilesByDialog)->setShortcut(Qt::CTRL | Qt::Key_O);
file->addAction("Open &example file", this, &TOPPASBase::openExampleDialog)->setShortcut(Qt::CTRL | Qt::Key_E);
file->addAction("&Include", this, &TOPPASBase::includePipeline)->setShortcut(Qt::CTRL | Qt::Key_I);
//file->addAction("Online &Repository", this, &TOPPASBase::openOnlinePipelineRepository)->setShortcut(Qt::CTRL | Qt::Key_R);
file->addAction("&Save", this, &TOPPASBase::savePipeline)->setShortcut(Qt::CTRL | Qt::Key_S);
file->addAction("Save &As", this, &TOPPASBase::saveCurrentPipelineAs)->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_S);
file->addAction("E&xport as image", this, &TOPPASBase::exportAsImage);
file->addAction("Refresh ¶meters", this, &TOPPASBase::refreshParameters)->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_P);
file->addAction("&Close pipeline", this, &TOPPASBase::closeFile)->setShortcut(Qt::CTRL | Qt::Key_W);
file->addSeparator();
// Recent files
file->addMenu(recent_files_menu_.getMenu()); // updates automatically via RecentFilesMenu class, since this is just a pointer
connect(&recent_files_menu_, &RecentFilesMenu::recentFileClicked, [this](const String& filename) { addTOPPASFile(filename, true);});
file->addSeparator();
file->addAction("&Load TOPPAS resource file", this, SLOT(loadPipelineResourceFile()));
file->addAction("Sa&ve TOPPAS resource file", this, SLOT(savePipelineResourceFile()));
file->addSeparator();
file->addAction("&Quit", qApp, SLOT(quit()));
//Pipeline menu
QMenu* pipeline = new QMenu("&Pipeline", this);
menuBar()->addMenu(pipeline);
pipeline->addAction("&Run (F5)", this, SLOT(runPipeline()));
pipeline->addAction("&Abort", this, SLOT(abortPipeline()));
//Windows menu
QMenu* windows = new QMenu("&Windows", this);
menuBar()->addMenu(windows);
//Help menu
QMenu* help = new QMenu("&Help", this);
menuBar()->addMenu(help);
QAction* action = help->addAction("OpenMS website", this, &TOPPASBase::showURL);
action->setData("http://www.OpenMS.de");
action = help->addAction("TOPPAS tutorial", this, &TOPPASBase::showURL);
action->setShortcut(Qt::Key_F1);
action->setData(String("html/TOPPAS_tutorial.html").toQString());
help->addSeparator();
help->addAction("&About", this, SLOT(showAboutDialog()));
//create status bar
message_label_ = new QLabel(statusBar());
statusBar()->addWidget(message_label_, 1);
//################## TOOLBARS #################
//create toolbars and connect signals
//--Basic tool bar--
//tool_bar_ = addToolBar("Basic tool bar");
//tool_bar_->show();
//################## DEFAULTS #################
//general
defaults_.setValue("preferences:default_path", ".", "Default path for loading and storing files.");
defaults_.setValue("preferences:default_path_current", "true", "If the current path is preferred over the default path.");
defaults_.setValidStrings("preferences:default_path_current", {"true","false"});
defaults_.setValue("preferences:version", "none", "OpenMS version, used to check if the TOPPAS.ini is up-to-date");
subsections_.emplace_back("preferences:RecentFiles");
defaultsToParam_();
//load param file
loadPreferences();
//################## Dock widgets #################
//TOPP tools window
QDockWidget* topp_tools_bar = new QDockWidget("TOPP", this);
topp_tools_bar->setObjectName("TOPP_tools_bar");
addDockWidget(Qt::LeftDockWidgetArea, topp_tools_bar);
QWidget* frame = new QWidget(topp_tools_bar);
auto frame_layout = new QVBoxLayout(frame);
//frame->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Maximum);
tools_tree_view_ = createTOPPToolsTreeWidget();
tools_filter_ = new QLineEdit();
tools_expand_all_ = new QPushButton("expand all");
tools_collapse_all_ = new QPushButton("collapse all");
frame_layout->addWidget(new QLabel("Filter: "));
frame_layout->addWidget(tools_filter_);
frame_layout->addWidget(tools_expand_all_);
frame_layout->addWidget(tools_collapse_all_);
frame_layout->addWidget(tools_tree_view_);
topp_tools_bar->setWidget(frame);
connect(tools_expand_all_, &QPushButton::clicked, tools_tree_view_, &TOPPASTreeView::expandAll);
connect(tools_collapse_all_, &QPushButton::clicked, tools_tree_view_, &TOPPASTreeView::collapseAll);
connect(tools_tree_view_, &QTreeWidget::itemDoubleClicked, this, &TOPPASBase::insertNewVertexInCenter_);
connect(tools_filter_, &QLineEdit::textChanged, this, &TOPPASBase::filterToolTree_);
windows->addAction(topp_tools_bar->toggleViewAction());
//log window
QDockWidget* log_bar = new QDockWidget("Log", this);
log_bar->setObjectName("log_bar");
addDockWidget(Qt::BottomDockWidgetArea, log_bar);
log_ = new LogWindow(log_bar);
log_->setMaxLength(1e7); // limit to 10 mio characters, and trim to 5 mio upon reaching this limit
log_bar->setWidget(log_);
log_bar->hide();
//windows->addAction("&Show log window",log_bar,SLOT(show()));
windows->addAction(log_bar->toggleViewAction());
//workflow description window
QDockWidget* description_bar = new QDockWidget("Workflow Description", this);
description_bar->setObjectName("workflow_description_bar");
addDockWidget(Qt::RightDockWidgetArea, description_bar);
desc_ = new QTextEdit(description_bar);
desc_->setTextColor(Qt::black);
desc_->setText("... put your workflow description here ...");
desc_->setTextColor(Qt::black);
desc_->document()->setDefaultFont(QFont("Arial", 12));
description_bar->setWidget(desc_);
windows->addAction(description_bar->toggleViewAction());
connect(desc_, SIGNAL(textChanged()), this, SLOT(descriptionUpdated_()));
// set current path
current_path_ = param_.getValue("preferences:default_path").toString();
// set & create temporary path -- make sure its a new subdirectory, as it will be deleted later
QString new_tmp_dir = File::getUniqueName(false).toQString();
QDir qd(File::getTempDirectory().toQString());
qd.mkdir(new_tmp_dir);
qd.cd(new_tmp_dir);
tmp_path_ = qd.absolutePath();
/*
QT5 replace with QWebEngine
// online browser
webview_ = new QWebView(parent);
webview_->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); // now linkClicked() is emitted
connect((webview_->page()), SIGNAL(linkClicked(const QUrl &)), this, SLOT(downloadTOPPASfromHomepage_(const QUrl &)));
*/
network_manager_ = new QNetworkAccessManager(this);
connect(network_manager_, SIGNAL(finished(QNetworkReply*)), this, SLOT(toppasFileDownloaded_(QNetworkReply*)));
// update the menu
updateMenu();
QSettings settings("OpenMS", "TOPPAS");
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("windowState").toByteArray());
}
void TOPPASBase::filterToolTree_()
{
tools_tree_view_->filter(tools_filter_->text());
}
TOPPASBase::~TOPPASBase()
{
savePreferences();
// delete temporary files (TODO: make this a user dialog and ask - for later resume)
// safety measure: only delete if subdirectory of Temp path; we do not want to delete / or c:
if (String(tmp_path_).substitute("\\", "/").hasPrefix(File::getTempDirectory().substitute("\\", "/") + "/"))
{
File::removeDirRecursively(tmp_path_);
}
}
void TOPPASBase::descriptionUpdated_()
{
if (!activeSubWindow_() || !activeSubWindow_()->getScene())
{
return;
}
//std::cerr << "changed to '" << String(desc_->toHtml()) << "'\n";
activeSubWindow_()->getScene()->setChanged(true);
activeSubWindow_()->getScene()->setDescription(desc_->toHtml());
}
void TOPPASBase::toppasFileDownloaded_(QNetworkReply* /* r */)
{
/* QT5
r->deleteLater();
if (r->error() != QNetworkReply::NoError)
{
log_->appendNewHeader(LogWindow::LogState::CRITICAL, "Download failed", "Error '" + r->errorString() + "' while downloading TOPPAS file: '" + r->url().toString() + "'");
return;
}
QByteArray data = r->readAll();
QString proposed_filename;
if (r->url().hasQueryItem("file"))
{
proposed_filename = r->url().queryItemValue("file");
}
else
{
proposed_filename = "Workflow.toppas";
OPENMS_LOG_WARN << "The URL format of downloads from the TOPPAS Online-Repository has changed. Please notify developers!";
}
QString filename = QFileDialog::getSaveFileName(this, "Where to save the TOPPAS file?", this->current_path_.toQString() + "/" + proposed_filename, tr("TOPPAS (*.toppas)"));
// check if the user clicked cancel, to avoid saving .toppas somewhere
if (String(filename).trim().empty())
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "Download succeeded, but saving aborted by user!", "");
return;
}
if (!filename.endsWith(".toppas", Qt::CaseInsensitive))
{
filename += ".toppas";
}
QFile file(filename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "Download succeeded. Cannot save the file. Try again with another filename and/or location!", "");
return;
}
QTextStream out(&file);
out << data;
file.close();
this->addTOPPASFile(filename);
log_->appendNewHeader(LogWindow::LogState::NOTICE, "File successfully saved to '" + filename + "'.", "");
*/
}
void TOPPASBase::TOPPASreadyRead()
{
QNetworkReply::NetworkError ne = network_reply_->error();
qint64 ba = network_reply_->bytesAvailable();
OPENMS_LOG_DEBUG << "Error code (QNetworkReply::NetworkError): " << ne << " bytes available: " << ba << std::endl;
return;
}
void TOPPASBase::downloadTOPPASfromHomepage_(const QUrl& url)
{
if (url.toString().endsWith(QString(".toppas"), Qt::CaseInsensitive))
{
network_reply_ = network_manager_->get(QNetworkRequest(url));
// debug
connect(network_reply_, SIGNAL(readyRead()), this, SLOT(TOPPASreadyRead()));
connect(network_reply_, SIGNAL(error(QNetworkReply::NetworkError code)), this, SLOT(TOPPASreadyRead()));
connect(network_reply_, SIGNAL(finished()), this, SLOT(TOPPASreadyRead()));
connect(network_reply_, SIGNAL(metaDataChanged()), this, SLOT(TOPPASreadyRead()));
connect(network_reply_, SIGNAL(sslErrors(const QList<QSslError> & errors)), this, SLOT(TOPPASreadyRead()));
// .. end debug
log_->appendNewHeader(LogWindow::LogState::NOTICE, "Downloading file '" + url.toString() + "'. You will be notified once the download finished.", "");
// webview_->close(); QT5 replace with QWebEngine
}
else
{
QMessageBox::warning(this, tr("Error"), tr("You can only click '.toppas' files on this page. No navigation is allowed!\n"));
/*
replace with QT5 webengine
webview_->setFocus();
webview_->activateWindow();
*/
}
}
void TOPPASBase::openOnlinePipelineRepository()
{
/* QT5
QUrl url = QUrl("http://www.OpenMS.de/TOPPASWorkflows/");
static bool proxy_settings_checked = false;
if (!proxy_settings_checked) // do only once because may take several seconds on windows
{
QNetworkProxy proxy;
QUrl tmp_proxy_url(QString(getenv("http_proxy")));
QUrl tmp_PROXY_url(QString(getenv("HTTP_PROXY")));
QUrl proxy_url = tmp_proxy_url.isValid() ? tmp_proxy_url : tmp_PROXY_url;
if (proxy_url.isValid())
{
QString hostname = proxy_url.host();
int port = proxy_url.port();
QString username = proxy_url.userName();
QString password = proxy_url.password();
proxy = QNetworkProxy(QNetworkProxy::HttpProxy, hostname, port, username, password);
}
else
{
QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery(url);
if (!proxies.empty())
{
proxy = proxies.first();
}
}
QNetworkProxy::setApplicationProxy(proxy); //no effect if proxy == QNetworkProxy()
proxy_settings_checked = true;
}
// show something immediately, so the user does not stare at white screen while the URL is fetched
webview_->setHtml("loading content ... ");
webview_->show();
// ... load the page in background
webview_->load(url);
*/
}
//static
TOPPASTreeView* TOPPASBase::createTOPPToolsTreeWidget(QWidget* parent_widget)
{
TOPPASTreeView* tools_tree_view = new TOPPASTreeView(parent_widget);
tools_tree_view->setWhatsThis("TOPP tools list<BR><BR>All available TOPP tools are shown here.");
tools_tree_view->setColumnCount(1);
QStringList header_labels;
header_labels.append(QString("TOPP tools"));
tools_tree_view->setHeaderLabels(header_labels);
auto add_list_item = [&tools_tree_view](const QString& node_name, const QString& tool_tip)
{
QTreeWidgetItem* item = new QTreeWidgetItem(tools_tree_view);
item->setText(0, node_name);
item->setToolTip(0, tool_tip);
tools_tree_view->addTopLevelItem(item);
};
add_list_item("<Input files>", "One or multiple input files, such as mzML or FASTA files from your local hard drive");
add_list_item("<Output files>", "Sink for one or more output files, which are produced by a TOPP tool and which you want to keep for later.");
add_list_item("<Output folder>", "Some TOPP tools write their output to a folder. Usually a fixed set of files, whose names cannot be set explicitly.");
add_list_item("<Merger>", "Concatenate files from multiple input edges to a list and forward that list.");
add_list_item("<Collector>", "Collect each single file from \na single input edge (for every time it runs)\nand then foward this list to the next tool (which is only invoked once)");
add_list_item("<Splitter>", "Opposite of a collector.");
//Param category_param = param_.copy("tool_categories:", true);
ToolListType tools_list = ToolHandler::getTOPPToolList(true);
// any tool without a category gets into "unassigned" bin
for (ToolListType::iterator it = tools_list.begin(); it != tools_list.end(); ++it)
{
if (it->second.category.trim().empty())
it->second.category = "Unassigned";
}
QSet<QString> category_set;
for (ToolListType::const_iterator it = tools_list.begin(); it != tools_list.end(); ++it)
{
category_set << String(it->second.category).toQString();
}
QStringList category_list = category_set.values();
std::sort(category_list.begin(), category_list.end());
std::map<QString, QTreeWidgetItem*> category_map;
for (const QString &category : category_list)
{
auto item = new QTreeWidgetItem((QTreeWidget*)nullptr);
item->setText(0, category);
tools_tree_view->addTopLevelItem(item);
category_map[category] = item;
}
for (const auto& tool : tools_list)
{
auto item = new QTreeWidgetItem(category_map[tool.second.category.toQString()]);
item->setText(0, tool.first.toQString());
QTreeWidgetItem* parent_item = item;
StringList types = ToolHandler::getTypes(tool.first);
for (const auto& type : types)
{
item = new QTreeWidgetItem(parent_item);
item->setText(0, type.toQString());
}
}
tools_tree_view->resizeColumnToContents(0);
return tools_tree_view;
}
void TOPPASBase::loadFiles(const StringList& list, QSplashScreen* splash_screen)
{
for (StringList::const_iterator it = list.begin(); it != list.end(); ++it)
{
splash_screen->showMessage((String("Loading file: ") + *it).toQString());
splash_screen->repaint();
QApplication::processEvents();
addTOPPASFile(*it);
}
}
void TOPPASBase::openExampleDialog()
{
QString file_name = QFileDialog::getOpenFileName(this, tr("Open example workflow"),
File::getOpenMSDataPath().toQString()
+ QDir::separator() + "examples" + QDir::separator()
+ "TOPPAS" + QDir::separator(),
tr("TOPPAS pipelines (*.toppas)"));
addTOPPASFile(file_name);
}
void TOPPASBase::openFilesByDialog()
{
QString file_name = QFileDialog::getOpenFileName(this, tr("Open workflow"), current_path_.toQString(), tr("TOPPAS pipelines (*.toppas)"));
addTOPPASFile(file_name);
}
void TOPPASBase::includePipeline()
{
QString file_name = QFileDialog::getOpenFileName(this, tr("Include workflow"), current_path_.toQString(), tr("TOPPAS pipelines (*.toppas)"));
addTOPPASFile(file_name, false);
}
void TOPPASBase::addTOPPASFile(const String& file_name, bool in_new_window)
{
if (file_name.empty()) return;
if (!file_name.toQString().endsWith(".toppas", Qt::CaseInsensitive))
{
OPENMS_LOG_ERROR << "The file '" << file_name << "' is not a .toppas file" << std::endl;
return;
}
recent_files_menu_.add(file_name);
TOPPASWidget* asw = activeSubWindow_();
TOPPASScene* scene = nullptr;
if (in_new_window)
{
if (asw)
{
TOPPASWidget* uninitialized_window = window_(asw->getFirstWindowID());
if (uninitialized_window && !uninitialized_window->getScene()->wasChanged())
closeByTab(asw->getFirstWindowID());
}
TOPPASWidget* tw = new TOPPASWidget(Param(), ws_, tmp_path_);
scene = tw->getScene();
scene->load(file_name); // first load WF, including description etc
showAsWindow_(tw, File::basename(file_name)); // show it
}
else
{
if (!activeSubWindow_()) return;
TOPPASScene* tmp_scene = new TOPPASScene(nullptr, this->tmp_path_.toQString(), false);
tmp_scene->load(file_name);
scene = activeSubWindow_()->getScene();
scene->include(tmp_scene);
delete tmp_scene;
}
//connect signals/slots for log messages
for (TOPPASScene::VertexIterator it = scene->verticesBegin(); it != scene->verticesEnd(); ++it)
{
TOPPASToolVertex* tv = dynamic_cast<TOPPASToolVertex*>(*it);
if (tv)
{
connect(tv, SIGNAL(toolStarted()), this, SLOT(toolStarted()));
connect(tv, SIGNAL(toolFinished()), this, SLOT(toolFinished()));
connect(tv, SIGNAL(toolCrashed()), this, SLOT(toolCrashed()));
connect(tv, SIGNAL(toolFailed()), this, SLOT(toolFailed()));
connect(tv, SIGNAL(toolFailed(const QString &)), this, SLOT(updateTOPPOutputLog(const QString &)));
// already done in ToppasScene:
//connect (tv, SIGNAL(toppOutputReady(const QString&)), this, SLOT(updateTOPPOutputLog(const QString&)));
continue;
}
TOPPASMergerVertex* tmv = dynamic_cast<TOPPASMergerVertex*>(*it);
if (tmv)
{
connect(tmv, SIGNAL(mergeFailed(const QString)), this, SLOT(updateTOPPOutputLog(const QString &)));
continue;
}
TOPPASOutputFileListVertex* oflv = dynamic_cast<TOPPASOutputFileListVertex*>(*it);
if (oflv)
{
connect(oflv, SIGNAL(outputFileWritten(const String &)), this, SLOT(outputVertexFinished(const String &)));
continue;
}
}
}
void TOPPASBase::newPipeline()
{
TOPPASWidget* tw = new TOPPASWidget(Param(), ws_, tmp_path_);
showAsWindow_(tw, "(Untitled)");
}
void TOPPASBase::savePipeline()
{
TOPPASWidget* w = nullptr;
QObject* sendr = QObject::sender();
QAction* save_button_clicked = dynamic_cast<QAction*>(sendr);
if (!save_button_clicked)
{
// scene has requested to be saved
TOPPASScene* ts = dynamic_cast<TOPPASScene*>(sendr);
if (ts && !ts->views().empty())
{
w = dynamic_cast<TOPPASWidget*>(ts->views().first());
}
}
else
{
w = activeSubWindow_();
}
if (!w)
{
return;
}
QString file_name = w->getScene()->getSaveFileName().toQString();
if (file_name != "")
{
// accept also upper case TOPPAS extensions, since
// we also support them while loading
if (!file_name.endsWith(".toppas", Qt::CaseInsensitive))
{
file_name += ".toppas";
}
if (!w->getScene()->store(file_name))
{
QMessageBox::warning(this, tr("Error"),
tr("Unable to save current pipeline. Possible reason: Invalid edges due to parameter refresh."));
}
}
else
{
QString savedFileName = TOPPASBase::savePipelineAs(w, current_path_.toQString());
// update tab title
if (savedFileName != "")
{
tab_bar_->setTabText(File::basename(savedFileName).toQString());
}
}
}
void TOPPASBase::saveCurrentPipelineAs()
{
TOPPASWidget* w = activeSubWindow_();
QString file_name = TOPPASBase::savePipelineAs(w, current_path_.toQString());
if (file_name != "")
{
tab_bar_->setTabText(File::basename(file_name).toQString());
}
}
// static
QString TOPPASBase::savePipelineAs(TOPPASWidget* w, const QString& current_path)
{
if (!w)
{
return "";
}
QString file_name = QFileDialog::getSaveFileName(w, tr("Save workflow"), current_path, tr("TOPPAS pipelines (*.toppas)"));
if (file_name != "")
{
if (!file_name.endsWith(".toppas", Qt::CaseInsensitive))
{
file_name += ".toppas";
}
if (!w->getScene()->store(file_name))
{
QMessageBox::warning(nullptr, tr("Error"),
tr("Unable to save current pipeline. Possible reason: Invalid edges due to parameter refresh."));
}
QString caption = File::basename(file_name).toQString();
w->setWindowTitle(caption);
}
return file_name;
}
void TOPPASBase::exportAsImage()
{
TOPPASWidget* w = activeSubWindow_();
TOPPASScene* s = w->getScene();
QString cp = current_path_.toQString();
QString file_name = QFileDialog::getSaveFileName(w, tr("Save image"), cp, tr("Images (*.svg *.png *.jpg)"));
if (file_name == "")
{
return;
}
if (!file_name.endsWith(".svg", Qt::CaseInsensitive) &&
!file_name.endsWith(".png", Qt::CaseInsensitive) &&
!file_name.endsWith(".jpg", Qt::CaseInsensitive))
{
file_name += ".svg";
}
bool svg = file_name.endsWith(".svg");
QRectF items_bounding_rect = s->itemsBoundingRect();
qreal wh_proportion = (qreal)(items_bounding_rect.width()) / (qreal)(items_bounding_rect.height());
bool w_larger_than_h = wh_proportion > 1;
qreal x1 = 0;
qreal y1 = 0;
qreal x2, y2;
qreal small_edge_length = svg ? 500 : 4000;
if (w_larger_than_h)
{
x2 = wh_proportion * small_edge_length;
y2 = small_edge_length;
}
else
{
x2 = small_edge_length;
y2 = (1.0 / wh_proportion) * small_edge_length;
}
qreal width = x2 - x1;
qreal height = y2 - y1;
if (svg)
{
QSvgGenerator svg_gen;
svg_gen.setFileName(file_name);
svg_gen.setSize(QSize(width, height));
svg_gen.setViewBox(QRect(x1, y1, x2, y2));
svg_gen.setTitle(tr("Title (TBD)"));
svg_gen.setDescription(tr("Description (TBD)"));
QPainter painter(&svg_gen);
s->render(&painter, QRectF(), items_bounding_rect);
}
else
{
QImage img(width, height, QImage::Format_RGB32);
img.fill(QColor(Qt::white).rgb());
QPainter painter(&img);
s->render(&painter, QRectF(), items_bounding_rect);
img.save(file_name);
}
}
void TOPPASBase::loadPipelineResourceFile()
{
TOPPASWidget* w = activeSubWindow_();
TOPPASBase::loadPipelineResourceFile(w, current_path_.toQString());
}
// static
QString TOPPASBase::loadPipelineResourceFile(TOPPASWidget* w, const QString& current_path)
{
if (!w)
{
return "";
}
TOPPASScene* scene = w->getScene();
QString file_name = QFileDialog::getOpenFileName(w, tr("Load resource file"), current_path, tr("TOPPAS resource files (*.trf)"));
if (file_name == "")
{
return "";
}
TOPPASResources resources;
resources.load(file_name);
scene->loadResources(resources);
return file_name;
}
void TOPPASBase::savePipelineResourceFile()
{
TOPPASWidget* w = activeSubWindow_();
TOPPASBase::savePipelineResourceFile(w, current_path_.toQString());
}
// static
QString TOPPASBase::savePipelineResourceFile(TOPPASWidget* w, const QString& current_path)
{
if (!w)
{
return "";
}
TOPPASScene* scene = w->getScene();
QString file_name = QFileDialog::getSaveFileName(w, tr("Save resource file"), current_path, tr("TOPPAS resource files (*.trf)"));
if (file_name == "")
{
return "";
}
if (!file_name.endsWith(".trf"))
{
file_name += ".trf";
}
TOPPASResources resources;
scene->createResources(resources);
resources.store(file_name);
return file_name;
}
void TOPPASBase::preferencesDialog()
{
// do something...
savePreferences();
}
void TOPPASBase::showAsWindow_(TOPPASWidget* tw, const String& caption)
{
ws_->addSubWindow(tw);
tw->showMaximized();
connect(tw, SIGNAL(sendStatusMessage(std::string, OpenMS::UInt)), this, SLOT(showStatusMessage(std::string, OpenMS::UInt)));
connect(tw, SIGNAL(sendCursorStatus(double, double)), this, SLOT(showCursorStatus(double, double)));
connect(tw, SIGNAL(toolDroppedOnWidget(double, double)), this, SLOT(insertNewVertex_(double, double)));
connect(tw, SIGNAL(pipelineDroppedOnWidget(const String &, bool)), this, SLOT(addTOPPASFile(const String &, bool)));
tw->setWindowTitle(caption.toQString());
tw->addToTabBar(tab_bar_, caption, true);
//show first window maximized (only visible windows are in the list)
if (ws_->subWindowList().count() == 0)
{
tw->showMaximized();
}
else
{
tw->show();
}
TOPPASScene* scene = tw->getScene();
connect(scene, SIGNAL(saveMe()), this, SLOT(savePipeline()));
connect(scene, SIGNAL(selectionCopied(TOPPASScene*)), this, SLOT(saveToClipboard(TOPPASScene*)));
connect(scene, SIGNAL(requestClipboardContent()), this, SLOT(sendClipboardContent()));
connect(scene, SIGNAL(mainWindowNeedsUpdate()), this, SLOT(updateMenu()));
connect(scene, SIGNAL(openInTOPPView(QStringList)), this, SLOT(openFilesInTOPPView(QStringList)));
connect(scene, SIGNAL(messageReady(const QString &)), this, SLOT(updateTOPPOutputLog(const QString &)));
connect(scene, SIGNAL(entirePipelineFinished()), this, SLOT(showPipelineFinishedLogMessage()));
connect(scene, SIGNAL(entirePipelineFinished()), this, SLOT(updateMenu()));
connect(scene, SIGNAL(pipelineExecutionFailed()), this, SLOT(updateMenu()));
QRectF scene_rect = scene->itemsBoundingRect();
tw->fitInView(scene_rect, Qt::KeepAspectRatio);
tw->scale(0.75, 0.75);
scene->setSceneRect(tw->mapToScene(tw->rect()).boundingRect());
QRectF items_rect = scene->itemsBoundingRect();
QRectF new_scene_rect = items_rect.united(tw->mapToScene(tw->rect()).boundingRect());
qreal top_left_x = new_scene_rect.topLeft().x();
qreal top_left_y = new_scene_rect.topLeft().y();
qreal bottom_right_x = new_scene_rect.bottomRight().x();
qreal bottom_right_y = new_scene_rect.bottomRight().y();
qreal width = new_scene_rect.width();
qreal height = new_scene_rect.height();
new_scene_rect.setTopLeft(QPointF(top_left_x - width / 2.0, top_left_y - height / 2.0));
new_scene_rect.setBottomRight(QPointF(bottom_right_x + width / 2.0, bottom_right_y + height / 2.0));
scene->setSceneRect(new_scene_rect);
desc_->blockSignals(true);
desc_->setHtml(scene->getDescription());
desc_->blockSignals(false);
}
void TOPPASBase::closeEvent(QCloseEvent* event)
{
QList<QMdiSubWindow*> all_windows = ws_->subWindowList();
for (QMdiSubWindow* w : all_windows)
{
TOPPASWidget* widget = dynamic_cast<TOPPASWidget*>(w->widget());
if (!widget) continue; // not a TOPPASWidget.. ignore it
if (!widget->getScene()->saveIfChanged())
{ // user chose 'abort' in dialog
event->ignore();
return;
}
}
event->accept();
QSettings settings("OpenMS", "TOPPAS");
settings.setValue("geometry", saveGeometry());
settings.setValue("windowState", saveState());
}
void TOPPASBase::showURL()
{
QString target = dynamic_cast<QAction*>(sender())->data().toString();
GUIHelpers::openURL(target);
}
TOPPASWidget* TOPPASBase::window_(int id) const
{
return dynamic_cast<TOPPASWidget*>(ws_->getWidget(id));
}
TOPPASWidget* TOPPASBase::activeSubWindow_() const
{
if (ws_ == nullptr || ws_->currentSubWindow() == nullptr)
{
return nullptr;
}
return dynamic_cast<TOPPASWidget*>(ws_->currentSubWindow()->widget());
}
void TOPPASBase::closeByTab(int id)
{
TOPPASWidget* window = window_(id);
if (window)
{
// try to close the window.. the user might say no
// The Dtor of 'window' will take care of removing it from the tabbar
if (window->close()) updateMenu();
}
}
void TOPPASBase::focusByTab(int id)
{
TOPPASWidget* window = window_(id);
if (window)
{
//std::cerr << "tab changed...\n";
desc_->blockSignals(true);
desc_->setHtml(window->getScene()->getDescription());
desc_->blockSignals(false);
window->setFocus();
}
else
{
desc_->blockSignals(true);
desc_->setHtml("");
desc_->blockSignals(false);
}
}
void TOPPASBase::closeFile()
{
if (ws_ != nullptr && ws_->currentSubWindow() != nullptr)
{
ws_->currentSubWindow()->close();
}
updateMenu();
}
void TOPPASBase::showStatusMessage(const string& msg, OpenMS::UInt time)
{
if (time == 0)
{
message_label_->setText(msg.c_str());
statusBar()->update();
}
else
{
statusBar()->showMessage(msg.c_str(), time);
}
QApplication::processEvents();
}
void TOPPASBase::showCursorStatus(double /*x*/, double /*y*/)
{
// TODO
}
void TOPPASBase::updateToolBar()
{
}
void TOPPASBase::updateTabBar(QMdiSubWindow* w)
{
if (w)
{
TOPPASWidget* tw = dynamic_cast<TOPPASWidget*>(w->widget());
if (tw)
{
Int window_id = tw->getWindowId();
tab_bar_->show(window_id);
}
}
}
void TOPPASBase::loadPreferences(String filename)
{
//compose default ini file path
String default_ini_file = String(QDir::homePath()) + "/.TOPPAS.ini";
if (filename.empty())
{
filename = default_ini_file;
}
//load preferences, if file exists
if (File::exists(filename))
{
bool error = false;
Param tmp;
ParamXMLFile paramFile;
try // the file might be corrupt
{
paramFile.load(filename, tmp);
}
catch (...)
{
error = true;
}
//apply preferences if they are of the current TOPPAS version
if (!error && tmp.exists("preferences:version") && tmp.getValue("preferences:version").toString() == VersionInfo::getVersion())
{
try
{
setParameters(tmp);
}
catch (Exception::InvalidParameter& /*e*/)
{
error = true;
}
}
else
{
error = true;
}
//set parameters to defaults when something is fishy with the parameters file
if (error)
{
//reset parameters (they will be stored again when TOPPAS quits)
setParameters(Param());
cerr << "The TOPPAS preferences files '" << filename << "' was ignored. It is no longer compatible with this TOPPAS version and will be replaced." << endl;
}
}
else if (filename != default_ini_file)
{
cerr << "Unable to load INI File: '" << filename << "'" << endl;
}
param_.setValue("PreferencesFile", filename);
// set the recent files
recent_files_menu_.setFromParam(param_.copy("preferences:RecentFiles"));
}
void TOPPASBase::savePreferences()
{
// replace recent files
param_.removeAll("preferences:RecentFiles");
param_.insert("preferences:RecentFiles:", recent_files_menu_.getAsParam());
//set version
param_.setValue("preferences:version", VersionInfo::getVersion());
Param save_param = param_.copy("preferences:");
try
{
ParamXMLFile paramFile;
// TODO: if closing multiple TOPPAS instances simultaneously, we might write to this file concurrently
// thus destroying its integrity. Think about using boost filelocks
// and also implement in TOPPView (and other GUI's which write to user directory)
paramFile.store(string(param_.getValue("PreferencesFile")), save_param);
}
catch (Exception::UnableToCreateFile& /*e*/)
{
cerr << "Unable to create INI File: '" << string(param_.getValue("PreferencesFile")) << "'" << endl;
}
}
void TOPPASBase::showAboutDialog()
{
QApplicationTOPP::showAboutDialog(this, "TOPPAS");
}
void TOPPASBase::updateMenu()
{
TOPPASWidget* tw = activeSubWindow_();
TOPPASScene* ts = nullptr;
if (tw)
{
ts = tw->getScene();
}
QList<QAction*> actions = this->findChildren<QAction*>("");
for (int i = 0; i < actions.count(); ++i)
{
QString text = actions[i]->text();
if (text == "&Run (F5)")
{
bool show = false;
if (ts && !(ts->isPipelineRunning()))
{
show = true;
}
actions[i]->setEnabled(show);
}
else if (text == "&Abort")
{
bool show = false;
if (ts && ts->isPipelineRunning())
{
show = true;
}
actions[i]->setEnabled(show);
}
else if (text == "&Include")
{
bool show = ts;
actions[i]->setEnabled(show);
}
else if (text == "&Load resource file")
{
bool show = ts;
actions[i]->setEnabled(show);
}
else if (text == "Save &resource file")
{
bool show = ts;
actions[i]->setEnabled(show);
}
else if (text == "&Save")
{
bool show = ts && ts->wasChanged();
actions[i]->setEnabled(show);
}
else if (text == "Refresh ¶meters")
{
bool show = ts && !(ts->isPipelineRunning());
actions[i]->setEnabled(show);
}
}
if (ts)
{
QString title = tw->windowTitle();
bool asterisk_shown = title.startsWith("*");
bool changed = ts->wasChanged();
if (asterisk_shown ^ changed)
{
title = asterisk_shown ? title.right(title.size() - 1) : QString("*") + title;
tw->setWindowTitle(title);
tab_bar_->setTabText(title);
}
}
}
void TOPPASBase::keyPressEvent(QKeyEvent* e)
{
if (e->key() == Qt::Key_F5)
{
TOPPASWidget* tw = activeSubWindow_();
if (!tw)
{
e->ignore();
return;
}
TOPPASScene* ts = tw->getScene();
ts->runPipeline();
e->accept();
}
}
void TOPPASBase::updateCurrentPath()
{
//do not update if the user disabled this feature.
if (param_.getValue("preferences:default_path_current") != "true")
return;
//reset
current_path_ = param_.getValue("preferences:default_path").toString();
//update if the current layer has a path associated TODO
//if (activeCanvas_() && activeCanvas_()->getLayerCount()!=0 && activeCanvas_()->getCurrentLayer().filename!="")
//{
// current_path_ = File::path(activeCanvas_()->getCurrentLayer().filename);
//}
}
void TOPPASBase::insertNewVertex_(double x, double y, QTreeWidgetItem* item)
{
if (!activeSubWindow_() || !activeSubWindow_()->getScene() || !tools_tree_view_)
{
return;
}
TOPPASScene* scene = activeSubWindow_()->getScene();
QTreeWidgetItem* current_tool = item ? item : tools_tree_view_->currentItem();
String tool_name = String(current_tool->text(0));
TOPPASVertex* tv = nullptr;
if (tool_name == "<Input files>")
{
tv = new TOPPASInputFileListVertex();
}
else if (tool_name == "<Output files>")
{
tv = new TOPPASOutputFileListVertex();
TOPPASOutputFileListVertex* oflv = dynamic_cast<TOPPASOutputFileListVertex*>(tv);
connect(tv, SIGNAL(outputFileWritten(const String &)), this, SLOT(outputVertexFinished(const String &)));
scene->connectOutputVertexSignals((TOPPASOutputVertex*)oflv);
}
else if (tool_name == "<Output folder>")
{
tv = new TOPPASOutputFolderVertex();
TOPPASOutputFolderVertex* oflv = dynamic_cast<TOPPASOutputFolderVertex*>(tv);
connect(tv, SIGNAL(outputFileWritten(const String&)), this, SLOT(outputVertexFinished(const String&)));
scene->connectOutputVertexSignals((TOPPASOutputVertex*)oflv);
}
else if (tool_name == "<Merger>")
{
tv = new TOPPASMergerVertex(true);
connect(tv, SIGNAL(mergeFailed(const QString)), this, SLOT(updateTOPPOutputLog(const QString &)));
}
else if (tool_name == "<Collector>")
{
tv = new TOPPASMergerVertex(false);
connect(tv, SIGNAL(mergeFailed(const QString)), this, SLOT(updateTOPPOutputLog(const QString &)));
}
else if (tool_name == "<Splitter>")
{
tv = new TOPPASSplitterVertex();
}
else // node is a TOPP tool
{
if (current_tool->childCount() > 0)
{
// category or tool name with types is selected (instead of a concrete type)
return;
}
String tool_type;
if (current_tool->parent() != nullptr && current_tool->parent()->parent() != nullptr)
{
// selected item is a type
tool_type = String(current_tool->text(0));
tool_name = String(current_tool->parent()->text(0));
}
else
{
// normal tool which does not have type selected
tool_name = String(current_tool->text(0));
tool_type = "";
}
tv = new TOPPASToolVertex(tool_name, tool_type);
TOPPASToolVertex* ttv = dynamic_cast<TOPPASToolVertex*>(tv);
// check if tool init was successful (i.e. tool was found); TODO: only populate Tool list with available tools so we do not need to check?!
if (!ttv->isToolReady())
{
delete ttv;
return;
}
connect(ttv, SIGNAL(toolStarted()), this, SLOT(toolStarted()));
connect(ttv, SIGNAL(toolFinished()), this, SLOT(toolFinished()));
connect(ttv, SIGNAL(toolCrashed()), this, SLOT(toolCrashed()));
connect(ttv, SIGNAL(toolFailed()), this, SLOT(toolFailed()));
// already done in ToppasScene:
//connect (ttv, SIGNAL(toppOutputReady(const QString&)), this, SLOT(updateTOPPOutputLog(const QString&)));
scene->connectToolVertexSignals(ttv);
}
scene->connectVertexSignals(tv);
scene->addVertex(tv);
tv->setPos(x, y);
tv->setZValue(z_value_);
z_value_ += 0.000001;
scene->topoSort(false);
scene->setChanged(true);
}
void TOPPASBase::runPipeline()
{
TOPPASWidget* w = activeSubWindow_();
if (w)
{
w->getScene()->runPipeline();
}
}
void TOPPASBase::abortPipeline()
{
TOPPASWidget* w = activeSubWindow_();
if (w)
{
w->getScene()->abortPipeline();
}
updateMenu();
}
void TOPPASBase::toolStarted()
{
TOPPASToolVertex* tv = dynamic_cast<TOPPASToolVertex*>(QObject::sender());
if (tv)
{
String text = tv->getName();
String type = tv->getType();
if (!type.empty())
{
text += " (" + type + ")";
}
text += " of node #" + String(tv->getTopoNr()) + " started. Processing ...";
log_->appendNewHeader(LogWindow::LogState::NOTICE, text, "");
}
updateMenu();
}
void TOPPASBase::toolFinished()
{
TOPPASToolVertex* tv = dynamic_cast<TOPPASToolVertex*>(QObject::sender());
if (tv)
{
String text = tv->getName();
String type = tv->getType();
if (!type.empty())
{
text += " (" + type + ")";
}
text += " finished!";
log_->appendNewHeader(LogWindow::LogState::NOTICE, text, "");
}
updateMenu();
}
void TOPPASBase::toolCrashed()
{
TOPPASToolVertex* tv = dynamic_cast<TOPPASToolVertex*>(QObject::sender());
if (tv)
{
String text = tv->getName();
String type = tv->getType();
if (!type.empty())
{
text += " (" + type + ")";
}
text += " crashed!";
log_->appendNewHeader(LogWindow::LogState::CRITICAL, text, "");
}
updateMenu();
}
void TOPPASBase::toolFailed()
{
TOPPASToolVertex* tv = dynamic_cast<TOPPASToolVertex*>(QObject::sender());
if (tv)
{
String text = tv->getName();
String type = tv->getType();
if (!type.empty())
{
text += " (" + type + ")";
}
text += " failed!";
log_->appendNewHeader(LogWindow::LogState::CRITICAL, text, "");
}
updateMenu();
}
void TOPPASBase::outputVertexFinished(const String& file)
{
String text = "Output file '" + file + "' written.";
log_->appendNewHeader(LogWindow::LogState::NOTICE, text, "");
}
void TOPPASBase::updateTOPPOutputLog(const QString& out)
{
const QString& text = out; // shortened version for now (if we reintroduce simultaneous tool execution,
// we need to rethink this (probably only trigger this slot when tool 100% finished)
//show log if there is output
dynamic_cast<QWidget*>(log_->parent())->show();
//update log_
log_->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor); // move cursor to end, since text is inserted at cursor
log_->insertPlainText(text);
}
void TOPPASBase::showPipelineFinishedLogMessage()
{
log_->appendNewHeader(LogWindow::LogState::NOTICE, "Entire pipeline execution finished!", "");
}
void TOPPASBase::insertNewVertexInCenter_(QTreeWidgetItem* item)
{
if (!activeSubWindow_() || !activeSubWindow_()->getScene() || !tools_tree_view_ || !tools_tree_view_->currentItem())
{
return;
}
QPointF insert_pos = activeSubWindow_()->mapToScene(QPoint((activeSubWindow_()->width() / 2.0) + (qreal)(5 * node_offset_), (activeSubWindow_()->height() / 2.0) + (qreal)(5 * node_offset_)));
insertNewVertex_(insert_pos.x(), insert_pos.y(), item);
node_offset_ = (node_offset_ + 1) % 10;
}
void TOPPASBase::saveToClipboard(TOPPASScene* scene)
{
if (clipboard_scene_ != nullptr)
{
delete clipboard_scene_;
clipboard_scene_ = nullptr;
}
clipboard_scene_ = scene;
}
void TOPPASBase::sendClipboardContent()
{
TOPPASScene* sndr = dynamic_cast<TOPPASScene*>(QObject::sender());
if (sndr != nullptr)
{
sndr->setClipboard(clipboard_scene_);
}
}
void TOPPASBase::refreshParameters()
{
TOPPASWidget* w = activeSubWindow_();
QString file_name = TOPPASBase::refreshPipelineParameters(w, current_path_.toQString());
if (file_name != "")
{
tab_bar_->setTabText(File::basename(file_name).toQString());
}
}
// static
QString TOPPASBase::refreshPipelineParameters(TOPPASWidget* tw, QString current_path)
{
TOPPASScene* ts = nullptr;
if (tw)
{
ts = tw->getScene();
}
if (!ts)
{
return "";
}
TOPPASScene::RefreshStatus st = ts->refreshParameters();
if (st == TOPPASScene::ST_REFRESH_NOCHANGE)
{
QMessageBox::information(tw, tr("Nothing to be done"),
tr("The parameters of the tools used in this workflow have not changed."));
return "";
}
ts->setChanged(true);
ts->updateEdgeColors();
if (st == TOPPASScene::ST_REFRESH_CHANGEINVALID)
{
QMessageBox::information(tw, "Parameters updated!",
"The resulting pipeline is now invalid. Probably some input or output parameters were removed or added. Please repair!",
QMessageBox::Ok);
return "";
}
else if (st == TOPPASScene::ST_REFRESH_REMAINSINVALID)
{
QMessageBox::information(tw, "Parameters updated!",
"The resulting pipeline remains invalid (not runnable). Maybe some input files or even edges are missing. Please repair!",
QMessageBox::Ok);
return "";
}
int ret = QMessageBox::information(tw, "Parameters updated!",
"The parameters of some tools in this workflow have changed. Do you want to save these changes now?",
QMessageBox::Save | QMessageBox::Cancel);
if (ret == QMessageBox::Save)
{
QString file_name = TOPPASBase::savePipelineAs(tw, std::move(current_path));
return file_name;
}
return "";
}
void TOPPASBase::openFilesInTOPPView(QStringList files)
{
if (files.empty()) return;
if (files.size() > 1)
{
// ask user how to open multiple files
QMessageBox msgBox(
QMessageBox::Question,
tr("Open files with overlay?"),
tr("How do you want to open the output files?"),
QMessageBox::Cancel);
QPushButton* overlayButton = msgBox.addButton(tr("&Single Tab - Overlay"), QMessageBox::YesRole);
msgBox.addButton(tr("&Separate tabs"), QMessageBox::NoRole);
msgBox.exec();
if (msgBox.clickedButton() == nullptr) return; // Escape was pressed
if (msgBox.clickedButton() == overlayButton)
{ // put a '+' in between the files (TOPPView's command line will interpret this as overlay)
files = files.join("#SpLiT_sTrInG#+#SpLiT_sTrInG#").split("#SpLiT_sTrInG#", Qt::SkipEmptyParts);
}
}
if (!GUIHelpers::startTOPPView(files))
{
QMessageBox::warning(this, "Could not start TOPPView", "TOPPView failed to start. Please see the commandline for details.");
}
}
void TOPPASBase::openToppasFile(const QString& filename)
{
addTOPPASFile(String(filename));
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/SwathWizardBase.cpp | .cpp | 2,369 | 89 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/APPLICATIONS/SwathWizardBase.h>
#include <ui_SwathWizardBase.h>
#include <OpenMS/APPLICATIONS/ToolHandler.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
#include <OpenMS/VISUAL/DIALOGS/SwathTabWidget.h>
//Qt
#include <QtCore/QDir>
#include <QDesktopServices>
#include <QMessageBox>
#include <QSettings>
using namespace std;
using namespace OpenMS;
namespace OpenMS
{
using namespace Internal;
SwathWizardBase::SwathWizardBase(QWidget* parent) :
QMainWindow(parent),
DefaultParamHandler("SwathWizardBase"),
//clipboard_scene_(nullptr),
ui(new Ui::SwathWizardBase)
{
ui->setupUi(this);
QSettings settings("OpenMS", "SwathWizard");
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("windowState").toByteArray());
setWindowTitle("SwathWizard");
setWindowIcon(QIcon(":/SwathWizard.png"));
SwathTabWidget* cw_swath = new SwathTabWidget(this);
setCentralWidget(cw_swath);
}
SwathWizardBase::~SwathWizardBase()
{
delete ui;
}
void SwathWizardBase::showAboutDialog()
{
QApplicationTOPP::showAboutDialog(this, "SwathWizard");
}
void OpenMS::SwathWizardBase::on_actionExit_triggered()
{
QApplicationTOPP::exit();
}
void OpenMS::SwathWizardBase::on_actionVisit_OpenSwath_homepage_triggered()
{
const char* url = "http://openswath.org";
if (!QDesktopServices::openUrl(QUrl(url)))
{
QMessageBox::warning(nullptr, "Cannot open browser. Please check your default browser settings.", QString(url));
}
}
void OpenMS::SwathWizardBase::on_actionReport_new_issue_triggered()
{
const char* url = "https://github.com/OpenMS/OpenMS/issues";
if (!QDesktopServices::openUrl(QUrl(url)))
{
QMessageBox::warning(nullptr, "Cannot open browser. Please check your default browser settings.", QString(url));
}
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/INIFileEditorWindow.cpp | .cpp | 4,934 | 178 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/APPLICATIONS/INIFileEditorWindow.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtWidgets/QToolBar>
#include <QtCore/QString>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QCheckBox>
#include <QCloseEvent>
using namespace std;
namespace OpenMS
{
INIFileEditorWindow::INIFileEditorWindow(QWidget* parent) :
QMainWindow(parent),
current_path_(".")
{
setWindowTitle("INIFileEditor");
setWindowIcon(QIcon(":/INIFileEditor.png"));
//create central widget and layout
QWidget* central_widget = new QWidget;
setCentralWidget(central_widget);
QGridLayout* layout = new QGridLayout(central_widget);
//create advanced check box and ParamEditor and connect them
editor_ = new ParamEditor(central_widget);
layout->addWidget(editor_, 0, 0, 1, 2);
QMenu* file = new QMenu("&File", this);
menuBar()->addMenu(file);
file->addAction("&Open", this, &INIFileEditorWindow::openFile)->setShortcut(Qt::CTRL | Qt::Key_O);
file->addSeparator();
file->addAction("&Save", this, &INIFileEditorWindow::saveFile)->setShortcut(Qt::CTRL | Qt::Key_S);
file->addAction("Save &As", this, SLOT(saveFileAs()));
file->addSeparator();
file->addAction("&Quit", this, SLOT(close()));
// we connect the "changes state"(changes made/no changes) signal from the ParamEditor to the window title updating slot
connect(editor_, SIGNAL(modified(bool)), this, SLOT(updateWindowTitle(bool)));
setMinimumSize(600, 600);
}
bool INIFileEditorWindow::openFile(const String& filename)
{
if (filename.empty())
{
filename_ = QFileDialog::getOpenFileName(this, tr("Open ini file"), current_path_.toQString(), tr("ini files (*.ini);; all files (*.*)"));
}
else
{
filename_ = filename.c_str();
}
if (!filename_.isEmpty())
{
if (File::readable(filename_.toStdString()))
{
param_.clear();
ParamXMLFile paramFile;
try
{
paramFile.load(filename_.toStdString(), param_);
editor_->load(param_);
updateWindowTitle(editor_->isModified());
return true;
}
catch (Exception::BaseException& e)
{
OPENMS_LOG_ERROR << "Error while parsing file '" << filename_.toStdString() << "'\n";
OPENMS_LOG_ERROR << e << "\n";
}
}
QMessageBox::critical(this, "Error opening file", ("The file '" + filename_.toStdString() + "' does not exist, is not readable or not a proper INI file!").c_str());
}
return false;
}
bool INIFileEditorWindow::saveFile()
{
if (filename_.isEmpty())
{
return false;
}
editor_->store();
ParamXMLFile paramFile;
paramFile.store(filename_.toStdString(), param_);
updateWindowTitle(editor_->isModified());
return true;
}
bool INIFileEditorWindow::saveFileAs()
{
filename_ = QFileDialog::getSaveFileName(this, tr("Save ini file"), current_path_.toQString(), tr("ini files (*.ini)"));
if (!filename_.isEmpty())
{
if (!filename_.endsWith(".ini"))
filename_.append(".ini");
editor_->store();
ParamXMLFile paramFile;
paramFile.store(filename_.toStdString(), param_);
updateWindowTitle(editor_->isModified());
return true;
}
return false;
}
void INIFileEditorWindow::closeEvent(QCloseEvent* event)
{
if (editor_->isModified())
{
QMessageBox::StandardButton result = QMessageBox::question(this, "Save?", "Do you want to save your changes?", QMessageBox::Ok | QMessageBox::Cancel | QMessageBox::Discard);
if (result == QMessageBox::Ok)
{
if (saveFile())
{
event->accept();
}
else
{
event->ignore();
}
}
else if (result == QMessageBox::Cancel)
{
event->ignore();
}
else
{
event->accept();
}
}
else
{
event->accept();
}
}
void INIFileEditorWindow::updateWindowTitle(bool update)
{
//update window title
if (update)
{
setWindowTitle((File::basename(filename_) + " * - INIFileEditor").toQString());
}
else
{
setWindowTitle((File::basename(filename_) + " - INIFileEditor").toQString());
}
//update last path as well
current_path_ = File::path(filename_);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/GUITOOLS/INIFileEditor.cpp | .cpp | 3,478 | 118 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/APPLICATIONS/INIFileEditorWindow.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
#if !defined(__APPLE__)
// Qt
#include <QtWidgets/QStyleFactory>
#endif
#ifdef OPENMS_WINDOWSPLATFORM
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0501 // Win XP (and above)
# endif
# include <Windows.h>
#endif
using namespace OpenMS;
using namespace std;
/**
@page TOPP_INIFileEditor INIFileEditor
@brief Can be used to visually edit INI files of TOPP tools.
The values can be edited by double-clicking or pressing F2.
The documentation of each value is shown in the text area on the bottom of the widget.
@image html INIFileEditor.png
*/
int main(int argc, const char** argv)
{
#ifdef OPENMS_WINDOWSPLATFORM
qputenv("QT_QPA_PLATFORM", "windows:darkmode=0"); // disable dark mode on Windows, since our buttons etc are not designed for it
#endif
std::map<std::string, std::string> options, flags, option_lists;
options["-print"] = "print";
flags["--help"] = "help";
Param param;
param.parseCommandLine(argc, argv, options, flags, option_lists);
//catch command line errors
if (param.exists("help") //help requested
|| argc > 3 //too many arguments
|| (argc == 3 && !param.exists("print")) //three argument but no -print
|| (param.exists("print") && param.getValue("print") == "") //-print but no file given
)
{
cerr << endl
<< "INIFileEditor -- An editor for OpenMS configuration files." << endl
<< endl
<< "Usage:" << endl
<< " INIFileEditor [options] [file]" << endl
<< endl
<< "Options are:" << endl
<< " --help Shows this help and exits" << endl
<< " -print <file> Prints the content of the file to the command line and exits" << endl
<< endl;
return 0;
}
//print a ini file as text
if (param.exists("print"))
{
Param data;
ParamXMLFile paramFile;
try
{
paramFile.load(param.getValue("print").toString(), data);
for (Param::ParamIterator it = data.begin(); it != data.end(); ++it)
{
cout << it.getName() << " = " << it->value << endl;
}
}
catch (Exception::BaseException& e)
{
OPENMS_LOG_ERROR << "Error while parsing file '" << param.getValue("print") << "'\n";
OPENMS_LOG_ERROR << e << "\n";
}
return 0;
}
//Create window
QApplicationTOPP app(argc, const_cast<char**>(argv));
INIFileEditorWindow editor_window;
//Open passed file
if (argc == 2)
{
//cout << "OPEN: " << argv[1] << endl;
editor_window.openFile(argv[1]);
}
#ifdef OPENMS_WINDOWSPLATFORM
FreeConsole(); // get rid of console window at this point (we will not see any console output from this point on)
AttachConsole(-1); // if the parent is a console, reattach to it - so we can see debug output - a normal user will usually not use cmd.exe to start a GUI)
#endif
editor_window.show();
return app.exec();
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/GUITOOLS/SwathWizard.cpp | .cpp | 7,507 | 207 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
/**
@page TOPP_SwathWizard SwathWizard
@brief An assistant for Swath analysis.
The Wizard takes the user through the whole analysis pipeline for SWATH proteomics data analysis,
i.e. the @ref TOPP_OpenSwathWorkflow tool, including downstream tools such
as <a href="https://github.com/PyProphet/pyprophet" target="_blank">pyProphet</a> and
the <a href="https://github.com/msproteomicstools/msproteomicstools" target="_blank">TRIC alignment</a> tool.
Since the downstream tools require Python and the respective modules, the Wizard will check their proper
installation status and warn the user if a component is missing.
Users can enter the required input data (mzML MS/MS data, configuration files) in dedicated fields, usually by drag'n'droping files from the
operating systems' file explorer (Explorer, Nautilus, Finder...).
The output of the Wizard is both the intermediate files from OpenSWATH (e.g. the XIC data in .sqMass format) and the
tab-separated table format (.tsv) from pyProphet and TRIC.
This is how the wizard looks like:
@image html SwathWizard.png
Schematic of the internal data flow (all tools are called by SwathWizard in the background):
*/
#ifdef OPENMS_HASDOXYGENDOT
/*
@dot
digraph wizard_workflow
{
node [ style="solid,filled", color=black, fillcolor=grey60, width=1.0, fixedsize=false, shape=square, fontname=Helvetica ];
edge [ arrowhead="open", style="solid" ];
rankdir="LR";
splines=ortho;
subgraph cluster_SwathWizard {
fontsize=26;
style=filled;
color=grey90;
topp_ows -> osw [ label="out_osw" ];
topp_ows -> sqMass [ label="out_chrom" ];
osw -> pyProphet;
pyProphet -> osw_inter;
osw_inter -> pyProphet;
pyProphet -> tsv;
tsv -> TRIC;
label = "SwathWizard";
}
mzml [ label="Swath mzML file(s)\n(.mzML | XML)" shape=oval fillcolor=white group=1];
iRTlib [ label="iRT library file\n(.pqp | sqlLite)" shape=oval fillcolor=white group=1];
transitionLib [ label="Swath library file\n(.pqp | sqlLite)" shape=oval fillcolor=white group=1];
topp_ows [ label="OpenSwath-\nWorkflow" URL="\ref OpenMS::OpenSwathWorkflow" group=1];
osw [ label="ID file(s)\n(.osw | sqlLite)" shape=oval fillcolor=white group=1];
sqMass [ label="Raw XIC data file(s)\n(.sqMass | sqlLite)" shape=oval fillcolor=white group=1];
mzml -> topp_ows [ xlabel = "in"];
iRTlib -> topp_ows[ xlabel = "tr_irt"];
transitionLib -> topp_ows[ xlabel = "tr"];
pyProphet [ label="pyProphet (FDR)" URL="https://github.com/PyProphet/pyprophet" group=2];
osw_inter [ label="annotated ID file(s)\n(.osw | sqlLite)" shape=oval fillcolor=white group=2];
tsv [ label="ID file(s)\n(.tsv | text)" shape=oval fillcolor=white group=2];
TRIC [ label="TRIC\n(TRansfer of\nIdentification\nConfidence)" URL="https://github.com/msproteomicstools/msproteomicstools/blob/master/TRIC-README.md" group=3];
tsv_aligned [ label="Aligned IDs file\n(.tsv | text)" shape=oval fillcolor=white group=3];
tsv_aligned_matrix [ label="Aligned Matrix IDs file\n(.tsv | text)" shape=oval fillcolor=white group=3];
TRIC -> tsv_aligned;
TRIC -> tsv_aligned_matrix;
topp_tv [ label = "TOPPView", group=4]
osw_inter -> topp_tv;
sqMass -> topp_tv;
}
@enddot
*/
#endif
/**
A recommended test data for the Wizard is the
<a href="https://db.systemsbiology.net/sbeams/cgi/PeptideAtlas/PASS_View?identifier=PASS00779" target="_blank">PASS00779</a>
dataset.
*/
//QT
#include <QApplication>
#include <QtWidgets/QSplashScreen>
//OpenMS
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/VISUAL/APPLICATIONS/SwathWizardBase.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
//STL
#include <iostream>
#include <map>
#include <vector>
#ifdef OPENMS_WINDOWSPLATFORM
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0501 // Win XP (and above)
# endif
# include <Windows.h>
#endif
using namespace OpenMS;
using namespace std;
//-------------------------------------------------------------
// command line name of this tool
//-------------------------------------------------------------
const char* tool_name = "SwathWizard";
//-------------------------------------------------------------
// description of the usage of this TOPP tool
//-------------------------------------------------------------
void print_usage(Logger::LogStream& stream = getGlobalLogInfo())
{
stream << "\n"
<< tool_name << " -- An assistant for Swath-Analysis." << "\n"
<< "\n"
<< "Usage:" << "\n"
<< " " << tool_name << " [options] [files]" << "\n"
<< "\n"
<< "Options are:" << "\n"
<< " --help Shows this help" << "\n"
<< " --debug Enables debug messages\n"
<< " -ini <File> Sets the INI file (default: ~/.SwathWizard.ini)" << "\n"
<< endl;
}
int main(int argc, const char** argv)
{
#ifdef OPENMS_WINDOWSPLATFORM
qputenv("QT_QPA_PLATFORM", "windows:darkmode=0"); // disable dark mode on Windows, since our buttons etc are not designed for it
#endif
// list of all the valid options
std::map<std::string, std::string> valid_options, valid_flags, option_lists;
valid_flags["--help"] = "help";
valid_flags["--debug"] = "debug";
valid_options["-ini"] = "ini";
Param param;
param.parseCommandLine(argc, argv, valid_options, valid_flags, option_lists);
// '--help' given
if (param.exists("help"))
{
print_usage();
return 0;
}
// '-debug' given
if (param.exists("debug"))
{
OPENMS_LOG_INFO << "Debug flag provided. Enabling 'OPENMS_LOG_DEBUG' ..." << std::endl;
getGlobalLogDebug().insert(cout); // allows to use OPENMS_LOG_DEBUG << "something" << std::endl;
}
// test if unknown options were given
if (param.exists("unknown"))
{
// if packed as Mac OS X bundle it will get a -psn_.. parameter by default from the OS
// if this is the only unknown option it will be ignored .. maybe this should be solved directly
// in Param.h
if (!(String(param.getValue("unknown").toString()).hasSubstring("-psn") && !String(param.getValue("unknown").toString()).hasSubstring(", ")))
{
OPENMS_LOG_ERROR << "Unknown option(s) '" << param.getValue("unknown").toString() << "' given. Aborting!" << endl;
print_usage(getGlobalLogError());
return 1;
}
}
QApplicationTOPP a(argc, const_cast<char**>(argv));
a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
SwathWizardBase mw;
mw.show();
if (param.exists("ini"))
{
//mw.loadPreferences((String)param.getValue("ini"));
}
#ifdef OPENMS_WINDOWSPLATFORM
FreeConsole(); // get rid of console window at this point (we will not see any console output from this point on)
AttachConsole(-1); // if the parent is a console, reattach to it - so we can see debug output - a normal user will usually not use cmd.exe to start a GUI)
#endif
int result = a.exec();
return result;
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/GUITOOLS/TOPPView.cpp | .cpp | 8,763 | 234 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
/**
@page TOPP_TOPPView TOPPView
TOPPView is a viewer for MS and HPLC-MS data. It can be used to inspect files in mzML, mzData, mzXML
and several other file formats. It also supports viewing data from an %OpenMS database.
The following figure shows two instances of TOPPView displaying a HPLC-MS map and a MS raw spectrum:
@image html TOPPView.png
More information about TOPPView can be found on the OpenMS ReadTheDocs
page: https://openms.readthedocs.io/en/latest/openms-applications-and-tools/visualize-with-openms.html
<B>The command line parameters of this tool are:</B>
@verbinclude TOPP_TOPPView.cli
Note: By default, TOPPView scans for novel TOPP tools if there has been a version update. To force a rescan you
can pass the --force flag. To skip the scan for tools, you can pass the --skip_tool_scan flag.
*/
//QT
#include <QtWidgets/QSplashScreen>
#include <QMessageBox>
//OpenMS
#include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
#include <OpenMS/SYSTEM/StopWatch.h>
//STL
#include <iostream>
#include <map>
#include <vector>
#ifdef OPENMS_WINDOWSPLATFORM
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0501 // Win XP (and above)
# endif
# include <Windows.h>
#endif
using namespace OpenMS;
using namespace std;
//-------------------------------------------------------------
// command line name of this tool
//-------------------------------------------------------------
const char* tool_name = "TOPPView";
//-------------------------------------------------------------
// description of the usage of this TOPP tool
//-------------------------------------------------------------
void print_usage()
{
cerr << endl
<< tool_name << " -- A viewer for mass spectrometry data." << "\n"
<< "\n"
<< "Usage:" << "\n"
<< " " << tool_name << " [options] [files]" << "\n"
<< "\n"
<< "Options are:" << "\n"
<< " --help Shows this help" << "\n"
<< " -ini <File> Sets the INI file (default: ~/.TOPPView.ini)" << "\n"
<< " --force Forces scan for new tools" << "\n"
<< " --skip_tool_scan Skips scan for new tools" << "\n"
<< "\n"
<< "Hints:" << "\n"
<< " - To open several files in one window put a '+' in between the files." << "\n"
<< " - '@bw' after a map file displays the dots in a white to black gradient." << "\n"
<< " - '@bg' after a map file displays the dots in a grey to black gradient." << "\n"
<< " - '@b' after a map file displays the dots in black." << "\n"
<< " - '@r' after a map file displays the dots in red." << "\n"
<< " - '@g' after a map file displays the dots in green." << "\n"
<< " - '@m' after a map file displays the dots in magenta." << "\n"
<< " - Example: '" << tool_name << " 1.mzML + 2.mzML @bw + 3.mzML @bg'" << "\n"
<< endl;
}
int main(int argc, const char** argv)
{
#ifdef OPENMS_WINDOWSPLATFORM
qputenv("QT_QPA_PLATFORM", "windows:darkmode=0"); // disable dark mode on Windows, since our buttons etc are not designed for it
#endif
//list of all the valid options
std::map<std::string, std::string> valid_options, valid_flags, option_lists;
valid_flags["--help"] = "help";
valid_flags["--force"] = "force";
valid_flags["--skip_tool_scan"] = "skip_tool_scan";
valid_flags["--debug"] = "debug";
valid_options["-ini"] = "ini";
Param param;
param.parseCommandLine(argc, argv, valid_options, valid_flags, option_lists);
// '--help' given
if (param.exists("help"))
{
print_usage();
return 0;
}
// test if unknown options were given
if (param.exists("unknown"))
{
// if TOPPView is packed as Mac OS X bundle it will get a -psn_.. parameter by default from the OS
// if this is the only unknown option it will be ignored .. maybe this should be solved directly
// in Param.h
if (!(String(param.getValue("unknown").toString()).hasSubstring("-psn") && !String(param.getValue("unknown").toString()).hasSubstring(", ")))
{
cout << "Unknown option(s) '" << param.getValue("unknown").toString() << "' given. Aborting!" << endl;
print_usage();
return 1;
}
}
try
{
#if defined(__APPLE__)
// see https://bugreports.qt.io/browse/QTBUG-104871
// if you link to QtWebEngine and the corresponding macros are enabled, it will
// try to default to OpenGL 4.1 on macOS (for hardware acceleration of WebGL in Chromium, which we do not need yet)
// but our OpenGL code for 3D View is written in OpenGL 2.x.
// Now we force 2.1 which is also available on all? Macs.
QSurfaceFormat format;
format.setVersion(2, 1); // the default is 2, 0
QSurfaceFormat::setDefaultFormat(format); // should be done before creating a QApplication
#endif
QApplicationTOPP a(argc, const_cast<char**>(argv));
a.connect(&a, &QApplicationTOPP::lastWindowClosed, &a, &QApplicationTOPP::quit);
TOPPViewBase::TOOL_SCAN mode = TOPPViewBase::TOOL_SCAN::SCAN_IF_NEWER_VERSION;
if (param.exists("force"))
{
mode = TOPPViewBase::TOOL_SCAN::FORCE_SCAN;
}
else if (param.exists("skip_tool_scan"))
{
mode = TOPPViewBase::TOOL_SCAN::SKIP_SCAN;
}
TOPPViewBase::VERBOSITY verbosity = TOPPViewBase::VERBOSITY::DEFAULT;
if (param.exists("debug"))
{
verbosity = TOPPViewBase::VERBOSITY::VERBOSE;
}
TOPPViewBase tb(mode, verbosity);
a.connect(&a, &QApplicationTOPP::fileOpen, &tb, &TOPPViewBase::openFile);
tb.show();
// Create the splashscreen that is displayed while the application loads (version is drawn dynamically)
QPixmap qpm(":/TOPPView_Splashscreen.png");
QPainter pt_ver(&qpm);
pt_ver.setFont(QFont("Helvetica [Cronyx]", 15, 2, true));
pt_ver.setPen(Qt::black);
// draw version number dynamcially on top left corner
pt_ver.drawText(5, 5 + 15, VersionInfo::getVersion().toQString());
QSplashScreen splash_screen(qpm);
splash_screen.show();
QApplication::processEvents();
StopWatch stop_watch;
stop_watch.start();
if (param.exists("ini"))
{
tb.loadPreferences(param.getValue("ini").toString());
}
//load command line files
if (param.exists("misc"))
{
tb.loadFiles(ListUtils::toStringList<std::string>(param.getValue("misc")), &splash_screen);
}
// We are about to show the application.
// Proper time to remove the splashscreen, if at least 3 seconds have passed...
while (stop_watch.getClockTime() < 3.0) /*wait*/
{
}
stop_watch.stop();
splash_screen.close();
#ifdef OPENMS_WINDOWSPLATFORM
FreeConsole(); // get rid of console window at this point (we will not see any console output from this point on)
AttachConsole(-1); // if the parent is a console, reattach to it - so we can see debug output - a normal user will usually not use cmd.exe to start a GUI)
#endif
return a.exec();
}
//######################## ERROR HANDLING #################################
catch (Exception::UnableToCreateFile& e)
{
cout << String("Error: Unable to write file (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::FileNotFound& e)
{
cout << String("Error: File not found (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::FileNotReadable& e)
{
cout << String("Error: File not readable (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::FileEmpty& e)
{
cout << String("Error: File empty (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::ParseError& e)
{
cout << String("Error: Unable to read file (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::InvalidValue& e)
{
cout << String("Error: Invalid value (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::BaseException& e)
{
cout << String("Error: Unexpected error (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
return 1;
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/GUITOOLS/TOPPAS.cpp | .cpp | 7,983 | 228 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
/**
@page TOPP_TOPPAS TOPPAS
@brief An assistant for GUI-driven TOPP workflow design.
TOPPAS allows to create, edit, open, save, and run TOPP workflows. Pipelines
can be created conveniently in a GUI by means of mouse interactions. The
parameters of all involved tools can be edited within the application
and are also saved as part of the pipeline definition in the @em .toppas file.
Furthermore, TOPPAS interactively performs validity checks during the pipeline
editing process, in order to make it more difficult to create an invalid workflow.
Once set up and saved, a workflow can also be run without the GUI using
the @em ExecutePipeline TOPP tool.
The following figure shows a simple example pipeline that has just been created
and executed successfully:
@image html TOPPAS_simple_example.png
More information about TOPPAS can be found in the @ref TOPPAS_tutorial.
<B>The command line parameters of this tool are:</B>
@verbinclude TOPP_TOPPAS.cli
*/
//QT
#include <QApplication>
#include <QPainter>
#include <QtWidgets/QSplashScreen>
#include <QtCore/QDir>
//OpenMS
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/SYSTEM/StopWatch.h>
#include <OpenMS/VISUAL/APPLICATIONS/TOPPASBase.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
//STL
#include <iostream>
#include <map>
#include <vector>
#ifdef OPENMS_WINDOWSPLATFORM
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0501 // Win XP (and above)
# endif
# include <Windows.h>
#endif
using namespace OpenMS;
using namespace std;
//-------------------------------------------------------------
// command line name of this tool
//-------------------------------------------------------------
const char* tool_name = "TOPPAS";
//-------------------------------------------------------------
// description of the usage of this TOPP tool
//-------------------------------------------------------------
void print_usage(Logger::LogStream& stream = getGlobalLogInfo())
{
stream << "\n"
<< tool_name << " -- An assistant for GUI-driven TOPP workflow design." << "\n"
<< "\n"
<< "Usage:" << "\n"
<< " " << tool_name << " [options] [.toppas files]" << "\n"
<< "\n"
<< "Options are:" << "\n"
<< " --help Shows this help" << "\n"
<< " --debug Enables debug messages\n"
<< " -ini <File> Sets the INI file (default: ~/.TOPPAS.ini)" << "\n"
<< endl;
}
int main(int argc, const char** argv)
{
#ifdef OPENMS_WINDOWSPLATFORM
qputenv("QT_QPA_PLATFORM", "windows:darkmode=0"); // disable dark mode on Windows, since our buttons etc are not designed for it
#endif
// list of all the valid options
std::map<std::string, std::string> valid_options, valid_flags, option_lists;
valid_flags["--help"] = "help";
valid_flags["--debug"] = "debug";
valid_options["-ini"] = "ini";
// invalid, but keep for now in order to inform users where to find this functionality now
valid_options["-execute"] = "execute";
valid_options["-out_dir"] = "out_dir";
Param param;
param.parseCommandLine(argc, argv, valid_options, valid_flags, option_lists);
// '--help' given
if (param.exists("help"))
{
print_usage();
return 0;
}
// '-debug' given
if (param.exists("debug"))
{
OPENMS_LOG_INFO << "Debug flag provided. Enabling 'OPENMS_LOG_DEBUG' ..." << std::endl;
getGlobalLogDebug().insert(cout); // allows to use OPENMS_LOG_DEBUG << "something" << std::endl;
}
// test if unknown options were given
if (param.exists("unknown"))
{
// if TOPPAS is packed as Mac OS X bundle it will get a -psn_.. parameter by default from the OS
// if this is the only unknown option it will be ignored .. maybe this should be solved directly
// in Param.h
if (!(String(param.getValue("unknown").toString()).hasSubstring("-psn") && !String(param.getValue("unknown").toString()).hasSubstring(", ")))
{
OPENMS_LOG_ERROR << "Unknown option(s) '" << param.getValue("unknown").toString() << "' given. Aborting!" << endl;
print_usage(getGlobalLogError());
return 1;
}
}
try
{
if (param.exists("execute") || param.exists("out_dir"))
{
OPENMS_LOG_ERROR << "The parameters '-execute' and '-out_dir' are not valid anymore. This functionality has been moved to the ExecutePipeline tool." << endl;
return 1;
}
QApplicationTOPP a(argc, const_cast<char**>(argv));
a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
TOPPASBase mw;
mw.show();
a.connect(&a, &QApplicationTOPP::fileOpen, &mw, &TOPPASBase::openToppasFile);
// Create the splashscreen that is displayed while the application loads (version is drawn dynamically)
QPixmap qpm(":/TOPPAS_Splashscreen.png");
QPainter pt_ver(&qpm);
pt_ver.setFont(QFont("Helvetica [Cronyx]", 15, 2, true));
pt_ver.setPen(Qt::black);
// draw version number dynamcially on top left corner
pt_ver.drawText(5, 5+15, VersionInfo::getVersion().toQString());
QSplashScreen splash_screen(qpm);
splash_screen.show();
QApplication::processEvents();
StopWatch stop_watch;
stop_watch.start();
if (param.exists("ini"))
{
mw.loadPreferences(param.getValue("ini").toString());
}
if (param.exists("misc"))
{
mw.loadFiles(ListUtils::toStringList<std::string>(param.getValue("misc")), &splash_screen);
}
else
{
mw.newPipeline();
}
// We are about to show the application.
// Proper time to remove the splashscreen, if at least 3 seconds have passed...
while (stop_watch.getClockTime() < 3.0) /*wait*/
{
}
stop_watch.stop();
splash_screen.close();
#ifdef OPENMS_WINDOWSPLATFORM
FreeConsole(); // get rid of console window at this point (we will not see any console output from this point on)
AttachConsole(-1); // if the parent is a console, reattach to it - so we can see debug output - a normal user will usually not use cmd.exe to start a GUI)
#endif
int result = a.exec();
return result;
}
//######################## ERROR HANDLING #################################
catch (Exception::UnableToCreateFile& e)
{
cout << String("Error: Unable to write file (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::FileNotFound& e)
{
cout << String("Error: File not found (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::FileNotReadable& e)
{
cout << String("Error: File not readable (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::FileEmpty& e)
{
cout << String("Error: File empty (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::ParseError& e)
{
cout << String("Error: Unable to read file (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::InvalidValue& e)
{
cout << String("Error: Invalid value (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
catch (Exception::BaseException& e)
{
cout << String("Error: Unexpected error (") << e.what() << ")" << endl << "Code location: " << e.getFile() << ":" << e.getLine() << endl;
}
return 1;
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/GUITOOLS/FLASHDeconvWizard.cpp | .cpp | 4,521 | 130 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Jihyung Kim $
// $Authors: Jihyung Kim $
// --------------------------------------------------------------------------
/**
@page TOPP_FLASHDeconvWizard FLASHDeconvWizard
@brief An assistant for FLASHDeconv execution.
The implementation of FLASHDeconvWizard is heavily inspired by the @ref TOPP_SwathWizard .
The Wizard helps the user to run @ref TOPP_FLASHDeconv for Top-down proteomics analysis.
Users can enter the required input data (mzML MS/MS data) in dedicated fields, usually by drag'n'droping files from the
operating systems' file explorer (Explorer, Nautilus, Finder...).
The main output of the Wizard is deconvolved feature files (*.tsv) from FLASHDeconv. Optional output files are as follows:
- deconvoluted MSn spectra files (*.tsv)
- deconvoluted mzML spectra file (*.mzML)
- Isobarically quantified deconvoluted MS2 in tsv format (*_quant.tsv)
- deconvoluted MSn spectra files in TopFD output format (*.msalign)
- deconvoluted MSn feature files in TopFD output format (*.feature)
*/
// QT
#include <QApplication>
// OpenMS
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/VISUAL/APPLICATIONS/FLASHDeconvWizardBase.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
// STL
#include <iostream>
#include <map>
#ifdef OPENMS_WINDOWSPLATFORM
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // Win XP (and above)
#endif
#include <Windows.h>
#endif
using namespace OpenMS;
using namespace std;
//-------------------------------------------------------------
// command line name of this tool
//-------------------------------------------------------------
const char* tool_name = "FLASHDeconvWizard";
//-------------------------------------------------------------
// description of the usage of this TOPP tool
//-------------------------------------------------------------
void print_usage(Logger::LogStream& stream = getGlobalLogInfo())
{
stream << "\n"
<< tool_name << " -- An assistant for FLASHDeconv.\n"
<< "\n"
<< "Usage: \n"
<< " " << tool_name << " [options] [files]\n"
<< "\n"
<< "Options are:\n"
<< " --help Shows this help\n"
<< " --debug Enables debug messages\n"
<< endl;
}
int main(int argc, const char** argv)
{
#ifdef OPENMS_WINDOWSPLATFORM
qputenv("QT_QPA_PLATFORM", "windows:darkmode=0"); // disable dark mode on Windows, since our buttons etc are not designed for it
#endif
// list of all the valid options
std::map<std::string, std::string> valid_options, valid_flags, option_lists;
valid_flags["--help"] = "help";
valid_flags["--debug"] = "debug";
Param param;
param.parseCommandLine(argc, argv, valid_options, valid_flags, option_lists);
// '--help' given
if (param.exists("help"))
{
print_usage();
return 0;
}
// '-debug' given
if (param.exists("debug"))
{
OPENMS_LOG_INFO << "Debug flag provided. Enabling 'OPENMS_LOG_DEBUG' ..." << std::endl;
getGlobalLogDebug().insert(cout); // allows to use OPENMS_LOG_DEBUG << "something" << std::endl;
}
// test if unknown options were given
if (param.exists("unknown"))
{
// if packed as Mac OS X bundle it will get a -psn_.. parameter by default from the OS
// if this is the only unknown option it will be ignored .. maybe this should be solved directly
// in Param.h
if (!(String(param.getValue("unknown").toString()).hasSubstring("-psn") && !String(param.getValue("unknown").toString()).hasSubstring(", ")))
{
OPENMS_LOG_ERROR << "Unknown option(s) '" << param.getValue("unknown").toString() << "' given. Aborting!" << endl;
print_usage(getGlobalLogError());
return 1;
}
}
QApplicationTOPP a(argc, const_cast<char**>(argv));
a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
FLASHDeconvWizardBase fw;
fw.show();
#ifdef OPENMS_WINDOWSPLATFORM
FreeConsole(); // get rid of console window at this point (we will not see any console output from this point on)
AttachConsole(-1); // if the parent is a console, reattach to it - so we can see debug output - a normal user will usually not use cmd.exe to start a GUI)
#endif
int result = a.exec();
return result;
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.cpp | .cpp | 5,036 | 152 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <cstdio>
#include <cstdlib>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/VersionInfo.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/APPLICATIONS/MISC/QApplicationTOPP.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/VISUAL/GUIProgressLoggerImpl.h>
//Qt
#include <QApplication>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QStyleFactory>
#include <QtWidgets/QPushButton>
#include <QMessageBox>
#include <QFile>
#include <QFileOpenEvent>
#include <QLibraryInfo>
namespace OpenMS
{
QApplicationTOPP::QApplicationTOPP(int& argc, char** argv) :
QApplication(argc, argv)
{
// inject the GUIProgressLoggerImpl to be used by OpenMS lib via an extern variable
make_gui_progress_logger =
[]() -> ProgressLogger::ProgressLoggerImpl* { return new GUIProgressLoggerImpl(); };
// set plastique style unless windows / mac style is available
if (QStyleFactory::keys().contains("windowsxp", Qt::CaseInsensitive))
{
this->setStyle("windowsxp");
}
else if (QStyleFactory::keys().contains("macintosh", Qt::CaseInsensitive))
{
this->setStyle("macintosh");
}
else if (QStyleFactory::keys().contains("plastique", Qt::CaseInsensitive))
{
this->setStyle("plastique");
}
// customize look and feel via Qt style sheets
String filename = File::find("GUISTYLE/qtStyleSheet.qss");
QFile fh(filename.toQString());
fh.open(QFile::ReadOnly);
QString style_string = QLatin1String(fh.readAll());
//std::cerr << "Stylesheet content: " << style_string.toStdString() << "\n\n\n";
this->setStyleSheet(style_string);
}
QApplicationTOPP::~QApplicationTOPP() = default;
/*
@brief: Catch exceptions in Qt GUI applications, preventing ungraceful exit
Re-implementing QApplication::notify() to catch exception thrown in event handlers (which is most likely OpenMS code).
*/
bool QApplicationTOPP::notify(QObject* rec, QEvent* ev)
{
// this is called quite often (whenever a signal is fired), so mind performance!
try
{
return QApplication::notify(rec, ev);
}
catch (Exception::BaseException& e)
{
String msg = String("Caught exception: '") + e.getName() + "' with message '" + e.what() + "'";
OPENMS_LOG_ERROR << msg << "\n";
QMessageBox::warning(nullptr, QString("Unexpected error occurred"), msg.toQString());
return false;
// we could also exit() here... but no for now
}
return false; // never reached, so return value does not matter
}
bool QApplicationTOPP::event(QEvent* event)
{
switch (event->type())
{
case QEvent::FileOpen:
emit fileOpen(static_cast<QFileOpenEvent*>(event)->file());
return true;
default:
return QApplication::event(event);
}
}
void QApplicationTOPP::showAboutDialog(QWidget* parent, const QString& toolname)
{
// dialog and grid layout
QDialog* dlg = new QDialog(parent);
QGridLayout* grid = new QGridLayout(dlg);
dlg->setWindowTitle("About " + toolname);
// image
QLabel* label = new QLabel(dlg);
label->setPixmap(QPixmap(":/TOPP_about.png"));
grid->addWidget(label, 0, 0);
// text
QString text = QString("<BR>"
"<FONT size=+3>%1</font><BR>"
"<BR>"
"Version %2 %3"
"<BR>"
"OpenMS and TOPP is free software available under the<BR>"
"BSD 3-Clause License (BSD-new)<BR>"
"<BR>"
"<BR>"
"<BR>"
"<BR>"
"<BR>"
"Any published work based on TOPP and OpenMS shall cite:<BR>%4")
.arg(toolname)
.arg(VersionInfo::getVersion().toQString())
.arg( // if we have a revision, embed it also into the shown version number
VersionInfo::getRevision().empty() ? "" : QString(" (") + VersionInfo::getRevision().toQString() + ")")
.arg((TOPPBase::cite_openms.title + "<BR>" + TOPPBase::cite_openms.when_where + "<BR>doi:" + TOPPBase::cite_openms.doi).c_str());
label = new QLabel(text, dlg);
grid->addWidget(label, 0, 1, Qt::AlignTop | Qt::AlignLeft);
// close button
QPushButton* button = new QPushButton("Close", dlg);
grid->addWidget(button, 1, 1, Qt::AlignBottom | Qt::AlignRight);
connect(button, SIGNAL(clicked()), dlg, SLOT(close()));
// execute
dlg->exec();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/Plot1DGoToDialog.cpp | .cpp | 1,923 | 82 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/Plot1DGoToDialog.h>
#include <ui_Plot1DGoToDialog.h>
#include <QtWidgets/QLineEdit>
using namespace std;
namespace OpenMS
{
Plot1DGoToDialog::Plot1DGoToDialog(QWidget * parent) :
QDialog(parent),
ui_(new Ui::Plot1DGoToDialogTemplate)
{
ui_->setupUi(this);
}
Plot1DGoToDialog::~Plot1DGoToDialog()
{
delete ui_;
}
void Plot1DGoToDialog::setRange(float min, float max)
{
ui_->min_->setText(QString::number(min));
ui_->max_->setText(QString::number(max));
}
void Plot1DGoToDialog::setMinMaxOfRange(float min, float max)
{
ui_->min_const_->setText(QString("min: ") + QString::number(min));
ui_->max_const_->setText(QString("max: ") + QString::number(max));
}
bool Plot1DGoToDialog::checked()
{
return ui_->clip_checkbox->checkState() == Qt::Checked;
}
void Plot1DGoToDialog::fixRange()
{
// load from GUI
float min_mz = ui_->min_->text().toFloat();
float max_mz = ui_->max_->text().toFloat();
// ensure correct order of min and max
if (min_mz > max_mz) swap(min_mz, max_mz);
// do not allow range of 0 --> extend to 1
if (min_mz == max_mz)
{
min_mz -= 0.5;
max_mz += 0.5;
}
// store in GUI
ui_->min_->setText(QString::number(min_mz));
ui_->max_->setText(QString::number(max_mz));
}
float Plot1DGoToDialog::getMin() const
{
return ui_->min_->text().toFloat();
}
float Plot1DGoToDialog::getMax() const
{
return ui_->max_->text().toFloat();
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/ListFilterDialog.cpp | .cpp | 3,329 | 109 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/ListFilterDialog.h>
#include <OpenMS/VISUAL/MISC/FilterableList.h>
#include <ui_ListFilterDialog.h>
#include <QCloseEvent>
using namespace std;
namespace OpenMS
{
/// C'tor with items to show and select from
ListFilterDialog::ListFilterDialog(QWidget* parent, const QStringList& items, const QStringList& items_prechosen)
: QDialog(parent),
ui_(new Ui::ListFilterDialog)
{
ui_->setupUi(this);
connect(ui_->ok_button_, &QPushButton::clicked, this, &QDialog::accept);
connect(ui_->cancel_button_, &QPushButton::clicked, this, &QDialog::reject);
connect(ui_->btn_left_right, &QPushButton::clicked, this, &ListFilterDialog::BtnLRClicked_);
connect(ui_->btn_left_right_all, &QPushButton::clicked, this, &ListFilterDialog::BtnLRAllClicked_);
connect(ui_->btn_right_left, &QPushButton::clicked, this, &ListFilterDialog::BtnRLClicked_);
connect(ui_->btn_right_left_all, &QPushButton::clicked, this, &ListFilterDialog::BtnRLAllClicked_);
// if something was double clicked, it's also selected. So just forward to '>>' button
connect(ui_->list_in, &FilterableList::itemDoubleClicked, this, &ListFilterDialog::BtnLRClicked_);
connect(ui_->list_out, &QListWidget::itemDoubleClicked, this, &ListFilterDialog::BtnRLClicked_);
setItems(items);
setPrechosenItems(items_prechosen);
}
ListFilterDialog::~ListFilterDialog()
{
delete ui_;
}
void ListFilterDialog::closeEvent(QCloseEvent* event)
{
event->accept();
reject();
}
void ListFilterDialog::setItems(const QStringList& items)
{
ui_->list_in->setItems(items);
}
void ListFilterDialog::setPrechosenItems(const QStringList& items_pre)
{
ui_->list_in->setBlacklistItems(items_pre);
ui_->list_out->clear();
ui_->list_out->addItems(items_pre);
}
QStringList ListFilterDialog::getChosenItems() const
{
QStringList items;
for (int row = 0; row < ui_->list_out->count(); ++row) items << ui_->list_out->item(row)->text();
return items;
}
void ListFilterDialog::BtnLRClicked_()
{
auto selected = ui_->list_in->getSelectedItems();
ui_->list_out->insertItems(ui_->list_out->count(), selected);
ui_->list_in->addBlackListItems(selected);
}
void ListFilterDialog::BtnLRAllClicked_()
{
auto selected = ui_->list_in->getAllVisibleItems();
ui_->list_out->insertItems(ui_->list_out->count(), selected);
ui_->list_in->addBlackListItems(selected);
}
void ListFilterDialog::BtnRLClicked_()
{
QStringList selected;
auto widget_selected = ui_->list_out->selectedItems();
for (auto& item : widget_selected) selected << item->text();
qDeleteAll(widget_selected);
ui_->list_in->removeBlackListItems(selected);
}
void ListFilterDialog::BtnRLAllClicked_()
{
QStringList selected = getChosenItems();
ui_->list_out->clear();
ui_->list_in->removeBlackListItems(selected);
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/PythonSelector.cpp | .cpp | 2,426 | 85 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/DIALOGS/PythonSelector.h>
#include <ui_PythonSelector.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/SYSTEM/PythonInfo.h>
#include <QString>
#include <QtWidgets/QFileDialog>
#include <QMessageBox>
using namespace std;
namespace OpenMS
{
namespace Internal
{
PythonSelector::PythonSelector(QWidget* parent) :
QWidget(parent),
ui_(new Ui::PythonSelector)
{
ui_->setupUi(this);
connect(ui_->btn_browse, SIGNAL(clicked()), this, SLOT(showFileDialog_()));
connect(ui_->line_edit, SIGNAL(editingFinished()), this, SLOT(validate_()));
// load/update UI
ui_->line_edit->setText(last_known_python_exe_.toQString());
// internally check
validate_();
}
PythonSelector::~PythonSelector()
{
delete ui_;
// TODO: store UI to INI?
}
void PythonSelector::showFileDialog_()
{
QString file_name = QFileDialog::getOpenFileName(this, tr("Specify Python executable"), tr(""), tr(/*valid formats*/ ""));
if (!file_name.isEmpty())
{
ui_->line_edit->setText(file_name); // will not trigger the validator
emit ui_->line_edit->editingFinished(); // simulate loosing focus or pressing return (to trigger validate_())
}
}
void PythonSelector::validate_()
{
String exe = ui_->line_edit->text();
String error;
bool success = PythonInfo::canRun(exe, error);
if (success)
{
last_known_python_exe_ = exe;
ui_->label->setText(PythonInfo::getVersion(exe).toQString());
currently_valid_ = true;
}
else
{
QMessageBox::warning(nullptr, QString("Python not found"), error.toQString());
// no need to currently_valid_=false, since we will revert to 'last_known_python_exe_'
}
// reset to last known
ui_->line_edit->setText(last_known_python_exe_.toQString());
emit valueChanged(last_known_python_exe_.toQString(), currently_valid_);
}
} //namespace Internal
} //namspace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/Plot1DPrefDialog.cpp | .cpp | 806 | 34 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/Plot1DPrefDialog.h>
#include <ui_Plot1DPrefDialog.h>
using namespace std;
namespace OpenMS
{
namespace Internal
{
Plot1DPrefDialog::Plot1DPrefDialog(QWidget * parent) :
QDialog(parent),
ui_(new Ui::Plot1DPrefDialogTemplate)
{
ui_->setupUi(this);
}
Plot1DPrefDialog::~Plot1DPrefDialog()
{
delete ui_;
}
} //namespace Internal
} //namspace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/TOPPASInputFileDialog.cpp | .cpp | 1,542 | 58 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/TOPPASInputFileDialog.h>
#include <ui_TOPPASInputFileDialog.h>
#include <QtWidgets/QMessageBox>
#include <QtCore/QFileInfo>
namespace OpenMS
{
TOPPASInputFileDialog::TOPPASInputFileDialog(const QString& file_name)
: QDialog(),
ui_(new Ui::TOPPASInputFileDialogTemplate)
{
ui_->setupUi(this);
ui_->input_file->setFilename(file_name);
connect(ui_->ok_button, SIGNAL(clicked()), this, SLOT(checkValidity_()));
connect(ui_->cancel_button, SIGNAL(clicked()), this, SLOT(reject()));
}
TOPPASInputFileDialog::~TOPPASInputFileDialog()
{
delete ui_;
}
void TOPPASInputFileDialog::setFileFormatFilter(const QString& fff)
{
ui_->input_file->setFileFormatFilter(fff);
}
QString TOPPASInputFileDialog::getFilename() const
{
return ui_->input_file->getFilename();
}
void TOPPASInputFileDialog::checkValidity_()
{
QFileInfo fi(getFilename());
if (!(fi.exists() && fi.isReadable() && (!fi.isDir())))
{
QMessageBox::warning(nullptr, "Invalid file name", "Filename does not exist!");
return; // do not close the dialog
}
accept();
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/PythonModuleRequirement.cpp | .cpp | 2,301 | 78 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/DIALOGS/PythonModuleRequirement.h>
#include <ui_PythonModuleRequirement.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/SYSTEM/PythonInfo.h>
#include <QString>
#include <QtWidgets/QFileDialog>
#include <QMessageBox>
using namespace std;
namespace OpenMS
{
namespace Internal
{
PythonModuleRequirement::PythonModuleRequirement(QWidget* parent) :
QWidget(parent),
ui_(new Ui::PythonModuleRequirement)
{
ui_->setupUi(this);
}
// slot
void PythonModuleRequirement::validate(const QString& python_exe)
{
QStringList valid_modules;
QStringList missing_modules;
ui_->lbl_modules->setText(" ... updating ... ");
for (const auto& s : required_modules_)
{
if (PythonInfo::isPackageInstalled(python_exe, s)) valid_modules.push_back(s);
else missing_modules.push_back(s);
}
emit valueChanged(valid_modules, missing_modules);
QString text = "<ul>";
if (!valid_modules.empty()) text += QString("<li> [<code style = \"color: green\">%1</code>] present").arg(valid_modules.join(", "));
if (!missing_modules.empty()) text += QString("<li> [<code style = \"color: red\">%1</code>] missing").arg(missing_modules.join(", "));
text += "</ul>";
ui_->lbl_modules->setText(text);
// if no modules are missing, we are good to go...
is_ready_ = missing_modules.empty();
}
PythonModuleRequirement::~PythonModuleRequirement()
{
delete ui_;
// TODO: store UI to INI?
}
void PythonModuleRequirement::setTitle(const QString& title)
{
ui_->box->setTitle(title);
}
void PythonModuleRequirement::setRequiredModules(const QStringList& m)
{
required_modules_ = m;
}
void PythonModuleRequirement::setFreeText(const QString& text)
{
ui_->lbl_freetext->setText(text);
}
} //namespace Internal
} //namspace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/TOPPASIOMappingDialog.cpp | .cpp | 11,306 | 329 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/TOPPASIOMappingDialog.h>
#include <ui_TOPPASIOMappingDialog.h>
#include <OpenMS/VISUAL/TOPPASEdge.h>
#include <OpenMS/VISUAL/TOPPASInputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASMergerVertex.h>
#include <OpenMS/VISUAL/TOPPASOutputFileListVertex.h>
#include <OpenMS/VISUAL/TOPPASSplitterVertex.h>
#include <OpenMS/VISUAL/TOPPASToolVertex.h>
#include <OpenMS/DATASTRUCTURES/ListUtilsIO.h>
#include <QtWidgets/QMessageBox>
#include <iostream>
#include <sstream>
#include <OpenMS/VISUAL/TOPPASOutputFolderVertex.h>
namespace OpenMS
{
TOPPASIOMappingDialog::TOPPASIOMappingDialog(TOPPASEdge* parent)
: ui_(new Ui::TOPPASIOMappingDialogTemplate)
{
ui_->setupUi(this);
edge_ = parent;
connect(ui_->ok_button, SIGNAL(clicked()), this, SLOT(checkValidity_()));
connect(ui_->cancel_button, SIGNAL(clicked()), this, SLOT(reject()));
fillComboBoxes_();
}
TOPPASIOMappingDialog::~TOPPASIOMappingDialog()
{
delete ui_;
}
int TOPPASIOMappingDialog::firstExec()
{
// check if only 1 parameter, if yes: select it
if (ui_->source_combo->count() == 2) // <select> + 1 parameter
{
ui_->source_combo->setCurrentIndex(1);
}
if (ui_->target_combo->count() == 2)
{
ui_->target_combo->setCurrentIndex(1);
}
// if the target is an output folder and there is no output parameter in the input tool, the egde is invalid
TOPPASOutputFolderVertex* target_dir = qobject_cast<TOPPASOutputFolderVertex*>(edge_->getTargetVertex());
if (target_dir && ui_->source_combo->count() == 0)
{
return QDialog::Rejected;
}
// is there only 1 possible mapping? -> do not show dialog
if ((ui_->source_combo->count() == 2 || ui_->source_combo->count() == 0) &&
(ui_->target_combo->count() == 2 || ui_->target_combo->count() == 0))
{
checkValidity_();
return QDialog::Accepted;
}
else
{
return QDialog::exec();
}
}
void TOPPASIOMappingDialog::fillComboBoxes_()
{
TOPPASVertex* source = edge_->getSourceVertex();
TOPPASVertex* target = edge_->getTargetVertex();
TOPPASToolVertex* source_tool = qobject_cast<TOPPASToolVertex*>(source);
TOPPASToolVertex* target_tool = qobject_cast<TOPPASToolVertex*>(target);
TOPPASMergerVertex* source_merger = qobject_cast<TOPPASMergerVertex*>(source);
TOPPASMergerVertex* target_merger = qobject_cast<TOPPASMergerVertex*>(target);
TOPPASSplitterVertex* source_splitter = qobject_cast<TOPPASSplitterVertex*>(source);
TOPPASSplitterVertex* target_splitter = qobject_cast<TOPPASSplitterVertex*>(target);
TOPPASInputFileListVertex* source_list = qobject_cast<TOPPASInputFileListVertex*>(source);
TOPPASOutputFileListVertex* target_list = qobject_cast<TOPPASOutputFileListVertex*>(target);
TOPPASOutputFolderVertex* target_dir = qobject_cast<TOPPASOutputFolderVertex*>(target);
// an output folder can only be connected to a tool
if (target_dir)
{
if (!source_tool)
{ // bad news: no source tool, hence no connection possible
return;
}
const auto source_output_dirs = source_tool->getOutputParameters();
ui_->source_combo->addItem("<select>");
for (const auto& info : source_output_dirs)
{
if (info.type != TOPPASToolVertex::IOInfo::IOT_DIR) continue;
String item_name = "Directory: " + info.param_name + " ";
ui_->source_combo->addItem(item_name.toQString(), source_output_dirs.indexOf(info));
}
if (ui_->source_combo->count() == 1) // no directories found; return empty to signal invalid edge
{
ui_->source_combo->clear();
return;
}
}
else if (source_tool)
{
QVector<TOPPASToolVertex::IOInfo> source_output_files = source_tool->getOutputParameters();
ui_->source_label->setText(source_tool->getName().toQString());
if (!source_tool->getType().empty())
{
ui_->source_type_label->setText("(" + source_tool->getType().toQString() + ")");
}
else
{
ui_->source_type_label->setVisible(false);
}
ui_->source_combo->addItem("<select>");
for (TOPPASToolVertex::IOInfo info : source_output_files)
{
if (info.type == TOPPASToolVertex::IOInfo::IOT_DIR) continue;
String item_name;
if (info.type == TOPPASToolVertex::IOInfo::IOT_FILE)
{
if (target_splitter) continue; // inputs for splitters must be lists
item_name = "File: ";
}
else
{
item_name = "List: ";
}
item_name += info.param_name + " ";
std::ostringstream ss;
ss << info.valid_types;
item_name += ss.str();
ui_->source_combo->addItem(item_name.toQString(), source_output_files.indexOf(info));
}
}
else if (source_list || source_merger || source_splitter)
{
if (source_list)
{
ui_->source_label->setText("List");
}
else if (source_merger)
{
ui_->source_label->setText(source_merger->roundBasedMode() ? "Merger" : "Collector");
}
else if (source_splitter)
{
ui_->source_label->setText("Splitter");
}
ui_->source_type_label->setVisible(false);
ui_->source_combo->setVisible(false);
ui_->source_parameter_label->setVisible(false);
}
if (target_tool)
{
QVector<TOPPASToolVertex::IOInfo> target_input_files = target_tool->getInputParameters();
ui_->target_label->setText(target_tool->getName().toQString());
if (!target_tool->getType().empty())
{
ui_->target_type_label->setText("(" + target_tool->getType().toQString() + ")");
}
else
{
ui_->target_type_label->setVisible(false);
}
ui_->target_combo->addItem("<select>");
for (TOPPASToolVertex::IOInfo info : target_input_files)
{
// check if parameter occupied by another edge already
bool occupied = false;
for (TOPPASVertex::ConstEdgeIterator it = target->inEdgesBegin(); it != target->inEdgesEnd(); ++it)
{
int param_index = (*it)->getTargetInParam();
if (*it != edge_ && param_index >= 0 && param_index < target_input_files.size())
{
if (info.param_name == target_input_files[param_index].param_name)
{
occupied = true;
break;
}
}
}
if (occupied)
{
continue;
}
String item_name;
if (info.type == TOPPASToolVertex::IOInfo::IOT_FILE)
{
if (source_merger && !source_merger->roundBasedMode()) continue; // collectors produce lists
item_name = "File: ";
}
else
{
item_name = "List: ";
}
item_name += info.param_name + " ";
std::ostringstream ss;
ss << info.valid_types;
item_name += ss.str();
ui_->target_combo->addItem(item_name.toQString(), target_input_files.indexOf(info));
}
}
else if (target_list || target_dir || target_merger || target_splitter)
{
if (target_list)
{
ui_->target_label->setText("List");
}
else if (target_dir)
{
ui_->target_label->setText("Directory");
}
else if (target_merger)
{
ui_->target_label->setText(target_merger->roundBasedMode() ? "Merger" : "Collector");
}
else if (target_splitter)
{
ui_->target_label->setText("Splitter");
}
ui_->target_type_label->setVisible(false);
ui_->target_combo->setVisible(false);
ui_->target_parameter_label->setVisible(false);
}
// pre-select the current mapping for existing edges
// note: for new edges, @p edge_index is -1
auto find_index = [](QComboBox* combo, int edge_index) -> int {
for (int i = 1; i < combo->count(); ++i)
{
if (combo->itemData(i).toInt() == edge_index) return i;
}
// no mapping found
if (combo->count() == 2) // only 1 parameter (+ <select>)
{
return 1; // pre-select the only parameter
}
return 0; // use '<select>'
};
ui_->source_combo->setCurrentIndex(find_index(ui_->source_combo, edge_->getSourceOutParam()));
ui_->target_combo->setCurrentIndex(find_index(ui_->target_combo, edge_->getTargetInParam()));
resize(width(), 0);
}
void TOPPASIOMappingDialog::checkValidity_()
{
const QString& source_text = ui_->source_combo->currentText();
const QString& target_text = ui_->target_combo->currentText();
TOPPASVertex* source = edge_->getSourceVertex();
TOPPASVertex* target = edge_->getTargetVertex();
TOPPASToolVertex* source_tool = qobject_cast<TOPPASToolVertex*>(source);
TOPPASToolVertex* target_tool = qobject_cast<TOPPASToolVertex*>(target);
if (source_text == "<select>")
{
QMessageBox::warning(nullptr, "Invalid selection", "You must specify the source output parameter!");
return;
}
if (target_text == "<select>")
{
QMessageBox::warning(nullptr, "Invalid selection", "You must specify the target input parameter!");
return;
}
if (source_tool)
{
edge_->setSourceOutParam(ui_->source_combo->currentData().toInt());
}
if (target_tool)
{
edge_->setTargetInParam(ui_->target_combo->currentData().toInt());
}
edge_->updateColor();
TOPPASEdge::EdgeStatus es = edge_->getEdgeStatus();
if (es == TOPPASEdge::ES_VALID || es == TOPPASEdge::ES_NOT_READY_YET)
{
accept();
}
else
{
if (es == TOPPASEdge::ES_NO_TARGET_PARAM)
{
QMessageBox::warning(nullptr, "Invalid selection", "You must specify the target input parameter!");
}
else if (es == TOPPASEdge::ES_NO_SOURCE_PARAM)
{
QMessageBox::warning(nullptr, "Invalid selection", "You must specify the source output parameter!");
}
else if (es == TOPPASEdge::ES_FILE_EXT_MISMATCH)
{
QMessageBox::warning(nullptr, "Invalid selection", "The file types of source output and target input parameter do not match!");
}
else if (es == TOPPASEdge::ES_MERGER_EXT_MISMATCH)
{
QMessageBox::warning(nullptr, "Invalid selection", "The file types of source output and the target input parameter do not match!");
}
else if (es == TOPPASEdge::ES_MERGER_WITHOUT_TOOL)
{
// this should be prevented already by "TOPPASScene::isEdgeAllowed_":
QMessageBox::warning(nullptr, "Invalid selection", "Mergers or splitters connecting input and output files directly are not allowed!");
}
else
{
QMessageBox::warning(nullptr, "Ooops", "This should not have happened. Please contact the OpenMS mailing list and report this bug.");
}
}
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/Plot2DGoToDialog.cpp | .cpp | 3,027 | 106 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/Plot2DGoToDialog.h>
#include <ui_Plot2DGoToDialog.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <QtWidgets/QLineEdit>
using namespace std;
namespace OpenMS
{
Plot2DGoToDialog::Plot2DGoToDialog(QWidget * parent, std::string_view x_name, std::string_view y_name) :
QDialog(parent),
ui_(new Ui::Plot2DGoToDialogTemplate)
{
ui_->setupUi(this);
ui_->dimx_->setText(x_name.data());
ui_->dimy_->setText(y_name.data());
}
Plot2DGoToDialog::~Plot2DGoToDialog()
{
delete ui_;
}
void Plot2DGoToDialog::setRange(const AreaXYType& range)
{
ui_->min_x_->setText(QString::number(range.minX()));
ui_->max_x_->setText(QString::number(range.maxX()));
ui_->min_y_->setText(QString::number(range.minY()));
ui_->max_y_->setText(QString::number(range.maxY()));
}
void Plot2DGoToDialog::setMinMaxOfRange(const AreaXYType& max_range)
{
ui_->min_x_const_->setText("min: " + QString::number(max_range.minX()));
ui_->max_x_const_->setText("max: " + QString::number(max_range.maxX()));
ui_->min_y_const_->setText("min: " + QString::number(max_range.minY()));
ui_->max_y_const_->setText("max: " + QString::number(max_range.maxY()));
}
Plot2DGoToDialog::AreaXYType Plot2DGoToDialog::getRange()
{
AreaXYType r{
ui_->min_x_->text().toFloat(),
ui_->min_y_->text().toFloat(),
ui_->max_x_->text().toFloat(),
ui_->max_y_->text().toFloat(),
};
r.ensureMinSpan({1,1});
return r;
}
bool Plot2DGoToDialog::checked()
{
return ui_->clip_checkbox->checkState() == Qt::Checked;
}
void Plot2DGoToDialog::enableFeatureNumber(bool enabled)
{
ui_->feature_label_->setEnabled(enabled);
ui_->nr_->setEnabled(enabled);
ui_->feature_number_->setEnabled(enabled);
//Reorder tab order
if (enabled)
{
setTabOrder(ui_->feature_number_, ui_->ok_button_);
setTabOrder(ui_->ok_button_, ui_->cancel_button_);
setTabOrder(ui_->cancel_button_, ui_->min_x_);
setTabOrder(ui_->min_x_, ui_->max_x_);
setTabOrder(ui_->max_x_, ui_->min_y_);
setTabOrder(ui_->min_y_, ui_->max_y_);
}
else
{
setTabOrder(ui_->min_x_, ui_->max_x_);
setTabOrder(ui_->max_x_, ui_->min_y_);
setTabOrder(ui_->min_y_, ui_->max_y_);
setTabOrder(ui_->max_y_, ui_->ok_button_);
setTabOrder(ui_->ok_button_, ui_->cancel_button_);
}
}
String Plot2DGoToDialog::getFeatureNumber() const
{
return ui_->feature_number_->text();
}
bool Plot2DGoToDialog::showRange() const
{
return getFeatureNumber().trim().empty();
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/DataFilterDialog.cpp | .cpp | 6,212 | 212 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/DataFilterDialog.h>
#include <ui_DataFilterDialog.h>
//Qt includes
#include <QDoubleValidator>
#include <QIntValidator>
#include <QtWidgets/QMessageBox>
#include <iostream>
using namespace std;
namespace OpenMS
{
DataFilterDialog::DataFilterDialog(DataFilters::DataFilter & filter, QWidget * parent) :
QDialog(parent),
filter_(filter),
ui_(new Ui::DataFilterDialogTemplate)
{
ui_->setupUi(this);
connect(ui_->ok_button_, SIGNAL(clicked()), this, SLOT(check_()));
connect(ui_->field_, SIGNAL(activated(const QString &)), this, SLOT(field_changed_(const QString &)));
connect(ui_->op_, SIGNAL(activated(const QString &)), this, SLOT(op_changed_(const QString &)));
//set values for edit mode
ui_->field_->setCurrentIndex((UInt)filter.field);
ui_->op_->setCurrentIndex((UInt)filter.op);
if (filter.field == DataFilters::META_DATA)
{
ui_->meta_name_field_->setText(filter.meta_name.toQString());
// if the value stored in filter is numerical, get value from filter.value (a double)
if (filter.value_is_numerical)
{
ui_->value_->setText(QString::number(filter.value));
}
else // get value from filter.value_string (a String)
{
ui_->value_->setText(filter.value_string.toQString());
}
ui_->meta_name_field_->setEnabled(true);
ui_->meta_name_label_->setEnabled(true);
if (filter.op == DataFilters::EXISTS)
{
ui_->value_->setEnabled(false);
ui_->value_label_->setEnabled(false);
}
}
else // for non meta data, the value is always numerical
{
ui_->value_->setText(QString::number(filter.value));
}
//focus the value if this is an edit operation
if (filter != DataFilters::DataFilter())
{
ui_->value_->selectAll();
setTabOrder(ui_->value_, ui_->cancel_button_);
setTabOrder(ui_->cancel_button_, ui_->ok_button_);
setTabOrder(ui_->ok_button_, ui_->field_);
setTabOrder(ui_->field_, ui_->meta_name_field_);
setTabOrder(ui_->meta_name_field_, ui_->op_);
}
}
DataFilterDialog::~DataFilterDialog()
{
delete ui_;
}
void DataFilterDialog::field_changed_(const QString & field)
{
QString op(ui_->op_->currentText());
if (field == "Meta data")
{
ui_->meta_name_field_->setEnabled(true);
ui_->meta_name_label_->setEnabled(true);
}
else
{
ui_->meta_name_field_->setEnabled(false);
ui_->meta_name_label_->setEnabled(false);
}
}
void DataFilterDialog::op_changed_(const QString & op)
{
QString field(ui_->field_->currentText());
if (op != "exists")
{
ui_->value_->setEnabled(true);
ui_->value_label_->setEnabled(true);
}
else
{
ui_->value_->setEnabled(false);
ui_->value_label_->setEnabled(false);
}
}
void DataFilterDialog::check_()
{
QString field = ui_->field_->currentText();
QString op = ui_->op_->currentText();
QString value = ui_->value_->text();
QString meta_name_field = ui_->meta_name_field_->text();
bool not_numerical = true;
int tmp;
//meta data
if (field == "Meta data")
{
QDoubleValidator dv(this);
not_numerical = dv.validate(value, tmp) == QValidator::Invalid;
if (meta_name_field.isEmpty())
{
QMessageBox::warning(this, "Insufficient arguments", "You must specify a meta name!");
return;
}
if (op == "<=" || op == ">=")
{
if (not_numerical)
{
QMessageBox::warning(this, "Invalid value", "<= and >= are defined for numerical values only!");
return;
}
}
}
//intensity, quality, charge:
else
{
if (op == "exists")
{
QMessageBox::warning(this, "Invalid operation", "Operation \"exists\" is defined for meta data only!");
return;
}
//double
if (field == "Intensity" || field == "Quality")
{
QDoubleValidator v(this);
if (v.validate(value, tmp) == QValidator::Invalid)
{
QMessageBox::warning(this, "Invalid value", "A real value is required!");
return;
}
}
//int
if (field == "Charge" || field == "Size")
{
QIntValidator v(this);
if (v.validate(value, tmp) == QValidator::Invalid)
{
QMessageBox::warning(this, "Invalid value", "An integer value is required!");
return;
}
}
}
//write result
if (field == "Intensity")
filter_.field = DataFilters::INTENSITY;
else if (field == "Quality")
filter_.field = DataFilters::QUALITY;
else if (field == "Charge")
filter_.field = DataFilters::CHARGE;
else if (field == "Size")
filter_.field = DataFilters::SIZE;
else if (field == "Meta data")
{
filter_.field = DataFilters::META_DATA;
filter_.meta_name = meta_name_field;
if (not_numerical) // entered value is not numerical, store it in value_string (as String)
{
filter_.value_string = String(value);
filter_.value_is_numerical = false;
}
else // value is numerical, store it in value (as double)
{
filter_.value = value.toDouble();
filter_.value_is_numerical = true;
}
}
if (op == ">=")
filter_.op = DataFilters::GREATER_EQUAL;
else if (op == "=")
filter_.op = DataFilters::EQUAL;
else if (op == "<=")
filter_.op = DataFilters::LESS_EQUAL;
else if (op == "exists")
filter_.op = DataFilters::EXISTS;
if (field == "Intensity" || field == "Quality")
filter_.value = value.toDouble();
else if (field == "Charge" || field == "Size")
filter_.value = value.toInt();
accept();
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/HistogramDialog.cpp | .cpp | 2,145 | 84 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/DIALOGS/HistogramDialog.h>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QGridLayout>
using namespace std;
namespace OpenMS
{
using namespace Math;
HistogramDialog::HistogramDialog(const Histogram<> & distribution, QWidget * parent) :
QDialog(parent)
{
setWindowTitle("Intensity Distribution");
//layout
QGridLayout * layout = new QGridLayout(this);
layout->setRowStretch(0, 100);
//ok
QPushButton * ok_button_ = new QPushButton("&Apply Filter", this);
ok_button_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(ok_button_, SIGNAL(clicked()), this, SLOT(accept()));
layout->addWidget(ok_button_, 1, 1);
//cancel
QPushButton * cancel_button_ = new QPushButton("&Cancel", this);
cancel_button_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(cancel_button_, SIGNAL(clicked()), this, SLOT(reject()));
layout->addWidget(cancel_button_, 1, 2);
//distribution
mw_ = new HistogramWidget(distribution, this);
mw_->showSplitters(true);
layout->addWidget(mw_, 0, 0, 1, 3);
//resize dialog
adjustSize();
}
HistogramDialog::~HistogramDialog() = default;
float HistogramDialog::getLeftSplitter()
{
return mw_->getLeftSplitter();
}
float HistogramDialog::getRightSplitter()
{
return mw_->getRightSplitter();
}
void HistogramDialog::setLeftSplitter(float position)
{
mw_->setLeftSplitter(position);
}
void HistogramDialog::setRightSplitter(float position)
{
mw_->setRightSplitter(position);
}
void HistogramDialog::setLegend(const String & legend)
{
mw_->setLegend(legend);
}
void HistogramDialog::setLogMode(bool log_mode)
{
mw_->setLogMode(log_mode);
}
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/TOPPASInputFilesDialog.cpp | .cpp | 1,377 | 51 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/TOPPASInputFilesDialog.h>
#include <ui_TOPPASInputFilesDialog.h>
#include <OpenMS/VISUAL/InputFileList.h>
namespace OpenMS
{
TOPPASInputFilesDialog::TOPPASInputFilesDialog(const QStringList& list, const QString& cwd, QWidget* parent)
: QDialog(parent),
ui_(new Ui::TOPPASInputFilesDialogTemplate)
{
ui_->setupUi(this);
ifl_ = (InputFileList*)ui_->input_file_list;
ifl_->setCWD(cwd);
ifl_->setFilenames(list);
connect(ui_->ok_button, SIGNAL(clicked()), this, SLOT(accept()));
connect(ui_->cancel_button, SIGNAL(clicked()), this, SLOT(reject()));
setAcceptDrops(true);
}
TOPPASInputFilesDialog::~TOPPASInputFilesDialog()
{
delete ui_;
}
void TOPPASInputFilesDialog::getFilenames(QStringList& files) const
{
ifl_->getFilenames(files);
if (ui_->flag_sort_list->isChecked())
files.sort();
}
const QString& TOPPASInputFilesDialog::getCWD() const
{
return ifl_->getCWD();
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/SaveImageDialog.cpp | .cpp | 4,926 | 189 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
//
#include <iostream>
#include <cmath>
#include <OpenMS/VISUAL/DIALOGS/SaveImageDialog.h>
#include <OpenMS/MATH/MathFunctions.h>
// Qt
#include <QtWidgets/QLayout>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QLabel>
#include <QValidator>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QImageWriter>
#include <QtWidgets/QApplication>
namespace OpenMS
{
SaveImageDialog::SaveImageDialog(QWidget * parent) :
QDialog(parent)
{
size_ratio_ = 1;
//create dialog and layout (grid)
QGridLayout * grid = new QGridLayout(this);
//add accept/cancel buttons (and their layout)
QBoxLayout * box_layout = new QHBoxLayout();
grid->addLayout(box_layout, 5, 1);
QPushButton * button = new QPushButton(this);
button->setText("Cancel");
connect(button, SIGNAL(clicked()), this, SLOT(reject()));
box_layout->addWidget(button);
button = new QPushButton(this);
button->setText("Accept");
button->setDefault(true);
connect(button, SIGNAL(clicked()), this, SLOT(checkSize()));
box_layout->addWidget(button);
//add picture format selector
QLabel * label = new QLabel("Picture format:", this);
grid->addWidget(label, 0, 0);
format_ = new QComboBox(this);
QList<QByteArray> list = QImageWriter::supportedImageFormats();
for (int i = 0; i < list.size(); ++i)
{
format_->insertItem(i, list.at(i));
}
grid->addWidget(format_, 0, 1, Qt::AlignLeft);
//set format to PNG/JPEG if available
int png = -1;
int jpeg = -1;
for (int i = 0; i < format_->count(); i++)
{
if (format_->itemText(i) == "PNG")
{
png = i;
}
if (format_->itemText(i) == "JPEG")
{
jpeg = i;
}
}
if (png != -1)
{
format_->setCurrentIndex(png);
}
else if (jpeg != -1)
{
format_->setCurrentIndex(jpeg);
}
//add size boxes and label (and their layout)
label = new QLabel("Size (WxH):", this);
grid->addWidget(label, 1, 0);
QValidator * v = new QIntValidator(1, 10000, this);
box_layout = new QHBoxLayout();
grid->addLayout(box_layout, 1, 1);
size_x_ = new QLineEdit(this);
size_x_->setValidator(v);
connect(size_x_, SIGNAL(textChanged(const QString &)), this, SLOT(xSizeChanged(const QString &)));
box_layout->addWidget(size_x_);
label = new QLabel("x", this);
box_layout->addWidget(label);
size_y_ = new QLineEdit(this);
size_y_->setValidator(v);
connect(size_y_, SIGNAL(textChanged(const QString &)), this, SLOT(ySizeChanged(const QString &)));
box_layout->addWidget(size_y_);
label = new QLabel("pixel", this);
box_layout->addWidget(label);
size_proportions_ = new QCheckBox("keep proportions", this);
size_proportions_->setChecked(true);
connect(size_proportions_, SIGNAL(toggled(bool)), this, SLOT(proportionsActivated(bool)));
grid->addWidget(size_proportions_, 2, 1);
}
void SaveImageDialog::setSize(int x, int y)
{
QString * temp = new QString();
temp->setNum(x);
size_x_->setText(*temp);
temp->setNum(y);
size_y_->setText(*temp);
setSizeRatio_(float(x) / float(y));
}
void SaveImageDialog::setSizeRatio_(float r)
{
if (r == 0.0)
{
size_ratio_ = 1.0;
}
else
{
size_ratio_ = r;
}
}
void SaveImageDialog::xSizeChanged(const QString & s)
{
if (size_proportions_->isChecked() && size_x_ == qApp->focusWidget())
{
QString * temp = new QString();
temp->setNum((int)Math::round(s.toInt() / size_ratio_));
size_y_->setText(*temp);
}
}
void SaveImageDialog::ySizeChanged(const QString & s)
{
if (size_proportions_->isChecked() && size_y_ == qApp->focusWidget())
{
QString * temp = new QString();
temp->setNum((int)Math::round(s.toInt() * size_ratio_));
size_x_->setText(*temp);
}
}
void SaveImageDialog::proportionsActivated(bool state)
{
if (state == true)
{
setSizeRatio_(QString(size_x_->text()).toFloat() / QString(size_y_->text()).toFloat());
}
}
void SaveImageDialog::checkSize()
{
int x = size_x_->text().toInt();
int y = size_y_->text().toInt();
if (x > 0 && y > 0)
{
accept();
}
}
int SaveImageDialog::getXSize()
{
return size_x_->text().toInt();
}
int SaveImageDialog::getYSize()
{
return size_y_->text().toInt();
}
QString SaveImageDialog::getFormat()
{
return format_->currentText();
}
} //namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/TheoreticalSpectrumGenerationDialog.cpp | .cpp | 17,673 | 449 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Tom Waschischeck $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/TheoreticalSpectrumGenerationDialog.h>
#include <ui_TheoreticalSpectrumGenerationDialog.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/FineIsotopePatternGenerator.h>
#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h>
#include <OpenMS/CHEMISTRY/NucleicAcidSpectrumGenerator.h>
#include <OpenMS/DATASTRUCTURES/String.h>
// Qt includes
#include <QtWidgets/QMessageBox>
#include <qflags.h>
#include <array>
#include <utility>
namespace OpenMS
{
TheoreticalSpectrumGenerationDialog::CheckBox::CheckBox(QDoubleSpinBox** sb, QLabel** l, std::array<CheckBoxState, 3> s, std::pair<String, String> p_t, std::pair<String, String> p_s) :
ptr_to_spin_box(sb), ptr_to_spin_label(l), state(s), param_this(std::move(p_t)), param_spin(std::move(p_s))
{}
TheoreticalSpectrumGenerationDialog::TheoreticalSpectrumGenerationDialog() :
ui_(new Ui::TheoreticalSpectrumGenerationDialogTemplate),
// Order has to be the same as in the UI!
check_boxes_ {
CheckBox(&(ui_->a_intensity), &(ui_->a_label), {CheckBoxState::ENABLED, CheckBoxState::ENABLED, CheckBoxState::HIDDEN}, {"add_a_ions", "Add peaks of a-ions to the spectrum"},
{"a_intensity", "Intensity of the a-ions"}),
CheckBox(&(ui_->a_b_intensity), &(ui_->a_b_label), {CheckBoxState::HIDDEN, CheckBoxState::ENABLED, CheckBoxState::HIDDEN}, {"add_a-B_ions", "Add peaks of a-B-ions to the spectrum (nucleotide sequences only)"},
{"a-B_intensity", "Intensity of the a-B-ions"}),
CheckBox(&(ui_->b_intensity), &(ui_->b_label), {CheckBoxState::PRECHECKED, CheckBoxState::PRECHECKED, CheckBoxState::HIDDEN}, {"add_b_ions", "Add peaks of b-ions to the spectrum"},
{"b_intensity", "Intensity of the b-ions"}),
CheckBox(&(ui_->c_intensity), &(ui_->c_label), {CheckBoxState::ENABLED, CheckBoxState::ENABLED, CheckBoxState::HIDDEN}, {"add_c_ions", "Add peaks of c-ions to the spectrum"},
{"c_intensity", "Intensity of the c-ions"}),
CheckBox(&(ui_->d_intensity), &(ui_->d_label), {CheckBoxState::HIDDEN, CheckBoxState::ENABLED, CheckBoxState::HIDDEN}, {"add_d_ions", "Add peaks of d-ions to the spectrum (nucleotide sequences only)"},
{"d_intensity", "Intensity of the d-ions"}),
CheckBox(&(ui_->w_intensity), &(ui_->w_label), {CheckBoxState::HIDDEN, CheckBoxState::ENABLED, CheckBoxState::HIDDEN}, {"add_w_ions", "Add peaks of w-ions to the spectrum (nucleotide sequences only)"},
{"w_intensity", "Intensity of the w-ions"}),
CheckBox(&(ui_->x_intensity), &(ui_->x_label), {CheckBoxState::ENABLED, CheckBoxState::ENABLED, CheckBoxState::HIDDEN}, {"add_x_ions", "Add peaks of x-ions to the spectrum"},
{"x_intensity", "Intensity of the x-ions"}),
CheckBox(&(ui_->y_intensity), &(ui_->y_label), {CheckBoxState::PRECHECKED, CheckBoxState::PRECHECKED, CheckBoxState::HIDDEN}, {"add_y_ions", "Add peaks of y-ions to the spectrum"},
{"y_intensity", "Intensity of the y-ions"}),
CheckBox(&(ui_->z_intensity), &(ui_->z_label), {CheckBoxState::ENABLED, CheckBoxState::ENABLED, CheckBoxState::HIDDEN}, {"add_z_ions", "Add peaks of z-ions to the spectrum"},
{"z_intensity", "Intensity of the z-ions"}),
CheckBox(nullptr, nullptr, {CheckBoxState::ENABLED, CheckBoxState::ENABLED, CheckBoxState::HIDDEN},
{"add_precursor_peaks", "Adds peaks of the precursor to the spectrum, which happen to occur sometimes"}, {"", ""}),
// Neutral losses: ui_->rel_loss_intensity is a normal spin box and has to be checked manually
CheckBox(nullptr, nullptr, {CheckBoxState::ENABLED, CheckBoxState::HIDDEN, CheckBoxState::HIDDEN},
{"add_losses", "Adds common losses to those ion expect to have them, only water and ammonia loss is considered (peptide sequences only)"}, {"", ""}),
CheckBox(nullptr, nullptr, {CheckBoxState::ENABLED, CheckBoxState::HIDDEN, CheckBoxState::HIDDEN},
{"add_abundant_immonium_ions", "Add most abundant immonium ions (peptide sequences only)"}, {"", ""})}
{
ui_->setupUi(this);
// if dialog is accepted, try generating a spectrum, only close dialog on success
connect(ui_->dialog_buttons, &QDialogButtonBox::accepted, this, &TheoreticalSpectrumGenerationDialog::calculateSpectrum_);
// signals for changing isotope model interface
connect(ui_->model_none_button, &QRadioButton::toggled, this, &TheoreticalSpectrumGenerationDialog::modelChanged_);
connect(ui_->model_coarse_button, &QRadioButton::toggled, this, &TheoreticalSpectrumGenerationDialog::modelChanged_);
connect(ui_->model_fine_button, &QRadioButton::toggled, this, &TheoreticalSpectrumGenerationDialog::modelChanged_);
// for the list widget items are checked/unchecked if they are clicked on (disables clicking on the check box though ..)
connect(ui_->ion_types, &QListWidget::itemClicked, this, &TheoreticalSpectrumGenerationDialog::listWidgetItemClicked_);
// don't add any isotopes by default and update interface
ui_->model_none_button->setChecked(true);
modelChanged_(); //because setting the check state of the button doesn't call 'toggled'
// signal for changing interface depending on sequence type
connect(ui_->seq_type, &QComboBox::currentTextChanged, this, &TheoreticalSpectrumGenerationDialog::seqTypeSwitch_);
// To set the interface and members
seqTypeSwitch_();
for (size_t i = 0; i < check_boxes_.size(); ++i)
{
if (check_boxes_.at(i).state.at(0) == CheckBoxState::PRECHECKED) // 'state.at(0)' because seq type was just set to "Peptide"
{
ui_->ion_types->item(i)->setCheckState(Qt::Checked);
}
else
{
ui_->ion_types->item(i)->setCheckState(Qt::Unchecked);
}
}
// automatic layout
// disables manual resizing from the user
layout()->setSizeConstraint(QLayout::SetFixedSize);
}
TheoreticalSpectrumGenerationDialog::~TheoreticalSpectrumGenerationDialog()
{
delete ui_;
}
const String TheoreticalSpectrumGenerationDialog::getSequence() const
{
return ui_->seq_input->text();
}
Param TheoreticalSpectrumGenerationDialog::getParam_() const
{
Param p;
if (seq_type_ != SequenceType::METABOLITE) // no ions for metabolite input
{
// add check boxes to parameters, i.e. ion types
for (size_t i = 0; i < check_boxes_.size(); ++i)
{
// for peptide input skip rna specific ions
if (seq_type_ == SequenceType::PEPTIDE && (check_boxes_.at(i).state.at(0) == CheckBoxState::HIDDEN))
continue;
// for rna input skip peptide specific ions
if (seq_type_ == SequenceType::RNA && (check_boxes_.at(i).state.at(1) == CheckBoxState::HIDDEN))
continue;
// set ion itself
bool status = (ui_->ion_types->item(i)->checkState() == Qt::Checked);
p.setValue(check_boxes_.at(i).param_this.first, status ? "true" : "false", check_boxes_.at(i).param_this.second);
// set intensity of ion
if (status)
{
QDoubleSpinBox** spin_ptr = check_boxes_.at(i).ptr_to_spin_box;
if (spin_ptr == nullptr)
continue;
p.setValue(check_boxes_.at(i).param_spin.first, (*spin_ptr)->value(), check_boxes_.at(i).param_spin.second);
}
}
}
// charge
p.setValue("charge", ui_->charge_spinbox->value());
if (!(seq_type_ == SequenceType::RNA)) // skip isotope pattern for RNA input
{
// isotopes
if (!ui_->model_none_button->isChecked()) // add isotopes if any other model than 'None' is chosen
{
bool coarse_model = ui_->model_coarse_button->isChecked();
String model = coarse_model ? "coarse" : "fine";
p.setValue("isotope_model", model,
"Model to use for isotopic peaks ('none' means no isotopic peaks are added, 'coarse' adds isotopic peaks in unit mass distance, 'fine' uses the hyperfine isotopic generator to add "
"accurate isotopic peaks. Note that adding isotopic peaks is very slow.");
if (coarse_model)
{
Size max_iso_count = (Size)ui_->max_iso_spinbox->value();
p.setValue("max_isotope", max_iso_count, "Defines the maximal isotopic peak which is added if 'isotope_model' is 'coarse'");
}
else
{
double max_iso_prob = (double)ui_->max_iso_prob_spinbox->value() / 100.;
p.setValue("max_isotope_probability", max_iso_prob, "Defines the maximal isotopic probability to cover if 'isotope_model' is 'fine'");
}
}
else // don't add isotopes
{
p.setValue("isotope_model", "none",
"Model to use for isotopic peaks ('none' means no isotopic peaks are added, 'coarse' adds isotopic peaks in unit mass distance, 'fine' uses the hyperfine isotopic generator to add "
"accurate isotopic peaks. Note that adding isotopic peaks is very slow.");
}
if (seq_type_ == SequenceType::PEPTIDE)
{
// loss intensity
double rel_loss_int = (double)(ui_->rel_loss_intensity->value()) / 100.0;
p.setValue("relative_loss_intensity", rel_loss_int, "Intensity of loss ions, in relation to the intact ion intensity");
}
}
return p;
}
const MSSpectrum& TheoreticalSpectrumGenerationDialog::getSpectrum() const
{
return spec_;
}
void TheoreticalSpectrumGenerationDialog::calculateSpectrum_()
{
if (!spec_.empty()) spec_.clear(true);
String seq_string(this->getSequence());
if (seq_string.empty())
{
const std::array<String, 3> types{"Peptide", "RNA", "Metabolite"};
QMessageBox::warning(this, "Error", QString("You must enter a ") + QString::fromStdString(types.at(int(seq_type_))) + " sequence!");
return;
}
AASequence aa_sequence;
NASequence na_sequence;
EmpiricalFormula ef;
try
{
if (seq_type_ == SequenceType::PEPTIDE)
{
aa_sequence = AASequence::fromString(seq_string);
}
else if (seq_type_ == SequenceType::RNA)
{
na_sequence = NASequence::fromString(seq_string);
}
else
{
ef = EmpiricalFormula::fromString(seq_string);
}
}
catch (Exception::BaseException& e)
{
QMessageBox::warning(this, "Error", QString("Spectrum generation failed! (") + e.what() + ")");
return;
}
Param p = this->getParam_();
Int charge = p.getValue("charge");
p.remove("charge"); // "charge" isn't a parameter of TheoreticalSpectrumGenerator
p.setValue("add_metainfo", "true", "Adds the type of peaks as metainfo to the peaks, like y8+, [M-H2O+2H]++");
TheoreticalSpectrumGenerator pep_generator;
NucleicAcidSpectrumGenerator na_generator;
try
{
if (seq_type_ == SequenceType::PEPTIDE)
{
p.setValue("add_first_prefix_ion", "true"); // do not skip b1 ion
pep_generator.setParameters(p);
pep_generator.getSpectrum(spec_, aa_sequence, charge, charge);
}
else if (seq_type_ == SequenceType::RNA)
{
na_generator.setParameters(p);
na_generator.getSpectrum(spec_, na_sequence, charge, charge);
}
else // metabolite
{
IsotopeDistribution dist;
if (p.getValue("isotope_model") == "coarse")
{
dist = ef.getIsotopeDistribution(CoarseIsotopePatternGenerator(Int(p.getValue("max_isotope"))));
}
else if (p.getValue("isotope_model") == "fine")
{
dist = ef.getIsotopeDistribution(FineIsotopePatternGenerator(double(p.getValue("max_isotope_probability"))));
}
else
{
QMessageBox::warning(this, "Error", QString("Isotope model 'None' is not supported for metabolite input!"));
return;
}
for (const auto& it : dist)
{
// currently no meta data is written in this setting
spec_.emplace_back(it.getMZ() / charge, it.getIntensity());
}
}
}
catch (Exception::BaseException& e)
{
QMessageBox::warning(this, "Error", QString("Spectrum generation failed! (") + e.what() + "). Please report this to the developers (specify what input you used)!");
return;
}
if (spec_.empty())
{
QMessageBox::warning(this, "Error", QString("The generated spectrum was empty and will not be drawn!"));
return;
}
this->accept();
}
void TheoreticalSpectrumGenerationDialog::modelChanged_()
{
if (ui_->model_none_button->isChecked())
{
ui_->max_iso_label->setEnabled(false);
ui_->max_iso_spinbox->setEnabled(false);
ui_->max_iso_prob_label->setEnabled(false);
ui_->max_iso_prob_spinbox->setEnabled(false);
}
else if (ui_->model_coarse_button->isChecked())
{
ui_->max_iso_label->setEnabled(true);
ui_->max_iso_spinbox->setEnabled(true);
ui_->max_iso_prob_label->setEnabled(false);
ui_->max_iso_prob_spinbox->setEnabled(false);
}
else if (ui_->model_fine_button->isChecked())
{
ui_->max_iso_label->setEnabled(false);
ui_->max_iso_spinbox->setEnabled(false);
ui_->max_iso_prob_label->setEnabled(true);
ui_->max_iso_prob_spinbox->setEnabled(true);
}
}
void TheoreticalSpectrumGenerationDialog::seqTypeSwitch_()
{
// save current sequence type setting in member
String tmp = ui_->seq_type->currentText();
if (tmp == "Peptide")
{
seq_type_ = SequenceType::PEPTIDE;
}
else if (tmp == "RNA")
{
seq_type_ = SequenceType::RNA;
}
else if (tmp == "Metabolite")
{
seq_type_ = SequenceType::METABOLITE;
}
else
{
// this will be reached if the entries of the sequence type combo box are changed
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Setting for the sequence type unkown! Was: " + tmp);
}
if (seq_type_ == SequenceType::PEPTIDE)
{
// change sequence label
ui_->enter_seq_label->setText("Enter sequence: ");
// enable ion types and intensities
ui_->ion_types->setHidden(false);
ui_->ion_types_label->setHidden(false);
ui_->intensities->setHidden(false);
updateIonTypes_();
// enable isotopes
ui_->isotope_model->setHidden(false);
modelChanged_();
// enable isotope model 'none'
ui_->model_none_button->setEnabled(true);
}
else
{
if (seq_type_ == SequenceType::RNA) // rna input
{
// change sequence label
ui_->enter_seq_label->setText("Enter sequence: ");
// enable ion types and intensities
ui_->ion_types->setHidden(false);
ui_->ion_types_label->setHidden(false);
ui_->intensities->setHidden(false);
updateIonTypes_();
// disable isotopes
ui_->isotope_model->setHidden(true);
}
else // metabolite input
{
// change sequence label
ui_->enter_seq_label->setText("Enter empirical formula (e.g. C6H12O6): ");
// enable isotopes
ui_->isotope_model->setHidden(false);
modelChanged_();
// disable isotope model 'none'
ui_->model_none_button->setEnabled(false);
if (ui_->model_none_button->isChecked())
{
ui_->model_fine_button->setChecked(true);
}
// disable ion types and intensities
ui_->ion_types->setHidden(true);
ui_->ion_types_label->setHidden(true);
ui_->intensities->setHidden(true);
}
}
}
void TheoreticalSpectrumGenerationDialog::listWidgetItemClicked_(QListWidgetItem* item)
{
if (item->checkState() == Qt::CheckState::Checked)
{
item->setCheckState(Qt::CheckState::Unchecked);
return;
}
item->setCheckState(Qt::CheckState::Checked);
return;
}
void TheoreticalSpectrumGenerationDialog::updateIonTypes_()
{
int input_type;
if (seq_type_ == SequenceType::PEPTIDE)
input_type = 0;
else if (seq_type_ == SequenceType::RNA)
input_type = 1;
else // Metabolite
input_type = 2;
for (size_t i = 0; i < check_boxes_.size(); ++i)
{
const CheckBox* curr_box = &check_boxes_.at(i);
bool hidden(curr_box->state.at(input_type) == CheckBoxState::HIDDEN);
// activate check box
ui_->ion_types->item(i)->setHidden(hidden);
// activte intensity with label
QDoubleSpinBox** spin_ptr = curr_box->ptr_to_spin_box;
if (spin_ptr == nullptr)
{
// manually check for neutral losses
if (curr_box->param_this.first == "add_losses")
{
ui_->rel_loss_intensity->setHidden(hidden);
ui_->rel_loss_label->setHidden(hidden);
}
continue;
}
(*spin_ptr)->setHidden(hidden);
QLabel** label_ptr = curr_box->ptr_to_spin_label;
if (label_ptr == nullptr)
continue;
(*label_ptr)->setHidden(hidden);
}
}
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/TOPPViewPrefDialog.cpp | .cpp | 6,714 | 153 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Chris Bielow $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/TOPPViewPrefDialog.h>
#include <ui_TOPPViewPrefDialog.h>
#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h>
#include <OpenMS/COMPARISON/SpectrumAlignment.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <QtWidgets/QFileDialog>
using namespace std;
namespace OpenMS
{
namespace Internal
{
TOPPViewPrefDialog::TOPPViewPrefDialog(QWidget* parent) :
QDialog(parent),
ui_(new Ui::TOPPViewPrefDialogTemplate),
tsg_param_(TheoreticalSpectrumGenerator().getParameters())
{
ui_->setupUi(this);
ui_->param_editor_spec_gen_->load(tsg_param_);
connect(ui_->browse_default, &QPushButton::clicked, this, &TOPPViewPrefDialog::browseDefaultPath_);
connect(ui_->browse_plugins, &QPushButton::clicked, this, &TOPPViewPrefDialog::browsePluginsPath_);
}
TOPPViewPrefDialog::~TOPPViewPrefDialog()
{
delete ui_;
}
const char* tsg_prefix = "idview:tsg:";
void TOPPViewPrefDialog::setParam(const Param& param)
{
param_ = getParam(); // get our own defaults
// make sure the params we write (using getParam) are the same as the ones we can read
param_.update(param, true, true, true, true, getGlobalLogInfo());
// general tab
ui_->default_path->setText(String(param_.getValue("default_path").toString()).toQString());
ui_->default_path_current->setChecked(param_.getValue("default_path_current").toBool());
ui_->plugins_path->setText(String(param_.getValue("plugins_path").toString()).toQString());
ui_->use_cached_ms1->setChecked(param_.getValue("use_cached_ms1").toBool());
ui_->use_cached_ms2->setChecked(param_.getValue("use_cached_ms2").toBool());
ui_->map_default->setCurrentIndex(ui_->map_default->findText(String(param_.getValue("default_map_view").toString()).toQString()));
ui_->map_cutoff->setCurrentIndex(ui_->map_cutoff->findText(String(param_.getValue("intensity_cutoff").toString()).toQString()));
ui_->on_file_change->setCurrentIndex(ui_->on_file_change->findText(String(param_.getValue("on_file_change").toString()).toQString()));
// 1D view
ui_->color_1D->setColor(QColor(String(param_.getValue("1d:peak_color").toString()).toQString()));
ui_->selected_1D->setColor(QColor(String(param_.getValue("1d:highlighted_peak_color").toString()).toQString()));
ui_->icon_1D->setColor(QColor(String(param_.getValue("1d:icon_color").toString()).toQString()));
// 2D view
ui_->peak_2D->gradient().fromString(param_.getValue("2d:dot:gradient"));
ui_->feature_icon_2D->setCurrentIndex(ui_->feature_icon_2D->findText(String(param_.getValue("2d:dot:feature_icon").toString()).toQString()));
ui_->feature_icon_size_2D->setValue((Int)param_.getValue("2d:dot:feature_icon_size"));
// 3D view
ui_->peak_3D->gradient().fromString(param_.getValue("3d:dot:gradient"));
ui_->shade_3D->setCurrentIndex((Int)param_.getValue("3d:dot:shade_mode"));
ui_->line_width_3D->setValue((Int)param_.getValue("3d:dot:line_width"));
// TSG view
tsg_param_ = param_.copy(tsg_prefix, true);
ui_->param_editor_spec_gen_->load(tsg_param_);
ui_->tolerance->setValue((double)param_.getValue("idview:align:tolerance"));
ui_->unit->setCurrentIndex(ui_->unit->findText(String(param_.getValue("idview:align:is_relative_tolerance") == "true" ? "ppm" : "Da").toQString()));
}
String fromCheckState(const Qt::CheckState cs)
{
switch (cs)
{
case Qt::CheckState::Checked: return "true";
case Qt::CheckState::Unchecked: return "false";
default: throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Checkbox had unexpected state", String(cs));
}
}
Param TOPPViewPrefDialog::getParam() const
{
Param p;
p.setValue("default_path", ui_->default_path->text().toStdString());
p.setValue("default_path_current", fromCheckState(ui_->default_path_current->checkState()));
p.setValue("plugins_path", ui_->plugins_path->text().toStdString());
p.setValue("use_cached_ms1", fromCheckState(ui_->use_cached_ms1->checkState()));
p.setValue("use_cached_ms2", fromCheckState(ui_->use_cached_ms2->checkState()));
p.setValue("default_map_view", ui_->map_default->currentText().toStdString());
p.setValue("intensity_cutoff", ui_->map_cutoff->currentText().toStdString());
p.setValue("on_file_change", ui_->on_file_change->currentText().toStdString());
p.setValue("1d:peak_color", ui_->color_1D->getColor().name().toStdString());
p.setValue("1d:highlighted_peak_color", ui_->selected_1D->getColor().name().toStdString());
p.setValue("1d:icon_color", ui_->icon_1D->getColor().name().toStdString());
p.setValue("2d:dot:gradient", ui_->peak_2D->gradient().toString());
p.setValue("2d:dot:feature_icon", ui_->feature_icon_2D->currentText().toStdString());
p.setValue("2d:dot:feature_icon_size", ui_->feature_icon_size_2D->value());
p.setValue("3d:dot:gradient", ui_->peak_3D->gradient().toString());
p.setValue("3d:dot:shade_mode", ui_->shade_3D->currentIndex());
p.setValue("3d:dot:line_width", ui_->line_width_3D->value());
// TSG view
ui_->param_editor_spec_gen_->store(); // to tsg_param_
p.insert(tsg_prefix, tsg_param_);
// from SpectrumAlignment
p.setValue("idview:align:tolerance", ui_->tolerance->value(), "Alignment tolerance value");
p.setValue("idview:align:is_relative_tolerance", ui_->unit->currentText().toStdString() == "ppm" ? "true" : "false", "Alignment tolerance unit (Da, ppm)");
param_ = p;
return param_;
}
void TOPPViewPrefDialog::browseDefaultPath_()
{
QString path = QFileDialog::getExistingDirectory(this, "Choose a directory", ui_->default_path->text());
if (!path.isEmpty())
{
ui_->default_path->setText(path);
}
}
void TOPPViewPrefDialog::browsePluginsPath_()
{
QString path = QFileDialog::getExistingDirectory(this, "Choose a directory", ui_->plugins_path->text());
if (!path.isEmpty())
{
ui_->plugins_path->setText(path);
}
}
} //namespace Internal
} //namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/TOPPViewOpenDialog.cpp | .cpp | 4,053 | 182 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/TOPPViewOpenDialog.h>
#include <ui_TOPPViewOpenDialog.h>
#include <OpenMS/config.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/String.h>
// QT includes
#include <QtWidgets/QButtonGroup>
// STL includes
#include <iostream>
using namespace std;
namespace OpenMS
{
TOPPViewOpenDialog::TOPPViewOpenDialog(const String & data_name, bool as_window, bool as_2d, bool cutoff, QWidget * parent) :
QDialog(parent),
map_as_2d_disabled_(false),
ui_(new Ui::TOPPViewOpenDialogTemplate)
{
ui_->setupUi(this);
//init map view
if (!as_2d)
{
ui_->d1_->setChecked(true);
ui_->d1_->setFocus();
}
else
{
ui_->d2_->setChecked(true);
ui_->d2_->setFocus();
}
//init intensity cutoff
if (cutoff)
{
ui_->intensity_cutoff_->setChecked(true);
}
//init open as
if (!as_window)
{
ui_->layer_->setChecked(true);
ui_->layer_->setFocus();
}
else
{
ui_->window_->setChecked(true);
ui_->window_->setFocus();
}
connect(ui_->merge_combo_, SIGNAL(activated(int)), ui_->merge_, SLOT(click()));
//set title
setWindowTitle((String("Open data options for ") + data_name).toQString());
}
TOPPViewOpenDialog::~TOPPViewOpenDialog()
{
delete ui_;
}
bool TOPPViewOpenDialog::viewMapAs2D() const
{
return ui_->d2_->isChecked();
}
bool TOPPViewOpenDialog::viewMapAs1D() const
{
return ui_->d1_->isChecked();
}
bool TOPPViewOpenDialog::isCutoffEnabled() const
{
return ui_->intensity_cutoff_->isChecked();
}
bool TOPPViewOpenDialog::isDataDIA() const
{
return ui_->dia_data_->isChecked();
}
bool TOPPViewOpenDialog::openAsNewWindow() const
{
return ui_->window_->isChecked();
}
void TOPPViewOpenDialog::disableDimension(bool as_2d)
{
ui_->d1_->setChecked(!as_2d);
ui_->d1_->setEnabled(false);
ui_->d2_->setChecked(as_2d);
ui_->d2_->setEnabled(false);
ui_->d3_->setEnabled(false);
map_as_2d_disabled_ = true;
}
void TOPPViewOpenDialog::disableCutoff(bool /* cutoff_on */)
{
ui_->intensity_cutoff_->setChecked(false);
}
void TOPPViewOpenDialog::disableLocation(bool as_window)
{
ui_->window_->setEnabled(false);
ui_->layer_->setEnabled(false);
ui_->merge_->setEnabled(false);
ui_->merge_combo_->setEnabled(false);
if (as_window)
{
ui_->window_->setChecked(true);
}
else
{
ui_->layer_->setChecked(true);
}
}
void TOPPViewOpenDialog::updateViewMode_(QAbstractButton * button)
{
if (button == ui_->layer_ || button == ui_->merge_)
{
ui_->d1_->setEnabled(false);
ui_->d2_->setEnabled(false);
ui_->d3_->setEnabled(false);
}
else if (!map_as_2d_disabled_)
{
ui_->d1_->setEnabled(true);
ui_->d2_->setEnabled(true);
ui_->d3_->setEnabled(true);
}
}
void TOPPViewOpenDialog::setMergeLayers(const std::map<Size, String> & layers)
{
// remove all items
ui_->merge_combo_->clear();
if (!layers.empty())
{
ui_->merge_->setEnabled(true);
ui_->merge_combo_->setEnabled(true);
UInt i = 0;
for (const auto& it : layers)
{
ui_->merge_combo_->insertItem(i++, it.second.toQString(), (int)(it.first));
}
}
else
{
ui_->merge_->setEnabled(false);
ui_->merge_combo_->setEnabled(false);
}
}
Int TOPPViewOpenDialog::getMergeLayer() const
{
if (ui_->merge_->isChecked())
{
return ui_->merge_combo_->itemData(ui_->merge_combo_->currentIndex()).toInt();
}
return -1;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/FLASHDeconvTabWidget.cpp | .cpp | 13,231 | 374 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Jihyung Kim $
// $Authors: Jihyung Kim $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/DIALOGS/FLASHDeconvTabWidget.h>
#include <OpenMS/VISUAL/DIALOGS/WizardHelper.h>
#include <ui_FLASHDeconvTabWidget.h>
#include <QDesktopServices>
#include <QMessageBox>
#include <QProcess>
#include <QProgressDialog>
#include <QSignalBlocker>
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <algorithm>
using namespace std;
namespace OpenMS
{
namespace Internal
{
template class WizardGUILock<FLASHDeconvTabWidget>;
String getFLASHDeconvExe()
{
return File::findSiblingTOPPExecutable("FLASHDeconv");
}
QString getFDDefaultOutDir()
{
auto dir = QDir::homePath().append("/FLASHDeconvOut");
if (!QDir().exists(dir))
QDir().mkpath(dir);
return dir;
}
FLASHDeconvTabWidget::FLASHDeconvTabWidget(QWidget* parent) :
QTabWidget(parent),
ui(new Ui::FLASHDeconvTabWidget),
ep_([&](const String& out) { writeLog_(out.toQString()); },
[&](const String& out) { writeLog_(out.toQString()); })
{
ui->setupUi(this);
writeLog_(QString("Welcome to the Wizard!"), Qt::darkGreen, true);
// keep the group of input widgets in sync with respect to their current-working-dir, when browsing for new files
connect(ui->input_mzMLs, &InputFileList::updatedCWD, this, &FLASHDeconvTabWidget::broadcastNewCWD_);
// check the "checkbox_spec" true (output files for masses per spectrum)
ui->checkbox_spec->setCheckState(Qt::Checked);
// param setting
setWidgetsfromFDDefaultParam_();
ui->out_dir->setDirectory(getFDDefaultOutDir());
}
FLASHDeconvTabWidget::~FLASHDeconvTabWidget()
{
delete ui;
}
String infileToFDoutput(const String& infile)
{
return FileHandler::swapExtension(File::basename(infile), FileTypes::TSV);
}
StringList FLASHDeconvTabWidget::getMzMLInputFiles() const
{
return ui->input_mzMLs->getFilenames();
}
void FLASHDeconvTabWidget::on_run_fd_clicked()
{
if (!checkFDInputReady_())
return;
WizardGUILock lock(this); // forbid user interaction
// get parameter
updateFLASHDeconvParamFromWidgets_();
updateOutputParamFromWidgets_();
Param fd_param;
fd_param.insert("FLASHDeconv:1:", flashdeconv_param_);
String tmp_ini = File::getTemporaryFile();
StringList in_mzMLs = getMzMLInputFiles();
writeLog_(QString("Starting FLASHDeconv with %1 mzML file(s)").arg(in_mzMLs.size()), Qt::darkGreen, true);
QProgressDialog progress("Running FLASHDeconv ", "Abort ...", 0, (int)in_mzMLs.size(), this);
progress.setWindowModality(Qt::ApplicationModal);
progress.setMinimumDuration(0); // show immediately
progress.setValue(0);
int step = 0;
for (const auto& mzML : in_mzMLs)
{
updateOutputParamFromPerInputFile(mzML.toQString());
Param tmp_param = Param(fd_param);
tmp_param.insert("FLASHDeconv:1:", flashdeconv_param_outputs_);
ParamXMLFile().store(tmp_ini, tmp_param);
auto r = ep_.run(this,
getFLASHDeconvExe().toQString(),
QStringList() << "-ini" << tmp_ini.toQString()
<< "-in" << mzML.toQString()
<< "-out" << getCurrentOutDir_() + "/" + infileToFDoutput(mzML).toQString(),
"",
true);
if (r != ExternalProcess::RETURNSTATE::SUCCESS)
break;
if (progress.wasCanceled())
break;
progress.setValue(++step);
} // mzML loop
progress.close();
}
void FLASHDeconvTabWidget::on_edit_advanced_parameters_clicked()
{
// refresh 'flashdeconv_param_' from data within the Wizards controls
updateFLASHDeconvParamFromWidgets_();
Param tmp_param = flashdeconv_param_;
// show the parameters to the user
String executable = File::getExecutablePath() + "INIFileEditor";
String tmp_file = File::getTemporaryFile();
ParamXMLFile().store(tmp_file, tmp_param);
QProcess qp;
qp.start(executable.toQString(), QStringList() << tmp_file.toQString());
ui->tab_run->setEnabled(false); // grey out the Wizard until INIFileEditor returns...
qp.waitForFinished(-1);
ui->tab_run->setEnabled(true);
ParamXMLFile().load(tmp_file, tmp_param);
flashdeconv_param_.update(tmp_param, false);
}
void FLASHDeconvTabWidget::on_open_output_directory_clicked()
{
QDesktopServices::openUrl(QUrl::fromLocalFile(getCurrentOutDir_()));
}
void FLASHDeconvTabWidget::updateFLASHDeconvParamFromWidgets_()
{
ui->list_editor->store();
}
void FLASHDeconvTabWidget::updateOutputParamFromWidgets_()
{
// refresh output params with default values
flashdeconv_output_tags_.clear();
// get checkbox results from the Wizard control
if (ui->checkbox_spec->isChecked())
{
flashdeconv_output_tags_.emplace_back("out_spec1");
flashdeconv_output_tags_.emplace_back("out_spec2");
flashdeconv_output_tags_.emplace_back("out_spec3");
flashdeconv_output_tags_.emplace_back("out_spec4");
}
if (ui->checkbox_mzml->isChecked())
{
flashdeconv_output_tags_.emplace_back("out_mzml");
flashdeconv_output_tags_.emplace_back("out_annotated_mzml");
}
if (ui->checkbox_quant->isChecked())
{
flashdeconv_output_tags_.emplace_back("out_quant");
}
if (ui->checkbox_topfd->isChecked())
{
flashdeconv_output_tags_.emplace_back("out_msalign1");
flashdeconv_output_tags_.emplace_back("out_msalign2");
flashdeconv_output_tags_.emplace_back("out_feature1");
flashdeconv_output_tags_.emplace_back("out_feature2");
}
// optional FLASHIda support part
if (ui->checkbox_readlogfile->isChecked())
{
flashdeconv_output_tags_.push_back("ida_log");
}
}
void FLASHDeconvTabWidget::updateOutputParamFromPerInputFile(const QString& input_file_name)
{
std::string filepath_without_ext = getCurrentOutDir_().toStdString() + "/" + FileHandler::stripExtension(File::basename(input_file_name));
for (const auto& param : flashdeconv_param_outputs_)
{
std::string tag = param.name;
std::string org_desc = param.description;
auto org_tags = flashdeconv_param_outputs_.getTags(tag);
// if this output format is requested by the user
bool is_requested = false;
if (!flashdeconv_output_tags_.empty() && std::find(flashdeconv_output_tags_.begin(), flashdeconv_output_tags_.end(), tag) != flashdeconv_output_tags_.end())
{
is_requested = true;
}
if (tag == "out_mzml" || tag == "out_annotated_mzml" || tag == "out_quant" || tag == "ida_log"
|| tag == "out_spec1"|| tag == "out_spec2"|| tag == "out_spec3"|| tag == "out_spec4"
|| tag == "out_msalign1" || tag == "out_msalign2"
|| tag == "out_feature1" || tag == "out_feature2") // params having string values // params having string values
{
// if not requested, set default value
if (!is_requested)
{
flashdeconv_param_outputs_.setValue(tag, "", org_desc, org_tags);
continue;
}
// if requested, set file path accordingly
String out_path = filepath_without_ext;
if (tag == "out_mzml")
{
out_path += "_deconv.mzML";
}
else if (tag == "out_annotated_mzml")
{
out_path += "_annotated.mzML";
}
else if (tag == "out_quant")
{
out_path += "_quant.tsv";
}
else if (tag == "ida_log")
{
String dir_path_only = File::path(input_file_name);
String file_name_only = FileHandler::stripExtension(File::basename(input_file_name));
out_path = dir_path_only + '/' + "IDALog_" + file_name_only + ".log";
}
else if (tag == "out_spec1")
{
out_path += "_ms1.tsv";
}
else if (tag == "out_spec2")
{
out_path += "_ms2.tsv";
}
else if (tag == "out_spec3")
{
out_path += "_ms3.tsv";
}
else if (tag == "out_spec4")
{
out_path += "_ms4.tsv";
}
else if (tag == "out_msalign1")
{
out_path += "_ms1.msalign";
}
else if (tag == "out_msalign2")
{
out_path += "_ms2.msalign";
}
else if (tag == "out_feature1")
{
out_path += "_ms1.feature";
}
else if (tag == "out_feature2")
{
out_path += "_ms2.feature";
}
flashdeconv_param_outputs_.setValue(tag, out_path, org_desc, org_tags);
}
else // Params with values as stringList
{
// if not requested, set default value
if (!is_requested)
{
std::vector<std::string> tmp;
flashdeconv_param_outputs_.setValue(tag, tmp, org_desc, org_tags);
continue;
}
}
}
}
void FLASHDeconvTabWidget::setWidgetsfromFDDefaultParam_()
{
// create a default INI of FLASHDeconv
String tmp_file = File::getTemporaryFile();
if (ep_.run(this, getFLASHDeconvExe().toQString(), QStringList() << "-write_ini" << tmp_file.toQString(), "", true) != ExternalProcess::RETURNSTATE::SUCCESS)
{
exit(1);
}
ParamXMLFile().load(tmp_file, flashdeconv_param_);
flashdeconv_param_ = flashdeconv_param_.copy("FLASHDeconv:1:", true);
// parameters to show in default mode : flashdeconv_param_wizard_
flashdeconv_param_.remove("log");
flashdeconv_param_.remove("no_progress");
flashdeconv_param_.remove("debug");
flashdeconv_param_.remove("in");
flashdeconv_param_.remove("out");
// parameters for different output format
StringList out_params = {"out_spec1","out_spec2","out_spec3","out_spec4", "out_annotated_mzml", "out_mzml",
"out_quant", "out_msalign1", "out_feature1", "out_msalign2", "out_feature2"};
for (const auto& name : out_params)
flashdeconv_param_outputs_.setValue(name, ""); // create a dummy param, just so we can use ::copySubset
flashdeconv_param_outputs_ = flashdeconv_param_.copySubset(flashdeconv_param_outputs_);
// remove output format params from global parameter set
for (const auto& name : out_params)
flashdeconv_param_.remove(name);
// add ida_log parameter to flashdeconv_param_outputs_ (rename ida_log to get it out of "FD:" prefix)
flashdeconv_param_outputs_.setValue("ida_log", "", flashdeconv_param_.getDescription("FD:ida_log"), flashdeconv_param_.getTags("FD:ida_log"));
flashdeconv_param_.remove("FD:ida_log");
ui->list_editor->load(flashdeconv_param_);
}
QString FLASHDeconvTabWidget::getCurrentOutDir_() const
{
QString out_dir(ui->out_dir->dirNameValid() ? ui->out_dir->getDirectory() : getFDDefaultOutDir());
return out_dir;
}
void FLASHDeconvTabWidget::writeLog_(const QString& text, const QColor& color, bool new_section)
{
QColor tc = ui->log_text->textColor();
if (new_section)
{
ui->log_text->setTextColor(Qt::darkBlue);
ui->log_text->append(QString(10, '#').append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")).append(QString(10, '#')).append("\n"));
ui->log_text->setTextColor(tc);
}
ui->log_text->setTextColor(color);
ui->log_text->append(text);
ui->log_text->setTextColor(tc); // restore old color
}
void FLASHDeconvTabWidget::writeLog_(const String& text, const QColor& color, bool new_section)
{
writeLog_(text.toQString(), color, new_section);
}
bool FLASHDeconvTabWidget::checkFDInputReady_()
{
if (ui->input_mzMLs->getFilenames().empty())
{
QMessageBox::critical(this, "Error", "Input mzML file(s) are missing! Please provide at least one!");
return false;
}
return true;
}
void FLASHDeconvTabWidget::broadcastNewCWD_(const QString& new_cwd)
{
// RAII to avoid infinite loop (setCWD signals updatedCWD which is connected to slot broadcastNewCWD_)
QSignalBlocker blocker1(ui->input_mzMLs);
ui->input_mzMLs->setCWD(new_cwd);
}
} // namespace Internal
} // namespace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/ToolsDialog.cpp | .cpp | 14,166 | 471 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/ToolsDialog.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/APPLICATIONS/ToolHandler.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/ParamEditor.h>
#include <OpenMS/VISUAL/TVToolDiscovery.h>
#include <OpenMS/VISUAL/MISC/CommonDefs.h>
#include <QProcess>
#include <QtCore/QStringList>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QRadioButton>
#include <utility>
using namespace std;
namespace OpenMS
{
ToolsDialog::ToolsDialog(
QWidget* parent,
const Param& params,
String ini_file,
String default_dir,
LayerDataBase::DataType layer_type,
const String& layer_name,
TVToolDiscovery* tool_scanner) :
QDialog(parent),
ini_file_(std::move(ini_file)),
default_dir_(std::move(default_dir)),
tool_params_(params.copy("tool_params:", true)),
plugin_params_(),
tool_scanner_(tool_scanner),
layer_type_(layer_type)
{
auto main_grid = new QGridLayout(this);
// Layer label
auto layer_label = new QLabel("Selected Layer:");
main_grid->addWidget(layer_label, 0, 0);
auto layer_label_name = new QLabel(layer_name.toQString());
main_grid->addWidget(layer_label_name, 0, 1);
auto label = new QLabel("TOPP tool:");
main_grid->addWidget(label, 1, 0);
// Determine all available tools compatible with the layer_type
tool_map_ = {
{FileTypes::Type::MZML, LayerDataBase::DataType::DT_PEAK},
{FileTypes::Type::MZXML, LayerDataBase::DataType::DT_PEAK},
{FileTypes::Type::FEATUREXML, LayerDataBase::DataType::DT_FEATURE},
{FileTypes::Type::CONSENSUSXML, LayerDataBase::DataType::DT_CONSENSUS},
{FileTypes::Type::IDXML, LayerDataBase::DataType::DT_IDENT}
};
QStringList list = createToolsList_();
tools_combo_ = new QComboBox;
tools_combo_->setMinimumWidth(150);
tools_combo_->addItems(list);
connect(tools_combo_, CONNECTCAST(QComboBox, activated, (int)), this, &ToolsDialog::setTool_);
main_grid->addWidget(tools_combo_, 1, 1);
reload_plugins_button_ = new QPushButton("Reload Plugins");
connect(reload_plugins_button_, &QPushButton::clicked, this, &ToolsDialog::reloadPlugins_);
main_grid->addWidget(reload_plugins_button_, 0, 2);
label = new QLabel("input argument:");
main_grid->addWidget(label, 2, 0);
input_combo_ = new QComboBox;
main_grid->addWidget(input_combo_, 2, 1);
label = new QLabel("output argument:");
main_grid->addWidget(label, 3, 0);
output_combo_ = new QComboBox;
main_grid->addWidget(output_combo_, 3, 1);
// tools description label
tool_desc_ = new QLabel;
tool_desc_->setAlignment(Qt::AlignTop | Qt::AlignLeft);
tool_desc_->setWordWrap(true);
main_grid->addWidget(tool_desc_, 1, 2, 3, 1);
//Add advanced mode check box
editor_ = new ParamEditor(this);
main_grid->addWidget(editor_, 4, 0, 1, 5);
auto hbox = new QHBoxLayout;
auto load_button = new QPushButton(tr("&Load"));
connect(load_button, &QPushButton::clicked, this, &ToolsDialog::loadINI_);
hbox->addWidget(load_button);
auto store_button = new QPushButton(tr("&Store"));
connect(store_button, &QPushButton::clicked, this, &ToolsDialog::storeINI_);
hbox->addWidget(store_button);
hbox->addStretch();
ok_button_ = new QPushButton(tr("&Ok"));
connect(ok_button_, &QPushButton::clicked, this, &ToolsDialog::ok_);
hbox->addWidget(ok_button_);
auto cancel_button = new QPushButton(tr("&Cancel"));
connect(cancel_button, &QPushButton::clicked, this, &ToolsDialog::reject);
hbox->addWidget(cancel_button);
main_grid->addLayout(hbox, 5, 0, 1, 5);
setLayout(main_grid);
setWindowTitle(tr("Apply TOPP tool to layer"));
disable_();
}
ToolsDialog::~ToolsDialog() = default;
std::vector<LayerDataBase::DataType> ToolsDialog::getTypesFromParam_(const Param& p) const
{
// Containing all types a tool is compatible with
std::vector<LayerDataBase::DataType> types;
for (const auto& entry : p)
{
if (entry.name == "in")
{
// Map all file extension to a LayerDataBase::DataType
for (auto& file_extension : entry.valid_strings)
{
// a file extension in valid_strings is of form "*.TYPE" -> convert to substr "TYPE".
const String& file_type = file_extension.substr(2, file_extension.size());
const auto& iter = tool_map_.find(FileTypes::nameToType(file_type));
// If mapping was found
if (iter != tool_map_.end())
{
types.push_back(iter->second);
}
}
break;
}
}
return types;
}
void ToolsDialog::setInputOutputCombo_(const Param &p)
{
String str;
QStringList input_list("<select>");
QStringList output_list("<select>");
bool outRequired = false;
for (Param::ParamIterator iter = p.begin(); iter != p.end(); ++iter)
{
// iter.getName() is either of form "ToolName:1:ItemName" or "ToolName:1:NodeName:[...]:ItemName".
// Cut off "ToolName:1:"
str = iter.getName().substr(iter.getName().rfind("1:") + 2, iter.getName().size());
// Only add items and no nodes
if (!str.empty() && str.find(":") == String::npos)
{
// Only add to input list if item has "input file" tag.
if (iter->tags.find("input file") != iter->tags.end())
{
input_list << QStringList(str.c_str());
}
// Only add to output list if item has "output file" tag.
else if (iter->tags.find("output file") != iter->tags.end())
{
output_list << QStringList(str.c_str());
// Check whether the item has a required tag i.e. is mandatory.
outRequired = (outRequired) || (iter->tags.find("required") != iter->tags.end());
}
}
}
// Clear and set input combo box
input_combo_->clear();
output_combo_->clear();
input_combo_->addItems(input_list);
Int pos = input_list.indexOf("in");
if (pos != -1)
{
input_combo_->setCurrentIndex(pos);
}
// Clear and set output combo box
output_combo_->addItems(output_list);
pos = output_list.indexOf("out");
if (pos != -1 && getTool() != "FileInfo" && outRequired)
{
output_combo_->setCurrentIndex(pos);
}
}
QStringList ToolsDialog::createToolsList_()
{
//Make sure the list is empty
QStringList list;
const auto& tools = ToolHandler::getTOPPToolList();
plugin_params_ = tool_scanner_->getPluginParams();
for (auto& pair : tools)
{
std::vector<LayerDataBase::DataType> tool_types = getTypesFromParam_(tool_params_.copy(pair.first + ':'));
if (std::find(tool_types.begin(), tool_types.end(), layer_type_) != tool_types.end())
{
list << pair.first.toQString();
}
}
//TODO: Plugins get added to the list just like tools and can't be differentiated in the GUI
for (const auto& name : tool_scanner_->getPlugins())
{
std::vector<LayerDataBase::DataType> tool_types = getTypesFromParam_(plugin_params_.copy(name + ":"));
if (std::find(tool_types.begin(), tool_types.end(), layer_type_) != tool_types.end())
{
list << String(name).toQString();
}
}
//sort list alphabetically
list.sort();
list.push_front("<select tool>");
return list;
}
void ToolsDialog::createINI_()
{
enable_();
if (!arg_param_.empty())
{
tool_desc_->clear();
arg_param_.clear();
vis_param_.clear();
editor_->clear();
}
auto tool_name = getTool();
arg_param_ = tool_params_.copy(tool_name + ":");
if (arg_param_.empty())
{
arg_param_ = plugin_params_.copy(tool_name + ":");
}
tool_desc_->setText(String(arg_param_.getSectionDescription(tool_name)).toQString());
vis_param_ = arg_param_.copy(tool_name + ":1:", true);
vis_param_.remove("log");
vis_param_.remove("no_progress");
vis_param_.remove("debug");
editor_->load(vis_param_);
setInputOutputCombo_(arg_param_);
editor_->setFocus(Qt::MouseFocusReason);
}
void ToolsDialog::setTool_(int i)
{
editor_->clear();
// no tool selected
if (i == 0)
{
disable_();
return;
}
createINI_();
}
void ToolsDialog::disable_()
{
ok_button_->setEnabled(false);
input_combo_->setCurrentIndex(0);
input_combo_->setEnabled(false);
output_combo_->setCurrentIndex(0);
output_combo_->setEnabled(false);
}
void ToolsDialog::enable_()
{
ok_button_->setEnabled(true);
input_combo_->setEnabled(true);
output_combo_->setEnabled(true);
}
void ToolsDialog::ok_()
{
if (input_combo_->currentText() == "<select>" || tools_combo_->currentText() == "<select>")
{
QMessageBox::critical(this, "Error", "You have to select a tool and an input argument!");
}
else
{
editor_->store();
arg_param_.insert(getTool() + ":1:", vis_param_);
if (!File::writable(ini_file_))
{
QMessageBox::critical(this, "Error", (String("Could not write to '") + ini_file_ + "'!").c_str());
}
ParamXMLFile paramFile;
paramFile.store(ini_file_, arg_param_);
accept();
}
}
void ToolsDialog::loadINI_()
{
QString string;
filename_ = QFileDialog::getOpenFileName(this, tr("Open ini file"), default_dir_.c_str(), tr("ini files (*.ini);; all files (*.*)"));
//not file selected
if (filename_.isEmpty())
{
return;
}
enable_();
if (!arg_param_.empty())
{
arg_param_.clear();
vis_param_.clear();
editor_->clear();
}
try
{
ParamXMLFile paramFile;
paramFile.load(filename_.toStdString(), arg_param_);
}
catch (Exception::BaseException& e)
{
QMessageBox::critical(this, "Error", QString("Error loading INI file: ") + e.what());
arg_param_.clear();
return;
}
//set tool combo
Param::ParamIterator iter = arg_param_.begin();
String str;
string = iter.getName().substr(0, iter.getName().find(":")).c_str();
Int pos = tools_combo_->findText(string);
if (pos == -1)
{
QMessageBox::critical(this, "Error", (String("Cannot apply '") + string + "' tool to this layer type. Aborting!").c_str());
arg_param_.clear();
return;
}
tools_combo_->setCurrentIndex(pos);
//Extract the required parameters
vis_param_ = arg_param_.copy(getTool() + ":1:", true);
vis_param_.remove("log");
vis_param_.remove("no_progress");
vis_param_.remove("debug");
//load data into editor
editor_->load(vis_param_);
setInputOutputCombo_(arg_param_);
}
void ToolsDialog::storeINI_()
{
//nothing to save
if (arg_param_.empty())
return;
filename_ = QFileDialog::getSaveFileName(this, tr("Save ini file"), default_dir_.c_str(), tr("ini files (*.ini)"));
//not file selected
if (filename_.isEmpty())
{
return;
}
if (!filename_.endsWith(".ini"))
{
filename_.append(".ini");
}
editor_->store();
arg_param_.insert(getTool() + ":1:", vis_param_);
try
{
ParamXMLFile paramFile;
paramFile.store(filename_.toStdString(), arg_param_);
}
catch (Exception::BaseException& e)
{
QMessageBox::critical(this, "Error", QString("Error storing INI file: ") + e.what());
return;
}
}
void ToolsDialog::reloadPlugins_()
{
QStringList list = createToolsList_();
int32_t selected_index = list.indexOf(tools_combo_->currentText());
if (selected_index < 1)
{
tool_desc_->clear();
arg_param_.clear();
vis_param_.clear();
editor_->clear();
input_combo_->clear();
output_combo_->clear();
disable_();
}
tools_combo_->clear();
tools_combo_->addItems(list);
if (selected_index > 0)
{
tools_combo_->setCurrentIndex(selected_index);
createINI_();
}
}
String ToolsDialog::getOutput()
{
if (output_combo_->currentText() == "<select>")
return "";
return output_combo_->currentText();
}
String ToolsDialog::getInput()
{
return input_combo_->currentText();
}
String ToolsDialog::getTool()
{
return tools_combo_->currentText();
}
String ToolsDialog::getExtension()
{
// Try to Return the first valid string for the extension on the output parameter
// If we can't get any valid strings show an error.
String extension = FileTypes::typeToName(FileTypes::UNKNOWN);
auto validStrings = vis_param_.getValidStrings(output_combo_->currentText().toStdString());
// If we have only one valid output type use that
if (validStrings.size() == 1)
{
extension = validStrings[0];
// Remove the leading .*
extension = extension.suffix(extension.size() - 2);
}
// Otherwise the type is unknown
else
{
// If we have no valid types, produce an error
if (validStrings.empty())
{
QMessageBox::critical(this, "Error", QString("Error determining output type from tool. Tool is not compatible with TOPPView"));
}
// If we have multiple valid output types, we don't know what the file actually contains, so use UNKNOWN
}
return extension;
}
}
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/Plot3DPrefDialog.cpp | .cpp | 805 | 33 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/Plot3DPrefDialog.h>
#include <ui_Plot3DPrefDialog.h>
using namespace std;
namespace OpenMS
{
namespace Internal
{
Plot3DPrefDialog::Plot3DPrefDialog(QWidget * parent) :
QDialog(parent),
ui_(new Ui::Plot3DPrefDialogTemplate)
{
ui_->setupUi(this);
}
Plot3DPrefDialog::~Plot3DPrefDialog()
{
delete ui_;
}
} //namespace Internal
} //namspace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/TOPPASVertexNameDialog.cpp | .cpp | 1,295 | 47 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/TOPPASVertexNameDialog.h>
#include <ui_TOPPASVertexNameDialog.h>
#include <QRegularExpressionValidator>
#include <QRegularExpression>
#include <iostream>
namespace OpenMS
{
TOPPASVertexNameDialog::TOPPASVertexNameDialog(const QString& name, const QString& input_regex)
: ui_(new Ui::TOPPASVertexNameDialogTemplate)
{
ui_->setupUi(this);
if (!input_regex.isEmpty())
{
QRegularExpression rx(input_regex);
ui_->line_edit->setValidator(new QRegularExpressionValidator(rx, ui_->line_edit));
}
ui_->line_edit->setText(name);
connect(ui_->ok_button, SIGNAL(clicked()), this, SLOT(accept()));
connect(ui_->cancel_button, SIGNAL(clicked()), this, SLOT(reject()));
}
TOPPASVertexNameDialog::~TOPPASVertexNameDialog()
{
delete ui_;
}
QString TOPPASVertexNameDialog::getName()
{
return ui_->line_edit->text();
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/FeatureEditDialog.cpp | .cpp | 1,423 | 55 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/FeatureEditDialog.h>
#include <ui_FeatureEditDialog.h>
using namespace std;
namespace OpenMS
{
FeatureEditDialog::FeatureEditDialog(QWidget * parent) :
QDialog(parent),
feature_(),
ui_(new Ui::FeatureEditDialogTemplate)
{
ui_->setupUi(this);
}
FeatureEditDialog::~FeatureEditDialog()
{
delete ui_;
}
void FeatureEditDialog::setFeature(const Feature & feature)
{
//copy feature
feature_ = feature;
//update widgets according to feature data
ui_->mz_->setValue(feature_.getMZ());
ui_->rt_->setValue(feature_.getRT());
ui_->int_->setValue(feature_.getIntensity());
ui_->charge_->setValue(feature_.getCharge());
}
const Feature & FeatureEditDialog::getFeature() const
{
//update feature data according to widget
feature_.setMZ(ui_->mz_->value());
feature_.setRT(ui_->rt_->value());
feature_.setIntensity(ui_->int_->value());
feature_.setCharge(ui_->charge_->value());
//return feature
return feature_;
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/SpectrumAlignmentDialog.cpp | .cpp | 2,604 | 104 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/SpectrumAlignmentDialog.h>
#include <ui_SpectrumAlignmentDialog.h>
#include <OpenMS/VISUAL/Plot1DWidget.h>
// QT includes
#include <QtWidgets/QButtonGroup>
#include <vector>
namespace OpenMS
{
SpectrumAlignmentDialog::SpectrumAlignmentDialog(Plot1DWidget * parent) :
layer_indices_1_(),
layer_indices_2_(),
ui_(new Ui::SpectrumAlignmentDialogTemplate)
{
ui_->setupUi(this);
QButtonGroup * button_group = new QButtonGroup(this);
button_group->addButton(ui_->ppm);
button_group->addButton(ui_->da);
ui_->da->setChecked(true);
Plot1DCanvas * cc = parent->canvas();
for (UInt i = 0; i < cc->getLayerCount(); ++i)
{
const auto& layer = cc->getLayer(i);
if (layer.flipped)
{
ui_->layer_list_2->addItem(layer.getName().toQString());
layer_indices_2_.push_back(i);
}
else
{
ui_->layer_list_1->addItem(layer.getName().toQString());
layer_indices_1_.push_back(i);
}
}
// select first item of each list
if (ui_->layer_list_1->count() > 0)
{
ui_->layer_list_1->setCurrentRow(0);
}
if (ui_->layer_list_2->count() > 0)
{
ui_->layer_list_2->setCurrentRow(0);
}
}
SpectrumAlignmentDialog::~SpectrumAlignmentDialog()
{
delete ui_;
}
double SpectrumAlignmentDialog::getTolerance() const
{
return ui_->tolerance_spinbox->value();
}
bool SpectrumAlignmentDialog::isPPM() const
{
return ui_->ppm->isChecked();
}
Int SpectrumAlignmentDialog::get1stLayerIndex()
{
if (ui_->layer_list_1->count() == 0 || ui_->layer_list_1->currentRow() == -1)
{
return -1;
}
if (layer_indices_1_.size() > (Size)(ui_->layer_list_1->currentRow()))
{
return layer_indices_1_[(Size)(ui_->layer_list_1->currentRow())];
}
return -1;
}
Int SpectrumAlignmentDialog::get2ndLayerIndex()
{
if (ui_->layer_list_2->count() == 0 || ui_->layer_list_2->currentRow() == -1)
{
return -1;
}
if (layer_indices_2_.size() > (Size)(ui_->layer_list_2->currentRow()))
{
return layer_indices_2_[(Size)(ui_->layer_list_2->currentRow())];
}
return -1;
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/Plot2DPrefDialog.cpp | .cpp | 805 | 33 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/Plot2DPrefDialog.h>
#include <ui_Plot2DPrefDialog.h>
using namespace std;
namespace OpenMS
{
namespace Internal
{
Plot2DPrefDialog::Plot2DPrefDialog(QWidget * parent) :
QDialog(parent),
ui_(new Ui::Plot2DPrefDialogTemplate)
{
ui_->setupUi(this);
}
Plot2DPrefDialog::~Plot2DPrefDialog()
{
delete ui_;
}
} //namespace Internal
} //namspace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/LayerStatisticsDialog.cpp | .cpp | 6,391 | 182 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/LayerStatisticsDialog.h>
#include <ui_LayerStatisticsDialog.h>
#include <OpenMS/VISUAL/PlotWidget.h>
#include <OpenMS/VISUAL/VISITORS/LayerStatistics.h>
#include <QtWidgets/QPushButton>
#include <array>
#include <variant>
using namespace std;
namespace OpenMS
{
// helper for visitor pattern with std::visit
template<class... Ts>
struct overload : Ts... {
using Ts::operator()...;
};
template<class... Ts>
overload(Ts...) -> overload<Ts...>;
/// stringify a number using thousand separator for better readability.
/// The actual separator used depends on the system locale
template<class T>
QString toStringWithLocale(const T number)
{
std::stringstream iss;
iss.imbue(std::locale("")); // use system locale, whatever it may be, e.g. "DE_de"
iss << number;
return QString(iss.str().c_str());
// custom locale is only valid for 'iss' and vanishes here
}
void showDistribution(LayerStatisticsDialog* lsd, const QString& text,
const Math::Histogram<>& hist)
{
if (text == "intensity")
{
qobject_cast<PlotWidget*>(lsd->parent())->showIntensityDistribution(hist);
}
else
{
qobject_cast<PlotWidget*>(lsd->parent())->showMetaDistribution(String(text), hist);
}
}
void addEmptyRow(QTableWidget* table, const int row_i, const QString& row_name)
{
table->setRowCount(row_i + 1);
// set row header name
QTableWidgetItem* item = new QTableWidgetItem();
item->setText(row_name);
table->setVerticalHeaderItem(row_i, item);
}
constexpr int col_count = 4; // columns: count, min, max, avg
void populateRow(QTableWidget* table, const int row_i, const std::array<QString, col_count>& data)
{
for (int col = 0; col < col_count; ++col)
{
QTableWidgetItem* item = new QTableWidgetItem();
item->setText(data[col]);
table->setItem(row_i, col, item);
}
}
/// insert an intermediate row with a single spanning cell, which describes where the values came from (e.g. from DataArrays, or MetaData)
void addHeaderRow(QTableWidget* table, int& row_i, const QString& row_name)
{
addEmptyRow(table, row_i, "");
QTableWidgetItem* item = new QTableWidgetItem();
item->setText(row_name);
//item->setBackgroundColor(QColor(Qt::darkGray));
QFont font;
font.setBold(true);
item->setFont(font);
item->setTextAlignment(Qt::AlignCenter);
table->setItem(row_i, 0, item);
table->setSpan(row_i, 0, 1, table->columnCount()); // extend row to span all columns
++row_i;
}
void addRangeRow(LayerStatisticsDialog* lsd, QTableWidget* table, int& row_i,
const RangeStatsType& row_name, const RangeStatsVariant& row_data,
const bool enable_show_button, LayerStatistics* stats)
{
addEmptyRow(table, row_i, row_name.name.c_str());
// get column data
std::array<QString, col_count> col_values = std::visit(overload{
[&](const RangeStatsInt& d) -> std::array<QString, col_count> { return {toStringWithLocale(d.getCount()),
QString::number(d.getMin()),
QString::number(d.getMax()),
QString::number(d.getAvg(), 'f', 2)}; },
[&](const RangeStatsDouble& d) -> std::array<QString, col_count> { return {toStringWithLocale(d.getCount()),
QString::number(d.getMin(), 'f', 2),
QString::number(d.getMax(), 'f', 2),
QString::number(d.getAvg(), 'f', 2)}; }
}, row_data);
populateRow(table, row_i, col_values);
if (enable_show_button)
{
auto button = new QPushButton(row_name.name.c_str(), table);
table->setCellWidget(row_i, col_count, button);
QObject::connect(button, &QPushButton::clicked, [=]() { showDistribution(lsd, row_name.name.c_str(), stats->getDistribution(row_name)); });
}
// next row
++row_i;
}
void addCountRow(QTableWidget* table, int& row_i, const QString& row_name, const StatsCounter& row_data)
{
addEmptyRow(table, row_i, row_name);
// column data
populateRow(table, row_i, {toStringWithLocale(row_data.counter), "-", "-", "-"});
// next row
++row_i;
}
LayerStatisticsDialog::LayerStatisticsDialog(PlotWidget* parent, std::unique_ptr<LayerStatistics>&& stats) :
QDialog(parent),
stats_(std::move(stats)),
ui_(new Ui::LayerStatisticsDialogTemplate)
{
ui_->setupUi(this);
ui_->table_->setColumnCount(col_count + 1); // +1 for button column
const auto& stats_range = stats_->getRangeStatistics();
const auto& stats_count = stats_->getCountStatistics();
// add each row
int row_i = 0;
RangeStatsSource old_category = RangeStatsSource::SIZE_OF_STATSSOURCE;
for (const auto& item : stats_range)
{
// add sections (relies on items being sorted!)
if (old_category != item.first.src)
{
addHeaderRow(ui_->table_, row_i, StatsSourceNames[(size_t)item.first.src]);
old_category = item.first.src;
}
bool show_button = (item.first == RangeStatsType{RangeStatsSource::CORE, "intensity"}) || item.first.src == RangeStatsSource::METAINFO;
addRangeRow(this, ui_->table_, row_i, item.first, item.second, show_button, stats_.get());
}
if (!stats_count.empty())
{
addHeaderRow(ui_->table_, row_i, "Meta count values");
for (const auto& item : stats_count)
{
addCountRow(ui_->table_, row_i, QString(item.first.c_str()), item.second);
}
}
}
LayerStatisticsDialog::~LayerStatisticsDialog()
{
delete ui_;
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/TOPPASOutputFilesDialog.cpp | .cpp | 1,932 | 78 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/TOPPASOutputFilesDialog.h>
#include <ui_TOPPASOutputFilesDialog.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtWidgets/QMessageBox>
#include <QtCore/QDir>
namespace OpenMS
{
TOPPASOutputFilesDialog::TOPPASOutputFilesDialog(const QString& dir_name, int num_jobs)
: ui_(new Ui::TOPPASOutputFilesDialogTemplate)
{
ui_->setupUi(this);
if (dir_name != "")
{
ui_->out_dir->setDirectory(dir_name);
}
else
{
ui_->out_dir->setDirectory(QDir::currentPath());
}
if (num_jobs >= 1)
{
ui_->num_jobs_box->setValue(num_jobs);
}
connect(ui_->ok_button, SIGNAL(clicked()), this, SLOT(checkValidity_()));
connect(ui_->cancel_button, SIGNAL(clicked()), this, SLOT(reject()));
// make Ok the default (just pressing Enter will run the workflow)
ui_->ok_button->setFocus();
}
TOPPASOutputFilesDialog::~TOPPASOutputFilesDialog()
{
delete ui_;
}
void TOPPASOutputFilesDialog::showFileDialog()
{
ui_->out_dir->showFileDialog();
}
QString TOPPASOutputFilesDialog::getDirectory() const
{
return ui_->out_dir->getDirectory();
}
int TOPPASOutputFilesDialog::getNumJobs() const
{
return ui_->num_jobs_box->value();
}
void TOPPASOutputFilesDialog::checkValidity_()
{
if (!ui_->out_dir->dirNameValid())
{
QMessageBox::warning(nullptr, "Invalid directory", "Either the specified path is no directory, or you have no permission to write there.");
return;
}
accept();
}
} // namespace
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/SwathTabWidget.cpp | .cpp | 24,563 | 556 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/VISUAL/DIALOGS/SwathTabWidget.h>
#include <ui_SwathTabWidget.h>
#include <OpenMS/VISUAL/DIALOGS/WizardHelper.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/VISUAL/DIALOGS/PythonModuleRequirement.h>
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QMessageBox>
#include <QProcess>
#include <QProgressDialog>
#include <QSignalBlocker>
#include <algorithm>
using namespace std;
namespace OpenMS
{
namespace Internal
{
template class WizardGUILock<SwathTabWidget>;
String getOSWExe()
{
return File::findSiblingTOPPExecutable("OpenSwathWorkflow");
}
QString getDefaultOutDir()
{
auto dir = QDir::homePath().append("/SwathWizardOut");
if (!QDir().exists(dir)) QDir().mkpath(dir);
return dir;
}
SwathTabWidget::SwathTabWidget(QWidget* parent) :
QTabWidget(parent),
ui(new Ui::SwathTabWidget),
ep_([&](const String& out) {writeLog_(out.toQString());},
[&](const String& out) {writeLog_(out.toQString());})
{
ui->setupUi(this);
writeLog_(QString("Welcome to the Wizard!"), Qt::darkGreen, true);
auto py_selector = (PythonSelector*)ui->py_selector;
auto py_pyprophet = (PythonModuleRequirement*)ui->py_pyprophet;
py_pyprophet->setRequiredModules( { "pyprophet", "msproteomicstoolslib" });
py_pyprophet->setFreeText("In order to run PyProphet and TRIC after OpenSWATH, the above modules need to be installed\n" \
"Once they are available, the 'PyProphet and TRIC' tab will become active and configurable.\n" \
"To install the modules, visit the <a href=\"http://www.openswath.org\">openswath.org homepage</a> and follow the installation instructions.");
py_pyprophet->setTitle("External: PyProphet and TRIC tools");
connect(py_selector, &PythonSelector::valueChanged, py_pyprophet, &PythonModuleRequirement::validate);
// call once to update py_pyprophet canvas
// alternative: load latest data from .ini and set py_selector (will update py_pyprophet via above signal/slot)
py_pyprophet->validate(py_selector->getLastPython().toQString());
ui->input_tr->setFileFormatFilter("Transition sqLite file (*.pqp)");
ui->input_iRT->setFileFormatFilter("Transition sqLite file (*.pqp)");
// create a default INI of OpenSwathWorkflow
String tmp_file = File::getTemporaryFile();
if (ep_.run(this, getOSWExe().toQString(), QStringList() << "-write_ini" << tmp_file.toQString(), "", true) != ExternalProcess::RETURNSTATE::SUCCESS)
{
exit(1);
}
ParamXMLFile().load(tmp_file, swath_param_);
swath_param_ = swath_param_.copy("OpenSwathWorkflow:1:", true);
// parameters to show within the Wizard:
StringList extract = {"mz_extraction_window", "rt_extraction_window", "threads"};
for (const auto& name : extract) swath_param_wizard_.setValue(name, ""); // create a dummy param, just so we can use ::copySubset
swath_param_wizard_ = swath_param_.copySubset(swath_param_wizard_);
ui->list_editor->load(swath_param_wizard_);
// keep the group of input widgets in sync with respect to their current-working-dir, when browsing for new files
connect(ui->input_mzMLs, &InputFileList::updatedCWD, this, &SwathTabWidget::broadcastNewCWD_);
connect(ui->input_iRT, &InputFile::updatedCWD, this, &SwathTabWidget::broadcastNewCWD_);
connect(ui->input_tr, &InputFile::updatedCWD, this, &SwathTabWidget::broadcastNewCWD_);
connect(ui->input_swath_windows, &InputFile::updatedCWD, this, &SwathTabWidget::broadcastNewCWD_);
// update information on assay libraries
connect(ui->input_iRT, &InputFile::updatedFile, ui->input_iRT_stats, &SwathLibraryStats::updateFromFile);
connect(ui->input_tr, &InputFile::updatedFile, ui->input_tr_stats, &SwathLibraryStats::updateFromFile);
// if out_dir (user defined output directory for OSW results) changes ...
connect(ui->out_dir, &OutputDirectory::directoryChanged, this, &SwathTabWidget::checkPyProphetInput_);
// ... or the mzML input changes --> update the input list of tbl_py_osws (which depend in the basenames of mzMLs and the OSW output directory)
connect(ui->input_mzMLs, &InputFileList::updatedCWD, this, &SwathTabWidget::checkPyProphetInput_);
// prepare table for pyProphet input files
auto& tbl = *(ui->tbl_py_osws);
tbl.setHeaders(QStringList() << "filename");
tbl.setSortingEnabled(false);
connect(ui->tbl_py_osws, &TableView::resized, [&]() {
ui->tbl_py_osws->setColumnWidth(0, ui->tbl_py_osws->width()); // full size column
});
ui->out_dir->setDirectory(getDefaultOutDir());
}
SwathTabWidget::~SwathTabWidget()
{
delete ui;
}
String infileToOSW(const String& infile)
{
return FileHandler::swapExtension(File::basename(infile), FileTypes::OSW);
}
String infileToChrom(const String& infile)
{
return FileHandler::swapExtension(File::basename(infile), FileTypes::SQMASS);
}
StringList SwathTabWidget::getMzMLInputFiles() const
{
return ui->input_mzMLs->getFilenames();
}
void SwathTabWidget::on_run_swath_clicked()
{
if (!checkOSWInputReady_()) return;
WizardGUILock lock(this); // forbid user interaction
updateSwathParamFromWidgets_();
Param tmp_param;
tmp_param.insert("OpenSwathWorkflow:1:", swath_param_);
String tmp_ini = File::getTemporaryFile();
ParamXMLFile().store(tmp_ini, tmp_param);
StringList in_mzMLs = getMzMLInputFiles();
writeLog_(QString("Starting OpenSwathWorkflow with %1 mzML file(s)").arg(in_mzMLs.size()), Qt::darkGreen, true);
QProgressDialog progress("Running OpenSwath", "Abort ...", 0, (int)in_mzMLs.size(), this);
progress.setWindowModality(Qt::ApplicationModal);
progress.setMinimumDuration(0); // show immediately
progress.setValue(0);
int step = 0;
writeLog_(QString("Running OpenSwathWorkflow (%1 files total): ").arg(in_mzMLs.size()), Qt::darkGreen, true);
for (const auto& mzML : in_mzMLs)
{
auto r = ep_.run(this,
getOSWExe().toQString(),
QStringList() << "-ini" << tmp_ini.toQString()
<< "-in" << mzML.toQString()
<< "-out_osw" << getCurrentOutDir_() + "/" + infileToOSW(mzML).toQString()
<< "-out_chrom" << getCurrentOutDir_() + "/" + infileToChrom(mzML).toQString(),
"",
true);
if (r != ExternalProcess::RETURNSTATE::SUCCESS) break;
if (progress.wasCanceled()) break;
progress.setValue(++step);
} // mzML loop
progress.close();
}
void SwathTabWidget::on_edit_advanced_parameters_clicked()
{
// refresh 'swath_param_' from data within the Wizards controls
updateSwathParamFromWidgets_();
Param tmp_param = swath_param_;
// remove all input and output parameters from the user interface we are about to show
StringList to_remove;
for (Param::ParamIterator it = tmp_param.begin(); it != tmp_param.end(); ++it)
{
if (it->tags.count("input file") || it->tags.count("output file"))
{
to_remove.push_back(it->name); // do not remove right away.. does not work
}
}
for (const auto& p : to_remove)
{
tmp_param.remove(p);
if (tmp_param.exists(p + "_type")) tmp_param.remove(p + "_type"); // for good measure of related input/output parameters
}
// show the parameters to the user
String executable = File::getExecutablePath() + "INIFileEditor";
String tmp_file = File::getTemporaryFile();
ParamXMLFile().store(tmp_file, tmp_param);
QProcess qp;
qp.start(executable.toQString(), QStringList() << tmp_file.toQString());
ui->tab_run->setEnabled(false); // grey out the Wizard until INIFileEditor returns...
qp.waitForFinished(-1);
ui->tab_run->setEnabled(true);
ParamXMLFile().load(tmp_file, tmp_param);
swath_param_.update(tmp_param, false);
// refresh controls
updateWidgetsfromSwathParam_();
}
void SwathTabWidget::updateSwathParamFromWidgets_()
{
// refresh 'swath_param_wizard_' which is linked into ParamEditor
ui->list_editor->store();
// ... and merge into main param
swath_param_.update(swath_param_wizard_, false);
Param tmp;
// grab the files
tmp.setValue("tr", ui->input_tr->getFilename().toStdString());
tmp.setValue("tr_irt", ui->input_iRT->getFilename().toStdString());
// do not set 'in' because it allows for one file only, while we have more and need to iterate manually
String swath_windows = ui->input_swath_windows->getFilename();
if (!swath_windows.empty()) tmp.setValue("swath_windows_file", swath_windows);
// do not set '-out_osw' because we might have multiple -in's and have to iterate manually
// call update(); do NOT write directly to swath_param_ using 'setValue(name, value)' because that will loose the description and the tags, i.e. input-file etc. We need this information though!
swath_param_.update(tmp, false, false, true, true, getGlobalLogWarn());
}
void SwathTabWidget::updateWidgetsfromSwathParam_()
{
swath_param_wizard_.update(swath_param_, false, false, true, false, getGlobalLogWarn());
ui->list_editor->load(swath_param_wizard_);
}
QString SwathTabWidget::getCurrentOutDir_() const
{
QString out_dir(ui->out_dir->dirNameValid() ?
ui->out_dir->getDirectory() :
getDefaultOutDir());
return out_dir;
}
vector<pair<String, bool>> SwathTabWidget::getPyProphetInputFiles() const
{
vector<pair<String, bool>> files;
String dir = getCurrentOutDir_();
for (const auto& file : getMzMLInputFiles())
{
// predict output OSW filenames
const String file_osw = dir + '/' + infileToOSW(file);
// check if exists
files.emplace_back(file_osw, File::exists(file_osw));
}
return files;
}
const char* msg_no_osws = "select mzML input files in 'LC-MS files' tab first and pick an output directory in 'Run OpenSwath' tab";
void SwathTabWidget::checkPyProphetInput_()
{
// populate the file list widget for pyProphet input
auto& tbl = *(ui->tbl_py_osws);
tbl.setRowCount(0); // clear the table; clear() does not resize the table!
auto files = getPyProphetInputFiles();
if (files.empty())
{
tbl.appendRow();
tbl.setAtBottomRow(msg_no_osws, 0, Qt::white, Qt::gray);
}
else
{
for (const auto& file : files)
{
tbl.appendRow();
tbl.setAtBottomRow(file.first.c_str(), 0, Qt::white,
file.second ? Qt::black : Qt::red)
->setCheckState(Qt::Unchecked);
}
}
// set label at bottom
ui->lbl_pyOutDir->setText("Results can be found in '" + getCurrentOutDir_() +
"'. If pyProphet ran, there will be PDF files with model statistics and TRIC will "
"generate TSV files (tric_aligned.tsv and tric_aligned_matrix.tsv) for downstream processing.\n To view results interactively, open them in TOPPView.");
}
void SwathTabWidget::writeLog_(const QString& text, const QColor& color, bool new_section)
{
QColor tc = ui->log_text->textColor();
if (new_section)
{
ui->log_text->setTextColor(Qt::darkBlue);
ui->log_text->append(QString(10, '#').append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")).append(QString(10, '#')).append("\n"));
ui->log_text->setTextColor(tc);
}
ui->log_text->setTextColor(color);
ui->log_text->append(text);
ui->log_text->setTextColor(tc); // restore old color
}
void SwathTabWidget::writeLog_(const String& text, const QColor& color, bool new_section)
{
writeLog_(text.toQString(), color, new_section);
}
bool SwathTabWidget::checkOSWInputReady_()
{
if (ui->input_mzMLs->getFilenames().empty())
{
QMessageBox::critical(this, "Error", "Input mzML file(s) are missing! Please provide at least one!");
return false;
}
if (ui->input_tr->getFilename().isEmpty())
{
QMessageBox::critical(this, "Error", "Input file 'Transition Library' is missing! Please provide one!");
return false;
}
if (ui->input_iRT->getFilename().isEmpty())
{
QMessageBox::critical(this, "Error", "Input file 'iRT Library' is missing! Please provide one!");
return false;
}
// swath_windows_file is optional... no need to check
return true;
}
void SwathTabWidget::broadcastNewCWD_(const QString& new_cwd)
{
// RAII to avoid infinite loop (setCWD signals updatedCWD which is connected to slot broadcastNewCWD_)
QSignalBlocker blocker1(ui->input_mzMLs);
QSignalBlocker blocker2(ui->input_iRT);
QSignalBlocker blocker3(ui->input_tr);
QSignalBlocker blocker4(ui->input_swath_windows);
ui->input_mzMLs->setCWD(new_cwd);
ui->input_iRT->setCWD(new_cwd);
ui->input_tr->setCWD(new_cwd);
ui->input_swath_windows->setCWD(new_cwd);
}
bool SwathTabWidget::findPythonScript_(const String& path_to_python_exe, String& script_name)
{
String path = File::path(path_to_python_exe);
String script_backup = script_name;
script_name = path + "/Scripts/" + script_backup; // Windows uses the Script subdirectory
if (File::readable(script_name)) return true;
writeLog_("Warning: Could not find " + script_backup + " at " + script_name + ".", Qt::red, true);
script_name = path + "/" + script_backup;
if (File::readable(script_name)) return true;
writeLog_("Warning: Could not find " + script_backup + " at " + script_name + ".", Qt::red, true);
return false;
}
QStringList SwathTabWidget::getPyProphetOutputFileNames() const
{
auto in = getPyProphetInputFiles();
QStringList out;
for (auto& f : in)
{
auto s = (FileHandler::stripExtension(f.first) + "_pyProphet_out.osw");
out << s.toQString();
}
return out;
}
void SwathTabWidget::on_btn_runPyProphet_clicked()
{
if (!ui->py_pyprophet->isReady())
{
QMessageBox::warning(this, "Error", "Could not find all requirements for 'pyprophet & tric' (see 'Config' tab). Install modules via 'pip install <modulename>' and make sure it's available in $PATH");
return;
}
WizardGUILock lock(this); // forbid user interaction
auto inputs = getPyProphetInputFiles();
if (inputs.empty())
{
QMessageBox::warning(this, "Error", "Provide at least one input file for pyProphet and TRIC in the 'LC-MS files' tab.");
return;
}
QStringList osws = getPyProphetOutputFileNames();
QStringList osws_orig;
QStringList osws_reduced;
QStringList tsvs;
for (const auto& file : inputs)
{
if (file.second == false)
{
QMessageBox::warning(this, "Error", String("Required input file '" + file.first + "' not found. Please run OpenSwathWorkflow first to create it").toQString());
return;
}
osws_orig << file.first.toQString();
osws_reduced << (FileHandler::stripExtension(file.first) + "_pyProphet.oswr").toQString();
tsvs << (FileHandler::swapExtension(file.first, FileTypes::TSV)).toQString();
}
// check presence of template
QString library = ui->input_tr->getFilename();
if (library.isEmpty())
{
QMessageBox::warning(this, "Error", String("The assay library is not specified. Please go to the 'database' tab and specify it.").toQString());
return;
}
#ifdef OPENMS_WINDOWSPLATFORM
String pp = "pyprophet.exe"; // we need the full path for findPythonScript_
#else
String pp = "pyprophet";
#endif
if (!findPythonScript_(ui->py_selector->getLastPython(), pp)) // searches Script in Python installation
{
QMessageBox::warning(this, "Error", String("Could not find 'pyprophet' in the python installation '" + ui->py_selector->getLastPython() + "'. Please make sure it is installed. Visit http://openswath.org/en/latest/docs/tric.html for details.").toQString());
return;
}
// list of calls to make: exe, args, [optional] list of args to append one-by-one in a loop
std::vector<Command> calls;
// merge all osws ...
calls.emplace_back(pp, QStringList() << "merge" << "--template=" + library << "--out=model.osw" << osws, ArgLoop{});
// to build/learn a common model --> creates merged_ms1ms2_report.pdf
calls.emplace_back(pp, QStringList() << "score" << "--in=model.osw" << "--level=ms1ms2", ArgLoop{});
// apply model in loop
calls.emplace_back(pp, QStringList() << "score" << "--apply_weights=model.osw" << "--level=ms1ms2" << "--in" << "%1", ArgLoop{ Args{osws, 4} });
// reduce (required to avoid https://github.com/PyProphet/pyprophet/issues/85)
calls.emplace_back(pp, QStringList() << "reduce" << "--in" << "%1" << "--out" << "%1", ArgLoop{ Args{osws, 2}, Args{osws_reduced, 4} });
// merge again for peptide and protein error rate control
calls.emplace_back(pp, QStringList() << "merge" << "--template=model.osw" << "--out=model_global.osw" << osws_reduced, ArgLoop{});
calls.emplace_back(pp, QStringList() << "peptide" << "--in=model_global.osw" << "--context=global", ArgLoop{});
calls.emplace_back(pp, QStringList() << "protein" << "--in=model_global.osw" << "--context=global", ArgLoop{});
// backpropagate in loop
calls.emplace_back(pp, QStringList() << "backpropagate" << "--apply_scores=model_global.osw" << "--in" << "%1", ArgLoop{ Args{osws, 3} });
// prepare for TRIC
calls.emplace_back(pp, QStringList() << "export" << "--format=legacy_merged" << "--max_global_peptide_qvalue=0.01" << "--max_global_protein_qvalue=0.01"
<< "--in=%1" << "--out=%1", ArgLoop{ Args{osws, 4}, Args{tsvs, 5} });
String feature_alignment_py = "feature_alignment.py";
if (!findPythonScript_(ui->py_selector->getLastPython(), feature_alignment_py)) // searches Script in Python installation
{
QMessageBox::warning(this, "Error", String("Could not find 'feature_alignment.py' from the msproteomicstool package in the python installation '" + ui->py_selector->getLastPython() + "'. Please make sure it is installed. Visit http://openswath.org/en/latest/docs/tric.html for details.").toQString());
return;
}
calls.emplace_back(ui->py_selector->getLastPython(), QStringList() << feature_alignment_py.toQString() << "--in" << tsvs
<< "--out" << "tric_aligned.tsv" << "--out_matrix" << "tric_aligned_matrix.tsv"
<< "--method" << "LocalMST" << "--realign_method" << "lowess" << "--max_rt_diff" << "90"
<< "--fdr_cutoff" << QString::number(ui->tric_FDR_threshold->value())
<< "--alignment_score" << QString::number(ui->tric_RTmax->value()), ArgLoop{});
QProgressDialog progress("Running pyprophet and TRIC", "Abort ...", 0, (int)calls.size(), this);
progress.setWindowModality(Qt::ApplicationModal);
progress.setMinimumDuration(0); // show immediately
progress.setValue(0);
// first - copy all original osw files, since augmenting them once with model information will lead to crashes when doing a second run on them
for (int i = 0; i < osws_orig.size(); ++i)
{
QFile::remove(osws[i]); // copy() will not overwrite existing files :/
QFile::copy(osws_orig[i], osws[i]);
}
int step = 0;
for (const auto& call : calls)
{
// this might just be one loop... depending on the call...
for (size_t i_loop = 0; i_loop < call.getLoopCount(); ++i_loop)
{
auto returnstate = ep_.run(this, call.exe.toQString(), call.getArgs(i_loop), getCurrentOutDir_(), true);
if (returnstate != ExternalProcess::RETURNSTATE::SUCCESS)
{
QMessageBox::warning(this, "Error", String("Running pyprophet/TRIC failed at step " + String(step) + "/" + String(calls.size()) + ". Please see log for details").toQString());
return;
}
if (progress.wasCanceled())
{
return;
}
}
progress.setValue(++step);
}
progress.close();
}
void SwathTabWidget::on_btn_pyresults_clicked()
{
GUIHelpers::openFolder(getCurrentOutDir_());
}
void SwathTabWidget::on_pushButton_clicked()
{
auto& tbl = *(ui->tbl_py_osws);
int selected_rows = 0;
QStringList missing_osw_files;
QStringList args;
auto raw_files = getMzMLInputFiles(); // mzML's for now; will be translated to sqMass below
auto osw_files = getPyProphetOutputFileNames();
if (tbl.rowCount() == 1 && tbl.item(0, 0)->data(Qt::DisplayRole).toString() == msg_no_osws)
{
QMessageBox::information(this, "Error", "No files are selected from the list above! Make sure to select mzML files in the 'LC-MS files' tab first.");
return;
}
if (size_t(tbl.rowCount()) != raw_files.size() || tbl.rowCount() != osw_files.count())
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Something went wrong in populating the input file window");
}
for (int i = 0; i < tbl.rowCount(); ++i)
{
if (tbl.item(i, 0)->checkState() == Qt::CheckState::Checked)
{
++selected_rows;
args << infileToChrom(raw_files[i]).toQString() << "!" << osw_files[i];
if (!File::exists(osw_files[i])) missing_osw_files << File::basename(osw_files[i]).toQString();
}
}
if (selected_rows == 0)
{
QMessageBox::information(this, "Error", "No files are selected from the list above! Select the files you want to open and try again.");
return;
}
if ( ! missing_osw_files.isEmpty())
{
QMessageBox::information(this, "Error", "The following selected files to not yet have a pyProphet result file:\n" + missing_osw_files.join("\n") + "\nPlease run pyProphet first");
return;
}
if (QMessageBox::question(this, "Confirm", (String("Confirm opening ") + selected_rows + " raw files in TOPPView").toQString(),
QMessageBox::StandardButton::Ok, QMessageBox::StandardButton::Cancel)
== QMessageBox::StandardButton::Ok)
{
// create on heap, to avoid QProcess being closed when application exits
// This is a small memleak, but QProcess::startDetached() is only available from Qt 5.10 on -- switch to that once its supported everywhere
QProcess* qp = new QProcess;
qp->setWorkingDirectory(getCurrentOutDir_());
auto tv = File::findSiblingTOPPExecutable("TOPPView");
qp->start(tv.toQString(), args);
if (!qp->waitForStarted(2000))
{
QMessageBox::warning(this, "Error", String("Could not open TOPPView executable from '" + tv + "'").toQString());
return;
}
// TOPPView is running now ... detached
}
}
} //namespace Internal
} //namspace OpenMS
| C++ |
3D | OpenMS/OpenMS | src/openms_gui/source/VISUAL/DIALOGS/TOPPASToolConfigDialog.cpp | .cpp | 6,091 | 193 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
// OpenMS includes
#include <OpenMS/VISUAL/DIALOGS/TOPPASToolConfigDialog.h>
#include <OpenMS/VISUAL/ParamEditor.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <QtCore/QStringList>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QRadioButton>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QCheckBox>
#include <QProcess>
using namespace std;
namespace OpenMS
{
TOPPASToolConfigDialog::TOPPASToolConfigDialog(QWidget* parent, Param& param, const String& default_dir, const String& tool_name, const String& tool_type, const String& tool_desc, const QVector<String>& hidden_entries) :
QDialog(parent),
param_(¶m),
default_dir_(default_dir),
tool_name_(tool_name),
tool_type_(tool_type),
hidden_entries_(hidden_entries)
{
QGridLayout* main_grid = new QGridLayout(this);
QLabel* description = new QLabel;
description->setAlignment(Qt::AlignTop | Qt::AlignLeft);
description->setWordWrap(true);
description->setText(tool_desc.toQString());
main_grid->addWidget(description, 0, 0, 1, 1);
//Add advanced mode check box
editor_ = new ParamEditor(this);
editor_->setMinimumSize(500, 500);
main_grid->addWidget(editor_, 1, 0, 1, 1);
QHBoxLayout* hbox = new QHBoxLayout;
QPushButton* load_button = new QPushButton(tr("&Load config from .INI file"));
connect(load_button, SIGNAL(clicked()), this, SLOT(loadINI_()));
hbox->addWidget(load_button);
QPushButton* store_button = new QPushButton(tr("&Store config to .INI file"));
connect(store_button, SIGNAL(clicked()), this, SLOT(storeINI_()));
hbox->addWidget(store_button);
hbox->addStretch();
// cancel button
QPushButton* cancel_button = new QPushButton(tr("&Cancel"));
connect(cancel_button, SIGNAL(clicked()), this, SLOT(reject()));
hbox->addWidget(cancel_button);
// ok button
QPushButton* ok_button_ = new QPushButton(tr("&Ok"));
connect(ok_button_, SIGNAL(clicked()), this, SLOT(ok_()));
hbox->addWidget(ok_button_);
main_grid->addLayout(hbox, 2, 0, 1, 1);
setLayout(main_grid);
editor_->load(*param_);
editor_->setFocus(Qt::MouseFocusReason);
setWindowTitle(tool_name.toQString() + " " + tr("configuration"));
}
TOPPASToolConfigDialog::~TOPPASToolConfigDialog() = default;
void TOPPASToolConfigDialog::ok_()
{
if (editor_->isModified())
{
editor_->store();
accept();
}
else
{
reject();
}
}
void TOPPASToolConfigDialog::loadINI_()
{
QString string;
filename_ = QFileDialog::getOpenFileName(this, tr("Open ini file"), default_dir_.c_str(), tr("ini files (*.ini);; all files (*.*)"));
//no file selected
if (filename_.isEmpty())
{
return;
}
if (!arg_param_.empty())
{
arg_param_.clear();
param_->clear();
editor_->clear();
}
try
{
ParamXMLFile paramFile;
paramFile.load(filename_.toStdString(), arg_param_);
}
catch (Exception::BaseException& e)
{
QMessageBox::critical(this, "Error", (String("Error loading INI file: ") + e.what()).c_str());
arg_param_.clear();
return;
}
//Extract the required parameters
*param_ = arg_param_.copy(tool_name_ + ":1:", true);
//param_->remove("log");
//param_->remove("no_progress");
//param_->remove("debug");
//remove parameters already explained by edges and the "type" parameter
for (const String &name : hidden_entries_)
{
param_->remove(name);
}
//load data into editor
editor_->load(*param_);
editor_->setModified(true);
}
void TOPPASToolConfigDialog::storeINI_()
{
//nothing to save
if (param_->empty())
return;
filename_ = QFileDialog::getSaveFileName(this, tr("Save ini file"), default_dir_.c_str(), tr("ini files (*.ini)"));
//no file selected
if (filename_.isEmpty())
return;
if (!filename_.endsWith(".ini"))
filename_.append(".ini");
bool was_modified = editor_->isModified();
editor_->store();
if (was_modified) editor_->setModified(true);
arg_param_.insert(tool_name_ + ":1:", *param_);
try
{
QString tmp_ini_file = File::getTempDirectory().toQString() + QDir::separator() + "TOPPAS_" + tool_name_.toQString() + "_";
if (!tool_type_.empty())
{
tmp_ini_file += tool_type_.toQString() + "_";
}
tmp_ini_file += File::getUniqueName().toQString() + "_tmp.ini";
//store current parameters
ParamXMLFile paramFile;
paramFile.store(tmp_ini_file.toStdString(), arg_param_);
//restore other parameters that might be missing
QString executable = File::findSiblingTOPPExecutable(tool_name_).toQString();
QStringList args;
args << "-write_ini" << filename_ << "-ini" << tmp_ini_file;
if (!tool_type_.empty())
{
args << "-type" << tool_type_.toQString();
}
if (QProcess::execute(executable, args) != 0)
{
QMessageBox::critical(nullptr, "Error", (String("Could not execute '\"") + executable + "\" \"" + args.join("\" \"") + "\"'!\n\nMake sure the TOPP tools are present in '" + File::getExecutablePath() + "', that you have permission to write to the temporary file path, and that there is space left in the temporary file path.").c_str());
return;
}
}
catch (Exception::BaseException& e)
{
QMessageBox::critical(this, "Error", (String("Error storing INI file: ") + e.what()).c_str());
return;
}
}
}
| C++ |
3D | OpenMS/OpenMS | src/pyOpenMS/docompile.py | .py | 1,316 | 36 | # Python script to compile Cython to C++
#
# this script compiles the *.pyx infile (pyopenms/pyopenms.pyx) to .cpp
#
# It can be run in the build process of pyopenms when manual changes to the pyx
# files need to be made (not recommended!).
#
# == taken from autowrap/Main.py run(), lower part
from __future__ import print_function
infile = "pyopenms/pyopenms.pyx"
import cPickle
persisted_data_path = "include_dir.bin"
autowrap_include_dirs = cPickle.load(open(persisted_data_path, "rb"))
# autowrap_include_dirs = ['/usr/local/lib/python2.7/dist-packages/autowrap/data_files/boost', '/usr/local/lib/python2.7/dist-packages/autowrap/data_files', '/path/to/pyOpenMS/pxds', 'from Map cimport Map as _Map']
from Cython.Compiler.Main import compile as cy_compile, CompilationOptions
from Cython.Compiler.Options import directive_defaults
directive_defaults["boundscheck"] = False
directive_defaults["wraparound"] = False
options = dict(include_path=autowrap_include_dirs,
compiler_directives=directive_defaults,
#output_dir=".",
#gdb_debug=True,
cplus=True)
print("Compiling with Cython the file", infile)
print("Using include_path", autowrap_include_dirs)
options = CompilationOptions(**options)
cy_compile(infile, options=options)
print("Success!")
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/setup.py | .py | 10,514 | 299 | # input-encoding: latin-1
from __future__ import print_function
# windows ?
import sys
iswin = sys.platform == "win32"
# osx ?
isosx = sys.platform == "darwin"
if isosx:
import platform
osx_ver = platform.mac_ver()[0] #e.g. ('10.15.1', ('', '', ''), 'x86_64')
import sys
no_optimization = False
if "--no-optimization" in sys.argv:
no_optimization = True
sys.argv.remove("--no-optimization")
# import config
from env import (OPEN_MS_COMPILER, PYOPENMS_SRC_DIR, OPEN_MS_GIT_BRANCH, OPEN_MS_BUILD_DIR, OPEN_MS_CONTRIB_BUILD_DIRS,
QT_INSTALL_LIBS, QT_INSTALL_BINS, MSVS_RTLIBS,
OPEN_MS_BUILD_TYPE, OPEN_MS_VERSION, INCLUDE_DIRS_EXTEND, LIBRARIES_EXTEND,
LIBRARY_DIRS_EXTEND, OPEN_MS_LIB, OPEN_SWATH_ALGO_LIB, PYOPENMS_INCLUDE_DIRS,
PY_NUM_MODULES, PY_NUM_THREADS, SYSROOT_OSX_PATH, LIBRARIES_TO_BE_PARSED_EXTEND,
OPENMS_GIT_LC_DATE_FORMAT, OPENMP_FOUND, OPENMP_CXX_FLAGS)
IS_DEBUG = OPEN_MS_BUILD_TYPE.upper() == "DEBUG"
OMP = (OPENMP_FOUND.upper() == "ON" or OPENMP_FOUND.upper() == "TRUE" or OPENMP_FOUND == "1")
if iswin and IS_DEBUG:
raise Exception("building pyopenms on windows in debug mode not tested yet.")
# use autowrap to generate Cython and .cpp file for wrapping OpenMS:
import pickle
import os
import glob
import re
import shutil
import time
if OPEN_MS_GIT_BRANCH == "nightly":
package_name = "pyopenms"
package_version = OPEN_MS_VERSION + ".dev" + OPENMS_GIT_LC_DATE_FORMAT
else:
package_name = "pyopenms"
package_version = OPEN_MS_VERSION
os.environ["CC"] = OPEN_MS_COMPILER
# AFAIK distutils does not care about CXX (set it to be safe)
os.environ["CXX"] = OPEN_MS_COMPILER
j = os.path.join
src_pyopenms = PYOPENMS_SRC_DIR
extra_includes = glob.glob(src_pyopenms + "/extra_includes/*.h*")
for include in extra_includes:
shutil.copy(include, "extra_includes/")
persisted_data_path = "include_dir.bin"
autowrap_include_dirs = pickle.load(open(persisted_data_path, "rb"))
from setuptools import setup, Extension, find_namespace_packages
with open("pyopenms/version.py", "w") as fp:
print("version=%r" % package_version, file=fp)
# parse config
if OPEN_MS_CONTRIB_BUILD_DIRS.endswith(";"):
OPEN_MS_CONTRIB_BUILD_DIRS = OPEN_MS_CONTRIB_BUILD_DIRS[:-1]
for OPEN_MS_CONTRIB_BUILD_DIR in OPEN_MS_CONTRIB_BUILD_DIRS.split(";"):
if os.path.exists(os.path.join(OPEN_MS_CONTRIB_BUILD_DIR, "lib")):
break
# Package data expected to be installed. On Linux the debian package
# contains share/ data and must be installed to get access to the OpenMS shared
# library.
#
if iswin:
if IS_DEBUG:
libraries = ["OpenMSd", "OpenSwathAlgod", "Qt5Cored", "Qt5Networkd"]
else:
libraries = ["OpenMS", "OpenSwathAlgo", "Qt5Core", "Qt5Network"]
elif sys.platform.startswith("linux"):
libraries = ["OpenMS", "OpenSwathAlgo", "Qt6Core", "Qt6Network"]
elif sys.platform == "darwin":
libraries = ["OpenMS", "OpenSwathAlgo"]
else:
print("\n")
print("platform", sys.platform, "not supported yet")
print("\n")
exit()
if (iswin):
library_dirs = [OPEN_MS_BUILD_DIR,
j(OPEN_MS_BUILD_DIR, "lib", "Release"),
j(OPEN_MS_BUILD_DIR, "bin", "Release"),
j(OPEN_MS_BUILD_DIR, "Release"),
QT_INSTALL_BINS,
QT_INSTALL_LIBS,
]
else:
library_dirs = [OPEN_MS_BUILD_DIR,
j(OPEN_MS_BUILD_DIR, "lib"),
j(OPEN_MS_BUILD_DIR, "bin"),
QT_INSTALL_BINS,
QT_INSTALL_LIBS,
]
# extend with contrib lib dirs
for OPEN_MS_CONTRIB_BUILD_DIR in OPEN_MS_CONTRIB_BUILD_DIRS.split(";"):
library_dirs.append(j(OPEN_MS_CONTRIB_BUILD_DIR, "lib"))
import numpy
include_dirs = [
"extra_includes",
numpy.get_include()
]
# append all include and library dirs exported by CMake
include_dirs.extend(PYOPENMS_INCLUDE_DIRS.split(";"))
if INCLUDE_DIRS_EXTEND: # only add if not empty
include_dirs.extend(INCLUDE_DIRS_EXTEND.split(";"))
if LIBRARY_DIRS_EXTEND: # only add if not empty
library_dirs.extend(LIBRARY_DIRS_EXTEND.split(";"))
if LIBRARIES_EXTEND: # only add if not empty
libraries.extend(LIBRARIES_EXTEND.split(";"))
# libraries of any type to be parsed and added
objects = []
add_libs = LIBRARIES_TO_BE_PARSED_EXTEND.split(";")
for lib in add_libs:
if not iswin:
if lib.endswith(".a"):
objects.append(lib)
name_search = re.search('.*/lib(.*)\.a$', lib)
if name_search:
libraries.append(name_search.group(1))
library_dirs.append(os.path.dirname(lib))
if lib.endswith(".so") or lib.endswith(".dylib"):
name_search = re.search('.*/lib(.*)\.(so|dylib)$', lib)
if name_search:
libraries.append(name_search.group(1))
library_dirs.append(os.path.dirname(lib))
else:
if lib.endswith(".lib"):
name_search = re.search('.*/(.*)\.lib$', lib)
if name_search:
libraries.append(name_search.group(1))
library_dirs.append(os.path.dirname(lib))
extra_link_args = []
extra_compile_args = []
if iswin:
# /EHs is important. It sets _CPPUNWIND which causes boost to
# set BOOST_NO_EXCEPTION in <boost/config/compiler/visualc.hpp>
# such that boost::throw_excption() is declared but not implemented.
# The linker does not like that very much ...
extra_compile_args = ["/EHs", "/bigobj"]
extra_compile_args.append("/std:c++17")
extra_link_args.append("/std:c++17")
elif sys.platform.startswith("linux"):
extra_link_args = ["-Wl,-s"]
if OMP:
libraries.append("gomp") # GNU OpenMP runtime
libraries.append("pthread")
elif sys.platform == "darwin":
library_dirs.insert(0,j(OPEN_MS_BUILD_DIR,"pyOpenMS","pyopenms"))
if OMP:
libraries.append("omp")
# we need to manually link to the Qt Frameworks
python_version = f"{sys.version_info.major}.{sys.version_info.minor}"
pyopenms_path = f"@loader_path/../lib/python{python_version}/site-packages/pyopenms"
extra_compile_args = ["-Qunused-arguments", "-fopenmp"]
extra_link_args = ["-Wl,-rpath,@loader_path/../lib", f"-Wl,-rpath,{pyopenms_path}", "-lomp"]
if IS_DEBUG:
extra_compile_args.append("-g2")
if OMP and OPENMP_CXX_FLAGS:
extra_compile_args.extend(OPENMP_CXX_FLAGS.split(";"))
if not iswin:
extra_link_args.append("-std=c++20")
extra_compile_args.append("-std=c++20")
if isosx: # MacOS
extra_compile_args.append("-stdlib=libc++")
extra_link_args.append("-stdlib=libc++") # MacOS libstdc++ does not include c++11+ lib support.
extra_link_args.append("-mmacosx-version-min=10.9") # due to libc++
extra_compile_args.append("-Wno-deprecated")
extra_compile_args.append("-Wno-nullability-completeness")
if (osx_ver >= "10.14.0" and SYSROOT_OSX_PATH): # since macOS Mojave
extra_link_args.append("-isysroot" + SYSROOT_OSX_PATH)
extra_compile_args.append("-isysroot" + SYSROOT_OSX_PATH)
else:
extra_compile_args.append("-Wno-deprecated-copy")
extra_compile_args.append("-Wno-redeclared-class-member")
extra_compile_args.append("-Wno-unused-local-typedefs")
extra_compile_args.append("-Wdeprecated-declarations")
extra_compile_args.append("-Wno-sign-compare")
extra_compile_args.append("-Wno-unknown-pragmas")
extra_compile_args.append("-Wno-header-guard")
extra_compile_args.append("-Wno-unused-function")
extra_compile_args.append("-Wno-deprecated-declarations")
extra_compile_args.append("-Wno-missing-declarations")
extra_compile_args.append("-Wno-int-in-bool-context")
if no_optimization:
extra_compile_args.append("-O0")
extra_link_args.append("-O0")
mnames = ["_pyopenms_%s" % (k+1) for k in range(int(PY_NUM_MODULES))]
ext = []
##WARNING debug - boost_regex naming varies by platform
libraries.append("boost_regex")
for module in mnames:
ext.append(Extension(
module,
sources=["pyopenms/%s.cpp" % module],
language="c++",
library_dirs=library_dirs,
libraries=libraries,
include_dirs=include_dirs + autowrap_include_dirs,
extra_compile_args=extra_compile_args,
extra_objects=objects,
extra_link_args=extra_link_args,
define_macros=[('BOOST_ALL_NO_LIB', None), ("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")] ## Deactivates boost autolink (esp. on win). Shuts up the damn "deprecated NumPy API" warning spam (https://docs.cython.org/en/latest/src/userguide/numpy_tutorial.html#numpy-compilation)
## Alternative is to specify the boost naming scheme (--layout param; easy if built from contrib)
## TODO just take over compile definitions from OpenMS (CMake)
))
# enforce 64bit-only build as OpenMS is not available in 32bit on osx
if sys.platform == "darwin":
os.environ['ARCHFLAGS'] = "-arch x86_64"
setup(
name=package_name,
packages=find_namespace_packages(
where=".",
include=["pyopenms", "pyopenms.*"],
exclude=["*.share", "*.share.*"]
),
ext_package="pyopenms",
package_data= {
'pyopenms': ['py.typed', '*.pyi']
},
install_requires=[
'numpy>=1.25.0',
'matplotlib>=3.5'
],
version=package_version,
maintainer="The OpenMS team",
maintainer_email="open-ms-general@lists.sourceforge.net",
license="http://opensource.org/licenses/BSD-3-Clause",
platforms=["any"],
description="Python wrapper for C++ LC-MS library OpenMS",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Topic :: Scientific/Engineering :: Bio-Informatics",
"Topic :: Scientific/Engineering :: Chemistry",
],
long_description=open("README.rst").read(),
long_description_content_type="text/x-rst",
zip_safe=False,
url="https://openms.de",
project_urls={
"Documentation": "https://pyopenms.readthedocs.io",
"Source Code": "https://github.com/OpenMS/OpenMS/tree/develop/src/pyOpenMS",
"Tracker": "https://github.com/OpenMS/OpenMS/issues",
"Documentation Source": "https://github.com/OpenMS/pyopenms-docs",
},
author="OpenMS team",
author_email="webmaster@openms.de",
ext_modules=ext,
include_package_data=True # see MANIFEST.in
)
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/fix_pyi_imports.py | .py | 341 | 12 | import sys
if __name__ == '__main__':
args = sys.argv[1:]
with open(args[0], 'r') as f:
save = f.readlines()
save.insert(2, 'from pyopenms import * # pylint: disable=wildcard-import; lgtm(py/polluting-import)\n')
save.insert(3, 'import numpy as _np\n')
with open(args[0], 'w') as f:
f.writelines(save)
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/run_valgrind.sh | .sh | 181 | 10 | #!/bin/sh
valgrind \
--tool=memcheck\
--leak-check=yes\
--error-limit=no \
--suppressions=valgrind-python.supp\
--num-callers=10\
-v\
nosetests -w tests
| Shell |
3D | OpenMS/OpenMS | src/pyOpenMS/requirements_check.py | .py | 1,952 | 56 | import pip
from pip._internal.req.req_file import parse_requirements
from importlib.metadata import version, PackageNotFoundError
from packaging.requirements import Requirement
from packaging.specifiers import SpecifierSet
from packaging.version import Version
import argparse
import sys
def check_dependencies(requirement_file_name):
"""
Checks to see if the python dependencies are fulfilled.
If check passes return 0. Otherwise print error and return 1.
"""
requirements = list(parse_requirements(requirement_file_name, session=False))
print("Found {} requirements".format(len(requirements)))
for req in requirements:
requirement_str = str(req.requirement)
try:
parsed_req = Requirement(requirement_str)
installed_version = version(parsed_req.name)
specifier_set = SpecifierSet(str(parsed_req.specifier))
if installed_version in specifier_set:
print(f" + {parsed_req.name}=={installed_version} is installed (required: {parsed_req})")
else:
print(f" - {parsed_req.name}=={installed_version} is installed but does not match the requirement {parsed_req}.")
return 1
except PackageNotFoundError:
print(f"{parsed_req.name} is not installed.")
return 1
except Exception as e:
print(f"An error occurred: {e}")
return 1
return 0
def main():
parser = argparse.ArgumentParser(description="Check if all modules (with correct version) required for pyOpenMS are installed.")
parser.add_argument('filename', help="The path where to find `requirements.txt`")
args = parser.parse_args()
if not args.filename:
print("Error: Filename providing a `requirements.txt` is required.")
sys.exit(1)
ret = check_dependencies(args.filename)
sys.exit(ret)
if __name__ == "__main__":
main()
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/check_test_coverage.py | .py | 2,428 | 81 | import os
import glob
import pyopenms
toTest = set()
# pyopenms in the ignore list as it is represented twice in
# the pyopenms package
ignore = ["numpy", "np", "re", "os", "types", "sysinfo", "pyopenms"]
for clz_name, clz in pyopenms.__dict__.items():
if clz_name in ignore or clz_name.startswith("__"):
continue
if not hasattr(clz, "__dict__"):
continue
for method_name, method in clz.__dict__.items():
if method_name.startswith("_") and not method_name.startswith("__"):
continue
if method_name in [ "__doc__", "__new__", "__file__", "__name__",
"__package__", "__builtins__", "__copy__"]:
continue
toTest.add("%s.%s" % (clz_name, method_name))
def parse_doc(item, collection):
if item.__doc__ is not None:
it = iter(item.__doc__.split("\n"))
for line in it:
if not "@tests" in line:
continue
for line in it:
line = line.strip()
if "@end" in line:
break
if not line:
continue
clz, method = line.split(".")
if clz=="":
clz = oldclzz
fullname = "%s.%s" % (clz, method)
if fullname.endswith("()"):
print fullname, "declared with parentesis, fix it"
fullname = fullname[:-2]
collection.add(fullname)
oldclzz = clz
def collectRecursed(obj, collection):
if hasattr(obj, "__dict__"):
for name, item in obj.__dict__.items():
if name.upper().startswith("TEST") or\
name.upper().startswith("_TEST"):
parse_doc(item, collection)
collectRecursed(item, collection)
declaredAsTested = set()
for p in glob.glob("tests/unittests/test*.py"):
module_name= p[:-3].replace("/",".").replace(os.sep, ".")
module = __import__(module_name).unittests
collectRecursed(module, declaredAsTested)
missing = toTest-declaredAsTested
if missing:
print
print len(missing), "tests/test declarations are missing !"
for name in sorted(missing):
print " ", name
toMuch = declaredAsTested-toTest
if toMuch:
print
print len(toMuch), "tests/test declarations do not fit:"
for name in toMuch:
print " ", name
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/create_cpp_extension.py | .py | 9,387 | 230 | # input-encoding: latin-1
from __future__ import print_function
# use autowrap to generate Cython and .cpp file for wrapping OpenMS:
import autowrap.Main
import autowrap.CodeGenerator
import autowrap.DeclResolver
import glob
import pickle
import os.path
import os
import shutil
import sys
# windows ?
iswin = sys.platform == "win32"
# make sure we only log errors and not info/debug ...
import logging
import autowrap
# from logging import CRITICAL, ERROR, WARNING, INFO, DEBUG
# INFO = 20, WARNING=30, autowrap progress reports = 25
logging.getLogger("autowrap").setLevel(logging.INFO+1)
def doCythonCodeGeneration(modname, allDecl_mapping, instance_map, converters):
m_filename = "pyopenms/%s.pyx" % modname
cimports, manual_code = autowrap.Main.collect_manual_code(allDecl_mapping[modname]["addons"])
autowrap.Main.register_converters(converters)
autowrap_include_dirs = autowrap.generate_code(allDecl_mapping[modname]["decls"], instance_map,
target=m_filename, debug=False, manual_code=manual_code,
extra_cimports=cimports,
include_numpy=True, all_decl=allDecl_mapping, add_relative=True)
allDecl_mapping[modname]["inc_dirs"] = autowrap_include_dirs
return autowrap_include_dirs
def doCythonCompile(arg):
"""
Perform the Cython compilation step for each module
"""
modname, autowrap_include_dirs = arg
m_filename = "pyopenms/%s.pyx" % modname
print ("Cython compile", m_filename)
autowrap.Main.run_cython(inc_dirs=autowrap_include_dirs, extra_opts={}, out=m_filename, warn_level=2)
if __name__ == '__main__':
# import config
from env import (QT_QMAKE_VERSION_INFO, OPEN_MS_BUILD_TYPE, PYOPENMS_SRC_DIR,
OPEN_MS_CONTRIB_BUILD_DIRS, OPEN_MS_LIB, OPEN_SWATH_ALGO_LIB,
OPEN_MS_BUILD_DIR, MSVS_RTLIBS, OPEN_MS_VERSION,
Boost_MAJOR_VERSION, Boost_MINOR_VERSION, PY_NUM_THREADS, PY_NUM_MODULES)
IS_DEBUG = OPEN_MS_BUILD_TYPE.upper() == "DEBUG"
print("Build type is: ", OPEN_MS_BUILD_TYPE)
print("Number of submodules: ", PY_NUM_MODULES)
print("Number of concurrent threads: ", PY_NUM_THREADS)
if iswin and IS_DEBUG:
raise Exception("building pyopenms on windows in debug mode not tested yet.")
classdocu_base = "http://www.openms.de/current_doxygen/html/"
autowrap.CodeGenerator.special_class_doc = "\n Original C++ documentation is available `here <" + classdocu_base + "class%(namespace)s_1_1%(cpp_name)s.html>`_\n"
autowrap.DeclResolver.default_namespace = "OpenMS"
def chunkIt(seq, num):
avg = len(seq) / float(num)
out = []
last = 0.0
while len(out) < num:
out.append(seq[int(last):int(last + avg)])
last += avg
# append the rest to the last element (if there is any)
out[-1].extend( seq[int(last):] )
return out
j = os.path.join
pxd_files = glob.glob(PYOPENMS_SRC_DIR + "/pxds/*.pxd")
addons = glob.glob(PYOPENMS_SRC_DIR + "/addons/*.pyx")
converters = [j(PYOPENMS_SRC_DIR, "converters")]
persisted_data_path = "include_dir.bin"
extra_cimports = []
# We need to parse them all together but keep the association about which class
# we found in which file (as they often need to be analyzed together)
# TODO think about having a separate NUM_THREADS argument for parsing/cythonizing, since it is less
# memory intensive than the actualy compilation into a module (done in setup.py).
# Hide annoying redeclaration errors from unscoped enums by using warning level 2.
# This might lead to a minimal amount of unseen errors, but with all the mess, we would not have spotted them anyway.
# This can be removed as soon as autowrap supports Cython 3 (intodruced scoped enum support) and OpenMS scopes all enums (e.g. with enum class).
decls, instance_map = autowrap.parse(pxd_files, ".", num_processes=int(PY_NUM_THREADS), cython_warn_level=2)
# Perform mapping
pxd_decl_mapping = {}
for de in decls:
tmp = pxd_decl_mapping.get(de.cpp_decl.pxd_path, [])
tmp.append(de)
pxd_decl_mapping[ de.cpp_decl.pxd_path] = tmp
# add __str__ if toString() method is declared:
for d in decls:
# enums, free functions, .. do not have a methods attribute
methods = getattr(d, "methods", dict())
to_strings = []
for name, mdecls in methods.items():
for mdecl in mdecls:
name = mdecl.cpp_decl.annotations.get("wrap-cast", name)
name = mdecl.cpp_decl.annotations.get("wrap-as", name)
if name == "toString":
to_strings.append(mdecl)
for to_string in to_strings:
if len(to_string.arguments) == 0:
d.methods.setdefault("__str__", []).append(to_string)
print("ADDED __str__ method to", d.name)
break
# Split into chunks based on pxd files and store the mapping to decls, addons
# and actual pxd files in a hash. We need to produce the exact number of chunks
# as setup.py relies on it as well.
pxd_files_chunk = chunkIt(list(pxd_decl_mapping.keys()), int(PY_NUM_MODULES))
# Sanity checks: we should find all of our chunks and not have lost files
if len(pxd_files_chunk) != int(PY_NUM_MODULES):
raise Exception("Internal Error: number of chunks not equal to number of modules")
if sum([len(ch) for ch in pxd_files_chunk]) != len(pxd_decl_mapping):
raise Exception("Internal Error: chunking lost files")
if (int(PY_NUM_MODULES)==1):
mnames = ["_pyopenms"]
else:
mnames = ["_pyopenms_%s" % (k+1) for k in range(int(PY_NUM_MODULES))]
allDecl_mapping = {}
for pxd_f, m in zip(pxd_files_chunk, mnames):
tmp_decls = []
for f in pxd_f:
tmp_decls.extend( pxd_decl_mapping[f] )
allDecl_mapping[m] = {"decls" : tmp_decls, "addons" : [] , "files" : pxd_f}
# Deal with addons, make sure the addons are added to the correct compilation
# unit (e.g. where the name corresponds to the pxd file).
# Note that there are some special cases, e.g. addons that go into the first
# unit or all *but* the first unit.
is_added = [False for k in addons]
for modname in mnames:
for k,a in enumerate(addons):
# Deal with special code that needs to go into all modules, only the
# first or only all other modules...
if modname == mnames[0]:
if os.path.basename(a) == "ADD_TO_FIRST" + ".pyx":
allDecl_mapping[modname]["addons"].append(a)
is_added[k] = True
else:
if os.path.basename(a) == "ADD_TO_ALL_OTHER" + ".pyx":
allDecl_mapping[modname]["addons"].append(a)
is_added[k] = True
if os.path.basename(a) == "ADD_TO_ALL" + ".pyx":
allDecl_mapping[modname]["addons"].append(a)
is_added[k] = True
# Match addon basename to pxd basename
for pfile in allDecl_mapping[modname]["files"]:
if os.path.basename(a).split(".")[0] == os.path.basename(pfile).split(".")[0]:
allDecl_mapping[modname]["addons"].append(a)
is_added[k] = True
# In the special case PY_NUM_MODULES==1 we need to mark ADD_TO_ALL_OTHER as is_added,
# so it doesn't get added to pyopenms_1.pxd
if PY_NUM_MODULES=='1':
if os.path.basename(a) == "ADD_TO_ALL_OTHER" + ".pyx":
is_added[k] = True
if is_added[k]:
continue
# Also match by class name (sometimes one pxd contains multiple classes
# and the addon is named after one of them)
for dclass in allDecl_mapping[modname]["decls"]:
if os.path.basename(a) == dclass.name + ".pyx":
allDecl_mapping[modname]["addons"].append(a)
is_added[k] = True
# add any addons that did not get added anywhere else
for k, got_added in enumerate(is_added):
if not got_added:
# add to all modules
for m in mnames:
allDecl_mapping[m]["addons"].append( addons[k] )
for modname in mnames:
autowrap_include_dirs = doCythonCodeGeneration(modname, allDecl_mapping, instance_map, converters)
pickle.dump(autowrap_include_dirs, open(persisted_data_path, "wb"))
argzip = [ (modname, allDecl_mapping[modname]["inc_dirs"]) for modname in mnames]
import multiprocessing
pool = multiprocessing.Pool(int(PY_NUM_THREADS))
pool.map(doCythonCompile, argzip)
pool.close()
pool.join()
print("Created all %s pyopenms.cpps" % PY_NUM_MODULES)
with open("pyopenms/_all_modules.py", "w") as fp:
for modname in mnames:
fp.write("from .%s import * # pylint: disable=wildcard-import; lgtm(py/polluting-import)\n" % modname)
with open("pyopenms/_all_modules.pyi", "w") as fp:
for modname in mnames:
fp.write("from .%s import * # pylint: disable=wildcard-import; lgtm(py/polluting-import)\n" % modname)
# create version information
version = OPEN_MS_VERSION
print("version=%r\n" % version, file=open("pyopenms/_version.py", "w"))
print("info=%r\n" % QT_QMAKE_VERSION_INFO, file=open("pyopenms/_qt_version_info.py", "w"))
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/doCythonCompileOnly.py | .py | 1,559 | 53 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
SPDX-License-Identifier: BSD-3-Clause
--------------------------------------------------------------------------
$Maintainer: Hannes Roest $
$Authors: Hannes Roest $
--------------------------------------------------------------------------
"""
"""
This program can be used to only compile the pyopenms.pyx to a cpp file using
Cython. This is an intermediate step in the pyOpenMS build process and it
should only be used for debugging.
It may be useful if something went wrong during the Cython compilation. One can
then try to fix the pyopenms.pyx file, run this script and see whether Cython
parses it.
Author: Hannes Roest
"""
# Py2/3 fix
try:
import cPickle
except ImportError:
import _pickle as cPickle
persisted_data_path = "include_dir.bin"
try:
autowrap_include_dirs = cPickle.load(open(persisted_data_path, "rb"))
except IOError:
print("The file include_dir.bin does not yet exist, please run setup.py first to create it.")
from Cython.Compiler.Main import compile, CompilationOptions
import Cython
print("Will try to compile with Cython version", Cython.__version__)
# Prepare options
print ("include:", autowrap_include_dirs)
options = dict(include_path=autowrap_include_dirs,
#output_dir=".",
#gdb_debug=True,
cplus=True)
# Do Cython compile
import sys
out = sys.argv[1]
options = CompilationOptions(**options)
compile(out, options=options)
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyopenms/_sysinfo.py | .py | 1,460 | 48 | import sys
if sys.platform.startswith("linux"):
import ctypes as c
import ctypes.util
libc = c.CDLL(ctypes.util.find_library("c"))
class SysInfo(c.Structure):
# for libc5: needs padding
padding = 20 - 2 * c.sizeof(c.c_long) - c.sizeof(c.c_int)
_fields_ = [("uptime", c.c_ulong),
("loads", 3 * c.c_ulong),
("totalram", c.c_ulong),
("freeram", c.c_ulong),
("sharedram", c.c_ulong),
("bufferram", c.c_ulong),
("totalswap", c.c_ulong),
("freeswap", c.c_ulong),
("procs", c.c_ushort),
("totalhigh", c.c_ulong),
("freehigh", c.c_ulong),
("mem_unit", c.c_ulong),
("_padding", padding * c.c_char)
]
def free_mem():
sys_info = SysInfo()
libc.sysinfo(c.byref(sys_info))
return sys_info.freeram
elif sys.platform == "win32":
try:
import win32api
except:
free_mem = lambda: 0 # memory will never change !
else:
def free_mem():
return win32api.GlobalMemoryStatus()['AvailPhys']
else:
sys.stderr.write("Determination of memory status is not supported on this \n"
" platform, measuring for memoryleaks will never fail\n")
free_mem = lambda: 0 # memory will never change !
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyopenms/run_cython.sh | .sh | 162 | 3 | AUTOWRAP=$(python -c "import autowrap; print autowrap.__path__[0]")
cython --cplus pyopenms.pyx -I ../pxds -I $AUTOWRAP/data_files -I $AUTOWRAP/data_files/boost
| Shell |
3D | OpenMS/OpenMS | src/pyOpenMS/pyopenms/__init__.py | .py | 4,800 | 113 | #!/usr/bin/python
# -*- encoding: utf8 -*-
"""Python bindings to the OpenMS C++ library.
The pyOpenMS package contains Python bindings for a large part of the OpenMS
library (https://openms.de) for mass spectrometry based proteomics. It thus
provides providing facile access to a feature-rich, open-source algorithm
library for mass-spectrometry based proteomics analysis. These Python bindings
allow raw access to the data-structures and algorithms implemented in OpenMS,
specifically those for file access (mzXML, mzML, TraML, mzIdentML among
others), basic signal processing (smoothing, filtering, de-isotoping and
peak-picking) and complex data analysis (including label-free, SILAC, iTRAQ and
SWATH analysis tools).
For further documentation, please see https://pyopenms.readthedocs.io
Please cite:
Röst HL, Schmitt U, Aebersold R, Malmström L.
pyOpenMS: a Python-based interface to the OpenMS mass-spectrometry algorithm library.
Proteomics. 2014 Jan;14(1):74-7. doi: 10.1002/pmic.201300246.
"""
from __future__ import print_function
import warnings
from ._sysinfo import * # pylint: disable=wildcard-import; lgtm(py/polluting-import)
from ._version import version as __version__
import os
here = os.path.abspath(os.path.dirname(__file__))
default_openms_data_path = os.path.join(here, "share", "OpenMS")
env_openms_data_path = os.environ.get("OPENMS_DATA_PATH")
if os.path.exists(default_openms_data_path):
if not env_openms_data_path:
os.environ["OPENMS_DATA_PATH"] = default_openms_data_path
elif os.path.abspath(env_openms_data_path) != os.path.abspath(default_openms_data_path):
warnings.warn(
"Warning: OPENMS_DATA_PATH environment exists and points to a different location "
"than the default share directory. "
"pyOpenMS will use it ({env}) to locate data in the OpenMS share folder "
"(e.g., the unimod database), instead of the default ({default})."
.format(env=env_openms_data_path, default=default_openms_data_path)
)
else:
if not env_openms_data_path:
warnings.warn(
"Warning: OPENMS_DATA_PATH environment variable not found and no share directory was installed. "
"Some functionality might not work as expected."
)
import sys
# on conda the libs will be installed to the general conda lib path which is available during load.
# try to skip this loading if we do not ship the libraries in the package (e.g. as wheel via pip)
# TODO check if this can be completely removed by now or e.g. by baking in an RPATH into the pyopenms*.so's
if sys.platform.startswith("linux") and os.path.exists(os.path.join(here, "libOpenMS.so")):
# load local shared libraries before we import pyopenms*.so, else
# those are not found. setting LD_LIBRARY_PATH does not work,
# see: http://stackoverflow.com/questions/1178094
import ctypes
ctypes.cdll.LoadLibrary(os.path.join(here, "libOpenSwathAlgo.so"))
ctypes.cdll.LoadLibrary(os.path.join(here, "libOpenMS.so"))
try:
from ._all_modules import * # pylint: disable=wildcard-import; lgtm(py/polluting-import)
from ._python_extras import * # pylint: disable=wildcard-import; lgtm(py/polluting-import)
# This has to be imported after all_modules so it can augment the core datastructures with dataframe
# export capabilities
from ._dataframes import * # pylint: disable=wildcard-import; lgtm(py/polluting-import)
except Exception as e:
print("")
print("="*70)
print("Error when loading pyOpenMS libraries!")
print("Libraries could not be found / could not be loaded.")
print("")
print("To debug this error, please run ldd (on linux), otool -L (on macOS) or dependency walker (on windows) on ")
print("")
print(os.path.join(here, "pyopenms*.so"))
print("")
print("="*70)
try:
import PyQt5.QtCore
except:
pass
else:
from ._qt_version_info import info
info = "\n ".join(info.split("\n"))
print("""PyQt5 was found to be installed. When building pyopenms qmake said:
%s
PYQT has version %s
This might cause a conflict if both are loaded. You can test this by importing pyopenms
first and then import PyQt5.QtCore.
""" % (info, PyQt5.QtCore.PYQT_VERSION_STR) )
print("Note: when using the Spyder IDE, the usage of PyQt might be circumvented")
print("by not using the 'Automatic' backend. Please change this in Tools ->")
print("Preferences -> IPython -> Graphics to 'Inline'.")
print("In general, try to install everything with conda in the same environment to make sure Qt is used in the same version.")
print("")
print("="*70)
print("\n")
raise e
del os, here, sys
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyopenms/_dataframes.py | .py | 5,996 | 163 | """DataFrame export utilities for pyOpenMS.
This module provides utility functions for converting OpenMS data structures to pandas DataFrames.
The get_df() methods are now implemented directly in the Cython classes (MSSpectrum, MSChromatogram,
Mobilogram, MSExperiment, ConsensusMap, FeatureMap, MRMTransitionGroupCP, PeptideIdentificationList).
This module provides backwards-compatible function aliases:
- peptide_identifications_to_df: Calls PeptideIdentificationList.get_df()
- update_scores_from_df: Calls PeptideIdentificationList.update_scores_from_df()
And utility functions:
- common_meta_value_types: Dictionary for numpy type mapping of common meta values
"""
from __future__ import annotations
__all__ = [
'peptide_identifications_to_df',
'update_scores_from_df',
'common_meta_value_types',
'_add_meta_values',
]
from typing import Any, TYPE_CHECKING
from . import PeptideIdentificationList as _PeptideIdentificationList
from . import DataValue as _DataValue
import numpy as _np
if TYPE_CHECKING:
import pandas as _pd
else:
class _PandasStub:
DataFrame = Any
_pd = _PandasStub()
# Common meta value types for numpy type mapping
common_meta_value_types = {
b'label': 'U50',
b'spectrum_index': 'i',
b'score_fit': 'f',
b'score_correlation': 'f',
b'FWHM': 'f',
b'spectrum_native_id': 'U100',
b'max_height': 'f',
b'num_of_masstraces': 'i',
b'masstrace_intensity': 'f',
b'Group': 'U50',
b'is_ungrouped_monoisotopic': 'i',
b'leftWidth': 'f',
b'rightWidth': 'f',
b'total_xic': 'f',
b'PeptideRef': 'U100',
b'peak_apices_sum': 'f'
}
"""Global dict to define which autoconversion to numpy types is tried for certain metavalues.
This can be changed to your liking but only affects future exports of any OpenMS datastructure to dataframes.
Especially string lengths (i.e., U types) benefit from adaption to save memory. The default type is currently
hardcoded to U50 (i.e., 50 unicode characters)
"""
def peptide_identifications_to_df(peps: _PeptideIdentificationList, decode_ontology: bool = True,
default_missing_values: dict = None,
export_unidentified: bool = True):
"""Converts a list of peptide identifications to a pandas DataFrame.
This is a backwards-compatible wrapper that calls PeptideIdentificationList.get_df().
For new code, prefer calling peps.get_df() directly.
:param peps: list of PeptideIdentification objects
:type peps: PeptideIdentificationList
:param decode_ontology: decode meta value names
:type decode_ontology: bool
:param default_missing_values: default value for missing values for each data type
:type default_missing_values: dict
:param export_unidentified: export PeptideIdentifications without PeptideHit
:type export_unidentified: bool
:return: peptide identifications in a DataFrame
:rtype: pandas.DataFrame
"""
return peps.get_df(decode_ontology=decode_ontology,
default_missing_values=default_missing_values,
export_unidentified=export_unidentified)
def update_scores_from_df(peps: _PeptideIdentificationList, df: _pd.DataFrame, main_score_name: str):
"""
Updates the scores in PeptideIdentification objects using a pandas dataframe.
This is a backwards-compatible wrapper that calls PeptideIdentificationList.update_scores_from_df().
For new code, prefer calling peps.update_scores_from_df(df, main_score_name) directly.
:param peps: list of PeptideIdentification objects
:param df: pandas dataframe obtained by converting peps to a dataframe. Minimum required: P_ID column and column with name passed by main_score_name
:param main_score_name: name of the score column
:return: the updated list of peptide identifications
"""
return peps.update_scores_from_df(df, main_score_name)
def _add_meta_values(df: _pd.DataFrame, object: Any) -> _pd.DataFrame:
"""
Adds metavalues from given object to given DataFrame.
:param df: DataFrame to which metavalues will be added.
:type df: pandas.DataFrame
:param object: Object from which metavalues will be extracted.
:type object: Any
:return: DataFrame with added meta values.
:rtype: pandas.DataFrame
"""
mvs = []
object.getKeys(mvs)
for k in mvs:
dv = object.getMetaValue(k)
col_name = k.decode()
try:
# Handle native Python types (returned by autowrap)
if isinstance(dv, float):
value = dv
dtype = "float64"
elif isinstance(dv, int):
value = dv
dtype = "int64"
elif isinstance(dv, str):
value = dv
dtype = f"U{max(1, len(value))}"
elif isinstance(dv, bytes):
value = dv.decode()
dtype = f"U{max(1, len(value))}"
# Handle DataValue objects (if ever returned)
elif hasattr(dv, 'valueType'):
if dv.valueType() == _DataValue.STRING_VALUE:
value = dv.toString().decode()
dtype = f"U{max(1, len(value))}"
elif dv.valueType() == _DataValue.INT_VALUE:
value = dv.toInt()
dtype = "int32"
elif dv.valueType() == _DataValue.DOUBLE_VALUE:
value = dv.toDouble()
dtype = "float64"
elif dv.valueType() == _DataValue.EMPTY_VALUE:
continue
else:
value = str(dv)
dtype = "object"
else:
value = str(dv)
dtype = "object"
df[col_name] = _np.full(df.shape[0], value, dtype=dtype)
except Exception:
df[col_name] = _np.full(df.shape[0], str(dv), dtype='object')
return df
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyopenms/plotting.py | .py | 21,178 | 460 | """Plot MSSpectrum & MSChromatogram data
The MSSpectrum plotting function are adapted from:
Wout Bittremieux. “spectrum_utils: A Python package for mass spectrometry data processing and visualization.”
Plot a single spectrum with plot_spectrum or two with mirror_plot_spectrum, using matplotlib.
"""
# Code adopted from:
# Wout Bittremieux. “spectrum_utils: A Python package for mass spectrometry data processing and visualization.”
# Analytical Chemistry 92 (1) 659-661 (2020) doi:10.1021/acs.analchem.9b04884.
# Apache License
# Version 2.0, January 2004
# http://www.apache.org/licenses/
#
# TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
#
# 1. Definitions.
#
# "License" shall mean the terms and conditions for use, reproduction,
# and distribution as defined by Sections 1 through 9 of this document.
#
# "Licensor" shall mean the copyright owner or entity authorized by
# the copyright owner that is granting the License.
#
# "Legal Entity" shall mean the union of the acting entity and all
# other entities that control, are controlled by, or are under common
# control with that entity. For the purposes of this definition,
# "control" means (i) the power, direct or indirect, to cause the
# direction or management of such entity, whether by contract or
# otherwise, or (ii) ownership of fifty percent (50%) or more of the
# outstanding shares, or (iii) beneficial ownership of such entity.
#
# "You" (or "Your") shall mean an individual or Legal Entity
# exercising permissions granted by this License.
#
# "Source" form shall mean the preferred form for making modifications,
# including but not limited to software source code, documentation
# source, and configuration files.
#
# "Object" form shall mean any form resulting from mechanical
# transformation or translation of a Source form, including but
# not limited to compiled object code, generated documentation,
# and conversions to other media types.
#
# "Work" shall mean the work of authorship, whether in Source or
# Object form, made available under the License, as indicated by a
# copyright notice that is included in or attached to the work
# (an example is provided in the Appendix below).
#
# "Derivative Works" shall mean any work, whether in Source or Object
# form, that is based on (or derived from) the Work and for which the
# editorial revisions, annotations, elaborations, or other modifications
# represent, as a whole, an original work of authorship. For the purposes
# of this License, Derivative Works shall not include works that remain
# separable from, or merely link (or bind by name) to the interfaces of,
# the Work and Derivative Works thereof.
#
# "Contribution" shall mean any work of authorship, including
# the original version of the Work and any modifications or additions
# to that Work or Derivative Works thereof, that is intentionally
# submitted to Licensor for inclusion in the Work by the copyright owner
# or by an individual or Legal Entity authorized to submit on behalf of
# the copyright owner. For the purposes of this definition, "submitted"
# means any form of electronic, verbal, or written communication sent
# to the Licensor or its representatives, including but not limited to
# communication on electronic mailing lists, source code control systems,
# and issue tracking systems that are managed by, or on behalf of, the
# Licensor for the purpose of discussing and improving the Work, but
# excluding communication that is conspicuously marked or otherwise
# designated in writing by the copyright owner as "Not a Contribution."
#
# "Contributor" shall mean Licensor and any individual or Legal Entity
# on behalf of whom a Contribution has been received by Licensor and
# subsequently incorporated within the Work.
#
# 2. Grant of Copyright License. Subject to the terms and conditions of
# this License, each Contributor hereby grants to You a perpetual,
# worldwide, non-exclusive, no-charge, royalty-free, irrevocable
# copyright license to reproduce, prepare Derivative Works of,
# publicly display, publicly perform, sublicense, and distribute the
# Work and such Derivative Works in Source or Object form.
#
# 3. Grant of Patent License. Subject to the terms and conditions of
# this License, each Contributor hereby grants to You a perpetual,
# worldwide, non-exclusive, no-charge, royalty-free, irrevocable
# (except as stated in this section) patent license to make, have made,
# use, offer to sell, sell, import, and otherwise transfer the Work,
# where such license applies only to those patent claims licensable
# by such Contributor that are necessarily infringed by their
# Contribution(s) alone or by combination of their Contribution(s)
# with the Work to which such Contribution(s) was submitted. If You
# institute patent litigation against any entity (including a
# cross-claim or counterclaim in a lawsuit) alleging that the Work
# or a Contribution incorporated within the Work constitutes direct
# or contributory patent infringement, then any patent licenses
# granted to You under this License for that Work shall terminate
# as of the date such litigation is filed.
#
# 4. Redistribution. You may reproduce and distribute copies of the
# Work or Derivative Works thereof in any medium, with or without
# modifications, and in Source or Object form, provided that You
# meet the following conditions:
#
# (a) You must give any other recipients of the Work or
# Derivative Works a copy of this License; and
#
# (b) You must cause any modified files to carry prominent notices
# stating that You changed the files; and
#
# (c) You must retain, in the Source form of any Derivative Works
# that You distribute, all copyright, patent, trademark, and
# attribution notices from the Source form of the Work,
# excluding those notices that do not pertain to any part of
# the Derivative Works; and
#
# (d) If the Work includes a "NOTICE" text file as part of its
# distribution, then any Derivative Works that You distribute must
# include a readable copy of the attribution notices contained
# within such NOTICE file, excluding those notices that do not
# pertain to any part of the Derivative Works, in at least one
# of the following places: within a NOTICE text file distributed
# as part of the Derivative Works; within the Source form or
# documentation, if provided along with the Derivative Works; or,
# within a display generated by the Derivative Works, if and
# wherever such third-party notices normally appear. The contents
# of the NOTICE file are for informational purposes only and
# do not modify the License. You may add Your own attribution
# notices within Derivative Works that You distribute, alongside
# or as an addendum to the NOTICE text from the Work, provided
# that such additional attribution notices cannot be construed
# as modifying the License.
#
# You may add Your own copyright statement to Your modifications and
# may provide additional or different license terms and conditions
# for use, reproduction, or distribution of Your modifications, or
# for any such Derivative Works as a whole, provided Your use,
# reproduction, and distribution of the Work otherwise complies with
# the conditions stated in this License.
#
# 5. Submission of Contributions. Unless You explicitly state otherwise,
# any Contribution intentionally submitted for inclusion in the Work
# by You to the Licensor shall be under the terms and conditions of
# this License, without any additional terms or conditions.
# Notwithstanding the above, nothing herein shall supersede or modify
# the terms of any separate license agreement you may have executed
# with Licensor regarding such Contributions.
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor,
# except as required for reasonable and customary use in describing the
# origin of the Work and reproducing the content of the NOTICE file.
#
# 7. Disclaimer of Warranty. Unless required by applicable law or
# agreed to in writing, Licensor provides the Work (and each
# Contributor provides its Contributions) on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied, including, without limitation, any warranties or conditions
# of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
# PARTICULAR PURPOSE. You are solely responsible for determining the
# appropriateness of using or redistributing the Work and assume any
# risks associated with Your exercise of permissions under this License.
#
# 8. Limitation of Liability. In no event and under no legal theory,
# whether in tort (including negligence), contract, or otherwise,
# unless required by applicable law (such as deliberate and grossly
# negligent acts) or agreed to in writing, shall any Contributor be
# liable to You for damages, including any direct, indirect, special,
# incidental, or consequential damages of any character arising as a
# result of this License or out of the use or inability to use the
# Work (including but not limited to damages for loss of goodwill,
# work stoppage, computer failure or malfunction, or any and all
# other commercial damages or losses), even if such Contributor
# has been advised of the possibility of such damages.
#
# 9. Accepting Warranty or Additional Liability. While redistributing
# the Work or Derivative Works thereof, You may choose to offer,
# and charge a fee for, acceptance of support, warranty, indemnity,
# or other liability obligations and/or rights consistent with this
# License. However, in accepting such obligations, You may act only
# on Your own behalf and on Your sole responsibility, not on behalf
# of any other Contributor, and only if You agree to indemnify,
# defend, and hold each Contributor harmless for any liability
# incurred by, or claims asserted against, such Contributor by reason
# of your accepting any such warranty or additional liability.
#
# END OF TERMS AND CONDITIONS
import math
from typing import Dict, Optional, Tuple, Union, List, Set
import itertools
import logging
# TODO switch to forward declarations via from __future__ import annotations
# when py 3.7 is minimum. Then you can use types instead of strings
def plot_chromatogram(c: "MSChromatogram"):
"""Plot chromatogram peaks.
:param c: The chromatogram to be plotted.
:type c: MSChromatogram
"""
import matplotlib.pyplot as plt
x, y = c.get_peaks()
plt.plot(x, y)
plt.xlabel("Retention time")
plt.ylabel("Intensity")
plt.show()
def _annotate_ion(mz: float, intensity: float, annotation: Optional[str],
color_ions: bool, annotate_ions: bool, matched: Optional[bool],
annotation_kws: Dict[str, object], colormap: Dict[str, str], ax) -> Tuple[str, int]:
"""Annotate a specific fragment peak.
:param mz: The peak's m/z value (position of the annotation on the x axis).
:type mz: float
:param intensity: The peak's intensity (position of the annotation on the y axis).
:type intensity: float
:param annotation: The annotation that will be plotted.
:type annotation: str, optional
:param color_ions: Flag whether to color the peak annotation or not.
:type color_ions: bool
:param annotate_ions: Flag whether to annotation the peak or not.
:type annotate_ions: bool
:param annotation_kws: Keyword arguments for `ax.text` to customize peak annotations.
:type annotation_kws: Dict[str, object]
:param ax: Axes instance on which to plot the annotation.
:type ax: plt.Axes
:return: A tuple of the annotation's color as a hex string and the annotation's zorder.
:rtype: Tuple[str, int]
"""
colors = {'a': '#388E3C', 'b': '#1976D2', 'c': '#00796B',
'x': '#7B1FA2', 'y': '#D32F2F', 'z': '#F57C00',
'p': '#512DA8', 'f': '#212121', None: '#212121',
'matched': '#ff0000', 'unmatched': '#aaaaaa'}
zorders = {'a': 3, 'b': 4, 'c': 3, 'x': 3, 'y': 4, 'z': 3,
'p': 3, '?': 2, 'f': 5, None: 1}
if colormap is not None:
colors.update(colormap)
annotation = annotation if annotation is not None and len(annotation.strip()) > 0 else ''
# Else: Add the textual annotation.
ion_type = None if len(annotation) == 0 else annotation[0]
if ion_type == '[': # precursor ion
ion_type = 'p'
if ion_type not in colors and color_ions:
logging.warning(f'Ion type {ion_type} not supported')
return colors.get(None), zorders.get(None)
color = (colors[ion_type] if color_ions else
colors[None])
zorder = (1 if ion_type not in zorders else zorders[ion_type])
if matched is not None and not matched:
color = colors.get('unmatched')
if matched is not None and matched and not color_ions:
color = colors.get('matched')
if annotate_ions:
annotation_pos = intensity
if annotation_pos > 0:
annotation_pos += 0.02
kws = annotation_kws.copy()
del kws['zorder']
ax.text(mz, annotation_pos, str(annotation), color=color,
zorder=zorder, **kws)
return color, zorder
def plot_spectrum(spectrum: "MSSpectrum", color_ions: bool = True,
annotate_ions: bool = True, matched_peaks: Optional[Set] = None, annot_kws: Optional[Dict] = None,
mirror_intensity: bool = False, grid: Union[bool, str] = False, colormap: Optional[Dict] = None,
spine: bool=False, show_unmatched_peaks=True, ax=None):
"""Plot an MS/MS spectrum.
:param spectrum: The spectrum to be plotted.
Reads annotations from the first StringDataArray if it has the same length as the number of peaks.
:type spectrum: MSSpectrum
:param color_ions: Flag indicating whether to color annotated fragment ions. The default is True.
:type color_ions: bool, optional
:param annotate_ions: Flag indicating whether to annotate fragment ions. The default is True.
:type annotate_ions: bool, optional
:param matched_peaks: Indices of matched peaks in a spectrum alignment.
:type matched_peaks: Optional[Set], optional
:param annot_kws: Keyword arguments for `ax.text` to customize peak annotations.
:type annot_kws: Optional[Dict], optional
:param mirror_intensity: Flag indicating whether to flip the intensity axis or not.
:type mirror_intensity : bool, optional
:param grid: Draw grid lines or not. Either a boolean to enable/disable both major
and minor grid lines or 'major'/'minor' to enable major or minor grid lines respectively.
:type grid: Union[bool, str], optional
:param colormap: A dictionary mapping ion types to colors. Accepted keys are the ion types: 'a', 'b', 'c', 'x', 'y',
'z', 'p', 'f'. None for unannotated peaks. 'matched' and 'unmatched' for peaks in matched_peaks and not in
matched_peaks, respectively, if provided.
:type colormap: Optional[Dict], optional
:param spine: Flag indicating whether to show the right and top spines.
:type spine: bool, optional
:param show_unmatched_peaks: Flag indicating whether to show unmatched peaks.
:type show_unmatched_peaks: bool, optional
:param ax: Axes instance on which to plot the spectrum. If None the current Axes instance is used.
:type ax : Optional[plt.Axes], optional
:return The matplotlib Axes instance on which the spectrum is plotted.
:rtype: plt.Axes
"""
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
if ax is None:
ax = plt.gca()
mz, intensity = spectrum.get_peaks()
min_mz = max(0, math.floor(mz[0] / 100 - 1) * 100)
max_mz = math.ceil(mz[-1] / 100 + 1) * 100
ax.set_xlim(min_mz, max_mz)
ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.))
y_max = 1.15 if annotate_ions else 1.05
ax.set_ylim(*(0, y_max) if not mirror_intensity else (-y_max, 0))
max_intensity = intensity.max()
if max_intensity == 0: max_intensity = 1
if len(spectrum.getStringDataArrays()) > 0 and len(list(spectrum.getStringDataArrays()[0])) == len(mz):
annotations = [ion.decode() for ion in spectrum.getStringDataArrays()[0]]
else:
annotations = itertools.repeat(None)
annotation_kws = {
'horizontalalignment': 'left' if not mirror_intensity else 'right',
'verticalalignment': 'center', 'rotation': 90,
'rotation_mode': 'anchor', 'zorder': 5}
if annot_kws is not None:
annotation_kws.update(annot_kws)
for i_peak, (peak_mz, peak_intensity, peak_annotation) in enumerate(zip(mz, intensity, annotations)):
peak_intensity = peak_intensity / max_intensity
if mirror_intensity:
peak_intensity *= -1
if matched_peaks is not None:
matched = matched_peaks is not None and i_peak in matched_peaks
else:
matched = None
if not show_unmatched_peaks and not matched:
continue
color, zorder = _annotate_ion(
peak_mz, peak_intensity, peak_annotation, color_ions, annotate_ions,
matched, annotation_kws, colormap, ax)
ax.plot([peak_mz, peak_mz], [0, peak_intensity], color=color, zorder=zorder)
ax.xaxis.set_minor_locator(mticker.AutoLocator())
ax.yaxis.set_minor_locator(mticker.AutoLocator())
ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
ax.yaxis.set_minor_locator(mticker.AutoMinorLocator())
ax.spines['right'].set_visible(spine)
ax.spines['top'].set_visible(spine)
if grid in (True, 'both', 'major'):
ax.grid(visible=True, which='major', color='#9E9E9E', linewidth=0.2)
if grid in (True, 'both', 'minor'):
ax.grid(visible=True, which='minor', color='#9E9E9E', linewidth=0.2)
ax.set_axisbelow(True)
ax.tick_params(axis='both', which='both', labelsize='small')
y_ticks = ax.get_yticks()
ax.set_yticks(y_ticks[y_ticks <= 1.])
ax.set_xlabel('m/z', style='italic')
ax.set_ylabel('Intensity')
return ax
def mirror_plot_spectrum(spec_top: "MSSpectrum", spec_bottom: "MSSpectrum", spectrum_top_kws: Optional[Dict] = None,
spectrum_bottom_kws: Optional[Dict] = None, ax=None):
"""Mirror plot two MS/MS spectra.
:param spec_top: The spectrum to be plotted on the top.
Reads annotations from the first StringDataArray if it has the same length as the number of peaks.
:type spec_top: MSSpectrum
:param spec_bottom: The spectrum to be plotted on the bottom.
Reads annotations from the first StringDataArray if it has the same length as the number of peaks.
:type spec_bottom: MSSpectrum
:param spectrum_top_kws: Keyword arguments for `Plotting.plot_spectrum` of top spectrum.
:type spectrum_top_kws: Optional[Dict], optional
:param spectrum_bottom_kws: Keyword arguments for `Plotting.plot_spectrum` of bottom spectrum.
:type spectrum_bottom_kws: Optional[Dict], optional
:param ax: Axes instance on which to plot the spectrum. If None the current Axes instance is used.
:type ax: Optional[plt.Axes], optional
:return: The matplotlib Axes instance on which the spectra are plotted.
:rtype: plt.Axes
"""
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
if ax is None:
ax = plt.gca()
if spectrum_top_kws is None:
spectrum_top_kws = {}
if spectrum_bottom_kws is None:
spectrum_bottom_kws = {}
# Top spectrum.
plot_spectrum(spec_top, mirror_intensity=False, ax=ax, **spectrum_top_kws)
y_max = ax.get_ylim()[1]
# Mirrored bottom spectrum.
plot_spectrum(spec_bottom, mirror_intensity=True, ax=ax, **spectrum_bottom_kws)
y_min = ax.get_ylim()[0]
ax.set_ylim(y_min, y_max)
ax.axhline(0, color='#9E9E9E', zorder=10)
# Update axes so that both spectra fit.
spec_top_mz, sp_top_intensity = spec_top.get_peaks()
spec_bottom_mz, sp_bottom_intensity = spec_bottom.get_peaks()
min_mz = max([0, math.floor(spec_top_mz[0] / 100 - 1) * 100,
math.floor(spec_bottom_mz[0] / 100 - 1) * 100])
max_mz = max([math.ceil(spec_top_mz[-1] / 100 + 1) * 100,
math.ceil(spec_bottom_mz[-1] / 100 + 1) * 100])
ax.set_xlim(min_mz, max_mz)
ax.yaxis.set_major_locator(mticker.AutoLocator())
ax.yaxis.set_minor_locator(mticker.AutoMinorLocator())
ax.yaxis.set_major_formatter(mticker.FuncFormatter(
lambda x, pos: f'{abs(x):.0%}'))
return ax
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyopenms/Constants.py | .py | 2,568 | 126 |
# @brief Mathematical and physical constants namespace.
#
# This namespace contains definitions for some basic mathematical and physical constants.
# All constants are double precision.
EPSILON = 1e-6
"""EPSILON (used for comparisons)"""
PI = 3.14159265358979323846
"""PI"""
E = 2.718281828459045235
"""Euler's number - base of the natural logarithm"""
ELEMENTARY_CHARGE = 1.60217738E-19
"""Elementary charge (Coulomb)"""
e0 = ELEMENTARY_CHARGE
ELECTRON_MASS = 9.1093897E-31
"""Electron mass (kg)"""
ELECTRON_MASS_U = 1.0 / 1822.8885020477
"""Electron mass in units"""
PROTON_MASS = 1.6726230E-27
"""Proton mass (kg)"""
PROTON_MASS_U = 1.0072764667710
"""Proton mass in units"""
C13C12_MASSDIFF_U = 1.0033548378
"""Mass difference between Carbon-13 and Carbon-12 in units"""
NEUTRON_MASS = 1.6749286E-27
"""Neutron mass (kg)"""
NEUTRON_MASS_U = 1.00866491566
"""Neutron mass in units"""
AVOGADRO = 6.0221367E+23
"""Avogadro constant (1/mol)"""
# Avogadro constant (alias)
NA = AVOGADRO
# Avogadro constant (alias)
MOL = AVOGADRO
BOLTZMANN = 1.380657E-23
"""Boltzmann constant (J/K) """
# Boltzmann constant (alias)
k = BOLTZMANN
PLANCK = 6.6260754E-34
"""Planck constant J * sec"""
# Planck constant (alias)
h = PLANCK
GAS_CONSTANT = NA * k
"""Gas constant (= NA * k)"""
# Gas constant (alias)
R = GAS_CONSTANT
FARADAY = NA * e0
"""Faraday constant (= NA * e0)"""
# Faraday constant (alias)
F = FARADAY
BOHR_RADIUS = 5.29177249E-11 # m
"""Bohr radius (m)"""
# Bohr radius (alias)
a0 = BOHR_RADIUS
# the following values from:
# P.W.Atkins: Physical Chemistry, 5th ed., Oxford University Press, 1995
VACUUM_PERMITTIVITY = 8.85419E-12
"""Vacuum permittivity in C^2 / (J * m)"""
VACUUM_PERMEABILITY = (4 * PI * 1E-7)
"""Vacuum permeability in J s^2 / (C^2 * m)"""
SPEED_OF_LIGHT = 2.99792458E+8
"""Speed of light in m/s"""
# Speed of Light (alias)
c = SPEED_OF_LIGHT
GRAVITATIONAL_CONSTANT = 6.67259E-11
""" Gravitational constant in N m^2 / kg^2"""
FINE_STRUCTURE_CONSTANT = 7.29735E-3
"""Fine structure constant"""
DEG_PER_RAD = 57.2957795130823209
"""Degree per rad"""
RAD_PER_DEG = 0.0174532925199432957
"""Rad per degree"""
MM_PER_INCH = 25.4
"""mm per inch"""
M_PER_FOOT = 3.048
"""m per foot"""
JOULE_PER_CAL = 4.184
"""Joule per calorie"""
CAL_PER_JOULE = (1 / 4.184)
"""Calories per Joule"""
PRECURSOR_ERROR_PPM_USERPARAM = "precursor_mz_error_ppm"
"""User parameter name for precursor mz error in ppm"""
FRAGMENT_ANNOTATION_USERPARAM = "fragment_annotation"
"""User parameter name for precursor mz error in ppm"""
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyopenms/_python_extras.py | .py | 589 | 23 | class SimpleOpenMSSpectraFactory:
@staticmethod
def getSpectrumAccessOpenMSPtr(exp):
is_cached = False
for i in range(exp.size()):
for dp in exp[i].getDataProcessing():
if dp.metaValueExists("cached_data"):
is_cached = True
for chrom in exp.getChromatograms():
for dp in chrom.getDataProcessing():
if dp.metaValueExists("cached_data"):
is_cached = True
if is_cached:
return SpectrumAccessOpenMSCached( exp.getLoadedFilePath() )
else:
return SpectrumAccessOpenMS( exp )
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/PeakPickerHiRes.py | .py | 2,971 | 94 | import argparse
import pyopenms as pms
import logging
from common import addDataProcessing, writeParamsIfRequested, updateDefaults
def run_peak_picker(input_map, params, out_path):
spec0 = input_map[0]
if pms.PeakTypeEstimator().estimateType(spec0) == \
pms. SpectrumSettings.SpectrumType.PEAKS:
logging.warn("input peak map does not look like profile data")
if any(not s.isSorted() for s in input_map):
raise Exception("Not all spectra are sorted according to m/z")
pp = pms.PeakPickerHiRes()
pp.setParameters(params)
out_map = pms.MSExperiment()
pp.pickExperiment(input_map, out_map)
out_map = addDataProcessing(out_map, params, pms.DataProcessing.ProcessingAction.PEAK_PICKING)
fh = pms.FileHandler()
fh.storeExperiment(out_path, out_map)
def main():
parser = argparse.ArgumentParser(description="PeakPickerHiRes")
parser.add_argument("-in",
action="store",
type=str,
dest="in_",
metavar="input_file",
)
parser.add_argument("-out",
action="store",
type=str,
metavar="output_file",
)
parser.add_argument("-ini",
action="store",
type=str,
metavar="ini_file",
)
parser.add_argument("-dict_ini",
action="store",
type=str,
metavar="python_dict_ini_file",
)
parser.add_argument("-write_ini",
action="store",
type=str,
metavar="ini_file",
)
parser.add_argument("-write_dict_ini",
action="store",
type=str,
metavar="python_dict_ini_file",
)
args = parser.parse_args()
run_mode = args.in_ is not None and args.out is not None\
and (args.ini is not None or args.dict_ini is not None)
write_mode = args.write_ini is not None or args.write_dict_ini is not None
ok = run_mode or write_mode
if not ok:
parser.error("either specify -in, -out and -(dict)ini for running "
"the peakpicker\nor -write(dict)ini for creating std "
"ini file")
defaults = pms.PeakPickerHiRes().getDefaults()
write_requested = writeParamsIfRequested(args, defaults)
if not write_requested:
updateDefaults(args, defaults)
fh = pms.MzMLFile()
fh.setLogType(pms.LogType.CMD)
input_map = pms.MSExperiment()
fh.load(args.in_, input_map)
run_peak_picker(input_map, defaults, args.out)
if __name__ == "__main__":
main()
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/FeatureLinkerUnlabeledQT.py | .py | 4,663 | 153 | import argparse
import pyopenms as pms
from common import addDataProcessing, writeParamsIfRequested, updateDefaults
from collections import Counter
def link(in_files, out_file, keep_subelements, params):
in_types = set(pms.FileHandler.getType(in_) for in_ in in_files)
if in_types == set((pms.Type.CONSENSUSXML,)):
link_features = False
elif in_types == set((pms.Type.FEATUREXML,)):
link_features = True
else:
raise Exception("different kinds of input files")
algorithm_parameters = params.copy("algorithm:", True)
algorithm = pms.FeatureGroupingAlgorithmQT()
algorithm.setParameters(algorithm_parameters)
out_map = pms.ConsensusMap()
fds = out_map.getColumnHeaders()
if link_features:
f = pms.FeatureXMLFile()
maps = []
for i, in_file in enumerate(in_files):
map_ = pms.FeatureMap()
f.load(in_file, map_)
# set filedescriptions
fd = fds.get(i, pms.ColumnHeader())
fd.filename = in_file
fd.size = map_.size()
fd.unique_id = map_.getUniqueId()
fds[i] = fd
maps.append(map_)
out_map.setColumnHeaders(fds)
algorithm.group(maps, out_map)
else:
f = pms.ConsensusXMLFile()
maps = []
for i, in_file in enumerate(in_files):
map_ = pms.ConsensusMap()
f.load(in_file, map_)
maps.append(map_)
algorithm.group(maps, out_map)
if not keep_subelements:
for i in range(len(in_files)):
# set filedescriptions
fd = fds.get(i, pms.ColumnHeader())
fd.filename = in_files[i]
fd.size = maps[i].size()
fd.unique_id = maps[i].getUniqueId()
fds[i] = fd
out_map.setColumnHeaders(fds)
else:
algorithm.transferSubelements(maps, out_map)
out_map.setUniqueIds()
addDataProcessing(out_map, params, pms.DataProcessing.ProcessingAction.FEATURE_GROUPING)
pms.ConsensusXMLFile().store(out_file, out_map)
sizes = []
for feat in out_map:
sizes.append(feat.size())
c = Counter(sizes)
print "Number of consensus features:"
for size, count in c.most_common():
print " of size %2d : %6d" % (size, count)
print " total : %6d" % out_map.size()
def main():
parser = argparse.ArgumentParser(description="FeatureLinkerUnlabeledQT")
parser.add_argument("-in",
action="append",
type=str,
dest="in_",
metavar="input_files",
)
parser.add_argument("-out",
action="store",
type=str,
metavar="output_file",
)
parser.add_argument("-ini",
action="store",
type=str,
metavar="ini_file",
)
parser.add_argument("-dict_ini",
action="store",
type=str,
metavar="python_dict_ini_file",
)
parser.add_argument("-write_ini",
action="store",
type=str,
metavar="ini_file",
)
parser.add_argument("-write_dict_ini",
action="store",
type=str,
metavar="python_dict_ini_file",
)
parser.add_argument("-keep_subelements",
action="store_true",
)
args = parser.parse_args()
def collect(args):
return [f.strip() for arg in args or [] for f in arg.split(",")]
in_files = collect(args.in_)
run_mode = (in_files and args.out) \
and (args.ini is not None or args.dict_ini is not None)
write_mode = args.write_ini is not None or args.write_dict_ini is not None
ok = run_mode or write_mode
if not ok:
parser.error("either specify -in, -out and -(dict)ini for running "
"the feature linker\nor -write(dict)ini for creating std "
"ini file")
defaults = pms.FeatureGroupingAlgorithmQT().getParameters()
write_requested = writeParamsIfRequested(args, defaults)
if not write_requested:
updateDefaults(args, defaults)
link(in_files, args.out, args.keep_subelements, defaults)
if __name__ == "__main__":
main()
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/run_pipeline.sh | .sh | 2,868 | 86 | #!/bin/sh
echo
echo ============================================================
echo PeakPickerHiRes.py
echo ============================================================
echo
python PeakPickerHiRes.py -write_ini pp.ini
python PeakPickerHiRes.py -ini pp.ini -in ../share/OpenMS/examples/peakpicker_tutorial_1_baseline_and_noise_filtered.mzML -out picked_1.mzML
python PeakPickerHiRes.py -ini pp.ini -in ../share/OpenMS/examples/peakpicker_tutorial_2.mzML -out picked_2.mzML
python PeakPickerHiRes.py -ini pp.ini -in ../share/OpenMS/examples/LCMS-centroided.mzML -out picked_3.mzML
echo
ls -lh picked_?.mzML
echo
echo
echo ============================================================
echo FeatureFinderCentroided.py
echo ============================================================
echo
python FeatureFinderCentroided.py -write_ini fd.ini
python FeatureFinderCentroided.py -ini fd.ini -in ../share/OpenMS/examples/LCMS-centroided.mzML -out feat_1.featureXML
python FeatureFinderCentroided.py -ini fd.ini -in ../share/OpenMS/examples/LCMS-centroided.mzML -out feat_2.featureXML
python FeatureFinderCentroided.py -ini fd.ini -in picked_3.mzML -out feat_3.featureXML
echo
ls -lh feat_?.featureXML
echo
echo
echo ============================================================
echo MapAlignerPoseClustering.py
echo ============================================================
echo
python MapAlignerPoseClustering.py -write_ini align.ini
python MapAlignerPoseClustering.py -ini align.ini -in feat_1.featureXML,feat_2.featureXML -out align_1.featureXML,align_2.featureXML -trafo_out trafo_1.transformationXML,trafo_2.transformationXML
echo
ls -lh align_?.featureXML trafo_?.transformationXML
echo
echo
echo ============================================================
echo FeatureLinkerUnlabeledQT
echo ============================================================
echo
python FeatureLinkerUnlabeledQT.py -write_ini linker.ini
python FeatureLinkerUnlabeledQT.py -ini linker.ini -in align_1.featureXML,align_2.featureXML -out cons.consensusXML
echo
ls -lh cons.consensusXML
echo
echo
echo ============================================================
echo IDMapper
echo ============================================================
echo
python IDMapper.py -write_ini mapper.ini
python IDMapper.py -ini mapper.ini -in align_1.featureXML -out cons_mapped.consensusXML -id /usr/share/OpenMS/examples/BSA/BSA1_OMSSA.idXML
python IDMapper.py -ini mapper.ini -in cons.consensusXML -out cons_mapped.consensusXML -id /usr/share/OpenMS/examples/BSA/BSA1_OMSSA.idXML
echo
ls -lh cons_mapped.consensusXML
echo
rm pp.ini
rm picked_1.mzML
rm picked_2.mzML
rm fd.ini
rm feat_1.featureXML
rm feat_2.featureXML
rm feat_3.featureXML
rm align.ini
rm align_1.featureXML
rm align_2.featureXML
rm trafo_1.transformationXML
rm trafo_2.transformationXML
rm linker.ini
rm cons.consensusXML
| Shell |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/common.py | .py | 1,752 | 57 | import sys
import os.path
import pyopenms as pms
import pprint
def addDataProcessing(obj, params, action):
if isinstance(obj, pms.MSExperiment):
result = pms.MSExperiment()
for spec in obj:
spec = _addDataProcessing(spec, params, action)
result.addSpectrum(spec)
else:
result = _addDataProcessing(obj, params, action)
return result
def _addDataProcessing(item, params, action):
dp = item.getDataProcessing()
p = pms.DataProcessing()
p.setProcessingActions(set([action]))
sw = p.getSoftware()
sw.setName(os.path.basename(sys.argv[0]))
sw.setVersion(pms.VersionInfo.getVersion())
p.setSoftware(sw)
p.setCompletionTime(pms.DateTime.now()) # TODO: check if this is the reason for the many data processing entries
for k, v in params.asDict().items():
p.setMetaValue(b"parameter: "+k, v)
dp.append(p)
item.setDataProcessing(dp)
return item
def writeParamsIfRequested(args, params):
if args.write_dict_ini or args.write_ini:
if args.write_dict_ini:
with open(args.write_dict_ini, "w") as fp:
pprint.pprint(params.asDict(), stream=fp)
if args.write_ini:
fh = pms.ParamXMLFile()
fh.store(args.write_ini, params)
return True
return False
def updateDefaults(args, defaults):
if args.ini:
param = pms.Param()
fh = pms.ParamXMLFile()
fh.load(args.ini, param)
defaults.update(param)
elif args.dict_ini:
with open(args.dict_ini, "r") as fp:
try:
dd = eval(fp.read())
except:
raise Exception("could not parse %s" % args.dict_ini)
defaults.update(dd)
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/FileConverter.py | .py | 363 | 14 | # import pyopenms
def main():
import optparse
# in: file
in_formats = "mzData,mzXML,mzML,DTA,DTA2D,mgf,featureXML,consensusXML,"\
"ms2,fid,tsv,peplist,kroenik,edta".split()
# out: file
out_formats = "mzData,mzXML,mzML,DTA2D,mgf,featureXML,"\
"consensusXML".split(",")
if __name__ == "__main__":
main()
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/OpenSwathFeatureXMLToTSV.py | .py | 1,635 | 62 |
import pyopenms
def convert_to_row(first, targ, run_id, keys, filename):
peptide_ref = first.getMetaValue("PeptideRef")
pep = targ.getPeptideByRef(peptide_ref)
full_peptide_name = "NA"
if (pep.metaValueExists("full_peptide_name")):
full_peptide_name = pep.getMetaValue("full_peptide_name")
decoy = "0"
peptidetransitions = [t for t in targ.getTransitions() if t.getPeptideRef() == peptide_ref]
if len(peptidetransitions) > 0:
if peptidetransitions[0].getDecoyTransitionType() == pyopenms.DecoyTransitionType().DECOY:
decoy = "1"
elif peptidetransitions[0].getDecoyTransitionType() == pyopenms.DecoyTransitionType().TARGET:
decoy = "0"
protein_name = "NA"
if len(pep.protein_refs) > 0:
protein_name = pep.protein_refs[0]
row = [
first.getMetaValue("PeptideRef"),
run_id,
filename,
first.getRT(),
first.getMetaValue("PrecursorMZ"),
first.getUniqueId(),
pep.sequence,
full_peptide_name,
pep.getChargeState(),
first.getMetaValue("PrecursorMZ"),
first.getIntensity(),
protein_name,
decoy
]
for k in keys:
row.append(first.getMetaValue(k))
return row
def get_header(features):
keys = []
features[0].getKeys(keys)
header = [
"transition_group_id",
"run_id",
"filename",
"RT",
"id",
"Sequence" ,
"FullPeptideName",
"Charge",
"m/z",
"Intensity",
"ProteinName",
"decoy"]
header.extend(keys)
return header
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/MRMTransitionGroupPicker.py | .py | 3,349 | 93 |
import sys
import pyopenms
def getTransitionGroup(exp, targeted, key, trgr_ids, chrom_map):
r = pyopenms.MRMTransitionGroupCP()
for tr in trgr_ids:
transition = targeted.getTransitions()[tr]
chrom_idx = chrom_map[ transition.getNativeID() ]
chrom = exp.getChromatograms()[ chrom_idx ]
chrom.setMetaValue("product_mz", transition.getProductMZ() )
chrom.setMetaValue("precursor_mz", transition.getPrecursorMZ() )
r.addTransition( transition, transition.getNativeID() )
r.addChromatogram( chrom, chrom.getNativeID() )
return r
def algorithm(exp, targeted, picker):
output = pyopenms.FeatureMap()
chrom_map = {}
pepmap = {}
trmap = {}
for i, chrom in enumerate(exp.getChromatograms()):
chrom_map[ chrom.getNativeID() ] = i
for i, pep in enumerate(targeted.getPeptides() ):
pepmap[ pep.id ] = i
for i, tr in enumerate(targeted.getTransitions() ):
tmp = trmap.get( tr.getPeptideRef() , [])
tmp.append( i )
trmap[ tr.getPeptideRef() ] = tmp
for key, value in trmap.iteritems():
print key, value
transition_group = getTransitionGroup(exp, targeted, key, value, chrom_map)
picker.pickTransitionGroup(transition_group);
for mrmfeature in transition_group.getFeatures():
features = mrmfeature.getFeatures()
for f in features:
# TODO
# f.getConvexHulls().clear()
f.ensureUniqueId()
mrmfeature.setSubordinates(features) # add all the subfeatures as subordinates
output.push_back(mrmfeature)
return output
def main(options):
out = options.outfile
chromat_in = options.infile
traml_in = options.traml_in
pp = pyopenms.MRMTransitionGroupPicker()
pp_params = pp.getDefaults();
pp_params.setValue("PeakPickerChromatogram:remove_overlapping_peaks", options.remove_overlapping_peaks, '')
pp_params.setValue("PeakPickerChromatogram:method", options.method, '')
pp.setParameters(pp_params);
chromatograms = pyopenms.MSExperiment()
fh = pyopenms.FileHandler()
fh.loadExperiment(chromat_in, chromatograms)
targeted = pyopenms.TargetedExperiment();
tramlfile = pyopenms.TraMLFile();
tramlfile.load(traml_in, targeted);
output = algorithm(chromatograms, targeted, pp)
pyopenms.FeatureXMLFile().store(out, output);
def handle_args():
import argparse
usage = ""
usage += "\nMRMTransitionGroupPicker picks transition groups in measured chromatograms (mzML)"
parser = argparse.ArgumentParser(description = usage )
parser.add_argument('--in', dest="infile", help = 'An input file containing chromatograms')
parser.add_argument("--tr", dest="traml_in", help="TraML input file containt the transitions")
parser.add_argument("--out", dest="outfile", help="Output file with annotated chromatograms")
parser.add_argument("--remove_overlapping_peaks", dest="remove_overlapping_peaks", default="false", help="true/false", metavar='0.1', type=str)
parser.add_argument("--method", dest="method", default="legacy", help="legacy/corrected", metavar='0.1', type=str)
args = parser.parse_args(sys.argv[1:])
return args
if __name__ == '__main__':
options = handle_args()
main(options)
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/pyTOPPExample.py | .py | 2,095 | 72 | import CTDopts
import sys
from CTDopts.CTDopts import CTDModel, parse_cl_directives
import pyopenms as pms
import logging
from common import addDataProcessing
from CTDsupport import *
def main():
# register command line arguments
model = CTDModel(
name='NameOfThePyTOPPTool', # required
version='1.0', # required
description='This is an example tool how to write pyTOPP tools compatible with the OpenMS workflow ecosystem.',
manual='RTF',
docurl='http://dummy.url/docurl.html',
category='Example',
executableName='exampletool',
executablePath='/path/to/exec/exampletool-1.0/exampletool'
)
# Register in / out etc. with CTDModel
model.add(
'input',
required=True,
type='input-file',
is_list=False,
file_formats=['mzML'], # filename restrictions
description='Input file'
)
model.add(
'output',
required=True,
type='output-file',
is_list=False,
file_formats=['mzML'], # filename restrictions
description='Output file'
)
defaults = pms.PeakPickerHiRes().getDefaults()
# expose algorithm parameters in command line options
addParamToCTDopts(defaults, model)
# parse command line
# if -write_ini is provided, store model in CTD file, exit with error code 0
# if -ini is provided, load CTD file into defaults Param object and return new model with paraneters set as defaults
arg_dict, openms_params = parseCTDCommandLine(sys.argv, model, defaults);
# data processing
fh = pms.MzMLFile()
fh.setLogType(pms.LogType.CMD)
input_map = pms.MSExperiment()
fh.load(arg_dict["input"], input_map)
pp = pms.PeakPickerHiRes()
pp.setParameters(openms_params)
out_map = pms.MSExperiment()
pp.pickExperiment(input_map, out_map)
out_map = addDataProcessing(out_map, openms_params, pms.DataProcessing.ProcessingAction.PEAK_PICKING)
fh = pms.FileHandler()
fh.storeExperiment(arg_dict["output"], out_map)
if __name__ == "__main__":
main()
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/MRMTransitionGroupScorer.py | .py | 5,020 | 127 |
import sys
import pyopenms
def getTransitionGroup(exp, targeted, key, trgr_ids, chrom_map):
r = pyopenms.LightMRMTransitionGroupCP()
r.setTransitionGroupID(key)
for tr in trgr_ids:
transition = targeted.getTransitions()[tr]
chrom_idx = chrom_map[ transition.getNativeID() ]
chrom = exp.getChromatograms()[ chrom_idx ]
chrom.setMetaValue("product_mz", transition.getProductMZ() )
chrom.setMetaValue("precursor_mz", transition.getPrecursorMZ() )
r.addTransition( transition, transition.getNativeID() )
r.addChromatogram( chrom, chrom.getNativeID() )
return r
def algorithm(exp, targeted, picker, scorer, trafo):
output = pyopenms.FeatureMap()
scorer.prepareProteinPeptideMaps_(targeted)
chrom_map = {}
pepmap = {}
trmap = {}
for i, chrom in enumerate(exp.getChromatograms()):
chrom_map[ chrom.getNativeID() ] = i
for i, pep in enumerate(targeted.getCompounds() ):
pepmap[ pep.id ] = i
for i, tr in enumerate(targeted.getTransitions() ):
tmp = trmap.get( tr.getPeptideRef() , [])
tmp.append( i )
trmap[ tr.getPeptideRef() ] = tmp
swath_maps_dummy = []
for key, value in trmap.iteritems():
try:
transition_group = getTransitionGroup(exp, targeted, key, value, chrom_map)
except Exception:
print "Skip ", key, value
continue
picker.pickTransitionGroup(transition_group);
scorer.scorePeakgroups(transition_group, trafo, swath_maps_dummy, output, False);
return output
def main(options):
out = options.outfile
chromat_in = options.infile
traml_in = options.traml_in
trafo_in = options.trafo_in
pp = pyopenms.MRMTransitionGroupPicker()
metabolomics = False
# this is an important weight for RT-deviation -- the larger the value, the less importance will be given to exact RT matches
# for proteomics data it tends to be a good idea to set it to the length of
# the RT space (e.g. for 100 second RT space, set it to 100)
rt_normalization_factor = 100.0
pp_params = pp.getDefaults();
pp_params.setValue("PeakPickerChromatogram:remove_overlapping_peaks", options.remove_overlapping_peaks, '')
pp_params.setValue("PeakPickerChromatogram:method", options.method, '')
if (metabolomics):
# Need to change those for metabolomics and very short peaks!
pp_params.setValue("PeakPickerChromatogram:signal_to_noise", 0.01, '')
pp_params.setValue("PeakPickerChromatogram:peak_width", 0.1, '')
pp_params.setValue("PeakPickerChromatogram:gauss_width", 0.1, '')
pp_params.setValue("resample_boundary", 0.05, '')
pp_params.setValue("compute_peak_quality", "true", '')
pp.setParameters(pp_params)
scorer = pyopenms.MRMFeatureFinderScoring()
scoring_params = scorer.getDefaults();
# Only report the top 5 features
scoring_params.setValue("stop_report_after_feature", 5, '')
scoring_params.setValue("rt_normalization_factor", rt_normalization_factor, '')
scorer.setParameters(scoring_params);
chromatograms = pyopenms.MSExperiment()
fh = pyopenms.FileHandler()
fh.loadExperiment(chromat_in, chromatograms)
targeted = pyopenms.TargetedExperiment();
tramlfile = pyopenms.TraMLFile();
tramlfile.load(traml_in, targeted);
trafoxml = pyopenms.TransformationXMLFile()
trafo = pyopenms.TransformationDescription()
if trafo_in is not None:
model_params = pyopenms.Param()
model_params.setValue("symmetric_regression", "false", "", [])
model_type = "linear"
trafoxml.load(trafo_in, trafo, True)
trafo.fitModel(model_type, model_params);
light_targeted = pyopenms.LightTargetedExperiment();
pyopenms.OpenSwathDataAccessHelper().convertTargetedExp(targeted, light_targeted)
output = algorithm(chromatograms, light_targeted, pp, scorer, trafo)
pyopenms.FeatureXMLFile().store(out, output);
def handle_args():
import argparse
usage = ""
usage += "\nMRMTransitionGroupScorer picks transition groups in measured chromatograms (mzML) and scores them"
parser = argparse.ArgumentParser(description = usage )
parser.add_argument('--in', dest="infile", help = 'An input file containing chromatograms')
parser.add_argument("--tr", dest="traml_in", help="TraML input file containt the transitions")
parser.add_argument("--trafo", dest="trafo_in", help="Trafo input file")
parser.add_argument("--out", dest="outfile", help="Output file with annotated chromatograms")
parser.add_argument("--remove_overlapping_peaks", dest="remove_overlapping_peaks", default="false", help="true/false", metavar='0.1', type=str)
parser.add_argument("--method", dest="method", default="legacy", help="legacy/corrected", metavar='0.1', type=str)
args = parser.parse_args(sys.argv[1:])
return args
if __name__ == '__main__':
options = handle_args()
main(options)
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/MRMMapper.py | .py | 4,562 | 106 | import copy, sys
import pyopenms
"""
python pyTOPP/MRMMapper.py --in ../source/TEST/TOPP/MRMMapping_input.chrom.mzML \
--tr ../source/TEST/TOPP/MRMMapping_input.TraML --out MRMMapper.tmp.out \
&& diff MRMMapper.tmp.out ../source/TEST/TOPP/MRMMapping_output.chrom.mzML
"""
def algorithm(chromatogram_map, targeted, precursor_tolerance, product_tolerance, allow_unmapped=True, allow_double_mappings=False):
output = copy.copy(chromatogram_map)
output.clear(False);
empty_chromats = []
output.setChromatograms(empty_chromats);
notmapped = 0
for chrom in chromatogram_map.getChromatograms():
mapped_already = False
for transition in targeted.getTransitions():
if (abs(chrom.getPrecursor().getMZ() - transition.getPrecursorMZ()) < precursor_tolerance and
abs(chrom.getProduct().getMZ() - transition.getProductMZ()) < product_tolerance):
if mapped_already:
this_peptide = targeted.getPeptideByRef(transition.getPeptideRef() ).sequence
other_peptide = chrom.getPrecursor().getMetaValue("peptide_sequence")
print "Found mapping of", chrom.getPrecursor().getMZ(), "/", chrom.getProduct().getMZ(), "to", transition.getPrecursorMZ(), "/",transition.getProductMZ()
print "Of peptide", this_peptide
print "But the chromatogram is already mapped to", other_peptide
if not allow_double_mappings: raise Exception("Cannot map twice")
mapped_already = True
precursor = chrom.getPrecursor();
peptide = targeted.getPeptideByRef(transition.getPeptideRef() )
precursor.setMetaValue("peptide_sequence", peptide.sequence)
chrom.setPrecursor(precursor)
chrom.setNativeID(transition.getNativeID())
if not mapped_already:
notmapped += 1
print "Did not find a mapping for chromatogram", chrom.getNativeID()
if not allow_unmapped: raise Exception("No mapping")
else:
output.addChromatogram(chrom)
if notmapped > 0:
print "Could not find mapping for", notmapped, "chromatogram(s)"
dp = pyopenms.DataProcessing()
# dp.setProcessingActions(ProcessingAction:::FORMAT_CONVERSION)
pa = pyopenms.DataProcessing().ProcessingAction().FORMAT_CONVERSION
dp.setProcessingActions(set([pa]))
chromatograms = output.getChromatograms();
for chrom in chromatograms:
this_dp = chrom.getDataProcessing()
this_dp.append(dp)
chrom.setDataProcessing(this_dp)
output.setChromatograms(chromatograms);
return output
def main(options):
precursor_tolerance = options.precursor_tolerance
product_tolerance = options.product_tolerance
out = options.outfile
chromat_in = options.infile
traml_in = options.traml_in
# precursor_tolerance = 0.05
# product_tolerance = 0.05
# out = "/tmp/out.mzML"
# chromat_in = "../source/TEST/TOPP/MRMMapping_input.chrom.mzML"
# traml_in = "../source/TEST/TOPP/MRMMapping_input.TraML"
ff = pyopenms.MRMFeatureFinderScoring()
chromatogram_map = pyopenms.MSExperiment()
fh = pyopenms.FileHandler()
fh.loadExperiment(chromat_in, chromatogram_map)
targeted = pyopenms.TargetedExperiment();
tramlfile = pyopenms.TraMLFile();
tramlfile.load(traml_in, targeted);
output = algorithm(chromatogram_map, targeted, precursor_tolerance, product_tolerance)
pyopenms.MzMLFile().store(out, output);
def handle_args():
import argparse
usage = ""
usage += "\nMRMMapper maps measured chromatograms (mzML) and the transitions used (TraML)"
parser = argparse.ArgumentParser(description = usage )
parser.add_argument('--in', dest="infile", help = 'An input file containing chromatograms')
parser.add_argument("--tr", dest="traml_in", help="TraML input file containt the transitions")
parser.add_argument("--out", dest="outfile", help="Output file with annotated chromatograms")
parser.add_argument("--precursor_tolerance", dest="precursor_tolerance", default=0.1, help="Precursor tolerance when mapping (in Th)", metavar='0.1', type=float)
parser.add_argument("--product_tolerance", dest="product_tolerance", default=0.1, help="Product tolerance when mapping (in Th)", metavar='0.1', type=float)
args = parser.parse_args(sys.argv[1:])
return args
if __name__ == '__main__':
options = handle_args()
main(options)
| Python |
3D | OpenMS/OpenMS | src/pyOpenMS/pyTOPP/IDMapper.py | .py | 5,044 | 160 | import argparse
import pyopenms as pms
from common import addDataProcessing, writeParamsIfRequested, updateDefaults
def id_mapper(in_file, id_file, out_file, params, use_centroid_rt,
use_centroid_mz, use_subelements ):
in_type = pms.FileHandler.getType(in_file)
protein_ids = []
peptide_ids = []
pms.IdXMLFile().load(id_file, protein_ids, peptide_ids)
mapper = pms.IDMapper()
mapper.setParameters(params)
if in_type == pms.Type.CONSENSUSXML:
file_ = pms.ConsensusXMLFile()
map_ = pms.ConsensusMap()
file_.load(in_file, map_)
mapper.annotate(map_, peptide_ids, protein_ids, use_subelements)
addDataProcessing(map_, params, pms.DataProcessing.ProcessingAction.IDENTIFICATION_MAPPING)
file_.store(out_file, map_)
elif in_type == pms.Type.FEATUREXML:
file_ = pms.FeatureXMLFile()
map_ = pms.FeatureMap()
file_.load(in_file, map_)
mapper.annotate(map_, peptide_ids, protein_ids, use_centroid_rt,
use_centroid_mz)
addDataProcessing(map_, params, pms.DataProcessing.ProcessingAction.IDENTIFICATION_MAPPING)
file_.store(out_file, map_)
else:
raise Exception("invalid input file format")
def main():
parser = argparse.ArgumentParser(description="IDMapper")
parser.add_argument("-id",
action="store",
type=str,
dest="id_",
metavar="id_file",
)
parser.add_argument("-in",
action="store",
type=str,
dest="in_",
metavar="input_file",
)
parser.add_argument("-out",
action="store",
type=str,
metavar="output_file",
)
parser.add_argument("-ini",
action="store",
type=str,
metavar="ini_file",
)
parser.add_argument("-dict_ini",
action="store",
type=str,
metavar="python_dict_ini_file",
)
parser.add_argument("-write_ini",
action="store",
type=str,
metavar="ini_file",
)
parser.add_argument("-write_dict_ini",
action="store",
type=str,
metavar="python_dict_ini_file",
)
parser.add_argument("-mz_tolerance",
action="store",
type=float)
parser.add_argument("-rt_tolerance",
action="store",
type=float)
parser.add_argument("-mz_measure",
action="store",
type=str)
parser.add_argument("-mz_reference",
action="store",
type=str)
parser.add_argument("-ignore_charge",
action="store_true")
parser.add_argument("-feature:use_centroid_rt",
action="store_true")
parser.add_argument("-feature:use_centroid_mz",
action="store_true")
parser.add_argument("-consensusfeature:use_subelements",
action="store_true")
args = parser.parse_args()
run_mode = (args.in_ and args.id_ and args.out) \
and (args.ini is not None or args.dict_ini is not None)
write_mode = args.write_ini is not None or args.write_dict_ini is not None
ok = run_mode or write_mode
if not ok:
parser.error("either specify -id, -in, -out and -(dict)ini for running "
"the id mapper\nor -write(dict)ini for creating std "
"ini file")
defaults = pms.IDMapper().getParameters()
write_requested = writeParamsIfRequested(args, defaults)
if not write_requested:
updateDefaults(args, defaults)
dd = defaults.asDict()
dd["ignore_charge"] = "true" if args.ignore_charge else "false"
for att in ["mz_tolerance", "rt_tolerance", "mz_measure",
"mz_reference"]:
value = getattr(args, att)
if value is not None:
dd[att] = value
defaults.update(dd)
feature_use_centroid_rt = getattr(args, "feature:use_centroid_rt")
feature_use_centroid_mz = getattr(args, "feature:use_centroid_mz")
consenususfeature_use_subelements = getattr(args,
"consensusfeature:use_subelements")
id_mapper(args.in_, args.id_, args.out, defaults,
feature_use_centroid_rt,
feature_use_centroid_mz,
consenususfeature_use_subelements
)
if __name__ == "__main__":
main()
| Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.