Overview

The Python API (or PyAPI for short) of MLatom mainly contains 3 components: mlatom.data, mlatom.models, and mlatom.simulations.

With class mlatom.data, one can create/manipulate/save/load chemical data into objects like mlatom.data.atom, mlatom.data.molecule, and mlatom.data.molecular_database.

The class mlatom.models contains lots of computational chemistry models, based on quantum mechanics and machine learning, for making predictions on molecules. The models can be categorized into 3 types:

mlatom.simulations makes use of an mlatom.models object to perform simulations such as geometry optimizations or molecular dynamics.

Please check a simple example that illustrates the usage of these components.

Data

!---------------------------------------------------------------------------!
! data: Module for working with data                                        !
! Implementations by: Pavlo O. Dral, Fuchun Ge,                             !
!                     Shuang Zhang, Yi-Fan Hou, Yanchi Ou, Mikołaj Martyka  !
!                     Jakub Martinka                                        !
!---------------------------------------------------------------------------!
class mlatom.data.atom(nuclear_charge: int | None = None, atomic_number: int | None = None, element_symbol: str | None = None, nuclear_mass: float | None = None, xyz_coordinates: ndarray | List | None = None)[source]

Create an atom object.

Parameters:
  • nuclear_charge (int, optional) – provide the nuclear charge to define the atom.

  • atomic_number (int, optional) – provide the atomic number to define the atom.

  • element_symbol (int, optional) – provide the element symbol to define the atom.

  • nuclear_mass (int, optional) – provide the nuclear mass to define the atom.

  • xyz_coordinates (Array-like, optional) – specify the location of atom in Cartesian coordinates.

__init__(nuclear_charge: int | None = None, atomic_number: int | None = None, element_symbol: str | None = None, nuclear_mass: float | None = None, xyz_coordinates: ndarray | List | None = None)[source]

Initialize atom object with atomic_number/nuclear_charge/element_symbol and xyz_coordinates. The nuclear_mass can be used to defind the mass of the atom (unit: AMU, atomic mass unit). By default, use the relative atomic mass.

property nuclear_charge

Nuclear charge of the atom.

property element_symbol

Element symbol of the atom.

property nuclear_mass

Nuclear mass of the atom.

property multiplicity

Multiplicity of the atom.

property H0

Enthalpy of formation at 0 K.

property nuclear_spin

Nuclear spin of the atom

copy(atomic_labels: List[str] = None) → atom[source]

Return a copy of the current atom object. It will always copy the basis properties of the atom (atomic number, nuclear mass, etc.).

Parameters:

atomic_labels (List[str]) – A list of properties to copy. It can be ['xyz_coordinates'] if you want to copy the xyz coordinates of the atom.

class mlatom.data.molecule(charge: int = 0, multiplicity: int = 1, atoms: List[atom] = None, pbc: ndarray | bool | None = None, cell: ndarray | None = None)[source]

Create a molecule object.

Parameters:
  • charge (float, optional) – Specify the charge of the molecule.

  • multiplicity (int, optional) – Specify the multiplicity of the molecule.

  • atoms (List[atom], optional) – Specify the atoms in the molecule.

Examples

Select an atom inside with subscription:

from mlatom.data import atom, molecule
at = atom(element_symbol = 'C')
mol = molecule(atoms = [at])
print(id(at), id(mol[0]))
id

The unique ID for this molecule.

charge

The electric charge of the molecule.

multiplicity

The multiplicity of the molecule.

load(filename: str, format: str) -> molecule:

Load a molecule object from a dumped file.

Updates a molecule object if initialized:

mol = molecule(); mol.load(filename='mymol.json')

Returns a molecule object if called as class method:

mol = molecule.load(filename='mymol.json')

Arguments:

filename (str): filename or path

format (str, optional): currently, 'json', 'xyz', 'xyzstring', 'gaussian', and 'mndo' are supported.

‘json’

json format

‘xyz’

xyz file

‘xyzstring’

xyz string

‘gaussian’

Gaussian output file

‘mndo’

MNDO output file

property pbc

The periodic boundary conditions of the molecule. Setting it with mol.pbc = True is equal to mol.pbc = [True, True, True].

property cell

The matrix of 3 vectors that defines the unicell. The setter of it simply wraps ase.geometry.cell.cellpar_to_cell().

property cell_coordinates: ndarray

The relative coordinates in the cell.

map_to_unicell()[source]

Map all atoms outside the unicell into it.

read_from_xyz_file(filename: str, format: str | None = None) → molecule[source]

Load molecular geometry from XYZ file.

Data in standard XYZ format can be read if parameter format is not specified.

Extra formats supoorted are:

  • 'COLUMBUS'

  • 'NEWTON-X' or 'NX'

  • 'turbomol'

Parameters:
  • filename (str) – The name of the file to be read.

  • format (str, optional) – The format of the file.

read_from_xyz_string(string: str = None, format: str | None = None) → molecule[source]

Load molecular geometry from XYZ string.

Data in standard XYZ format can be read if parameter format is not specified.

Extra formats supoorted are:

  • 'COLUMBUS'

  • 'NEWTON-X' or 'NX'

  • 'turbomol'

Parameters:
  • string (str) – The string input.

  • format (str, optional) – The format of the string.

read_from_numpy(coordinates: ndarray, species: ndarray) → molecule[source]

Load molecular geometry from a numpy array of coordinates and another one for species.

The shape of the input coordinates should be (N, 3), while (N,) for the input species.

Where the N is the number of atoms.

read_from_smiles_string(smi_string: str) → molecule[source]

Generate molecular geometry from a SMILES string provided.

The geometry will be generated and optimized with Pybel’s make3D() method.

classmethod from_xyz_file(filename: str, format: str | None = None) → molecule[source]

Classmethod wrapper for molecule.read_from_xyz_file(), returns a molecule object.

classmethod from_xyz_string(string: str = None, format: str | None = None) → molecule[source]

Classmethod wrapper for molecule.read_from_xyz_string(), returns a molecule object.

classmethod from_numpy(coordinates: ndarray, species: ndarray) → molecule[source]

Classmethod wrapper for molecule.read_from_numpy(), returns a molecule object.

classmethod from_smiles_string(smi_string: str) → molecule[source]

Classmethod wrapper for molecule.read_from_smiles_string(), returns a molecule object.

add_atom_from_xyz_string(line: str) → None[source]

Add an atom to molecule from a string in XYZ format

add_scalar_property(scalar, property_name: str = 'y') → None[source]

Add a scalar property to the molecule. So the property can be called by molecule.<property_name>.

Parameters:
  • scalar – The scalar to be added.

  • property_name (str, optional) – The name assign to the scalar property.

add_xyz_derivative_property(derivative, property_name: str = 'y', xyz_derivative_property: str = 'xyz_derivatives') → None[source]

Add a XYZ derivative property to the molecule.

Parameters:
  • derivative – The derivative property to be added.

  • property_name (str, optional) – The name of the associated non-derivative property.

  • xyz_derivative_property (str, optional) – the name assign to the derivative property.

add_hessian_property(hessian, hessian_propety: str = 'hessian') → None[source]

Add a hessian property to the molecule

Parameters:
  • hessian – Hessian matrix (3N, 3N) to be added

  • hessian_propety (str, optional) – the name assign to the hessian property

add_xyz_vectorial_property(vector, xyz_vectorial_property: str = 'xyz_vector') → None[source]

Add a XYZ vectorial property to the molecule.

Parameters:
  • vector – The vector to be added.

  • xyz_vectorial_property (str, optional) – the name assign to the vectorial property.

write_file_with_xyz_coordinates(filename: str, format: str | None = None) → None[source]

Write the molecular geometry data into a file. Data in standard XYZ format can be read if parameter format is not specified.

Extra formats supoorted are:

  • 'COLUMBUS'

  • 'NEWTON-X' or 'NX'

  • 'turbomol'

Parameters:
  • filename (str) – The name of the file to be written.

  • format (str, optional) – The format of the file.

get_xyz_string(only_coordinates=False) → str[source]

Return the molecular geometry in a string of XYZ format.

Parameters:

only_coordinates (bool, optional) – print only coordinates, otherwise print number of atoms and comment line, default: False.

property atomic_numbers: ndarray

The atomic numbers of the atoms in the molecule.

property element_symbols: ndarray

The element symbols of the atoms in the molecule.

property smiles: str

The SMILES representation of the molecule.

property xyz_coordinates: ndarray

The XYZ geometry of the molecule.

property energy_gradients: ndarray

Energy gradients of the molecule.

get_number_of_atoms()[source]

Get the number of atoms in the molecule.

get_property(property_name)[source]

Get the property in the molecule.

A dotted name reaches a property held under a named label source rather than in the flat slot: mol.get_property('wb97x.energy_gradients') is the gradients as computed by the source registered under 'wb97x', while mol.get_property('energy') is the flat value, whose source is recorded in mol.label_source.

A dotted name that does not resolve raises, because it names one source explicitly and there is no sensible value to return instead. A plain name keeps its long-standing behaviour of returning NaN when absent, which molecular_database.filter_by_property() depends on.

static _named_contents(container)[source]

Names worth listing in a “cannot resolve” message, bookkeeping aside.

_get_property_from_source(property_name)[source]

Resolve a dotted property name, e.g. 'wb97x.energy_gradients' or 'aiqm2_nn.member_0.energy', walking the named nodes in turn.

label_sources_present()[source]

Names of the label sources this molecule carries labels under, i.e. the namespaces reachable with a dotted property name.

set_label_source(source, **properties)[source]

Record that this molecule’s flat labels came from source, and optionally file a copy of them under that name.

mol.set_label_source('ccsdt', energy=-76.4) sets mol.energy, mol.ccsdt.energy and mol.label_source; without keyword arguments it only records where the labels already in the flat slots came from.

set_property(**kwargs) → None[source]

Set properties to the molecule.

Example

import mlatom as ml
mol = ml.data.molecule.load(...)
mol.set_property(property1=..., property2=...)
get_xyz_vectorial_properties(property_name) → ndarray[source]

Get the xyz vectorial property of the molecule

Example

import mlatom as ml
mol = ml.data.molecule.load(...)
xyz_coordinates = mol.get_xyz_vectorial_properties("xyz_coordinates")
# It is equivalent to
xyz_coordinates = mol.xyz_coordinates
property nuclear_masses: ndarray

Get the array of nuclear masses of the atoms in the molecule.

property kinetic_energy: float

Give out the kinetic energy (A.U.) based on the xyz_velocities.

copy(atomic_labels: List[str] = None, molecular_labels: List[str] = None) → molecule[source]

Return a copy of current molecule object. By default it will copy all the things in the molecule unless the user specifies either atomic_labels or molecular_labels.

Parameters:
  • atomic_labels (List[str]) – A list of atomic properties to copy. It can be ['xyz_coordinates'] if you want to copy the xyz coordinates of the atoms.

  • molecular_labels (List[str]) – A list of molecular properties to copy. It can be ['energy'] if you want to copy the energy of the molecule.

update_from(another_molecule: molecule) → None[source]

Update the current molecule with properties from another molecule

Example

bond_length(a1, a2) → float[source]

Return the distance between atom numbers a1 and a2.

Atoms are numbered from zero.

bond_angle(a1, a2, a3, degrees=True) → float[source]

Return the bond angle a1-a2-a3.

The angle is defined by the vectors a1-a2 and a2-a3. Atoms are numbered from zero. based on Tom Keal MNDOtools.py, October 2007 degrees - if true, return angle in degrees, else radians.

dihedral_angle(a1, a2, a3, a4, degrees=True, unsigned=False) → float[source]

Return the signed dihedral angle a1-a2-a3-a4.

The angle is defined between the planes a1-a2-a3 and a2-a3-a4. Atoms are numbered from zero.

Positive angle corresponds to a counter-clockwise rotation from the a1-a2-bond projection to the a3-a4-bond projection when looking along the a2->a3 direction.

degrees - if true, return angle in degrees, else radians.

proliferate(shifts: Iterable | None = None, XYZshifts: Iterable | None = None, Xshifts: Iterable | None = [0], Yshifts: Iterable | None = [0], Zshifts: Iterable | None = [0], PBC_constrained: bool = True) → molecule[source]

Proliferate the unicell by specified shifts along cell vectors (called X/Y/Z here).

Returns a new molecule object.

Parameters:
  • shifts (Iterable, optional) – The list of shifts to perform. Each shift should be a 3D vector that indicates the coefficient applies to the corresponding cell vector.

  • XYZshifts (Iterable, optional) – Generate all possible shifts with given shift coefficients in all three directions when a list is specified. When a list of 3 lists is specified, it’s equal to setting X/Y/Zshifts

  • Xshifts (Iterable, optional) – Specify all possible shift coefficients in the direction of the first cell vector.

  • Yshifts (Iterable, optional) – Specify all possible shift coefficients in the direction of the second cell vector.

  • Zshifts (Iterable, optional) – Specify all possible shift coefficients in the direction of the third cell vector.

  • PBC_constrained (bool) – Controls whether the shifts in some directions are disabled where corresponding PBC is false. Only applies to XYZshifts.

Note

Priorities for different types of shifts:

shifts > XYZshifts > X/Y/Zshifts

Examples

Single H atom in the centre of a cubic cell (2x2x2):

mol = ml.molecule.from_numpy(np.ones((1, 3)), np.array([1]))
mol.pbc = True
mol.cell = 2

Proliferate to get two periods in all three directions, with shifts:

new_mol = mol.proliferate(
    shifts = [
        [0, 0, 0],
        [1, 0, 0],
        [0, 1, 0],
        [0, 0, 1],
        [1, 1, 0],
        [1, 0, 1],
        [0, 1, 1],
        [1, 1, 1],
    ]
)

with XYZshifts:

new_mol = mol.proliferate(XYZshifts=range(2))
# or
new_mol = mol.proliferate(XYZshifts=[range(2)]*3)

with X/Y/Zshifts:

new_mol = mol.proliferate(Xshifts=range(2), Yshifts=(0, 1), Zshifts=[0, 1]))

All scripts above will make new_mol.xyz_coordinates be:

array([[1., 1., 1.],
       [3., 1., 1.],
       [1., 3., 1.],
       [3., 3., 1.],
       [1., 1., 3.],
       [3., 1., 3.],
       [1., 3., 3.],
       [3., 3., 3.]])
dump(filename=None, format='json') → None[source]

Dump the current molecule object into a file. Now, json and Gaussian output formats are supported.

get_internuclear_distance_matrix() → ndarray[source]

Get the internuclear distance matrix

get_bonds()[source]

Get bonds in the molecule. Shape: (Nbonds, 2). Each row has the indices of two bonding atoms.

is_it_linear() → bool[source]

Check if the molecule is linear.

property state_energies: ndarray

The electronic state energies of the molecule.

property state_gradients: ndarray

The electronic state energy gradients of the molecule.

property energy_gaps: ndarray

The energy gaps of different states.

property excitation_energies: ndarray

The excitation energies of the molecule from ground state.

property nstates: int

The number of electronic states.

get_xyzvib_string(normal_mode=0)[source]

Get the xyz string with geometries and displacements along the vibrational normal modes

view(normal_mode=None, slider=True, width=400, height=300)[source]

Visualize the molecule and its vibrations if requested. Uses py3Dmol. :param normal_mode: the index of a normal mode to visualize. Default: None. :type normal_mode: integer, optional :param slider: show interactive slider to choose the mode.

Default: True (only works if normal_mode is not None).

Parameters:
  • width (int, float) – the width of the window with geometry. Default 400.

  • height (int, float) – the height of the window with geometry. Default 300.

property velocities: ndarray

XYZ velocities of the molecule.

property CoM: ndarray

Center of mass of the molecule.

property linear_momentum: ndarray

Linear momentum of the molecule.

property angular_momentum: ndarray

Angular momentum of the molecule

property moment_of_inertia_tensor: ndarray

Moment of inertia tensor of the molecule.

property angular_velocities: ndarray

Angular velocities of the molecule.

zero_angular_momentum(center=None) → None[source]

Clear the angular momentum of the molecule.

class mlatom.data.molecular_trajectory(steps=None)[source]

A class for storing/access molecular trajectory data, which is generated from a dynamics or a optimization task.

dump(filename=None, format=None)[source]

Dump the molecular_trajectory object into a file.

Available formats are:

  • 'h5md' (requires python module h5py and pyh5md)

  • 'json'

  • 'plain_text'

load(filename: str = None, format: str = None)[source]

Load the previously dumped molecular_trajectory from file.

get_xyz_string() → str[source]

Return the XYZ string of the molecules in the trajectory.

to_database() → molecular_database[source]

Return a molecular database comprising the molecules in the trajectory.

view(width=400, height=300)[source]

Visualize the molecular trajectory. Uses py3Dmol.

Parameters:
  • width (int, float) – the width of the window with geometry. Default 400.

  • height (int, float) – the height of the window with geometry. Default 300.

reset_step_index()[source]

Reset the step index to ascending order

plot_energy_profile(filename='energy_profile', relative_to='first', unit='kcal/mol', xlabel='Image (reactant to product)', title=None)[source]

Plot the energy profile along the trajectory (e.g. a nudged-elastic-band band or a reaction path): each step’s energy relative to a reference, versus the step index. Writes <filename>.png and the raw data <filename>.txt, and returns the .png path. Each step’s molecule must carry an energy.

Parameters:
  • filename (str) – output path stem; .png and .txt are appended. Default energy_profile.

  • relative_to (str, int) – reference energy — 'first' (reactant, default), 'min', 'max' (the peak), or a 0-based step index.

  • unit (str) – 'kcal/mol' (default) or 'Hartree'.

  • xlabel (str) – x-axis caption.

  • title (str) – plot title; auto-generated (with the barrier) if None.

class mlatom.data.h5md(filename: str, data: Dict[str, Any] = {}, mode: str = 'w')[source]

Saving trajectory data to file in H5MD format

Parameters:
  • filename (str) – The filename of the h5md file output.

  • data (Dict) – The data to be stored (optional, if provided, the file will be closed after storing data).

  • mode (str, optional) – A string that controls the file processing mode (default value: ‘w’ for a new file, ‘r+’ for an exisiting file). The choices are listed in the table below which is consistent with pyh5md.File()

r

Readonly, file must exist

r+

Read/write, file must exist

w

Create file, truncate if exists

w- or x

Create file, fail if exists

Examples:

traj0 = h5md('traj.h5')  # open 'traj.h5'
traj1 = h5md('/tmp/test.h5', mode='r')  # open an existing file in readonly mode
traj2 = h5md('/tmp/traj2.h5', data={'time': 1.0, 'total_energy': -32.1, 'test': 8848}) # add some data to the file, then close the file

traj0.write(data) # write data to opened file
traj0(data) # an alternative way to write data

data = traj0.export() # export the data in the opened file
data = traj0() # an alternative way to export data
with h5md('test.h5') as traj: # export with a with statement
    data = traj.export()


traj0.close() # close the file

Note

the default data path in HDF5 file

particles/all:

‘box’, ‘gradients’, ‘mass’, ‘nad’, ‘names’, ‘position’, ‘species’, ‘velocities’

observables:

‘angular_momentum’, ‘generated_random_number’, ‘kinetic_energy’, ‘linear_momentum’, ‘nstatdyn’, ‘oscillator_strengths’, ‘populations’, ‘potential_energy’, ‘random_seed’, ‘sh_probabilities’, ‘total_energy’, ‘wavefunctions’,

and any other keywords

h5

the HDF5 file object

write(data: Dict[str, Any]) → None[source]

Write data to the opened H5 file. Data should be a dictionary-like object with ‘time’ in its keys().

export() → Dict[str, ndarray][source]

Export the data in the opened H5 file.

Returns:

A dictionary of the trajectory data in the H5 file.

close() → None[source]

Close the opened file.

__call__() → Dict[str, ndarray]

Export the data in the opened H5 file.

Returns:

A dictionary of the trajectory data in the H5 file.

Models

!---------------------------------------------------------------------------!
! models: Module with models                                                !
! Implementations by: Pavlo O. Dral, Fuchun Ge, Yi-Fan Hou, Yuxinxin Chen,  !
!                     Peikun Zheng                                          !
!---------------------------------------------------------------------------!
class mlatom.models.model[source]

Parent (super) class for models to enable useful features such as logging during geometry optimizations.

