3. API Reference

The following sections provide detailed API documentation for the main classes in LAMMPS-GUI. Documentation is generated from Doxygen comments in the source code.

3.1. Main Window

3.1.1. LammpsGui Class

class LammpsGui : public QMainWindow

Main application window for LAMMPS-GUI.

LammpsGui is the central component of the LAMMPS-GUI application, serving as the main window that coordinates all other components. It manages:

  • The code editor for LAMMPS input scripts with syntax highlighting

  • File operations (open, save, recent files)

  • LAMMPS simulation execution and control

  • Visualization windows (images, charts, log output)

  • Application preferences and settings

  • Tutorial wizard for interactive LAMMPS learning

The class integrates with Qt’s main window framework and provides menu actions, toolbars, and status bar components. It uses a LammpsWrapper to interface with the LAMMPS library and LammpsRunner to execute simulations in a separate thread.

See also

CodeEditor for the text editor component

See also

ChartWindow for the charts window component

See also

LogWindow for the log output window component

See also

ImageViewer for the snapshot image window component

See also

SlideShow for the slide show viewer window component

See also

Preferences for the preferences window component

See also

LammpsRunner for simulation execution in a separate thread

See also

LammpsWrapper for LAMMPS library interface

Public Functions

LammpsGui(QWidget *parent = nullptr, const QString &filename = QString(), int width = 0, int height = 0)

Construct the main application window.

Initializes the main window, sets up the UI components, loads preferences, initializes the LAMMPS library, and optionally opens a file if provided.

Parameters:
  • parent – Parent widget (typically nullptr for main window)

  • filename – Optional file to open on startup

  • width – Optional main editor window width override

  • height – Optional main editor window height override

~LammpsGui() override

Destructor.

Cleans up resources including dynamically created widgets and LAMMPS instances.

LammpsGui() = delete
LammpsGui(const LammpsGui&) = delete
LammpsGui(LammpsGui&&) = delete
LammpsGui &operator=(const LammpsGui&) = delete
LammpsGui &operator=(LammpsGui&&) = delete
void openFile(const QString &filename)

Load a file into the editor.

Ends a running simulation and closes the output windows, and offers to save the current buffer first if it was changed. Also reachable from the command window’s “edit”.

Parameters:

filename – File to edit; nothing happens if it is empty

bool plotFile(const QString &fileName)

Plot the columns of a data file, asking which ones.

The return value lets a caller with several files to plot stop at the first cancel rather than ask again for each of the rest. Also reachable from the command window’s “plot”.

Parameters:

fileName – Data file to read

Returns:

false only if the user canceled the column dialog

void viewFile(const QString &filename)

Open a file in a read-only text viewer.

Refuses an image or a movie file, which belong in openImageFiles(), and a binary one, which belongs nowhere. Also reachable from the command window’s “open”.

Parameters:

filename – File to show; nothing happens if it is empty

void openImageFiles(const QStringList &files)

Open image or movie files in a slide show viewer.

The list is taken as given: openImages() collects it from a file dialog, the command window’s “open” from a shell that has expanded it. Movie files are offered for frame extraction as they are added, which is why the viewer is shown before they are.

Parameters:

files – Images and movies to show together in one viewer

QList<QMenu*> sharedMenus() const

The menus that act on the application rather than on one view.

These are owned by the main window but shown by every window that has a menu bar: a QMenu can be added to more than one QMenuBar, which puts the same actions there rather than duplicates. That is what lets a run be started or stopped from any window, and it is also why the accelerators stay unambiguous &#8212; one action matches once, however many menus show it.

Returns:

Run, View, Tutorials and About, in the order they should appear

void updateMenuBarForFocus(QWidget *focused)

Put the focused view’s own menu at the front of the menu bar.

Combined layout only; does nothing with individual windows, where each window carries its own menu bar.

Parameters:

focused – Widget that just took the keyboard focus

Public Slots

void quit()

Quit the application.

void stopRun()

Stop a running LAMMPS simulation.

inline void runBuffer()

Run LAMMPS with content from editor buffer.

Protected Functions

void inspectFile(const QString &filename)

Read a restart file into LAMMPS and open the inspection windows.

void writeFile(const QString &filename)

Write current editor content to a file.

void updateEditorTitle(const QString &file)

Set the editor window title from the current file and run number.

In the docked layout the views are named by their dock tab and no longer carry a window title with the run number, so the editor title shows it.

void updateRecents(const QString &filename = "")

Update the recent files list.

void clearVariables()

Delete all variables defined in the LAMMPS instance.

void updateVariables()

Rebuild the variables list from the editor buffer.

void refreshVariables()

Fold input script edits into the variables list.

Re-parses the editor buffer and merges the result into the current variables list: a changed index variable definition in the input wins over a previous value, an unchanged one keeps the value set in the Set Variables dialog. Also updates the override markers shown in the editor. Called before the variables list is consumed (run setup, input check, Set Variables dialog).

void doRun(bool use_buffer, bool dryrun = false)

Execute a LAMMPS simulation.

Parameters:
  • use_buffer – If true, runs from editor buffer; if false, saves and runs from file

  • dryrun – If true, checks the input via a dry run: LAMMPS executes the setup of every command but no timesteps (the equivalent of the -skiprun command line flag)

bool hasSystemState()

Check whether the LAMMPS instance holds a usable system state.

Guard for operations that act on the current system state outside of a run, like writing a restart file or extending the previous run.

Returns:

true if LAMMPS is open, idle, and a simulation box is defined

void launchRunner(std::string input, std::string file, bool clearfirst)

Create and start a LammpsRunner thread and the log update timer.

Shared tail of doRun() and extendRun(): dispatches the given input to a new runner thread, connects its completion to runDone(), and starts the periodic polling of captured output and thermo data.

Parameters:
  • input – String of LAMMPS commands to execute (can be empty)

  • file – Input file path to execute (can be empty)

  • clearfirst – If true, wipe the current LAMMPS system state first

void startLammps()

Initialize and start a new LAMMPS instance.

void populateSyntax()

Fill the syntax registry from LAMMPS library introspection.

Queries the command and style name lists from the running LAMMPS instance into syntax and re-highlights the editor. Does nothing when no LAMMPS instance is available (the registry then stays unpopulated and unknown-name marking is disabled).

QStringList presetVariableNames() const

Variable names that are defined before the input runs.

The names from the Set Variables dialog plus the always-present gui_run variable; passed to the input checker as preset names.

bool confirmLintIssues()

Run the pre-run input lint and ask about found errors.

Called from doRun() when the pre-run check preference is enabled. Warning-level findings never block; they are noted in the status bar. Error-level findings pop up a “run anyway?” dialog.

Returns:

true when the run should proceed

void runDone()

Handle completion of a LAMMPS run.

void setDocver()

Set the documentation version string for help links.

void autoSave()

Perform an auto-save of the current file.

void setFont(const QFont &newfont)

Update the editor font.

Parameters:

newfont – The font to apply to the editor

QWizardPage *tutorialIntro(int collection, int ntutorial, const QString &infotext)

Create an introduction page for a tutorial.

Parameters:
  • collection – Tutorial collection index

  • ntutorial – Tutorial number within the collection

  • infotext – Information text to display

Returns:

Wizard page with tutorial introduction

QWizardPage *tutorialDirectory(int collection, int ntutorial)

Create a directory selection page for a tutorial.

Parameters:
  • collection – Tutorial collection index

  • ntutorial – Tutorial number within the collection

Returns:

Wizard page for tutorial directory selection

void setupTutorial(int collection, int tutno, const QString &dir, bool purgedir, bool getsolution, bool openwebpage)

Set up files and resources for a tutorial.

Parameters:
  • collection – Tutorial collection index

  • tutno – Tutorial number within the collection

  • dir – Directory to create files in

  • purgedir – Whether to clean the directory first

  • getsolution – Whether to include solution files

  • openwebpage – Whether to open the tutorial web page

void purgeInspectList()

Clean up the inspect file dialog list.

bool eventFilter(QObject *watched, QEvent *event) override

Event filter for handling special events.

Parameters:
  • watched – Object being watched

  • event – Event to filter

Returns:

true if event was handled

Protected Attributes

int nthreads

Number of threads for parallel execution.

int mainx

Override value for main editor window width or 0.

int mainy

Override value for main editor window height or 0.

bool hasClipboard

true if Qt was configured with Clipboard support, otherwise false


3.1.2. TutorialWizard Class

class TutorialWizard : public QWizard

Wizard dialog for interactive LAMMPS tutorials.

TutorialWizard provides a step-by-step wizard interface for setting up and running LAMMPS tutorials. It guides users through directory selection, file preparation, and launching tutorial exercises.

Public Functions

TutorialWizard(int collection, int ntutorial, LammpsGui *lammpsgui, QWidget *parent = nullptr)

Construct a tutorial wizard.

Parameters:
  • collection – Tutorial collection index

  • ntutorial – Tutorial number within the collection

  • lammpsgui – Pointer to LammpsGui for sending signals

  • parent – Parent widget

void accept() override

Accept the wizard and set up the tutorial.

Called when the user completes the wizard. Sets up tutorial files and opens the tutorial in the main window.


3.1.3. Tutorial Collections

The TutorialCollection struct (src/tutorials.h) is the single source of truth for the tutorial collections offered in the Tutorials menu. Each entry describes one independently hosted collection (its files repository, web pages, per-tutorial titles and blurbs, and how much of it is released). The menu and the TutorialWizard consume the table through the tutorialCollections() and tutorialCollection() accessors. See Adding or updating a tutorial collection for how to add or update a tutorial or a whole collection.

struct TutorialCollection

Metadata for one collection of LAMMPS-GUI tutorials.

LAMMPS-GUI ships support for multiple, independently hosted tutorial collections (e.g. the molecular soft-matter set and the materials-science set). Each collection is a numbered series of tutorials laid out identically &#8212; one files/tutorial<N>/ folder per tutorial with a .manifest and an optional solution/ subfolder &#8212; so the only thing that varies between collections is this metadata. The single source of truth is the table in tutorials.cpp, consumed by the Tutorials menu and the TutorialWizard.

Public Functions

inline int count() const

Number of tutorials in this collection.

inline QString logoFor(int n) const

Logo resource for tutorial n (1-based); resolves a “%1” pattern.

Public Members

QString key

stable identifier, e.g. “softmatter”, “matsci”

QString name

display name for the menu and wizard

QString dirPrefix

working-directory folder prefix (e.g. “tutorial”)

QString author

short author/attribution line for the intro page

QString filesUrl

raw files base, “…tutorial%1/%2” (number, filename)

QString filesRepoUrl

human-facing repository URL shown on the intro page

QString webUrl

per-tutorial web page pattern, “…%1/%2.html” (number, slug)

QString siteUrl

collection landing page (fallback web page)

QString logo

logo resource; may contain “%1” for per-tutorial logos

QStringList titles

short per-tutorial titles (count() entries)

QStringList slugs

per-tutorial web-page slugs (count() entries, or empty)

QStringList blurbs

per-tutorial HTML descriptions (count() entries)

bool published

true once the whole collection is released (hides the teaser label)

QString status

menu label for an unpublished collection (“coming soon”, “planned”)

int available = 0

number of leading tutorials that are launchable now; the remaining count()-available entries appear as disabled teasers


const QList<TutorialCollection> &tutorialCollections()

The available tutorial collections, in display order.

const TutorialCollection &tutorialCollection(int index)

Collection at index, clamped to a valid entry (0 if out of range)


3.2. Editor Components

3.2.1. CodeEditor Class

class CodeEditor : public QPlainTextEdit

Custom text editor with LAMMPS syntax support and auto-completion.

The CodeEditor class extends QPlainTextEdit to provide specialized features for editing LAMMPS input scripts:

  • Line numbers in a margin area

  • Syntax highlighting via Highlighter

  • Context-aware auto-completion for LAMMPS commands

  • Automatic indentation and formatting

  • Context menu with LAMMPS-specific help

  • Line highlighting for error visualization

Public Functions

CodeEditor(QWidget *parent = nullptr)

Constructor.

Parameters:

parent – Parent widget (typically the main window)

~CodeEditor() override

Destructor.

CodeEditor() = delete
CodeEditor(const CodeEditor&) = delete
CodeEditor(CodeEditor&&) = delete
CodeEditor &operator=(const CodeEditor&) = delete
CodeEditor &operator=(CodeEditor&&) = delete
inline void setSyntax(const LammpsSyntax *newsyntax)

Set the syntax registry used for completion and help lookups.

Parameters:

newsyntax – Syntax registry (not owned)

void lineNumberAreaPaintEvent(QPaintEvent *event)

Paint line numbers in the line number area.

Parameters:

event – Paint event to handle

int lineNumberAreaWidth()

Calculate width needed for line number area.

Returns:

Width in pixels

void setFont(const QFont &newfont)

Set editor font.

Parameters:

newfont – Font to use for editor text

void setCursor(int block)

Set cursor to specific text block.

Parameters:

block – Block number (line number) to position cursor

void setHighlight(int block, bool error)

Highlight a specific line (used for error indication)

Parameters:
  • block – Block number to highlight

  • error – true for the error (red) highlight, false for the normal (green) one

inline void setReformatOnReturn(bool flag)

Enable/disable automatic reformatting on Enter key.

Parameters:

flag – true to enable, false to disable

inline void setAutoComplete(bool flag)

Enable/disable automatic completion popup.

Parameters:

flag – true to enable, false to disable

QString reformatLine(const QString &line)

Reformat a line with proper indentation.

Parameters:

line – Line to reformat

Returns:

Reformatted line

void setCommandList(const QStringList &words)

Set word list for LAMMPS command completion.

Parameters:

words – List of command names

void setFixList(const QStringList &words)

Set word list for fix style completion.

Parameters:

words – List of fix style names

void setComputeList(const QStringList &words)

Set word list for compute style completion.

Parameters:

words – List of compute style names

void setDumpList(const QStringList &words)

Set word list for dump style completion.

Parameters:

words – List of dump style names

void setAtomList(const QStringList &words)

Set word list for atom style completion.

Parameters:

words – List of atom style names

void setPairList(const QStringList &words)

Set word list for pair style completion.

Parameters:

words – List of pair style names

void setBondList(const QStringList &words)

Set word list for bond style completion.

Parameters:

words – List of bond style names

void setAngleList(const QStringList &words)

Set word list for angle style completion.

Parameters:

words – List of angle style names

void setDihedralList(const QStringList &words)

Set word list for dihedral style completion.

Parameters:

words – List of dihedral style names

void setImproperList(const QStringList &words)

Set word list for improper style completion.

Parameters:

words – List of improper style names

void setKspaceList(const QStringList &words)

Set word list for kspace style completion.

Parameters:

words – List of kspace style names

void setRegionList(const QStringList &words)

Set word list for region style completion.

Parameters:

words – List of region style names

void setIntegrateList(const QStringList &words)

Set word list for integration style completion.

Parameters:

words – List of integration style names

void setMinimizeList(const QStringList &words)

Set word list for minimization style completion.

Parameters:

words – List of minimization style names

void setVariableList(const QStringList &words)

Set word list for variable style completion.

Parameters:

words – List of variable style names

void setUnitsList(const QStringList &words)

Set word list for units style completion.

Parameters:

words – List of units style names

void setExtraList(const QStringList &words)

Set extra word list for completion.

Parameters:

words – List of extra words

void setColorList(const QStringList &words)

Set list of color names for completion.

Parameters:

words – List of color names

void setImageKwList(const QStringList &words)

Set list of dump image keywords for completion.

Parameters:

words – List of dump image keywords

void setGroupList()

Update group ID list from the editor buffer.

void setVarNameList()

Update variable name list from the editor buffer and LAMMPS instance.

void setComputeIDList()

Update compute ID list from the editor buffer.

void setFixIDList()

Update fix ID list from the editor buffer.

void setFileList()

Update file list from current directory.

void setVariableOverrides(const QList<VariableEntry> &vars)

Set the variables list used to mark overridden index variable values.

Entries whose value overrides the definition in the input script (see isOverridden()) get a thin frame drawn around the value text of their definition line and a tooltip showing the overriding value.

Parameters:

vars – Current variable entries (parse results plus dialog edits)

Public Static Attributes

static constexpr int NO_HIGHLIGHT = 1 << 30

Constant for disabled highlighting.

Protected Functions

void resizeEvent(QResizeEvent *event) override

Handle resize events to update line number area.

Parameters:

event – The resize event

void paintEvent(QPaintEvent *event) override

Paint the editor and frame overridden index variable values.

Parameters:

event – The paint event

bool event(QEvent *event) override

Handle tooltip events for overridden index variable values.

Parameters:

event – The event to handle

Returns:

true if the event was handled

bool canInsertFromMimeData(const QMimeData *source) const override

Check if MIME data can be inserted (for drag-and-drop)

Parameters:

source – The MIME data to check

Returns:

true if data can be inserted

void dragEnterEvent(QDragEnterEvent *event) override

Handle drag enter events.

Parameters:

event – The drag enter event

void dragLeaveEvent(QDragLeaveEvent *event) override

Handle drag leave events.

Parameters:

event – The drag leave event

void dropEvent(QDropEvent *event) override

Handle drop events.

Parameters:

event – The drop event

void contextMenuEvent(QContextMenuEvent *event) override

Handle context menu events.

Parameters:

event – The context menu event

void keyPressEvent(QKeyEvent *event) override

Handle key press events (for auto-completion and formatting)

Parameters:

event – The key event

void setDocver()

Set LAMMPS documentation version for help links.


3.2.2. LineNumberArea Class

class LineNumberArea : public QWidget

Widget displaying line numbers alongside the code editor.

This widget is placed in the margin of the CodeEditor to show line numbers. All painting is delegated back to the CodeEditor class.

Public Functions

inline explicit LineNumberArea(CodeEditor *editor)

Constructor.

Parameters:

editor – Pointer to the associated CodeEditor

~LineNumberArea() override = default

Destructor.

LineNumberArea() = delete
LineNumberArea(const LineNumberArea&) = delete
LineNumberArea(LineNumberArea&&) = delete
LineNumberArea &operator=(const LineNumberArea&) = delete
LineNumberArea &operator=(LineNumberArea&&) = delete
inline QSize sizeHint() const override

Get the ideal size for the line number area.

Returns:

QSize with width from editor, height 0 (fills available height)

Protected Functions

inline void paintEvent(QPaintEvent *event) override

Paint event handler - delegates to CodeEditor.

Parameters:

event – The paint event


3.2.3. Highlighter Class

class Highlighter : public QSyntaxHighlighter

Syntax highlighter for LAMMPS input scripts.

This class extends QSyntaxHighlighter to provide syntax highlighting for LAMMPS input files in the CodeEditor. Lines are lexed with the shared syntax engine (tokenizeLine()), so multi-line constructs &#8212; ‘&’ line continuations (including mid-word joins), triple-quoted strings, and quoted strings spanning continuations &#8212; are tracked through the QSyntaxHighlighter block states and continuation lines are highlighted in the context of their logical command. Command words keep the historically grown per-category colors; arguments are colored by their role from the LammpsSyntax command spec table plus lexical classes (numbers, strings, comments, variable references, special words). Keywords that embed a second command in a command line &#8212; the “modify” of write_dump and the “dump” of rerun &#8212; are shown in the color of the command they stand for (dump_modify and read_dump, respectively) and the arguments after them are colored as arguments of that command. Command and style names that are unknown to the populated syntax registry are flagged with a wavy underline, except for the word currently being edited at the cursor.

Public Functions

Highlighter(const LammpsSyntax *syntax, QTextDocument *parent)

Constructor.

Parameters:
  • syntax – Syntax registry with name sets and command specs (not owned, may not be null)

  • parent – Parent text document to highlight

~Highlighter() override = default

Destructor.

Highlighter() = delete
Highlighter(const Highlighter&) = delete
Highlighter(Highlighter&&) = delete
Highlighter &operator=(const Highlighter&) = delete
Highlighter &operator=(Highlighter&&) = delete

Public Slots

void setCursorPos(int blockNumber, int column)

Track the editing cursor to suppress unknown-name marking there.

The unknown-name underline is not shown for the word the cursor is on, so a partially typed name is not flagged. Re-highlights the previously active and the new block.

Parameters:
  • blockNumber – block (line) number of the cursor position

  • column – column of the cursor within the block

Protected Functions

void highlightBlock(const QString &text) override

Highlight a single block (line) of text.

Parameters:

text – The text to highlight


3.2.4. LammpsSyntax Class

class LammpsSyntax

Registry of LAMMPS syntax data for highlighting, completion, and checking.

Holds the sets of valid command and style names for each StyleCat plus the per-command argument role table. The name sets are populated by injection (normally from LAMMPS library introspection right after the LAMMPS instance is created; from literal lists in unit tests), so this class has no dependency on the LAMMPS library. The role table is loaded from the command spec resource table; additional tables can be loaded on top and override earlier entries.

Public Functions

LammpsSyntax()

Constructor; seeds the static keyword sets.

~LammpsSyntax() = default

Destructor.

LammpsSyntax(const LammpsSyntax&) = delete
LammpsSyntax(LammpsSyntax&&) = delete
LammpsSyntax &operator=(const LammpsSyntax&) = delete
LammpsSyntax &operator=(LammpsSyntax&&) = delete
void setStyles(StyleCat cat, const QStringList &names)

Set the full (unfiltered) list of valid names for one category.

The unfiltered set is used for name validity checks; a sorted list with accelerator-suffixed variants removed is derived for completions.

Parameters:
  • cat – category to populate

  • names – full list of valid names for the category

inline void setCommands(const QStringList &names)

convenience alias for setStyles(StyleCat::Command, names)

bool loadCommandSpecs(const QString &path)

Load a command spec table from a file or Qt resource.

Parameters:

path – file system path or Qt resource path of the table

