Debian Codegraph @

avogadro/molequeue/inputgenerator.h

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 #ifndef AVOGADRO_MOLEQUEUE_INPUTGENERATOR_H
7 #define AVOGADRO_MOLEQUEUE_INPUTGENERATOR_H
8
9 #include "avogadromolequeueexport.h"
10 #include <QtCore/QObject>
11
12 #include <avogadro/core/avogadrocore.h>
13
14 #include <QtCore/QJsonObject>
15 #include <QtCore/QMap>
16 #include <QtCore/QStringList>
17
18 #include <QRegularExpression>
19
20 class QJsonDocument;
21 class QProcess;
22 class QTextCharFormat;
23
24 namespace Avogadro {
25
26 namespace Core {
27 class Molecule;
28 }
29
30 namespace QtGui {
31 class GenericHighlighter;
32 class PythonScript;
33 } // namespace QtGui
34
35 namespace MoleQueue {
36 /**
37 * @class InputGenerator inputgenerator.h <avogadro/molequeue/inputgenerator.h>
38 * @brief The InputGenerator class provides an interface to input generator
39 * scripts.
40 * @sa InputGeneratorWidget
41 *
42 * The QuantumInput extension provides a scriptable method for users to add
43 * custom input generators to Avogadro. By writing an executable that implements
44 * the interface defined below, new input generators can be created faster and
45 * easier than writing full Avogadro extensions.
46 *
47 * Script Entry Points
48 * ===================
49 *
50 * The script must handle the following command-line arguments:
51 * - `--debug` Enable extra debugging output. Used with other commands.
52 * It is not required that the script support extra debugging, but it should
53 * not crash when this option is passed.
54 * - `--print-options` Print the available options supported by the
55 * script, e.g. simulation parameters, etc. See below for more details.
56 * - `--generate-input` Read an option block from stdin and print
57 * input files to stdout. See below for more details.
58 * - `--display-name` Print a user-friendly name for the input generator.
59 * This is used in the GUI for menu entries, window titles, etc.
60 *
61 * Specifying parameters with `--print-options`
62 * ============================================
63 *
64 * The format of the `--print-options` output must be a JSON object of
65 * the following form:
66 ~~~{.js}
67 {
68 "userOptions": {
69 ...
70 },
71 "highlightStyles": [
72 {
73 "style": "Descriptive name",
74 "rules": [
75 {
76 "patterns": [ ... ],
77 "format": { ... }
78 },
79 ...
80 ],
81 },
82 ...
83 ],
84 "inputMoleculeFormat": "cjson"
85 }
86 ~~~
87 * The `userOptions` block contains a JSON object keyed with option names
88 * (e.g. "First option name"), which are used in the GUI to label simulation
89 * parameter settings. Various parameter types are supported:
90 *
91 * Fixed Mutually-Exclusive Parameter Lists
92 * ----------------------------------------
93 *
94 * Parameters that have a fixed number of mutually-exclusive string values will
95 * be presented using a QComboBox. Such a parameter can be specified in the
96 * `userOptions` block as:
97 ~~~{.js}
98 {
99 "userOptions": {
100 "Parameter Name": {
101 "type": "stringList",
102 "values": ["Option 1", "Option 2", "Option 3"],
103 "default": 0
104 }
105 }
106 }
107 ~~~
108 * Here, `Parameter Name` is the label that will be displayed in the GUI as a
109 * label next to the combo box.
110 * The array of strings in `values` will be used as the available entries in
111 * the combo box in the order they are written.
112 * `default` is a zero-based index into the `values` array and indicates
113 * which value should be initially selected by default.
114 *
115 * Short Free-Form Text Parameters
116 * -------------------------------
117 *
118 * A short text string can be requested (e.g. for the "title" of an
119 * optimization) via:
120 ~~~{.js}
121 {
122 "userOptions": {
123 "Parameter Name": {
124 "type": "string",
125 "default": "blah blah blah"
126 }
127 }
128 }
129 ~~~
130 * This will add a QLineEdit to the GUI, initialized with the text specified by
131 * `default`.
132 *
133 * Existing files
134 * --------------
135 *
136 * An input generator can ask for the absolute path to an existing file using
137 * the following option block:
138 ~~~{.js}
139 {
140 "userOptions": {
141 "Parameter Name": {
142 "type": "filePath",
143 "default": "/path/to/some/file"
144 }
145 }
146 }
147 ~~~
148 * This will add an Avogadro::QtGui::FileBrowseWidget to the GUI, initialized to
149 * the file pointed to by default.
150 *
151 * Clamped Integer Values
152 * ----------------------
153 *
154 * Scripts may request integer values from a specified range by adding a
155 * user-option of the following form:
156 ~~~{.js}
157 {
158 "userOptions": {
159 "Parameter Name": {
160 "type": "integer",
161 "minimum": -5,
162 "maximum": 5,
163 "default": 0,
164 "prefix": "some text ",
165 "suffix": " units"
166 }
167 }
168 }
169 ~~~
170 * This block will result in a QSpinBox, configured as follows:
171 * - `minimum` and `maximum` indicate the valid range of integers for the
172 * parameter.
173 * - `default` is the integer value that will be shown initially.
174 * - (optional) `prefix` and `suffix` are used to insert text before or
175 * after the integer value in the spin box.
176 * This is handy for specifying units.
177 * Note that any prefix or suffix will be stripped out of the corresponding
178 * entry in the call to `--generate-input`, and just the raw integer value
179 * will be sent.
180 *
181 * Boolean Parameters
182 * ------------------
183 *
184 * If a simple on/off value is needed, a boolean type option can be requested:
185 ~~~{.js}
186 {
187 "userOptions": {
188 "Parameter Name": {
189 "type": "boolean",
190 "default": true,
191 }
192 }
193 }
194 ~~~
195 * This will result in a QCheckBox in the dynamically generated GUI, with
196 * the initial check state shown in `default`.
197 *
198 * Special Parameters
199 * ------------------
200 *
201 * Some parameters are common to most calculation codes.
202 * If the following parameter names are found, they will be handled specially
203 * while creating the GUI.
204 * It is recommended to use the names below for these options to provide a
205 * consistent interface and ensure that MoleQueue job staging uses correct
206 * values where appropriate.
207 *
208 * | Option name | type | description |
209 * | :----------------: | :--------: |
210 :------------------------------------------------------------------ |
211 * | "Title" | string | Input file title comment, MoleQueue job
212 description. |
213 * | "Filename Base" | string | Input file base name, e.g. "job" in
214 "job.inp". |
215 * | "Processor Cores" | integer | Number of cores to use. Will be passed to
216 MoleQueue. |
217 * | "Calculation Type" | stringList | Type of calculation, e.g. "Single Point"
218 or "Equilibrium Geometry". |
219 * | "Theory" | stringList | Levels of QM theory, e.g. "RHF", "B3LYP",
220 "MP2", "CCSD", etc. |
221 * | "Basis" | stringList | Available basis sets, e.g. "STO-3G",
222 "6-31G**", etc. |
223 * | "Charge" | integer | Charge on the system. |
224 * | "Multiplicity" | integer | Spin multiplicity of the system. |
225 *
226 * Syntax Highlighting
227 * -------------------
228 *
229 * Rules for syntax highlighting can be specified as a collection of regular
230 * expressions or wildcard patterns and text format specifications in the
231 * "highlightRules" array. The `highlightRules` format is:
232 ~~~{.js}
233 "highlightStyles": [
234 {
235 "style": "Style 1",
236 "rules": [ (list of highlight rules, see below) ],
237 },
238 {
239 "style": "Style 2",
240 "rules": [ (list of highlight rules, see below) ],
241 },
242 ...
243 ],
244 ~~~
245 * The `style` name is unique to the style object, and used to associate a
246 * set of highlighting rules with particular output files. See the
247 * `--generate-input` documentation for more details.
248 *
249 * The general form of a highlight rule is:
250 ~~~{.js}
251 {
252 "patterns": [
253 { "regexp": "^Some regexp?$" },
254 { "wildcard": "A * wildcard expression" },
255 { "string": "An exact string to match.",
256 "caseSensitive": false
257 },
258 ...
259 ],
260 "format": {
261 "preset": "<preset name>"
262 }
263 }
264 ~~~
265 *
266 * or,
267 *
268 ~~~{.js}
269 {
270 "patterns": [
271 ...
272 ],
273 "format": {
274 "foreground": [ 255, 128, 64 ],
275 "background": [ 0, 128, 128 ],
276 "attributes": ["bold", "italic", "underline"],
277 "family": "serif"
278 }
279 }
280 ~~~
281 *
282 * The `patterns` array contains a collection of fixed strings, wildcard
283 * expressions, and regular expressions (using the QRegularExpression syntax
284 * flavor, see the QRegularExpression documentation) that are used to identify
285 * strings that should be formatted.
286 * There must be one of the following members present in each pattern object:
287 * - `regexp` A QRegularExpresion-style regular expression. If no capture groups
288 * ("(...)") are defined, the entire match is formatted. If one or more
289 * capture groups, only the captured texts will be marked.
290 * - `wildcard` A wildcard expression
291 * - `string` An exact string to match.
292 *
293 * Any pattern object may also set a boolean `caseSensitive` member to indicate
294 * whether the match should consider character case. If omitted, a
295 * case-sensitive match is assumed.
296 *
297 * The preferred form of the `format` member is simply a specification of a
298 * preset format.
299 * This allows for consistent color schemes across input generators.
300 * The recognized presets are:
301 * - `"title"`: A human readable title string.
302 * - `"keyword"`: directives defined by the target input format specification
303 * to have special meaning, such as tags indicating where coordinates are
304 * to be found.
305 * - `"property"`: A property of the simulation, such as level of theory, basis
306 * set, minimization method, etc.
307 * - `"literal"`: A numeric literal (i.e. a raw number, such as a coordinate).
308 * - `"comment"`: Sections of the input that are ignored by the simulation code.
309 *
310 * If advanced formatting is desired, the second form of the `format` member
311 * allows fine-tuning of the font properties:
312 * - `foreground` color as an RGB tuple, ranged 0-255
313 * - `background` color as an RGB tuple, ranged 0-255
314 * - `attributes` array of font attributes, valid strings are `"bold"`,
315 * `"italic"`, or `"underline"`
316 * - `family` of font. Valid values are `"serif"`, `"sans"`, or `"mono"`
317 *
318 * Any of the font property members may be omitted and default QTextCharFormat
319 * settings will be substituted.
320 *
321 * The input generator extension will apply the entries in the `highlightRules`
322 * object to the text in the order they appear. Thus, later rules will
323 * override the formatting of earlier rules should a conflict arise.
324 *
325 * Requesting Full Structure of Current Molecule
326 * ---------------------------------------------
327 *
328 * The `inputMoleculeFormat` is optional, and can be used to request a
329 * representation of the current molecule's geometry when
330 * `--generate-input` is called. The corresponding value
331 * indicates the format of the molecule that the script expects. If this value
332 * is omitted, no representation of the structure will be provided.
333 *
334 * @note Currently valid options for inputMoleculeFormat are "cjson" for
335 * Chemical JSON or "cml" for Chemical Markup Language.
336 *
337 * Handling User Selections: `--generate-input`
338 * ============================================
339 *
340 * When `--generate-input` is passed, the information needed to generate
341 * the input file will be written to the script's standard input
342 * channel as JSON string of the following form:
343 ~~~{.js}
344 {
345 "cjson": {...},
346 "options": {
347 "First option name": "Value 2",
348 "Second option name": "Value 1",
349 ...
350 }
351 }
352 ~~~
353 * The `cjson` entry will contain a Chemical JSON representation
354 * of the molecule if `inputMoleculeFormat` is set to "cjson" in the
355 * `--print-options` output.
356 * Similarly, a `cml` entry and CML string will exist if a Chemical Markup
357 * Language representation was requested.
358 * It will be omitted entirely if `inputMoleculeFormat` is not set.
359 * The `options` block contains key/value
360 * pairs for each of the options specified in the `userOptions` block of the
361 * `--print-options` output.
362 *
363 * If the script is called with `--generate-input`, it must write a JSON
364 * string to standard output with the following format:
365 ~~~{.js}
366 {
367 "files": [
368 {
369 "filename": "file1.ext",
370 "contents": "...",
371 "highlightStyles": [ ... ]
372 },
373 {
374 "filename": "file2.ext",
375 "filePath": "/path/to/file/on/local/filesystem"
376 },
377 ...
378 ],
379 "warnings": ["First warning.", "Second warning.", ... ],
380 "mainFile": "file2.ext"
381 }
382 ~~~
383 * The `files` block is an array of objects, which define the actual input
384 * files. The `filename` member provides the name of the file, and
385 * either `contents` or `filePath` provide the text that goes into the file.
386 * The `contents` string will be used as the file contents, and `filePath`
387 * should contain an absolute path to a file on the filesystem to read and use
388 * as the input file contents.
389 * The optional `highlightStyles` member is an array of strings describing any
390 * highlight styles to apply to the file (see `--print-options` documentation).
391 * Each string in this array must match a `style` description in a highlighting
392 * rule in the `--print-options` output.
393 * Zero or more highlighting styles may be applied to any file.
394 * The order of the files in the
395 * GUI will match the order of the files in the array, and the first file will
396 * be displayed first.
397 *
398 * The `warnings` member provides an array of strings that describe non-fatal
399 * warnings to be shown to the users. This is useful for describing
400 * the resolution of conflicting options, e.g. "Ignoring basis set for
401 * semi-empirical calculation.". This member is optional and should be omitted
402 * if no warnings are present.
403 *
404 * The `mainFile` member points to the primary input file for a calculation.
405 * This is the file that will be used as a command line argument when executing
406 * the simulation code (if applicable), and used by MoleQueue to set the
407 * `$$inputFileName$$` and `$$inputFileBaseName$$` input template keywords.
408 * This is optional; if present, the filename must exist in the `files` array.
409 * If absent and only one file is specified in `files`, the single input file
410 * will be used. Otherwise, the main file will be left unspecified.
411 *
412 * Automatic Generation of Geometry
413 * ================================
414 *
415 * The generation of molecular geometry descriptions may be skipped in the
416 * script and deferred to the InputGenerator class by use of a special keyword.
417 * The "contents" string may contain a keyword of the form
418 ~~~
419 $$coords:[coordSpec]$$
420 ~~~
421 * where `[coordSpec]` is a sequence of characters.
422 * The characters in `[coordSpec]` indicate the information needed about each
423 * atom in the coordinate block.
424 * See the CoordinateBlockGenerator documentation for a list of recognized
425 * characters.
426 *
427 * Other keywords that can be used in the input files are:
428 * - `$$atomCount$$`: Number of atoms in the molecule.
429 * - `$$bondCount$$`: Number of bonds in the molecule.
430 *
431 * Error Handling
432 * ==============
433 *
434 * In general, these scripts should be written robustly so that they will not
435 * fail under normal circumstances. However, if for some reason an error
436 * occurs that must be reported to the user, simply write the error message to
437 * standard output as plain text (i.e. not JSON), and it will be shown to the
438 * user.
439 *
440 * Debugging
441 * =========
442 *
443 * Debugging may be enabled by defining AVO_QM_INPUT_DEBUG in the process's
444 * environment. This will cause the <tt>--debug</tt> option to be passed in
445 * all calls to generator scripts, and will print extra information to the
446 * qDebug() stream from within avogadro. The script is free to handle the
447 * debug flag as the author wishes.
448 */
449 class AVOGADROMOLEQUEUE_EXPORT InputGenerator : public QObject
450 {
451 Q_OBJECT
452 public:
453 /**
454 * Constructor
455 * @param scriptFilePath_ Absolute path to generator script.
456 */
457 explicit InputGenerator(const QString& scriptFilePath_,
458 QObject* parent_ = nullptr);
459 explicit InputGenerator(QObject* parent_ = nullptr);
460 ~InputGenerator() override = default;
461
462 /**
463 * @return True if debugging is enabled.
464 */
465 bool debug() const;
466
467 /**
468 * @return True if the generator is configured with a valid script.
469 */
470 bool isValid() const;
471
472 /**
473 * Query the script for the available options (<tt>--generate-options</tt>)
474 * and return the output as a JSON object.
475 * @note The results will be cached the first time this function is called
476 * and reused in subsequent calls.
477 * @note If an error occurs, the error string will be set. Call hasErrors()
478 * to check for success, and errorString() or errorList() to get a
479 * user-friendly description of the error.
480 */
481 QJsonObject options() const;
482
483 /**
484 * Return a user-friendly name for the generator.
485 * @note In package mode this is taken from package metadata. For legacy
486 * script mode, the value is queried from <tt>--display-name</tt>.
487 * @note The results will be cached the first time this function is called
488 * and reused in subsequent calls.
489 * @note If an error occurs, the error string will be set. Call hasErrors()
490 * to check for success, and errorString() or errorList() to get a
491 * user-friendly description of the error.
492 */
493 QString displayName() const;
494
495 /**
496 * @return The path to the generator file.
497 */
498 QString scriptFilePath() const;
499
500 /**
501 * Set the path to the input generator script file. This will reset any
502 * cached data held by this class.
503 */
504 void setScriptFilePath(const QString& scriptFile);
505
506 /**
507 * Pre-load options from a JSON object, bypassing the script's
508 * --print-options call. Used by package-based generators that store
509 * options in a separate JSON file declared in pyproject.toml.
510 */
511 void setOptions(const QJsonObject& options);
512
513 /**
514 * Access to the underlying PythonScript interpreter for direct
515 * configuration (e.g. setting package mode via setPackageInfo()).
516 * @{
517 */
518 QtGui::PythonScript& interpreter() { return *m_interpreter; }
519 const QtGui::PythonScript& interpreter() const { return *m_interpreter; }
520 /** @} */
521
522 /**
523 * Clear any cached data and return to an uninitialized state.
524 */
525 void reset();
526
527 /**
528 * Request input files from the script using the supplied options object and
529 * molecule. See the class documentation for details on the @p options_
530 * object format.
531 *
532 * If the files are generated successfully, use the functions
533 * numberOfInputFiles(), fileNames(), and fileContents() to retrieve them.
534 *
535 * @return true on success and false on failure.
536 * @note If an error occurs, the error string will be set. Call hasErrors()
537 * to check for success, and errorString() or errorList() to get a
538 * user-friendly description of the error.
539 */
540 bool generateInput(const QJsonObject& options_, const Core::Molecule& mol);
541
542 /**
543 * @return The number of input files stored by generateInput().
544 * @note This function is only valid after a successful call to
545 * generateInput().
546 */
547 int numberOfInputFiles() const;
548
549 /**
550 * @return A list of filenames created by generateInput().
551 * @note This function is only valid after a successful call to
552 * generateInput().
553 */
554 QStringList fileNames() const;
555
556 /**
557 * @return The "main" input file of the collection. This is the input file
558 * used by MoleQueue to determine the $$inputFileName$$ and
559 * $$inputFileBaseName$$ keywords.
560 * @note This function is only valid after a successful call to
561 * generateInput().
562 */
563 QString mainFileName() const;
564
565 /**
566 * @return A file contents corresponding to @p fileName. Must call
567 * generateInput() first.
568 * @sa fileNames
569 */
570 QString fileContents(const QString& fileName) const;
571
572 /**
573 * @return A syntax highlighter for the file @a fileName. Must call
574 * generateInput() first. The caller takes ownership of the returned object.
575 * If no syntax highlighter is defined, this function returns nullptr.
576 * @sa fileNames
577 */
578 QtGui::GenericHighlighter* createFileHighlighter(
579 const QString& fileName) const;
580
581 /**
582 * @return True if an error is set.
583 */
584 bool hasErrors() const { return !m_errors.isEmpty(); }
585
586 /**
587 * Reset the error counter.
588 */
589 void clearErrors() { m_errors.clear(); }
590
591 /**
592 * @return A QStringList containing all errors that occurred in the last call
593 * to the input generator script.
594 */
595 QStringList errorList() const { return m_errors; }
596
597 /**
598 * @return A QStringList containing all warnings returned by the input
599 * generator script in the last call to generateInput. These are
600 * script-specific warnings.
601 */
602 QStringList warningList() const { return m_warnings; }
603
604 public slots:
605 /**
606 * Enable/disable debugging.
607 */
608 void setDebug(bool d);
609
610 private:
611 QtGui::PythonScript* m_interpreter;
612
613 void setDefaultPythonInterpreter();
614 QByteArray execute(const QStringList& args,
615 const QByteArray& scriptStdin = QByteArray()) const;
616 bool parseJson(const QByteArray& json, QJsonDocument& doc) const;
617 QString processErrorString(const QProcess& proc) const;
618 bool insertMolecule(QJsonObject& json, const Core::Molecule& mol) const;
619 QString generateCoordinateBlock(const QString& spec,
620 const Core::Molecule& mol) const;
621 void replaceKeywords(QString& str, const Core::Molecule& mol) const;
622 bool parseHighlightStyles(const QJsonArray& json) const;
623 bool parseRules(const QJsonArray& json,
624 QtGui::GenericHighlighter& highligher) const;
625 bool parseFormat(const QJsonObject& json, QTextCharFormat& format) const;
626 bool parsePattern(const QJsonValue& json, QRegularExpression& pattern) const;
627
628 // File extension of requested molecule format
629 mutable QString m_moleculeExtension;
630 mutable QString m_displayName;
631 mutable QJsonObject m_options;
632 mutable QStringList m_warnings;
633 mutable QStringList m_errors;
634
635 QStringList m_filenames;
636 QString m_mainFileName;
637 QMap<QString, QString> m_files;
638 QMap<QString, QtGui::GenericHighlighter*> m_fileHighlighters;
639
640 mutable QMap<QString, QtGui::GenericHighlighter*> m_highlightStyles;
641 };
642
643 inline bool InputGenerator::isValid() const
644 {
645 displayName();
646 return !hasErrors();
647 }
648
649 } // namespace MoleQueue
650 } // namespace Avogadro
651
652 #endif // AVOGADRO_MOLEQUEUE_INPUTGENERATOR_H