Debian Codegraph @

avogadro/qtplugins/openbabel/obprocess.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 "obprocess.h"
7
8 #include <QtCore/QCoreApplication>
9 #include <QtCore/QDebug>
10 #include <QtCore/QDir>
11 #include <QtCore/QFileInfo>
12 #include <QtCore/QProcess>
13
14 #include <QRegularExpression>
15
16 namespace Avogadro::QtPlugins {
17
18 OBProcess::OBProcess(QObject* parent_)
19 : QObject(parent_), m_processLocked(false), m_aborted(false),
20 m_process(new QProcess(this)),
21 #if defined(_WIN32)
22 m_obabelExecutable("obabel.exe")
23 #else
24 m_obabelExecutable("obabel")
25 #endif
26 {
27 // Read the AVO_OBABEL_EXECUTABLE env var to optionally override the
28 // executable used for obabel.
29 QByteArray obabelExec = qgetenv("AVO_OBABEL_EXECUTABLE");
30 if (!obabelExec.isEmpty()) {
31 m_obabelExecutable = obabelExec;
32 } else {
33 // If not overridden, look for an obabel next to the executable.
34 QDir baseDir(QCoreApplication::applicationDirPath());
35 if (!baseDir.absolutePath().startsWith("/usr/") &&
36 QFileInfo(baseDir.absolutePath() + '/' + m_obabelExecutable).exists()) {
37 m_obabelExecutable = baseDir.absolutePath() + '/' + m_obabelExecutable;
38 QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
39 #if defined(_WIN32)
40 env.insert("BABEL_DATADIR",
41 QCoreApplication::applicationDirPath() + "/data");
42 #else
43 QDir dir(QCoreApplication::applicationDirPath() + "/../share/openbabel");
44 QStringList filters;
45 filters << "3.*"
46 << "2.*";
47 QStringList dirs = dir.entryList(filters);
48 if (dirs.size() == 1) {
49 env.insert("BABEL_DATADIR", QCoreApplication::applicationDirPath() +
50 "/../share/openbabel/" + dirs[0]);
51 } else {
52 qDebug() << "Error, Open Babel data directory not found.";
53 }
54 dir.setPath(QCoreApplication::applicationDirPath() + "/../lib/openbabel");
55 dirs = dir.entryList(filters);
56 if (dirs.size() == 0) {
57 env.insert("BABEL_LIBDIR", QCoreApplication::applicationDirPath() +
58 "/../lib/openbabel/");
59 } else if (dirs.size() == 1) {
60 env.insert("BABEL_LIBDIR", QCoreApplication::applicationDirPath() +
61 "/../lib/openbabel/" + dirs[0]);
62 } else {
63 qDebug() << "Error, Open Babel plugins directory not found.";
64 }
65 #endif
66 m_process->setProcessEnvironment(env);
67 }
68 }
69 }
70
71 QString OBProcess::version()
72 {
73 QString result;
74
75 if (!tryLockProcess()) {
76 qWarning() << "OBProcess::version: process already in use.";
77 return result;
78 }
79
80 executeObabel(QStringList() << "-V");
81
82 if (m_process->waitForFinished(500))
83 result = m_process->readAllStandardOutput().trimmed();
84
85 releaseProcess();
86 return result;
87 }
88
89 void OBProcess::abort()
90 {
91 m_aborted = true;
92 emit aborted();
93 }
94
95 void OBProcess::obError()
96 {
97 qDebug() << "Process encountered an error, and did not execute correctly.";
98 if (m_process) {
99 qDebug() << "\tExit code:" << m_process->exitCode();
100 qDebug() << "\tExit status:" << m_process->exitStatus();
101 qDebug() << "\tExit output:" << m_process->readAll();
102 }
103 }
104
105 bool OBProcess::queryReadFormats()
106 {
107 if (!tryLockProcess()) {
108 qWarning() << "OBProcess::queryReadFormats: process already in use.";
109 return false;
110 }
111
112 // Setup options
113 QStringList options;
114 options << "-L"
115 << "formats"
116 << "read";
117
118 executeObabel(options, this, SLOT(queryReadFormatsPrepare()));
119 return true;
120 }
121
122 bool OBProcess::queryWriteFormats()
123 {
124 if (!tryLockProcess()) {
125 qWarning() << "OBProcess::queryWriteFormats: process already in use.";
126 return false;
127 }
128
129 // Setup options
130 QStringList options;
131 options << "-L"
132 << "formats"
133 << "write";
134
135 executeObabel(options, this, SLOT(queryWriteFormatsPrepare()));
136 return true;
137 }
138
139 void OBProcess::queryReadFormatsPrepare()
140 {
141 if (m_aborted) {
142 releaseProcess();
143 return;
144 }
145
146 QMultiMap<QString, QString> result;
147
148 QString output = QString::fromLatin1(m_process->readAllStandardOutput());
149
150 QRegularExpression parser(R"(\s*([^\s]+)\s+--\s+([^\n]+)\n)");
151 QRegularExpressionMatch match;
152 int pos = 0;
153 while ((match = parser.match(output, pos)).hasMatch()) {
154 QString extension = match.captured(1);
155 QString description = match.captured(2);
156 result.insertMulti(description, extension);
157 pos = match.capturedEnd(0);
158 }
159
160 releaseProcess();
161 emit queryReadFormatsFinished(result);
162 return;
163 }
164
165 void OBProcess::queryWriteFormatsPrepare()
166 {
167 if (m_aborted) {
168 releaseProcess();
169 return;
170 }
171
172 QMultiMap<QString, QString> result;
173
174 QString output = QString::fromLatin1(m_process->readAllStandardOutput());
175
176 QRegularExpression parser(R"(\s*([^\s]+)\s+--\s+([^\n]+)\n)");
177 QRegularExpressionMatch match;
178 int pos = 0;
179 while ((match = parser.match(output, pos)).hasMatch()) {
180 QString extension = match.captured(1);
181 QString description = match.captured(2);
182
183 // skip some formats that we want to ignore
184 if (extension == "png" || extension == "svg" || extension == "paint" ||
185 extension == "nul") {
186 pos = match.capturedEnd(0);
187 continue;
188 }
189
190 result.insertMulti(description, extension);
191 pos = match.capturedEnd(0);
192 }
193
194 releaseProcess();
195 emit queryWriteFormatsFinished(result);
196 return;
197 }
198
199 bool OBProcess::convert(const QByteArray& input, const QString& inFormat,
200 const QString& outFormat, const QStringList& options)
201 {
202 if (!tryLockProcess()) {
203 qWarning() << "OBProcess::convert: process already in use.";
204 return false;
205 }
206
207 QStringList realOptions;
208 realOptions << QString("-i%1").arg(inFormat) << QString("-o%1").arg(outFormat)
209 << options;
210
211 executeObabel(realOptions, this, SLOT(convertPrepareOutput()), input);
212 return true;
213 }
214
215 bool OBProcess::convert(const QString& filename, const QString& inFormat,
216 const QString& outFormat, const QStringList& options)
217 {
218 if (!tryLockProcess()) {
219 qWarning() << "OBProcess::convert: process already in use.";
220 return false;
221 }
222
223 QStringList realOptions;
224 realOptions << QString("-i%1").arg(inFormat) << filename
225 << QString("-o%1").arg(outFormat) << options;
226
227 executeObabel(realOptions, this, SLOT(convertPrepareOutput()));
228 return true;
229 }
230
231 void OBProcess::convertPrepareOutput()
232 {
233 if (m_aborted) {
234 releaseProcess();
235 return;
236 }
237
238 // Keep this empty if an error occurs:
239 QByteArray output;
240
241 // Check for errors.
242 QString errorOutput = QString::fromLatin1(m_process->readAllStandardError());
243 QRegularExpression errorChecker("\\b0 molecules converted\\b"
244 "|"
245 "obabel: cannot read input format!");
246 if (!errorOutput.contains(errorChecker)) {
247 if (m_process->exitStatus() == QProcess::NormalExit)
248 output = m_process->readAllStandardOutput();
249 }
250
251 /// Print any meaningful warnings @todo This should go to a log at some point.
252 if (!errorOutput.isEmpty() && errorOutput != "1 molecule converted\n")
253 qWarning() << m_obabelExecutable << " stderr:\n" << errorOutput;
254
255 emit convertFinished(output);
256 releaseProcess();
257 }
258
259 bool OBProcess::queryForceFields()
260 {
261 if (!tryLockProcess()) {
262 qWarning() << "OBProcess::queryForceFields(): process already in use.";
263 return false;
264 }
265
266 QStringList options;
267 options << "-L"
268 << "forcefields";
269
270 executeObabel(options, this, SLOT(queryForceFieldsPrepare()));
271 return true;
272 }
273
274 void OBProcess::queryForceFieldsPrepare()
275 {
276 if (m_aborted) {
277 releaseProcess();
278 return;
279 }
280
281 QMultiMap<QString, QString> result;
282
283 QString output = QString::fromLatin1(m_process->readAllStandardOutput());
284
285 QRegularExpression parser(R"(([^\s]+)\s+(\S[^\n]*[^\n\.]+)\.?\n)");
286 QRegularExpressionMatch match;
287 int pos = 0;
288 while ((match = parser.match(output, pos)).hasMatch()) {
289 QString key = match.captured(1);
290 QString desc = match.captured(2);
291 result.insertMulti(key, desc);
292 pos = match.capturedEnd(0);
293 }
294
295 releaseProcess();
296 emit queryForceFieldsFinished(result);
297 }
298
299 bool OBProcess::queryCharges()
300 {
301 if (!tryLockProcess()) {
302 qWarning() << "OBProcess::queryCharges(): process already in use.";
303 return false;
304 }
305
306 QStringList options;
307 options << "-L"
308 << "charges";
309
310 executeObabel(options, this, SLOT(queryChargesPrepare()));
311 return true;
312 }
313
314 void OBProcess::queryChargesPrepare()
315 {
316 if (m_aborted) {
317 releaseProcess();
318 return;
319 }
320
321 QMultiMap<QString, QString> result;
322
323 QString output = QString::fromLatin1(m_process->readAllStandardOutput());
324
325 QRegularExpression parser(R"(([^\s]+)\s+(\S[^\n]*[^\n\.]+)\.?\n)");
326 QRegularExpressionMatch match;
327 int pos = 0;
328 while ((match = parser.match(output, pos)).hasMatch()) {
329 QString key = match.captured(1);
330 QString desc = match.captured(2);
331 result.insertMulti(key, desc);
332 pos = match.capturedEnd(0);
333 }
334
335 releaseProcess();
336 emit queryChargesFinished(result);
337 }
338
339 bool OBProcess::calculateCharges(const QByteArray& mol,
340 const std::string& format,
341 const std::string& type)
342 {
343 if (!tryLockProcess()) {
344 qWarning() << "OBProcess::calculateCharges(): process already in use.";
345 return false;
346 }
347
348 QStringList realOptions;
349
350 if (format == "cjson") {
351 realOptions << "-icjson";
352 } else {
353 realOptions << "-icml";
354 }
355 realOptions << "-onul" // ignore the output
356 << "--partialcharge" << type.c_str() << "--print";
357
358 // Start the optimization
359 executeObabel(realOptions, this, SLOT(chargesPrepareOutput()), mol);
360 return true;
361 }
362
363 void OBProcess::chargesPrepareOutput()
364 {
365 if (m_aborted) {
366 releaseProcess();
367 return;
368 }
369
370 // Keep this empty if an error occurs:
371 QByteArray output;
372
373 // Check for errors.
374 QString errorOutput = QString::fromLatin1(m_process->readAllStandardError());
375 QRegularExpression errorChecker("\\b0 molecules converted\\b"
376 "|"
377 "obabel: cannot read input format!");
378 if (!errorOutput.contains(errorChecker)) {
379 if (m_process->exitStatus() == QProcess::NormalExit)
380 output = m_process->readAllStandardOutput();
381 }
382
383 /// Print any meaningful warnings @todo This should go to a log at some point.
384 if (!errorOutput.isEmpty() && errorOutput != "1 molecule converted\n")
385 qWarning() << m_obabelExecutable << " stderr:\n" << errorOutput;
386
387 // Convert the output line-by-line to charges
388 Core::Array<double> charges;
389 QTextStream stream(output);
390 QString line;
391 while (stream.readLineInto(&line)) {
392 bool ok;
393 double charge = line.toDouble(&ok);
394 if (!ok)
395 break;
396
397 charges.push_back(charge);
398 }
399
400 emit chargesFinished(charges);
401 releaseProcess();
402 }
403
404 bool OBProcess::optimizeGeometry(const QByteArray& mol,
405 const QStringList& options,
406 const std::string format)
407 {
408 if (!tryLockProcess()) {
409 qWarning() << "OBProcess::optimizeGeometry(): process already in use.";
410 return false;
411 }
412
413 QStringList realOptions;
414 if (format == "cjson") {
415 realOptions << "-icjson"
416 << "-ocjson";
417 } else {
418 realOptions << "-icml"
419 << "-ocml";
420 }
421 realOptions << "--minimize"
422 << "--noh" // new in OB 3.0.1
423 << "--log" << options;
424
425 // We'll need to read the log (printed to stderr) to update progress
426 connect(m_process, SIGNAL(readyReadStandardError()),
427 SLOT(optimizeGeometryReadLog()));
428
429 // Initialize the log reader ivars
430 m_optimizeGeometryLog.clear();
431 m_optimizeGeometryMaxSteps = -1;
432
433 // Start the optimization
434 executeObabel(realOptions, this, SLOT(optimizeGeometryPrepare()), mol);
435 return true;
436 }
437
438 bool OBProcess::generateConformers(const QByteArray& mol,
439 const QStringList& options,
440 const std::string format)
441 {
442 if (!tryLockProcess()) {
443 qWarning() << "OBProcess::generateConformers(): process already in use.";
444 return false;
445 }
446
447 QStringList realOptions;
448 if (format == "cjson") {
449 realOptions << "-icjson"
450 << "-ocjson";
451 } else {
452 realOptions << "-icml"
453 << "-ocml";
454 }
455 realOptions << "--conformer"
456 << "--noh" // new in OB 3.0.1
457 << "--log" << options;
458
459 // We'll need to read the log (printed to stderr) to update progress
460 connect(m_process, SIGNAL(readyReadStandardError()),
461 SLOT(conformerReadLog()));
462
463 // Initialize the log reader ivars
464 m_optimizeGeometryLog.clear();
465 m_maxConformers = -1;
466
467 // Start the optimization
468 executeObabel(realOptions, this, SLOT(conformerPrepare()), mol);
469 return true;
470 }
471
472 void OBProcess::optimizeGeometryPrepare()
473 {
474 if (m_aborted) {
475 releaseProcess();
476 return;
477 }
478
479 QByteArray result = m_process->readAllStandardOutput();
480
481 releaseProcess();
482 emit optimizeGeometryFinished(result);
483 }
484
485 void OBProcess::conformerPrepare()
486 {
487 if (m_aborted) {
488 releaseProcess();
489 return;
490 }
491
492 QByteArray result = m_process->readAllStandardOutput();
493
494 releaseProcess();
495 emit generateConformersFinished(result);
496 }
497
498 void OBProcess::optimizeGeometryReadLog()
499 {
500 // Append the current stderr to the log
501 m_optimizeGeometryLog +=
502 QString::fromLatin1(m_process->readAllStandardError());
503
504 // Search for the maximum number of steps if we haven't found it yet
505 if (m_optimizeGeometryMaxSteps < 0) {
506 QRegularExpression maxStepsParser("\nSTEPS = ([0-9]+)\n\n");
507 QRegularExpressionMatch match;
508 if ((match = maxStepsParser.match(m_optimizeGeometryLog)).hasMatch()) {
509 m_optimizeGeometryMaxSteps = match.captured(1).toInt();
510 emit optimizeGeometryStatusUpdate(0, m_optimizeGeometryMaxSteps, 0.0,
511 0.0);
512 }
513 }
514
515 // Emit the last printed step
516 if (m_optimizeGeometryMaxSteps >= 0) {
517 QRegularExpression lastStepParser(
518 R"(\n\s*([0-9]+)\s+([-0-9.]+)\s+([-0-9.]+)\n)");
519 QRegularExpressionMatchIterator matchIterator =
520 lastStepParser.globalMatch(m_optimizeGeometryLog);
521 QRegularExpressionMatch lastMatch;
522 while (matchIterator.hasNext()) {
523 lastMatch = matchIterator.next(); // Capture the last match
524 }
525 if (lastMatch.hasMatch()) {
526 int step = lastMatch.captured(1).toInt();
527 double energy = lastMatch.captured(2).toDouble();
528 double lastEnergy = lastMatch.captured(3).toDouble();
529 emit optimizeGeometryStatusUpdate(step, m_optimizeGeometryMaxSteps,
530 energy, lastEnergy);
531 }
532 }
533 }
534
535 void OBProcess::conformerReadLog()
536 {
537 // Append the current stderr to the log
538 // (we're grabbing the log from the geometry optimization)
539 m_optimizeGeometryLog +=
540 QString::fromLatin1(m_process->readAllStandardError());
541
542 // Search for the maximum number of steps if we haven't found it yet
543 if (m_optimizeGeometryMaxSteps < 0) {
544 QRegularExpression maxStepsParser("\nSTEPS = ([0-9]+)\n\n");
545 QRegularExpressionMatch match;
546 if ((match = maxStepsParser.match(m_optimizeGeometryLog)).hasMatch()) {
547 m_optimizeGeometryMaxSteps = match.captured(1).toInt();
548 emit optimizeGeometryStatusUpdate(0, m_optimizeGeometryMaxSteps, 0.0,
549 0.0);
550 }
551 }
552
553 // Emit the last printed step
554 if (m_optimizeGeometryMaxSteps >= 0) {
555 QRegularExpression lastStepParser(
556 R"(\n\s*([0-9]+)\s+([-0-9.]+)\s+([-0-9.]+)\n)");
557 QRegularExpressionMatch match;
558 if ((match = lastStepParser.match(m_optimizeGeometryLog)).hasMatch()) {
559 int step = match.captured(1).toInt();
560 double energy = match.captured(2).toDouble();
561 double lastEnergy = match.captured(3).toDouble();
562 emit optimizeGeometryStatusUpdate(step, m_optimizeGeometryMaxSteps,
563 energy, lastEnergy);
564 }
565 }
566 }
567
568 void OBProcess::executeObabel(const QStringList& options, QObject* receiver,
569 const char* slot, const QByteArray& obabelStdin)
570 {
571 // Setup exit handler
572 if (receiver) {
573 connect(m_process, SIGNAL(finished(int)), receiver, slot);
574 connect(m_process, SIGNAL(errorOccurred(QProcess::ProcessError)), receiver,
575 slot);
576 connect(m_process, SIGNAL(errorOccurred(QProcess::ProcessError)), this,
577 SLOT(obError()));
578 }
579
580 // Start process
581 #ifndef NDEBUG
582 qDebug() << "OBProcess::executeObabel: "
583 "Running"
584 << m_obabelExecutable << options.join(" ");
585 #endif
586 m_process->start(m_obabelExecutable, options);
587 if (!obabelStdin.isNull()) {
588 m_process->write(obabelStdin);
589 m_process->closeWriteChannel();
590 }
591 }
592
593 void OBProcess::resetState()
594 {
595 m_aborted = false;
596 m_process->disconnect(this);
597 disconnect(m_process);
598 connect(this, SIGNAL(aborted()), m_process, SLOT(kill()));
599 }
600
601 } // namespace Avogadro::QtPlugins