Python API
Documentation for the core functions in gpuma.
Package layout
Everything documented here is re-exported from the top-level gpuma
namespace, so the public API is flat: from gpuma import optimize_single_smiles,
Config, read_multi_xyz all work regardless of where a symbol lives internally.
Internally the package is organised into subpackages:
gpuma.models— model dispatchers (load_calculator,load_torchsim_model) and theAVAILABLE_*_MODELSregistries, with backend-specific loaders undermodels/fairchem.py,models/orb.py,models/sevennet.py.gpuma.conformer_generation— SMILES → 3D structure/ensemble embedding (embed.py,mol_utils.py).gpuma.utils— I/O (io_handler.py), logging (logging_utils.py) and timing helpers (decorators.py).- Top-level modules
structure.py,config.py,optimizer.py,api.py,cli.py.
The fully-qualified paths below (e.g. gpuma.utils.io_handler.read_xyz) are
the canonical source locations; the short top-level aliases (gpuma.read_xyz)
are equivalent.
Public high-level Python API for common geometry optimization workflows.
This module provides convenience functions built on top of the lower-level I/O and optimization utilities. It allows users to easily optimize molecular structures starting from SMILES strings or XYZ files, as well as optimizing ensembles of conformers.
Data Structures
The core container passed between I/O, conformer generation and optimization.
Structure
dataclass
Container for a molecular structure used in GPUMA.
Attributes
symbols : list[str]
List of atomic symbols.
coordinates : list[tuple[float, float, float]]
N x 3 list of floats for atomic positions in Angstrom.
charge : int
Total charge of the system.
multiplicity : int
Spin multiplicity of the system.
energy : float | None
Optional energy value of the structure in eV.
comment : str
Optional comment or metadata string.
metadata : dict
Free-form metadata dictionary for additional information.
Source code in src/gpuma/structure.py
n_atoms
property
Return the number of atoms in the structure.
Returns
int Number of atoms.
with_energy(energy)
Set the energy of the structure and return the modified instance.
Parameters
energy : float | None
Energy value in eV to assign to this structure. None clears
the current energy.
Returns
Structure
The same :class:Structure instance, to allow method chaining.
Source code in src/gpuma/structure.py
Single Structure Optimization
Methods for optimizing individual molecules provided as SMILES or XYZ files.
optimize_single_smiles(smiles, output_file=None, config=None)
Optimize a single molecule from a SMILES string.
This function uses the provided SMILES string to generate an initial 3D structure using the Morfeus library. It then optimizes the structure using the specified optimization pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
SMILES string of the molecule to optimize. |
required |
output_file
|
str
|
Path to an output XYZ file where the optimized structure will be written. If None, the optimized structure is not saved to a file. |
None
|
config
|
Config
|
Config object to control the optimization pipeline. Highly recommended to specify. If None, the configuration will be loaded from the default file. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Structure |
Structure
|
The optimized molecular structure as a Structure object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the generated structure is not valid. |
Source code in src/gpuma/api.py
optimize_single_xyz_file(input_file, output_file=None, config=None)
Optimize a single structure from an XYZ file.
This function reads a molecular structure from the specified XYZ file, optimizes it using the provided optimization pipeline, and optionally writes the optimized structure to an output XYZ file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_file
|
str
|
Path to an input XYZ file from which to read the initial structure. |
required |
output_file
|
str
|
Path to an output XYZ file where the optimized structure will be written. If None, the optimized structure will not be saved to a file. |
None
|
config
|
Config
|
Config object to control the optimization pipeline. Highly recommended to specify. If None, the configuration will be loaded from the default file. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Structure |
Structure
|
The optimized molecular structure as a Structure object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input file does not exist or if the read structure is not valid. |
Source code in src/gpuma/api.py
Batch & Ensemble Optimization
Methods for processing multiple structures, ensembles, or entire directories.
optimize_ensemble_smiles(smiles, output_file=None, config=None)
Optimize a conformer ensemble generated from a SMILES string.
This function generates a specified number of conformers from the provided SMILES string using the Morfeus library. It then optimizes each conformer using the specified optimization pipeline. Optionally, the optimized ensemble can be saved to a multi-structure XYZ file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
SMILES string of the molecule for which to generate conformers. |
required |
output_file
|
str
|
Path to an output multi-structure XYZ file where the optimized ensemble will be written. If None, the ensemble is not saved to a file. |
None
|
config
|
Config
|
Config object to control the optimization pipeline. Highly recommended to specify. If None, the configuration will be loaded from the default file. |
None
|
Returns:
| Type | Description |
|---|---|
list[Structure]
|
list[Structure]: A list of optimized molecular structures as Structure objects. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If output_file is not specified when required or if the generated conformers are not valid. |
Source code in src/gpuma/api.py
optimize_batch_multi_xyz_file(input_file, output_file=None, config=None)
Optimize a batch of structures from a multi-structure XYZ file.
This function reads multiple molecular structures from the specified multi-structure XYZ file, optimizes each structure using the provided optimization pipeline, and writes the optimized structures to an output multi-structure XYZ file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_file
|
str
|
Path to an input multi-structure XYZ file from which to read the initial structures. |
required |
output_file
|
str
|
Path to an output multi-structure XYZ file where the optimized structures will be written. If None, the optimized structures will not be saved to a file. |
None
|
config
|
Config
|
Config object to control the optimization pipeline. Highly recommended to specify. If None, the configuration will be loaded from the default file. |
None
|
Returns:
| Type | Description |
|---|---|
list[Structure]
|
list[Structure]: A list of optimized molecular structures as Structure objects. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input file does not exist or if the read structures are not valid. |
Source code in src/gpuma/api.py
optimize_batch_xyz_directory(input_directory, output_file, config=None)
Optimize a batch of structures from XYZ files in a directory.
This function reads multiple molecular structures from XYZ files in the specified input directory, optimizes each structure using the provided optimization pipeline, and writes the optimized structures to a multi-structure XYZ output file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_directory
|
str
|
Path to an input directory containing XYZ files. |
required |
output_file
|
str
|
Path to an output multi-structure XYZ file where the optimized structures will be written. |
required |
config
|
Config
|
Config object to control the optimization pipeline. Highly recommended to specify. If None, the configuration will be loaded from the default file. |
None
|
Returns:
| Type | Description |
|---|---|
list[Structure]
|
list[Structure]: A list of optimized molecular structures as Structure objects. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input directory does not exist or contains no valid XYZ files. |
Source code in src/gpuma/api.py
Model Loading
Functions for directly loading model calculators and torch-sim wrappers.
load_calculator(config)
Load an ASE-compatible calculator for single-structure optimization.
Dispatches to the Fairchem, ORB-v3, or SevenNet backend based on
config.model.model_type.
Parameters
config : Config GPUMA configuration object.
Returns
calculator
An ASE calculator (FAIRChemCalculator, ORBCalculator, or
SevenNetCalculator).
Raises
ImportError If the required backend package is not installed. ValueError If the model name is unknown or missing.
Source code in src/gpuma/models/__init__.py
load_torchsim_model(config)
Load a torch-sim model wrapper for GPU-accelerated batch optimization.
Dispatches to the Fairchem, ORB-v3, or SevenNet backend based on
config.model.model_type.
Parameters
config : Config GPUMA configuration object.
Returns
model
A torch-sim model (FairChemModel, OrbTorchSimModel, or a
Float64Wrapper-wrapped SevenNet model).
Raises
ImportError If the required backend package is not installed. ValueError If the model name is unknown or missing.
Source code in src/gpuma/models/__init__.py
Configuration
The Config object controls model selection, optimization settings, conformer
generation and technical/device options. It is accepted by every high- and
low-level optimization function. A ready-to-use instance carrying the built-in
defaults is available as gpuma.default_config (equivalent to Config()). See
the Configuration page for the full list of keys and defaults.
Config
Dict-backed configuration with attribute access for sections.
Example:
cfg = load_config_from_file() print(cfg.technical.logging_level) cfg.technical.device = "cuda" save_config_to_file(cfg, "config.json")
Source code in src/gpuma/config.py
conformer_generation
property
Return the conformer generation section of the configuration.
model
property
Return the model section of the configuration.
optimization
property
Return the optimization section of the configuration.
technical
property
Return the technical section of the configuration.
__init__(data=None)
Initialize configuration with optional overrides.
Parameters
data: Optional dictionary of configuration overrides.
Source code in src/gpuma/config.py
from_dict(data)
classmethod
load_config_from_file(filepath='config.json')
Load configuration from a JSON/YAML file and deep-merge with defaults.
This function caches the raw dictionary loaded from the file to avoid repeated I/O and parsing. The returned Config object is always a new instance, safe to modify.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to the config file. If it doesn't exist, defaults are used. |
'config.json'
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
Config
|
class: |
Config
|
Unknown keys are preserved. |
Source code in src/gpuma/config.py
save_config_to_file(config, filepath)
Save configuration to JSON/YAML file.
Accepts either a :class:Config instance or a plain dictionary.
Source code in src/gpuma/config.py
resolve_model_type(config)
Normalize a model_type value to its canonical form.
Accepted aliases:
- "fairchem" / "uma" -> "fairchem"
- "orb" / "orb-v3" -> "orb"
- "sevennet" / "7net" -> "sevennet"
Works with either :class:Config or a plain dict.
Source code in src/gpuma/config.py
I/O & Structure Conversion
Functions for reading, writing, and converting molecular structures.
read_xyz(file_path, charge=0, multiplicity=1)
Read an XYZ file and return a :class:Structure instance.
Parameters
file_path:
Path to the XYZ file to read.
charge:
Optional total charge to set on the structure (default: 0).
multiplicity:
Optional spin multiplicity to set (default: 1).
Returns
Structure Object with symbols, coordinates, and an optional comment.
Raises
FileNotFoundError If the specified file does not exist. ValueError If the file format is invalid.
Source code in src/gpuma/utils/io_handler.py
read_multi_xyz(file_path, charge=0, multiplicity=1)
Read an XYZ file containing multiple structures.
Parameters
file_path:
Path to the multi-structure XYZ file.
charge:
Optional total charge to set on all returned structures (default: 0).
multiplicity:
Optional spin multiplicity to set (default: 1).
Returns
list[Structure] List of structures read from the file.
Raises
FileNotFoundError If the specified file does not exist. ValueError If the file format is invalid.
Source code in src/gpuma/utils/io_handler.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | |
read_xyz_directory(directory_path, charge=0, multiplicity=1, sort=True)
Read all XYZ files from a directory.
Parameters
directory_path:
Path to directory containing XYZ files.
charge:
Optional total charge to set on all returned structures (default: 0).
multiplicity:
Optional spin multiplicity to set (default: 1).
sort:
Controls the order in which files are read. If True (default),
files are sorted in natural numerical order (e.g. mol_2.xyz
before mol_10.xyz). If False, files are read in
OS-dependent order, which is not guaranteed and may vary between
runs or platforms. If a callable is provided, it is used as the
sort key instead (see :func:sorted).
Returns
list[Structure]
List of structures from all XYZ files in the directory, in the
order determined by sort.
Raises
FileNotFoundError If the directory does not exist. ValueError If no valid XYZ files are found.
Source code in src/gpuma/utils/io_handler.py
smiles_to_xyz(smiles_string, return_full_xyz_str=False, multiplicity=None, config=None)
Convert a SMILES string to a :class:Structure or an XYZ string.
Parameters
smiles_string:
Valid SMILES string representing the molecular structure.
return_full_xyz_str:
If True, return an XYZ-format string instead of a
:class:Structure instance.
multiplicity:
Optional spin multiplicity to set on the structure (default: None).
Returns
Structure | str
Either a :class:Structure or an XYZ string depending on
return_full_xyz_str.
Source code in src/gpuma/utils/io_handler.py
smiles_to_ensemble(smiles_string, max_num_confs, multiplicity=None, seed=None, config=None)
Generate conformer ensemble from SMILES.
Parameters
smiles_string:
Valid SMILES string representing the molecular structure.
max_num_confs:
Maximum number of conformers to generate.
multiplicity:
Optional spin multiplicity to set on the structures (default: None).
seed:
Optional random seed for reproducible conformer generation.
Returns
list[Structure]
A list of :class:Structure instances representing the conformers.
Source code in src/gpuma/utils/io_handler.py
save_xyz_file(structure, file_path)
Save a single :class:Structure to an XYZ file.
The comment line includes the energy (if set), charge, and multiplicity.
Parameters
structure: Structure to write. file_path: Destination file path.
Source code in src/gpuma/utils/io_handler.py
save_multi_xyz(structures, file_path, comments=None)
Save multiple structures to a single multi-structure XYZ file.
Each structure block includes the energy (if set), charge, and multiplicity in the comment line.
Parameters
structures: List of structures to write. file_path: Destination file path. comments: Optional per-structure comment strings. Falls back to each structure's own comment if not provided.
Source code in src/gpuma/utils/io_handler.py
save_as_single_xyz_files(structures, output_dir, comments=None)
Save each structure to its own XYZ file in a directory.
Files are zero-padded to sort naturally, e.g. structure_01.xyz for
up to 99 structures, structure_0001.xyz for up to 9999, etc.
Parameters
structures: List of structures to save. output_dir: Directory where files will be written. Created if it does not exist. comments: Optional per-structure comment strings.
Source code in src/gpuma/utils/io_handler.py
Batched Conformer Generation
Convert many SMILES to 3D structures in one call. These batch across molecules,
which is what makes the optional GPU backend worthwhile; the per-molecule
helpers above call into them. The backend follows technical.device in the
configuration and falls back to CPU when no GPU is usable.
generate_structures(smiles_list, config=None, multiplicity=None, n_confs=None, seed=DEFAULT_SEED, prune_rms_thresh=DEFAULT_PRUNE_RMS, max_iters=DEFAULT_MAX_ITERS, batch_size=500, n_threads=1, allow_cpu_fallback=True)
Convert SMILES to one 3D structure each, as a single batch.
Embeds a conformer ensemble per molecule, minimizes every conformer, and
keeps the lowest-energy one. Use :func:generate_ensembles to keep more
than one.
Parameters
smiles_list:
SMILES strings to convert.
config:
gpuma configuration; technical.device selects the backend. Loaded
from the default location if omitted.
multiplicity:
Spin multiplicity applied to every returned structure. None takes
config.optimization.multiplicity.
n_confs:
Conformers generated per molecule. None selects a budget from
rotatable-bond count via :data:CONF_BUDGET; an explicit int applies
that count uniformly instead.
seed:
Random seed for the embedding. -1 lets RDKit choose one per run,
making geometries non-reproducible.
prune_rms_thresh:
RMSD threshold for discarding duplicate conformers during embedding.
max_iters:
Maximum force-field minimization iterations per conformer. GPU backend
only -- the CPU backend goes through morfeus, which does not expose it.
batch_size:
Molecules per nvMolKit batch. GPU backend only.
n_threads:
Thread count handed to RDKit, CPU backend only. Leave at 1 when the
caller already parallelizes across molecules.
allow_cpu_fallback:
When a GPU was requested but is unusable, True transparently runs
on CPU. Set False to re-raise instead, so a caller that
parallelizes CPU work itself can choose its own strategy rather than
silently getting a serial CPU run.
Returns
list[Structure | None]
One entry per input, in input order. None marks a molecule that
could not be parsed or embedded, so one bad SMILES cannot abort a
library.
Raises
Exception
Whatever the GPU backend raised, when a GPU was requested and
allow_cpu_fallback is False.
Source code in src/gpuma/conformer_generation/embed.py
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | |
generate_ensembles(smiles_list, max_num_confs, config=None, multiplicity=None, n_confs=None, seed=DEFAULT_SEED, prune_rms_thresh=DEFAULT_PRUNE_RMS, max_iters=DEFAULT_MAX_ITERS, batch_size=500, n_threads=1, allow_cpu_fallback=True)
Convert SMILES to conformer ensembles, as a single batch.
As :func:generate_structures, but keeps several conformers per molecule
instead of one. All other parameters carry the same meaning.
Parameters
max_num_confs:
Maximum conformers returned per molecule, lowest energy first. This
is distinct from n_confs, which controls how many are generated --
generating fewer than you keep simply wastes the budget. Fewer than
requested may come back either way, since RMSD pruning removes
duplicates.
Returns
list[list[Structure] | None]
One entry per input, in input order. Each entry is a list of at most
max_num_confs structures, or None for a molecule that could not
be parsed or embedded.
Raises
ValueError
If max_num_confs is not positive.
Exception
Whatever the GPU backend raised, when a GPU was requested and
allow_cpu_fallback is False.
Source code in src/gpuma/conformer_generation/embed.py
Low-Level Optimization
Lower-level functions used by the high-level API.
optimize_single_structure(structure, config=None, calculator=None)
Optimize a single :class:Structure using an ASE optimizer.
The same structure instance is returned with updated coordinates and
energy.
Parameters
structure : Structure
Molecular structure to optimize.
config : Config, optional
Configuration controlling the model and convergence settings.
Defaults to :func:load_config_from_file if not provided.
calculator : optional
Pre-loaded ASE calculator. If None, one is loaded (and cached)
from the configuration.
Returns
Structure The input structure with optimized coordinates and energy set.
Raises
RuntimeError If the optimization fails for any reason.
Source code in src/gpuma/optimizer.py
optimize_structure_batch(structures, config=None)
Optimize a list of structures and return them with updated coordinates.
The optimization mode is controlled by
config.optimization.batch_optimization_mode:
"sequential": Each structure is optimized individually with ASE using a shared calculator."batch": All structures are optimized together using torch-sim GPU-accelerated batch optimization (requires GPU).
Parameters
structures : list[Structure]
Structures to optimize.
config : Config, optional
Configuration object. Defaults to :func:load_config_from_file.
Returns
list[Structure] Optimized structures with coordinates and energies set.
Raises
ValueError If structures have mismatched symbols/coordinates or are empty, or if the optimization mode is unknown.
Source code in src/gpuma/optimizer.py
Utilities
Timing decorators and context managers for profiling.
time_it(func)
Measure the execution time of a function and log the result.
Parameters
func: Callable to be wrapped.
Returns
callable
Wrapped function that logs its runtime at :mod:logging.INFO level.
Source code in src/gpuma/utils/decorators.py
timed_block
Context manager that measures and logs a named code block.
The elapsed time (in seconds) is available via the :attr:elapsed
attribute after the block exits. While inside any
:class:capture_timings context manager, the (name, elapsed) pair
is also published to that capture.
Example
with timed_block("model loading") as tb: ... model = load_model() print(tb.elapsed)
Source code in src/gpuma/utils/decorators.py
__enter__()
__exit__(*exc_info)
Stop the timer, store elapsed time, log, and notify captures.