|
AvogadroLibs 2.1.0-20261111
|
The Interface class provides an interface to external scripts. More...
#include <interfacescript.h>
Public Slots | |
| void | setDebug (bool d) |
| void | commandFinished () |
Signals | |
| void | finished () |
| void | progress (const QString &message, int value, int maximum) |
Public Member Functions | |
| InterfaceScript (const QString &scriptFilePath_, QObject *parent_=nullptr) | |
| InterfaceScript (QObject *parent_=nullptr) | |
| bool | debug () const |
| bool | isValid () const |
| QJsonObject | options () const |
| QString | displayName () const |
| QString | menuPath () const |
| QString | scriptFilePath () const |
| void | setScriptFilePath (const QString &scriptFile) |
| void | reset () |
| void | setOptionsJson (const QJsonObject &opts) |
| bool | runCommand (const QJsonObject &options_, Core::Molecule *mol) |
| void | setCamera (const Matrix4f &modelView, const Matrix4f &projection) |
| bool | processCommand (Core::Molecule *mol) |
| bool | generateInput (const QJsonObject &options_, const Core::Molecule &mol) |
| int | numberOfInputFiles () const |
| QStringList | fileNames () const |
| QString | mainFileName () const |
| QString | fileContents (const QString &fileName) const |
| QtGui::GenericHighlighter * | createFileHighlighter (const QString &fileName) const |
| bool | hasErrors () const |
| void | clearErrors () |
| QStringList | errorList () const |
| QStringList | warningList () const |
| PythonScript & | interpreter () |
| const PythonScript & | interpreter () const |
Protected Member Functions | |
| bool | parseJson (const QByteArray &json, QJsonDocument &doc) const |
| QString | generateCoordinateBlock (const QString &spec, const Core::Molecule &mol) const |
| void | replaceKeywords (QString &str, const Core::Molecule &mol, const QJsonObject &options) const |
| QString | generateZMatrixBlock (const QString &spec, const Core::Molecule &mol, bool padded) const |
| bool | parseHighlightStyles (const QJsonArray &json) const |
| bool | parseRules (const QJsonArray &json, QtGui::GenericHighlighter &highligher) const |
| bool | parseFormat (const QJsonObject &json, QTextCharFormat &format) const |
| bool | parsePattern (const QJsonValue &json, QRegularExpression &pattern) const |
<avogadro/molequeue/interfacescript.h>
The QuantumInput extension provides a scriptable method for users to add custom input generators to Avogadro. By writing an executable that implements the interface defined below, new input generators can be created faster and easier than writing full Avogadro extensions.
The script must handle the following command-line arguments:
The format of the --print-options output must be a JSON object of the following form:
The userOptions block contains a JSON object keyed with option names (e.g. "First option name"), which are used in the GUI to label simulation parameter settings. Various parameter types are supported:
Parameters that have a fixed number of mutually-exclusive string values will be presented using a QComboBox. Such a parameter can be specified in the userOptions block as:
Here, Parameter Name is the label that will be displayed in the GUI as a label next to the combo box. The array of strings in values will be used as the available entries in the combo box in the order they are written. default is a zero-based index into the values array and indicates which value should be initially selected by default.
A short text string can be requested (e.g. for the "title" of an optimization) via:
This will add a QLineEdit to the GUI, initialized with the text specified by default.
An input generator can ask for the absolute path to an existing file using the following option block:
This will add an Avogadro::QtGui::FileBrowseWidget to the GUI, initialized to the file pointed to by default.
Scripts may request integer values from a specified range by adding a user-option of the following form:
This block will result in a QSpinBox, configured as follows:
If a simple on/off value is needed, a boolean type option can be requested:
This will result in a QCheckBox in the dynamically generated GUI, with the initial check state shown in default.
Some parameters are common to most calculation codes. If the following parameter names are found, they will be handled specially while creating the GUI. It is recommended to use the names below for these options to provide a consistent interface and ensure that MoleQueue job staging uses correct values where appropriate.
| Option name | type | description | | :-------------—: | :-----—: | :---------------------------------------------------------------— | | "Title" | string | Input file title comment, MoleQueue job description. | | "Filename Base" | string | Input file base name, e.g. "job" in "job.inp". | | "Processor Cores" | integer | Number of cores to use. Will be passed to MoleQueue. | | "Calculation Type" | stringList | Type of calculation, e.g. "Single Point" or "Equilibrium Geometry". | | "Theory" | stringList | Levels of QM theory, e.g. "RHF", "B3LYP", "MP2", "CCSD", etc. | | "Basis" | stringList | Available basis sets, e.g. "STO-3G", "6-31G**", etc. | | "Charge" | integer | Charge on the system. | | "Multiplicity" | integer | Spin multiplicity of the system. |
Rules for syntax highlighting can be specified as a collection of regular expressions or wildcard patterns and text format specifications in the "highlightRules" array. The highlightRules format is:
The style name is unique to the style object, and used to associate a set of highlighting rules with particular output files. See the --generate-input documentation for more details.
The general form of a highlight rule is:
or,
The patterns array contains a collection of fixed strings, wildcard expressions, and regular expressions (using the QRegularExpression syntax flavor, see the QRegularExpression documentation) that are used to identify strings that should be formatted. There must be one of the following members present in each pattern object:
Any pattern object may also set a boolean caseSensitive member to indicate whether the match should consider character case. If omitted, a case-sensitive match is assumed.
The preferred form of the format member is simply a specification of a preset format. This allows for consistent color schemes across input generators. The recognized presets are:
If advanced formatting is desired, the second form of the format member allows fine-tuning of the font properties:
Any of the font property members may be omitted and default QTextCharFormat settings will be substituted.
The input generator extension will apply the entries in the highlightRules object to the text in the order they appear. Thus, later rules will override the formatting of earlier rules should a conflict arise.
The inputMoleculeFormat is optional, and can be used to request a representation of the current molecule's geometry when --generate-input is called. The corresponding value indicates the format of the molecule that the script expects. If this value is omitted, no representation of the structure will be provided.
When --generate-input is passed, the information needed to generate the input file will be written to the script's standard input channel as JSON string of the following form:
The cjson entry will contain a Chemical JSON representation of the molecule if inputMoleculeFormat is set to "cjson" in the --print-options output. Similarly, a cml entry and CML string will exist if a Chemical Markup Language representation was requested. It will be omitted entirely if inputMoleculeFormat is not set. The options block contains key/value pairs for each of the options specified in the userOptions block of the --print-options output.
If the script is called with --generate-input, it must write a JSON string to standard output with the following format:
The files block is an array of objects, which define the actual input files. The filename member provides the name of the file, and either contents or filePath provide the text that goes into the file. The contents string will be used as the file contents, and filePath should contain an absolute path to a file on the filesystem to read and use as the input file contents. The optional highlightStyles member is an array of strings describing any highlight styles to apply to the file (see --print-options documentation). Each string in this array must match a style description in a highlighting rule in the --print-options output. Zero or more highlighting styles may be applied to any file. The order of the files in the GUI will match the order of the files in the array, and the first file will be displayed first.
The warnings member provides an array of strings that describe non-fatal warnings to be shown to the users. This is useful for describing the resolution of conflicting options, e.g. "Ignoring basis set for semi-empirical calculation.". This member is optional and should be omitted if no warnings are present.
The mainFile member points to the primary input file for a calculation. This is the file that will be used as a command line argument when executing the simulation code (if applicable), and used by MoleQueue to set the $$inputFileName$$ and $$inputFileBaseName$$ input template keywords. This is optional; if present, the filename must exist in the files array. If absent and only one file is specified in files, the single input file will be used. Otherwise, the main file will be left unspecified.
The generation of molecular geometry descriptions may be skipped in the script and deferred to the InterfaceScript class by use of a special keyword. The "contents" string may contain a keyword of the form
where [coordSpec] is a sequence of characters. The characters in [coordSpec] indicate the information needed about each atom in the coordinate block. See the CoordinateBlockGenerator documentation for a list of recognized characters.
The geometry may also be written as a z-matrix, with one of
$$zmat$$ leaves out the fields the opening rows cannot carry, which is what Gaussian, NWChem, Q-Chem, Psi4, Molpro and CFOUR expect; $$zmatpad$$ pads them with zeros instead, which is what ORCA's int format, MOPAC and SIESTA expect. Both take the same [coordSpec] alphabet, extended with I, J and K for the three reference rows and R, A and T for the distance, angle and torsion.
A script that can write either form declares a Coordinates string list option whose values are Cartesian and Z-Matrix / Internal, and puts both keywords in its generated file, each on its own line. Whichever form the user did not choose is removed along with its line, so the script itself needs no branch. A file that offers both forms but comes with no Coordinates option gets the Cartesian block, as it always did.
Only a file offering both forms has anything to choose between: where the surrounding syntax differs too much to write both – ORCA's * gzmt block header, say – the script can branch itself and emit just the one keyword, which is then always used. A file whose only geometry keyword is $$zmat$$ therefore gets a z-matrix whatever the option says, rather than losing its geometry altogether.
Writing a z-matrix may require the atoms to be reordered, since every row has to be measured against atoms already placed. When that happens, or when a linear fragment leaves a row's angle or torsion meaningless, a warning is added to the generated input's warning list.
Other keywords that can be used in the input files are:
A long-running command script can report its progress while it works, so the user sees a determinate progress bar and/or a status message instead of an anonymous spinner. To do so, print a single line of JSON to standard output of the form:
All three members are optional:
These lines are consumed by Avogadro and removed from the script's output, so they do not interfere with the final result. A line is only treated as a progress update if it is a complete JSON object on one line with exactly one member, named avogadro, whose value is an object — a pretty-printed result block is never mistaken for one, and any other output the script prints is passed through untouched.
Check AVO_PROGRESS_PROTOCOL before printing an envelope. Avogadro 2.0.0 and earlier read the whole of a script's standard output as a single JSON document, so an extra line makes that parse fail and the command reports an error instead of its result. Avogadro sets this environment variable only when it is reading progress updates, so a script that guards on it keeps working on older releases — it just shows the old indeterminate spinner. The value is the protocol revision, currently 1.
flush=True is required. Python block-buffers standard output when it is connected to a pipe rather than a terminal, so without an explicit flush the updates sit in the buffer and only reach Avogadro when the script exits — by which point the progress bar is gone.
The avogadro.command module (shipped with Avogadro) handles both of these, and is a no-op when progress is unsupported, so it is always safe to call:
That module is not importable in every environment a script may run in (for example a package plugin with its own pixi environment), so scripts are free to copy this self-contained equivalent instead. Do not drop the environment check — without it the script breaks on Avogadro 2.0.0:
Reporting progress is entirely optional; a script that prints nothing until it is finished behaves exactly as it always has.
The progress dialog shown while a command runs has a Cancel button, which kills the script's process. Scripts that write files or otherwise touch state outside Avogadro should be prepared to be terminated partway through.
In general, these scripts should be written robustly so that they will not fail under normal circumstances. However, if for some reason an error occurs that must be reported to the user, simply write the error message to standard output as plain text (i.e. not JSON), and it will be shown to the user.
While a command script runs (--run-command), its standard output and standard error are kept separate: the result and any plain-text error belong on standard output, while standard error is captured for diagnostics and reported if the output cannot be parsed. This means library chatter and warnings on standard error cannot corrupt the result.
Debugging may be enabled by defining AVO_QM_INPUT_DEBUG in the process's environment. This will cause the –debug option to be passed in all calls to generator scripts, and will print extra information to the qDebug() stream from within avogadro. The script is free to handle the debug flag as the author wishes.
|
explicit |
Constructor
| scriptFilePath_ | Absolute path to generator script. |
| bool debug | ( | ) | const |
| bool isValid | ( | ) | const |
| QJsonObject options | ( | ) | const |
Query the script for the available options (–generate-options) and return the output as a JSON object.
| QString displayName | ( | ) | const |
Return a user-friendly name for the script.
| QString menuPath | ( | ) | const |
Query the script for the menu path (–menu-path).
| QString scriptFilePath | ( | ) | const |
| void setScriptFilePath | ( | const QString & | scriptFile | ) |
Set the path to the input generator script file. This will reset any cached data held by this class.
| PythonScript & interpreter | ( | ) |
Access to the underlying PythonScript interpreter for direct configuration (e.g. setting package mode via setPackageInfo()).
| const PythonScript & interpreter | ( | ) | const |
Access to the underlying PythonScript interpreter for direct configuration (e.g. setting package mode via setPackageInfo()).
| void reset | ( | ) |
Clear any cached data and return to an uninitialized state.
| void setOptionsJson | ( | const QJsonObject & | opts | ) |
Set the user options directly from a JSON object, bypassing the –print-options script call. Use this for package-based plugins whose options are stored in a file referenced by the pyproject.toml metadata. Insert "inputMoleculeFormat" into opts before calling if you need a specific molecule format (mirrors the InputGenerator::setOptions() pattern). After calling this, reloadOptions() on the widget will use the cached options without invoking the script.
| bool runCommand | ( | const QJsonObject & | options_, |
| Core::Molecule * | mol ) |
Asynchronously run a command script using the supplied options object and molecule. See the class documentation for details on the options_ object format.
| void setCamera | ( | const Matrix4f & | modelView, |
| const Matrix4f & | projection ) |
Supply the current view camera, so that the CJSON handed to the script carries the orientation the user is actually looking at.
The matrices are written to the CJSON as properties.modelView and properties.projection, the same keys CjsonFormat uses, and they override any stale matrices the molecule kept from the file it was read from. Without this, a script only ever sees the camera as of the last save.
| modelView | The camera's world-to-eye transform. |
| projection | The camera's projection matrix. Its (3, 3) element is 0 for a perspective camera and 1 for an orthographic one. |
| bool processCommand | ( | Core::Molecule * | mol | ) |
Finish processing an asynchronous command script
| bool generateInput | ( | const QJsonObject & | options_, |
| const Core::Molecule & | mol ) |
Request input files from the script using the supplied options object and molecule. See the class documentation for details on the options_ object format.
If the files are generated successfully, use the functions numberOfInputFiles(), fileNames(), and fileContents() to retrieve them.
| int numberOfInputFiles | ( | ) | const |
| QStringList fileNames | ( | ) | const |
| QString mainFileName | ( | ) | const |
| QString fileContents | ( | const QString & | fileName | ) | const |
fileName. Must call generateInput() first. | QtGui::GenericHighlighter * createFileHighlighter | ( | const QString & | fileName | ) | const |
| bool hasErrors | ( | ) | const |
| void clearErrors | ( | ) |
Reset the error counter.
| QStringList errorList | ( | ) | const |
| QStringList warningList | ( | ) | const |
|
signal |
A running command script reported its progress. See the "Progress and Status Updates" section above for the script-side protocol.
| message | Status text to show, or an empty string if the script did not supply one. |
| value | The current step, or -1 if the script did not supply one. |
| maximum | The total number of steps, or -1 if the script did not supply one. |
|
slot |
Enable/disable debugging.
|
slot |
Receives a signal when asynchronous command scripts are finished