Returns:

true if the file could be read and contained no malformed entries

bool loadCommandSpecsFromString(const QString &text)

Load a command spec table from a string (tests, future overlays)

Later entries override earlier entries with the same command name. Malformed lines are skipped.

Parameters:

text – complete table text

Returns:

true if no malformed entries were found

inline bool isPopulated() const

true once command names have been populated; gates unknown-name checks

inline bool knownCommand(const QString &word) const

check whether a word is a known command name

bool knownStyle(StyleCat cat, const QString &name) const

check whether a name is in the full style set of a category

inline bool isSpecialWord(const QString &word) const

check for the special argument words (INF, EDGE, NULL, SELF, if/then/else/elif)

CmdCat commandCategory(const QString &cmd) const

display category for a command word (CmdCat::Other if not in the table)

inline int commandIndex(const QString &cmd) const

stable spec table index for a command (-1 if the command has no spec entry)

const CommandSpec *spec(int index) const

spec table entry by index (nullptr for invalid index)

ArgSpec argSpec(int cmdIndex, int argIndex) const

role of argument position argIndex (>= 1) of command spec cmdIndex

QStringList completionList(StyleCat cat, bool withNone) const

Sorted completion word list for a category.

Accelerator-suffixed style variants are filtered out.

Parameters:
  • cat – category of the word list

  • withNone – prepend the “none” style (pair/bond/… styles)

CompletionTarget completionTarget(int prevBlockState, const QString &line, int cursorCol) const

Determine which completion applies at a cursor position.

Tokenizes the line with the given previous block state, locates the word under the cursor, and classifies it: the command completer on word 0 of a fresh logical line, and per-argument completers from the command spec table (style categories, group IDs, file names) plus the v_/c_/f_ reference prefixes and the read_data extra keywords. Because the previous block state carries the active command across ‘&’ line continuations, completion works on continuation lines as well.

Parameters:
  • prevBlockState – block state after the previous line (-1 or 0 for none)

  • line – physical line the cursor is on

  • cursorCol – column of the cursor within the line

Returns:

completer kind, style category, and the word under the cursor


3.2.5. InputScanner Class

class InputScanner

Assemble logical LAMMPS commands from the physical lines of a buffer.

Feeds physical lines through tokenizeLine() while threading the multi-line state, joins ‘&’ continuations (including mid-word joins and quoted strings spanning lines), and reports each completed logical command as a list of words with their original line numbers. Comment and empty lines produce no commands. Tokenizer-level problems (unbalanced quotes, an unclosed triple-quoted block, or a dangling ‘&’ on the final line) are collected as diagnostics. This is the input-scanning building block for whole-buffer consumers such as the pre-run syntax checker; the highlighter works on the per-block state directly instead.

Public Types

enum class Diag : quint8

tokenizer-level problems found while scanning

Values:

enumerator UnbalancedQuote

a single/double quote was left unclosed

enumerator UnclosedTriple

a triple-quoted block was still open at the end

enumerator DanglingContinuation

the final line ended with a ‘&’ continuation

Public Functions

InputScanner() = default

Constructor.

~InputScanner() = default

Destructor.

InputScanner(const InputScanner&) = default

Copy constructor.

InputScanner(InputScanner&&) = default

Move constructor.

InputScanner &operator=(const InputScanner&) = default

Copy assignment.

InputScanner &operator=(InputScanner&&) = default

Move assignment.

void scan(const QString &buffer)

scan a whole buffer (split on newlines, 1-based line numbers); results accumulate, so use a fresh scanner for every buffer

inline const QVector<LogicalCommand> &commands() const

completed logical commands in buffer order

inline const QVector<Diagnostic> &diagnostics() const

diagnostics in detection order

struct Diagnostic

one diagnostic with the line it was detected on

Public Members

Diag what = Diag::UnbalancedQuote

kind of problem

int line = 0

1-based line number

struct LogicalCommand

one logical command with continuations joined

Public Members

int firstLine = 0

line number of the first physical line

int lastLine = 0

line number of the last physical line

QVector<Word> words

words in command order; words[0] is the command

struct Word

one whitespace-separated word of a logical command

Public Members

QString text

word text; surrounding matching quotes stripped

int line = 0

line number of the word’s first character

bool quoted = false

word contains (or is) a quoted section

bool hasSubst = false

word contains a ‘$’ variable reference


3.2.6. SyntaxChecker Class

class SyntaxChecker

Static lint checks for LAMMPS input scripts.

Scans an input buffer with the syntax engine’s InputScanner and applies a set of deterministic checks against the introspected name registry: unknown commands and style names, quoting and line continuation problems, references to undefined variables and groups, references to computes, fixes, or variables defined nowhere in the buffer, missing input files, missing required arguments, and non-numeric arguments in a curated list of strictly numeric positions.

The design priority is the absence of false positives: any word containing a ‘$’ substitution is exempt from every check, a substitution anywhere on a line disables its argument-count check, and script features that make static analysis unreliable disable whole rule groups. Any of include files, jump/label loops, if/then commands, or python scripting disables all definition-tracking rules (variable, group, and reference checks); jump/label additionally downgrades unknown commands to warnings; shell, geturl, and include disable file-existence checks downstream; read_restart disables group and ID checks downstream; plugin disables unknown-name errors downstream. Only ERROR severity findings should gate a run.

Public Functions

inline explicit SyntaxChecker(const LammpsSyntax *syntax)

Constructor.

Parameters:

syntax – Syntax registry with name sets and command specs (not owned, may not be null)

~SyntaxChecker() = default
SyntaxChecker() = delete
SyntaxChecker(const SyntaxChecker&) = delete
SyntaxChecker(SyntaxChecker&&) = delete
SyntaxChecker &operator=(const SyntaxChecker&) = delete
SyntaxChecker &operator=(SyntaxChecker&&) = delete
QList<LintIssue> check(const QString &buffer, const QStringList &presetVariables, const QString &cwd) const

Check an input buffer.

Parameters:
  • buffer – complete input script text

  • presetVariables – variable names that are defined outside the script before the run (the SetVariables dialog entries and the always-present gui_run variable)

  • cwd – directory that relative file names are resolved against

Returns:

findings sorted by line number

Public Static Functions

static int countErrors(const QList<LintIssue> &issues)

number of ERROR severity findings in a result list

static QString formatIssues(const QList<LintIssue> &issues, int maxShown = -1)

Format findings as a plain text list, one finding per line.

Parameters:
  • issues – findings to format

  • maxShown – maximum number of findings listed (-1 = all); when truncated, a final “… and N more” line is appended

Returns:

the formatted list

struct LintIssue

one finding of the pre-run input check

Public Members

int line = 0

1-based physical line number

LintSeverity severity = LintSeverity::Warning

how serious the finding is

QString message

human readable description

enum class LintSeverity : quint8

severity of a single lint finding

Values:

enumerator Warning

suspicious, but may be intentional

enumerator Error

LAMMPS will reject this input.


3.2.7. Syntax Engine Functions

Functions

LineTokens tokenizeLine(const QString &text, int prevState = 0)

Split one physical line of a LAMMPS input into tokens with spans.

Mirrors the parsing rules of the LAMMPS Input class (lammps/src/input.cpp): trailing whitespace is trimmed before the ‘&’ continuation check, ‘#’ starts a comment unless it appears inside a quoted string, single, double, and triple quotes group text, and quoted strings may span ‘&’ continuations. Multi-line state (open triple quote, continuation, open quote) is carried in the state integer, see SyntaxState.

The command spec index bits of the returned state are preserved from prevState while a logical line continues and reset to “none” when a new logical line starts; callers that track the active command patch the state with SyntaxState::withCommand() before storing it.

Parameters:
  • text – physical line (no trailing newline)

  • prevState – block state after the previous line (-1 or 0 for none)

Returns:

tokens with spans and the state after this line

QVector<Token> findVarRefs(const QString &text)

Find $x, ${name}, and variable references.

