Debian Codegraph @

avogadro/qtplugins/openbabel/openbabel.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "openbabel.h"
7
8 #include "conformersearchdialog.h"
9 #include "obcharges.h"
10 #include "obfileformat.h"
11 #include "obforcefielddialog.h"
12 #include "obprocess.h"
13
14 #include <avogadro/calc/chargemanager.h>
15 #include <avogadro/io/fileformatmanager.h>
16
17 #include <avogadro/qtgui/molecule.h>
18 #include <avogadro/qtgui/rwmolecule.h>
19
20 #include <QtCore/QCoreApplication>
21 #include <QtCore/QDebug>
22 #include <QtCore/QSettings>
23 #include <QtCore/QTimer>
24
25 #include <QAction>
26 #include <QtWidgets/QFileDialog>
27 #include <QtWidgets/QInputDialog>
28 #include <QtWidgets/QMessageBox>
29 #include <QtWidgets/QProgressDialog>
30
31 #include <QRegularExpression>
32
33 #include <string>
34
35 using Avogadro::QtGui::Molecule;
36 using namespace std::string_literals;
37
38 namespace Avogadro::QtPlugins {
39
40 OpenBabel::OpenBabel(QObject* p)
41 : ExtensionPlugin(p), m_molecule(nullptr), m_process(new OBProcess(this)),
42 m_readFormatsPending(true), m_writeFormatsPending(true),
43 m_defaultFormat("cml"), m_progress(nullptr),
44 m_conformerSearchDialog(nullptr)
45 {
46 auto* action = new QAction(this);
47 action->setEnabled(true);
48 action->setText(tr("Optimize Geometry"));
49 connect(action, SIGNAL(triggered()), SLOT(onOptimizeGeometry()));
50 m_actions.push_back(action);
51
52 action = new QAction(this);
53 action->setEnabled(true);
54 action->setText(tr("Configure Force Field…"));
55 connect(action, SIGNAL(triggered()), SLOT(onConfigureGeometryOptimization()));
56 m_actions.push_back(action);
57
58 action = new QAction(this);
59 action->setEnabled(true);
60 action->setText(tr("Conformer Search…"));
61 connect(action, SIGNAL(triggered()), SLOT(onConfigureConformerSearch()));
62 m_actions.push_back(action);
63
64 action = new QAction(this);
65 action->setEnabled(true);
66 action->setText(tr("Perceive Bonds"));
67 connect(action, SIGNAL(triggered()), SLOT(onPerceiveBonds()));
68 m_actions.push_back(action);
69
70 action = new QAction(this);
71 action->setEnabled(true);
72 action->setText(tr("Add Hydrogens"));
73 connect(action, SIGNAL(triggered()), SLOT(onAddHydrogens()));
74 m_actions.push_back(action);
75
76 action = new QAction(this);
77 action->setEnabled(true);
78 action->setText(tr("Add Hydrogens for pH…"));
79 connect(action, SIGNAL(triggered()), SLOT(onAddHydrogensPh()));
80 m_actions.push_back(action);
81
82 action = new QAction(this);
83 action->setEnabled(true);
84 action->setText(tr("Remove Hydrogens"));
85 connect(action, SIGNAL(triggered()), SLOT(onRemoveHydrogens()));
86 m_actions.push_back(action);
87
88 refreshReadFormats();
89 refreshWriteFormats();
90 refreshForceFields();
91 refreshCharges();
92
93 QString info = openBabelInfo();
94 if (info.isEmpty()) {
95 qWarning() << tr("%1 not found! Disabling Open Babel plugin actions.")
96 .arg(OBProcess().obabelExecutable());
97 foreach (QAction* a, m_actions)
98 a->setEnabled(false);
99 } else {
100 qDebug() << OBProcess().obabelExecutable() << " found: " << info;
101 }
102 }
103
104 OpenBabel::~OpenBabel() {}
105
106 QList<QAction*> OpenBabel::actions() const
107 {
108 return m_actions;
109 }
110
111 QStringList OpenBabel::menuPath(QAction*) const
112 {
113 return QStringList() << tr("&Extensions") << tr("&Open Babel");
114 }
115
116 QList<Io::FileFormat*> OpenBabel::fileFormats() const
117 {
118 // Return empty list if not ready yet, and print a warning.
119 if (m_readFormatsPending || m_writeFormatsPending) {
120 qDebug() << tr("The Open Babel file formats are not ready to be added.");
121 return QList<Io::FileFormat*>();
122 }
123
124 QList<Io::FileFormat*> result;
125
126 std::string mapDesc;
127 std::string fname;
128 std::string fidentifier;
129 std::string fdescription;
130 std::string fspecificationUrl(
131 "https://openbabel.org/docs/FileFormats/Overview.html");
132 // http://openbabel.org/wiki/Category:Formats
133 std::vector<std::string> fexts;
134 std::vector<std::string> fmime;
135
136 // Simple lambda to replace toSet in QList
137 auto toSet = [&](const QList<QString>& list) {
138 return QSet<QString>(list.begin(), list.end());
139 };
140 QSet<QString> formatDescriptions;
141 formatDescriptions.unite(toSet(m_readFormats.uniqueKeys()));
142 formatDescriptions.unite(toSet(m_writeFormats.uniqueKeys()));
143
144 QSet<QString> formatExtensions;
145
146 // These can only be read directly from file:
147 QList<QString> multifileFormatDescriptions;
148 multifileFormatDescriptions << "VASP format";
149 multifileFormatDescriptions << "Gaussian Output"; // Issue #571
150 multifileFormatDescriptions << "Generic Output file format"; // #571 and 827
151
152 foreach (const QString& qdesc, formatDescriptions) {
153 mapDesc = qdesc.toStdString();
154 fname = mapDesc;
155 fidentifier = "OpenBabel: "s + mapDesc;
156 fdescription = mapDesc;
157 fexts.clear();
158 fmime.clear();
159 bool fileOnly = multifileFormatDescriptions.contains(qdesc);
160
161 formatExtensions.clear();
162 Io::FileFormat::Operations rw = Io::FileFormat::None;
163
164 if (m_readFormats.contains(qdesc)) {
165 formatExtensions.unite(toSet(m_readFormats.values(qdesc)));
166 rw |= Io::FileFormat::Read;
167 }
168 if (m_writeFormats.contains(qdesc)) {
169 formatExtensions.unite(toSet(m_writeFormats.values(qdesc)));
170 rw |= Io::FileFormat::Write;
171 }
172
173 foreach (const QString& ext, formatExtensions)
174 fexts.push_back(ext.toStdString());
175
176 auto* fmt =
177 new OBFileFormat(fname, fidentifier, fdescription, fspecificationUrl,
178 fexts, fmime, m_defaultFormat, fileOnly);
179
180 fmt->setReadWriteFlags(rw);
181 result.append(fmt);
182 }
183
184 qDebug() << "Open Babel formats ready: " << result.size();
185
186 return result;
187 }
188
189 QString OpenBabel::openBabelInfo() const
190 {
191 OBProcess proc;
192 QString version = proc.version();
193 if (version.isEmpty())
194 return QString();
195 return QString("%1: %2").arg(proc.obabelExecutable(), version);
196 }
197
198 void OpenBabel::setMolecule(QtGui::Molecule* mol)
199 {
200 if (mol != m_molecule)
201 m_molecule = mol;
202 }
203
204 bool OpenBabel::readMolecule(QtGui::Molecule& mol)
205 {
206 m_progress->setLabelText(tr("Loading molecule from Open Babel…"));
207
208 bool result = false;
209
210 if (m_moleculeQueue.isEmpty()) {
211 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
212 tr("An internal error occurred: "
213 "OpenBabel::readMolecule called, but no obabel "
214 "output is available to parse!"),
215 QMessageBox::Ok);
216 } else {
217 QByteArray output = m_moleculeQueue.takeFirst();
218 // Empty output means openbabel crashed, etc.
219 if (output.isEmpty()) {
220 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
221 tr("An error occurred while running Open Babel "
222 "(%1).")
223 .arg(m_process->obabelExecutable()),
224 QMessageBox::Ok);
225 } else {
226 result = Io::FileFormatManager::instance().readString(
227 mol, output.constData(), m_defaultFormat);
228 if (!result) {
229 qWarning() << "Error parsing OpenBabel output:\n" << output;
230 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
231 tr("Error parsing openbabel output."),
232 QMessageBox::Ok);
233 }
234 }
235 }
236
237 m_progress->reset();
238 return result;
239 }
240
241 void OpenBabel::refreshReadFormats()
242 {
243 // No need to check if the member process is in use -- we use a temporary
244 // process for the refresh methods.
245 auto* proc = new OBProcess(this);
246
247 connect(proc, SIGNAL(queryReadFormatsFinished(QMultiMap<QString, QString>)),
248 SLOT(handleReadFormatUpdate(QMultiMap<QString, QString>)));
249
250 proc->queryReadFormats();
251 }
252
253 void OpenBabel::handleReadFormatUpdate(const QMultiMap<QString, QString>& fmts)
254 {
255 m_readFormatsPending = false;
256
257 auto* proc = qobject_cast<OBProcess*>(sender());
258 if (proc)
259 proc->deleteLater();
260
261 m_readFormats = fmts;
262
263 // Emit a signal indicating the file formats are ready if read and write
264 // formats have both returned their results.
265 if (!m_readFormatsPending && !m_writeFormatsPending) {
266 // Update the default format if cjson is available
267 if (m_readFormats.contains("Chemical JSON") &&
268 m_writeFormats.contains("Chemical JSON")) {
269 m_defaultFormat = "cjson";
270
271 qDebug() << "Setting default format to " << m_defaultFormat.c_str();
272 }
273
274 emit fileFormatsReady();
275 }
276 }
277
278 void OpenBabel::refreshWriteFormats()
279 {
280 // No need to check if the member process is in use -- we use a temporary
281 // process for the refresh methods.
282 auto* proc = new OBProcess(this);
283
284 connect(proc, SIGNAL(queryWriteFormatsFinished(QMultiMap<QString, QString>)),
285 SLOT(handleWriteFormatUpdate(QMultiMap<QString, QString>)));
286
287 proc->queryWriteFormats();
288 }
289
290 void OpenBabel::handleWriteFormatUpdate(const QMultiMap<QString, QString>& fmts)
291 {
292 m_writeFormatsPending = false;
293
294 auto* proc = qobject_cast<OBProcess*>(sender());
295 if (proc)
296 proc->deleteLater();
297
298 m_writeFormats = fmts;
299
300 // Emit a signal indicating the file formats are ready if read and write
301 // formats have both returned their results.
302 if (!m_readFormatsPending && !m_writeFormatsPending) {
303 emit fileFormatsReady();
304
305 // Update the default format if cjson is available
306 if (m_readFormats.contains("Chemical JSON") &&
307 m_writeFormats.contains("Chemical JSON")) {
308 m_defaultFormat = "cjson";
309 qDebug() << "Setting default format to cjson.";
310 }
311 }
312 }
313
314 void OpenBabel::refreshForceFields()
315 {
316 // No need to check if the member process is in use -- we use a temporary
317 // process for the refresh methods.
318 auto* proc = new OBProcess(this);
319
320 connect(proc, SIGNAL(queryForceFieldsFinished(QMultiMap<QString, QString>)),
321 SLOT(handleForceFieldsUpdate(QMultiMap<QString, QString>)));
322
323 proc->queryForceFields();
324 }
325
326 void OpenBabel::handleForceFieldsUpdate(
327 const QMultiMap<QString, QString>& ffMap)
328 {
329 auto* proc = qobject_cast<OBProcess*>(sender());
330 if (proc)
331 proc->deleteLater();
332
333 m_forceFields = ffMap;
334 }
335
336 void OpenBabel::refreshCharges()
337 {
338 // No need to check if the member process is in use -- we use a temporary
339 // process for the refresh methods.
340 auto* proc = new OBProcess(this);
341
342 connect(proc, SIGNAL(queryChargesFinished(QMultiMap<QString, QString>)),
343 SLOT(handleChargesUpdate(QMultiMap<QString, QString>)));
344
345 proc->queryCharges();
346 }
347
348 void OpenBabel::handleChargesUpdate(
349 const QMultiMap<QString, QString>& chargeMap)
350 {
351 auto* proc = qobject_cast<OBProcess*>(sender());
352 if (proc)
353 proc->deleteLater();
354
355 m_charges = chargeMap;
356 // register the charge models
357 foreach (const QString& key, m_charges.keys()) {
358 // we're only picking a few select models for now
359 if (key == "eem" || key == "eem2015ba" || key == "eqeq" ||
360 key == "gasteiger" || key == "mmff94") {
361 auto* model = new OBCharges(key.toStdString());
362 Calc::ChargeManager::instance().registerModel(model);
363 }
364 }
365 }
366
367 void OpenBabel::onConfigureGeometryOptimization()
368 {
369 // If the force field map is empty, there is probably a problem with the
370 // obabel executable. Warn the user and return.
371 if (m_forceFields.isEmpty()) {
372 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
373 tr("An error occurred while retrieving the list of "
374 "supported forcefields. (using '%1').")
375 .arg(m_process->obabelExecutable()),
376 QMessageBox::Ok);
377 return;
378 }
379
380 QSettings settings;
381 QStringList options =
382 settings.value("openbabel/optimizeGeometry/lastOptions").toStringList();
383
384 options = OBForceFieldDialog::prompt(qobject_cast<QWidget*>(parent()),
385 m_forceFields.keys(), options,
386 autoDetectForceField());
387
388 // User cancel
389 if (options.isEmpty())
390 return;
391
392 settings.setValue("openbabel/optimizeGeometry/lastOptions", options);
393 }
394
395 void OpenBabel::onConfigureConformerSearch()
396 {
397 // If the force field map is empty, there is probably a problem with the
398 // obabel executable. Warn the user and return.
399 if (m_forceFields.isEmpty()) {
400 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
401 tr("An error occurred while retrieving the list of "
402 "supported forcefields. (using '%1').")
403 .arg(m_process->obabelExecutable()),
404 QMessageBox::Ok);
405 return;
406 }
407
408 QSettings settings;
409 QStringList options =
410 settings.value("openbabel/conformerSearch/lastOptions").toStringList();
411
412 if (m_conformerSearchDialog == nullptr) {
413 m_conformerSearchDialog =
414 new ConformerSearchDialog(qobject_cast<QWidget*>(parent()));
415 connect(m_conformerSearchDialog, SIGNAL(accepted()), this,
416 SLOT(onGenerateConformers()));
417 }
418 // todo set options from last run
419 m_conformerSearchDialog->show();
420 m_conformerSearchDialog->raise();
421 m_conformerSearchDialog->activateWindow();
422 }
423
424 void OpenBabel::onOptimizeGeometry()
425 {
426 if (!m_molecule || m_molecule->atomCount() == 0) {
427 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
428 tr("Molecule invalid. Cannot optimize geometry."),
429 QMessageBox::Ok);
430 return;
431 }
432
433 // If the force field map is empty, there is probably a problem with the
434 // obabel executable. Warn the user and return.
435 if (m_forceFields.isEmpty()) {
436 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
437 tr("An error occurred while retrieving the list of "
438 "supported forcefields. (using '%1').")
439 .arg(m_process->obabelExecutable()),
440 QMessageBox::Ok);
441 return;
442 }
443
444 // Fail here if the process is already in use
445 if (m_process->inUse()) {
446 showProcessInUseError(tr("Cannot optimize geometry with Open Babel."));
447 return;
448 }
449
450 QSettings settings;
451 QStringList options =
452 settings.value("openbabel/optimizeGeometry/lastOptions").toStringList();
453 bool autoDetect =
454 settings.value("openbabel/optimizeGeometry/autoDetect", true).toBool();
455
456 if (autoDetect) {
457 QString ff = autoDetectForceField();
458 int ffIndex = options.indexOf("--ff");
459 if (ffIndex >= 0) {
460 // Shouldn't happen, but just to be safe...
461 if (ffIndex + 1 == options.size())
462 options << ff;
463 else
464 options[ffIndex + 1] = ff;
465 } else {
466 options << "--ff" << ff;
467 }
468 }
469
470 // Setup progress dialog
471 initializeProgressDialog(tr("Optimizing Geometry (Open Babel)"),
472 tr("Generating…"), 0, 0, 0);
473
474 // Connect process
475 disconnect(m_process);
476 m_process->disconnect(this);
477 connect(m_progress, SIGNAL(canceled()), m_process, SLOT(abort()));
478 connect(m_process,
479 SIGNAL(optimizeGeometryStatusUpdate(int, int, double, double)),
480 SLOT(onOptimizeGeometryStatusUpdate(int, int, double, double)));
481 connect(m_process, SIGNAL(optimizeGeometryFinished(QByteArray)),
482 SLOT(onOptimizeGeometryFinished(QByteArray)));
483
484 // Generate CML
485 std::string mol;
486 if (!Io::FileFormatManager::instance().writeString(*m_molecule, mol,
487 m_defaultFormat)) {
488 m_progress->reset();
489 QMessageBox::critical(
490 qobject_cast<QWidget*>(parent()), tr("Error"),
491 tr("An internal error occurred while generating an "
492 "Open Babel representation of the current molecule."),
493 QMessageBox::Ok);
494 return;
495 }
496
497 m_progress->setLabelText(tr("Starting %1…", "arg is an executable file.")
498 .arg(m_process->obabelExecutable()));
499
500 // Run obabel
501 m_process->optimizeGeometry(QByteArray(mol.c_str()), options,
502 m_defaultFormat);
503 }
504
505 void OpenBabel::onOptimizeGeometryStatusUpdate(int step, int numSteps,
506 double energy, double lastEnergy)
507 {
508 QString status;
509
510 if (step == 0) {
511 status = tr("Step %1 of %2\nCurrent energy: %3\ndE: %4")
512 .arg(step)
513 .arg(numSteps)
514 .arg(fabs(energy) > 1e-10 ? QString::number(energy, 'g', 5)
515 : QString("(pending)"))
516 .arg("(pending)");
517 } else {
518 double dE = energy - lastEnergy;
519 status = tr("Step %1 of %2\nCurrent energy: %3\ndE: %4")
520 .arg(step)
521 .arg(numSteps)
522 .arg(energy, 0, 'g', 5)
523 .arg(dE, 0, 'g', 5);
524 }
525
526 m_progress->setRange(0, numSteps);
527 m_progress->setValue(step);
528 m_progress->setLabelText(status);
529 }
530
531 void OpenBabel::onOptimizeGeometryFinished(const QByteArray& output)
532 {
533 m_progress->setLabelText(tr("Updating molecule…"));
534
535 // CML --> molecule
536 Core::Molecule mol;
537 if (!Io::FileFormatManager::instance().readString(mol, output.constData(),
538 m_defaultFormat)) {
539 m_progress->reset();
540 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
541 tr("Error interpreting Open Babel output."),
542 QMessageBox::Ok);
543 qDebug() << "Open Babel:" << output;
544 return;
545 }
546
547 /// @todo cache a pointer to the current molecule in the above slot, and
548 /// verify that we're still operating on the same molecule.
549
550 // Check that the atom count hasn't changed:
551 if (mol.atomCount() != m_molecule->atomCount()) {
552 m_progress->reset();
553 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
554 tr("Number of atoms in obabel output (%1) does not "
555 "match the number of atoms in the original "
556 "molecule (%2).")
557 .arg(mol.atomCount())
558 .arg(m_molecule->atomCount()),
559 QMessageBox::Ok);
560 return;
561 }
562
563 m_molecule->undoMolecule()->setAtomPositions3d(mol.atomPositions3d(),
564 tr("Optimize Geometry"));
565 m_molecule->emitChanged(QtGui::Molecule::Atoms | QtGui::Molecule::Modified);
566 m_progress->reset();
567 }
568
569 void OpenBabel::onGenerateConformers()
570 {
571 if (!m_molecule || m_molecule->atomCount() == 0) {
572 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
573 tr("Molecule invalid. Cannot generate conformers."),
574 QMessageBox::Ok);
575 return;
576 }
577
578 // If the force field map is empty, there is probably a problem with the
579 // obabel executable. Warn the user and return.
580 if (m_forceFields.isEmpty()) {
581 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
582 tr("An error occurred while retrieving the list of "
583 "supported forcefields. (using '%1').")
584 .arg(m_process->obabelExecutable()),
585 QMessageBox::Ok);
586 return;
587 }
588
589 // Fail here if the process is already in use
590 if (m_process->inUse()) {
591 showProcessInUseError(tr("Cannot generate conformers with Open Babel."));
592 return;
593 }
594
595 if (m_conformerSearchDialog == nullptr) {
596 return; // should't happen
597 }
598
599 QSettings settings;
600 QStringList options = m_conformerSearchDialog->options();
601
602 QStringList ffOptions =
603 settings.value("openbabel/optimizeGeometry/lastOptions").toStringList();
604 bool autoDetect =
605 settings.value("openbabel/optimizeGeometry/autoDetect", true).toBool();
606
607 if (autoDetect) {
608 QString ff = autoDetectForceField();
609 int ffIndex = ffOptions.indexOf("--ff");
610 if (ffIndex >= 0) {
611 // Shouldn't happen, but just to be safe...
612 if (ffIndex + 1 == ffOptions.size())
613 ffOptions << ff;
614 else
615 ffOptions[ffIndex + 1] = ff;
616 } else {
617 ffOptions << "--ff" << ff;
618 }
619 }
620
621 options << ffOptions;
622
623 // Setup progress dialog
624 initializeProgressDialog(tr("Generating Conformers (Open Babel)"),
625 tr("Generating…"), 0, 0, 0);
626
627 // Connect process
628 disconnect(m_process);
629 m_process->disconnect(this);
630 connect(m_progress, SIGNAL(canceled()), m_process, SLOT(abort()));
631 connect(m_process, SIGNAL(conformerStatusUpdate(int, int, double, double)),
632 SLOT(onConformerStatusUpdate(int, int, double, double)));
633 connect(m_process, SIGNAL(generateConformersFinished(QByteArray)),
634 SLOT(onGenerateConformersFinished(QByteArray)));
635
636 std::string mol;
637 if (!Io::FileFormatManager::instance().writeString(*m_molecule, mol,
638 m_defaultFormat)) {
639 m_progress->reset();
640 QMessageBox::critical(
641 qobject_cast<QWidget*>(parent()), tr("Error"),
642 tr("An internal error occurred while generating an "
643 "Open Babel representation of the current molecule."),
644 QMessageBox::Ok);
645 return;
646 }
647
648 m_progress->setLabelText(tr("Starting %1…", "arg is an executable file.")
649 .arg(m_process->obabelExecutable()));
650
651 // Run obabel
652 m_process->generateConformers(QByteArray(mol.c_str()), options,
653 m_defaultFormat);
654 }
655
656 void OpenBabel::onConformerStatusUpdate(int step, int numSteps, double energy,
657 double lastEnergy)
658 {
659 QString status;
660
661 if (step == 0) {
662 status = tr("Step %1 of %2\nCurrent energy: %3\ndE: %4")
663 .arg(step)
664 .arg(numSteps)
665 .arg(fabs(energy) > 1e-10 ? QString::number(energy, 'g', 5)
666 : QString("(pending)"))
667 .arg("(pending)");
668 } else {
669 double dE = energy - lastEnergy;
670 status = tr("Step %1 of %2\nCurrent energy: %3\ndE: %4")
671 .arg(step)
672 .arg(numSteps)
673 .arg(energy, 0, 'g', 5)
674 .arg(dE, 0, 'g', 5);
675 }
676
677 m_progress->setRange(0, numSteps);
678 m_progress->setValue(step);
679 m_progress->setLabelText(status);
680 }
681
682 void OpenBabel::onGenerateConformersFinished(const QByteArray& output)
683 {
684 m_progress->setLabelText(tr("Updating molecule…"));
685
686 // output --> molecule
687 Core::Molecule mol;
688 if (!Io::FileFormatManager::instance().readString(mol, output.constData(),
689 m_defaultFormat)) {
690 m_progress->reset();
691 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
692 tr("Error interpreting Open Babel output."),
693 QMessageBox::Ok);
694 qDebug() << "Open Babel:" << output;
695 return;
696 }
697
698 /// @todo cache a pointer to the current molecule in the above slot, and
699 /// verify that we're still operating on the same molecule.
700
701 // Check that the atom count hasn't changed:
702 if (mol.atomCount() != m_molecule->atomCount()) {
703 m_progress->reset();
704 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
705 tr("Number of atoms in obabel output (%1) does not "
706 "match the number of atoms in the original "
707 "molecule (%2).")
708 .arg(mol.atomCount())
709 .arg(m_molecule->atomCount()),
710 QMessageBox::Ok);
711 return;
712 }
713
714 m_molecule->undoMolecule()->setAtomPositions3d(mol.atomPositions3d(),
715 tr("Generate Conformers"));
716
717 // copy the coordinate sets
718 m_molecule->clearCoordinate3d();
719 for (size_t i = 0; i < mol.coordinate3dCount(); ++i)
720 m_molecule->setCoordinate3d(mol.coordinate3d(i), static_cast<int>(i));
721
722 // energy data too
723 // TODO: check if other properties are needed
724 m_molecule->setData("energies", mol.data("energies"));
725
726 m_molecule->emitChanged(QtGui::Molecule::Atoms | QtGui::Molecule::Modified);
727 m_progress->reset();
728 }
729
730 void OpenBabel::onPerceiveBonds()
731 {
732 // Fail here if the process is already in use
733 if (m_process->inUse()) {
734 showProcessInUseError(tr("Cannot open file with Open Babel."));
735 return;
736 }
737
738 if (!m_molecule || m_molecule->atomCount() < 2) {
739 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
740 tr("Invalid molecule: Cannot perceive bonds."),
741 QMessageBox::Ok);
742 return;
743 }
744
745 // Setup progress dialog
746 initializeProgressDialog(tr("Perceiving Bonds (Open Babel)"),
747 tr("Generating XYZ representation…"), 0, 0, 0);
748
749 // Generate XYZ
750 std::string xyz;
751 if (!Io::FileFormatManager::instance().writeString(*m_molecule, xyz, "xyz")) {
752 m_progress->reset();
753 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
754 tr("Error generating XYZ string."), QMessageBox::Ok);
755 return;
756 }
757
758 // Connect process
759 disconnect(m_process);
760 m_process->disconnect(this);
761 connect(m_progress, SIGNAL(canceled()), m_process, SLOT(abort()));
762 connect(m_process, SIGNAL(convertFinished(QByteArray)),
763 SLOT(onPerceiveBondsFinished(QByteArray)));
764
765 m_progress->setLabelText(tr("Converting XYZ to Open Babel with %1…")
766 .arg(m_process->obabelExecutable()));
767
768 // Run process
769 m_process->convert(QByteArray(xyz.c_str(), xyz.size()), "xyz",
770 m_defaultFormat.c_str());
771 }
772
773 void OpenBabel::onPerceiveBondsFinished(const QByteArray& output)
774 {
775 m_progress->setLabelText(tr("Updating molecule from Open Babel…"));
776
777 // CML --> molecule
778 Core::Molecule mol;
779 if (!Io::FileFormatManager::instance().readString(mol, output.constData(),
780 m_defaultFormat)) {
781 m_progress->reset();
782 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
783 tr("Error interpreting Open Babel output."),
784 QMessageBox::Ok);
785 return;
786 }
787
788 /// @todo cache a pointer to the current molecule in the above slot, and
789 /// verify that we're still operating on the same molecule.
790
791 // Check that the atom count hasn't changed:
792 if (mol.atomCount() != m_molecule->atomCount()) {
793 m_progress->reset();
794 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
795 tr("Number of atoms in obabel output (%1) does not "
796 "match the number of atoms in the original "
797 "molecule (%2).")
798 .arg(mol.atomCount())
799 .arg(m_molecule->atomCount()),
800 QMessageBox::Ok);
801 return;
802 }
803
804 // Update the undo stack
805 Molecule newMolecule = *m_molecule;
806 newMolecule.clearBonds();
807 for (size_t i = 0; i < mol.bondCount(); ++i) {
808 Avogadro::Core::Bond bond = mol.bond(i);
809 newMolecule.addBond(newMolecule.atom(bond.atom1().index()),
810 newMolecule.atom(bond.atom2().index()), bond.order());
811 }
812
813 Molecule::MoleculeChanges changes =
814 Molecule::Bonds | Molecule::Added | Molecule::Removed | Molecule::Modified;
815 m_molecule->undoMolecule()->modifyMolecule(newMolecule, changes,
816 "Perceive Bonds");
817 m_progress->reset();
818 }
819
820 void OpenBabel::onAddHydrogens()
821 {
822 if (!m_molecule || m_molecule->atomCount() == 0)
823 return; // Nothing to do.
824
825 // Fail here if the process is already in use
826 if (m_process->inUse()) {
827 showProcessInUseError(tr("Cannot add hydrogens with Open Babel."));
828 return;
829 }
830
831 // Setup progress dialog
832 initializeProgressDialog(tr("Adding Hydrogens (Open Babel)"),
833 tr("Generating Open Babel input…"), 0, 0, 0);
834
835 // Generate MDL
836 std::string mol;
837 if (!Io::FileFormatManager::instance().writeString(*m_molecule, mol,
838 m_defaultFormat)) {
839 m_progress->reset();
840 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
841 tr("Error generating Open Babel input."),
842 QMessageBox::Ok);
843 return;
844 }
845
846 // Connect process
847 disconnect(m_process);
848 m_process->disconnect(this);
849 connect(m_progress, SIGNAL(canceled()), m_process, SLOT(abort()));
850 connect(m_process, SIGNAL(convertFinished(QByteArray)),
851 SLOT(onHydrogenOperationFinished(QByteArray)));
852
853 m_progress->setLabelText(
854 tr("Running %1…").arg(m_process->obabelExecutable()));
855
856 // Run process
857 m_process->convert(QByteArray(mol.c_str(), mol.size()),
858 m_defaultFormat.c_str(), m_defaultFormat.c_str(),
859 QStringList() << "-h");
860 }
861
862 void OpenBabel::onAddHydrogensPh()
863 {
864 if (!m_molecule || m_molecule->atomCount() == 0)
865 return; // Nothing to do.
866
867 // Fail here if the process is already in use
868 if (m_process->inUse()) {
869 showProcessInUseError(tr("Cannot add hydrogens with Open Babel."));
870 return;
871 }
872
873 // Prompt for pH
874 bool ok = false;
875 double pH = QInputDialog::getDouble(qobject_cast<QWidget*>(parent()),
876 tr("Add hydrogens for pH"), tr("pH:"),
877 7.4, 0, 14, 2, &ok);
878 if (!ok) // user cancel
879 return;
880
881 // Setup progress dialog
882 initializeProgressDialog(tr("Adding Hydrogens (Open Babel)"),
883 tr("Generating obabel input…"), 0, 0, 0);
884
885 // Generate MDL
886 std::string mol;
887 if (!Io::FileFormatManager::instance().writeString(*m_molecule, mol,
888 m_defaultFormat)) {
889 m_progress->reset();
890 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
891 tr("Error generating Open Babel input."),
892 QMessageBox::Ok);
893 return;
894 }
895
896 // Connect process
897 disconnect(m_process);
898 m_process->disconnect(this);
899 connect(m_progress, SIGNAL(canceled()), m_process, SLOT(abort()));
900 connect(m_process, SIGNAL(convertFinished(QByteArray)),
901 SLOT(onHydrogenOperationFinished(QByteArray)));
902
903 m_progress->setLabelText(
904 tr("Running %1…").arg(m_process->obabelExecutable()));
905
906 // Run process
907 m_process->convert(QByteArray(mol.c_str(), mol.size()),
908 m_defaultFormat.c_str(), m_defaultFormat.c_str(),
909 QStringList() << "-p" << QString::number(pH));
910 }
911
912 void OpenBabel::onRemoveHydrogens()
913 {
914 if (!m_molecule || m_molecule->atomCount() == 0)
915 return; // Nothing to do.
916
917 // Fail here if the process is already in use
918 if (m_process->inUse()) {
919 showProcessInUseError(tr("Cannot remove hydrogens with Open Babel."));
920 return;
921 }
922
923 // Setup progress dialog
924 initializeProgressDialog(tr("Removing Hydrogens (Open Babel)"),
925 tr("Generating obabel input…"), 0, 0, 0);
926
927 // Generate MDL
928 std::string mol;
929 if (!Io::FileFormatManager::instance().writeString(*m_molecule, mol,
930 m_defaultFormat)) {
931 m_progress->reset();
932 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
933 tr("Error generating Open Babel data."),
934 QMessageBox::Ok);
935 return;
936 }
937
938 // Connect process
939 disconnect(m_process);
940 m_process->disconnect(this);
941 connect(m_progress, SIGNAL(canceled()), m_process, SLOT(abort()));
942 connect(m_process, SIGNAL(convertFinished(QByteArray)),
943 SLOT(onHydrogenOperationFinished(QByteArray)));
944
945 m_progress->setLabelText(
946 tr("Running %1…").arg(m_process->obabelExecutable()));
947
948 // Run process
949 m_process->convert(QByteArray(mol.c_str(), mol.size()),
950 m_defaultFormat.c_str(), m_defaultFormat.c_str(),
951 QStringList() << "-d");
952 }
953
954 void OpenBabel::onHydrogenOperationFinished(const QByteArray& mdl)
955 {
956 m_progress->setLabelText(tr("Reading obabel output…"));
957
958 // MDL --> molecule
959 Core::Molecule mol;
960 if (!Io::FileFormatManager::instance().readString(mol, mdl.constData(),
961 m_defaultFormat)) {
962 m_progress->reset();
963 qWarning() << "Open Babel error: " << mdl;
964 QMessageBox::critical(qobject_cast<QWidget*>(parent()), tr("Error"),
965 tr("Error interpreting Open Babel output."),
966 QMessageBox::Ok);
967 qDebug() << "Open Babel:" << mdl;
968 return;
969 }
970
971 /// @todo cache a pointer to the current molecule in the above slot, and
972 /// verify that we're still operating on the same molecule.
973
974 // Update the undo stack
975 Molecule newMolecule;
976 for (Index i = 0; i < mol.atomCount(); ++i) {
977 Core::Atom atom = mol.atom(i);
978 newMolecule.addAtom(atom.atomicNumber()).setPosition3d(atom.position3d());
979 }
980 for (Index i = 0; i < mol.bondCount(); ++i) {
981 Core::Bond bond = mol.bond(i);
982 newMolecule.addBond(newMolecule.atom(bond.atom1().index()),
983 newMolecule.atom(bond.atom2().index()), bond.order());
984 }
985
986 Molecule::MoleculeChanges changes = Molecule::Atoms | Molecule::Bonds |
987 Molecule::Added | Molecule::Removed |
988 Molecule::Modified;
989
990 // If the number of atoms is greater, we added hydrogens. Else, we removed
991 // them!
992 QString undoString = "Add Hydrogens";
993 if (m_molecule->atomCount() > newMolecule.atomCount())
994 undoString = "Remove Hydrogens";
995
996 m_molecule->undoMolecule()->modifyMolecule(newMolecule, changes, undoString);
997 m_progress->reset();
998 }
999
1000 void OpenBabel::initializeProgressDialog(const QString& title,
1001 const QString& label, int min, int max,
1002 int value, bool showDialog)
1003 {
1004 if (!m_progress)
1005 m_progress = new QProgressDialog(qobject_cast<QWidget*>(parent()));
1006
1007 m_progress->setWindowTitle(title);
1008 m_progress->setLabelText(label);
1009 m_progress->setRange(min, max);
1010 m_progress->setValue(value);
1011 m_progress->setMinimumDuration(0);
1012 if (showDialog)
1013 m_progress->show();
1014 }
1015
1016 void OpenBabel::showProcessInUseError(const QString& title) const
1017 {
1018 QMessageBox::critical(qobject_cast<QWidget*>(parent()), title,
1019 tr("Already running Open Babel. Wait for the other "
1020 "operation to complete and try again."),
1021 QMessageBox::Ok);
1022 }
1023
1024 QString OpenBabel::autoDetectForceField() const
1025 {
1026 // Guess forcefield based on molecule. Preference is GAFF, MMFF94, then UFF.
1027 // See discussion at
1028 // http://forums.openbabel.org/Heuristic-for-selecting-best-forcefield-td4655917.html
1029 QString formula = QString::fromStdString(m_molecule->formula());
1030 QStringList elementTypes =
1031 formula.split(QRegularExpression("\\d+"), Qt::SkipEmptyParts);
1032 bool mmff94Valid = true;
1033 bool gaffValid = true;
1034 QStringList::const_iterator eleIter = elementTypes.constBegin();
1035 while (eleIter != elementTypes.constEnd() && (mmff94Valid || gaffValid)) {
1036 // These are supported by GAFF and MMFF94s
1037 if (*eleIter != "C" && *eleIter != "H" && *eleIter != "F" &&
1038 *eleIter != "Cl" && *eleIter != "Br" && *eleIter != "I" &&
1039 *eleIter != "N" && *eleIter != "O" && *eleIter != "P" &&
1040 *eleIter != "S") {
1041 gaffValid = false;
1042 mmff94Valid = false;
1043
1044 // MMFF94 supports isolated metal ions but it's safer to use UFF
1045 // Fixes #1324
1046 }
1047 ++eleIter;
1048 }
1049
1050 QStringList ffs = m_forceFields.keys();
1051 QString result;
1052 if (gaffValid && ffs.contains("GAFF"))
1053 result = "GAFF";
1054 else if (mmff94Valid && ffs.contains("MMFF94"))
1055 result = "MMFF94";
1056 // MMFF94 handles nitrogens more correctly than MMFF94s, but this
1057 // can be used in a pinch.
1058 else if (mmff94Valid && ffs.contains("MMFF94s"))
1059 result = "MMFF94s";
1060 else if (ffs.contains("UFF"))
1061 result = "UFF";
1062
1063 return result;
1064 }
1065 } // namespace Avogadro::QtPlugins