Debian Codegraph @

avogadro/qtplugins/scriptcharges/scriptchargemodel.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 "scriptchargemodel.h"
7
8 #include <avogadro/core/molecule.h>
9 #include <avogadro/qtgui/pythonscript.h>
10
11 // formats supported in scripts
12 #include <avogadro/io/cjsonformat.h>
13 #include <avogadro/io/cmlformat.h>
14 #include <avogadro/io/mdlformat.h>
15 #include <avogadro/io/pdbformat.h>
16 #include <avogadro/io/sdfformat.h>
17 #include <avogadro/io/xyzformat.h>
18
19 #include <QtCore/QDebug>
20 #include <QtCore/QJsonArray>
21 #include <QtCore/QJsonDocument>
22 #include <QtCore/QJsonObject>
23 #include <QtCore/QJsonValue>
24 #include <QtCore/QList>
25 #include <QtCore/QScopedPointer>
26
27 namespace Avogadro::QtPlugins {
28
29 // Strip any leading non-JSON output (e.g. deprecation warnings printed to
30 // stdout by third-party libraries). Find the first '{' or '['.
31 static void stripLeadingNonJson(QByteArray& data)
32 {
33 qsizetype jsonObj = data.indexOf('{');
34 qsizetype jsonArr = data.indexOf('[');
35 qsizetype jsonStart = (jsonObj < 0) ? jsonArr
36 : (jsonArr < 0) ? jsonObj
37 : qMin(jsonObj, jsonArr);
38 if (jsonStart > 0)
39 data = data.mid(jsonStart);
40 }
41
42 // Parse a JSON byte array into a flat list of doubles.
43 // Accepts either a bare JSON array or an object containing `arrayKey`.
44 // Calls errorReporter(message) for structural problems and invalid elements.
45 // Returns true when JSON parsed successfully (even if some elements were
46 // invalid); returns false when JSON parsing itself failed, signalling the
47 // caller should fall through to legacy line-delimited parsing.
48 template <typename ErrorFunc>
49 static bool parseJsonNumericArray(const QByteArray& result,
50 const QString& arrayKey,
51 QList<double>& outValues, int maxCount,
52 ErrorFunc errorReporter)
53 {
54 QJsonParseError parseError;
55 QJsonDocument doc = QJsonDocument::fromJson(result, &parseError);
56 if (parseError.error != QJsonParseError::NoError)
57 return false;
58
59 QJsonArray values;
60 if (doc.isArray()) {
61 values = doc.array();
62 } else if (doc.isObject()) {
63 QJsonValue v = doc.object().value(arrayKey);
64 if (!v.isArray()) {
65 errorReporter(QStringLiteral("Invalid ") + arrayKey +
66 QStringLiteral(" output: missing required '") + arrayKey +
67 QStringLiteral("' JSON array."));
68 return true; // JSON was valid; caller receives empty outValues
69 }
70 values = v.toArray();
71 } else {
72 return false; // neither array nor object; fall through to legacy parser
73 }
74
75 if (values.size() > maxCount)
76 errorReporter(QStringLiteral("Too many ") + arrayKey +
77 QStringLiteral(" in script output."));
78
79 const int n = qMin(static_cast<int>(values.size()), maxCount);
80 outValues.resize(n);
81 for (int i = 0; i < n; ++i) {
82 const auto value = values.at(i);
83 if (!value.isDouble()) {
84 errorReporter(QStringLiteral("Invalid ") + arrayKey +
85 QStringLiteral(" value in JSON output at index ") +
86 QString::number(i) + QStringLiteral("."));
87 outValues[i] = 0.0;
88 } else {
89 outValues[i] = value.toDouble();
90 }
91 }
92 return true;
93 }
94
95 ScriptChargeModel::ScriptChargeModel(const QString& scriptFileName_)
96 : m_interpreter(new QtGui::PythonScript(scriptFileName_)),
97 m_inputFormat(NotUsed), m_valid(false), m_partialCharges(false),
98 m_electrostatics(false), m_inputCjson(false)
99 {
100 m_elements.reset();
101 if (!scriptFileName_.isEmpty())
102 readMetaData();
103 }
104
105 ScriptChargeModel::~ScriptChargeModel()
106 {
107 delete m_interpreter;
108 }
109
110 void ScriptChargeModel::setPackageInfo(const QString& packageDir,
111 const QString& command,
112 const QString& identifier)
113 {
114 m_interpreter->setPackageInfo(packageDir, command, identifier);
115 }
116
117 void ScriptChargeModel::readMetaData(const QVariantMap& metadata)
118 {
119 resetMetaData();
120
121 m_identifier = metadata.value("identifier").toString().toStdString();
122 m_name = metadata.value("model-name").toString().toStdString();
123 m_description = metadata.value("description").toString().toStdString();
124
125 QString inputFmt = metadata.value("input-format").toString();
126 m_inputFormat = stringToFormat(inputFmt.toStdString());
127 m_formatString = inputFmt;
128
129 QVariantMap support = metadata.value("support").toMap();
130 m_partialCharges = support.value("charges", false).toBool();
131 m_electrostatics = support.value("potentials", false).toBool();
132 m_inputCjson = metadata.value("input-cjson", false).toBool();
133
134 QString elemStr = support.value("elements").toString();
135 if (!elemStr.isEmpty())
136 processElementString(elemStr);
137
138 m_valid =
139 !m_identifier.empty() && !m_name.empty() && m_inputFormat != NotUsed;
140 }
141
142 QString ScriptChargeModel::scriptFilePath() const
143 {
144 return m_interpreter->scriptFilePath();
145 }
146
147 Calc::ChargeModel* ScriptChargeModel::newInstance() const
148 {
149 auto* copy = new ScriptChargeModel();
150 copy->m_interpreter->setPackageInfo(m_interpreter->packageDir(),
151 m_interpreter->packageCommand(),
152 m_interpreter->packageIdentifier());
153 copy->copyMetaDataFrom(*this);
154 return copy;
155 }
156
157 void ScriptChargeModel::copyMetaDataFrom(const ScriptChargeModel& other)
158 {
159 m_identifier = other.m_identifier;
160 m_name = other.m_name;
161 m_description = other.m_description;
162 m_inputFormat = other.m_inputFormat;
163 m_formatString = other.m_formatString;
164 m_partialCharges = other.m_partialCharges;
165 m_electrostatics = other.m_electrostatics;
166 m_inputCjson = other.m_inputCjson;
167 m_elements = other.m_elements;
168 m_valid = other.m_valid;
169 }
170
171 MatrixX ScriptChargeModel::partialCharges(const Core::Molecule& mol) const
172 {
173 MatrixX charges(mol.atomCount(), 1);
174
175 // check to see if we already have them in the molecule
176 charges = mol.partialCharges(m_identifier);
177 // if there's a non-zero charge, then we're done
178 for (unsigned int i = 0; i < charges.rows(); ++i) {
179 if (abs(charges(i, 0)) > 0.00001)
180 return charges;
181 }
182
183 // Create the intermediate format writer
184 std::string intermediate;
185 QScopedPointer<Io::FileFormat> format(createFileFormat(m_inputFormat));
186
187 if (format.isNull()) {
188 appendError("Cannot create file format.");
189 return charges;
190 }
191
192 if (!format->writeString(intermediate, mol)) {
193 appendError(format->error(), false);
194 return charges;
195 }
196
197 QByteArray scriptInput;
198 if (m_interpreter->isPackageMode()) {
199 // Package-mode scripts consume structured JSON from stdin.
200 QJsonObject request;
201 request[m_formatString] = QString::fromStdString(intermediate);
202 if (m_inputCjson) {
203 // Some package features request both the selected input format and a
204 // parsed cjson molecule object.
205 std::string cjson;
206 Io::CjsonFormat cjsonFormat;
207 if (!cjsonFormat.writeString(cjson, mol)) {
208 appendError(cjsonFormat.error(), false);
209 return charges;
210 }
211 QJsonParseError cjsonParseError;
212 QJsonDocument cjsonDoc = QJsonDocument::fromJson(
213 QByteArray::fromStdString(cjson), &cjsonParseError);
214 if (cjsonParseError.error == QJsonParseError::NoError &&
215 cjsonDoc.isObject()) {
216 request["cjson"] = cjsonDoc.object();
217 } else {
218 appendError("Failed to serialize cjson input for charge script.");
219 return charges;
220 }
221 }
222 scriptInput = QJsonDocument(request).toJson(QJsonDocument::Compact);
223 } else {
224 scriptInput = QByteArray::fromStdString(intermediate);
225 }
226
227 // Call the script to convert the file
228 QByteArray result =
229 m_interpreter->execute(QStringList() << "--charges", scriptInput);
230
231 if (m_interpreter->hasErrors()) {
232 foreach (const QString& err, m_interpreter->errorList())
233 appendError(err.toStdString());
234
235 return charges;
236 }
237
238 stripLeadingNonJson(result);
239
240 // parse the result - preferred output is JSON: bare array or {"charges":[]}
241 QList<double> jsonValues;
242 if (parseJsonNumericArray(
243 result, QStringLiteral("charges"), jsonValues,
244 static_cast<int>(charges.rows()),
245 [this](const QString& msg) { appendError(msg.toStdString()); })) {
246 for (int i = 0; i < jsonValues.size(); ++i)
247 charges(i, 0) = jsonValues[i];
248 return charges;
249 }
250
251 // Backward compatibility: accept legacy line-delimited numeric output.
252 QString resultString = QString::fromUtf8(result);
253 QStringList lines = resultString.split('\n');
254 // keep a separate atom counter in case there is other text
255 // (e.g., "normal termination, etc.")
256 unsigned int atom = 0;
257 for (const auto& line : lines) {
258 if (line.isEmpty())
259 continue;
260
261 if (atom >= static_cast<unsigned int>(charges.rows())) {
262 appendError("Too many charges in script output.");
263 break;
264 }
265
266 bool ok;
267 double charge = line.toDouble(&ok);
268 if (!ok) {
269 appendError("Invalid charge: " + line.toStdString());
270 continue;
271 }
272
273 charges(atom, 0) = charge;
274 ++atom;
275 }
276 return charges;
277 }
278
279 MatrixX ScriptChargeModel::partialCharges(Core::Molecule& mol) const
280 {
281 // just create a copy of the const version
282 MatrixX charges = partialCharges(static_cast<const Core::Molecule&>(mol));
283 // cache them
284 mol.setPartialCharges(m_identifier, charges);
285 return charges;
286 }
287
288 double ScriptChargeModel::potential(Core::Molecule& mol,
289 const Vector3& point) const
290 {
291 // just create an array of size one and run that
292 Core::Array<Vector3> points;
293 points.push_back(point);
294
295 Core::Array<double> results = potentials(mol, points);
296 if (results.size() == 1)
297 return results[0];
298 else
299 return 0.0;
300 }
301
302 Core::Array<double> ScriptChargeModel::potentials(
303 Core::Molecule& mol, const Core::Array<Vector3>& points) const
304 {
305 // first off, if the script doesn't handle potentials
306 // call the parent class (default method from partial charges)
307 if (!m_electrostatics)
308 return Calc::ChargeModel::potentials(mol, points);
309
310 // Create the intermediate format writer
311 std::string intermediate;
312 QScopedPointer<Io::FileFormat> format(createFileFormat(m_inputFormat));
313 Core::Array<double> potentials(points.size(), 0.0);
314
315 if (format.isNull()) {
316 appendError("Cannot create file format.");
317 return potentials;
318 }
319
320 if (!format->writeString(intermediate, mol)) {
321 appendError(format->error(), false);
322 return potentials;
323 }
324
325 // now we stuff the file and the points into JSON
326 QJsonObject json;
327 json[m_formatString] = QString::fromStdString(intermediate);
328 if (m_inputCjson) {
329 // Mirror the package-mode charge request and include cjson when requested.
330 std::string cjson;
331 Io::CjsonFormat cjsonFormat;
332 if (!cjsonFormat.writeString(cjson, mol)) {
333 appendError(cjsonFormat.error(), false);
334 return potentials;
335 }
336 QJsonParseError cjsonParseError;
337 QJsonDocument cjsonDoc = QJsonDocument::fromJson(
338 QByteArray::fromStdString(cjson), &cjsonParseError);
339 if (cjsonParseError.error == QJsonParseError::NoError &&
340 cjsonDoc.isObject()) {
341 json["cjson"] = cjsonDoc.object();
342 } else {
343 appendError("Failed to serialize cjson input for potential script.");
344 return potentials;
345 }
346 }
347 QJsonArray pointsArray;
348 for (const auto& i : points) {
349 QJsonArray point;
350 point << i.x() << i.y() << i.z();
351 pointsArray.append(point);
352 }
353 json["points"] = pointsArray;
354 QJsonDocument doc(json);
355
356 // Call the script to convert the file
357 QByteArray result =
358 m_interpreter->execute(QStringList() << "--potentials", doc.toJson());
359
360 if (m_interpreter->hasErrors()) {
361 foreach (const QString& err, m_interpreter->errorList())
362 appendError(err.toStdString());
363 return potentials;
364 }
365
366 stripLeadingNonJson(result);
367
368 // Preferred output is JSON: bare array or {"potentials":[...]}
369 QList<double> jsonValues;
370 if (parseJsonNumericArray(
371 result, QStringLiteral("potentials"), jsonValues,
372 static_cast<int>(potentials.size()),
373 [this](const QString& msg) { appendError(msg.toStdString()); })) {
374 for (int i = 0; i < jsonValues.size(); ++i)
375 potentials[i] = jsonValues[i];
376 return potentials;
377 }
378
379 // Backward compatibility: accept legacy line-delimited numeric output.
380 QString resultString = QString::fromUtf8(result);
381 QStringList lines = resultString.split('\n');
382 unsigned int point = 0;
383 for (const QString& line : lines) {
384 if (line.isEmpty())
385 continue;
386
387 if (point >= potentials.size()) {
388 appendError("Too many potentials in script output.");
389 break;
390 }
391
392 bool ok;
393 double potential = line.toDouble(&ok);
394 if (!ok) {
395 appendError("Invalid potential: " + line.toStdString());
396 continue;
397 }
398 potentials[point] = potential;
399 ++point;
400 }
401
402 return potentials;
403 }
404
405 ScriptChargeModel::Format ScriptChargeModel::stringToFormat(
406 const std::string& str)
407 {
408 if (str == "cjson")
409 return Cjson;
410 else if (str == "cml")
411 return Cml;
412 else if (str == "mdl" || str == "mol")
413 return Mdl;
414 else if (str == "sdf")
415 return Sdf;
416 else if (str == "pdb")
417 return Pdb;
418 else if (str == "xyz")
419 return Xyz;
420 return NotUsed;
421 }
422
423 Io::FileFormat* ScriptChargeModel::createFileFormat(
424 ScriptChargeModel::Format fmt)
425 {
426 switch (fmt) {
427 case Cjson:
428 return new Io::CjsonFormat;
429 case Cml:
430 return new Io::CmlFormat;
431 case Mdl:
432 return new Io::MdlFormat;
433 case Pdb:
434 return new Io::PdbFormat;
435 case Sdf:
436 return new Io::SdfFormat;
437 case Xyz:
438 return new Io::XyzFormat;
439 default:
440 case NotUsed:
441 return nullptr;
442 }
443 }
444
445 void ScriptChargeModel::resetMetaData()
446 {
447 m_valid = false;
448 m_partialCharges = false;
449 m_electrostatics = false;
450 m_inputCjson = false;
451 m_inputFormat = NotUsed;
452 m_identifier.clear();
453 m_name.clear();
454 m_description.clear();
455 m_formatString.clear();
456 }
457
458 void ScriptChargeModel::readMetaData()
459 {
460 resetMetaData();
461
462 QByteArray output(m_interpreter->execute(QStringList() << "--metadata"));
463
464 if (m_interpreter->hasErrors()) {
465 qWarning() << "Error retrieving metadata for charge script:"
466 << scriptFilePath() << "\n"
467 << m_interpreter->errorList();
468 return;
469 }
470
471 QJsonParseError parseError;
472 QJsonDocument doc(QJsonDocument::fromJson(output, &parseError));
473 if (parseError.error != QJsonParseError::NoError) {
474 qWarning() << "Error parsing metadata for charge script:"
475 << scriptFilePath() << "\n"
476 << parseError.errorString() << "(at offset" << parseError.offset
477 << ")";
478 return;
479 }
480
481 if (!doc.isObject()) {
482 qWarning() << "Error parsing metadata for charge script:"
483 << scriptFilePath() << "\nResult is not a JSON object:\n"
484 << output;
485 return;
486 }
487
488 const QJsonObject metaData(doc.object());
489
490 // Read required inputs first.
491 std::string identifierTmp;
492 if (!parseString(metaData, "identifier", identifierTmp)) {
493 qWarning() << "Error parsing metadata for charge script:"
494 << scriptFilePath() << "\n"
495 << "Error parsing required member 'identifier'"
496 << "\n"
497 << output;
498 return;
499 }
500 m_identifier = identifierTmp;
501
502 std::string nameTmp;
503 if (!parseString(metaData, "name", nameTmp)) {
504 qWarning() << "Error parsing metadata for charge script:"
505 << scriptFilePath() << "\n"
506 << "Error parsing required member 'name'"
507 << "\n"
508 << output;
509 return;
510 }
511 m_name = nameTmp;
512
513 std::string descriptionTmp;
514 parseString(metaData, "description", descriptionTmp);
515 m_description = descriptionTmp; // optional
516
517 Format inputFormatTmp = NotUsed;
518 std::string inputFormatStrTmp;
519 if (!parseString(metaData, "inputFormat", inputFormatStrTmp)) {
520 qWarning() << "Error parsing metadata for charge script:"
521 << scriptFilePath() << "\n"
522 << "Member 'inputFormat' required for writable formats."
523 << "\n"
524 << output;
525 return;
526 }
527 m_formatString = inputFormatStrTmp.c_str(); // for the json key
528
529 // Validate the input format
530 inputFormatTmp = stringToFormat(inputFormatStrTmp);
531 if (inputFormatTmp == NotUsed) {
532 qWarning() << "Error parsing metadata for charge script:"
533 << scriptFilePath() << "\n"
534 << "Member 'inputFormat' not recognized:"
535 << inputFormatStrTmp.c_str()
536 << "\nValid values are cjson, cml, mdl/sdf, pdb, or xyz.\n"
537 << output;
538 return;
539 }
540 m_inputFormat = inputFormatTmp;
541
542 // check if we handle charges and/or potentials
543 if (!metaData["charges"].isBool()) {
544 return; // not valid
545 }
546 m_partialCharges = metaData["charges"].toBool();
547 if (!metaData["potential"].isBool()) {
548 return; // not valid
549 }
550 m_electrostatics = metaData["potential"].toBool();
551 if (metaData["inputCjson"].isBool())
552 m_inputCjson = metaData["inputCjson"].toBool();
553
554 // get the element mask
555 // (if it doesn't exist, the default is no elements anyway)
556 m_valid = parseElements(metaData);
557 }
558
559 bool ScriptChargeModel::parseString(const QJsonObject& ob, const QString& key,
560 std::string& str)
561 {
562 if (!ob[key].isString())
563 return false;
564
565 str = ob[key].toString().toStdString();
566
567 return !str.empty();
568 }
569
570 void ScriptChargeModel::processElementString(const QString& str)
571 {
572 // parse the QString
573 // first turn any commas into whitespace
574 QString str2(str);
575 str2.replace(',', ' ');
576 // then split on whitespace
577 QStringList strList =
578 str2.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
579 foreach (QString sstr, strList) {
580 // these should be numbers or ranges (e.g., 1-84)
581 if (sstr.contains('-')) {
582 // range, so split on the dash
583 QStringList strList2 = sstr.split('-');
584 if (strList2.size() != 2)
585 return;
586
587 // get the two numbers
588 bool ok;
589 int start = strList2[0].toInt(&ok);
590 if (!ok || start < 1 || start > 119)
591 return;
592 int end = strList2[1].toInt(&ok);
593 if (!ok || end < 1 || end > 119)
594 return;
595 for (int i = start; i <= end; ++i)
596 m_elements.set(i);
597 }
598
599 bool ok;
600 int i = sstr.toInt(&ok);
601 if (!ok || i < 1 || i > 119)
602 return;
603
604 m_elements.set(i);
605 }
606 }
607
608 bool ScriptChargeModel::parseElements(const QJsonObject& ob)
609 {
610 m_elements.reset();
611
612 // we could either get a string or an array (of numbers)
613 if (ob["elements"].isString()) {
614 auto str = ob["elements"].toString();
615 processElementString(str);
616
617 } else if (ob["elements"].isArray()) {
618 QJsonArray arr = ob["elements"].toArray();
619 for (auto&& i : arr) {
620 if (i.isString()) {
621 processElementString(i.toString());
622 } else if (i.isDouble()) {
623 int element = i.toInt();
624 if (element >= 1 && element <= 119) // check the range
625 m_elements.set(element);
626 }
627 }
628 }
629 return true;
630 }
631
632 } // namespace Avogadro::QtPlugins