Follows the LAMMPS substitution rules: a ‘$’ preceded by a backslash is escaped, ‘${’ extends to the closing brace, ‘$(’ extends to the balanced closing parenthesis (an optional ‘:format’ suffix is part of the expression), otherwise the single following character names the variable. References are reported everywhere including inside quoted strings, since commands like print, if, and python substitute their quoted arguments.

Parameters:

text – text to scan

Returns:

VarRef tokens with spans in scan order

QHash<int, QString> argumentTexts(const LineTokens &lt, const QString &line)

Collect the full text of each argument of a tokenized line.

Joins the tokens belonging to the same argument (words may consist of several tokens when they contain quoted sections), skipping comment and continuation tokens.

Parameters:
  • lt – result of tokenizeLine() for the line

  • line – the tokenized line

Returns:

map from argument index to the argument’s full text

bool isNumberWord(const QString &word)

Check whether a word is a number the way the LAMMPS-GUI editor colors them.

Accepts integers, floating point numbers with optional e/E/d/D exponent, and integer ranges / type wildcards built from digits, ‘:’, and ‘*’.

Parameters:

word – word to test

Returns:

true if the word is number-like


3.2.8. Syntax Engine Types

enum class StyleCat : quint8

Style-list categories known to the syntax registry.

The first group mirrors the categories that can be enumerated through the LAMMPS library interface (lammps_style_count() / lammps_style_name()); Variable, Units, Extra, and ImageKw are static keyword sets that LAMMPS does not expose through introspection, and Color is injected from the shared color name list (see lammpsImageColors()).

Values:

enumerator Command

command names (input commands + registered command styles)

enumerator Fix

fix styles

enumerator Compute

compute styles

enumerator Dump

dump styles

enumerator Atom

atom styles

enumerator Pair

pair styles

enumerator Bond

bond styles

enumerator Angle

angle styles

enumerator Dihedral

dihedral styles

enumerator Improper

improper styles

enumerator Kspace

kspace styles

enumerator Region

region styles

enumerator Integrate

integrator styles (run_style)

enumerator Minimize

minimizer styles (min_style)

enumerator Variable

variable command styles (static set)

enumerator Units

units command arguments (static set)

enumerator Extra

read_data / create_box “extra/…” keywords (static set)

enumerator Color

color names accepted by the dump image command (injected)

enumerator ImageKw

keywords of the dump image command (static set)

enumerator None

no style category (used in ArgSpec for non-style roles)

enum class CmdCat : quint8

Display category of a command word.

These are the historically grown highlight classes of the LAMMPS-GUI editor; the mapping of command names to categories is read from the command spec table and must be kept consistent with the colors users are accustomed to.

Values:

enumerator Lattice

system setup / lattice / geometry commands

enumerator Output

file I/O and output commands

enumerator Modify

*_modify commands

enumerator Particle

particle, force field, and definition commands

enumerator Run

run-like commands

enumerator Setup

settings commands

enumerator Special

undo / flow control commands

enumerator Other

recognized command without an explicit category entry

enum class ArgRole : quint8

Role of an argument position within a command.

Values:

enumerator Any

no specific role; only lexical highlighting applies

enumerator DefineId

an ID defined by this command (fix/compute/dump/region/variable ID)

enumerator GroupId

reference to an atom group ID

enumerator Style

a style name; the category is in ArgSpec::cat

enumerator SubStyle

may name a sub-style of a hybrid style; recognized when the word is a member of the category’s style set, like LAMMPS itself separates hybrid sub-styles from their arguments

enumerator File

a file name argument

enumerator Int

an integer number is expected (informational in the spec table for now; the checker uses its own vetted numeric list)

enumerator Number

a floating point number is expected (informational, see Int)

enumerator Keyword

a keyword-like argument

enumerator Label

reference to an ID defined elsewhere (unfix/jump/label targets)

enum class TokType : quint8

Type of a token produced by tokenizeLine() / findVarRefs()

Values:

enumerator Word

unquoted (part of a) word

enumerator String

single- or double-quoted string span

enumerator TripleString

triple-quoted string span

enumerator Comment

comment from ‘#’ to end of line

enumerator Continuation

trailing ‘&’ line continuation character

enumerator VarRef

$x, ${name}, or variable reference (findVarRefs() only)

enum class CompleterKind : quint8

Which completion word list applies at a completion location.

Values:

enumerator None

no completion at this location

enumerator Command

command names (word 0 of a logical line)

enumerator Style

style names; the category is in CompletionTarget::cat

enumerator Group

group IDs

enumerator VarName

variable name references (v_…)

enumerator ComputeId

compute ID references (c_…)

enumerator FixId

fix ID references (f_…)

enumerator File

file names

enumerator Extra

read_data / create_box “extra/…” keywords

struct ArgSpec

Role and (for ArgRole::Style) style category of one argument position.

Public Members

ArgRole role = ArgRole::Any

role of this argument position

StyleCat cat = StyleCat::None

style category when role == ArgRole::Style

struct CommandSpec

Per-command syntax information loaded from the command spec table.

Public Members

QString name

command name

CmdCat category = CmdCat::Other

display category of the command word

int minArgs = 0

minimum number of required arguments

QVector<ArgSpec> args

roles of argument positions 1, 2, …

bool repeatLast = false

repeat the last role for excess arguments

struct Token

One token within a physical line of a LAMMPS input.

Adjacent tokens with the same argIndex belong to the same argument (words may contain embedded quoted sections).

Public Members

int start = 0

offset of the first character within the line

int length = 0

number of characters

TokType type = TokType::Word

token type

int argIndex = -1

0 = command word, > 0 argument position, -1 = not an argument

bool isNumber = false

word parses as a LAMMPS number, range, or type wildcard

bool hasSubst = false

word contains a ‘$’ variable reference

bool fragment = false

word is split across a mid-word ‘&’ continuation

struct LineTokens

Result of tokenizing one physical line.

Public Members

QVector<Token> tokens

tokens in line order

int outState = 0

block state after this line (see SyntaxState)

bool unbalancedQuote = false

a single/double quote was left unclosed

struct CompletionTarget

Result of LammpsSyntax::completionTarget()

Public Members

CompleterKind kind = CompleterKind::None

which completer applies

StyleCat cat = StyleCat::None

style category when kind == Style

int wordStart = -1

start column of the word under the cursor

int wordLength = 0

length of the word under the cursor

namespace SyntaxState

Packing helpers for the per-block syntax state integer.

The state is stored in QSyntaxHighlighter block states and threaded through tokenizeLine() so multi-line constructs (triple-quoted strings, ‘&’ line continuations, quoted strings spanning continuations) are lexed consistently. Layout: bits 0-5 flags, bits 6-18 command spec index + 1 (0 = no spec), bits 19-26 number of arguments consumed so far.

Functions

inline int flags(int state)

extract the flag bits from a block state

inline int cmdIndex(int state)

extract the command spec index from a block state (-1 if none)

inline int argsUsed(int state)

extract the number of arguments consumed so far from a block state

inline int pack(int flagbits, int cmdidx, int nargs)

combine flags, command spec index (-1 for none), and argument count into a block state

inline int withCommand(int state, int cmdidx)

replace the command spec index in a block state (-1 for none)

inline int withArgs(int state, int nargs)

replace the number of arguments consumed so far in a block state; used to renumber the arguments when a command embeds a second command (the “modify” section of write_dump, the “dump” section of rerun)

inline bool logicalContinues(int state)

true when a line with this previous-line state continues the logical line (an open continuation, triple-quoted block, or quoted string)

Variables

constexpr int TRIPLE = 1 << 0

inside an open triple-quoted string

constexpr int CONTINUE = 1 << 1

previous line ended with ‘&’: logical line continues

constexpr int MIDWORD = 1 << 2

the ‘&’ directly followed a word character

constexpr int COMMENT = 1 << 3

the continuation is inside a comment

constexpr int SINGLEQ = 1 << 4

inside an open single-quoted string

constexpr int DOUBLEQ = 1 << 5

inside an open double-quoted string

constexpr int FLAG_MASK = 0x3f

mask covering all flag bits

constexpr int CMD_SHIFT = 6

bit position of the command spec index

constexpr int CMD_MASK = 0x1fff

13 bits for the command spec index + 1

constexpr int ARG_SHIFT = 19

bit position of the argument counter

constexpr int ARG_MASK = 0xff

8 bits for the argument counter

constexpr int ARG_MAXX = ARG_MASK

saturation value of the argument counter


3.3. LAMMPS Interface

3.3.1. LammpsWrapper Class

class LammpsWrapper

C++ wrapper for the LAMMPS C library interface.

This class provides a C++-oriented interface to the LAMMPS library, routing all library calls through a unified API. It manages the LAMMPS instance and handles dynamic loading of the library when the application is built in plugin mode.

Public Types

enum StyleConst

Constants for variable styles.

Values:

enumerator EQUAL_STYLE
enumerator ATOM_STYLE
enumerator VECTOR_STYLE
enumerator STRING_STYLE
enum ScopeConst

Constants for data scopes.

Values:

enumerator GLOBAL_STYLE
enumerator DUMMY
enumerator LOCAL_STYLE
enum TypeConst

Constants for data types.

Values:

enumerator SCALAR_TYPE
enumerator VECTOR_TYPE
enumerator ARRAY_TYPE
enumerator NUM_ROWS
enumerator NUM_COLS

Public Functions

LammpsWrapper()

Constructor - initializes wrapper.

~LammpsWrapper()

Destructor.

Does not close an open LAMMPS instance. Callers must invoke close() explicitly before destroying the wrapper. In plugin mode the handle to the dynamically loaded LAMMPS library is released.

LammpsWrapper(const LammpsWrapper&) = delete
LammpsWrapper(LammpsWrapper&&) = delete
LammpsWrapper &operator=(const LammpsWrapper&) = delete
LammpsWrapper &operator=(LammpsWrapper&&) = delete
void open(int nargs, char **args)

Create a new LAMMPS instance.

Parameters:
  • nargs – Number of command-line arguments

  • args – Command-line arguments array

void close()

Close the LAMMPS instance.

void finalize()

Finalize MPI (if used) and close LAMMPS.

void file(const QString &fname)

Process commands from a LAMMPS input file.

Parameters:

fname – Filename as Qt-style QString

void command(const QString &cmd)

Execute a single LAMMPS command.

Parameters:

cmd – Command string as Qt-style QString

void commandsString(const QString &cmd)

Execute multiple LAMMPS commands from a string.

Parameters:

cmd – Commands string with newlines as Qt-style QString

void forceTimeout()

Force a timeout condition in LAMMPS.

int version()

Get LAMMPS version number.

Returns:

Version number as integer (YYYYMMDD format)

int extractSetting(const char *keyword)

Extract a global setting from LAMMPS.

Parameters:

keyword – Setting name to extract

Returns:

Integer value of the setting

void *extractGlobal(const char *keyword)

Extract a pointer to global data from LAMMPS.

Parameters:

keyword – Name of global data to extract

Returns:

Pointer to the data

void *extractPair(const char *keyword)

Extract pair style data from LAMMPS.

Parameters:

keyword – Name of pair data to extract

Returns:

Pointer to the pair data cast to a void pointer

void *extractAtom(const char *keyword)

Extract atom data from LAMMPS.

Parameters:

keyword – Name of atom data to extract

Returns:

Pointer to the atom data cast to void pointer

void *extractCompute(const QString &id, int style, int type)

Extract data from a compute from LAMMPS.

Parameters:
  • id – compute id as a QString

  • style – style of data to extract

  • type – type of data to extract

Returns:

data cast to a void pointer

void *extractFix(const QString &id, int style, int type, int nrow, int ncol)

Extract data from a fix from LAMMPS.

Parameters:
  • id – fix id as a QString

  • style – style of data to extract

  • type – type of data to extract

  • nrow – row index (only for global)

  • ncol – column index (only for global)

Returns:

data cast to a void pointer. Must be freed for global elements

double extractVariable(const char *keyword)

Extract a variable value from LAMMPS.

Parameters:

keyword – Variable name to extract

Returns:

Value of the variable as double

int extractVariableDatatype(const QString &keyword)

Extract style of a variable from LAMMPS.

Parameters:

keyword – variable name as a QString

Returns:

Value type of variable as integer

int hasId(const char *idtype, const char *id)

Check if a compute/fix/variable ID exists.

Parameters:
  • idtype – Type of ID (“compute”, “fix”, “variable”)

  • id – The ID to check

Returns:

1 if exists, 0 otherwise

int idCount(const char *idtype)

Get count of IDs of a specific type.

Parameters:

idtype – Type of ID (“compute”, “fix”, “variable”, “group”)

Returns:

Number of IDs of that type

QString idName(const char *idtype, int idx)

Get the name of an ID by index.

Parameters:
  • idtype – Type of ID (“compute”, “fix”, “variable”, “group”, …)

  • idx – Index of the ID

Returns:

The ID name, or an empty string on error

int styleCount(const char *keyword)

Get count of styles of a specific type.

Parameters:

keyword – Type of style (“compute”, “fix”, “pair”, etc.)

Returns:

Number of available styles

QString styleName(const char *keyword, int idx)

Get the name of a style by index.

Parameters:
  • keyword – Type of style (“command”, “pair”, “fix”, …)

  • idx – Index of the style

Returns:

The style name, or an empty string on error

QString variableInfo(int idx)

Get the name of a variable by index.

Parameters:

idx – Variable index

Returns:

The variable name, or an empty string on error

double getThermo(const char *keyword)

Get current value of a thermodynamic quantity.

Parameters:

keyword – Thermo keyword

Returns:

Value of the thermo quantity

void *lastThermo(const char *keyword, int idx)

Get a specific value from last thermo output.

Parameters:
  • keyword – Thermo keyword

  • idx – Index for vector quantities

Returns:

Pointer to the value

template<typename T>
inline T lastThermoAs(const char *keyword, int idx)

Typed read of a cached last-thermo value.

Template Parameters:

T – scalar type the thermo value points to (int, int64_t, double)

Parameters:
  • keyword – Thermo keyword (“step”, “num”, “type”, “data”, …)

  • idx – Index for vector quantities

Returns:

The dereferenced value, or a value-initialized T if the query returns null

inline QString lastThermoString(const char *keyword, int idx)

Read a string-valued cached last-thermo entry.

Parameters:
  • keyword – Thermo keyword that returns text (e.g. “keyword”, “imagename”)

  • idx – Index for vector quantities

Returns:

The value as a QString (empty if unavailable)

inline bool isOpen() const

Check if LAMMPS instance is open.

Returns:

true if LAMMPS is initialized, false otherwise

bool isRunning()

Check if LAMMPS is currently executing a run.

Returns:

true if running, false otherwise

bool hasError() const

Check if LAMMPS has encountered an error.

Returns:

true if error occurred, false otherwise

int getLastErrorMessage(char *errorbuf, int buflen)

Get the last error message from LAMMPS.

Parameters:
  • errorbuf – Buffer to store error message

  • buflen – Length of buffer

Returns:

Error type code

QString lastErrorMessage()

Get the last error message from LAMMPS as a string.

Convenience wrapper around getLastErrorMessage() that manages the character buffer internally. Retrieving the message also clears the pending error state in LAMMPS.

Returns:

The error text, or an empty string if no error is pending

bool configAccelerator(const char *package, const char *category, const char *setting) const

Check if an accelerator package is available.

Parameters:
  • package – Package name

  • category – Category name

  • setting – Setting name

Returns:

true if available, false otherwise

bool configHasPackage(const char *pkg) const

Check if a package is included in LAMMPS build.

Parameters:

pkg – Package name

Returns:

true if included, false otherwise

bool configHasCurlSupport() const

Check if LAMMPS was built with CURL support.

Returns:

true if CURL is available, false otherwise

bool configHasOmpSupport() const

Check if LAMMPS was built with OpenMP support.

Returns:

true if OpenMP is available, false otherwise

bool configHasPngSupport() const

Check if LAMMPS was compiled with PNG format image support.

Returns:

true if PNG image format support is available, false if not

bool configHasJpegSupport() const

Check if LAMMPS was compiled with JPEG format image support.

Returns:

true if JPEG image format support is available, false if not

bool hasGpuDevice() const

Check if GPU device is available for GPU package.

Returns:

true if GPU device found, false otherwise

bool loadLib(const QString &fname)

Load LAMMPS shared library (plugin mode)

Parameters:

fname – Library filename (QString version)

Returns:

true on success, false on failure

bool hasPlugin() const

Check if running in plugin mode.

Returns:

true if plugin mode enabled, false if linked mode


3.3.2. LammpsRunner Class

class LammpsRunner : public QThread

Worker thread for executing LAMMPS simulations.

This class runs LAMMPS simulations in a background thread to maintain UI responsiveness during long calculations. It executes either a LAMMPS command string or a full input file and emits a signal upon completion.

Input is passed using std::string, ensuring clean ownership transfer.

Public Functions

explicit LammpsRunner(QObject *parent = nullptr)

Constructor.

Parameters:

parent – Parent QObject

~LammpsRunner() override = default

Destructor.

LammpsRunner(const LammpsRunner&) = delete
LammpsRunner(LammpsRunner&&) = delete
LammpsRunner &operator=(const LammpsRunner&) = delete
LammpsRunner &operator=(LammpsRunner&&) = delete
void setupRun(LammpsWrapper *_lammps, std::string _input, std::string _file = {}, bool _clearfirst = true)

Prepare the runner thread with LAMMPS instance and commands.

Sets up the runner with the LAMMPS instance and input. Clears any previous LAMMPS state with the “clear” command, unless _clearfirst is false, which continues from the current state (used to extend a previous run). Either input or file should be provided, not both.

Parameters:
  • _lammps – Pointer to LammpsWrapper instance

  • _input – String of LAMMPS commands to execute (can be empty)

  • _file – Input file path to execute (can be empty)

  • _clearfirst – If true, wipe the current LAMMPS system state first

Signals

void resultReady()

Signal emitted when LAMMPS execution completes.

Protected Functions

void run() override

Thread execution function - runs LAMMPS commands or input file.

This function executes in the worker thread. It processes either a string of LAMMPS commands or an input file, then signals completion.


3.4. Visualization Components

3.4.1. ChartWindow Class

class ChartWindow : public QWidget

Window for displaying and managing multiple time-series charts.

ChartWindow provides a GUI for displaying and manipulating multiple charts showing time-series data from LAMMPS simulations (thermodynamic output). It supports data smoothing, zooming via range sliders, and export to various formats (PNG, CSV, YAML, DAT).

Public Functions

explicit ChartWindow(const QString &filename, LammpsGui *lammpsgui = nullptr, QWidget *parent = nullptr)

Constructor.

Parameters:
  • filename – Path to the log file containing the data

  • lammpsgui – Pointer to LammpsGui for sending signals (optional; nullptr for a standalone window with no live simulation)

  • parent – Parent widget

inline int numCharts() const

Get the number of charts currently displayed.

Returns:

Number of charts

inline bool hasTitle(const QString &title, int index) const

Check if a chart at given index has the specified title.

Parameters:
  • title – Title to check

  • index – Chart index

Returns:

true if chart has the title, false otherwise

int getStep() const

Get the current simulation step number.

Returns:

Current step

void resetCharts()

Reset all charts to initial state.

void reset(const QString &filename)

Clear the window for a new run.

Drops all charts and reference lines and re-reads the chart preferences, so the window can be reused instead of destroyed and recreated for every run. Keeps the position and size the window currently has on screen.

Parameters:

filename – Name of the log/input file the new run belongs to

void resetZoom()

Manually update chart display zoom status.

This is needed at an end of a run when the run finishes too quickly and the regular chart update has not yet triggered.

void addChart(const QString &title, int index)

Add a new chart to the window.

Parameters:
  • title – Chart title (thermodynamic property name)

  • index – Chart index

void addData(int step, double data, int index)

Add a data point to a chart.

Parameters:
  • step – Simulation step number

  • data – Data value

  • index – Chart index

void setUnits(const QString &_units)

Set the units displayed for thermodynamic quantities.

Parameters:

_units – Units string (e.g., “real”, “metal”, “lj”)

void setNorm(bool norm)

Enable/disable data normalization.

Parameters:

norm – true to normalize data, false otherwise

void setRangeEnabled(bool enabled)

Enable/Disable range sliders.

Parameters:

enabled – true to enable sliders and false to disable them

void loadData(const PlotData &data, int xcol, const QList<int> &ycols, const PlotErrors &yerrs = {})

Populate the window from an external data table (file plotting)

Replaces any existing charts; each selected y column becomes a chart titled by its column name, with the x axis labeled by the x column. Unlike the live thermo feed this loads all rows in one shot.

Parameters:
  • data – Parsed column data

  • xcol – Index of the column to use as the shared x axis

  • ycols – Indices of the columns to plot, one chart each

  • yerrs – Optional error bars, indexed like the columns of data; an empty or wrongly sized entry means that column has none. Their lower half is used where it is filled in

Protected Functions

void closeEvent(QCloseEvent *event) override

Handle window close event.

Parameters:

event – Close event


3.4.2. ChartColumn Struct

ChartWindow owns one ChartColumn per thermo column: a plain, move-only data holder (src/chartviewer.h) that bundles the column’s PlotSeries objects, cached data bounds, smoothing parameters, display style, and overlay/reference-line state. The single ChartViewer is rebound (via setColumn()) to whichever column is currently selected.

struct ChartColumn

The per-column data and display state of one chart.

Holds everything specific to a single plotted column: its neutral PlotSeries objects, cached data bounds, smoothing parameters, display style, and the overlay/reference-line state. It is a plain (non-QWidget) value type, move-only because of its unique_ptr<PlotSeries> members, so that the single shared renderer can be pointed at any column on demand.

Public Members

int index = -1

Chart index (thermo column id)

double lastX = -1.0

Last (largest) x value appended.

double rawXmin = 1.0e100

Running min x of the raw series (live path)

double rawXmax = -1.0e100

Running max x of the raw series.

double rawYmin = 1.0e100

Running min y of the raw series.

double rawYmax = -1.0e100

Running max y of the raw series.

int window = 10

Smoothing window.

int order = 4

Smoothing polynomial order.

std::unique_ptr<PlotSeries> series

Raw data series (always present)

std::unique_ptr<PlotSeries> smooth

Smoothed data series (created on demand)

std::unique_ptr<PlotSeries> scatter

Raw data as points (created on demand)

std::unique_ptr<PlotSeries> smoothScatter

Processed data as points (created on demand)

std::unique_ptr<PlotSeries> fit

Optional fit-curve overlay (created on demand)

QTime lastUpdate

Time of last chart update.

bool doRaw = true

Show raw data series.

bool doSmooth = false

Show smoothed data series.

bool eosMode = false

True when fit is a BM EOS overlay (visibility follows doSmooth)

ChartDisplayMode dispmode = ChartDisplayMode::Lines

How the raw series is drawn.

QColor rawColor

Raw series color override (invalid = configured default)

qreal rawWidth = Cfg::LINE_WIDTH_DEFAULT

Raw series line width.

qreal rawPointSize = Cfg::POINT_SIZE_DEFAULT

Raw series marker diameter.

ChartDisplayMode smoothmode = ChartDisplayMode::Lines

How the processed series is drawn.

QColor smoothcolor

Processed series color (invalid = configured default)

qreal smoothwidth = Cfg::LINE_WIDTH_DEFAULT

Processed series line width.

qreal smoothpointsize = Cfg::POINT_SIZE_DEFAULT

Processed series marker diameter.

QColor errColor

Error bar color of every series of this column (invalid = configured)

qreal errWidth = Cfg::ERR_WIDTH_DEFAULT

Error bar line width.

std::vector<std::unique_ptr<PlotSeries>> overlaySeries

Extra series from secondary files.

std::vector<std::unique_ptr<PlotSeries>> vlines

Reference line series (decorative)

QList<RefLine> reflineDefs

Reference line definitions (parallel to vlines)

QString yTitle

This column’s Y-axis label (restored on the shared plot)

QString procLabel = QStringLiteral("Smooth")

Label of the processed-series slot in the Plot combo (“Smooth”, or a fit/function name)


3.4.3. ChartViewer Class

class ChartViewer : public QWidget

Rebindable view of a single ChartColumn.

ChartViewer renders whichever ChartColumn it is currently bound to (via setColumn()) with its PlotWidget, supporting both raw and smoothed data display. The column data objects are owned by ChartWindow; this class is only the view.

Public Functions

explicit ChartViewer(QWidget *parent = nullptr)

Constructor &#8212; creates the renderer; no column is bound yet.

Parameters:

parent – Parent widget

~ChartViewer() override

Destructor.

ChartViewer(const ChartViewer&) = delete
ChartViewer(ChartViewer&&) = delete
ChartViewer &operator=(const ChartViewer&) = delete
ChartViewer &operator=(ChartViewer&&) = delete
void setColumn(ChartColumn *c)

Bind this view to a column (or nullptr) and render it.

Unregisters the previous column’s series from the shared plot and (re)attaches and draws c, restoring its Y-axis label. The column is owned by ChartWindow, not by the viewer.

void addPoint(double x, double y)

Append an (x, y) data point to the chart.

The point is appended only if x is greater than the last appended x; this keeps the live thermo feed monotonic in the step number.

Parameters:
  • x – X value (e.g. the simulation step, or an arbitrary abscissa)

  • y – Y value

QRectF getMinMax() const

Get the min/max bounds of the data.

Returns:

Rectangle containing data bounds

void setXAxisRange(double min, double max)

Set the displayed X-axis range (used by the range sliders)

void setYAxisRange(double min, double max)

Set the displayed Y-axis range (used by the range sliders)

void resetZoom()

Reset zoom to show all data.

void updateSmooth()

Recalculate and update smoothed data.

inline int getCount() const

Get number of data points.

Returns:

Number of points in series

QString getName() const

Get the series (data column) name.

This is the per-column identifier (e.g. the thermo keyword), distinct from the shared plot title. Used for data-export column headers.

Returns:

The property/column name this chart was created with

inline double getStep(int index) const

Get step number at given index.

Parameters:

index – Data point index

Returns:

Step number (X value)

inline double getData(int index) const

Get data value at given index.

Parameters:

index – Data point index

Returns:

Data value (Y value)

inline double getError(int index) const

Get the error bar half-height at a given index.

Asymmetric bars are reported by their mean half-height, which is what a fit weighted by the uncertainty can use as a standard deviation.

Parameters:

index – Data point index

Returns:

Half the extent of the error bar, or 0 if the series has none

void setTLabel(const QString &tlabel)

Set chart title.

Parameters:

tlabel – New title

void setYLabel(const QString &ylabel)

Set Y-axis label.

Parameters:

ylabel – New Y-axis label

void setXLabel(const QString &xlabel)

Set the X-axis label.

Parameters:

xlabel – New X-axis label

void setXLabelFormat(const QString &fmt)

Set the X-axis tick label format.

Call after setXLabel() when the x-axis carries non-integer data (e.g. lattice constants from a Plot Data file). The thermo live-feed path leaves the default integer format in place.

Parameters:

fmt – printf-style format string (e.g. “%.6g” for floating-point, “%d” for integer steps)

void addOverlaySeries(const QList<QPointF> &pts, const QString &name, const QColor &color, const QList<double> &yerr = {}, const QList<double> &yerrLo = {})

Add an overlay data series from a second file.

Overlay series are always shown in full (no smoothing); they are included in the axis range calculation.

Parameters:
  • pts – (x, y) data points

  • name – Series name (shown as a tooltip / legend entry)

  • color – Line color

  • yerr – Optional error bars, one per point (ignored if the size differs)

  • yerrLo – Optional lower half of asymmetric error bars (empty = symmetric)

inline int overlaySeriesCount() const

Number of overlay series currently displayed.

void setReferenceLines(const QList<RefLine> &lines)

Set reference lines (replaces any existing set)

Each line spans the full data range perpendicular to its orientation and is updated on every zoom reset. Lines are described by their orientation, position, label (series name), anchor, and color.

Parameters:

lines – List of reference line descriptors

void setLegendPos(LegendPos pos)

Set the in-plot legend placement (corner, or off)

void setRefLabelStyle(double pointSize, double distance, bool boxed)

Set the window-wide reference-label style (font size, gap, boxed)

void setDisplayStyle(ChartDisplayMode mode, const QColor &color, qreal width, qreal pointSize)

Set how the raw data series is displayed.

Parameters:
  • mode – Lines, points, or both

  • color – Series color (invalid color falls back to the theme default)

  • width – Line width (used for the line and lines+points modes)

  • pointSize – Marker diameter (used for the points and lines+points modes)

inline ChartDisplayMode displayMode() const

Current display mode.

inline QColor displayColor() const

Current series color (may be invalid, meaning the theme default)

inline qreal displayWidth() const

Current line width.

inline qreal displayPointSize() const

Current marker diameter.

void setSmoothStyle(ChartDisplayMode mode, const QColor &color, qreal width, qreal pointSize)

Set how the processed (smoothed) data series is displayed.

Parameters:
  • mode – Lines, points, or both

  • color – Series color (invalid color falls back to the theme default)

  • width – Line width (used for the line and lines+points modes)

  • pointSize – Marker diameter (used for the points and lines+points modes)

inline ChartDisplayMode smoothMode() const

Current processed-series display mode.

inline QColor smoothColor() const

Current processed-series color (may be invalid, meaning the theme default)

inline qreal smoothWidth() const

Current processed-series line width.

inline qreal smoothPointSize() const

Current processed-series marker diameter.

void setErrorStyle(const QColor &color, qreal width)

Set how the error bars of this chart are drawn.

The style applies to every series of the chart that carries error bars, so that the bars read as one annotation layer rather than as part of the curve they belong to.

Parameters:
  • color – Bar color (invalid color falls back to the color of the series)

  • width – Bar line width; the end caps grow with it

inline QColor errorColor() const

Current error bar color (may be invalid, meaning the series color)

inline qreal errorWidth() const

Current error bar line width.

void setFitCurve(const QList<QPointF> &points, const QString &name = QString(), bool eosFit = false)

Overlay a fit curve on the chart.

Parameters:
  • points – Curve points (x, y) drawn as an overlay line; created on the first call and replaced on subsequent calls

  • name – Optional series name for the overlay (e.g. the fitted expression or a user label); shown wherever series names are surfaced

  • eosFit – When true the curve is treated as an EOS fit: its visibility follows the doSmooth flag (hidden in Raw mode, visible in Smoothed/Both mode) and it replaces the Savitzky-Golay series while active.

inline bool isEosFit() const

True when the current fit overlay is a Birch-Murnaghan EOS fit.

QString getXLabel() const

Get X-axis label.

Returns:

X-axis label

QString getYLabel() const

Get Y-axis label.

Returns:

Y-axis label


3.4.4. PlotWidget Class

Native QWidget + QPainter 2D line/scatter chart renderer (src/plotwidget.h). It is the sole chart backend; ChartViewer feeds it neutral PlotSeries / PlotAxis model objects plus the Qt-free axis-layout helpers from plotaxismath – no Qt Charts, Graphs, or QML.

class PlotWidget : public QWidget

QPainter-based renderer for the neutral chart model.

Series objects are referenced, not owned: the caller owns each PlotSeries and registers / unregisters it here, then calls update() after changing its data or style.

Public Functions

explicit PlotWidget(QWidget *parent = nullptr)

Constructor.

Parameters:

parent – Parent widget

void setTitle(const QString &title)

Set the chart title (drawn centered at the top)

void setXTitle(const QString &title)

Set the X-axis title.

QString xTitle() const

Get the X-axis title.

void setYTitle(const QString &title)

Set the Y-axis title.

QString yTitle() const

Get the Y-axis title.

void setXRange(double min, double max)

Set the displayed X-axis range.

void setYRange(double min, double max)

Set the displayed Y-axis range.

void setXLabelFormat(const QString &fmt)

Set the printf-style tick label format of the X-axis.

void setGrid(bool major, bool minor)

Toggle major and minor gridline visibility on both axes.

void setLegendPos(LegendPos pos)

Place a legend in one of the plot corners (or turn it off)

The legend lists each visible, named data series (raw / processed / fit / overlays); reference lines and unnamed marker-only mirrors are excluded.

void setRefLabelStyle(double pointSize, double distance, bool boxed)

Style applied to all reference-line labels.

The per-line label position along the line comes from each reference series’ RefAnchor; this sets the window-wide font/offset/box appearance.

Parameters:
  • pointSize – Label font point size (<= 0 keeps the default size)

  • distance – Perpendicular gap between the label and its line, in px

  • boxed – Draw a frame + opaque background behind each label

void addSeries(const PlotSeries *series)

Register a series for drawing (non-owning; ignored if already present)

Parameters:

series – Series owned by the caller

void removeSeries(const PlotSeries *series)

Remove a previously registered series (does not delete it)

bool hasSeries(const PlotSeries *series) const

Whether a series is currently registered.

void clearSeries()

Unregister all series (does not delete them)

Protected Functions

void paintEvent(QPaintEvent *event) override

Paint the chart onto the widget.

QSize sizeHint() const override

Recommended size.


3.4.5. Chart Model and Axis Math

Neutral chart model value types (src/plotseries.h) consumed by PlotWidget, and the Qt-free axis-layout helpers (src/plotaxismath.h: nice-number ticks, tick values, and printf-style label formatting).

Enums

enum class PlotSeriesType

Whether a PlotSeries is drawn as a connected line or as markers.

Values:

enumerator Line
enumerator Scatter
enum class RefAnchor

Where a reference-line label sits along its line.

For a vertical line: Start = top, Center = middle, End = bottom. For a horizontal line: Start = left, Center = center, End = right.

Values:

enumerator Start
enumerator Center
enumerator End
struct PlotSeries
#include <plotseries.h>

One data series in the neutral chart model.

Carries the points plus the minimal styling the native renderer needs.

Public Functions

inline void append(double x, double y)

Append one (x, y) point.

inline void replace(const QList<QPointF> &p)

Replace all points (and drop any error bars, which no longer fit)

inline bool hasErrors() const

Whether the series carries usable error bars.

inline bool hasAsymErrors() const

Whether the bars extend by different amounts up and down.

inline double errHigh(int i) const

How far the bar of point i reaches above the value.

inline double errLow(int i) const

How far the bar of point i reaches below the value.

inline int count() const

Number of points.

inline QPointF at(int i) const

Point at index i.

inline void setVisible(bool v)

Set visibility.

inline bool isVisible() const

Whether the series is visible.

Public Members

PlotSeriesType type = PlotSeriesType::Line

line vs. scatter rendering

QList<QPointF> points

data points in axis coordinates

QList<double> yerr

upper y error per point (empty = none)

QList<double> yerrLo

lower y error per point (empty = symmetric)

QColor errColor

error bar color (invalid = series color)

qreal errWidth = 1.5

error bar line width

QColor color = Qt::black

line / marker color

qreal width = 1.0

line width (Line series)

Qt::PenStyle style = Qt::SolidLine

line style, e.g. dashed reference lines

qreal markerSize = 8.0

marker diameter (Scatter series)

QString name

series label (shown in the legend)

bool visible = true

whether the series is drawn

bool isReference = false

draw as a labeled reference line

QString refLabel

text drawn next to a reference line

RefAnchor refAnchor = RefAnchor::Start

where the label sits along the line

struct PlotAxis
#include <plotseries.h>

One linear value axis in the neutral chart model.

Public Members

double min = 0.0

lower end of the displayed range

double max = 1.0

upper end of the displayed range

QString title

axis title

QString labelFormat = QStringLiteral("%g")

printf-style tick label format

int subTicks = 4

minor subdivisions between major ticks

bool gridVisible = true

draw major gridlines

bool minorGridVisible = true

draw minor gridlines

namespace PlotAxisMath

3.4.6. ImageViewer Class

class ImageViewer : public QDialog

Dialog for viewing and manipulating LAMMPS snapshot images.

This class provides an image viewer dialog for displaying LAMMPS snapshots created by the dump image command. It allows interactive manipulation of visualization parameters such as zoom, rotation, atom size, coloring, and rendering options. Changes can be applied to regenerate the image using the LAMMPS library interface.

dump-image command preparation used by createImage()

Gather widget state and LAMMPS-derived data into a DumpImageParams snapshot

dialog row builders/readers used by the *Settings() slots

Build one compute/fix table row per map entry (shared by fixSettings)

Public Functions

explicit ImageViewer(const QString &fileName, LammpsWrapper *lammps, LammpsGui *lammpsgui, QWidget *parent = nullptr)

Constructor.

Parameters:
  • fileName – Path to the image file to display

  • lammps – Pointer to LammpsWrapper for regenerating images

  • lammpsgui – Pointer to LammpsGui for sending signals

  • parent – Parent widget

~ImageViewer() override

Destructor.

ImageViewer() = delete
ImageViewer(const ImageViewer&) = delete
ImageViewer(ImageViewer&&) = delete
ImageViewer &operator=(const ImageViewer&) = delete
ImageViewer &operator=(ImageViewer&&) = delete
void createImage()

Generate image using current settings.

Constructs and executes a LAMMPS dump image command with current visualization parameters and updates the displayed image.

Protected Functions

bool eventFilter(QObject *watched, QEvent *event) override

Intercept Alt-keystrokes.

void showEvent(QShowEvent *event) override

Redo the initial window fit once shown.


3.4.7. Dump Image Command Builder

The DumpImageParams struct and the buildDumpImageCommand() free function (src/dumpimage.h) form a GUI-free, unit-testable core that assembles the LAMMPS write_dump ... image ... command from a snapshot of the viewer state. ImageViewer populates the struct (resolving all LAMMPS queries up front) and then calls the pure builder, which returns a DumpImageCommand holding the render and dump_modify argument strings; toWriteDumpCommand() composes the final one-shot write_dump command from those pieces.

struct DumpImageParams

Pre-resolved inputs for assembling a LAMMPS dump image command.

ImageViewer::gatherDumpImageParams() populates this struct from the widget state and from a set of LAMMPS library queries (atom/setting/global data) before the image is rendered. All LAMMPS-derived values are captured here as plain data so that buildDumpImageCommand() can run as a pure function &#8212; it never touches the GUI or a live LAMMPS instance and is therefore unit-testable on its own.

The computes/fixes/regions maps hold non-owning pointers to ImageInfo and RegionInfo objects owned elsewhere (by ImageViewer at runtime, or by the test fixture in unit tests); they only need to outlive the call.

Public Members

QString group

atom group to render

QString dumpfile

full path of the temporary .ppm output file

bool atomcustom

use custom atom color/diameter properties

bool useelements

element data available (color/diameter by element)

bool usediameter

per-atom diameter (radius) attribute available

bool usesigma

Lennard-Jones sigma usable as atom radius.

bool showatoms

draw atoms

QString atomcolor

custom atom color property

QString atomdiam

custom atom diameter property (attribute name, a “v_” atom-style variable reference, or a numeric diameter)

double vdwfactor

van der Waals radius scaling factor

double atomSize

explicit atom size (radius)

QString elements

pre-built element <X> <Y> ... argument string

QString adiams

pre-built adiam <i> <d> ... argument string

bool showbodies

draw body particles

int body_flag

LAMMPS body_flag setting.

QString bodycolor

body color property

double bodydiam

body diameter

int bodyflag

body draw flag (triangle, cylinder, or both)

bool showlines

draw line particles

int line_flag

LAMMPS line_flag setting.

QString linecolor

line color property

double linediam

line diameter

bool showtris

draw triangle particles

int tri_flag

LAMMPS tri_flag setting.

QString tricolor

triangle color property

int triflag

triangle draw flag (triangle, cylinder, or both)

double tridiam

triangle diameter

bool showellipsoids

draw ellipsoid particles

int ellipsoid_flag

LAMMPS ellipsoid_flag setting.

QString ellipsoidcolor

ellipsoid color property

int ellipsoidflag

ellipsoid draw flag (triangle or cylinder)

int ellipsoidlevel

ellipsoid refinement level

double ellipsoiddiam

ellipsoid diameter

int nbondtypes

number of bond types

int bond_flag

LAMMPS bond_flag setting.

bool showbonds

draw bonds

QString bondcolor

bond color property (or “c_<id>” when bondbyvalue)

bool bondbyvalue

color bonds by a per-bond compute value (emit bmap)

QString bonddiam

bond diameter property

bool autobond

derive bonds from a distance cutoff

bool haspairstyle

a pair style other than “none” is defined

double bondcutoff

autobond distance cutoff

int xsize

rendered image width in pixels

int ysize

rendered image height in pixels

double zoom

zoom level

double shinyfactor

shininess / specular factor

bool antialias

enable full-scene anti-aliasing

int dimension

system dimension (2 or 3)

int hrot

horizontal rotation angle

int vrot

vertical rotation angle

bool usessao

enable screen-space ambient occlusion

double ssaoval

SSAO strength.

int ssaosamples

SSAO sampling directions, 0 = derived from the SSAO strength.

bool usedepthcue

enable depth cueing

double depthcuefactor

depth cueing strength (0.0 - 1.0)

QString depthcuecolor

fog color name, or “auto” = fade toward the background

QString depthcuestart

fading start as a box fraction along the view direction, or “auto”

bool usedefocus

enable defocusing of distant objects

double defocusfactor

defocus blur strength (0.0 - 1.0)

QString defocusstart

blurring start as a box fraction along the view direction, or “auto”

bool useoutline

draw outlines at depth jumps

int outlinewidth

outline width in pixels (1 - 16)

QString outlinecolor

outline color name

QString specular

specular preset “none”/”wide”/”narrow”/”tight”, or “auto” = highlight width derived from the shiny factor

bool usemetal

enable metallic surface shading

double metalfactor

how metallic the objects appear (0.0 - 1.0)

QString metalfinish

metal surface finish “satin”/”polished”/”mirror”

bool showbox

draw simulation box

double boxdiam

box edge diameter

bool showsubbox

draw subdomain boxes

double subboxdiam

subbox edge diameter

bool showaxes

draw coordinate axes

QString axesloc

axes location

double axeslen

axes length

double axesdiam

axes diameter

bool dynamiccenter

use the dynamic (“d”) instead of the static (“s”) center flavor

double xcenter

view center x coordinate

double ycenter

view center y coordinate

double zcenter

view center z coordinate

double xup

camera up vector x component

double yup

camera up vector y component

double zup

camera up vector z component

int ntypes

number of atom types

QList<QPair<QString, QColor>> color_list

per-type atom color table

QString boxcolor

box / subbox color

QString backcolor

lower background color

QString backcolor2

upper background color

bool usegradient

draw a vertical gradient

double axestrans

axes transparency

double boxtrans

box / subbox transparency

double atomtrans

atom transparency

double bondtrans

bond transparency

double ambientlight

ambient light setting

double keylight

key light setting

double filllight

fill light setting

double backlight

back light setting

double gammaval

gamma adjustment of rendered objects (0.1 - 10.0), 1.0 = unchanged

int version

LAMMPS version (date) id.

QString colormap

name of the selected atom color map

QString mapmin

minimum-value choice for the atom color map

QString mapmax

maximum-value choice for the atom color map

bool revcolormap

reverse (mirror) the atom color map

QString bondcolormap

name of the selected bond color map

QString bondmapmin

minimum-value choice for the bond color map

QString bondmapmax

maximum-value choice for the bond color map

bool revbondcolormap

reverse (mirror) the bond color map

std::map<std::string, ImageInfo*> computes

per-compute graphics settings

std::map<std::string, ImageInfo*> fixes

per-fix graphics settings

std::map<std::string, RegionInfo*> regions

per-region display settings


DumpImageCommand buildDumpImageCommand(const DumpImageParams &p)

Assemble the render and dump_modify argument strings for a dump image.

Pure function: depends only on p, performs no I/O and no LAMMPS calls, and is therefore exercised directly by the unit tests.

Parameters:

p – Fully populated parameter struct (no GUI or LAMMPS access required)

Returns:

The two argument strings (see DumpImageCommand)


struct DumpImageCommand

The two argument strings of an assembled dump image command.

The render options (everything that follows ... image <N> <file>) and the dump_modify options (colors, color maps, lighting, …) are kept separate so the caller can compose either an explicit dump/dump_modify pair or a one-shot write_dump (via toWriteDumpCommand()), and so each builder step can append to whichever string is logical. Both strings begin with a leading space.

Public Members

QString dumpargs

render options after image <N> <file>

QString modifyargs

options for dump_modify <id> / after modify

bool dofixes

a fix/compute graphic is active (write_dump omits noinit)


QString toWriteDumpCommand(const DumpImageCommand &c, const QString &group, const QString &file)

Compose a one-shot write_dump ... image ... command from the pieces.

Parameters:
  • c – the two argument strings from buildDumpImageCommand()

  • group – atom group to render

  • file – output image file name

Returns:

A complete write_dump command string


3.4.8. Color Maps

The dump-image color maps are defined once, as a table of ColorMapDef entries in src/colormaps.cpp. Both the command builder (appendColorMapArgs() in src/dumpimage.cpp) and the settings-dialog preview swatches (addColorMapItems() in src/imageviewersettings.cpp) consume this single source of truth, so they cannot drift apart. See Adding or modifying a color map for how to add or modify a map.

Functions

const ColorMapDef &colorMapDef(const QString &name)

Look up a color-map definition by name.

Parameters:

name – color-map name (e.g. “Viridis”); unknown names fall back to “BWR”

Returns:

reference to the (statically stored) definition

const QStringList &colorMapNames()

The selectable color-map names, in display order.

Returns:

reference to the (statically stored) ordered name list

struct ColorMapStop
#include <colormaps.h>

A single color stop of a dump-image color map.

A stop is either a LAMMPS named color (name non-empty, used verbatim in the generated command and resolved with QColor for the preview) or an explicit RGB color (name empty, r / g / b used). Storing the RGB as floats keeps the generated command identical to the values LAMMPS renders and lets the preview use the very same numbers via QColor::fromRgbF(). pos is the stop position in [0,1] and is only meaningful for continuous maps (the first stop maps to the min value, the last to max).

Public Members

double pos

position in [0,1] (continuous maps); 0 = min, 1 = max

QString name

LAMMPS named color, or empty when an explicit RGB is given.

double r

explicit red in [0,1], used when name is empty

double g

explicit green in [0,1], used when name is empty

double b

explicit blue in [0,1], used when name is empty

struct ColorMapDef
#include <colormaps.h>

Definition of a named dump-image color map.

This is the single source of truth shared by the command builder (appendColorMapArgs() in dumpimage.cpp, which emits dump_modify amap/bmap) and the settings-dialog preview swatches (addColorMapItems() in imageviewersettings.cpp), so the swatch a user picks matches what LAMMPS renders.

Public Members

bool continuous

true: interpolated (cf); false: discrete sequence (sa)

QList<ColorMapStop> stops

ordered color stops


3.4.9. SlideShow Class

class SlideShow : public QDialog

Slideshow viewer for displaying sequences of images.

SlideShow provides a dialog for viewing and navigating through sequences of images, typically from LAMMPS dump image commands. It supports manual navigation (first/prev/next/last), automatic playback with configurable timing, looping, and zoom controls. Images can be exported as a movie file.

Public Functions

explicit SlideShow(const QString &fileName, LammpsGui *lammpsgui = nullptr, QWidget *parent = nullptr)

Constructor.

Parameters:
  • fileName – Path to first image file

  • lammpsgui – Pointer to LammpsGui for sending signals (optional; nullptr for a standalone viewer with no live simulation)

  • parent – Parent widget

~SlideShow() override = default

Destructor.

SlideShow() = delete
SlideShow(const SlideShow&) = delete
SlideShow(SlideShow&&) = delete
SlideShow &operator=(const SlideShow&) = delete
SlideShow &operator=(SlideShow&&) = delete
void addImage(const QString &filename, const QString &label = QString())

Add an image to the slideshow sequence.

Parameters:
  • filename – Path to image file to add

  • label – Text shown in place of the file name (optional)

int addMovie(const QString &filename)

Extract the frames of a movie file and add them as images.

Probes the movie, asks the user to confirm the extraction and to select a frame range and interval, and decodes the selected frames into PNG files inside the image cache, where they are removed together with the rest of the cache when the slide show window is closed.

Parameters:

filename – Path to the movie file

Returns:

Number of images added; 0 when canceled or on failure

inline int imageCount() const

Number of images currently in the slideshow sequence.

void clear()

Clear all images from slideshow.

Protected Functions

void showEvent(QShowEvent *event) override

Redo the initial window fit once shown.


3.4.10. ImageCache Class

SlideShow owns an ImageCache (src/imagecache.h) that holds the temporary files it creates: the PNG copies of image formats that Qt cannot decode natively, and the frames extracted from imported movie files. A source file is converted at most once, since the cache entries are validated against the modification time and the size of the source file, and the whole cache directory is removed when the slide show window is closed.

class ImageCache

Cache of images converted to a format that Qt can decode.

Qt reads only a subset of the image formats that LAMMPS and other tools can write. For the remaining ones (tga, eps, sgi, …) readImage() shells out to ImageMagick and converts the file to a temporary PNG. That conversion is expensive, so the PNG is kept and reused: a file is converted at most once, unless it changes on disk. Cache entries are keyed by the absolute source path and validated against its modification time and size, so a file that is rewritten (a growing dump image sequence, for example) is converted again.

An entry therefore exists only for a file that Qt cannot decode, and a fresh entry answers a request without handing the source file to Qt again. That matters beyond the saved work: several of Qt’s image format plugins print a warning for every file they reject (the TGA plugin is a notorious example), which would otherwise be repeated on every single display of the image. The one unavoidable attempt is made under a QtMessageSilencer, and its output is reported only if ImageMagick cannot rescue the file either. A file that cannot be read at all is remembered as such, so it is neither converted nor complained about twice.

All temporary files live in a single QTemporaryDir that is created on first use and removed, with everything in it, when the cache is destroyed. The directory also hosts the frames extracted from imported movie files, for which makeSubDir() hands out private subdirectories.

The class is not thread-safe and must only be used from the GUI thread.

Public Functions

ImageCache()

Constructor. The temporary directory is created lazily.

~ImageCache()

Destructor. Removes the temporary directory and its contents.

ImageCache(const ImageCache&) = delete
ImageCache(ImageCache&&) = delete
ImageCache &operator=(const ImageCache&) = delete
ImageCache &operator=(ImageCache&&) = delete
QImage readImage(const QString &filename)

Read an image file, converting it first if Qt cannot decode it.

Files that Qt understands are decoded directly and never cached. For the others ImageMagick (magick or convert) is used, if available, and the resulting PNG is cached for subsequent calls. A file that neither Qt nor ImageMagick can read is reported once, on standard error, and then remembered as unreadable.

Parameters:

filename – Path to the image file

Returns:

The decoded image, or a null QImage if it cannot be read

QSize imageSize(const QString &filename)

Dimensions of an image file, without decoding its pixels.

Reads the header only, so it is much cheaper than readImage() when just the dimensions are needed. For a file with a cached conversion the header of the converted PNG is read instead of the original, so a format that Qt cannot decode is not handed to it a second time.

Parameters:

filename – Path to the image file

Returns:

Image size, or an invalid QSize if it cannot be determined

QString makeSubDir(const QString &prefix)

Create a private subdirectory inside the cache directory.

Each call creates a new directory, so two imports of the same movie do not overwrite each other’s frames.

Parameters:

prefix – Name hint; characters outside [A-Za-z0-9_-] are replaced

Returns:

Absolute path of the new directory, or an empty string on failure

void registerFrames(const QString &subdir)

Account for the files a caller has written into a subdirectory.

The cache does not create movie frames itself, so it has to be told about them before it can report them in frameImages() and frameBytes().

Parameters:

subdir – Directory from makeSubDir() that now holds extracted frames

void forget(const QString &filename)

Drop what the cache knows about a single source file.

Deletes its converted copy, if any. Call this when the source file is removed from disk, since its conversion is then useless and would occupy the cache directory until the cache is destroyed.

Parameters:

filename – Path to the source file

void purgeConversions()

Delete every converted image, keeping the extracted movie frames.

A conversion can be redone from its source file on demand, so discarding it only costs time. Movie frames cannot be re-created without running FFmpeg over the movie again and are therefore left alone, as are the records of files that could not be read at all: forgetting those would only make the cache report them a second time.

QString path()

Path of the temporary cache directory, creating it if needed.

Returns:

Absolute path, or an empty string if the directory cannot be made

inline int count() const

Number of source files Qt cannot decode that the cache knows about.

Counts both the files with a converted copy and those remembered as unreadable. Files that Qt decodes directly are never given an entry.

inline int conversions() const

Number of times ImageMagick has been run to convert a file.

A cache that works keeps this at one run per file, however often the file is displayed.

inline int cachedImages() const

Number of converted images currently held in the cache directory.

inline qint64 cachedBytes() const

Total size in bytes of the converted images.

inline int frameImages() const

Number of extracted movie frames registered with registerFrames()

inline qint64 frameBytes() const

Total size in bytes of the extracted movie frames.

inline bool isEmpty() const

Whether the cache directory holds any images at all.

void clear()

Drop all cached conversions and delete the temporary directory.


3.4.11. Movie Frame Import

Movie files are turned into a sequence of images before they can be shown in the slide show viewer. probeMovie() collects the properties of the video stream by running ffprobe, MovieImportDialog lets the user confirm the extraction and select a frame range and interval, and extractMovieFrames() runs ffmpeg to decode the selected frames into the ImageCache. The parsing and frame-counting helpers (src/movieimport.h) are free functions so that they can be unit tested without running either program.

struct MovieInfo

Properties of the first video stream of a movie file.

Filled in by probeMovie(). When valid is false, error holds a message suitable for display in a dialog and all other members are meaningless.

Public Members

bool valid = false

True when the movie was probed successfully.

int width = 0

Frame width in pixels.

int height = 0

Frame height in pixels.

int frames = 0

Number of frames in the video stream.

double fps = 0.0

Nominal frame rate in frames per second.

double duration = 0.0

Duration of the movie in seconds.

QString error

Reason why the movie could not be probed.


class MovieImportDialog : public QDialog

Dialog to confirm and configure the import of movie frames as images.

Shows the properties of the movie, lets the user pick a frame range and a frame interval, and estimates how much temporary disk space the extracted images will need. The estimate is the size of a single decoded sample frame times the number of selected frames. When it exceeds Cfg::MOVIE_WARN_BYTES, Cfg::MOVIE_WARN_FRAMES frames, or most of the free space on the volume holding the temporary directory, a highlighted warning is displayed.

The sample frame is shown as a thumbnail next to the movie properties. When the middle of the selected range moves away from the sampled frame (see sampleOutdated()), a frame near the new middle is decoded after a short delay, and the thumbnail and the size estimate are refreshed from it.

Public Functions

MovieImportDialog(const QString &filename, const MovieInfo &info, QWidget *parent = nullptr)

Constructor.

Parameters:
  • filename – Path to the movie file, used for the labels only

  • info – Movie properties from probeMovie(); must be valid

  • parent – Parent widget

~MovieImportDialog() override = default

Destructor.

MovieImportDialog() = delete
MovieImportDialog(const MovieImportDialog&) = delete
MovieImportDialog(MovieImportDialog&&) = delete
MovieImportDialog &operator=(const MovieImportDialog&) = delete
MovieImportDialog &operator=(MovieImportDialog&&) = delete
int firstFrame() const

First selected frame, counted from 1.

int lastFrame() const

Last selected frame (inclusive), counted from 1.

int frameInterval() const

Selected frame interval; 1 selects every frame.


MovieInfo probeMovie(const QString &filename)

Determine the properties of a movie file by running ffprobe.

Parameters:

filename – Path to the movie file

Returns:

Movie properties, with MovieInfo::valid indicating success

MovieInfo parseProbeOutput(const QByteArray &json)

Extract the movie properties from the JSON output of ffprobe.

Separated from probeMovie() so that the parsing can be tested without running ffprobe.

Parameters:

json – Output of “ffprobe -of json” for the first video stream

Returns:

Movie properties; MovieInfo::frames is 0 when the frame count is not stored in the container and must be determined separately

double parseFrameRate(const QString &rate)

Convert an FFmpeg frame rate to a number.

Parameters:

rate – Rate as a rational (“30000/1001”) or plain number (“25”)

Returns:

Frames per second, or 0.0 if rate cannot be parsed

int selectedFrameCount(int first, int last, int interval)

Number of frames selected by a range and a stride.

The frame numbers may be counted from either 0 or 1, the result is the same.

Parameters:
  • first – First frame of the range

  • last – Last frame of the range (inclusive)

  • interval – Stride; 1 selects every frame, 2 every other one, …

Returns:

Number of selected frames, or 0 if the arguments are inconsistent

QStringList extractMovieFrames(QWidget *parent, const QString &filename, const QString &outdir, int first, int last, int interval, QString &error)

Extract selected frames of a movie into individual PNG files.

Runs FFmpeg with a progress dialog that lets the user abort a long extraction. On abort or failure the partial output is removed and an empty list is returned.

Parameters:
  • parent – Parent widget of the progress dialog

  • filename – Path to the movie file

  • outdir – Existing directory that receives the PNG files

  • first – First frame to extract, counted from 1

  • last – Last frame to extract (inclusive), counted from 1

  • interval – Stride; 1 extracts every frame, 2 every other one, …

  • error – Set to a message when the result is empty

Returns:

Paths of the extracted PNG files in movie order, empty on failure


3.5. Dialog Components

3.5.1. FindAndReplace Class

class FindAndReplace : public QDialog

Find and Replace dialog for the code editor.

FindAndReplace provides a dialog for searching and replacing text in the CodeEditor. It supports case-sensitive/insensitive search, whole word matching, text wrapping, and batch replace operations. The dialog is non-modal so users can continue editing while searching.

Public Functions

explicit FindAndReplace(CodeEditor *_editor, QWidget *parent = nullptr)

Constructor.

Parameters:
  • _editor – Pointer to the CodeEditor to search in

  • parent – Parent widget

~FindAndReplace() override = default

Destructor.

FindAndReplace() = delete
FindAndReplace(const FindAndReplace&) = delete
FindAndReplace(FindAndReplace&&) = delete
FindAndReplace &operator=(const FindAndReplace&) = delete
FindAndReplace &operator=(FindAndReplace&&) = delete

3.5.2. SetVariables Class

class SetVariables : public QDialog

Dialog for editing LAMMPS index-style variable definitions.

SetVariables provides a dialog for managing name-value pairs that will be used as index-style variables in LAMMPS input scripts. Users can add, delete, and edit variable definitions. The dialog shows the variables that the input script defines or uses; values that override a differing definition in the input script are shown in bold with a tooltip listing the script value.

Public Functions

explicit SetVariables(QList<VariableEntry> &vars, QWidget *parent = nullptr)

Constructor.

Parameters:
  • vars – Reference to list of variable entries (modified in place)

  • parent – Parent widget

~SetVariables() override = default

Destructor.

SetVariables() = delete
SetVariables(const SetVariables&) = delete
SetVariables(SetVariables&&) = delete
SetVariables &operator=(const SetVariables&) = delete
SetVariables &operator=(SetVariables&&) = delete

3.5.3. ShellAliases Class

class ShellAliases : public QDialog

Editor for the aliases the command window defines in its shell.

The shell the command window starts reads the user’s start-up file, but a section of that file guarded by a test for a terminal stops before it runs, because the shell is reading a pipe. On several distributions that is where ls, ll and l. are defined, so those go missing while every other alias is present. Programs behave differently for the same reason: ls lists one entry per line rather than in columns unless it is told otherwise.

Rather than give the shell a terminal, this dialog lets those few aliases be stated once and defines them in every shell the command window starts. The defaults cover the common case &#8212; ls and ll with the arguments that restore the output a terminal would have produced.

Only what is in the table is sent, and only when a shell starts or the table is accepted; nothing else ever reaches the shell without being typed.

See also

CommandWindow

Public Functions

explicit ShellAliases(QWidget *parent = nullptr)

Constructor.

Parameters:

parent – Parent widget

~ShellAliases() override = default
ShellAliases() = delete
ShellAliases(const ShellAliases&) = delete
ShellAliases(ShellAliases&&) = delete
ShellAliases &operator=(const ShellAliases&) = delete
ShellAliases &operator=(ShellAliases&&) = delete

Public Slots

void accept() override

Store the table and close.

Public Static Functions

static QList<ShellAlias> aliases()

The aliases to define, in the order they are listed.

The defaults are returned until the dialog has been accepted once, so a new installation starts with ls and ll already useful.

Returns:

Name and definition of each alias

static QList<ShellAlias> defaults()

The aliases a new installation starts with.

Returns:

Name and definition of each alias


3.5.4. ShellPrompt Class

class ShellPrompt : public QLineEdit

Input line that completes with Tab, the way a shell prompt does.

A plain QLineEdit gives Tab away to the focus chain and completes with nothing, which is the wrong half of both. This takes the key back: Tab offers what matches the word being typed, Tab again walks the offers, and a word with only one match is completed without a list appearing at all.

Both interceptions have to happen in event() rather than in keyPressEvent() or an event filter, for two separate reasons:

  • QWidget::event() hands the focus on when it sees Tab, before keyPressEvent() is ever reached.

  • While the completion popup is up, QCompleter delivers keys to this widget by calling event() on it directly instead of sending them through the event loop, so an event filter installed on the line edit never sees them.

The same override is what keeps Enter from doing two things at once; see event() for what Qt does with it when left alone.

The widget completes from whatever QCompleter it was given with setCompleter(). What it does not know is which list the word being typed should be completed from &#8212; in a shell that depends on where in the line the word is &#8212; so it emits completing() first and leaves that choice to its owner.

Public Functions

inline explicit ShellPrompt(QWidget *parent = nullptr)

Constructor.

Parameters:

parent – Parent widget (optional)

~ShellPrompt() override = default

Destructor.

ShellPrompt(const ShellPrompt&) = delete
ShellPrompt(ShellPrompt&&) = delete
ShellPrompt &operator=(const ShellPrompt&) = delete
ShellPrompt &operator=(ShellPrompt&&) = delete

Signals

void completing(const QString &text)

Emitted before completions are computed, so the completer can be pointed at the list this word should be completed from.

Parameters:

text – The line as it currently stands

Protected Functions

bool event(QEvent *event) override

Filter out the keys a completing prompt has to own.

Parameters:

event – Event to handle

Returns:

true if the event was consumed


3.5.5. Index Variable Helpers

The parse, merge, and override-detection helpers behind the Set Variables dialog and the editor’s override markers are free functions over plain value types (src/inputvariables.h).

struct VariableEntry

One index-style variable managed via the Set Variables dialog.

The effective value is what LAMMPS-GUI defines before a run (like the -var command line flag would); the script value records what the input script currently assigns so that edits to the input can be told apart from overrides entered in the Set Variables dialog.

Public Members

QString name

variable name

QString value

effective value defined before a run; empty if unset

QString scriptValue

value assigned in the input script; empty if not defined there

struct IndexVariableMatch

Result of matching a line against an index variable definition.

The value offsets refer to the unmodified line text so they can be used to locate the value in a text editor for visual markup.

Public Members

bool valid = false

true if the line defines an index style variable

QString name

variable name

QString value

assigned value with surrounding whitespace removed

int valueStart = 0

offset of the value in the line

int valueLength = 0

length of the (trimmed) value in the line

Functions

IndexVariableMatch matchIndexVariable(const QString &line)

Match a single input script line against an index variable definition.

Parameters:

line – One line of input script text

Returns:

Match result with the name, value, and value position on success

QList<VariableEntry> parseInputVariables(const QString &text)

Collect index-style variables from an input script.

Records every index variable definition (first definition wins, as in LAMMPS) with its assigned value and every use of an otherwise undefined variable with an empty value.

Parameters:

text – Complete input script text

Returns:

List of variable entries in order of appearance

QList<VariableEntry> mergeInputVariables(const QList<VariableEntry> &parsed, const QList<VariableEntry> &previous)

Fold a fresh parse of the input script into an existing variable list.

A changed, non-empty script value is the most recent user edit and replaces the current value, while an unchanged one preserves the value (which may be an override from the Set Variables dialog). Entries no longer present in the script are kept as long as they have a value (they may apply to included files) and dropped otherwise.

Parameters:
  • parsed – Entries from parsing the current input script

  • previous – Current variable list (parse results plus dialog edits)

Returns:

Merged list: script order first, then retained leftover entries

bool isOverridden(const VariableEntry &entry)

Check whether an entry overrides the definition in the input script.

Parameters:

entry – Variable entry to check

Returns:

true if the entry’s value replaces a different script definition


3.5.6. PlotDataDialog Class

class PlotDataDialog : public QDialog

Dialog to choose which columns of a PlotData to plot.

Presents the parsed columns of an external data file and lets the user assign a role to each column: exactly one column is the shared x-axis (exclusive radio buttons), any number of columns are plotted on the y-axis (checkboxes), and columns with neither selected are ignored. When the x-axis selection moves to a different column, the previous x-axis column becomes a y-axis column. A small preview of the first rows is shown to help identify column content.

A “Compute derived column” section at the bottom lets the user add derived columns from expressions that reference the existing column names as variables (e.g. nfcc/ntot or load_eV_per_Ang*1.602176634). The column’s first-row value is also available under colname_first.

For a block-structured fix ave/\* file (see plotblockdata.h) the dialog grows a “Data blocks” group above the column grid, which reduces the blocks to the single flat table the columns below then refer to: either one chosen block, or the average of a range of them with error bars. Changing the reduction rebuilds the column grid, keeping the roles and names the user has already assigned and re-evaluating any derived columns against the new table.

Public Functions

explicit PlotDataDialog(const PlotData &data, QWidget *parent = nullptr)

Constructor for a flat data table.

Parameters:
  • data – Parsed column data to choose from (stored as a working copy)

  • parent – Parent widget

explicit PlotDataDialog(const PlotBlockData &blocks, QWidget *parent = nullptr)

Constructor for a block-structured fix ave/* file.

Starts out on the reduction that suits the detected format, which the “Data blocks” group then lets the user change.

Parameters:
  • blocks – Parsed blocks (stored as a working copy)

  • parent – Parent widget

~PlotDataDialog() override = default
PlotDataDialog() = delete
PlotDataDialog(const PlotDataDialog&) = delete
PlotDataDialog(PlotDataDialog&&) = delete
PlotDataDialog &operator=(const PlotDataDialog&) = delete
PlotDataDialog &operator=(PlotDataDialog&&) = delete
int xColumn() const

Index of the column used as the x-axis.

Returns the index of the column whose x-axis radio button is selected. Falls back to 0 if no column is selected as the x-axis. Indices refer to buildData() columns.

Returns:

Column index

QList<int> yColumns() const

Indices of the columns selected to plot on the y-axis.

Indices refer to buildData() columns.

Returns:

List of column indices (all columns with a checked y checkbox)

QStringList columnNames() const

User-edited column names (may differ from the original parsed names)

Each entry corresponds to a column by index in buildData().

Returns:

List of column name strings, one per column

PlotData buildData() const

Return the working data with renames and derived columns applied.

Includes any columns added via the “Compute derived column” section and applies the user’s name edits. Use this in place of calling renameColumns() on the original data.

Returns:

Updated PlotData ready for plotting

PlotErrors buildErrors() const

Error bars belonging to the columns of buildData()

Only a block average produces them; everything else returns entries that are all empty. Indexed like the columns of buildData().

Returns:

Per-column error bars


3.5.7. Preferences Class

class Preferences : public QDialog

Preferences/Settings dialog for LAMMPS-GUI.

This dialog provides a tabbed interface for configuring various aspects of LAMMPS-GUI including:

  • General settings (LAMMPS library path, plugins, etc.)

  • Accelerator package settings

  • Image viewer defaults

  • Editor appearance and behavior

  • Chart viewer settings

Settings are persisted using QSettings and loaded on startup.

Public Functions

explicit Preferences(LammpsWrapper *lammps, LammpsGui *lammpsgui, QWidget *parent = nullptr)

Constructor.

Parameters:
  • lammps – Pointer to LammpsWrapper for querying LAMMPS configuration

  • lammpsgui – Pointer to LammpsGui for sending signals

  • parent – Parent widget

~Preferences() override

Destructor.

Preferences() = delete
Preferences(const Preferences&) = delete
Preferences(Preferences&&) = delete
Preferences &operator=(const Preferences&) = delete
Preferences &operator=(Preferences&&) = delete
inline void setRelaunch(bool val)

Set flag indicating application needs restart.

Some settings require restarting the application to take effect.

Parameters:

val – true if restart needed, false otherwise

inline void setRelaunch(const QString &reason)

Request a restart and record why.

The reasons are collected and shown together in the dialog that announces the relaunch, so a single visit to the preferences that changes several restart-only settings explains all of them.

Parameters:

reason – One sentence naming the setting that changed


3.5.8. GeneralTab Class

class GeneralTab : public QWidget

Preferences Tab for General LAMMPS-GUI Settings.

Public Functions

explicit GeneralTab(QSettings *settings, LammpsWrapper *lammps, LammpsGui *lammpsgui, QWidget *parent = nullptr)

Constructor.

Parameters:
  • settings – Pointer to QSettings for storing preferences

  • lammps – Pointer to LammpsWrapper for querying LAMMPS configuration

  • lammpsgui – Pointer to LammpsGui for sending signals

  • parent – Parent widget


3.5.9. AcceleratorTab Class

class AcceleratorTab : public QWidget

Preferences Tab for LAMMPS Accelerator settings.

Public Types

enum AccelType

Constants for selecting LAMMPS accelerator package

Values:

enumerator None

no accelerator

enumerator Opt

OPT package.

enumerator OpenMP

OPENMP package.

enumerator Intel

INTEL package.

enumerator Kokkos

KOKKOS package.

enumerator Gpu

GPU package.

enum AccelPrec

Constants for selecting LAMMPS accelerator precision

Values:

enumerator Double

full double precision

enumerator Mixed

only accumulators in double precision, rest in single precision

enumerator Single

full single precision

Public Functions

explicit AcceleratorTab(QSettings *settings, LammpsWrapper *lammps, QWidget *parent = nullptr)

Constructor.

Parameters:
  • settings – Pointer to QSettings for storing preferences

  • lammps – Pointer to LammpsWrapper for querying available accelerator packages

  • parent – Parent widget


3.5.10. SnapshotTab Class

class SnapshotTab : public QWidget

Preferences Tab for Snapshot Viewer Settings.

Public Functions

explicit SnapshotTab(QSettings *settings, QWidget *parent = nullptr)

Constructor.

Parameters:
  • settings – Pointer to QSettings for storing preferences

  • parent – Parent widget


3.5.11. EditorTab Class

class EditorTab : public QWidget

Preferences Tab for LAMMPS-GUI Editor Settings.

Public Functions

explicit EditorTab(QSettings *settings, QWidget *parent = nullptr)

Constructor.

Parameters:
  • settings – Pointer to QSettings for storing preferences

  • parent – Parent widget


3.5.12. ChartsTab Class

class ChartsTab : public QWidget

Preferences Tab for LAMMPS-GUI Charts Viewer Settings.

Public Functions

explicit ChartsTab(QSettings *settings, QWidget *parent = nullptr)

Constructor.

Parameters:
  • settings – Pointer to QSettings for storing preferences

  • parent – Parent widget


3.5.13. AboutDialog Class

class AboutDialog : public QDialog

Custom About dialog for LAMMPS-GUI.

AboutDialog displays version information, LAMMPS configuration details, and available styles in scrollable text areas. The dialog automatically scrolls down when the content exceeds the visible area, pauses at the bottom, and then returns back to the top. When style information is available, the dialog allocates 2/3 of the combined scroll area space to the configuration information text and 1/3 to the style information text.

The style information text uses the configured fixed-width font from the QSettings keys “monofamily” and “monosize” while the rest uses the application’s default (variable width) font.

Public Functions

AboutDialog(const QString &version, const QString &info, const QString &details, int minwidth, QWidget *parent = nullptr)

Constructor.

Parameters:
  • version – Version information text displayed at the top

  • info – LAMMPS configuration info displayed in a scroll area

  • details – Style information displayed in a scroll area with fixed-width font

  • minwidth – minimum width of dialog

  • parent – Parent widget

~AboutDialog() override = default
AboutDialog() = delete
AboutDialog(const AboutDialog&) = delete
AboutDialog(AboutDialog&&) = delete
AboutDialog &operator=(const AboutDialog&) = delete
AboutDialog &operator=(AboutDialog&&) = delete

Protected Functions

void showEvent(QShowEvent *event) override

Event handler for widget show events; implements the auto-scroll functionality.

Parameters:

event – The show event


3.6. Utility Components

3.6.1. CommandWindow Class

class CommandWindow : public QWidget

A shell prompt with a scrollback, next to the simulation.

CommandWindow forwards typed lines to one long-lived shell process and streams what it writes back into a read-only scrollback. It exists for the ordinary work that surrounds a run &#8212; post-process a dump file with a Python script, look at what a run just wrote, call a plotting tool &#8212; without leaving the GUI.

It is deliberately not a terminal emulator: there is no pseudo terminal, so no escape sequence interpretation, no cursor addressing, no color, and no curses program. TERM is set to dumb precisely so that a program needing more than a stream of bytes finds out and says so, rather than writing escape sequences into a scrollback that cannot interpret them.

The shell is kept alive between commands, which is what makes cd, pushd / popd, environment variables and the rest of the shell state work at all. This class does not implement any of them; it only observes the result, by appending a sentinel to every command that reports the exit status and the shell’s working directory.

Public Functions

explicit CommandWindow(LammpsGui *lammpsgui, QWidget *parent = nullptr)

Constructor.

Parameters:
  • lammpsgui – Pointer to the main window, which provides quit() and the shared menus (may be nullptr in standalone use)

  • parent – Parent widget

~CommandWindow() override

Destructor; ends the shell process.

CommandWindow() = delete
CommandWindow(const CommandWindow&) = delete
CommandWindow(CommandWindow&&) = delete
CommandWindow &operator=(const CommandWindow&) = delete
CommandWindow &operator=(CommandWindow&&) = delete
void changeDirectory(const QString &dir)

Move the shell to a directory.

Sent as a command, so the shell stays the one place that knows where it is and the prompt is updated from its answer like any other change. Held back until the shell is at a prompt when a command is running.

Parameters:

dir – Directory to change to

Public Static Functions

static QString preferredShell()

The command interpreter that will be run.

The shell selected in the preferences, if one was. Otherwise $SHELL on Unix-like systems, falling back to /bin/bash and then /bin/sh; COMSPEC% on Windows, falling back to cmd.exe.

Returns:

Path of the user’s preferred shell

static QStringList availableShells()

The command interpreters installed on this machine.

On Unix-like systems the entries of /etc/shells that exist and are not a nologin, plus $SHELL. On Windows cmd.exe, PowerShell and any bash.exe found on the search path or in a Git for Windows installation. Each shell name appears once: a shell listed under several paths (e.g. /bin and /usr/bin) is offered only under the first of them, with the spelling of $SHELL taking precedence.

Returns:

Sorted list of shells the preferences can offer

Protected Functions

bool eventFilter(QObject *watched, QEvent *event) override

Filter the prompt’s key presses for the history keys.

Parameters:
  • watched – Object being watched

  • event – Event to filter

Returns:

true if the event was consumed


3.6.2. WindowLayout Class

enum class ViewSlot

The output views LammpsGui presents alongside the editor.

One enumerator per view that LammpsGui keeps for the lifetime of a session (as opposed to the transient file viewers and inspection windows, which are created and closed on demand). Used to address a view in WindowLayout without the layout having to know the concrete widget classes.

Values:

enumerator Log

Output window with the captured LAMMPS log.

enumerator Chart

Charts window with the thermo data of the current run.

enumerator Image

Snapshot image viewer.

enumerator SlideShow

Slide show viewer for dump image sequences.

enumerator Variables

Variables window listing the active index variables.

enumerator Command

Shell prompt with a scrollback.

enumerator Count

Number of slots; not a view itself.

enum class LayoutMode

How the output views are presented.

Values:

enumerator Windows

Each view is an individual, freely placed top-level window.

enumerator Docked

The views are docked into the main window around the editor.

class WindowLayout : public QObject

Presentation policy for the output views of the main window.

WindowLayout is the single place that decides how an output view is put in front of the user. LammpsGui creates and owns the view widgets and keeps its typed pointers to them, but does not call show(), hide() or isVisible() on them directly: it hands each widget to the layout with place() and then addresses it by its ViewSlot.

Two policies are available, chosen once at construction from the user preference:

  • LayoutMode::Windows keeps every view an individual top-level window, freely placed and stacked, which is what the application has always done.

  • LayoutMode::Docked puts the views into dock areas around the editor, which stays the central widget: the charts, image and slide show views share a tabbed group on the right, the log, the variables view and the command window share a group across the full width at the bottom.

In docked mode the layout owns one QDockWidget per slot, created up front so that a saved arrangement can be restored before the views themselves exist. place() only swaps the content of the dock, so a view that is destroyed and rebuilt (as the image viewer is on every render) keeps its position and its place in the tab order.

The layout never owns the view widgets themselves. It watches them for destruction, so a slot whose widget is deleted elsewhere empties itself and never hands out a dangling pointer.

See also

LammpsGui for the owner of both the layout and the view widgets

Public Functions

WindowLayout(QMainWindow *mainwindow, LayoutMode mode)

Constructor.

In docked mode the dock widgets are created and a previously saved arrangement is restored here, before any view exists.

Parameters:
  • mainwindow – Main window the views belong to; also becomes the parent object, so the layout is deleted along with it

  • mode – Presentation policy to apply

~WindowLayout() override

Destructor.

WindowLayout() = delete
WindowLayout(const WindowLayout&) = delete
WindowLayout(WindowLayout&&) = delete
WindowLayout &operator=(const WindowLayout&) = delete
WindowLayout &operator=(WindowLayout&&) = delete
inline LayoutMode mode() const

The policy this layout applies.

Returns:

The mode passed to the constructor

void place(ViewSlot slot, QWidget *view)

Put a view widget into a slot.

Replaces whatever the slot held before without deleting it &#8212; the widgets stay owned by LammpsGui. Safe to call again with the same widget, which is what a reused Output or Charts window does.

Parameters:
  • slot – Slot the widget belongs to

  • view – Widget to present; may be nullptr to empty the slot

QWidget *view(ViewSlot slot) const

Widget currently in a slot.

Parameters:

slot – Slot to query

Returns:

The widget, or nullptr if the slot is empty

void show(ViewSlot slot)

Show the view in a slot.

Does nothing when the slot is empty.

Parameters:

slot – Slot to show

void hide(ViewSlot slot)

Hide the view in a slot.

Does nothing when the slot is empty.

Parameters:

slot – Slot to hide

void raise(ViewSlot slot)

Show the view in a slot and bring it to the front.

Use for an explicit request from the user. Unlike show(), this pulls the view to the front of its tab group, which is not wanted for the periodic updates during a run.

Parameters:

slot – Slot to raise

void setVisible(ViewSlot slot, bool visible)

Show or hide the view in a slot.

Parameters:
  • slot – Slot to update

  • visible – true to show the view, false to hide it

bool toggle(ViewSlot slot)

Flip the visibility of the view in a slot.

Docked, a view that is on screen without holding the keyboard focus is raised and focused rather than hidden, so the key that opened a panel is also the key that goes back to it; a second press, with the focus in it by then, hides it as before.

Persists the new state for the slots that have a “show by default” preference (Output and Charts), so the next session starts the way the session ended.

Parameters:

slot – Slot to toggle

Returns:

Visibility of the view after the call (false for an empty slot)

void focusNextPane(bool forward)

Move the keyboard focus to the neighboring pane.

The panes are the editor and the panels that are on screen, walked in the order they are arranged around it and wrapping at either end. A panel behind a tab is not a pane of its own: it is reached with the key that opens it, which raises it within its group. Does nothing with individual windows, where the window manager has a key for this.

Parameters:

forward – true for the next pane, false for the previous one

bool isVisible(ViewSlot slot) const

Check whether the view in a slot is visible.

Parameters:

slot – Slot to query

Returns:

true if the slot holds a widget and that widget is visible

void addAuxiliaryView(QWidget *view, ViewSlot group, const QString &title)

Show a transient view as a tab beside an existing panel.

With individual windows this just shows the widget. Docked, it gets a dock of its own tabbed into that group, which is removed again when the widget is destroyed.

Parameters:
  • view – Widget to show; it keeps its own lifetime

  • group – Slot whose dock the new tab joins

  • title – Short label for the tab &#8212; the window title of a viewer is far too long to sit in one

void saveState() const

Store the current dock arrangement in the settings.

Does nothing in windowed mode, where the views carry their own geometry. Call before the main window is destroyed.

Signals

void viewActivated(QWidget *view)

A view was brought to the front of its group.

The combined layout shows one menu bar for the whole window, so whoever owns it needs to know which panel the user just asked to see.

Parameters:

view – The view now in front, or nullptr if the slot was empty

Protected Functions

bool eventFilter(QObject *watched, QEvent *event) override

Track the docked views and their containers.

Parameters:
  • watched – Object being watched: the main window (resizes keep the dock proportions), a dock (a dragged splitter updates them), or a view (its close is redirected to its dock)

  • event – Event to inspect

Returns:

true if the event was consumed


3.6.3. URLDownloader Class

class URLDownloader

Utility class for downloading files over HTTPS.

URLDownloader provides a synchronous interface for downloading files from HTTPS URLs. It respects the “https_proxy” preference setting (or the https_proxy environment variable) when configured.

See also

Preferences for the proxy setting

Public Functions

explicit URLDownloader(QWidget *parent = nullptr)

Construct a new URLDownloader.

Parameters:

parent – Optional parent widget for progress dialogs

~URLDownloader()

Destructor.

URLDownloader(const URLDownloader&) = delete
URLDownloader(URLDownloader&&) = delete
URLDownloader &operator=(const URLDownloader&) = delete
URLDownloader &operator=(URLDownloader&&) = delete
bool download(const QString &url, const QString &file, bool showDialog = false, bool keepBackup = false)

Download a file from the given HTTPS URL to a local file.

Performs a synchronous (blocking) download of the resource at url, writing the result to the local file file. Respects the configured HTTPS proxy setting. Optionally display a dialog with the downloaded URL and the location of the downloaded file.

When a SHA256SUMS file is available in the same remote directory, the checksum of the downloaded data is verified before it replaces an existing file, so a corrupted download never clobbers a working file.

Parameters:
  • url – The HTTPS URL to download from

  • file – The local file path to write to

  • showDialog – Display a dialog with the downloaded URL and target file location while downloading

  • keepBackup – Rename an existing target file to a backup name instead of replacing it in place; required to update a shared library that is currently loaded on Windows, where a loaded library can be renamed but not deleted or overwritten. The caller is responsible for removing the backup file eventually (LAMMPS-GUI does this at launch).

Returns:

true if the download completed successfully, false otherwise

inline QString errorString() const

Return the last error message.

Returns:

Human-readable error description or empty string

void abort()

Abort the current download and any further ones on this instance.

Safe to call from a slot triggered while download() blocks in its event loop (e.g. the Cancel button of a progress dialog). The in-flight request is aborted and all subsequent download() calls on this instance fail immediately, so one cancellation stops a whole batch of downloads.

inline bool wasAborted() const

Return whether the download was canceled via abort()

QString getRemoteChecksum(const QString &url)

Return the remote SHA-256 checksum for a given URL.

Fetches the SHA256SUMS file from the same remote directory as the resource at url, and returns the expected hex-hash for the resource’s filename.

Parameters:

url – The HTTPS URL of the resource

Returns:

Hex-hash string or empty string if not found or on error

Public Static Functions

static QString getLocalChecksum(const QString &file)

Compute the local SHA-256 checksum for a given file.

Parameters:

file – The local file path

Returns:

Hex-hash string or empty string on error


3.6.4. DownloadProgress Class

class DownloadProgress : public QDialog

Splash-style transient dialog showing the progress of a batch download.

Shows a logo, a headline, a single activity line, a dedicated progress bar, and a Cancel button while files are downloaded. The bar is indeterminate (busy indicator) while the number of files is not yet known (e.g. during the initial fetch of a manifest) and switches to determinate per-file progress afterwards. Canceling (button, escape, or closing the dialog) emits QDialog::rejected(); the caller connects that to aborting the download. When the batch ends (success or failure), the caller must end the dialog with accept() &#8212; QDialog::close() implies reject() and would be indistinguishable from a user cancellation.

The setters show the dialog and process pending events, so the updated state is painted even when the caller immediately blocks in a synchronous download loop afterwards.

Public Functions

explicit DownloadProgress(const QString &headline, const QPixmap &logo, QWidget *parent = nullptr)

Create the dialog.

Parameters:
  • headline – Bold headline describing the batch (e.g. the tutorial name)

  • logo – Image shown to the left of the text (may be null)

  • parent – Parent widget

~DownloadProgress() override = default
DownloadProgress() = delete
DownloadProgress(const DownloadProgress&) = delete
DownloadProgress(DownloadProgress&&) = delete
DownloadProgress &operator=(const DownloadProgress&) = delete
DownloadProgress &operator=(DownloadProgress&&) = delete
void setBusy(const QString &text)

Show indeterminate (busy) progress with the given activity text.

void setProgress(const QString &text, int value, int maximum)

Show determinate progress with the given activity text.

Parameters:
  • text – Current activity (e.g. name of the file being downloaded)

  • value – Number of completed items

  • maximum – Total number of items


3.6.5. FileViewer Class

class FileViewer : public QPlainTextEdit

Read-only text viewer for displaying file contents.

FileViewer provides a simple read-only text window for viewing file contents. It’s used in the context menu of the code editor to view files referenced in LAMMPS input scripts (data files, potential files, etc.). The viewer supports keyboard shortcuts for closing and stopping the simulation.

Public Functions

explicit FileViewer(const QString &filename, LammpsGui *lammpsgui, const QString &title = "", QWidget *parent = nullptr)

Constructor.

Parameters:
  • filename – Path to file to display

  • lammpsgui – Pointer to LammpsGui for sending signals

  • title – Window title (defaults to filename if empty)

  • parent – Parent widget

~FileViewer() override = default

Destructor.

FileViewer() = delete
FileViewer(const FileViewer&) = delete
FileViewer(FileViewer&&) = delete
FileViewer &operator=(const FileViewer&) = delete
FileViewer &operator=(FileViewer&&) = delete

Protected Functions

void resizeEvent(QResizeEvent *event) override

Keep the menu bar across the top of the viewport.

Parameters:

event – Resize event


3.6.6. LogWindow Class

class LogWindow : public QPlainTextEdit

Text viewer for LAMMPS log output with warning/error detection.

LogWindow specializes QPlainTextEdit for LAMMPS log viewing. It highlights warnings and errors, detects embedded YAML data for extraction, provides navigation between warnings, and makes error URLs clickable.

Public Functions

LogWindow(const QString &filename, LammpsGui *lammpsgui, QWidget *parent = nullptr)

Constructor.

Parameters:
  • filename – Name of the input file the run belongs to (used for default save-file names)

  • lammpsgui – Pointer to LammpsGui for sending signals

  • parent – Parent widget

~LogWindow() override

Destructor.

void reset(const QString &filename)

Clear the window for a new run.

Discards the collected log text and the warning/error counters so the window can be reused instead of destroyed and recreated for every run. Keeps the position and size the window currently has on screen.

Parameters:

filename – Name of the input file the new run belongs to

LogWindow() = delete
LogWindow(const LogWindow&) = delete
LogWindow(LogWindow&&) = delete
LogWindow &operator=(const LogWindow&) = delete
LogWindow &operator=(LogWindow&&) = delete

Protected Functions

void closeEvent(QCloseEvent *event) override

Handle window close event.

Parameters:

event – Close event

void mouseDoubleClickEvent(QMouseEvent *event) override

Handle double-click to open URLs.

Parameters:

event – Mouse event

void contextMenuEvent(QContextMenuEvent *event) override

Show context menu with log-specific actions.

Parameters:

event – Context menu event

void changeEvent(QEvent *event) override

Keep the fixed-width document font when the inherited font changes.

Parameters:

event – Change event

void resizeEvent(QResizeEvent *event) override

Keep the menu bar across the top of the viewport.

Parameters:

event – Resize event

bool checkYaml()

Check if log contains embedded YAML data.

Returns:

true if YAML data detected, false otherwise


3.6.7. FlagWarnings Class

class FlagWarnings : public QSyntaxHighlighter

Syntax highlighter for LAMMPS warning and error messages.

FlagWarnings extends QSyntaxHighlighter to detect and highlight warning and error messages in LAMMPS log output. It also detects and highlights URLs, enabling easy navigation and documentation access. The class maintains a count of warnings and updates a summary label.

Public Functions

explicit FlagWarnings(QLabel *label = nullptr, QTextDocument *parent = nullptr)

Constructor.

Parameters:
  • label – Optional label to display warning count summary

  • parent – Text document to apply highlighting to

~FlagWarnings() override = default

Destructor.

FlagWarnings() = delete
FlagWarnings(const FlagWarnings&) = delete
FlagWarnings(FlagWarnings&&) = delete
FlagWarnings &operator=(const FlagWarnings&) = delete
FlagWarnings &operator=(FlagWarnings&&) = delete
inline int getNWarnings() const

Get the current number of warnings detected.

Returns:

Number of warnings found in the document

void reset()

Clear the warning and line counters.

The counters are accumulated across calls to highlightBlock() and are never decremented, so they must be cleared explicitly when the attached document is reused for new content. Also resets the summary label to its empty-document text.

Public Static Functions

static QString summaryText(int nwarnings, int nlines)

The text of the summary label for the given counters.

The one place the format lives; also used to seed the label before any highlighting has run.

Parameters:
  • nwarnings – Number of warnings/errors counted

  • nlines – Number of lines counted

Returns:

Formatted summary text

Protected Functions

void highlightBlock(const QString &text) override

Highlight a single block (line) of text.

Searches for warning/error patterns and URLs, applies formatting, and updates warning count.

Parameters:

text – Text to highlight


3.6.8. ImageInfo Class

class ImageInfo

Store settings for displaying graphics from a fix or compute in a LAMMPS snapshot image.

Public Functions

ImageInfo() = delete
inline ImageInfo(bool _enabled, const QString &_style, int _colorstyle, const QString &_color, double _opacity, double _flag1, double _flag2)

Custom constructor

Public Members

bool enabled

display graphics if true

QString style

name of style

int colorstyle

color style for graphics: TYPE, ELEMENT, CONSTANT

QString color

custom color of graphics objects for style == CONSTANT

double opacity

opacity of graphics objects for style == CONSTANT

double flag1

Flag #1 for graphics.

double flag2

Flag #2 for graphics.


3.6.9. RegionInfo Class

class RegionInfo

Store settings for displaying a region in a LAMMPS snapshot image.

Public Functions

RegionInfo() = delete
inline RegionInfo(bool _enabled, int _style, const QString &_color, double _diameter, double _opacity, int _npoints)

Custom constructor

Public Members

bool enabled

display region if true

int style

style of region object: FRAME, FILLED, TRANSPARENT, or POINTS

QString color

color of region display

double diameter

diameter value for POINTS and FRAME

double opacity

opacity for TRANSPARENT

int npoints

number of points to be used for POINTS style region display


3.6.10. StdCapture Class

class StdCapture

Capture stdout output to a string buffer.

This class provides functionality to redirect and capture standard output (stdout) into a string buffer. Used to capture output from LAMMPS library calls for display in the GUI.

Public Functions

StdCapture()

Constructor - initializes capture buffers.

StdCapture(const StdCapture&) = delete
StdCapture(StdCapture&&) = delete
StdCapture &operator=(const StdCapture&) = delete
StdCapture &operator=(StdCapture&&) = delete
~StdCapture()

Destructor - closes the capture pipe descriptors.

void beginCapture()

Start capturing stdout.

Redirects stdout to an internal pipe for capture

bool endCapture()

Stop capturing stdout and restore original stdout.

Returns:

true if capture was active, false otherwise

std::string getCapture()

Get all captured output and clear the buffer.

Returns:

String containing all captured output

std::string getChunk()

Get a chunk of captured output without clearing.

Returns:

String containing new output since last getChunk call

double getBufferUse() const

Get the buffer usage as a fraction of max buffer size.

Returns:

Value between 0.0 and 1.0 indicating buffer fullness

inline bool isUsable() const

Whether stdout could be redirected at all.

False means nothing the library writes can ever be shown, and diagnostic() says why. Worth asking: the failure is otherwise completely silent, because printf() reports success either way and the runtime simply drops the bytes.

Returns:

true when captured output can reach the caller

inline const std::string &diagnostic() const

Why capture is not available.

Returns:

One line naming the step that failed, empty while capture works

inline size_t totalRead() const

Bytes retrieved through getChunk() since the capture began.

Returns:

Byte count; zero after a whole run means the output was lost

std::string probeRunEnd()

Decide which side lost the output of a run that captured nothing.

Performs one more marker round trip while the capture is still active: a marker that comes back proves the redirect held for the whole run (the library’s output went elsewhere), one that does not means stdout was re-pointed while the run was underway. Call before endCapture(); any real output drained alongside the marker is preserved and delivered through the following endCapture()/getCapture().

Returns:

One line stating whether the redirect still worked at run end, empty when there is no active, usable capture to probe


3.6.11. Qt Helper Widgets

class QHline : public QFrame

Horizontal line widget for visual separation.

Provides a simple horizontal line widget for grouping UI elements in forms or dialogs.

Public Functions

QHline(QWidget *parent = nullptr)

Constructor.

Parameters:

parent – Parent widget


class QColorCompleter : public QCompleter

Auto-completer for color name inputs.

Provides auto-completion for color names in text fields, suggesting valid color names for use with the LAMMPS dump image command.

Public Functions

QColorCompleter(QWidget *parent = nullptr)

Constructor.

Parameters:

parent – Parent widget


class QColorValidator : public QValidator

Validator for color name inputs.

Ensures color inputs are names from the LAMMPS color list. Fix-up trims whitespace and lowercases the input.

Public Functions

QColorValidator(QWidget *parent = nullptr)

Constructor.

Parameters:

parent – Parent widget

void fixup(QString &input) const override

Attempt to fix invalid color input.

Parameters:

input – String to fix (modified in place)

QValidator::State validate(QString &input, int &pos) const override

Validate color input string.

Parameters:
  • input – String to validate

  • pos – Cursor position (unused)

Returns:

Validation state (Invalid, Intermediate, Acceptable)


class RangeSlider : public QSlider

Custom Qt Widget implementing a variant of QSlider that has two instead of one handle.

Public Functions

RangeSlider(Qt::Orientation ot = Qt::Horizontal, QWidget *parent = nullptr)

Constructor.

Copyright Hoyoung Lee (2024-07-14).

hoyoung.yi@gmail.com

This software is a computer program whose purpose is to provide “Qt widget of range slider with two handles”.

This software is governed by the CeCILL-A license under French law and abiding by the rules of distribution of free software. You can use, modify and/or redistribute the software under the terms of the CeCILL-A license as circulated by CEA, CNRS and INRIA at the following URL: “http://www.cecill.info”.

As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software’s author, the holder of the economic rights, and the successive licensors have only limited liability.

In this respect, the user’s attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software’s suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security.

The fact that you are presently reading this means that you have had knowledge of the CeCILL-A license and that you accept its terms.

Parameters:
  • ot – Slider orientation (default: Horizontal)

  • parent – Parent widget

inline int low() const

Return the rangeslider’s current low handle value.

inline void setLow(int low_limit)

Set the rangeslider’s current low handle value.

inline int high() const

Return the rangeslider’s current high handle value.

inline void setHigh(int high_limit)

Set the rangeslider’s current high handle value.

Signals

void sliderMoved(int, int)

This signal is emitted when sliderDown is true and one of the two sliders moves.

Protected Functions

void paintEvent(QPaintEvent *ev) override

handle paint event

void mousePressEvent(QMouseEvent *ev) override

handle mouse press event

void mouseMoveEvent(QMouseEvent *ev) override

handle mouse move event

inline int pick(QPoint const &pt) const

Extract the relevant coordinate from a point based on slider orientation.

int pixelPosToRangeValue(int pos)

Convert a pixel position along the slider to a range value.

Protected Attributes

int lowLimit

position of rangeslider’s lower handle

int highLimit

position of rangeslider’s upper handle

QStyle::SubControl pressed_control

currently pressed sub-control (handle)

int tick_interval

interval between tick marks

QSlider::TickPosition tick_position

position of tick marks relative to slider

QStyle::SubControl hover_control

sub-control currently under the mouse cursor

int click_offset

offset from handle center to click position

int active_slider

index of the currently active slider handle


class RangeBandSlider : public QSlider

Horizontal QSlider that colors an active sub-range of its track.

RangeBandSlider behaves like an ordinary horizontal QSlider for selecting the current value (e.g. an image index), but paints its track in two colors: values inside the active [low, high] range use the “active” color, while values outside it (the skipped images) use the “skipped” color. The handle is still drawn by the platform style, so it keeps its native appearance. The active range is expressed in the same units as the slider value and is updated with setActiveRange().

Public Functions

inline explicit RangeBandSlider(QWidget *parent = nullptr)

Constructor.

Parameters:

parent – Parent widget (optional)

~RangeBandSlider() override = default

Destructor.

RangeBandSlider(const RangeBandSlider&) = delete
RangeBandSlider(RangeBandSlider&&) = delete
RangeBandSlider &operator=(const RangeBandSlider&) = delete
RangeBandSlider &operator=(RangeBandSlider&&) = delete
void setActiveRange(int low, int high)

Set the active value range to highlight.

Parameters:
  • low – First in-range value (inclusive, in slider value units)

  • high – Last in-range value (inclusive, in slider value units)

Protected Functions

void paintEvent(QPaintEvent *event) override

Paint a two-color track plus the native handle.

Parameters:

event – The paint event (unused)


class VerticalLabel : public QWidget

Widget displaying text rotated 90 degrees counter-clockwise.

Renders text vertically, optimized for y-axis titles in charts where horizontal space is limited.

Public Functions

explicit VerticalLabel(const QString &text, QWidget *parent = nullptr)

Constructor.

Parameters:
  • text – Text to display

  • parent – Parent widget

void setText(const QString &text)

Update the displayed text.

Parameters:

text – New text to display

QString text() const

Get the displayed text.

Returns:

Current text

Protected Functions

void paintEvent(QPaintEvent *event) override

event handler for requests to draw all or parts of the custom widget

QSize sizeHint() const override

return the recommended size for the widget

QSize minimumSizeHint() const override

return the recommended minimum size for the widget


3.6.12. StdoutSilencer Class

class StdoutSilencer

RAII guard that silences stdout for the duration of its scope.

Calls silenceStdout() on construction and restoreStdout() on destruction, so stdout is restored on every exit path from the enclosing scope, including early returns and exceptions. Use in place of manual silenceStdout() / restoreStdout() pairs.

Note

Not thread-safe. Must only be used from the main thread.

Public Functions

inline StdoutSilencer()
inline ~StdoutSilencer()
StdoutSilencer(const StdoutSilencer&) = delete
StdoutSilencer(StdoutSilencer&&) = delete
StdoutSilencer &operator=(const StdoutSilencer&) = delete
StdoutSilencer &operator=(StdoutSilencer&&) = delete

3.6.13. QtMessageSilencer Class

class QtMessageSilencer

RAII guard that collects Qt log messages instead of printing them.

Installs a Qt message handler on construction and restores the previous one on destruction. Debug, info, and warning messages emitted while the guard is alive are collected and can be retrieved with messages(); they are never printed. Critical and fatal messages are passed on to the previous handler, since those must not be swallowed.

The intended use is a scope whose failure is expected and handled, such as asking Qt to decode an image in a format it may not support: some of Qt’s image format plugins print a warning for every file they reject, which would otherwise be repeated for each file and each attempt. Retrieve the collected text with messages() and report it once if the operation fails for good.

Note

The Qt message handler is process-wide, so the guard also captures messages emitted by other threads while it is alive. Keep the guarded scope short and use it only from the main thread.

Public Functions

QtMessageSilencer()
~QtMessageSilencer()
QtMessageSilencer(const QtMessageSilencer&) = delete
QtMessageSilencer(QtMessageSilencer&&) = delete
QtMessageSilencer &operator=(const QtMessageSilencer&) = delete
QtMessageSilencer &operator=(QtMessageSilencer&&) = delete
QString messages() const

The messages collected so far, one per line.

Returns:

Collected text, or an empty string if nothing was captured


3.6.14. PlotData and File Parsers

Column-oriented numeric data model (src/plotdata.h) and the parsers for external data files (whitespace/.dat, CSV, LAMMPS YAML, and JSON) used to plot data from files.

Functions

PlotData parsePlotCsv(const QString &text, QString *error = nullptr)

Parse comma-separated values into a PlotData.

The first line is treated as a header of column names unless every field parses as a number, in which case generic names are generated and the line is treated as data.

Parameters:
  • text – File contents

  • error – Optional out-parameter set to a message on failure

Returns:

Parsed table (empty on failure)

PlotData parsePlotWhitespace(const QString &text, QString *error = nullptr)

Parse whitespace-separated columns (gnuplot / LAMMPS .dat) into a PlotData.

Lines beginning with # are comments; the last comment line before the data is used for column names if its field count matches the data.

Parameters:
  • text – File contents

  • error – Optional out-parameter set to a message on failure

Returns:

Parsed table (empty on failure)

PlotData parsePlotYaml(const QString &text, QString *error = nullptr)

Parse YAML (LAMMPS thermo keywords:+data: or a sequence of maps) into a PlotData.

Parameters:
  • text – File contents

  • error – Optional out-parameter set to a message on failure

Returns:

Parsed table (empty on failure)

PlotData parsePlotJson(const QByteArray &bytes, QString *error = nullptr)

Parse JSON into a PlotData.

Supports two simple shapes only: an array of equally long numeric rows ([[...],[...]], generic column names) and an object mapping names to numeric arrays ({"a":[...],"b":[...]}).

Parameters:
  • bytes – File contents

  • error – Optional out-parameter set to a message on failure

Returns:

Parsed table (empty on failure)

PlotData loadPlotData(const QString &filename, QString *error = nullptr)

Load a file into a PlotData, choosing the parser by file extension or content.

Parameters:
  • filename – Path to the data file (.csv, .yaml/.yml, .json; else the whitespace format, with a content-sniffing fallback to YAML/JSON)

  • error – Optional out-parameter set to a message on failure

Returns:

Parsed table (empty on failure)

QString writePlotCsv(const PlotData &data)

Format a PlotData as comma-separated values.

Round-trips through parsePlotCsv().

Parameters:

data – Table to format

Returns:

CSV text: a header row of column names, then one row per data point

QString writePlotDat(const PlotData &data, const QString &source = QString())

Format a PlotData as whitespace-separated columns (gnuplot style)

Parameters:
  • data – Table to format

  • source – Optional description placed in the leading comment line

Returns:

Text with a # comment header carrying the column names, then the numeric columns; round-trips through parsePlotWhitespace()

QString writePlotYaml(const PlotData &data)

Format a PlotData as a LAMMPS-style thermo YAML document.

Parameters:

data – Table to format

Returns:

YAML text with a quoted keywords: list and a data: list of rows; round-trips through parsePlotYaml()

class PlotData
#include <plotdata.h>

Column-oriented table of named numeric columns.

Holds a set of equally long columns of doubles, each with a name. It is the GUI-free data model shared by the file parsers and the chart window when plotting external data.

Public Functions

PlotData() = default
~PlotData() = default
PlotData(const PlotData&) = default

Copy constructor.

PlotData(PlotData&&) = default

Move constructor.

PlotData &operator=(const PlotData&) = default

Copy assignment.

PlotData &operator=(PlotData&&) = default

Move assignment.

inline int columnCount() const

Number of columns.

inline int rowCount() const

Number of rows (length of the columns; 0 if empty)

inline bool isEmpty() const

True if there are no columns or no rows.

inline const QString &columnName(int c) const

Name of a column.

Parameters:

c – Column index

Returns:

Column name

inline const QStringList &columnNames() const

All column names.

inline const std::vector<double> &column(int c) const

Read access to a column’s values.

Parameters:

c – Column index

Returns:

Reference to the column data

void setColumnNames(const QStringList &columnNames)

Reset the table to a fresh set of (empty) named columns.

Parameters:

columnNames – Names of the columns to create

void renameColumns(const QStringList &newNames)

Rename columns in place without clearing data.

Parameters:

newNames – New names; entries beyond columnCount() are ignored, missing ones keep the old name

bool appendRow(const std::vector<double> &row)

Append one row of values, one per column.

Parameters:

row – Values to append (size must equal columnCount())

Returns:

true on success, false if the size does not match

void addColumn(const QString &name, std::vector<double> data)

Append a complete named column.

Used by the column-wise parsers (e.g. JSON object-of-arrays).

Parameters:
  • name – Column name

  • data – Column values

Private Members

QStringList names

per-column names

std::vector<std::vector<double>> cols

column-major numeric payload

struct PlotErrors
#include <plotdata.h>

Per-column error bars, parallel to the columns of a PlotData.

Entry i of upper holds the (upper) error of column i, or is empty when that column has no error bars. Errors are kept beside the table rather than as extra columns so that they never appear as plottable columns of their own, and so that columns added later (e.g. a derived column) simply have none.

lower is only filled for bars that are not symmetric around the value &#8212; the min/max spread of a set of blocks is the case that needs it. While it is empty the bars extend by upper in both directions.

Public Functions

inline bool isEmpty() const

True if no column carries error bars.

inline bool isAsymmetric() const

True if the bars extend by different amounts up and down.

inline std::size_t columnCount() const

Number of columns covered.

inline void clear()

Drop all error bars.

inline void resize(std::size_t ncol)

Grow or shrink to ncol columns, keeping the existing ones.

inline void appendEmpty()

Append one column without error bars.

Public Members

std::vector<std::vector<double>> upper

upper (or symmetric) error per column

std::vector<std::vector<double>> lower

lower error per column (empty = symmetric)


3.6.15. Block-Structured fix ave/* Files

Data model and parsers (src/plotblockdata.h) for the block-structured output files of fix ave/time in vector mode, fix ave/histo and fix ave/correlate, which are reduced to a flat PlotData before they are plotted.

struct PlotDataBlock

One per-timestep block of a fix ave/* output file.

A block is the table LAMMPS writes for a single output timestep: the rows of a vector, the bins of a histogram, or the time windows of a correlation function. scalars carries the extra per-block numbers some styles put on the block header line (for fix ave/histo the total and missing counts and the value range); their names are in PlotBlockData::scalarNames.

Public Members

long long step = 0

timestep this block was written for

std::vector<double> scalars

per-block extras from the block header line

PlotData rows

the block’s table of named columns

struct PlotBlockData

A parsed block-structured fix ave/* output file.

All blocks of a well-formed file have the same columns; blocks of differing shape can still occur when a file was appended to by a second fix, and are dropped by the reduction step rather than by the parser.

Public Functions

inline int blockCount() const

Number of blocks.

inline bool isEmpty() const

True if no block carrying data was found.

inline QStringList columnNames() const

Column names of the first block (empty if there is none)

Public Members

AveFileKind kind = AveFileKind::Unknown

detected format

QString fixId

fix ID from the default header, if present

QStringList scalarNames

names for PlotDataBlock::scalars

std::vector<PlotDataBlock> blocks

the per-timestep blocks, in file order

Functions

QString aveFileKindName(AveFileKind kind)

Human-readable name of a file kind, as shown in the import dialog.

Parameters:

kind – Detected or user-selected kind

Returns:

Descriptive name, e.g. “fix ave/histo”

PlotBlockData parseAveBlocks(const QString &text, QString *error = nullptr)

Parse the native (whitespace-separated) fix ave/* block format.

Recognizes both block layouts LAMMPS writes: a numeric block header line (step nrows ...) followed by nrows data rows, and the # Timestep: N comment delimiter of fix ave/correlate/long. Comment lines anywhere in the file re-synchronize the scanner, so a file that a second fix instance appended its own header to still parses.

Parameters:
  • text – File contents

  • error – Optional out-parameter set to a message on failure

Returns:

Parsed blocks (empty on failure)

PlotBlockData parseAveBlocksYaml(const QString &text, QString *error = nullptr)

Parse the vector-mode YAML variant fix ave/time writes.

The shape is a keywords: list followed by data: as a map of timestep keys, each holding a list of flow-style rows. A leading Row column is synthesized so that the table matches the native format, whose rows carry an explicit row index. Returns nothing for the scalar-mode YAML shape (a plain list of rows), which parsePlotYaml() already handles.

Parameters:
  • text – File contents

  • error – Optional out-parameter set to a message on failure

Returns:

Parsed blocks (empty on failure)

bool looksLikeAveBlocks(const QString &text)

Test whether a file’s contents are block-structured fix ave/* output.

Requires an actual block structure, not just a matching header comment: the row-index column of every block has to count 1, 2, … n. A flat table is therefore never mistaken for a block file, whatever its comments say.

Parameters:

text – File contents

Returns:

true if the file should be imported through the block path

PlotBlockData loadPlotBlockData(const QString &filename, QString *error = nullptr)

Load a file as block-structured data, choosing the parser by extension or content.

Parameters:
  • filename – Path to the data file

  • error – Optional out-parameter set to a message on failure

Returns:

Parsed blocks; empty if the file is not block structured

QString blockErrorTypeName(BlockErrorType type)

Name of an error type as offered in the import dialog.

Parameters:

type – Error type

Returns:

Descriptive name, e.g. “standard deviation”

PlotData singleBlock(const PlotBlockData &data, int index)

Extract the rows of a single block (import mode “single block”)

Parameters:
  • data – Parsed blocks

  • index – Block index; clamped to the available range

Returns:

That block’s table, or an empty table if there are no blocks

BlockAverage averageBlocks(const PlotBlockData &data, int first, int last, BlockErrorType type)

Average a contiguous range of blocks row by row (import mode “average”)

The last block of the range sets the expected shape; blocks of a different shape are dropped and counted in BlockAverage::skippedBlocks rather than silently reinterpreted. Error bars need at least two contributing blocks, and are computed in two passes so that a small spread on top of a large mean does not lose its significant digits.

Note that successive averaging windows are not strictly independent, so the standard error is a lower bound on the true uncertainty. BlockErrorType::MinMax makes no statistical claim at all: it just marks the range the blocks covered, which is why it is the one error type with an asymmetric result.

Parameters:
  • data – Parsed blocks

  • first – First block of the range (inclusive)

  • last – Last block of the range (inclusive)

  • type – Which uncertainty to report as error bars

Returns:

Means, error bars, and how many blocks contributed

AveImportDefaults aveImportDefaults(const PlotBlockData &data)

Pick the import defaults that suit a parsed file.

Histograms and correlation functions default to the block average, because their time evolution is rarely what is wanted. A file whose correlator accumulates over the whole run defaults to the last block instead: there every block is a successive estimate of the same quantity, so averaging them would be statistically wrong.

Parameters:

data – Parsed blocks

Returns:

Reduction mode and column roles to preselect in the dialog

Enums

enum class AveFileKind

Which LAMMPS fix wrote a block-structured data file.

The kind only selects the sensible import defaults (which column is the x axis, whether averaging blocks is meaningful); the parser itself is generic, so an unrecognized file still imports as Unknown without losing data.

Values:

enumerator Unknown

block structure recognized, but not the writing fix

enumerator AveTimeVector

fix ave/time in vector mode

enumerator AveHisto

fix ave/histo (and fix ave/histo/weight)

enumerator AveCorrelate

fix ave/correlate

enumerator AveCorrelateLong

fix ave/correlate/long

enumerator AveChunk

fix ave/chunk

enum class BlockErrorType

Which uncertainty a block average reports.

Values:

enumerator None

no error bars

enumerator StdDev

standard deviation of the blocks

enumerator StdError

standard error of the mean, sigma/sqrt(N)

enumerator MinMax

full spread: the bar spans the smallest to the largest value


3.6.16. Least-Squares Toolkit

Self-contained (Qt-free) dense linear-algebra and least-squares routines (src/leastsquares.h) used by the chart smoothing and reusable for polynomial and equation-of-state fits.

Typedefs

using float_vect = std::vector<double>

Dense vector of doubles used by the least-squares routines

using int_vect = std::vector<int>

Dense vector of integers used for LU pivot bookkeeping

Functions

float_mat transpose(const float_mat &a)

Return the transpose of a matrix.

Return the transpose of a matrix.

Parameters:

a – Input matrix

Returns:

Transposed matrix

float_mat operator*(const float_mat &a, const float_mat &b)

Matrix-matrix multiplication.

Matrix-matrix multiplication.

Parameters:
  • a – Left operand

  • b – Right operand (must have as many rows as a has columns)

Returns:

Product matrix

float_mat lin_solve(const float_mat &A, const float_mat &a)

Solve the linear system A*X = a via in-place LU decomposition.

Setting a to the identity matrix yields the inverse of A.

Solve the linear system A*X = a via in-place LU decomposition.

Parameters:
  • A – Coefficient matrix

  • a – Right-hand side(s); each column is an independent system

Returns:

Solution matrix X with the same shape as a

float_mat invert(const float_mat &A)

Invert a square matrix using LU decomposition.

Invert a square matrix using LU decomposition.

Parameters:

A – Square matrix to invert

Returns:

Inverse of A

float_vect sg_smooth(const float_vect &v, std::size_t width, int deg)

Smooth a data vector with a Savitzky-Golay filter.

Fits a polynomial of degree deg to a sliding window of width 2*width+1 by least squares; non-symmetric windows are used near the borders.

Smooth a data vector with a Savitzky-Golay filter.

This method means fitting a polynomial of degree ‘deg’ to a sliding window of width 2w+1 throughout the data. The needed coefficients are generated dynamically by doing a least squares fit on a “symmetric” unit vector of size 2w+1, e.g. for w=2 b=(0,0,1,0,0). evaluating the polynomial yields the sg-coefficients. at the border non symmetric vectors b are used.

Parameters:
  • v – Input samples (assumed equally spaced)

  • width – Half-window size; the filter window spans 2*width+1 points

  • deg – Polynomial degree fitted in each window (0 = moving average)

Returns:

Smoothed vector with the same length as v

class float_mat : public std::vector<float_vect>
#include <leastsquares.h>

Simple dense matrix of doubles backed by a vector of rows.

Elements are indexed [row][column] with 0-based indices (C style). Because the storage is row-major, iterating over rows is cheaper than over columns. Used as the working type for the LU solver, matrix inverse, and the Savitzky-Golay coefficient generation.

Public Functions

float_mat() = delete
float_mat(float_mat&&) = default

Move constructor.

~float_mat() = default
float_mat &operator=(const float_mat&) = delete
float_mat &operator=(float_mat&&) = delete
float_mat(std::size_t rows, std::size_t cols, double def = 0.0)

Construct a rows x cols matrix filled with a default value.

Parameters:
  • rows – Number of rows

  • cols – Number of columns

  • def – Initial value for every element (default 0.0)

float_mat(const float_mat &m)

Copy constructor.

float_mat(const float_vect &v)

Construct a single-row matrix from a vector.

Parameters:

v – Row contents

inline std::size_t nr_rows() const

Number of rows.

inline std::size_t nr_cols() const

Number of columns (size of the first row)


3.6.17. Post-Processing Analyses

Self-contained (Qt-free) post-processing analyses (src/analysis.h) used by the chart post-processing dialog.

Functions

std::vector<double> autocorrelation(const std::vector<double> &y, int maxlag)

Normalized autocorrelation function (ACF) of a data series.

Uses the standard biased estimator \( \mathrm{ACF}(k) = \frac{\sum_{i=0}^{N-1-k}(y_i-\bar y)(y_{i+k}-\bar y)} {\sum_{i=0}^{N-1}(y_i-\bar y)^2} \).

Parameters:
  • y – Input samples (assumed equally spaced)

  • maxlag – Largest lag to compute; values <= 0 or >= y.size() are clamped to y.size()-1

Returns:

ACF values for lags 0..maxlag (length maxlag+1), normalized so that the lag-0 value is 1; an empty vector if the input has fewer than two samples or zero variance (a constant series)


3.6.18. Curve Fitting

Linear-least-squares curve fits (src/fitting.h) – polynomial and 4-parameter Birch-Murnaghan equation of state – built on the leastsquares toolkit and used by the chart post-processing dialog.

Functions

PolynomialFit polynomialFit(const std::vector<double> &x, const std::vector<double> &y, int degree)

Least-squares polynomial fit of y(x)

Parameters:
  • x – Abscissa values

  • y – Ordinate values (same length as x)

  • degree – Polynomial degree (>= 0)

Returns:

Fit result; ok is false if the sizes mismatch or there are fewer than degree+1 points

double evalPolynomial(const std::vector<double> &coeffs, double x)

Evaluate a polynomial at a point.

Parameters:
  • coeffs – Coefficients c0..cn (y = sum_k c_k x^k)

  • x – Evaluation point

Returns:

Polynomial value

EosFit birchMurnaghanFit(const std::vector<double> &v, const std::vector<double> &e)

4-parameter Birch-Murnaghan EOS fit of energy versus volume

Parameters:
  • v – Volumes (must be positive)

  • e – Energies (same length as v)

Returns:

Fit result; ok is false if the sizes mismatch, there are fewer than four points, a volume is non-positive, or no physical minimum exists

double evalBirchMurnaghan(const EosFit &fit, double v)

Evaluate the fitted Birch-Murnaghan energy at a volume.

Parameters:
  • fit – Fit result (uses its a/b/c/d coefficients)

  • v – Volume

Returns:

Energy E(V)

struct PolynomialFit
#include <fitting.h>

Result of a least-squares polynomial fit.

Public Members

std::vector<double> coeffs

coefficients c0..cn, i.e. y = sum_k c_k x^k

double rms = 0.0

root-mean-square residual

bool ok = false

true if the fit succeeded

struct EosFit
#include <fitting.h>

Result of a 4-parameter Birch-Murnaghan equation-of-state fit.

The fitted model is the linear-in-coefficients form \( E(V) = a + b\,V^{-2/3} + c\,V^{-4/3} + d\,V^{-2} \), from which the physical quantities are derived.

Public Members

double a = 0.0

constant coefficient

double b = 0.0

coefficient of V^(-2/3)

double c = 0.0

coefficient of V^(-4/3)

double d = 0.0

coefficient of V^(-2)

double v0 = 0.0

equilibrium volume

double e0 = 0.0

equilibrium energy

double b0 = 0.0

bulk modulus (in energy/volume units)

double b0prime = 0.0

pressure derivative of the bulk modulus

double rms = 0.0

root-mean-square residual

bool ok = false

true if the fit succeeded and a minimum was found


3.6.19. Nonlinear Least Squares

Compact, self-contained (Qt-free) Levenberg-Marquardt solver (src/levmar.h) for nonlinear least-squares fits. The model is supplied as a residual/Jacobian callback, so the core is independent of how the model is expressed; it is driven by the custom-fit code with LeptonMini expressions and their symbolic derivatives, and solves the damped normal equations with the leastsquares LU solver. LeptonMini is based on the Lepton library by Peter Eastman and OpenMM contributors distributed under the MIT License.

Typedefs

using LevmarModel = std::function<bool(const std::vector<double> &params, std::vector<double> &residuals, std::vector<std::vector<double>> &jacobian)>

Callback evaluating residuals and the Jacobian at a parameter vector.

Given the current params (length n), it must fill residuals (length m) with model(x_i) - y_i and jacobian (m rows of n columns) with d model(x_i) / d p_j. Returning false signals an evaluation failure (e.g. a domain error) for that parameter vector; the solver treats the trial step as rejected rather than aborting.

Functions

LevmarResult levmarFit(int numResiduals, int numParams, const std::vector<double> &initial, const LevmarModel &model, int maxIterations = 200, double tolerance = 1.0e-12)

Levenberg-Marquardt nonlinear least-squares minimization.

Parameters:
  • numResiduals – Number of data points m (must be >= numParams)

  • numParams – Number of free parameters n (> 0)

  • initial – Initial parameter guess (length numParams)

  • model – Residual/Jacobian callback

  • maxIterations – Maximum number of outer iterations

  • tolerance – Relative cost-change convergence threshold

Returns:

Fit result; ok is false (with a message) on bad dimensions or a failed initial evaluation

struct LevmarResult
#include <levmar.h>

Result of a Levenberg-Marquardt nonlinear least-squares fit.

Public Members

std::vector<double> params

fitted parameter values (empty on failure)

double rms = 0.0

root-mean-square residual at the solution

int iterations = 0

number of outer iterations performed

bool ok = false

true if the fit ran to a usable solution

std::string message

human-readable status/diagnostic


3.6.20. Custom-Function Evaluation and Fitting

Evaluation and nonlinear fitting of user-supplied mathematical expressions (src/customfunc.h) via the vendored LeptonMini parser, used for custom-function plotting and custom curve fits in the chart post-processing dialog. The fit builds its Jacobian from LeptonMini’s analytic derivatives and minimizes with the Levenberg-Marquardt solver. LeptonMini is based on the Lepton library by Peter Eastman and OpenMM contributors distributed under the MIT License.

Functions

CustomCurve evalCustomCurve(const QString &expression, double xmin, double xmax, int nsamples, const QString &variable = QStringLiteral("x"))

Parse and evaluate a single-variable expression over an x range.

Parses expression with the vendored LeptonMini parser, optimizes it, and evaluates it at nsamples + 1 equally spaced points spanning [xmin, xmax]. Points whose value is not finite (NaN/inf) are omitted.

Parameters:
  • expression – Math expression in the variable variable (LeptonMini syntax)

  • xmin – Lower bound of the sampling range

  • xmax – Upper bound of the sampling range

  • nsamples – Number of sub-intervals (clamped to >= 1); nsamples+1 points

  • variable – Name of the independent variable in expression (default “x”)

Returns:

Curve result; on a parse/evaluation error CustomCurve::ok is false and CustomCurve::error describes the problem

CustomFit fitCustomCurve(const QString &expression, const QList<FitParam> &initialParams, const std::vector<double> &xdata, const std::vector<double> &ydata, double xmin, double xmax, int nsamples, const QString &variable = QStringLiteral("x"), const std::vector<double> &weights = {})

Nonlinear least-squares fit of a custom expression to (x, y) data.

Fits expression &#8212; a function of the independent variable variable and the named parameters in initialParams &#8212; to the data (xdata, ydata) by Levenberg-Marquardt. The Jacobian is built from analytic derivatives of the expression with respect to each parameter (via LeptonMini’s symbolic differentiation). On success the fitted model is sampled at nsamples + 1 points over [xmin, xmax] for overlaying on the chart.

Parameters:
  • expression – Math expression in variable and the parameter names

  • initialParams – Parameters with their initial guesses (at least one)

  • xdata – Independent-variable data

  • ydata – Dependent-variable data (same length as xdata)

  • xmin – Lower bound for sampling the fitted curve

  • xmax – Upper bound for sampling the fitted curve

  • nsamples – Number of sub-intervals (clamped to >= 1); nsamples+1 points

  • variable – Name of the independent variable (default “x”)

  • weights – Optional per-point weights w_i for a weighted fit, which minimizes sum w_i (model_i - y_i)^2. Empty (the default) or a wrongly sized vector means every point counts the same; negative entries are treated as zero. Weighting decides which part of the data a model that cannot describe all of it will follow

Returns:

Fit result; on a parse/dimension/evaluation error CustomFit::ok is false and CustomFit::error describes the problem. CustomFit::rms is the plain, unweighted residual either way, so that fits with different weightings stay comparable

class CompiledExpression
#include <customfunc.h>

A parsed and compiled LeptonMini expression with QString error reporting.

Confines the LeptonMini (std::string) parsing boundary to one translation unit, the way LammpsWrapper confines the LAMMPS C API. Construct from a QString expression, check isValid / error, then call evaluate repeatedly with a name -> value variable map. evaluate propagates the LeptonMini exception thrown for an unbound variable, so callers that may reference variables not present in the map should evaluate inside a try block.

Public Functions

explicit CompiledExpression(const QString &expression)

Parse, optimize, and compile expression (a LeptonMini string)

~CompiledExpression()
CompiledExpression() = delete
CompiledExpression(const CompiledExpression&) = delete
CompiledExpression(CompiledExpression&&) = delete
CompiledExpression &operator=(const CompiledExpression&) = delete
CompiledExpression &operator=(CompiledExpression&&) = delete
inline bool isValid() const

True if the expression parsed and compiled successfully.

inline const QString &error() const

Parse-error message (empty when isValid is true)

double evaluate(const std::map<std::string, double> &variables) const

Evaluate with the given variable bindings (may throw on unbound vars)

Private Members

std::unique_ptr<LeptonMini::ExpressionProgram> program

compiled program (null if invalid)

bool valid = false

parse/compile succeeded

QString errorMsg

parse error (empty when valid)

struct CustomCurve
#include <customfunc.h>

Result of sampling a custom expression over an x range.

Public Members

bool ok = false

true if the expression parsed and evaluated

QString error

human-readable error message when ok is false

QList<QPointF> points

sampled (x, y) points; non-finite y values are skipped

struct FitParam
#include <customfunc.h>

A named nonlinear-fit parameter.

Carries the initial guess on input to fitCustomCurve() and the fitted value on output.

Public Members

QString name

parameter name as it appears in the expression

double value = 0.0

initial guess (input) / fitted value (output)

struct CustomFit
#include <customfunc.h>

Result of a nonlinear least-squares fit of a custom expression.

Public Members

bool ok = false

true if the fit produced a usable solution

QString error

human-readable error message when ok is false

QList<FitParam> params

fitted parameters, in the input order

QList<QPointF> curve

fitted model sampled over the x range

double rms = 0.0

root-mean-square residual at the solution

int iterations = 0

Levenberg-Marquardt iterations performed.

namespace LeptonMini

3.6.21. Helper Functions

Functions

QFont monoFontFromSettings()

Build the configured fixed-width font from the application settings.

Returns:

Fixed-pitch QFont with the family and point size stored in the settings, falling back to the platform default GUI_MONOFONT

int dateCompare(const QString &one, const QString &two)

Compare two date strings in LAMMPS “DD MMM YYYY” format (e.g. “22 Jul 2025”)

Parameters:
  • one – First date string

  • two – Second date string

Returns:

-1 if one < two, 0 if equal, 1 if one > two

QStringList splitLine(const QString &text)

Split a string into words while respecting quotes.

Parameters:

text – The string to split

Returns:

List of words extracted from the string

void setDialogIcons(QMessageBox &mb, const QString &iconPath)

Apply the bundled SVG icons to a QMessageBox.

Replaces the standard large icon of the message box with the given bundled SVG icon and sets the window icon and a styled standard “Ok” button consistently. Custom buttons can be added after this call.

Parameters:
  • mb – Message box to style

  • iconPath – Resource path of the SVG icon used as the large dialog icon

void information(QWidget *parent, const QString &title, const QString &text1, const QString &text2 = QString())

Provide standardized information dialog.

Parameters:
  • parent – Pointer to parent widget

  • title – Information dialog title

  • text1 – Information message part 1

  • text2 – Information message part 2 (optional)

void critical(QWidget *parent, const QString &title, const QString &text1, const QString &text2 = QString())

Provide standardized critical error dialog.

Parameters:
  • parent – Pointer to parent widget

  • title – Error dialog title

  • text1 – Error message summary

  • text2 – Detailed error message (optional)

void warning(QWidget *parent, const QString &title, const QString &text1, const QString &text2 = QString())

Provide standardized custom warning dialog.

Parameters:
  • parent – Pointer to parent widget

  • title – Warning dialog title

  • text1 – Warning message summary

  • text2 – Detailed warning message (optional)

QString getLammpsLibName()

Provide platform specific name of a LAMMPS shared library.

Returns:

String with the filename or an empty string if compiled without plugin support

QString getLammpsDownloadUrl()

Provide platform specific URL for downloading a LAMMPS shared library.

Returns:

String with the URL or an empty string if compiled without plugin support or with a compiler that is incompatible with the pre-compiled libraries (MSVC)

void exportImage(QWidget *parent, QImage *image, const QString &title, const QString &defaultname)

Save image directly or convert with ImageMagick.

Parameters:
  • parent – Pointer to parent widget

  • image – Pointer to image class

  • title – Warning dialog title if failed

  • defaultname – Default file name offered by the save dialog (resolved relative to the current working directory)

QString defaultFileStem(const QString &filename)

Derive the default save-file name stem from an input or data file name.

Strips any directory part, a leading “in.” prefix, and any trailing known file extensions (input, plottable data, log, restart, image, and movie formats), so “in.melt”, “melt.lmp”, or “melt.lmp.txt” all yield “melt”. Falls back to “lammps” when nothing remains.

Parameters:

filename – Name of the file the stem is derived from (may include a path)

Returns:

the stem to build default save-file names from

QString ensureFileSuffix(const QString &filename, const QString &suffix)

Append a default suffix to a file name that has no suffix.

Parameters:
  • filename – File name selected in a save dialog

  • suffix – Default suffix (without the leading dot)

Returns:

the file name with the default suffix appended if it had none

bool hasExe(const QString &exe)

Check if an executable is in the executable search path.

Uses findExe(), so the macOS package manager fallback locations apply.

Parameters:

exe – The executable name to search for

Returns:

true if executable is found, false otherwise

QString findExe(const QString &exe)

Find an executable in the executable search path.

On macOS, an application launched from the Finder inherits a minimal PATH without the common package manager locations, so the Homebrew (Arm and Intel macs) and MacPorts binary folders are searched as a fallback. Launch external helper programs with the path returned by this function rather than the bare executable name, so they are also found in that case.

Parameters:

exe – The executable name to search for

Returns:

Full path to the executable or an empty string when not found

QString renameToBackup(const QString &file)

Rename a file to a backup name with the Cfg::BACKUP_SUFFIX suffix.

An existing backup file is replaced. When it cannot be removed (on Windows a loaded shared library is locked against deletion), a numbered backup name is used instead. Windows does permit renaming a locked file, so this is the way to move a loaded shared library out of the way before an update. The caller is responsible for removing the backup file eventually.

Parameters:

file – Path of the file to rename

Returns:

Path of the backup file or an empty string on failure

bool isImageFile(const QString &filename)

Check whether a file is (likely) an image.

Recognizes the formats Qt can decode plus common ImageMagick-only formats (e.g. tga, eps, sgi) so callers can route them through a conversion step.

Parameters:

filename – Path to the file

Returns:

true if the extension is a known image type, or the file exists and QImageReader recognizes its contents as an image

bool isMovieFile(const QString &filename)

Check whether a file is a movie (video) file.

An animated GIF is both an image and a movie, and isImageFile() also claims it. Callers that route a file to either destination must therefore test isMovieFile() first.

Parameters:

filename – Path to the file

Returns:

true if the extension is a known movie type, or the file is an animated GIF with more than one frame

bool isRestartFile(const QString &filename)

Check whether a file is a LAMMPS binary restart file.

Parameters:

filename – Path to the file

Returns:

true if the file exists and begins with the LAMMPS restart magic string

bool looksLikeBinaryFile(const QString &filename)

Heuristic check whether a file is binary rather than text.

Null bytes are essentially absent from text (ASCII, UTF-8, Latin-1) but ubiquitous in binary formats (IEEE floats, packed integers, padding). This is the same heuristic used by git, grep, and the POSIX file utility. Returns false for files that cannot be opened (callers handle that separately).

Parameters:

filename – Path to the file

Returns:

true if the first 8 KB of the file contains a null byte

void relaunchApplication()

Re-exec the current LAMMPS-GUI process in place (e.g. to reload the plugin)

Replaces the running process with a fresh launch of the same executable. On success it does not return; it returns only if the re-exec failed, so callers must handle that case (typically warn and/or exit).

void purgeDirectory(const QString &dir)

Recursively delete all files in a directory.

Parameters:

dir – The directory to purge

bool isLightTheme()

Determine if the current Qt theme is light or dark.

Returns:

true if light theme, false if dark theme

int showUnsavedChangesDialog(QWidget *parent, const QString &filename, const QString &question)

Show a standardized “unsaved changes” confirmation dialog.

Provides a consistent confirmation dialog used whenever the user may lose unsaved changes (opening a new file, quitting, running LAMMPS, etc.).

Parameters:
  • parent – Pointer to the parent widget

  • filename – Name of the file with unsaved changes

  • question – Informative text explaining the context (e.g. “save before opening?”)

Returns:

QMessageBox::Yes, QMessageBox::No, or QMessageBox::Cancel

bool confirmUnexpectedFile(QWidget *parent, const QString &filename, const QString &kind)

Ask before opening a file that is not what it is being opened as.

For the cases where opening the wrong file is a mistake rather than an error: a binary in the editor, a picture handed to the plotter. Answering No is what Return and Escape do, because the usual reason to see this is a name that was mistyped or a file that was mis-picked. Ask only when the file fails the test for its kind &#8212; a file that looks right must never produce a dialog.

Parameters:
  • parent – Pointer to the parent widget

  • filename – File about to be opened; only its name is shown

  • kind – What it was expected to be, worded to follow “a”: “text”, “data”, “image or movie”

Returns:

true if the user wants to go ahead

void styleDialogButtons(QDialogButtonBox *box)

Apply the bundled SVG icons to a dialog button box’s standard buttons.

Qt fetches QDialogButtonBox standard-button icons (Ok, Cancel, …) via QIcon::fromTheme(), which falls back to the desktop theme because the bundled lammpsgui icon theme only carries the editor context-menu actions. This applies our own dialog-ok / dialog-cancel / dialog-no / window-close SVGs to whichever standard buttons the box contains, so every dialog button looks the same regardless of platform or desktop theme.

Parameters:

box – The button box whose standard buttons should be re-iconed

void silenceStdout()

Silence stdout by redirecting it to the null device.

Redirects stdout to /dev/null (Unix) or NUL: (Windows) to suppress all output. Does nothing if StdCapture is currently active or if stdout is already silenced.

Note

Not thread-safe. Must only be called from the main thread.

void restoreStdout()

Restore stdout after it was silenced.

Restores the original stdout file descriptor that was saved by silenceStdout(). Does nothing if stdout is not currently silenced.

Note

Not thread-safe. Must only be called from the main thread.

bool isStdoutSilenced()

Check if stdout is currently silenced.

Returns:

true if silenceStdout() is active, false otherwise

void notifyCaptureState(bool active)

Notify the silence/restore system about StdCapture state changes.

Called by StdCapture to indicate whether it is actively capturing output. While capture is active, silenceStdout() becomes a no-op to avoid interfering with the capture pipe.

Parameters:

active – true when StdCapture starts capturing, false when it stops

QImage grayscaleImage(const QImage &src)

Fade an image into an unmistakably inactive version of itself.

Removes the color and, in addition, pulls the gray levels towards Cfg::GRAYSCALE_MIDPOINT, keeping only Cfg::GRAYSCALE_CONTRAST of the original contrast: a merely desaturated icon retains all of its structure and still reads as active next to its colored counterpart.

Parameters:

src – Image to convert

Returns:

Grayscale, low-contrast copy of src with the original transparency

QPixmap grayscalePixmap(const QPixmap &src)

Fade a pixmap into an unmistakably inactive version of itself.

Applies grayscaleImage() to the pixmap. Used for the “inactive” state of a status icon, so the widget does not depend on the disabled-widget visual, which does not refresh reliably on all platforms (e.g. macOS 12) and cannot be applied to an enabled widget at all.

Parameters:

src – Pixmap to convert

Returns:

Grayscale, low-contrast copy of src with the original transparency

QSize toolButtonSize(const QAbstractButton *sample)

Square size for a toolbar/status-bar button from a sample’s size hint.

Implements the shared tool-button sizing policy: take the sample button’s minimum size hint height, enlarge it by Cfg::TOOLBAR_BUTTON_MARGIN, and return a square of that side. Compute this once per button row and reuse it for the row’s buttons (via styleToolButtons()) and any adjacent widgets (line edits, labels, spin boxes) that should share the button height.

Parameters:

sample – Representative button (typically the first in the row)

Returns:

Square button size in logical pixels

void styleToolButtons(const QSize &size, std::initializer_list<QAbstractButton*> buttons)

Apply the shared tool-button policy to a set of buttons.

Fixes every button to size (a square from toolButtonSize()) and gives it the standard Cfg::TOOLBAR_ICON_SIZE icon, so only a small, uniform padding remains between icon and frame. The image viewer, slide show, chart window, and editor status bar all use this so their button rows look identical.

Parameters:
  • size – Square button size (from toolButtonSize())

  • buttons – Buttons to size and assign the standard icon size

void applyWindowFlags(QWidget *window)

Apply the shared window-manager hints to a top-level output window.

Strips the dialog property (so the window is an independent top-level window, not a transient that stays above its parent) and removes the minimize button. The maximize button is also removed, except on macOS where it is kept because removing it makes the window non-resizable there. Used for the log, chart, image, slide-show, file-viewer and variables windows so they share one frame policy.

Note

setWindowFlags() re-shows a hidden widget, so call this before a final hide() when the window must start hidden.

Parameters:

window – Top-level window to adjust (no-op if null)

void retireViewMenuBar(QMenuBar *menubar)

Retire an output view’s own menu bar in the combined layout.

Docked, a view does not show a menu bar of its own: the main window puts the view’s File menu into its menu bar while the view has the focus. The menu bar object still exists, because it is where the menu was built, so it is simply hidden &#8212; which is enough on every platform but one.

On macOS a QMenuBar is not a widget in the window but a handle on the system-wide menu bar, and the last one to claim a window replaces the one before it. Docked, both the main window’s menu bar and the view’s live in the same window, so opening the first panel handed the system menu bar to a menu bar that is hidden and empty: everything but the application menu that macOS assembles itself disappeared. Detaching the view’s menu bar from the platform gives the window back to the main window’s, and costs nothing elsewhere, where a QMenuBar is an ordinary widget already.

In the individual-window layout each view is a window of its own and claims its own menu bar legitimately, so this is only for the docked case.

Parameters:

menubar – Menu bar of a docked output view (no-op if null)

QSize viewerFitSize(const QSize &content, const QSize &budget, int frame, int sbext)

Compute the scroll area size that shows the given content, within a budget.

Pure size computation behind fitViewerWindow(). The natural size is the content plus the scroll area frame, with no scroll bars. An axis whose natural size exceeds the budget is clamped and gets a scroll bar, which consumes sbext pixels of viewport on the other axis, so that axis is enlarged accordingly (still within its budget). The result depends only on the arguments &#8212; never on the current scroll bar visibility &#8212; so repeated calls with the same input always yield the same size.

Parameters:
  • content – Size of the displayed content (image) in pixels

  • budget – Largest allowed outer scroll area size (e.g. a screen fraction)

  • frame – Total scroll area frame thickness (2 * frameWidth())

  • sbext – Scroll bar thickness (QStyle::PM_ScrollBarExtent)

Returns:

Outer scroll area size that best fits the content within the budget

QSize fitViewerWindow(QWidget *window, QScrollArea *area, const QSize &content, const QSize &budget, const QSize &lastFit)

Resize a viewer window so its scroll area just fits the displayed image.

Shared auto-resize policy of the image viewer and the slide show: the scroll area is sized via viewerFitSize() and the window is resized around it. The scroll area’s minimum size is pinned only for the duration of the resize, so the user can freely shrink the window afterwards. When the computed size equals lastFit, the window is left untouched; passing the previous return value back in keeps navigating a sequence of equally-sized images from ever moving or resizing the window.

While window is still hidden its layout uses unpolished style metrics, so the applied size is only approximate: the fit is applied but an invalid QSize is returned instead of the memoized size. The viewers use that in their showEvent() overrides to apply the fit once more on the shown window.

Parameters:
  • window – Top-level viewer window to resize

  • area – Scroll area inside window that shows the content

  • content – Size of the displayed content (image) in pixels

  • budget – Largest allowed outer scroll area size (e.g. a screen fraction)

  • lastFit – Return value of the previous call (default QSize() initially)

Returns:

The scroll area size applied, or an invalid QSize while window is hidden; pass this value back as lastFit on the next call

template<typename Recv, typename Func>
QAction *addMenuAction(QMenu *menu, const QString &text, const QString &icon, Recv *receiver, Func slot)

Append an action with an optional icon and a triggered() handler to a menu.

Collapses the recurring “addAction() + setIcon() + connect()” idiom used when building context menus and tool menus across the widget classes.

Parameters:
  • menu – Menu to append the new action to

  • text – Action label text

  • icon – Resource path for the action icon (empty for no icon)

  • receiver – Object that owns the slot/callable

  • slot – Member function pointer or callable invoked on trigger

Returns:

The created action, for any further configuration by the caller (e.g. setData())

bool dockedLayout()

Whether the output views are docked into the main window.

The layout is chosen once at startup (WindowLayout applies it), so this only reads the stored preference, or what forceLayout() was given instead. Widgets consult it for the things that make no sense in a dock, such as remembering their own window size.

Returns:

true when the docked layout is in effect for this session

void forceLayout(bool docked)

Override the stored layout preference for this session.

What the -j/&#8212;joined and -w/&#8212;windows command-line flags do. The preference itself is left alone: the choice applies to the process it was given to and nothing else, which is also why a relaunch (which passes no arguments on) goes back to what the preferences say. Call before the first window is built, since that is when the layout is decided.

Parameters:

docked – true for the combined main window, false for individual windows

void setMainWindowShortcuts(const QList<QKeySequence> &keys)

Record the key sequences the main window’s menus already use.

Called once by the main window after its menus are built. A view that ends up as a dock panel lives inside that same window, so a sequence it binds would match at the same time as the menu does and Qt would fire neither. WindowLayout consults this when a widget actually becomes a panel; a view that stays a window of its own keeps all of its shortcuts.

Parameters:

keys – Every shortcut reachable from the main window’s menu bar

bool isMainWindowShortcut(const QKeySequence &keys)

Whether a key sequence belongs to the main window’s menus.

Parameters:

keys – Sequence to check

Returns:

true if the main window already binds it

void scopeShortcut(QWidget *widget, QAction *action, const QKeySequence &keys)

Give a menu action a keyboard shortcut that is scoped to one widget.

A menu action is only associated with the menu it was added to, and a menu is a popup that never holds the keyboard focus. Associating the action with widget as well is therefore what makes Qt::WidgetWithChildrenShortcut usable here at all: without it the shortcut would never match. See addShortcut() for why the output windows want focus scope in the first place.

Parameters:
  • widget – Widget the shortcut belongs to

  • action – Action to bind the shortcut to

  • keys – Key sequence to bind

template<typename Recv, typename Func>
QShortcut *addShortcut(QWidget *widget, const QKeySequence &keys, Recv *receiver, Func slot)

Add a keyboard shortcut that is scoped to one widget.

The shortcut uses Qt::WidgetWithChildrenShortcut, so it fires only while the keyboard focus is inside widget rather than anywhere in its window. That is what keeps the per-window shortcuts of the output windows (several of which repeat main window accelerators such as Ctrl+S, Ctrl+Q or Ctrl+/) from becoming ambiguous overloads once those windows are docked into the main window instead of being windows in their own right.

Parameters:
  • widget – Widget the shortcut belongs to and that owns the QShortcut

  • keys – Key sequence to bind

  • receiver – Object that owns the slot/callable

  • slot – Member function pointer or callable invoked on activation

Returns:

The created shortcut, for any further configuration by the caller