config_multiprocessing()[source]

for scripts that need to be executed before running model in parallel

predict(molecular_database: molecular_database = None, molecule: molecule = None, calculate_energy: bool = False, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, **kwargs)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

methods

!---------------------------------------------------------------------------!
! models: Module with models                                                !
! Implementations by: Pavlo O. Dral, Fuchun Ge, Yi-Fan Hou, Yuxinxin Chen,  !
!                     Peikun Zheng                                          !
!---------------------------------------------------------------------------!
mlatom.models.methods(method: str = None, program: str = None, **kwargs)[source]

Create a model object with a specified method.

Parameters:
  • method (str) – Specify the method. Available methods are listed in the section below.

  • program (str, optional) – Specify the program to use.

  • **kwargs – Other method and program-specific options

Available Methods:

'AIQM1', 'AIQM1@DFT', 'AIQM1@DFT*', 'AM1', 'ANI-1ccx', 'ANI-1x', 'ANI-1x-D4', 'ANI-2x', 'ANI-2x-D4', 'CCSD(T)*/CBS', 'CNDO/2', 'D4', 'DFTB0', 'DFTB2', 'DFTB3', 'GFN2-xTB', 'MINDO/3', 'MNDO', 'MNDO/H', 'MNDO/d', 'MNDO/dH', 'MNDOC', 'ODM2', 'ODM2*', 'ODM3', 'ODM3*', 'OM1', 'OM2', 'OM3', 'PM3', 'PM6', 'RM1', 'SCC-DFTB', 'SCC-DFTB-heats'.

Methods listed above can be accepted without specifying a program. The required programs still have to be installed though as described in the installation manual.

Available Programs and Their Corresponding Methods:

Program

Methods

TorchANI

'AIQM1', 'AIQM1@DFT', 'AIQM1@DFT*', 'ANI-1ccx', 'ANI-1x', 'ANI-1x-D4', 'ANI-2x', 'ANI-2x-D4', 'ANI-1xnr'

dftd4

'AIQM1', 'AIQM1@DFT', 'ANI-1x-D4', 'ANI-2x-D4', 'D4'

MNDO or Sparrow

'AIQM1', 'AIQM1@DFT', 'AIQM1@DFT*', 'MNDO', 'MNDO/d', 'ODM2*', 'ODM3*', 'OM2', 'OM3', 'PM3', 'SCC-DFTB', 'SCC-DFTB-heats'

MNDO

'CNDO/2', 'MINDO/3', 'MNDO/H', 'MNDO/dH', 'MNDOC', 'ODM2', 'ODM3', 'OM1', semiempirical OMx, DFTB, NDDO-type methods

Sparrow

'DFTB0', 'DFTB2', 'DFTB3', 'PM6', 'RM1', semiempirical OMx, DFTB, NDDO-type methods

xTB

'GFN2-xTB', semiempirical GFNx-TB methods

Orca

'CCSD(T)*/CBS', DFT

Gaussian

ab initio methods, DFT

PySCF

ab initio methods, DFT

AIQM1

!---------------------------------------------------------------------------!
! aiqm1: Artificial intelligence quantum-mechanical method 1                !
! Implementations by: Peikung Zheng & Pavlo O. Dral                         !
!---------------------------------------------------------------------------!
class mlatom.aiqm1.aiqm1_ani_wrapper(*args, **kwargs)[source]

Rebuilds an original AIQM1 ensemble member as a fully trainable ani object, matching its AEV and network architecture.

That is all this class does; the prediction keywords AIQM1 passes down and a network has no answer for are handled by ani.ignorable_prediction_kwargs, not here. Defined at module level so saved model trees can be reloaded.

classmethod from_pretrained(member, device=None)[source]

Convert an ani_nns_in_aiqm1 member into a trainable aiqm1_ani_wrapper instance.

Parameters:
  • member (ani_nns_in_aiqm1) – Original AIQM1 ensemble member.

  • device (torch.device or str, optional) – Target device. Defaults to member.device.

Return type:

aiqm1_ani_wrapper

class mlatom.aiqm1.aiqm1(*args, **kwargs)[source]

The Artificial intelligence-quantum mechanical method as in the AIQM1 paper.

Parameters:
  • method (str, optional) – AIQM method used. Currently supports AIQM1, AIQM1@DFT*, and AIQM1@DFT. Default value: AIQM1.

  • qm_program (str) – The QM program used in the calculation of ODM2* part. Currently supports MNDO and Sparrow program.

  • qm_program_kwargs (dictionary, optional) – Keywords passed to QM program.

  • baseline_kwargs (dictionary, optional) – Keywords passed to the ODM2* baseline method.

  • dispersion_kwargs (dictionary, optional) – Keywords passed to the D4 dispersion method.

  • model_index (int or list, optional) – Ensemble member(s) to fine-tune. Defaults to all 8 members.

  • device (str or torch.device, optional) – Device used for the ANI NN part.

  • working_directory (str, optional) – Working directory for baseline/dispersion calculations.

  • nthreads (int, optional) – Number of threads. Default: 1.

# Initialize molecule
mol = ml.data.molecule()
mol.read_from_xyz_file(filename='ethanol.xyz')
# Run AIQM1 calculation
aiqm1 = ml.methods(method='AIQM1', qm_program='MNDO')
aiqm1.predict(molecule=mol, calculate_energy=True, calculate_energy_gradients=True)
# Get energy, gradient, and prediction uncertainty of AIQM1
energy = mol.energy
gradient = mol.gradient
std = mol.aiqm1_nn.energy_standard_deviation
property nthreads

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

predict(molecular_database=None, molecule=None, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, nstates=1, current_state=0, **kwargs)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

_iter_ani_leaves(node=None)[source]

Iterate over the aiqm1_ani_wrapper leaf models inside the AIQM1 tree.

static _resolve_model_paths(model_dict, base_dir)[source]

Recursively resolve relative model_file paths.

static _make_paths_relative(model_dict, base_dir)[source]

Recursively make model_file paths relative to base_dir.

save(model_file='')[source]

Save the transfer-learned AIQM1 model to a directory.

The directory will contain:

  • tree.json: model metadata and tree structure

  • cv*.pt: TorchANI weights for each ensemble member

classmethod load(model_file, device=None)[source]

Load a transfer-learned AIQM1 model from a directory or tree.json.

classmethod from_dict(model_dict, device=None, base_dir=None)[source]

Reconstruct an aiqm1 instance from a dictionary produced by save().

class mlatom.aiqm1.atomic_energy_shift(method='AIQM1')[source]
predict(molecular_database=None, molecule=None, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, nstates=1, **kwargs)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

class mlatom.aiqm1.ani_nns_in_aiqm1(*args, **kwargs)[source]
predict(molecular_database=None, molecule=None, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, nstates=1, **kwargs)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

AIQM2

!---------------------------------------------------------------------------!
! aiqm2: Artificial Intelligence-Enhanced Quantum Mechanical Method 2       !
! Implementations by: Yuxinxin Chen and                                     !
!                     Pavlo O. Dral                                         !
!---------------------------------------------------------------------------!
class mlatom.aiqm2.aiqm2(method: str = 'AIQM2', working_directory: str = None, baseline_kwargs: dict = None, dispersion_kwargs: dict = None, nthreads: int = 1, model_index=None, device=None)[source]

GFN2-xTB based artificial intelligence quantum-mechanical method 2 (AIQM2)

Parameters:
  • method (str, optional) – Currently supports AIQM2, AIQM2@DFT

  • working_directory (str, optional) – The path to save temporary calculation file

  • qm_program_kwargs (dict, optional) – Keywords passed to GFN2-xTB

# Initialize molecule
mol = ml.data.molecule()
mol.read_from_xyz_file(filename='ethanol.xyz')
# Run AIQM2 calculation
aiqm2 = ml.methods(method='aiqm2')
aiqm2.predict(molecule=mol, calculate_energy=True, calculate_energy_gradients=True, calculate_hessian=True)
# Get energy, gradient, and uncertainty of AIQM2
energy = mol.energy
gradient = mol.get_energy_gradients()
hess = mol.hessian
std = mol.aiqm2_nn.energy_standard_deviation

Molecules containing elements outside the set the model was trained on cannot be treated by AIQM2 itself. Models covering more elements include AIQM3, the Aitomic add-ons (for example AIQM4@DFT) and AIQM2@UAIQM, the UAIQM extension of this model, which can be used out of the box for them. The add-ons, including the UAIQM models, are installed separately (http://MLatom.com/aitomic); see the UAIQM tutorial for the model choice and its version.

property nthreads

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

predict(molecular_database=None, molecule=None, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, calculate_dipole_derivatives=False, calculate_polarizability_derivatives=False)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

_iter_ani_leaves(node=None)[source]

Iterate over the ani leaf models inside the AIQM2 model tree.

Yields tuples (node, cv_index) where node is a model_tree_node whose .model is an ani instance, and cv_index is parsed from the node name.

static _resolve_model_paths(model_dict, base_dir)[source]

Recursively resolve relative model_file paths.

static _make_paths_relative(model_dict, base_dir)[source]

Recursively make model_file paths relative to base_dir.

save(model_file: str = '') → None[source]

Save the transfer-learned AIQM2 model to a directory.

The directory will contain:

  • tree.json: model metadata and tree structure

  • cv*.pt: TorchANI weights for each ensemble member

classmethod load(model_file: str, device=None)[source]

Load a transfer-learned AIQM2 model from a directory or tree.json.

classmethod from_dict(model_dict, device=None, base_dir=None)[source]

Reconstruct an aiqm2 instance from a dictionary produced by save().

AIQM3

!---------------------------------------------------------------------------!
! aiqm3: Artificial Intelligence-Enhanced Quantum Mechanical Method 3       !
! Implementations by: Yuxinxin Chen and                                     !
!                     Pavlo O. Dral                                         !
!---------------------------------------------------------------------------!

The AIQM3 weights are fetched at first use from Zenodo record 15876694; their own terms apply. Cite Y. Chen, Y.-F. Hou, R. Zubatyuk, O. Isayev, P.O. Dral, J. Chem. Theory Comput. 2026, 22, 2232.

class mlatom.aiqm3.aiqm3(method: str = 'AIQM3', working_directory: str = None, baseline_kwargs: dict = None, dispersion_kwargs: dict = None, nthreads: int = 1, model_index=None, device=None)[source]

GFN2-xTB based artificial intelligence quantum-mechanical method 3 (AIQM3)

Parameters:
  • method (str, optional) – Currently supports AIQM3, AIQM3@DFT, AIQM3@DFT*. Default: AIQM3

  • working_directory (str, optional) – The path to save temporary calculation file. By default, current directory will be choosed.

  • baseline_kwargs (dict, optional) – Keywords passed to GFN2-xTB. Default: None

  • dispersion_kwargs (dict, optional) – keywords passed to dftd3. Default: None

  • nthreads (int, optional) – The number of threads to be used. Default: None

# Initialize molecule
mol = ml.data.molecule()
mol.read_from_xyz_file(filename='ethanol.xyz')
# Run AIQM3 calculation
aiqm3 = ml.methods(method='aiqm3')
aiqm3.predict(molecule=mol, calculate_energy=True, calculate_energy_gradients=True, calculate_hessian=True)
# Get energy, gradient, and uncertainty of AIQM3
energy = mol.energy
gradient = mol.get_energy_gradients()
hess = mol.hessian
std = mol.aiqm3_nn.energy_standard_deviation

Molecules containing elements outside the set the model was trained on cannot be treated by AIQM3 itself. Models covering more elements include the Aitomic add-ons (for example AIQM4@DFT) and AIQM3@UAIQM, the UAIQM extension of this model, which can be used out of the box for them; only elements that GFN2-xTB itself cannot describe are out of reach. The add-ons, including the UAIQM models, are installed separately (http://MLatom.com/aitomic). Specify the model version explicitly:

uaiqm = ml.models.methods(method='uaiqm_gfn2xtbstar@cc', version='20250115')
mlatom sp uaiqm_gfn2xtbstar@cc uversion=20250115 xyzfile=mol.xyz
property nthreads

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

predict(molecular_database=None, molecule=None, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, calculate_dipole_derivatives=False)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

_supported_element_symbols()[source]

The elements this model can treat: its weights’ species, or the published set.

_iter_ani_leaves(node=None)[source]

Iterate over the ani leaf models inside the AIQM3 model tree.

static _resolve_model_paths(model_dict, base_dir)[source]

Recursively resolve relative model_file paths.

static _make_paths_relative(model_dict, base_dir)[source]

Recursively make model_file paths relative to base_dir.

save(model_file: str = '') → None[source]

Save the transfer-learned AIQM3 model to a directory.

classmethod load(model_file: str, device=None)[source]

Load a transfer-learned AIQM3 model from a directory or tree.json.

classmethod from_dict(model_dict, device=None, base_dir=None)[source]

Reconstruct an aiqm3 instance from a dictionary produced by save().

OMNI-P2x

omnip2x: OMNI-P2x: A Universal Neural Network Potential for Excited-State Simulations
Implementations by: Mikolaj Martyka and Pavlo O. Dral
class mlatom.omnip2x.omnip2x(method: str = 'OMNI-P2x', working_directory: str = '.', nthreads=1, warnings=True)[source]
property nthreads

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

predict(molecular_database=None, molecule=None, calculate_energy=True, calculate_energy_gradients=False, nstates=1, current_state=0, use_fragment_correction=False)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

ml_model

!---------------------------------------------------------------------------!
! models: Module with models                                                !
! Implementations by: Pavlo O. Dral, Fuchun Ge, Yi-Fan Hou, Yuxinxin Chen,  !
!                     Peikun Zheng                                          !
!---------------------------------------------------------------------------!
class mlatom.models.ml_model[source]

Useful as a superclass for the ML models that need to be trained.

calculate_validation_loss(training_kwargs=None, prediction_kwargs=None, cv_splits_ml_databases=None, cv_splits_molecular_databases=None, calculate_CV_split_errors=False, subtraining_ml_database=None, validation_ml_database=None, subtraining_molecular_database=None, validation_molecular_database=None, validation_loss_function=None, validation_loss_function_kwargs={}, debug=False)[source]

Returns the validation loss for the given hyperparameters.

By default, the validation loss is RMSE evaluated as a geometric mean of scalar and vectorial properties, e.g., energies and gradients.

Parameters:
  • training_kwargs (dict, optional) – the kwargs to be passed to yourmodel.train() function.

  • prediction_kwargs (dict, optional) – the kwargs to be passed to yourmodel.predict() function.

  • cv_splits_molecular_databases (list, optional) – the list with cross-validation splits, each element is molecular_database.

  • calculate_CV_split_errors (bool, optional) – requests to return the errors for each cross-validation split as a list in addtion to the aggregate cross-validation error.

  • subtraining_molecular_database (molecular_database, optional) – molecular database for sub-training to be passed to yourmodel.train() function.

  • validation_molecular_database (molecular_database, optional) – molecular database for validation to be passed to yourmodel.predict() function.

  • validation_loss_function (function, optional) – user-defined validation function.

  • validation_loss_function_kwargs (dict, optional) – kwargs for above validation_loss_function.

dump(filename=None, format='json')[source]

Dumps model class object information in a json file (do not confused with saving the model itself, i.e., its parameters!).

generate_model_dict()[source]

Generates model dictionary for dumping in json format.

optimize_hyperparameters(hyperparameters=None, training_kwargs=None, prediction_kwargs=None, cv_splits_ml_databases=None, cv_splits_molecular_databases=None, subtraining_ml_database=None, validation_ml_database=None, subtraining_molecular_database=None, validation_molecular_database=None, optimization_algorithm=None, optimization_algorithm_kwargs={}, maximum_evaluations=10000, validation_loss_function=None, validation_loss_function_kwargs={}, debug=False)[source]

Optimizes hyperparameters by minimizing the validation loss.

By default, the validation loss is RMSE evaluated as a geometric mean of scalar and vectorial properties, e.g., energies and gradients.

Parameters:
  • hyperparameters (list, required) – the list with strings - names of hyperparameters. Hyperparameters themselves must be in youmodel.hyperparameters defined with class instance hyperparameters consisting of hyperparameter defining the optimization space.

  • training_kwargs (dict, optional) – the kwargs to be passed to yourmodel.train() function.

  • prediction_kwargs (dict, optional) – the kwargs to be passed to yourmodel.predict() function.

  • cv_splits_molecular_databases (list, optional) – the list with cross-validation splits, each element is molecular_database.

  • calculate_CV_split_errors (bool, optional) – requests to return the errors for each cross-validation split as a list in addtion to the aggregate cross-validation error.

  • subtraining_molecular_database (molecular_database, optional) – molecular database for sub-training to be passed to yourmodel.train() function.

  • validation_molecular_database (molecular_database, optional) – molecular database for validation to be passed to yourmodel.predict() function.

  • validation_loss_function (function, optional) – user-defined validation function.

  • validation_loss_function_kwargs (dict, optional) – kwargs for above validation_loss_function.

  • optimization_algorithm (str, required) – optimization algorithm. No default, must be specified among: ‘grid’ (‘brute’), ‘TPE’, ‘Nelder-Mead’, ‘BFGS’, ‘L-BFGS-B’, ‘Powell’, ‘CG’, ‘Newton-CG’, ‘TNC’, ‘COBYLA’, ‘SLSQP’, ‘trust-constr’, ‘dogleg’, ‘trust-krylov’, ‘trust-exact’.

  • optimization_algorithm_kwargs (dict, optional) – kwargs to be passed to optimization algorithm, e.g., {'grid_size': 5} (default 9 for the grid search).

  • maximum_evaluations (int, optional) – maximum number of optimization evaluations (default: 10000) supported by all optimizers except for grid search.

Saves the final hyperparameters in yourmodel.hyperparameters adn validation loss in yourmodel.validation_loss.

predict(ml_database: data.ml_database = None, entry: data.entry = None, molecular_database: data.molecular_database = None, molecule: data.molecule = None, calculate_energy: bool = False, property_to_predict: str | None = 'estimated_y', calculate_energy_gradients: bool = False, xyz_derivative_property_to_predict: str | None = 'estimated_xyz_derivatives_y', calculate_hessian: bool = False, hessian_to_predict: str | None = 'estimated_hessian_y') → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • property_to_predict (str, optional) – The label name where the predicted properties to be saved.

  • xyz_derivative_property_to_predict (str, optional) – The label name where the predicted XYZ derivatives to be saved.

  • hessian_to_predict (str, optional) – The label name where the predicted Hessians to be saved.

reset()[source]

Resets model (deletes the ML model file from the hard disk).

train(ml_database: ml_database, molecular_database: molecular_database, property_to_learn: str | None = 'y', xyz_derivative_property_to_learn: str = None) → None[source]

Train the model with molecular database provided.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – The database of molecules for training.

  • property_to_learn (str, optional) – The label of property to be learned in model training.

  • xyz_derivative_property_to_learn (str, optional) – The label of XYZ derivative property to be learned.

class mlatom.models.hyperparameter(value: Any = None, optimization_space: str = 'linear', dtype: Callable | None = None, name: str = '', minval: Any = None, maxval: Any = None, step: Any = None, choices: Iterable[Any] = [], **kwargs)[source]

Class of hyperparameter object, containing data could be used in hyperparameter optimizations.

Parameters:
  • value (Any, optional) – The value of the hyperparameter.

  • optimization_space (str, optional) – Defines the space for hyperparameter. Currently supports 'linear', and 'log'.

  • dtype (Callable, optional) – A callable object that forces the data type of value. Automatically choose one if set to None.

copy()[source]

Returns a copy of current instance.

Returns:

a new instance copied from current one.

Return type:

mlatom.models.hyperparamter

update(new_hyperparameter: hyperparameter) → None[source]

Update hyperparameter with data in another instance.

Parameters:

new_hyperparameter (mlatom.models.hyperparamters) – Whose data are to be applied to the current instance.

class mlatom.models.hyperparameters(dict=None, /, **kwargs)[source]

Class for storing hyperparameters, values are auto-converted to mlatom.models.hyperparameter objects. Inherit from collections.UserDict.

Initiaion:

Initiate with a dictinoary or kwargs or both.

e.g.:

hyperparamters({'a': 1.0}, b=hyperparameter(value=2, minval=0, maxval=4))
copy(keys: Iterable[str] | None = None) → hyperparameters[source]

Returns a copy of current instance.

Parameters:

keys (Iterable[str], optional) – If keys provided, only the hyperparameters selected by keys will be copied, instead of all hyperparameters.

Returns:

a new instance copied from current one.

Return type:

mlatom.models.hyperparamters

class mlatom.models.kreg(model_file: str | None = None, ml_program: str = 'KREG_API', equilibrium_molecule: molecule | None = None, prior: float = 0, nthreads: int | None = None, hyperparameters: Dict[str, Any] | hyperparameters = {})[source]

Create a KREG model object.

Parameters:
  • model_file (str, optional) – The name of the file where the model should be dumped to or loaded from.

  • ml_program (str, optional) – Specify which ML program to use. Avaliable options: 'KREG_API', 'MLatomF.

  • equilibrium_molecule (mlatom.data.molecule | None) – Specify the equilibrium geometry to be used to generate RE descriptor. The geometry with lowest energy/value will be selected if set to None.

  • prior (default - None) – the prior can be ‘mean’, None (0.0), or any floating point number.

  • hyperparameters (Dict[str, Any] | mlatom.models.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

generate_model_dict()[source]

Generates model dictionary for dumping in json format.

train(molecular_database=None, property_to_learn=None, xyz_derivative_property_to_learn=None, save_model=True, invert_matrix=False, matrix_decomposition=None, prior=None, hyperparameters: Dict[str, Any] | hyperparameters = {})[source]

Train the KREG model with molecular database provided.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – The database of molecules for training.

  • property_to_learn (str, optional) – The label of property to be learned in model training.

  • xyz_derivative_property_to_learn (str, optional) – The label of XYZ derivative property to be learned.

  • prior (str or float or int, optional) – default zero prior. It can also be ‘mean’ and any user-defined number.

predict(molecular_database=None, molecule=None, calculate_energy=False, calculate_energy_gradients=False, calculate_hessian=False, property_to_predict=None, xyz_derivative_property_to_predict=None, hessian_to_predict=None)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • property_to_predict (str, optional) – The label name where the predicted properties to be saved.

  • xyz_derivative_property_to_predict (str, optional) – The label name where the predicted XYZ derivatives to be saved.

  • hessian_to_predict (str, optional) – The label name where the predicted Hessians to be saved.

class mlatom.models.ani(*args, **kwargs)[source]

Create an ANI (ANAKIN-ME: Accurate NeurAl networK engINe for Molecular Energie) model object.

Interfaces to TorchANI.

Parameters:
  • model_file (str, optional) – The filename that the model to be saved with or loaded from.

  • device (str, optional) – Indicate which device the calculation will be run on. i.e. ‘cpu’ for CPU, ‘cuda’ for Nvidia GPUs. When not speficied, it will try to use CUDA if there exists valid CUDA_VISIBLE_DEVICES in the environ of system.

  • hyperparameters (Dict[str, Any] | model_cls.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • verbose (int, optional) – 0 for silence, 1 for verbosity.

NN_initialize(a: float = 1.0) → None[source]

Reset the network parameters using torch.nn.init.kaiming_normal_().

Parameters:

a (float) – Check torch.nn.init.kaiming_normal_().

classmethod check_ignorable(given)[source]

Refuse any keyword this model is not entitled to ignore.

fix_layers(layers_to_fix: List[List[int]] | List[int])[source]

Fix specific layers to be non-trainable for each element.

Parameters:

layers_to_fix (List) –

Should be:

  • A list of integers. Layers indicated by the integers will be fixed.

  • A list of lists of integers. Each sub-list defines the layers to be fixed for each species, in the order of self.species_order.

Examples

import mlatom as ml
>>> ani = ml.ani(model_file='ANI.pt')
model loade from ANI.pt
>>> ani.model # show model summary
Sequential(
(0): AEVComputer()
(1): ANIModel(
    (C): Sequential(
    (0): Linear(in_features=240, out_features=160, bias=True)
    (1): CELU(alpha=0.1)
    (2): Linear(in_features=160, out_features=128, bias=True)
    (3): CELU(alpha=0.1)
    (4): Linear(in_features=128, out_features=96, bias=True)
    (5): CELU(alpha=0.1)
    (6): Linear(in_features=96, out_features=1, bias=True)
    )
    (H): Sequential(
    (0): Linear(in_features=240, out_features=160, bias=True)
    (1): CELU(alpha=0.1)
    (2): Linear(in_features=160, out_features=128, bias=True)
    (3): CELU(alpha=0.1)
    (4): Linear(in_features=128, out_features=96, bias=True)
    (5): CELU(alpha=0.1)
    (6): Linear(in_features=96, out_features=1, bias=True)
    )
    (O): Sequential(
    (0): Linear(in_features=240, out_features=160, bias=True)
    (1): CELU(alpha=0.1)
    (2): Linear(in_features=160, out_features=128, bias=True)
    (3): CELU(alpha=0.1)
    (4): Linear(in_features=128, out_features=96, bias=True)
    (5): CELU(alpha=0.1)
    (6): Linear(in_features=96, out_features=1, bias=True)
    )
  )
)
>>> parameters = dict(a.model.named_parameters())
>>> {key: parameters[key].requires_grad for key in parameters} # show the trainability of parameters
{'1.C.0.weight': True, '1.C.0.bias': True, '1.C.2.weight': True, '1.C.2.bias': True, '1.C.4.weight': True, '1.C.4.bias': True, '1.C.6.weight': True, '1.C.6.bias': True, '1.H.0.weight': True, '1.H.0.bias': True, '1.H.2.weight': True, '1.H.2.bias': True, '1.H.4.weight': True, '1.H.4.bias': True, '1.H.6.weight': True, '1.H.6.bias': True, '1.O.0.weight': True, '1.O.0.bias': True, '1.O.2.weight': True, '1.O.2.bias': True, '1.O.4.weight': True, '1.O.4.bias': True, '1.O.6.weight': True, '1.O.6.bias': True}
>>> ani.fix_layers([[0, 2], [0], [4]]) # fix layer 0 and 2 for C, layer 0 for H, and layer 4 for O
>>> {key: parameters[key].requires_grad for key in parameters}
{'1.C.0.weight': False, '1.C.0.bias': False, '1.C.2.weight': False, '1.C.2.bias': False, '1.C.4.weight': True, '1.C.4.bias': True, '1.C.6.weight': True, '1.C.6.bias': True, '1.H.0.weight': False, '1.H.0.bias': False, '1.H.2.weight': True, '1.H.2.bias': True, '1.H.4.weight': True, '1.H.4.bias': True, '1.H.6.weight': True, '1.H.6.bias': True, '1.O.0.weight': True, '1.O.0.bias': True, '1.O.2.weight': True, '1.O.2.bias': True, '1.O.4.weight': False, '1.O.4.bias': False, '1.O.6.weight': True, '1.O.6.bias': True}
>>> ani.fix_layers([[0, 2, 4]]) # fix layer 0, 2, and 4 for all networks
{'1.C.0.weight': False, '1.C.0.bias': False, '1.C.2.weight': False, '1.C.2.bias': False, '1.C.4.weight': False, '1.C.4.bias': False, '1.C.6.weight': True, '1.C.6.bias': True, '1.H.0.weight': False, '1.H.0.bias': False, '1.H.2.weight': False, '1.H.2.bias': False, '1.H.4.weight': False, '1.H.4.bias': False, '1.H.6.weight': True, '1.H.6.bias': True, '1.O.0.weight': False, '1.O.0.bias': False, '1.O.2.weight': False, '1.O.2.bias': False, '1.O.4.weight': False, '1.O.4.bias': False, '1.O.6.weight': True, '1.O.6.bias': True}
ignorable_prediction_kwargs = ('calculate_dipole_derivatives', 'calculate_polarizability_derivatives', 'nstates', 'current_state')

Prediction keywords a composite model passes down to every child and that an ANI network has no answer for: properties it cannot compute, and the electronic-state selection it does not have. predict() accepts and ignores exactly these.

Whether an ANI network can produce a dipole derivative is a fact about ANI, not about whoever is asking, so it is recorded here once. It used to be stripped by a wrapper subclass per parent - three of them, each with a slightly different list, so the same question had three answers.

Anything not named here still raises: the point of naming them is that a misspelled or genuinely wrong keyword stays loud rather than being swallowed along with the rest.

load(model_file: str = '', species_order: List[str] | None = None, AEV_parameters: Dict | None = None, self_energies: List[float] | None = None, reset_parameters: bool = False, method: str = '') → None[source]

Load a saved ANI model from file (.pt format).

Parameters:
  • model_file (str) – The filename of the model to be loaded.

  • species_order (List[str], optional) – Manually provide species order if it’s not present in the saved model.

  • AEV_parameters (Dict, optional) – Manually provide AEV parameters if it’s not present in the saved model.

  • self_energies (List[float], optional) – Manually provide self energies if it’s not present in the saved model.

  • reset_parameters (bool) – Reset network paramters in the loaded model.

  • method (str) – Load an ANI method, see also ani.load_ani_model().

load_ani_model(method: str, **hyperparameters) → None[source]

Load an ANI model.

Arguments:

method(str): Can be 'ANI-1x', 'ANI-1ccx', 'ANI-2x', or 'ANI-1xnr'.

predict(molecular_database: molecular_database = None, molecule: molecule = None, calculate_energy: bool = False, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, property_to_predict: str | None = 'estimated_y', xyz_derivative_property_to_predict: str | None = None, hessian_to_predict: str | None = None, batch_size: int = 65536, **not_for_a_network) → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • property_to_predict (str, optional) – The label name where the predicted properties to be saved.

  • xyz_derivative_property_to_predict (str, optional) – The label name where the predicted XYZ derivatives to be saved.

  • hessian_to_predict (str, optional) – The label name where the predicted Hessians to be saved.

  • batch_size (int, optional) – The batch size for batch-predictions.

reset()[source]

Resets model (deletes the ML model file from the hard disk).

save(model_file: str = '') → None[source]

Save the model to file (.pt format).

Parameters:

model_file (str, optional) – The filename that the model to be saved into. If not provided, a randomly generated string will be used.

train(molecular_database: molecular_database, property_to_learn: str = 'energy', xyz_derivative_property_to_learn: str = None, validation_molecular_database: molecular_database | str | None = 'sample_from_molecular_database', hyperparameters: Dict[str, Any] | hyperparameters = {}, spliting_ratio: float = 0.8, save_model: bool = True, file_to_save_model: str = None, check_point: str = None, reset_optim_state: bool = False, use_last_model: bool = False, reset_aev: bool = False, reset_parameters: bool = False, reset_network: bool = False, reset_optimizer: bool = False, reset_energy_shifter=False, save_every_epoch: bool = False, save_epoch_interval: int = None, energy_weighting_function: Callable = None, energy_weighting_function_kwargs: dict = {}, verbose: int = None) → None[source]

Train the model with molecular database provided.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – The database of molecules for training.

  • property_to_learn (str, optional) – The label of property to be learned in model training.

  • xyz_derivative_property_to_learn (str, optional) – The label of XYZ derivative property to be learned.

  • validation_molecular_database (mlatom.data.molecular_database | str, optional) – Explicitly defines the database for validation, or use 'sample_from_molecular_database' to make it sampled from the training set.

  • hyperparameters (Dict[str, Any] | mlatom.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • spliting_ratio (float, optional) – The ratio sub-training dataset in the whole training dataset.

  • save_model (bool, optional) – Whether save the model to disk during training process. Note that the model might be saved many times during training.

  • reset_optim_state (bool, optional) – Whether to reset the state of optimizer.

  • use_last_model (bool, optional) – Whether to keep the self.model as it is in the last training epoch. If False, the best model will be loaded to memory at the end of training.

  • reset_parameters (bool, optional) – Whether to reset the model’s parameters before training.

  • reset_network (bool, optional) – Whether to re-construct the network before training.

  • reset_optimizer (bool, optional) – Whether to re-define the optimizer before training .

  • save_every_epoch (bool, optional) – Whether to save model in every epoch, valid when save_model is True.

  • save_epoch_interval (int, optional) – The interval to save each epoch.

  • energy_weighting_function (Callable, optional) – A weighting function \(\mathit{W}(\mathbf{E_ref})\) that assign weights to training points based on their reference energies.

  • energy_weighting_function_kwargs (dict, optional) – Extra weighting function arguments in a dictionary.

mlatom.models.dpmd(**kwargs)[source]

Returns a DPMD model object (see mlatom.interfaces.dpmd_interface.dpmd).

mlatom.models.gap(**kwargs)[source]

Returns a GAP model object (see mlatom.interfaces.gap_interface.gap).

mlatom.models.physnet(**kwargs)[source]

Returns a PhysNet model object (see mlatom.interfaces.physnet_interface.physnet).

mlatom.models.sgdml(**kwargs)[source]

Returns an sGDML model object (see mlatom.interfaces.sgdml_interface.sgdml).

mlatom.models.mace(**kwargs)[source]

Returns an MACE model object (see mlatom.interfaces.mace_interface.mace).

model_tree_node

!---------------------------------------------------------------------------!
! models: Module with models                                                !
! Implementations by: Pavlo O. Dral, Fuchun Ge, Yi-Fan Hou, Yuxinxin Chen,  !
!                     Peikun Zheng                                          !
!---------------------------------------------------------------------------!
class mlatom.models.model_tree_node(name=None, parent=None, children=None, operator=None, model=None)[source]

Create a model tree node.

Parameters:
  • name (str) – The name assign to the object.

  • parent – The parent of the model node.

  • children – The children of this model tree node.

  • operator – Specify the operation to be made when making predictions.

dump(filename=None, format='json')[source]

Dump the object to a file.

predict(**kwargs)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

Interfaces

TorchANI

!---------------------------------------------------------------------------!
! Interface_TorchANI: Interface between TorchANI and MLatom                 !
! Implementations by: Fuchun Ge and Max Pinheiro Jr                         !
! Defines the MS-ANI model                                                  !
! Implemented by: Mikolaj Martyka                                           !
!---------------------------------------------------------------------------!
mlatom.interfaces.torchani_interface._angular_terms_without_prod(Rca: float, ShfZ, EtaA, Zeta, ShfA, vectors12)[source]

torchani.aev.angular_terms (TorchANI 2.2) with every torch.prod over the two neighbours of an angle written as the product of the two factors. The forward values are the same bit for bit; the second derivatives are not.

torch.prod’s backward is grad * prod / input whenever no element of its input is exactly zero, and the Hessian differentiates that formula once more: for the product of two bond-vector components a * b, the second derivative with respect to a, exactly zero, comes out as the difference of two terms of size b / a, each rounded. A component that is tiny but not zero - two atoms with (almost) the same coordinate, as at symmetric geometries - left an error of order eps * b / a in the analytic Hessian: 0.02-0.05 Ha/A^2 in float32 at the beads of an NH3 instanton with components of 1e-7 A, still 2e-7 in float64 with a component of 1e-9 A and growing as it shrinks. One exact zero anywhere in the input switches torch.prod to its zero-safe backward, and a rotation removes the small component, so the fault disappeared after a rotation and at most geometries.

mlatom.interfaces.torchani_interface.fix_torchani_angular_terms()[source]

Make TorchANI’s AEV computer use _angular_terms_without_prod(), so that analytic Hessians of every TorchANI-based model (ANI, MS-ANI, AIQM1, ANI-1ccx, …) are right at geometries with nearly equal coordinates. torchani.aev.compute_aev looks angular_terms up in its module when it runs, so replacing the module attribute is enough for eager (not TorchScript-compiled) AEV computers. Done once; a TorchANI whose angular_terms has another signature is left alone (the test API.MLP.ANI.hessian_small_component then fails).

mlatom.interfaces.torchani_interface.scheduler_is_better(scheduler, value, best)[source]

Has the validation loss improved? PyTorch renamed ReduceLROnPlateau.is_better to _is_better, and training crashes on the newer one with AttributeError at the end of the first epoch. Both names work here.

class mlatom.interfaces.torchani_interface.ani(*args, **kwargs)[source]

Create an ANI (ANAKIN-ME: Accurate NeurAl networK engINe for Molecular Energie) model object.

Interfaces to TorchANI.

Parameters:
  • model_file (str, optional) – The filename that the model to be saved with or loaded from.

  • device (str, optional) – Indicate which device the calculation will be run on. i.e. ‘cpu’ for CPU, ‘cuda’ for Nvidia GPUs. When not speficied, it will try to use CUDA if there exists valid CUDA_VISIBLE_DEVICES in the environ of system.

  • hyperparameters (Dict[str, Any] | model_cls.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • verbose (int, optional) – 0 for silence, 1 for verbosity.

ignorable_prediction_kwargs = ('calculate_dipole_derivatives', 'calculate_polarizability_derivatives', 'nstates', 'current_state')

Prediction keywords a composite model passes down to every child and that an ANI network has no answer for: properties it cannot compute, and the electronic-state selection it does not have. predict() accepts and ignores exactly these.

Whether an ANI network can produce a dipole derivative is a fact about ANI, not about whoever is asking, so it is recorded here once. It used to be stripped by a wrapper subclass per parent - three of them, each with a slightly different list, so the same question had three answers.

Anything not named here still raises: the point of naming them is that a misspelled or genuinely wrong keyword stays loud rather than being swallowed along with the rest.

classmethod check_ignorable(given)[source]

Refuse any keyword this model is not entitled to ignore.

reset()[source]

Resets model (deletes the ML model file from the hard disk).

save(model_file: str = '') → None[source]

Save the model to file (.pt format).

Parameters:

model_file (str, optional) – The filename that the model to be saved into. If not provided, a randomly generated string will be used.

load(model_file: str = '', species_order: List[str] | None = None, AEV_parameters: Dict | None = None, self_energies: List[float] | None = None, reset_parameters: bool = False, method: str = '') → None[source]

Load a saved ANI model from file (.pt format).

Parameters:
  • model_file (str) – The filename of the model to be loaded.

  • species_order (List[str], optional) – Manually provide species order if it’s not present in the saved model.

  • AEV_parameters (Dict, optional) – Manually provide AEV parameters if it’s not present in the saved model.

  • self_energies (List[float], optional) – Manually provide self energies if it’s not present in the saved model.

  • reset_parameters (bool) – Reset network paramters in the loaded model.

  • method (str) – Load an ANI method, see also ani.load_ani_model().

load_ani_model(method: str, **hyperparameters) → None[source]

Load an ANI model.

Arguments:

method(str): Can be 'ANI-1x', 'ANI-1ccx', 'ANI-2x', or 'ANI-1xnr'.

train(molecular_database: molecular_database, property_to_learn: str = 'energy', xyz_derivative_property_to_learn: str = None, validation_molecular_database: molecular_database | str | None = 'sample_from_molecular_database', hyperparameters: Dict[str, Any] | hyperparameters = {}, spliting_ratio: float = 0.8, save_model: bool = True, file_to_save_model: str = None, check_point: str = None, reset_optim_state: bool = False, use_last_model: bool = False, reset_aev: bool = False, reset_parameters: bool = False, reset_network: bool = False, reset_optimizer: bool = False, reset_energy_shifter=False, save_every_epoch: bool = False, save_epoch_interval: int = None, energy_weighting_function: Callable = None, energy_weighting_function_kwargs: dict = {}, verbose: int = None) → None[source]

Train the model with molecular database provided.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – The database of molecules for training.

  • property_to_learn (str, optional) – The label of property to be learned in model training.

  • xyz_derivative_property_to_learn (str, optional) – The label of XYZ derivative property to be learned.

  • validation_molecular_database (mlatom.data.molecular_database | str, optional) – Explicitly defines the database for validation, or use 'sample_from_molecular_database' to make it sampled from the training set.

  • hyperparameters (Dict[str, Any] | mlatom.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • spliting_ratio (float, optional) – The ratio sub-training dataset in the whole training dataset.

  • save_model (bool, optional) – Whether save the model to disk during training process. Note that the model might be saved many times during training.

  • reset_optim_state (bool, optional) – Whether to reset the state of optimizer.

  • use_last_model (bool, optional) – Whether to keep the self.model as it is in the last training epoch. If False, the best model will be loaded to memory at the end of training.

  • reset_parameters (bool, optional) – Whether to reset the model’s parameters before training.

  • reset_network (bool, optional) – Whether to re-construct the network before training.

  • reset_optimizer (bool, optional) – Whether to re-define the optimizer before training .

  • save_every_epoch (bool, optional) – Whether to save model in every epoch, valid when save_model is True.

  • save_epoch_interval (int, optional) – The interval to save each epoch.

  • energy_weighting_function (Callable, optional) – A weighting function \(\mathit{W}(\mathbf{E_ref})\) that assign weights to training points based on their reference energies.

  • energy_weighting_function_kwargs (dict, optional) – Extra weighting function arguments in a dictionary.

predict(molecular_database: molecular_database = None, molecule: molecule = None, calculate_energy: bool = False, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, property_to_predict: str | None = 'estimated_y', xyz_derivative_property_to_predict: str | None = None, hessian_to_predict: str | None = None, batch_size: int = 65536, **not_for_a_network) → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • property_to_predict (str, optional) – The label name where the predicted properties to be saved.

  • xyz_derivative_property_to_predict (str, optional) – The label name where the predicted XYZ derivatives to be saved.

  • hessian_to_predict (str, optional) – The label name where the predicted Hessians to be saved.

  • batch_size (int, optional) – The batch size for batch-predictions.

NN_initialize(a: float = 1.0) → None[source]

Reset the network parameters using torch.nn.init.kaiming_normal_().

Parameters:

a (float) –

Check torch.nn.init.kaiming_normal_().

fix_layers(layers_to_fix: List[List[int]] | List[int])[source]

Fix specific layers to be non-trainable for each element.

Parameters:

layers_to_fix (List) –

Should be:

  • A list of integers. Layers indicated by the integers will be fixed.

  • A list of lists of integers. Each sub-list defines the layers to be fixed for each species, in the order of self.species_order.

Examples

import mlatom as ml
>>> ani = ml.ani(model_file='ANI.pt')
model loade from ANI.pt
>>> ani.model # show model summary
Sequential(
(0): AEVComputer()
(1): ANIModel(
    (C): Sequential(
    (0): Linear(in_features=240, out_features=160, bias=True)
    (1): CELU(alpha=0.1)
    (2): Linear(in_features=160, out_features=128, bias=True)
    (3): CELU(alpha=0.1)
    (4): Linear(in_features=128, out_features=96, bias=True)
    (5): CELU(alpha=0.1)
    (6): Linear(in_features=96, out_features=1, bias=True)
    )
    (H): Sequential(
    (0): Linear(in_features=240, out_features=160, bias=True)
    (1): CELU(alpha=0.1)
    (2): Linear(in_features=160, out_features=128, bias=True)
    (3): CELU(alpha=0.1)
    (4): Linear(in_features=128, out_features=96, bias=True)
    (5): CELU(alpha=0.1)
    (6): Linear(in_features=96, out_features=1, bias=True)
    )
    (O): Sequential(
    (0): Linear(in_features=240, out_features=160, bias=True)
    (1): CELU(alpha=0.1)
    (2): Linear(in_features=160, out_features=128, bias=True)
    (3): CELU(alpha=0.1)
    (4): Linear(in_features=128, out_features=96, bias=True)
    (5): CELU(alpha=0.1)
    (6): Linear(in_features=96, out_features=1, bias=True)
    )
  )
)
>>> parameters = dict(a.model.named_parameters())
>>> {key: parameters[key].requires_grad for key in parameters} # show the trainability of parameters
{'1.C.0.weight': True, '1.C.0.bias': True, '1.C.2.weight': True, '1.C.2.bias': True, '1.C.4.weight': True, '1.C.4.bias': True, '1.C.6.weight': True, '1.C.6.bias': True, '1.H.0.weight': True, '1.H.0.bias': True, '1.H.2.weight': True, '1.H.2.bias': True, '1.H.4.weight': True, '1.H.4.bias': True, '1.H.6.weight': True, '1.H.6.bias': True, '1.O.0.weight': True, '1.O.0.bias': True, '1.O.2.weight': True, '1.O.2.bias': True, '1.O.4.weight': True, '1.O.4.bias': True, '1.O.6.weight': True, '1.O.6.bias': True}
>>> ani.fix_layers([[0, 2], [0], [4]]) # fix layer 0 and 2 for C, layer 0 for H, and layer 4 for O
>>> {key: parameters[key].requires_grad for key in parameters}
{'1.C.0.weight': False, '1.C.0.bias': False, '1.C.2.weight': False, '1.C.2.bias': False, '1.C.4.weight': True, '1.C.4.bias': True, '1.C.6.weight': True, '1.C.6.bias': True, '1.H.0.weight': False, '1.H.0.bias': False, '1.H.2.weight': True, '1.H.2.bias': True, '1.H.4.weight': True, '1.H.4.bias': True, '1.H.6.weight': True, '1.H.6.bias': True, '1.O.0.weight': True, '1.O.0.bias': True, '1.O.2.weight': True, '1.O.2.bias': True, '1.O.4.weight': False, '1.O.4.bias': False, '1.O.6.weight': True, '1.O.6.bias': True}
>>> ani.fix_layers([[0, 2, 4]]) # fix layer 0, 2, and 4 for all networks
{'1.C.0.weight': False, '1.C.0.bias': False, '1.C.2.weight': False, '1.C.2.bias': False, '1.C.4.weight': False, '1.C.4.bias': False, '1.C.6.weight': True, '1.C.6.bias': True, '1.H.0.weight': False, '1.H.0.bias': False, '1.H.2.weight': False, '1.H.2.bias': False, '1.H.4.weight': False, '1.H.4.bias': False, '1.H.6.weight': True, '1.H.6.bias': True, '1.O.0.weight': False, '1.O.0.bias': False, '1.O.2.weight': False, '1.O.2.bias': False, '1.O.4.weight': False, '1.O.4.bias': False, '1.O.6.weight': True, '1.O.6.bias': True}
class mlatom.interfaces.torchani_interface.msani(*args, **kwargs)[source]

Create an `MS-ANI’, an extension of the ANI NN model for multi-state learning. First described in <10.26434/chemrxiv-2024-dtc1w>.

Interfaces to TorchANI.

Parameters:
  • model_file (str, optional) – The filename that the model to be saved with or loaded from.

  • device (str, optional) – Indicate which device the calculation will be run on. i.e. ‘cpu’ for CPU, ‘cuda’ for Nvidia GPUs. When not speficied, it will try to use CUDA if there exists valid CUDA_VISIBLE_DEVICES in the environ of system.

  • hyperparameters (Dict[str, Any] | mlatom.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • verbose (int, optional) – 0 for silence, 1 for verbosity.

reset()[source]

Resets model (deletes the ML model file from the hard disk).

save(model_file: str = '') → None[source]

Save the model to file (.pt format).

Parameters:

model_file (str, optional) – The filename that the model to be saved into. If not provided, a randomly generated string will be used.

load(model_file: str = '', species_order: List[str] | None = None, AEV_parameters: Dict | None = None, self_energies: List[float] | None = None, reset_parameters: bool = False, method: str = '') → None[source]

Load a saved ANI model from file (.pt format).

Parameters:
  • model_file (str) – The filename of the model to be loaded.

  • species_order (List[str], optional) – Manually provide species order if it’s not present in the saved model.

  • AEV_parameters (Dict, optional) – Manually provide AEV parameters if it’s not present in the saved model.

  • self_energies (List[float], optional) – Manually provide self energies if it’s not present in the saved model.

  • reset_parameters (bool) – Reset network paramters in the loaded model.

  • method (str) – Load an ANI method, see also ani.load_ani_model().

load_ani_model(method: str, **hyperparameters) → None[source]

Load an ANI model.

Arguments:

method(str): Can be 'ANI-1x', 'ANI-1ccx', or 'ANI-2x'.

train(molecular_database: molecular_database, property_to_learn: str = 'energy', xyz_derivative_property_to_learn: str = None, validation_molecular_database: molecular_database | str | None = 'sample_from_molecular_database', hyperparameters: Dict[str, Any] | hyperparameters = {}, spliting_ratio: float = 0.8, save_model: bool = True, check_point: str = None, reset_optim_state: bool = False, use_last_model: bool = False, reset_parameters: bool = False, reset_network: bool = False, reset_optimizer: bool = False, reset_energy_shifter: bool = False, save_every_epoch: bool = False, energy_weighting_function: Callable = None, energy_weighting_function_kwargs: dict = {}) → None[source]

Train the model with molecular database provided.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – The database of molecules for training.

  • property_to_learn (str, optional) – The label of property to be learned in model training.

  • xyz_derivative_property_to_learn (str, optional) – The label of XYZ derivative property to be learned.

  • validation_molecular_database (mlatom.data.molecular_database | str, optional) – Explicitly defines the database for validation, or use 'sample_from_molecular_database' to make it sampled from the training set.

  • hyperparameters (Dict[str, Any] | mlatom.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • spliting_ratio (float, optional) – The ratio sub-training dataset in the whole training dataset.

  • save_model (bool, optional) – Whether save the model to disk during training process. Note that the model might be saved many times during training.

  • reset_optim_state (bool, optional) – Whether to reset the state of optimizer.

  • use_last_model (bool, optional) – Whether to keep the self.model as it is in the last training epoch. If False, the best model will be loaded to memory at the end of training.

  • reset_parameters (bool, optional) – Whether to reset the model’s parameters before training.

  • reset_network (bool, optional) – Whether to re-construct the network before training.

  • reset_optimizer (bool, optional) – Whether to re-define the optimizer before training .

  • save_every_epoch (bool, optional) – Whether to save model in every epoch, valid when save_model is True.

  • energy_weighting_function (Callable[Array-like], optional) – A weighting function \(\mathit{W}(\mathbf{E_ref})\) that assign weights to training points based on their reference energies.

predict(molecular_database: molecular_database = None, molecule: molecule = None, nstates=1, current_state=0, calculate_energy: bool = False, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, property_to_predict: str | None = 'estimated_y', xyz_derivative_property_to_predict: str | None = None, hessian_to_predict: str | None = None, batch_size: int = 65536) → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • property_to_predict (str, optional) – The label name where the predicted properties to be saved.

  • xyz_derivative_property_to_predict (str, optional) – The label name where the predicted XYZ derivatives to be saved.

  • hessian_to_predict (str, optional) – The label name where the predicted Hessians to be saved.

  • batch_size (int, optional) – The batch size for batch-predictions.

NN_initialize(a: float = 1.0) → None[source]

Reset the network parameters using torch.nn.init.kaiming_normal_().

Parameters:

a (float) –

Check torch.nn.init.kaiming_normal_().

fix_layers(layers_to_fix: List[List[int]] | List[int])[source]

Fix specific layers to be non-trainable for each element.

Parameters:

layers_to_fix (List) –

Should be:

  • A list of integers. Layers indicate by the integers will be fixed

  • A list of lists of integers. Each sub-list defines the layers to be fixed for each species, in the order of self.species_order.

class mlatom.interfaces.torchani_interface.ani_child(*args, **kwargs)[source]
predict(molecular_database: molecular_database = None, molecule: molecule = None, calculate_energy: bool = False, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, batch_size: int = 65536) → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

class mlatom.interfaces.torchani_interface.ani_methods(*args, **kwargs)[source]

Create a model object with one of the ANI methods

Parameters:
  • method (str) – A string that specifies the method. Available choices: 'ANI-1x', 'ANI-1ccx', 'ANI-2x', 'ANI-1ccx-gelu' or 'ANI-1x-gelu'.

  • device (str, optional) – Indicate which device the calculation will be run on, i.e. ‘cpu’ for CPU, ‘cuda’ for Nvidia GPUs. When not speficied, it will try to use CUDA if there exists valid CUDA_VISIBLE_DEVICES in the environ of system.

predict(molecular_database: molecular_database = None, molecule: molecule = None, calculate_energy: bool = True, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, batch_size: int = 65536) → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • batch_size (int, optional) – The batch size for batch-predictions.

_iter_ani_leaves(node=None)[source]

Iterate over the ani leaf models inside the model tree.

Yields tuples (node, cv_index) where node is a model_tree_node whose .model is an ani instance, and cv_index is parsed from the node name.

static _resolve_model_paths(model_dict, base_dir)[source]

Recursively convert relative model_file paths in a dumped model_tree_node dictionary into absolute paths.

static _make_paths_relative(model_dict, base_dir)[source]

Recursively convert absolute model_file paths in a dumped model_tree_node dictionary into paths relative to base_dir.

save(model_file: str = '') → None[source]

Save the transfer-learned ani_methods model to a directory.

The directory will contain:

  • tree.json: model metadata and tree structure

  • cv*.pt: TorchANI weights for each ensemble member

Parameters:

model_file (str) – Path to the directory to create. If empty, a default name based on the method is used.

classmethod load(model_file: str, device=None)[source]

Load a transfer-learned ani_methods model from a directory or from the tree.json file inside it.

Parameters:
  • model_file (str) – Path to the saved directory, or to the tree.json file inside it.

  • device (str, optional) – Device to load the model on. If not given, the device recorded at save time is used.

classmethod from_dict(model_dict, device=None, base_dir=None)[source]

Reconstruct an ani_methods instance from a dictionary produced by save().

Parameters:
  • model_dict (dict) – Dictionary produced by save().

  • device (str, optional) – Device to load the model on.

  • base_dir (str, optional) – Directory used to resolve relative model_file paths in the model tree.

DeepMD-kit

!---------------------------------------------------------------------------!
! Interface_DeePMDkit: Interface between DeePMD-kit and MLatom              !
! Implementations by: Fuchun Ge                                             !
!---------------------------------------------------------------------------!
class mlatom.interfaces.dpmd_interface.dpmd(model_file=None, hyperparameters={}, verbose=1)[source]

Create an DeepPot-SE model object.

Interfaces to DeepMD-kit.

Parameters:
  • model_file (str, optional) – The filename that the model to be saved with or loaded from.

  • hyperparameters (Dict[str, Any] | mlatom.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • verbose (int, optional) – 0 for silence, 1 for verbosity.

train(molecular_database: molecular_database, property_to_learn: str = 'energy', xyz_derivative_property_to_learn: str = None, validation_molecular_database: molecular_database | str | None = 'sample_from_molecular_database', hyperparameters: Dict[str, Any] | hyperparameters = {}, spliting_ratio=0.8, stdout=None, stderr=None, json_input=None, dirname=None)[source]

Train the model with molecular database provided.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – The database of molecules for training.

  • property_to_learn (str, optional) – The label of property to be learned in model training.

  • xyz_derivative_property_to_learn (str, optional) – The label of XYZ derivative property to be learned.

predict(molecular_database: data.molecular_database = None, molecule: data.molecule = None, calculate_energy: bool = False, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, property_to_predict: str | None = 'estimated_y', xyz_derivative_property_to_predict: str | None = None, hessian_to_predict: str | None = None) → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • property_to_predict (str, optional) – The label name where the predicted properties to be saved.

  • xyz_derivative_property_to_predict (str, optional) – The label name where the predicted XYZ derivatives to be saved.

  • hessian_to_predict (str, optional) – The label name where the predicted Hessians to be saved.

GAP/QUIP

!---------------------------------------------------------------------------!
! Interface_GAP: Interface between GAP and MLatom                           !
! Implementations by: Fuchun Ge                                             !
!---------------------------------------------------------------------------!
class mlatom.interfaces.gap_interface.gap(model_file=None, hyperparameters={}, verbose=0)[source]

Create an GAP-SOAP model object.

Interfaces to QUIP.

Parameters:
  • model_file (str, optional) – The filename that the model to be saved with or loaded from.

  • hyperparameters (Dict[str, Any] | mlatom.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • verbose (int, optional) – 0 for silence, 1 for verbosity.

train(molecular_database: molecular_database, property_to_learn: str = 'energy', xyz_derivative_property_to_learn: str = None, hyperparameters: Dict[str, Any] | hyperparameters = {}, stdout=None, stderr=None)[source]

Train the model with molecular database provided.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – The database of molecules for training.

  • property_to_learn (str, optional) – The label of property to be learned in model training.

  • xyz_derivative_property_to_learn (str, optional) – The label of XYZ derivative property to be learned.

predict(molecular_database: data.molecular_database = None, molecule: data.molecule = None, calculate_energy: bool = False, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, property_to_predict: str | None = 'estimated_y', xyz_derivative_property_to_predict: str | None = None, hessian_to_predict: str | None = None) → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • property_to_predict (str, optional) – The label name where the predicted properties to be saved.

  • xyz_derivative_property_to_predict (str, optional) – The label name where the predicted XYZ derivatives to be saved.

  • hessian_to_predict (str, optional) – The label name where the predicted Hessians to be saved.

PhysNet

!---------------------------------------------------------------------------!
! Interface_PhysNet: Interface between PhysNet and MLatom                   !
! Implementations by: Fuchun Ge and Max Pinheiro Jr                         !
!---------------------------------------------------------------------------!
class mlatom.interfaces.physnet_interface.physnet(model_file=None, hyperparameters={}, verbose=1)[source]

Create an PhysNet model object.

Interfaces to PhysNet program.

Parameters:
  • model_file (str, optional) – The filename that the model to be saved with or loaded from.

  • hyperparameters (Dict[str, Any] | mlatom.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • verbose (int, optional) – 0 for silence, 1 for verbosity.

reset()[source]

Resets model (deletes the ML model file from the hard disk).

train(molecular_database: molecular_database, property_to_learn: str = 'energy', xyz_derivative_property_to_learn: str = None, validation_molecular_database: molecular_database | str | None = 'sample_from_molecular_database', hyperparameters: Dict[str, Any] | hyperparameters = {}, spliting_ratio=0.8, save_model=True, log=True, check_point=False, use_last_model=False, summary_interval=1, validation_interval=1, save_interval=1, record_run_metadata=0) → None[source]

Train the model with molecular database provided.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – The database of molecules for training.

  • property_to_learn (str, optional) – The label of property to be learned in model training.

  • xyz_derivative_property_to_learn (str, optional) – The label of XYZ derivative property to be learned.

predict(molecular_database: data.molecular_database = None, molecule: data.molecule = None, calculate_energy: bool = False, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, property_to_predict: str | None = 'estimated_y', xyz_derivative_property_to_predict: str | None = None, hessian_to_predict: str | None = None) → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • property_to_predict (str, optional) – The label name where the predicted properties to be saved.

  • xyz_derivative_property_to_predict (str, optional) – The label name where the predicted XYZ derivatives to be saved.

  • hessian_to_predict (str, optional) – The label name where the predicted Hessians to be saved.

MACE

!---------------------------------------------------------------------------!
! Interface_MACE: Interface between MACE and MLatom                         !
! Implementations by: Fuchun Ge, Yuxinxin Chen, Matheus O. Bispo            !
!---------------------------------------------------------------------------!
mlatom.interfaces.mace_interface.get_dataset_from_molDB(train_db: molecular_database, valid_db: molecular_database, valid_fraction: float = 0.1, config_type_weights: Dict = {'Default': 1.0}, energy_key: str = '', gradients_key: str = '') → Tuple[mace.tools.scripts_utils.SubsetCollection, Dict[int, float] | None][source]

Load training and test dataset from molecular database

class mlatom.interfaces.mace_interface.mace(model_file: str = None, device: str = None, hyperparameters: Dict[str, Any] | hyperparameters = {}, verbose=True)[source]

Create an MACE model object.

Interfaces to MACE program.

Parameters:
  • model_file (str, optional) – The filename that the model to be saved with or loaded from.

  • device (str, optional) – Indicate which device the calculation will be run on. i.e. ‘cpu’ for CPU, ‘cuda’ for Nvidia GPUs. When not speficied, it will try to use CUDA if there exists valid CUDA_VISIBLE_DEVICES in the environ of system.

  • hyperparameters (Dict[str, Any] | mlatom.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • verbose (int, optional) – 0 for silence, 1 for verbosity.

train(molecular_database: data.molecular_database, property_to_learn: str = 'energy', xyz_derivative_property_to_learn: str = None, validation_molecular_database: data.molecular_database | str | None = 'sample_from_molecular_database', spliting_ratio: float = 0.8, hyperparameters: Dict[str, Any] | hyperparameters = {}) → None[source]

Train the model with molecular database provided.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – The database of molecules for training.

  • property_to_learn (str, optional) – The label of property to be learned in model training.

  • xyz_derivative_property_to_learn (str, optional) – The label of XYZ derivative property to be learned.

  • validation_molecular_database (mlatom.data.molecular_database | str, optional) – Explicitly defines the database for validation, or use 'sample_from_molecular_database' to make it sampled from the training set.

  • hyperparameters (Dict[str, Any] | mlatom.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

predict(molecular_database: data.molecular_database = None, molecule: data.molecule = None, calculate_energy: bool = False, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, property_to_predict: str | None = 'estimated_y', xyz_derivative_property_to_predict: str | None = None, hessian_to_predict: str | None = None, batch_size: int = 8) → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • property_to_predict (str, optional) – The label name where the predicted properties to be saved.

  • xyz_derivative_property_to_predict (str, optional) – The label name where the predicted XYZ derivatives to be saved.

  • hessian_to_predict (str, optional) – The label name where the predicted Hessians to be saved.

  • batch_size (int, optional) – The batch size for batch-predictions.

class mlatom.interfaces.mace_interface.CheckpointHandler_modified(*args: Any, **kwargs: Any)[source]

sGDML

!---------------------------------------------------------------------------!
! Interface_sGDML: Interface between sGDML and MLatom                       !
! Implementations by: Fuchun Ge                                             !
!---------------------------------------------------------------------------!
class mlatom.interfaces.sgdml_interface.sgdml(model_file=None, hyperparameters={}, verbose=1, max_memory=None, max_processes=None, use_torch=False, lazy_training=False)[source]

Create an sGDML model object.

Interfaces to sGDML.

Parameters:
  • model_file (str, optional) – The filename that the model to be saved with or loaded from.

  • hyperparameters (Dict[str, Any] | mlatom.hyperparameters, optional) – Updates the hyperparameters of the model with provided.

  • verbose (int, optional) – 0 for silence, 1 for verbosity.

Hyperparameters:

Please refer to the sgdml manual

no_E: mlatom.hyperparameter(value=False) gdml: mlatom.hyperparameter(value=False) perms: mlatom.hyperparameter(value=None) sigma: mlatom.hyperparameter(value=None) E_cstr: mlatom.hyperparameter(value=False) cprsn: mlatom.hyperparameter(value=False)

reset()[source]

Resets model (deletes the ML model file from the hard disk).

train(molecular_database: molecular_database, property_to_learn: str = 'energy', xyz_derivative_property_to_learn: str = None, validation_molecular_database: molecular_database | str | None = None, hyperparameters: Dict[str, Any] | hyperparameters = {}, spliting_ratio=0.8, save_model=True, task_dir=None, overwrite=False, max_memory=None, max_processes=None, use_torch=None, lazy_training=None)[source]

Train the model with molecular database provided.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – The database of molecules for training.

  • property_to_learn (str, optional) – The label of property to be learned in model training.

  • xyz_derivative_property_to_learn (str, optional) – The label of XYZ derivative property to be learned.

predict(molecular_database: data.molecular_database = None, molecule: data.molecule = None, calculate_energy: bool = False, calculate_energy_gradients: bool = False, calculate_hessian: bool = False, property_to_predict: str | None = 'estimated_y', xyz_derivative_property_to_predict: str | None = None, hessian_to_predict: str | None = None, batch_size: int = 65536) → None[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • property_to_predict (str, optional) – The label name where the predicted properties to be saved.

  • xyz_derivative_property_to_predict (str, optional) – The label name where the predicted XYZ derivatives to be saved.

  • hessian_to_predict (str, optional) – The label name where the predicted Hessians to be saved.

  • batch_size (int, optional) – The batch size for batch-predictions.

Gaussian

!---------------------------------------------------------------------------!
! gaussian_interface: interface to the Gaussian program                     !
! Implementations by: Pavlo O. Dral, Peikun Zheng, Yi-Fan Hou               !
!---------------------------------------------------------------------------!
class mlatom.interfaces.gaussian_interface.gaussian_methods(method='B3LYP/6-31G*', gaussian_keywords=None, additional_input='', chkfilename=None, memory=None, nthreads=None, save_files_in_current_directory=False, working_directory=None)[source]

Gaussian interface

Parameters:
  • method (str) – Method to use

  • chkfilename (bool, str) – request to create chk file defined by %chk in Gaussian (default: None). If True, assignes default filename.

  • memory (str) – equivalent to %mem in Gaussian input file, e.g., memory=16Gb (default: None).

  • nthreads (int) – equivalent to %proc in Gaussian input file.

  • gaussian_keywords (str) – any gaussian keywords in addition to method.

  • additional_input (str) – any additional input to be appended to the Gaussian input file.

  • save_files_in_current_directory (bool) – whether to keep input and output files, default 'False'.

  • working_directory (str) – path to the directory where the program output files and other tempory files are saved, default 'None'.

Note

The format of method should be the same as that in Gaussian, e.g., 'B3LYP/6-31G*'

predict(molecular_database=None, molecule=None, nstates=1, current_state=0, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, calculate_dipole_derivatives=False, gaussian_keywords='')[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • nstates (int) – number of electronic structure states (default: 1, ground state)

  • current_state (int) – default is the ground state (for nstates=1) or the first excited state (nstates > 1)

  • gaussian_keywords (str) – any gaussian keywords.

mlatom.interfaces.gaussian_interface._parse_gaussian_log_orbitals(chunk)[source]

Parse “Alpha/Beta occ./virt. eigenvalues” lines from a Gaussian log chunk and return (mo_energies, mo_occupations) as ndarrays.

Format (printed by default — no pop=full needed):

Alpha  occ. eigenvalues --  -10.18773 -10.18747 -10.18746 ...
Alpha  occ. eigenvalues --  -10.18665  -0.84634  -0.73985 ...
...
Alpha virt. eigenvalues --    0.00361   0.00364   0.09074 ...
...
Beta  occ. eigenvalues --   ...        (only present for UKS)
Beta virt. eigenvalues --   ...

Gaussian prints multiple sets (initial guess + each SCF iteration); we take the LAST set (the converged one) — each new “Alpha occ” block reset the accumulators.

Schema (matches pyscf shape per dral 2026-06-02):

RKS/RHF: 1D ndarray; occupations 2.0 / 0.0 UKS/UHF: ndarray shape (2, N) [alpha, beta]; occupations 1.0 / 0.0

Returns (None, None) if no Alpha-occ block is found.

mlatom.interfaces.gaussian_interface.parse_gaussian_output(filename=None, molecule=None)[source]

Parse Gaussian output file and return a molecule obj :param filename: Name of Gaussian output file (e.g. benzene.log or benzene.out) :return: molecule if molecule is not provided

Orca

!---------------------------------------------------------------------------!
! orca: interface to the ORCA program                                       !
! Implementations by: Yuxinxin Chen                                         !
! NEVPT2 and TD-DFT implemented by Mikołaj Martyka, Li Wang and Xinyu Tong  !
!---------------------------------------------------------------------------!
class mlatom.interfaces.orca_interface.orca_methods(method='wb97x/6-31G*', save_files_in_current_directory: bool = True, working_directory: str = None, nthreads: int = 1, maxcore: int = 1000, solvent: str = None, solvation_model: str = 'SMD', additional_keywords: list = None, input_file: str = '', output_keywords: list = None, **kwargs)[source]

ORCA interface

Parameters:
  • method (str) – Method specification. Use 'B3LYP/6-31G*' for ground state DFT, 'TD-wb97x-d3bj/def2-SVP' for TD-DFT, 'TDA-wb97x-d3bj/def2-SVP' for TDA, 'qd-nevpt2/cc-pVDZ' for QD-NEVPT2, or 'CCSD(T)*/CBS' for composite method.

  • save_files_in_current_directory (bool) – Keep input/output files, default True

  • working_directory (str) – Directory for output files, default None

  • nthreads (int) – Number of parallel processes (%pal nprocs)

  • maxcore (int) – Memory per core in MB (%maxcore)

  • solvent (str) – Solvent name for implicit solvation

  • solvation_model (str) – 'SMD' or 'CPCM', default 'SMD'

  • additional_keywords (list) – Extra keywords for ORCA input line

  • setup (Example)

  • code-block: (..) –

    python: td_dft = ml.models.methods(method=’TD-B3LYP/def2-SVP’, program=’orca’,

    working_directory=’./orca_tddft’, nthreads=1, maxcore=1000, )

    qd_nevpt2 = ml.models.methods(method=’QD-NEVPT2/def2-SVP’, program=’orca’,

    nthreads=1, maxcore=1000, working_directory=’./orca_NEVPT2’, )

predict(molecular_database: molecular_database = None, molecule: molecule = None, calculate_energy: bool = True, calculate_energy_gradients=False, calculate_hessian: bool = False, nstates: int = 1, current_state: int = 0, active_space: tuple = None, casscf_kwargs: dict = None)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

Run ORCA calculation.

Parameters:
  • molecular_database – collection of molecules stored in ml.data.molecular_database object to make predictions for.

  • molecule – molecule to predict for.

  • calculate_energy – bool, whether to update the energy of the molecule.

  • calculate_energy_gradients – bool or list of bool. If list, e.g. [False, True, False] requests gradient for S1 only. Only one state gradient can be requested at a time.

  • current_state – 0-indexed state (0 = S0, 1 = S1, etc.), for which the energy and gradient will be used.

  • active_space – tuple (nel, norb) for CASSCF/QD-NEVPT2, e.g. (6, 6)

  • casscf_kwargs – dict of additional CASSCF keywords (maxiter, actorbs, etc.)

  • nstates – number of electronic states to compute

  • calculate_hessian – whether to calculate hessian matrix.

Example usage: .. code-block:: python

td_dft.predict(

molecule=mol, nstates=2, current_state=0, calculate_energy=True, calculate_energy_gradients=True,

)

qd_nevpt2.predict( molecule=mol, nstates=2, current_state=1, active_space = (2,2) )

_parse_output_keywords(molecule)[source]

Parse custom keywords from property.txt file.

Used by CCSD(T)*/CBS and similar methods to extract specific values.

_setup_working_directory() → str[source]

Setup and return the working directory path.

_generate_input(molecule)[source]

Generate ORCA input file.

_run_orca(workdir: str)[source]

Execute ORCA calculation.

_parse_qd_nevpt2_output(molecule)[source]

Parse QD-NEVPT2 output from .out file.

_extract_qd_energies_from_out(lines: list) → tuple[source]

Extract QD-NEVPT2 and CASSCF energies from .out file.

Parses “QD-NEVPT2 Results” block: ROOT = 0 … Zero Order Energy : E0 = -230.38678408697643 (CASSCF) Total Energy (E0+dE) : E = -231.11493305070951 (QD-NEVPT2)

Returns:

(pt2_energies dict, casscf_energies dict)

Return type:

tuple

_parse_qd_absorption_spectrum(molecule, out_file: str)[source]

Parse oscillator strengths from QD-NEVPT2 absorption spectrum.

_parse_tddft_output(molecule)[source]

Parse TD-DFT/ground-state DFT output.

_parse_tddft_spectrum(out_file: str) → tuple[source]

Parse TD-DFT absorption spectrum from output file.

_parse_gradients(molecule)[source]

Parse energy gradients from .engrad file.

_parse_hessian(molecule)[source]

Parse Hessian matrix from .hess file.

_parse_frequencies(molecule, hess_lines: list)[source]

Parse vibrational frequencies from .hess file content.

class mlatom.interfaces.orca_interface.ccsdtstarcbs(**kwargs)[source]
predict(molecular_database, **kwargs)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

mlatom.interfaces.orca_interface.parse_orca_output(filename, molecule=None)[source]

Parse ORCA output file and return/populate a molecule object.

Automatically detects calculation type (QD-NEVPT2, TD-DFT, or ground state DFT). Also looks for .engrad and .hess files in the same directory.

Parameters:
  • filename – Path to ORCA output file (.out)

  • molecule – Optional molecule object to update. If None, returns new molecule.

Returns:

molecule object if molecule is None, otherwise updates provided molecule

Example

>>> mol = parse_orca_output('calculation.out')
>>> print(mol.energy)
>>> print(mol.electronic_states[1].energy)  # S1 energy
mlatom.interfaces.orca_interface._parse_orca_orbitals(lines)[source]

Parse ORCA’s “ORBITAL ENERGIES” block from output lines.

Closed-shell (RKS) format:

ORBITAL ENERGIES
----------------

  NO   OCC          E(Eh)            E(eV)
   0   2.0000      -9.959394      -271.0089
   1   2.0000      -9.914123      -269.7770
   ...
   N   0.0000       0.296508         8.0684

Open-shell (UKS) format inserts “SPIN UP ORBITALS” / “SPIN DOWN ORBITALS” markers between the two blocks.

ORCA can print multiple sets across an output (geom-opt steps, excited-state passes, etc.); we take the LAST converged set.

Returns (None, None) if the block isn’t found.

mlatom.interfaces.orca_interface._parse_geometry_from_content(mol, lines)[source]

Parse molecular geometry from ORCA output.

mlatom.interfaces.orca_interface._parse_qd_nevpt2_from_content(mol, lines, current_state)[source]

Parse QD-NEVPT2 energies from output content.

mlatom.interfaces.orca_interface._parse_tddft_from_content(mol, lines, current_state, orca_version=None)[source]

Parse TD-DFT energies from output content.

mlatom.interfaces.orca_interface._parse_ground_state_from_content(mol, lines)[source]

Parse ground state DFT/HF energy from output content.

mlatom.interfaces.orca_interface._parse_tddft_spectrum_from_lines(lines, orca_version=None)[source]

Parse TD-DFT absorption spectrum from output lines.

mlatom.interfaces.orca_interface._parse_absorption_spectrum(mol, lines, is_qd_nevpt2=False)[source]

Parse oscillator strengths from absorption spectrum.

mlatom.interfaces.orca_interface._parse_gradients_from_file(mol, engrad_file, current_state=0)[source]

Parse gradients from .engrad file and add to electronic state.

mlatom.interfaces.orca_interface._parse_hessian_from_file(mol, hess_file)[source]

Parse Hessian matrix from .hess file.

mlatom.interfaces.orca_interface._parse_frequencies_from_lines(mol, hess_lines)[source]

Parse vibrational frequencies from .hess file content.

DFT-D4

!---------------------------------------------------------------------------!
! dftd4: interface to the dftd4 program                                     !
! Implementations by: Pavlo O. Dral & Peikun Zheng                          !
!---------------------------------------------------------------------------!
class mlatom.interfaces.dftd4_interface.dftd4_methods(method: str = 'D4', functional: str = 'wb97x', damping_function_params=None, save_files_in_current_directory: bool = False, working_directory: str = None, nthreads: int = 1)[source]

DFT-D4 interface

Parameters:
  • functional (str) – functional to use

  • save_files_in_current_directory (bool) – whether to keep input and output files, default 'True'

  • working_directory (str) – path to the directory where the program output files and other tempory files are saved, default 'None'

Note

The default DFT-D4 implementation provides a shared memory parallelisation for CPUs. They offer openMP parallelisation, which is not implemented here currently. For more discussion, please refer to https://github.com/dftd4/dftd4/issues/20.

predict(molecular_database=None, molecule=None, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, nstates=1, **kwargs)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

PySCF

!---------------------------------------------------------------------------!
! Interface_PySCF: interface to the PySCF program                           !
! Implementations by: Yuxinxin Chen                                         !
!---------------------------------------------------------------------------!
mlatom.interfaces.pyscf_interface._attach_mo_data(molecule, pyscf_method)[source]

Attach mol.mo_energies + mol.mo_occupations from a pyscf method.

Shape and values mirror pyscf_method.mo_energy / .mo_occ verbatim:

RHF / RKS: ndarray shape (N,); mo_occ ∈ {0.0, 2.0} UHF / UKS: ndarray shape (2, N); mo_occ ∈ {0.0, 1.0}

— index 0 = alpha, 1 = beta

Units: mo_energies in Hartree (consistent with mol.energy).

Stored as np.ndarray on the molecule. mlatom.data serializes ndarray → JSON list at dump time and reconstructs ndarray on load (class_instance_to_dict + dict_to_molecule_class_instance); consumers see ndarrays in both directions, no list-vs-array drift.

Best-effort: silently skip if the pyscf object doesn’t expose the attrs (e.g. some post-HF wrappers). Never raise.

mlatom.interfaces.pyscf_interface._dump_minimal_chkfile(molecule, pyscf_method)[source]

Persist the minimal PySCF wavefunction artifact for orbital cubes (D3b).

Writes a MINIMAL pyscf chkfile (mo_coeff + mo_energy + mo_occ + Mole pickle only — no DIIS history, no density-matrix history, no 2e integrals) to <cwd>/pyscf_mo.chk. Bounded by mo_coeff size: ~50 KB for water/6-31G*, ~600 KB for caffeine, ~10 MB for 50-atom def2-TZVP. The full default chkfile (which can reach 50-200 MB on large systems) is NOT written.

This is the source-of-truth for the post-D3b cube_from_calc MCP tool’s PySCF branch: read pyscf_mo.chk → reconstruct Mole + mo_coeff via pyscf.lib.chkfile.load_mol + load → pyscf.tools.cubegen.orbital(mol, outfile, mo_coeff[:, idx]).

Path convention: written to the calc’s CWD (typically the engine’s scr/ dir). For OPT, this is overwritten on every step’s SCF; the converged-geometry SCF wins because it fires last. For SP/FREQ at a single geometry it’s the only write. The bundle-promotion layer in the calling layer is responsible for moving pyscf_mo.chk to <bundle>/scr/<stem>.pyscf.chk post-success if the bundle layout policy requires; this helper only ensures the artifact exists on disk in the calc’s working directory.

AO ordering convention: PySCF’s native ordering (spherical or cartesian depending on mol.cart). The chkfile carries the Mole pickle so the reader rebuilds the Mole with the exact same basis + ordering — no cross-engine convention drift.

Best-effort: silently skip if the pyscf object doesn’t have a usable .mol (e.g. post-HF wrappers around an SCF object) or if chkfile.dump raises. Never let MO persistence kill the calc.

mlatom.interfaces.pyscf_interface._split_unrestricted(method)[source]

Split a leading unrestricted “U” off a method name.

The “U” prefix is the standard notation for a spin-unrestricted reference, e.g. UB3LYP, UPBE0, UHF. Returns (method_without_U, unrestricted), keeping any leading TD-/TDA- excited-state prefix in place: “UB3LYP” -> (“B3LYP”, True), “TD-UB3LYP” -> (“TD-B3LYP”, True), “B3LYP” -> (“B3LYP”, False).

class mlatom.interfaces.pyscf_interface.OMP_pyscf[source]
class mlatom.interfaces.pyscf_interface.pyscf_methods(method='B3LYP/6-31g', nthreads=None, density_fitting=False)[source]

PySCF interface

Parameters:
  • method (str) – Method to use

  • nthreads (int) – Set the number of OMP threads

Note

Methods supported:

Energy: HF, MP2, DFT, CISD, FCI, CCSD/CCSD(T), TD-DFT/TD-HF

Gradients: HF, MP2, DFT, CISD, CCSD, RCCSD(T), TD-DFT/TD-HF

Hessian: HF, DFT

predict(molecule=None, molecular_database=None, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, nstates=1, current_state=1, **kwargs)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

  • **kwargs – # needs to be documented.

Sparrow

!---------------------------------------------------------------------------!
! sparrow: interface to the Sparrow program                                 !
! Implementations by: Pavlo O. Dral & Peikun Zheng                          !
!---------------------------------------------------------------------------!
class mlatom.interfaces.sparrow_interface.sparrow_methods(method='ODM2*', read_keywords_from_file='', save_files_in_current_directory=False, working_directory=None, numerical_gradients_kwargs=None, numerical_hessian_kwargs=None)[source]

Sparrow interface

Parameters:
  • method (str) – method to use

  • read_keywords_from_file (str) – keywords used in Sparrow

  • save_files_in_current_directory (bool) – whether to keep input and output files, default 'False'

  • working_directory (str) – path to the directory where the program output files and other tempory files are saved, default 'None'

  • numerical_gradients_kwargs (dict) – Options for numerical gradients. Defaults to central differences with displacement 0.001 Angstrom, chosen for Sparrow’s energy-file precision.

  • numerical_hessian_kwargs (dict) – Options for numerical Hessians. Defaults to central energy differences with displacement 0.01 Angstrom. Override either dictionary for a different output precision or convergence regime.

Note

Methods supported:

Energy: DFTB0, DFTB2, DFTB3 MNDO, MNDO/d, AM1, PM3, PM6, RM1, OM2, OM3, ODM2*, ODM3* AIQM1

Gradients: DFTB0, DFTB2, DFTB3 MNDO, MNDO/d, AM1, PM3, PM6, RM1

predict(molecular_database=None, molecule=None, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, **kwargs)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

xTB

!---------------------------------------------------------------------------!
! xtb: interface to the xtb program                                         !
! Implementations by: Pavlo O. Dral                                         !
!---------------------------------------------------------------------------!
mlatom.interfaces.xtb_interface._parse_xtb_orbitals(stdout_lines)[source]

Parse xtb’s “Orbital Energies and Occupations” table from stdout.

Returns (mo_energies, mo_occupations) as float64 ndarrays in Hartree (matching pyscf_method.mo_energy / .mo_occ shape), or (None, None) if the block isn’t found or parsing fails.

Closed-shell xtb output (one block, 1D arrays):

* Orbital Energies and Occupations

     #    Occupation            Energy/Eh            Energy/eV
  -------------------------------------------------------------
     1        2.0000           -0.6810697             -18.5329
     ...
     4        2.0000           -0.4473129             -12.1720 (HOMO)
     5                          0.0833760               2.2688 (LUMO)
     ...
  -------------------------------------------------------------

Virtual rows have a BLANK occupation column (not 0.0000). The optional (HOMO) / (LUMO) markers must be stripped before column-counting.

Open-shell xtb output (alpha+beta blocks, 2D shape (2, N)) is handled by repeating the parse and stacking — best-effort; if only one block is found we return 1D.

mlatom.interfaces.xtb_interface._persist_xtb_molden(tmpdirname, namespace='molecule0')[source]

Promote xtb’s molden output to a stable filename in cwd (D3b).

xtb, when invoked with --molden, writes <namespace>.molden.input inside its working directory (the run-job tmpdirname). For the post-D3b cube_from_calc MCP tool’s xtb branch (which also covers AIQM1/2/3 + uaiqm, all GFN2-xTB-baselined), we promote that file to <cwd>/xtb_molden.input so a caller can find it at a fixed path deterministically — mirrors the pyscf branch’s pyscf_mo.chk in cwd convention.

Validation: returns silently if the source molden is missing, empty, or lacks the canonical [GTO] + [MO] markers (the xtb molden is unreliable on non-converged SCFs — workflow blocker mitigation; we only ever fire this helper AFTER xtb returned cleanly, but the file-shape check is a cheap belt-and-suspenders).

For OPT trajectories, the helper fires from each predict() inside the optimizer; the LAST step’s molden overwrites earlier ones at the cwd target — naturally giving us the converged-geometry MO artifact, mirroring the pyscf chkfile convention.

class mlatom.interfaces.xtb_interface.xtb_methods(method: str = 'GFN2-xTB', read_keywords_from_file: str = '', nthreads: int = 1, solvent: str = None, stack_size: str = None, etemp=None, acc=None, unlimited_stack_size: bool = False, restart: bool = False, save_files_in_current_directory: bool = False, working_directory: str = None)[source]

xTB interface

Parameters:
  • method (str) – xTB methods

  • read_keywords_from_file (str) – the file that contain keywords used in xTB

  • nthreads (int) – number of threads used in xTB. It will be passed to OMP_NUM_THREADS.

  • solvent (str) – the implicit solvent model.

  • stack_size (str) – the stack size to be use for each threads, e.g., ‘100m’, ‘1G’. It will be passed to OMP_STACKSIZE

  • etemp (float) – the electronic temperature. By default is 300K

  • acc (float) – the threshold for SCF convergence. By default is 1 (1e-5)

  • unlimited_stack_size (bool) – equal to ulimit -c unlimited in bash

  • restart (bool) – whether to reuse previous calculation files. By default turned off

  • save_files_in_current_directory (bool) – whether to save files in current directory. By default False

  • working_directory (str) – the path to save calculation files. By default is None.

Note

GFN2-xTB and GFN2-xTB* (remove D4 from GFN2-xTB) are available.

Examples:

from mlatom import xtb_methods

# read molecule from xyz file
mol = ml.data.molecule()
mol.read_from_xyz_file('sp.xyz')

# initialize xtb methods
model = xtb_methods(method='GFN2-xTB)

# calculate energy, gradients and hessian
model.predict(molecule=mol,
            calculate_energy_gradients=True,
            calculate_hessian=True)
print(mol.energy)
predict(molecular_database=None, molecule=None, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, calculate_dipole_derivatives=False, calculate_polarizability_derivatives=False)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

MNDO

!---------------------------------------------------------------------------!
! mndo: interface to the MNDO program                                       !
! Implementations by: Pavlo O. Dral, Peikun Zheng, and Lina Zhang,          !
! Mikołaj Martyka                                                           !
!---------------------------------------------------------------------------!
class mlatom.interfaces.mndo_interface.mndo_methods(method='ODM2*', read_keywords_from_file='', save_files_in_current_directory=True, working_directory=None, param_file=None)[source]

MNDO interface

Parameters:
  • method (str) – method used in MNDO

  • read_keywords_from_file (str) – keywords used in MNDO

  • save_files_in_current_directory (bool) – whether to keep input and output files, default 'True'

  • working_directory (str) – path to the directory where the program output files and other tempory files are saved, default 'None'

predict(molecular_database=None, molecule=None, nstates=1, current_state=0, calculate_energy=True, calculate_energy_gradients=False, calculate_hessian=False, calculate_dipole_derivatives=False, calculate_nacv=False, read_density_matrix=False)[source]

Make predictions for molecular geometries with the model.

Parameters:
  • molecular_database (mlatom.data.molecular_database, optional) – A database contains the molecules whose properties need to be predicted by the model.

  • molecule (mlatom.models.molecule, optional) – A molecule object whose property needs to be predicted by the model.

  • calculate_energy (bool, optional) – Use the model to calculate energy.

  • calculate_energy_gradients (bool, optional) – Use the model to calculate energy gradients.

  • calculate_hessian (bool, optional) – Use the model to calculate energy hessian.

mlatom.interfaces.mndo_interface.parse_mndo_output(filename=None, molecule=None)[source]

Parse MNDO output file and return a molecule obj :param filename: Name of Gaussian output file (e.g. benzene.log or benzene.out) :return: molecule if molecule is not provided

Simulations

!---------------------------------------------------------------------------!
! simulations: Module for simulations                                       !
! Implementations by: Pavlo O. Dral, Fuchun Ge, Yi-Fan Hou, Yuxinxin Chen   !
!---------------------------------------------------------------------------!

Geomopt, freq, DMC

class mlatom.simulations.optimize_geometry(model=None, model_predict_kwargs: dict = {}, initial_molecule: molecule | None = None, molecule: molecule | None = None, ts: bool | None = False, reactants: molecule | None = None, products: molecule | None = None, program: str | None = None, program_kwargs: dict | None = None, optimization_algorithm: str | None = None, maximum_number_of_steps: int | None = None, convergence_criterion_for_forces: float | None = None, working_directory: str | None = None, print_properties: bool | None = None, dump_trajectory_interval: int | None = None, filename: str | None = None, format: str | None = 'json', constraints: dict | None = None)[source]

Geometry optimization.

Parameters:
  • model (mlatom.models.model or mlatom.models.methods) – any model or method which provides energies and forces.

  • model_predict_kwargs (dict) – additional kwargs of model prediction.

  • initial_molecule (mlatom.data.molecule) – the molecule object to optimize.

  • molecule (mlatom.data.molecule,optional) – the molecule object to optimize.

  • ts (bool, optional) – whether to do transition state search. Currently only be done with program=Gaussian, ASE and geometric.

  • reactants (mlatom.data.molecule,optional) – reactant of the transition state, used in qst2 and qst3 only.

  • products (mlatom.data.molecule,optional) – products of the transition state, used in qst2 and qst3 only.

  • program (str, optional) – the engine used in geometry optimization. Currently supports Gaussian, ASE, scipy and PySCF.

  • program_kwargs (dict, optional) – additional kwargs of program

  • optimization_algorithm (str, optional) – the optimization algorithm. Default value: None.

  • maximum_number_of_steps (int, optional) – the maximum number of steps for ASE, SciPy and geometric. Default value: 200.

  • convergence_criterion_for_forces (float, optional) – forces convergence criterion in ASE. Default value: 0.02 eV/Angstroms.

  • working_directory (str, optional) – working directory. Default value: ‘.’, i.e., current directory.

  • constraints (dict, optional) – constraints for geometry optimization. Currently only available with program=ASE and program=geometric. For program=ASE, constraints follows the same conventions as in ASE: constraints={'bonds':[[target,[index0,index1]], ...],'angles':[[target,[index0,index1,index2]], ...],'dihedrals':[[target,[index0,index1,index2,index3]], ...]} (check FixInternals class in ASE for more information). For program=geometric, the name of constraint file should be provided and please refer to constrained optimization for the format of the constraint file.

  • print_properties (None or str, optional) – properties to print. Default: None. Possible ‘all’.

  • dump_trajectory_interval (int, optional) – dump trajectory at every time step (1). Set to None to disable dumping (default).

  • filename (str, optional) – the file that saves the dumped trajectory.

  • format (str, optional) – format in which the dumped trajectory is saved.

Examples:

# Initialize molecule
mol = ml.data.molecule()
mol.read_from_xyz_file(filename='ethanol.xyz')
# Initialize methods
aiqm1 = ml.models.methods(method='AIQM1', qm_program='MNDO')
# Run geometry optimization
geomopt = ml.simulations.optimize_geometry(model = aiqm1, initial_molecule=mol, program = 'ASE')
# Get the optimized geometry, energy, and gradient
optmol = geomopt.optimized_molecule
geo = optmol.get_xyz_coordinates()
energy = optmol.energy
gradient = optmol.get_energy_gradients()
class mlatom.simulations.freq(model=None, model_predict_kwargs: dict = None, molecule: molecule = None, program: str | None = None, ir: bool | None = False, raman: bool | None = False, normal_mode_normalization: str | None = 'mass deweighted normalized', anharmonic: bool | None = False, anharmonic_kwargs: dict | None = {}, working_directory: str | None = None, program_kwargs: dict | None = None)[source]

Frequence analysis.

Parameters:
  • model (mlatom.models.model or mlatom.models.methods) – any model or method which provides energies and forces and Hessian.

  • model_predict_kwargs (dict, optional) – additional kwargs of model prediction.

  • molecule (mlatom.data.molecule) – the molecule object with necessary information.

  • model_predict_kwargs – Additional keywords used for prediction.

  • program (str, optional) – the engine used in frequence analysis through modified TorchANI (if Gaussian not found or any other string is given), pyscf or Gaussian interfaces.

  • normal_mode_normalization (str, optional) – normal modes output scheme. It should be one of: mass weighted normalized, mass deweighted unnormalized, and mass deweighted normalized. Default: mass deweighted normalized.

  • anharmonic (bool) – whether to do anharmonic frequence calculation.

  • working_directory (str, optional) – working directory. Default value: ‘.’, i.e., current directory.

  • ir (bool) – whether to calculate infrared (IR) intensities

  • raman (bool) – whether to calculate Raman intensities

Examples:

# Initialize molecule
mol = ml.data.molecule()
mol.read_from_xyz_file(filename='ethanol.xyz')
# Initialize methods
aiqm1 = ml.models.methods(method='AIQM1', qm_program='MNDO')
# Run frequence analysis
ml.simulations.freq(model=aiqm1, molecule=mol, program='ASE')
# Get frequencies
frequencies = mol.frequencies
class mlatom.simulations.thermochemistry(model=None, molecule=None, program=None, ir=False, raman=False, normal_mode_normalization='mass deweighted normalized', working_directory: str | None = None)[source]

Thermochemical properties calculation.

Parameters:
  • model (mlatom.models.model or mlatom.models.methods) – any model or method which provides energies and forces and Hessian.

  • molecule (mlatom.data.molecule) – the molecule object with necessary information.

  • program (str) – the engine used in thermochemical properties calculation. Currently support Gaussian and ASE.

  • normal_mode_normalization (str, optional) – normal modes output scheme. It should be one of: mass weighted normalized, mass deweighted unnormalized, and mass deweighted unnormalized (default).

# Initialize molecule
mol = ml.data.molecule()
mol.read_from_xyz_file(filename='ethanol.xyz')
# Initialize methods
aiqm1 = ml.models.methods(method='AIQM1', qm_program='MNDO')
# Run thermochemical properties calculation
ml.simulations.thermochemistry(model=aiqm1, molecule=mol, program='ASE')
# Get ZPE and heat of formation
ZPE = mol.ZPE
Hof = mol.DeltaHf298

The thermochemical properties available in molecule object after the calculation:

  • ZPE: Zero-point energy

  • DeltaE2U: Thermal correction to Energy (only available in Gaussian)

  • DeltaE2H: Thermal correction to Enthalpy (only available in Gaussian)

  • DeltaE2G: Thermal correction to Gibbs free energy (only available in Gaussian)

  • U0: Internal energy at 0K

  • H0: Enthalpy at 0K

  • U: Internal energy (only available in Gaussian)

  • H: Enthalpy

  • G: Gibbs free energy

  • S: Entropy (only available in Gaussian)

  • atomization_energy_0K

  • ZPE_exclusive_atomization_energy_0K

  • DeltaHf298: Heat of formation at 298 K

class mlatom.simulations.dmc(model: model, initial_molecule: molecule = None, initial_molecular_database: molecular_database = None, energy_scaling_factor: float = 1.0)[source]

Run diffusion Monte Carlo simulation for molecule(s) using PyVibDMC.

Parameters:
  • model (mlatom.models.model) – The potential energy surfaces model. The unit should be Hartree, otherwise a correct energy_scaling_factor need to be set.

  • initial_molecule (mlatom.data.molecule) – The initial geometry for the walkers. Usually a energy minimum geometry should be provided. By default every coordinate will be scaled by 1.01 to make it slightly distorted.

  • energy_scaling_factor (float, optional) – A factor that will be multiplied to the model’s energy pridiction.

run(run_dir: str = 'DMC', weighting: str = 'discrete', number_of_walkers: int = 5000, number_of_timesteps: int = 10000, equilibration_steps: int = 500, dump_trajectory_interval: int = 500, dump_wavefunction_interval: int = 1000, descendant_weighting_steps: int = 300, time_step: float = 0.024188843265857, initialize: bool = False)[source]

Run the DMC simulation.

Parameters:
  • run_dir (str) – The folder for the output files.

  • weighting (str) – 'discrete' or 'continuous'. 'continuous' keeps the ensemble size constant.

  • number_of_walkers (int) – The number of geometries exploring the potential surface.

  • number_of_timesteps (int) – The number of steps the simulation will go.

  • equilibration_steps (int) – The number of steps for equilibration.

  • dump_trajectory_interval (int) – The interval for dumping walkers’ trajectories.

  • dump_wavefunction_interval (int) – The interval for collecting wave function.

  • descendant_weighting_steps (int) – The number of time steps for descendant weighting per wave function.

  • time_step (float) – The length of each time step in fs.

load(filename)[source]

Load previous simulation results from a HDF5 file.

get_zpe(start_step=1000) → float[source]

Return calculated zero-point energy in Hartree.

Parameters:

start_step (int) – The starting step for averaging the energies.

mlatom.simulations.numerical_gradients(molecule, model, displacement=None, model_kwargs={}, return_molecular_database=False, nthreads=None, algorithm='central')[source]

Calculate numerical gradients with central or forward differences.

Central: g_i = (E(x + h e_i) - E(x - h e_i)) / (2 h), costing 2 N energies. Forward: g_i = (E(x + h e_i) - E(x)) / h, costing N + 1 energies. h is displacement in Angstrom, E is the energy at Cartesian coordinates x, and e_i is the unit vector along Cartesian coordinate i. N = 3 * number of atoms. Single-point calculations are run in parallel.

Parameters:
  • molecule (mlatom.data.molecule) – the molecule object.

  • model (mlatom.models.model or mlatom.models.methods) – any model or method which provides energies (takes molecule as an argument).

  • displacement (float, optional) – displacement of nuclear coordinates in Angstrom (default: None selects 0.001 for central, 1e-5 for forward).

  • model_kwargs (dict, optional) – kwargs to be passed to model (except for molecule).

  • return_molecular_database (bool, optional) – whether to return the mlatom.data.molecular_database with the displaced geometries and energies (default: False).

  • nthreads (int, optional) – number of threads (default: None, using all threads it can find).

  • algorithm (str, optional) – ‘central’ (default) or ‘forward’.

mlatom.simulations.numerical_hessian(molecule, model, displacement=None, displacement4grads=1e-05, model_kwargs={}, nthreads=None, algorithm=None)[source]

Calculate numerical Hessians from energies or model-returned gradients.

By default, use central finite differences of energies. Select gradient_central explicitly, or use semi_numerical_hessian, to differentiate model-returned gradients. No gradient capability detection is performed.

h is displacement in Angstrom, x is the Cartesian coordinate vector, e_i is its i-th unit vector, E(x) is energy and g(x) is the gradient. H_ij denotes a Hessian element and N = 3 * number of atoms.

energy_central uses H_ii = (E_i+ - 2 E + E_i-) / h^2 and H_ij = (E_i+j+ + E_i-j- - E_i+ - E_i- - E_j+ - E_j- + 2 E) / (2 h^2), costing N^2 + N + 1 energies. Single-point calculations are run in parallel.

gradient_central uses H_:i = (g(x + h e_i) - g(x - h e_i)) / (2 h), followed by H = (H + H^T) / 2. It costs 2 N gradient predictions, made in one batched molecular-database prediction. Numerical model gradients can hide further energy evaluations, e.g. 4 N^2 for nested central differences.

The deprecated forward algorithm preserves the original forward differences of forward numerical gradients, costing (N + 1)^2 energies. Its outer displacement defaults to 5.29167e-4 Angstrom; displacement4grads controls the inner step.

Parameters:
  • molecule (mlatom.data.molecule) – the molecule object.

  • model (mlatom.models.model or mlatom.models.methods) – any model or method which provides energies or energy gradients.

  • displacement (float, optional) – displacement of nuclear coordinates in Angstrom (default: None selects 0.01 for energy differences, 0.001 for gradient differences, 5.29167e-4 for deprecated forward differences).

  • displacement4grads (float, optional) – inner numerical-gradient displacement for the deprecated forward algorithm (default: 1e-5 Angstrom).

  • model_kwargs (dict, optional) – kwargs to be passed to model. For gradient_central, gradient-request defaults are merged with supplied settings; contradictory requests are rejected.

  • nthreads (int, optional) – parallel energy predictions (default: None, using all threads it can find). Batched gradient predictions use the model’s own parallelism.

  • algorithm (str, optional) – None (energy differences, default), ‘energy_central’, ‘gradient_central’ or deprecated ‘forward’.

mlatom.simulations.semi_numerical_hessian(molecule, model, displacement=0.001, model_kwargs=None, nthreads=None)[source]

Calculate a Hessian by central differences of model-returned gradients.

This thin wrapper selects gradient_central in numerical_hessian. It costs 2 N gradient predictions in one batched prediction, or 4 N^2 energies if every gradient internally uses central energy differences. The model need not declare whether its gradients are analytic or numerical.

Parameters:
  • molecule (mlatom.data.molecule) – the molecule object.

  • model (mlatom.models.model or mlatom.models.methods) – any model or method which provides energy gradients.

  • displacement (float, optional) – displacement of nuclear coordinates in Angstrom (default: 1e-3).

  • model_kwargs (dict, optional) – kwargs used to request gradients (default: calculate_energy_gradients=True and calculate_hessian=False).

  • nthreads (int, optional) – retained for API consistency; batched predictions use the model’s own parallelism.

IRC

class mlatom.irc.irc(model=None, molecule: molecule = None, model_predict_kwargs: dict = None, trajdb: molecular_database = None, ftrajdb: molecular_database = None, btrajdb: molecular_database = None, program: str | None = None, program_kwargs: dict | None = None, forward: bool | None = None, backward: bool | None = None, working_directory: str | None = None, overwrite: bool | None = None, plot: bool | None = None, plot_filename: str | None = None, dump: bool | None = None, dump_filename: str | None = None, dump_format: List[str] | None = None, verbose: bool | None = None)[source]

Provide the intrinsic reaction coordinates (IRC) given transition state. IRC is the mimial energy path under the mass weighted coordinates. Path direction of each point on IRC follows the negative energy gradients (by definition).

Parameters:
  • model (mlatom.models.model or mlatom.models.methods) – Model or method to provide energy and energy derivatives for IRC generation.

  • molecule (data.molecule) – The transtion state molecule to start with.

  • model_predict_kwargs (dict, optional) – Additional keywords used for prediction.

  • program (str, optional) – The program to be used for generating IRC. Available options are geometric, gaussian, pysisyphus and mlatom. Default: None, i.e., the built-in implementation in mlatom

  • program_kwargs (dict, optional) – Control the behavior of the program. Default: None

  • forward (bool, optional) – Whether to generate forward trajectory. Default: None

  • backward (bool, optional) – Whether to generate backward trajectory. Default: None

  • working_directory (str, optional) – The working directory for IRC calculation. Default: current directory

  • overwrite (bool, optional) – Whether to overwrite the $task_directory if it exits. Default: True

  • plot (bool, optional) – Whether to plot the energy changes with respect to the reaction coordinates. Default: True

  • plot_filename (str, optional) – The file name to save the plot. Default: irc_plot (it will dump irc_plot.png and irc_plot.txt with the raw data for this plot)

  • dump (bool, optional) – Whether to dump the obtained IRC trajectory file. Default:True

  • dump_filename (str, optional) – The file name without extension to save the IRC trajectory. Default: irc_traj (the extension will be added based on the format, see below)

  • dump_format (List[str], str, optional) – The format of the file to save the IRC trajectory. Default: ['json', 'xyz], i.e., the molecular database in .json format and .xyz

  • verbose (bool, optional) – Whether to print information. Default: True

Example:

mol = ml.molecule.from_xyz_file('init_ts.xyz')
method = ml.models.methods(method='AIQM2')

# optimize TS
geomopt = ml.optimize_geometry(model=method, initial_molecule=mol, ts=True)
optmol = geomopt.optimized_molecule
_ = ml.freq(model=method, molecule=optmol, program='pyscf')

# run IRC
irc_results = ml.irc(
    model=method,
    molecule=optmol)

print(irc_results)
classmethod load(working_directory=None, dump_filename=None)[source]

load IRC results from the traj folder

add_comment(direction)[source]

add information of IRC to comment

read_comment()[source]

read comment to add information to IRC traj

classmethod combine(ftrajdb, btrajdb)[source]

Combine forward results and backward results

split()[source]

Split the trajdb into ftrajdb and btrajdb according to reaction coord

mlatom.irc.psb(prev_hessian, prev_grad, current_grad, prev_step)[source]

Or Powell updating DOI: 10.1007/BF01584071

mlatom.irc.sr1(prev_hessian, prev_grad, current_grad, prev_step)[source]

Murtagh B A & Sargent RWH. Computational experience with quadratically convergent minimisation methods. Computer J. 13:185-94, 1970

mlatom.irc.bofill(prev_hessian, prev_grad, current_grad, prev_step)[source]

DOI: 10.1002/jcc.540150102

dH = (1-psi) * dH_MS + psi * dH_psb

Initial conditions

mlatom.initial_conditions.generate_initial_conditions(molecule: molecule | None = None, generation_method: str | None = None, number_of_initial_conditions: int | None = 1, file_with_initial_xyz_coordinates: str | None = None, file_with_initial_xyz_velocities: str | None = None, eliminate_angular_momentum: bool | None = True, degrees_of_freedom: int | None = None, initial_temperature: float | None = None, initial_kinetic_energy: float | None = None, use_hessian: bool | None = False, reaction_coordinate_momentum: bool | None = True, filter_by_energy_window: bool | None = False, window_filter_kwargs: dict | None = {}, random_seed: int | None = None)[source]

Generate initial conditions

Parameters:
  • molecule (data.molecule) – molecule with necessary information

  • generation_method (str) – initial condition generation method, see below the table

  • number_of_initial_conditions (int) – number of initial conditions to generate, 1 by default

  • file_with_initial_xyz_coordinates (str) – file with initial xyz coordinates, only valid for generation_method='user-defined'

  • file_with_initial_xyz_velocities (str) – file with initial xyz velocities, only valid for generation_method='user-defined'

  • eliminate_angular_momentum (bool) – remove angular momentum from velocities, valid for generation_method='random', generation_method='maxwell-boltzmann' and generation_method='wigner'

  • degrees_of_freedom (int) – degrees of freedom of the molecule, by default remove translational and rotational degrees of freedom. It can be a negative value, which means that some value is subtracted from 3*Natoms

  • initial_temperature (float) – initial temperature in Kelvin, control random initial velocities

  • initial_kinetic_energy (float) – initial kinetic energy in Hartree, control random initial velocities

  • random_seed (int) – random seed for numpy random number generator (do not use unless you want to obtain the same results every time)

  • filter_by_energy_window (bool) – filter by excitation energy window

  • window_filter_kwargs (dict) – keyword arguments for filtering the energy window, see below the table

  • reaction_coordinate_momentum (bool) – add velocities to the reaction coordinate

generation_method

description

'user-defined' (default)

use user-defined initial conditions

'random'

generate random velocities

'maxwell-boltzmann'

randomly generate initial velocities from Maxwell-Boltzmann distribution

'wigner'

use Wigner sampling as implemented in Newton-X

window_filter_kwargs

description

model

model or method that can calculate excitation energies and oscillator strengths

model_predict_kwargs

keyword arguments for above model, typically nstates specifying how many states to calculate

target_excitation_energy (float)

in eV

window_half_width (float)

in eV

random_seed (int)

random seed for numpy random number generator (do not use unless you want to obtain the same results every time)

Returns:

A molecular database (ml.data.molecular_database) with number_of_initial_conditions initial conditions

Examples:

# Use user-defined initial conditions
init_cond_db = ml.generate_initial_conditions(molecule = mol,
                                              generation_method = 'user-defined',
                                              file_with_initial_xyz_coordinates = 'ethanol.xyz',
                                              file_with_initial_xyz_velocities  = 'ethanol.vxyz',
                                              number_of_initial_conditions = 1)
# Generate random velocities
init_cond_db = ml.generate_initial_conditions(molecule = mol,
                                              generation_method = 'random',
                                              initial_temperature = 300,
                                              number_of_initial_conditions = 1)
# Use Wigner sampling
init_cond_db = ml.generate_initial_conditions(molecule = mol,
                                              generation_method = 'wigner',
                                              number_of_initial_conditions = 1)

# Sample with filtering by excitation energy window. Requires the model for calculating excitation energies and oscillator strengths.
model = ml.models.methods(method='AIQM1')
model_predict_kwargs={'nstates':9} # requests calculation of 9 electronic states
window_filter_kwargs={'model':model,
                      'model_predict_kwargs':model_predict_kwargs,
                      'target_excitation_energy':5.7, # eV
                      'window_half_width':0.1, # eV}
init_cond_db = ml.generate_initial_conditions(molecule=mol,
                                            generation_method='wigner',
                                            number_of_initial_conditions=5,
                                            initial_temperature=0,
                                            random_seed=0,
                                            use_hessian=False,
                                            filter_by_energy_window=True,
                                            window_filter_kwargs=window_filter_kwargs)

Note

Wigner sampling needs Hessian matrix. You can use ml.models.methods.predict(molecule=mol,calculate_hessian=True) to get Hessian matrix.

Molecular dynamics

!---------------------------------------------------------------------------!
! md: Module for molecular dynamics                                         !
! Implementations by: Yi-Fan Hou & Pavlo O. Dral                            !
!---------------------------------------------------------------------------!
class mlatom.md.md(model=None, model_predict_kwargs: dict | None = {}, molecule_with_initial_conditions: molecule | None = None, molecule: molecule | None = None, ensemble: str | None = 'NVE', thermostat: Thermostat | None = None, time_step: float | None = 0.1, maximum_propagation_time: float | None = 1000, dump_trajectory_interval: int | None = None, filename: str | None = None, format: str | None = 'h5md', eliminate_momentum: bool | None = False, stop_function=None, stop_function_kwargs=None)[source]

Molecular dynamics

Parameters:
  • model (mlatom.models.model or mlatom.models.methods) – Any model or method which provides energies and forces.

  • molecule_with_initial_conditions (data.molecule) – The molecule with initial conditions.

  • ensemble (str, optional) – Which kind of ensemble to use.

  • thermostat (thermostat.Thermostat) – The thermostat applied to the system.

  • time_step (float) – Time step in femtoseconds.

  • maximum_propagation_time (float) – Maximum propagation time in femtoseconds.

  • dump_trajectory_interval (int, optional) – Dump trajectory at which interval. Set to None to disable dumping.

  • filename (str, optional) – The file that saves the dumped trajectory

  • format (str, optional) – Format in which the dumped trajectory is saved

  • stop_function (any, optional) – User-defined function that stops MD before maximum_propagation_time

  • stop_function_kwargs (Dict, optional) – Kwargs of stop_function

ensemble

description

'NVE' (default)

Microcanonical (NVE) ensemble

'NVT'

Canonical (NVT) ensemble

thermostat

description

ml.md.Andersen_thermostat

Andersen thermostat

ml.md.Nose_Hoover_thermostat

Hose-Hoover thermostat

None (default)

No thermostat is applied

For theoretical details, see and cite original paper.

Examples:

# Initialize molecule
mol = ml.data.molecule()
mol.read_from_xyz_file(filename='ethanol.xyz')
# Initialize methods
aiqm1 = ml.models.methods(method='AIQM1')
# User-defined initial condition
init_cond_db = ml.generate_initial_conditions(molecule = mol,
                                              generation_method = 'user-defined',
                                              file_with_initial_xyz_coordinates = 'ethanol.xyz',
                                              file_with_initial_xyz_velocities  = 'ethanol.vxyz')
init_mol = init_cond_db.molecules[0]
# Initialize thermostat
nose_hoover = ml.md.Nose_Hoover_thermostat(temperature=300,molecule=init_mol,degrees_of_freedom=-6)
# Run dynamics
dyn = ml.md(model=aiqm1,
            molecule_with_initial_conditions = init_mol,
            ensemble='NVT',
            thermostat=nose_hoover,
            time_step=0.5,
            maximum_propagation_time = 10.0)
# Dump trajectory
traj = dyn.molecular_trajectory
traj.dump(filename='traj', format='plain_text')
traj.dump(filename='traj.h5', format='h5md')

Note

Trajectory is saved in ml.md.molecular_trajectory, which is a ml.data.molecular_trajectory class

Warning

In MLatom, energy unit is Hartree and distance unit is Angstrom. Make sure that the units in your model are consistent.

class Andersen_thermostat(**kwargs)

Andersen thermostat object

Parameters:
  • gamma (float) – collision rate in fs^{-1}, 0.2 by default

  • temperature (float) – System temperature to equilibrate in Kelvin, 300 by default

class Nose_Hoover_thermostat(**kwargs)

Nose-Hoover thermostat object

Parameters:
  • nose_hoover_chain_length (int) – Nose Hoover chain length, should be a positive number, 3 by default

  • multiple_time_step (int) – Multiple time step, should be a positive number, 3 by default

  • number_of_yoshida_suzuki_steps (int) – Number of Yoshida Suzuki steps, can be any in (1,3,5,7), 7 by default

  • nose_hoover_chain_frequency (float) – Nose-Hoover chain frequency in $fs^{-1}$, 0.0625 by default, should be comparable to the frequency you want to equilibrate

  • temperature (float) – System temperature to equilibrate in Kelvin, 300 by default

  • molecule (data.molecule) – The molecule to be equilibrated

  • degrees_of_freedom – Degrees of freedom of the system

Conical intersection optimization

!---------------------------------------------------------------------------!
! ciopt: Module for minimum-energy conical intersection optimization        !
! Implementations by: Mikolaj Martyka, 4 November 2025                      !
!---------------------------------------------------------------------------!
class mlatom.ciopt.ci_opt(model=None, model_predict_kwargs={}, initial_molecule=None, molecule=None, maximum_number_of_steps=None, working_directory=None, print_properties=None, dump_trajectory_interval=None, program=None, program_kwargs=None, convergence_criterion_for_forces=None, filename=None, format='json', state_0=0, state_1=1, sigma=3.5, alpha=0.02)[source]

Perform a geometry optimization of a molecule with a two-state penalty scheme, following the method of penalty-constrained optimization described by Levine et al. (J. Phys. Chem. B 112(2):405-413, 2008. DOI: https://doi.org/10.1021/jp0761618).

Example:

mol = ml.data.molecule()
mol.read_from_smiles_string("C=C")
odm2 = ml.models.methods(method='ODM2', read_keywords_from_file='mndokw')
ml.ci_opt(molecule=mol, model=odm2, maximum_number_of_steps=400)
Parameters:
  • model (mlatom.models.model) – Model providing energies and gradients for the molecule.

  • model_predict_kwargs (dict, optional) – Additional keyword arguments passed to the model’s prediction routine.

  • initial_molecule – mlatom.data.molecule, optional Starting geometry (cannot be used with molecule).

  • molecule – mlatom.data.molecule, optional Molecule to be optimized in place (cannot be used with initial_molecule).

  • maximum_number_of_steps – int, optional Maximum number of optimization steps (default 200).

  • working_directory – str, optional Directory for output files (default current directory).

  • print_properties – list or None, optional Properties to print at each step; enables trajectory dumping if set.

  • dump_trajectory_interval – int or None, optional Interval for writing trajectory frames (1 or None supported).

  • filename – str, optional Trajectory file name; generated automatically if omitted.

  • format – {‘json’, ‘h5md’}, default=’json’ Format for trajectory output.

  • program – {‘geometric’, ‘scipy’}, default=’geometric’ Optimization backend. Raises an error if unsupported.

  • program_kwargs – dict, optional Additional keyword arguments for the optimization backend.

  • state_0 – int, default=0 Index of the lower electronic state.

  • state_1 – int, default=1 Index of the upper electronic state.

  • sigma – float, default=3.5 Dimensionless scaling factor for the CI penalty term.

  • alpha – float, default=0.02 Energy-scale regularization parameter (same units as energy).

Surface-hopping dynamics

!---------------------------------------------------------------------------!
! namd: Module for nonadiabatic molecular dynamics                          !
! Implementations by: Lina Zhang & Pavlo O. Dral                            !
! Implementation of FSSH by: Jakub Martinka                                 !
!---------------------------------------------------------------------------!
class mlatom.namd.surface_hopping_md(model=None, model_predict_kwargs={}, molecule_with_initial_conditions=None, molecule=None, ensemble='NVE', thermostat=None, time_step=0.1, time_step_tdse=None, integrator='Butcher', decoherence_model='SDM', decoherence_SDM_decay=0.1, coupling_calc_threshold=None, maximum_propagation_time=100, dump_trajectory_interval=None, filename=None, format='h5md', stop_function=None, stop_function_kwargs=None, hopping_algorithm='LZBL', nstates=None, initial_state=None, random_seed=<function generate_random_seed>, prevent_back_hop=False, reduce_memory_usage=False, rescale_velocity_direction=None, insufficient_energy_action=None, reduce_kinetic_energy=False)[source]

Surface-hopping molecular dynamics

Parameters:
  • model (mlatom.models.model or mlatom.models.methods) – Any model or method which provides energies and forces (and couplings).

  • model_predict_kwargs (Dict, optional) – Kwargs of model prediction

  • molecule_with_initial_conditions (data.molecule) – The molecule with initial conditions.

  • molecule (data.molecule) – Work the same as molecule_with_initial_conditions

  • ensemble (str, optional) – Which kind of ensemble to use.

  • thermostat (thermostat.Thermostat) – The thermostat applied to the system.

  • time_step (float) – Time step in femtoseconds.

  • time_step_tdse (float) – Sub-time step in femtoseconds.

  • integrator (str, optional) – Integrator of semiclassical time dependent Schrödinger equation.

  • decoherence_model (str, optional) – Decoherence correction type

  • decoherence_SDM_decay (float, optional) – Decay used in Simplified Decay of Mixing decoherence correction.

  • coupling_calc_threshold (float, optional) – Calculate NACs/TDBAs only, when dE < coupling_calc_threshold (units: eV; typical values are 0.5-0.6 eV). By default, NACs/TDBA are calculated for all time steps.

  • maximum_propagation_time (float) – Maximum propagation time in femtoseconds.

  • dump_trajectory_interval (int, optional) – Dump trajectory at which interval. Set to None to disable dumping.

  • filename (str, optional) – The file that saves the dumped trajectory

  • format (str, optional) – Format in which the dumped trajectory is saved

  • stop_function (any, optional) – User-defined function that stops MD before maximum_propagation_time

  • stop_function_kwargs (Dict, optional) – Kwargs of stop_function

  • hopping_algorithm (str, optional) – Surface hopping algorithm (default: ‘LZBL’, also supported: ‘FSSH’)

  • nstates (int) – Number of states

  • initial_state (int) – Initial state

  • random_seed (int) – Random seed

  • random_numbers (list) – List of predefined random numbers.

  • prevent_back_hop (bool, optional) – Whether to prevent back hopping

  • rescale_velocity_direction (string, optional) – Rescale velocity direction (defaults: ‘momentum’ for LZBL, ‘nacv’ for FSSH, also available: ‘gradient difference’)

  • reduce_kinetic_energy (bool, optional) – Whether to reduce kinetic energy

ensemble

description

'NVE' (default)

Microcanonical (NVE) ensemble

'NVT'

Canonical (NVT) ensemble

thermostat

description

ml.md.Andersen_thermostat

Andersen thermostat

ml.md.Nose_Hoover_thermostat

Hose-Hoover thermostat

None (default)

No thermostat is applied

For theoretical details, see and cite original paper: Lina Zhang, Sebastian V. Pios, Mikołaj Martyka, Fuchun Ge, Yi-Fan Hou, Yuxinxin Chen, Lipeng Chen, Joanna Jankowska, Mario Barbatti, and Pavlo O. Dral. MLatom Software Ecosystem for Surface Hopping Dynamics in Python with Quantum Mechanical and Machine Learning Methods. Journal of Chemical Theory and Computation 2024 20 (12), 5043-5057. DOI: 10.1021/acs.jctc.4c00468

For FSSH implementation details Jakub Martinka, Lina Zhang, Yi-Fan Hou, Mikołaj Martyka, Jiří Pittner, Mario Barbatti, and Pavlo O. Dral. A Descriptor Is All You Need: Accurate Machine Learning of Nonadiabatic Coupling Vectors. The Journal of Physical Chemistry Letters 2025 16 (45), 11732-11744. DOI: 10.1021/acs.jpclett.5c02810.

Examples:

# Propagate multiple surface-hopping trajectories in parallel
# .. setup LZBL dynamics calculations
namd_kwargs = {
            'model': aiqm1,
            'time_step': 0.25,
            'maximum_propagation_time': 5,
            'hopping_algorithm': 'LZBL',
            'nstates': 3,
            'initial_state': 2,
            }

# .. setup FSSH dynamics calculations
namd_kwargs = {
            'model': model,
            'time_step': 0.1,
            'time_step_tdse': 0.005,
            'maximum_propagation_time': 5,
            'hopping_algorithm': 'FSSH',
            # the lines commented out are the defaults
            #'decoherence_model': 'SDM',
            #'rescale_velocity_direction': 'nacv',
            #'prevent_back_hop': False,
            'nstates': 3,
            'initial_state': 2
            }

# .. setup TDBA dynamics calculations
namd_kwargs = {
            'model': model,
            'time_step': 0.1,
            'time_step_tdse': 0.005,
            'maximum_propagation_time': 5,
            'hopping_algorithm': 'TDBA',
            # the lines commented out are the defaults
            #'decoherence_model': 'SDM',
            #'rescale_velocity_direction': 'momentum',
            #'prevent_back_hop': False,
            'nstates': 3,
            'initial_state': 2
            }

# .. run trajectories in parallel
dyns = ml.simulations.run_in_parallel(molecular_database=init_cond_db,
                                    task=ml.namd.surface_hopping_md,
                                    task_kwargs=namd_kwargs,
                                    create_and_keep_temp_directories=True)
trajs = [d.molecular_trajectory for d in dyns]

# Dump the trajectories
itraj=0
for traj in trajs:
    itraj+=1
    traj.dump(filename=f"traj{itraj}.h5",format='h5md')

# Analyze the result of trajectories and make the population plot
ml.namd.analyze_trajs(trajectories=trajs, maximum_propagation_time=5)
ml.namd.plot_population(trajectories=trajs, time_step=0.25,
                    max_propagation_time=5, nstates=3, filename=f'pop.png',
                    pop_filename='pop.txt')

Note

Trajectory is saved in ml.md.molecular_trajectory, which is a ml.data.molecular_trajectory class

Warning

In MLatom, energy unit is Hartree and distance unit is Angstrom. Make sure that the units in your model are consistent.

evolve_coeff_butcher(c_o, c_oo, cdot_o, cdot_oo, dt_coupling, dt_coupling_o, phase)[source]

Butcher 5th order

evolve_coeff_am5(c_o, cdot_o, cdot_oo, cdot_ooo, cdot_oooo, dt_coupling, phase)[source]

Adams Moulton 5th order

evolve_coeff_rk4(c_oo, cdot_oo, dt_coupling, phase)[source]

Runge-Kutta 4th order

mlatom.namd.plot_pes(traj, ax=None)[source]

Plot potential energy surfaces (PESs) and current state along a trajectory.

Parameters:
  • traj (object) – Molecular trajectory object containing steps.

  • ax (matplotlib.axes.Axes, optional) – Axis object used for plotting.

mlatom.namd.plot_nacs(traj, ax=None)[source]

Plot the Frobenius norms of nonadiabatic coupling vectors (NACs) over time.

Parameters:
  • traj (object) – Molecular trajectory object containing steps.

  • ax (matplotlib.axes.Axes, optional) – Axis object used for plotting.

Notes

  • If predicted NACs are available in traj.steps[i].molecule.nacv_predicted, they are overlaid with hollow markers for comparison.

mlatom.namd.plot_tdc(traj, ax=None)[source]

Plot the time-derivative couplings (TDCs) between each pair of electronic states over time.

Parameters:
  • traj (object) – Molecular trajectory object containing steps.

  • ax (matplotlib.axes.Axes, optional) – Axis object used for plotting.

mlatom.namd.plot_pop(traj, ax=None)[source]

Plot the populations of electronic states over time.

Parameters:
  • traj (object) – Molecular trajectory object containing steps.

  • ax (matplotlib.axes.Axes, optional) – Axis object used for plotting.

mlatom.namd.plot_dist(traj, ax=None, geom_params=[[0, 1]], left_axis=False)[source]

Plot degrees of freedom defined by 2(distance), 3(angle) or 4(dihedral angle) atoms over time.

Parameters:
  • traj (object) – Molecular trajectory object containing steps.

  • ax (matplotlib.axes.Axes, optional) – Axis object used for plotting.

  • geom_params (list of lists, optional) – List of degrees of freedom to plot. Each element is: - [i, j] for bond distances between atoms i and j - [i, j, k] for bond angles between atoms i-j-k - [i, j, k, l] for dihedral angles between atoms i-j-k-l.

  • left_axis (bool, optional) – If True, shift the primary axis to the left and update the right y-axis position.

mlatom.namd.plot_trajs(trajectories=None, geom_params=[[0, 1]], show_tdc=False, only_energy_params=False, filename=None)[source]

Plot multiple aspects of molecular trajectories including PES, NACs/TDCs, populations, and degrees of freedom.

Parameters:
  • trajectories (list) – List of molecular trajectory objects.

  • geom_params (list of lists, optional) – List of degrees of freedom to plot. Each element is: - [i, j] for bond distances between atoms i and j - [i, j, k] for bond angles between atoms i-j-k - [i, j, k, l] for dihedral angles between atoms i-j-k-l.

  • show_tdc (bool, optional) – If True, plot TDCs instead of NACs when available.

  • only_energy_params (bool, optional) – If True, adjust extra y-axis positions to match Landau-Zener surface hopping plotting style.

  • filename (str, optional) – File path to save the figure. If None, the figure is not saved.

mlatom.namd.internal_consistency_check(trajectories=None, filename=None)[source]

Compare classical state occupations with average adiabatic populations to check internal consistency.

Parameters:
  • trajectories (list) – List of molecular trajectory objects.

  • filename (bool, optional) – File path to save the figure. If None, the figure is not saved.

Spectra

!---------------------------------------------------------------------------!
! spectra: Module for working with spectra                                  !
! Implementations by: Yi-Fan Hou, Fuchun Ge, Bao-Xin Xue, Pavlo O. Dral     !
!---------------------------------------------------------------------------!
class mlatom.spectra.uvvis(x=None, y=None, wavelengths_nm=None, energies_eV=None, molar_absorbance=None, cross_section=None, meta_data=None)[source]

UV/Vis absorption spectrum class

Parameters:
  • x (float, np.ndarray) – range of spectra (e.g., wavelength in nm, recommended, or energies in eV)

  • y (float, np.ndarray) – user-provided intensities (e.g., molar absorpbance, recommended, or cross section)

  • done (It is better to provide spectrum information explicitly so that the correct conversions to different units are)

  • wavelengths_nm (float, np.ndarray) – range of wavelengths in nm

  • energies_eV (float, np.ndarray) – range of energies in eV

  • molar_absorbance (float, np.ndarray) – molar absorbance (extinction coefficients) in M^-1 cm^-1

  • cross_section (float, np.ndarray) – cross section in A^2/molecule

  • Also

  • meta-data (the user is encouraged to provide the)

  • meta_data (str) – meta data such as solvent, references, etc.

Example

uvvis = mlatom.spectra.uvvis(

wavelengths_nm = np.array(…), molar_absorbance = np.array(…), meta_data = ‘solvent: benzene, reference: DOI…’ )

# spectral properties can be accessed as: # uvvis.x is equivalent to what is provided by the user, e.g., wavelengths_nm or energies_eV # uvvis.y is equivalent to what is provided by the user, e.g., molar_absorbance or cross_section # wavelength range (float, np.ndarray) in nm uvvis.wavelengths_nm # molar absorbance (extinction coefficients) (float, np.ndarray) in M^-1 cm^-1 uvvis.molar_absorbance # energies corresponding to the wavelength range (float, np.ndarray), in eV uvvis.energies_eV # absorption cross-section (float, np.ndarray) in A^2/molecule uvvis.cross_section

classmethod spc(molecule=None, band_width=0.3, shift=0.0, refractive_index=1.0)[source]

Single-point convolution (SPC) approach for obtaining UV/vis spectrum via calculating the extinction coefficient (and absorption cross section) from the single-point excited-state simulations for a single geometry Implementation follows http://doi.org/10.1007/s00894-020-04355-y

Parameters:
  • molecule (mlatom.data.molecule) – molecule object with excitation_energies (in Hartree, not eV!) and oscillator_strengths

  • wavelengths_nm (float, np.ndarray) – range of wavelengths in nm (default: np.arange(400, 800))

  • band_width (float) – band width in eV (default: 0.3 eV)

  • shift (float) – shift of excitation energies, eV (default: 0 eV)

  • refractive_index (float) – refractive index (default: 1)

Example

uvvis = mlatom.spectra.uvvis.spc(

molecule=mol, wavelengths_nm=np.arange(100, 200), band_width=0.3)

# spectral properties can be accessed as: # uvvis.x is equivalent to uvvis.wavelengths_nm # uvvis.y is equivalent to uvvis.molar_absorbance # wavelength range (float, np.ndarray) in nm uvvis.wavelengths_nm # molar absorbance (extinction coefficients) (float, np.ndarray) in M^-1 cm^-1 uvvis.molar_absorbance # energies corresponding to the wavelength range (float, np.ndarray), in eV uvvis.energies_eV # absorption cross-section (float, np.ndarray) in A^2/molecule uvvis.cross_section # quick plot uvvis.plot(filename=’uvvis.png’)

classmethod spc_broadening_func(DeltaE, ff, wavelength_range, band_width, refractive_index=1, shift=0.0)[source]

Spectrum convolution function

Parameters:
  • band_width (float) – width of band

  • DeltaE (float) – vertical excitation energy, eV

  • ff (float) – oscillator strength

  • wavelength_range (float, np.ndarray) – range of wavelengths

  • refractive_index (float) – refractive index

  • shift (float) – peak shift

Returns:

extinction coefficients in M^-1 cm^-1

Return type:

(float, np.ndarray)

classmethod nea(molecular_database=None, wavelengths_nm=None, broadening_width=0.05)[source]

Nuclear ensemble approach (NEA) for obtaining UV/vis spectrum. Implementation follows Theor. Chem. Acc. 2012, 131, 1237.

Parameters:
  • molecular_database (mlatom.data.molecular_database) – molecular_database object with molecules containing excitation_energies (in Hartree, not eV!) and oscillator_strengths

  • wavelengths_nm (float, np.ndarray) – range of wavelengths in nm (default: determined automatically)

  • broadening_width (float) – broadening factor in eV (default: 0.05 eV)

Example

uvvis = mlatom.spectra.uvvis.nea(molecular_database=db,

wavelengths_nm=wavelengths_nm, broadening_width=0.02)

# spectral properties can be accessed as: # uvvis.x is equivalent to uvvis.wavelengths_nm # uvvis.y is equivalent to uvvis.molar_absorbance # wavelength range (float, np.ndarray) in nm uvvis.wavelengths_nm # molar absorbance (extinction coefficients) (float, np.ndarray) in M^-1 cm^-1 uvvis.molar_absorbance # energies corresponding to the wavelength range (float, np.ndarray), in eV uvvis.energies_eV # absorption cross-section (float, np.ndarray) in A^2/molecule uvvis.cross_section # quick plot uvvis.plot(filename=’uvvis.png’)

Active learning

Initial data sampling

initdata_sampler can be:

  • 'wigner'

  • 'harmonic-quantum-boltzmann'

User-defined ML models

The user has the flexibility to create their own ML model class for AL. Minimum requirements to such a class:

  • it must have the usual train and predict functions.

  • the train function must accept molecular_database parameter.

  • the predict function must accept molecule and/or molecular_database parameters.

The realistic, fully fledged example of how to create a usable ML model class is below (it is what we use in al routine!):

class my_model():
    def __init__(self, al_info = {}, model_file=None, device=None, verbose=False):
        import torch
        if device is None:
            device = 'cuda' if torch.cuda.is_available() else 'cpu'

        if model_file is None:
            if 'mlmodel_file' in al_info.keys():
                self.model_file = al_info['mlmodel_file']
            else:
                self.model_file = 'mlmodel'
                al_info['mlmodel_file'] = self.model_file
        else:
            self.model_file = model_file
            al_info['mlmodel_file'] = self.model_file
        if 'main_mlmodel_file' in al_info.keys():
            main_mlmodel_file = al_info['main_mlmodel_file']
        else:
            main_mlmodel_file = f'{self.model_file}.pt'
            al_info['main_mlmodel_file'] = main_mlmodel_file
        if 'aux_mlmodel_file' in al_info.keys():
            aux_mlmodel_file = al_info['aux_mlmodel_file']
        else:
            aux_mlmodel_file = f'aux_{self.model_file}.pt'
            al_info['aux_mlmodel_file'] = aux_mlmodel_file
        self.device = device
        self.verbose = verbose
        self.main_model = ml.models.ani(model_file=main_mlmodel_file,device=device,verbose=verbose)
        self.aux_model = ml.models.ani(model_file=aux_mlmodel_file,device=device,verbose=verbose)

    def train(self, molecular_database=None, al_info={}):
        if 'working_directory' in al_info.keys():
            workdir = al_info['working_directory']
            self.main_model.model_file = f'{workdir}/{self.model_file}.pt'
            self.aux_model.model_file = f'{workdir}/aux_{self.model_file}.pt'

        validation_set_fraction = 0.1
        [subtraindb, valdb] = molecular_database.split(number_of_splits=2, fraction_of_points_in_splits=[1-validation_set_fraction, validation_set_fraction], sampling='random')

        # train the model on energies and gradients
        self.main_model = ml.models.ani(model_file=self.main_model.model_file,device=self.device,verbose=self.verbose)
        self.main_model.train(molecular_database=subtraindb,validation_molecular_database=valdb,property_to_learn='energy',xyz_derivative_property_to_learn='energy_gradients')

        # train the auxiliary model only on energies
        self.aux_model = ml.models.ani(model_file=self.aux_main_model.model_file,device=self.device,verbose=self.verbose)
        self.aux_model.train(molecular_database=subtraindb,validation_molecular_database=valdb,property_to_learn='energy')

        if not 'uq_threshold' in al_info.keys():
            self.predict(molecular_database=valdb)
            uqs = valdb.get_property('uq')
            al_info['uq_threshold'] = np.median(uqs) + 3*stats.calc_median_absolute_deviation(uqs)
        self.uq_threshold = al_info['uq_threshold']

        # if the models were trained successfully, let's update al info where we can find them
        al_info['main_mlmodel_file'] = self.main_model.model_file
        al_info['aux_mlmodel_file'] = self.aux_model.model_file

    def predict(self, molecule=None, molecular_database=None):

        # predict energies and gradients with the main model
        self.main_model.predict(molecule=molecule, molecular_database=molecular_database,property_to_predict='energy',xyz_derivative_property_to_predict='energy_gradients')

        # predict energies with the auxiliary model
        self.aux_model.predict(molecule=molecule, molecular_database=molecular_database,property_to_predict='aux_energy')

        # calculate uncertainties
        moldb = molecular_database
        if moldb is None:
            moldb = ml.molecular_database()

        for mol in moldb:
            mol.uq = abs(mol.energy - mol.aux_energy)
            if mol.uq > self.uq_threshold:
                mol.uncertain = True
            else:
                mol.uncertain = False

    # This are useful in some internal al routines, e.g., when we want to make predictions in parallel (if nthreads is not set properly, it may slow down al significantly!)
    @property
    def nthreads(self):
        return self.main_model.nthreads

    @nthreads.setter
    def nthreads(self, value):
        self.main_model.nthreads = value
        self.aux_model.nthreads  = value

ml.al(
    ...
    ml_model = my_model,
    # do not use my_model(...), if you want to pass any arguments, use ml_model_kwargs:
    ml_model_kwargs = {...}, # 'al_info' is unnecessary to include, it will be added automatically. If you supply 'al_info' key, it will overwrite the default one so use if you know what you are doing.
    ...
)

As you can see, it is helpful (but not required) if the __init__ and train functions of the ML model class also accept the al_info parameter which can be used to pass information during active learning from one routine to another.

Sampler

Here is a realistic example of the sampler function used in the physics-informed active learning:

def my_sampler(al_info={}, ml_model=None, initcond_sampler=None, initcond_sampler_kwargs={}, maximum_propagation_time=1000, time_step=0.1, ensemble='NVE', thermostat=None, dump_trajs=False, dump_trajectory_interval=None, stop_function=None, batch_parallelization=True):

    moldb2label = ml.data.molecular_database()

    # generate initial conditions
    if type(initcond_sampler) == str:
        if initcond_sampler.casefold() in ['wigner', 'harmonic-quantum-boltzmann']:
            initcond_sampler = ml.generate_initial_conditions
            initcond_sampler_kwargs['generation_method'] = initcond_sampler
    import inspect
    args, varargs, varkw, defaults = inspect.getargspec(initcond_sampler)
    # Do we need al_info below?
    if 'al_info' in args:
        initial_molecular_database = initcond_sampler(al_info=al_info, **initcond_sampler_kwargs)
    else:
        initial_molecular_database = initcond_sampler(**initcond_sampler_kwargs)

    # run MD in parallel to collect uncertain points
    if batch_parallelization: # Faster way to propagate many trajs with ML
        dyn = ml.md_parallel(model=ml_model,
                             molecular_database=initial_molecular_database,
                             ensemble=ensemble,
                             thermostat=thermostat,
                             time_step=time_step,
                             maximum_propagation_time=maximum_propagation_time,
                             dump_trajectory_interval=dump_trajectory_interval,
                             stop_function=stop_function)
        trajs = dyn.molecular_trajectory
        for itraj in range(len(trajs.steps[0])):
            print(f"Trajectory {itraj} number of steps: {trajs.traj_len[itraj]}")
            if trajs.steps[trajs.traj_len[itraj]][itraj].uncertain:
                print(f'Adding molecule from trajectory {itraj} at time {trajs.traj_len[itraj]*time_step} fs')
                moldb2label.molecules.append(trajs.steps[trajs.traj_len[itraj]][itraj])

            # Dump traj
            if dump_trajs:
                import os
                traj = ml.data.molecular_trajectory()
                for istep in range(trajs.traj_len[itraj]+1):

                    step = ml.data.molecular_trajectory_step()
                    step.step = istep
                    step.time = istep * time_step
                    step.molecule = trajs.steps[istep][itraj]
                    traj.steps.append(step)
                if 'working_directory' in al_info.keys():
                    dirname = f'{al_info['working_directory']}/trajs'
                else:
                    dirname = 'trajs'
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                traj.dump(f"{dirname}/traj{itraj}.h5",format='h5md')
    else:
        md_kwargs = {
                    'molecular_database': initial_molecular_database,
                    'model': ml_model,
                    'time_step': time_step,
                    'maximum_propagation_time': maximum_propagation_time,
                    'ensemble': ensemble,
                    'thermostat': thermostat,
                    'dump_trajectory_interval': dump_trajectory_interval,
                    'stop_function': stop_function
                    }
        dyns = ml.simulations.run_in_parallel(molecular_database=initial_molecular_database,
                                            task=ml.md,
                                            task_kwargs=md_kwargs,
                                            create_and_keep_temp_directories=False)
        trajs = [d.molecular_trajectory for d in dyns]
        itraj=0
        for traj in trajs:
            itraj+=1
            print(f"Trajectory {itraj} number of steps: {len(traj.steps)}")
            if traj.steps[-1].molecule.uncertain:
                print('Adding molecule from trajectory %d at time %.2f fs' % (itraj, traj.steps[-1].time))
                moldb2label.molecules.append(traj.steps[-1].molecule)

            # Dump traj
            if dump_trajs:
                import os
                if 'working_directory' in al_info.keys():
                    dirname = f'{al_info['working_directory']}/trajs'
                else:
                    dirname = 'trajs'
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                traj.dump(f"{dirname}/traj{itraj}.h5",format='h5md')
    # add the source of molecule
    for mol in moldb2label:
        mol.sampling = 'md'
    return moldb2label

ml.al(
    ...
    sampler=my_sampler,
    sampler_kwargs={'time_step': 0.5},
    ...
)

Analysis

!—————————————————————————! ! xyz: different operations on XYZ coordinates ! ! Implementations by: Fuchun Ge, Yi-Fan Hou, Pavlo O. Dral ! !—————————————————————————!

mlatom.xyz.rmsd(molecule1, molecule2, reorder=False, check_reflection=False, keep_stereo=False)[source]

Calculate RMSD (root-mean-squared deviation) between two structures.

Parameters:
  • molecule1 (required) – either molecule class instance or numpy array with xyz coordinates

  • molecule2 (required) – either molecule class instance or numpy array with xyz coordinates

  • reorder (bool or str, optional) – whether to try to reorder atoms to get smaller RMSD (default: False; other supported options are True which is equivalent to Hungarian)

  • check_reflection (bool, optional) – check reflections (default: False).

  • keep_stereo (bool, optional) – (default: False).

reorder

description

None (default)

no reorder

'QML'

reorder using QML similarity and Hungarian method for assignment

'Hungarian'

reorder using Hungarian alogrithm

'Inertia-Hungarian'

align the principal inertia axis then reorder using Hungarian algorithm

'Brute'

reorder using all possible permutations

'Distance'

reorder by atom type and then by distance of each atom from the centroid

Example of the simple use:

rmsd = mlatom.xyz.rmsd(molecule1.xyz_coordinates, molecule2.xyz_coordinates)

Example of using Hungarian algorithm to check for homonuclear atom permutation and reflections:

rmsd = mlatom.xyz.rmsd(molecule1, molecule2, reorder=’Hungarian’, check_reflection=True)