Energy Calculators

  1. MMFFEnergy

  2. UFFEnergy

  3. MacroModelEnergy

  4. MOPACEnergy

  5. FormationEnergy

  6. XTBEnergy

  7. XTBFreeEnergy

  8. If

  9. TryCatch

  10. Random

  11. RaisingCalculator

Energy calculators are objects which calculate the energy of molecules. Each EnergyCalculator is initialized with some settings and calculates the energy of a molecule with get_energy().

import stk

# Energy calculators work with any Molecule objects, such as
# BuildingBlock or ConstructedMolecule.
mol1 = stk.BuildingBlock('[Br]CC[Br]', ['bromine'])

chain = stk.polymer.Linear('A', [0], 12)
mol2 = stk.ConstructedMolecule([mol1], chain)

# Create the energy calculator.
mmff = stk.MMFFEnergy()

# Calculate energies of various molecules.
mol1_energy = mmff.get_energy(mol1)
mol2_energy = mmff.get_energy(mol2)

By default, calling get_energy() twice on the same molecule will calculate the energy a second time. However, we can use the use_cache option to prevent recalculations when the same molecule is given to the same energy calculator a second time

caching_mmff = MMFFEnergy(use_cache=True)
# Calculate the energy the first time.
energy1 = caching_mmff.get_energy(mol1)
# The second time, the energy is returned directly from memory, a
# second calculation is not run.
energy2 = caching_mmff.get_energy(mol1)

Making New Energy Calculators

New energy calculators can be made by simply making a class which inherits the EnergyCalculator abstract base class and implements its virtual methods.

class EnergyCalculator

Bases: stk.calculators.base_calculators.MoleculeCalculator

An abstract base class for energy calculators.

Methods

add_to_cache(self, mol[, value])

Add a molecule to the cache.

get_cached_value(self, mol)

Return the value stored in the cache for mol.

get_energy(self, mol)

Calculate the energy of mol.

is_caching(self)

True if the calculator has caching turned on.

is_in_cache(self, mol)

Return True if mol is cached.

set_cache_use(self, use_cache)

Set cache use on or off.

__init__(self, /, *args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

add_to_cache(self, mol, value=None)

Add a molecule to the cache.

Parameters
  • mol (Molecule) – The molecule to be added to the cache.

  • value (class:object, optional) – The cached value associated with the molecule.

Returns

The calculator.

Return type

MoleculeCalculator

Raises

NotImplementedError – This is a virtual method and needs to be implemented in a subclass.

get_cached_value(self, mol)

Return the value stored in the cache for mol.

Parameters

mol (Molecule) – The molecule whose cached value is to be returned.

Returns

The cached value.

Return type

object

Raises

NotImplementedError – This is a virtual method and needs to be implemented in a subclass.

get_energy(self, mol)

Calculate the energy of mol.

Parameters

mol (Molecule) – The Molecule whose energy is to be calculated.

Returns

The energy.

Return type

float

is_caching(self)

True if the calculator has caching turned on.

Returns

True if the calculator has caching turned on.

Return type

bool

Raises

NotImplementedError – This is a virtual method and needs to be implemented in a subclass.

is_in_cache(self, mol)

Return True if mol is cached.

Parameters

mol (Molecule) – The molecule being checked.

Returns

True if mol is cached.

Return type

bool

Raises

NotImplementedError – This is a virtual method and needs to be implemented in a subclass.

set_cache_use(self, use_cache)

Set cache use on or off.

Parameters

use_cache (bool) – True if the cache is to be used.

Returns

The calculator.

Return type

MoleculeCalculator

Raises

NotImplementedError – This is a virtual method and needs to be implemented in a subclass.

exception EnergyError

Bases: Exception

Indicates a failed energy calculation.

__init__(self, /, *args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class FormationEnergy(energy_calculator, reactants, products, use_cache=False)

Bases: stk.calculators.base_calculators._MoleculeCalculator, stk.calculators.energy.energy_calculators.EnergyCalculator

Calculates the formation energy of a molecule.

Examples

import stk

# Make the molecules needed to calculate formation energy.
water = stk.BuildingBlock('[H]O[H]')
bb1 = stk.BuildingBlock('NCCCN', ['amine'])
bb2 = stk.BuildingBlock('O=CCC=O', ['aldehyde'])

chain = stk.polymer.Linear('AB', [0, 0], 6)
polymer = stk.ConstructedMolecule(
    building_blocks=[bb1, bb2],
    topology_graph=chain
)

# Make the energy calculator used to calculate energies.
uff_energy = stk.UFFEnergy()

# Make the formation energy calculator.
formation = stk.FormationEnergy(
    energy_calculator=uff_energy,
    reactants=[bb1]*6 + [bb2]*6,
    products=[water]*polymer.bonds_made
)

# Calculate the formation energy.
formation_energy = formation.get_energy(polymer)

Methods

add_to_cache(self, mol[, value])

Add a molecule to the cache.

get_cached_value(self, mol)

Return the value stored in the cache for mol.

get_energy(self, mol)

Calculate the energy of mol.

is_caching(self)

True if the calculator has caching turned on.

is_in_cache(self, mol)

Return True if mol is cached.

set_cache_use(self, use_cache)

Set cache use on or off.

__init__(self, energy_calculator, reactants, products, use_cache=False)

Initialize a FormationEnergy instance.

Parameters
  • energy_calculator (EnergyCalculator) – The EnergyCalculator used to calculate the energy of all reactant and product molecules.

  • reactants (list of Molecule) – The reactants. If there are multiples of the same reactant then it must appear multiple times in this list.

  • products (list of Molecule) – The molecules which are produced as a result of the formation reaction. This list must omit the Molecule passed to get_energy(). If there are multiples of the same product, it must appear multiple times in this list.

  • use_cache (bool, optional) – If True get_energy() will not run twice on the same molecule, but will instead return the previously calculated value.

add_to_cache(self, mol, value=None)

Add a molecule to the cache.

Parameters
  • mol (Molecule) – The molecule to be added to the cache.

  • value (class:object, optional) – The cached value associated with the molecule.

Returns

The calculator.

Return type

MoleculeCalculator

get_cached_value(self, mol)

Return the value stored in the cache for mol.

Parameters

mol (Molecule) – The molecule whose cached value is to be returned.

Returns

The cached value.

Return type

object

get_energy(self, mol)

Calculate the energy of mol.

Parameters

mol (Molecule) – The Molecule whose energy is to be calculated.

Returns

The energy.

Return type

float

is_caching(self)

True if the calculator has caching turned on.

Returns

True if the calculator has caching turned on.

Return type

bool

is_in_cache(self, mol)

Return True if mol is cached.

Parameters

mol (Molecule) – The molecule being checked.

Returns

True if mol is cached.

Return type

bool

set_cache_use(self, use_cache)

Set cache use on or off.

Parameters

use_cache (bool) – True if the cache is to be used.

Returns

The calculator.

Return type

MoleculeCalculator

class MMFFEnergy(use_cache=False)

Bases: stk.calculators.base_calculators._MoleculeCalculator, stk.calculators.energy.energy_calculators.EnergyCalculator

Uses the MMFF force field to calculate energies.

Examples

import stk

# Create a molecule whose energy we want to know.
mol1 = stk.BuildingBlock('CCCNCCCN')

# Create the energy calculator.
mmff = stk.MMFFEnergy()

# Calculate the energy.
energy1 = mmff.get_energy(mol1)

Methods

add_to_cache(self, mol[, value])

Add a molecule to the cache.

get_cached_value(self, mol)

Return the value stored in the cache for mol.

get_energy(self, mol)

Calculate the energy of mol.

is_caching(self)

True if the calculator has caching turned on.

is_in_cache(self, mol)

Return True if mol is cached.

set_cache_use(self, use_cache)

Set cache use on or off.

__init__(self, use_cache=False)

Initialize the Calculator.

Parameters

use_cache (bool, optional) – If True, a calculation will not be performed on the same molecule twice.

add_to_cache(self, mol, value=None)

Add a molecule to the cache.

Parameters
  • mol (Molecule) – The molecule to be added to the cache.

  • value (class:object, optional) – The cached value associated with the molecule.

Returns

The calculator.

Return type

MoleculeCalculator

get_cached_value(self, mol)

Return the value stored in the cache for mol.

Parameters

mol (Molecule) – The molecule whose cached value is to be returned.

Returns

The cached value.

Return type

object

get_energy(self, mol)

Calculate the energy of mol.

Parameters

mol (Molecule) – The Molecule whose energy is to be calculated.

Returns

The energy.

Return type

float

is_caching(self)

True if the calculator has caching turned on.

Returns

True if the calculator has caching turned on.

Return type

bool

is_in_cache(self, mol)

Return True if mol is cached.

Parameters

mol (Molecule) – The molecule being checked.

Returns

True if mol is cached.

Return type

bool

set_cache_use(self, use_cache)

Set cache use on or off.

Parameters

use_cache (bool) – True if the cache is to be used.

Returns

The calculator.

Return type

MoleculeCalculator

class UFFEnergy(use_cache=False)

Bases: stk.calculators.base_calculators._MoleculeCalculator, stk.calculators.energy.energy_calculators.EnergyCalculator

Uses the UFF force field to calculate energies.

Examples

import stk

# Create a molecule whose energy we want to know.
mol1 = stk.BuildingBlock('CCCNCCCN')

# Create the energy calculator.
uff = stk.UFFEnergy()

# Calculate the energy.
energy1 = uff.get_energy(mol1)

Methods

add_to_cache(self, mol[, value])

Add a molecule to the cache.

get_cached_value(self, mol)

Return the value stored in the cache for mol.

get_energy(self, mol)

Calculate the energy of mol.

is_caching(self)

True if the calculator has caching turned on.

is_in_cache(self, mol)

Return True if mol is cached.

set_cache_use(self, use_cache)

Set cache use on or off.

__init__(self, use_cache=False)

Initialize the Calculator.

Parameters

use_cache (bool, optional) – If True, a calculation will not be performed on the same molecule twice.

add_to_cache(self, mol, value=None)

Add a molecule to the cache.

Parameters
  • mol (Molecule) – The molecule to be added to the cache.

  • value (class:object, optional) – The cached value associated with the molecule.

Returns

The calculator.

Return type

MoleculeCalculator

get_cached_value(self, mol)

Return the value stored in the cache for mol.

Parameters

mol (Molecule) – The molecule whose cached value is to be returned.

Returns

The cached value.

Return type

object

get_energy(self, mol)

Calculate the energy of mol.

Parameters

mol (Molecule) – The Molecule whose energy is to be calculated.

Returns

The energy.

Return type

float

is_caching(self)

True if the calculator has caching turned on.

Returns

True if the calculator has caching turned on.

Return type

bool

is_in_cache(self, mol)

Return True if mol is cached.

Parameters

mol (Molecule) – The molecule being checked.

Returns

True if mol is cached.

Return type

bool

set_cache_use(self, use_cache)

Set cache use on or off.

Parameters

use_cache (bool) – True if the cache is to be used.

Returns

The calculator.

Return type

MoleculeCalculator

class XTBEnergy(xtb_path, gfn_version=2, output_dir=None, num_cores=1, calculate_free_energy=False, electronic_temperature=300, solvent=None, solvent_grid='normal', charge=0, num_unpaired_electrons=0, unlimited_memory=False, use_cache=False)

Bases: stk.calculators.base_calculators._MoleculeCalculator, stk.calculators.energy.energy_calculators.EnergyCalculator

Uses GFN-xTB [R6e92b130b761-1] to calculate energy and other properties.

By default, get_energy() will extract other properties of the Molecule passed to get_energy(), which will be saved in the attributes of XTBEnergy.

Notes

When running get_energy(), this calculator changes the present working directory with os.chdir(). The original working directory will be restored even if an error is raised, so unless multi-threading is being used this implementation detail should not matter.

If multi-threading is being used an error could occur if two different threads need to know about the current working directory as XTBEnergy can change it from under them.

Note that this does not have any impact on multi-processing, which should always be safe.

total_energies

dict of the total energy of each Molecule passed to get_energy().

Type

dict

homo_lumo_gaps

dict of the HOMO-LUMO gap of each Molecule passed to get_energy().

Type

dict

fermi_levels

dict of the Fermi level of each Molecule passed to get_energy().

Type

dict

homo_lumo_orbitals

dict of the HOMO-LUMO orbital properties of each Molecule passed to get_energy().

Type

dict

qonly_dipole_moments

dict of the q only dipole moment of each Molecule passed to get_energy().

Type

dict

full_dipole_moments

dict of the full dipole moment of each Molecule passed to get_energy().

Type

dict

qonly_quadrupole_moments

dict of the q only quadrupole moment of each Molecule passed to get_energy().

Type

dict

qdip_quadrupole_moments

dict of the q+dip quadrupole moment of each Molecule passed to get_energy().

Type

dict

full_quadrupole_moments

dict of the full quadrupole moment of each Molecule passed to get_energy().

Type

dict

total_free_energies

dict of the total free energy of each Molecule passed to get_energy(). This is empty if calculate_free_energy is False.

Type

dict

frequencies

dict of the vibrational frequencies of each Molecule passed to get_energy(). This is empty if calculate_free_energy was False.

Type

dict

Examples

import stk

bb1 = stk.BuildingBlock('NCCNCCN', ['amine'])
bb2 = stk.BuildingBlock('O=CCCC=O', ['aldehyde'])
polymer = stk.ConstructedMolecule(
    building_blocks=[bb1, bb2],
    topology_graph=stk.polymer.Linear("AB", [0, 0], 3)
)

# Optimize the constructed molecule so that it has a
# reasonable structure.
optimizer = stk.OptimizerSequence(
    stk.ETKDG(),
    stk.XTB(xtb_path='/opt/gfnxtb/xtb', unlimited_memory=True)
)
optimizer.optimize(polymer)

# Calculate energy using GFN-xTB.
xtb = stk.XTBEnergy(
    xtb_path='/opt/gfnxtb/xtb',
    unlimited_memory=True
)

p_total_energy = xtb.get_energy(polymer)

# Extract properties from the energy calculator for a given
# molecule.
homo_lumo_gap = xtb.homo_lumo_gaps[polymer]
fermi_levels = xtb.fermi_levels[polymer]
homo_lumo_orbitals = xtb.homo_lumo_orbitals[polymer]
full_dipole_moments = xtb.full_dipole_moments[polymer]
full_quadrupole_moments = xtb.full_quadrupole_moments[polymer]

# The total energy can be extracted at any point from the
# calculator.
total_energy = xtb.total_energies[polymer]

If calculate_free_energy is True, xTB performs a numerical Hessian calculation and calculates the total free energy and vibrational frequencies of a molecule. It is recommended that a well optimized structure be used as input for these calculations

# Optimize the constructed molecule so that it has a
# reasonable structure.
optimizer = stk.OptimizerSequence(
    stk.ETKDG(),
    stk.XTB(
        xtb_path='/opt/gfnxtb/xtb',
        unlimited_memory=True,
        opt_level='verytight'
    )
)
optimizer.optimize(polymer)

# Calculate energy using GFN-xTB.
xtb = stk.XTBEnergy(
    xtb_path='/opt/gfnxtb/xtb',
    unlimited_memory=True,
    calculate_free_energy=True
)

p_total_energy = xtb.get_energy(polymer)

# Extract properties from the energy calculator for a given
# molecule.
p_total_free_energy = xtb.total_energies[polymer]
p_frequencies = xtb.frequencies[polymer]

References

R6e92b130b761-1

https://xtb-docs.readthedocs.io/en/latest/setup.html

Methods

add_to_cache(self, mol[, value])

Add a molecule to the cache.

get_cached_value(self, mol)

Return the value stored in the cache for mol.

get_energy(self, mol)

Calculate the energy of mol.

is_caching(self)

True if the calculator has caching turned on.

is_in_cache(self, mol)

Return True if mol is cached.

set_cache_use(self, use_cache)

Set cache use on or off.

__init__(self, xtb_path, gfn_version=2, output_dir=None, num_cores=1, calculate_free_energy=False, electronic_temperature=300, solvent=None, solvent_grid='normal', charge=0, num_unpaired_electrons=0, unlimited_memory=False, use_cache=False)

Initializes a XTBEnergy instance.

Parameters
  • xtb_path (str) – The path to the xTB executable.

  • gfn_version (int, optional) – Parameterization of GFN to use in xTB. For details see https://xtb-docs.readthedocs.io/en/latest/basics.html.

  • output_dir (str, optional) – The name of the directory into which files generated during the calculation are written, if None then uuid.uuid4() is used.

  • num_cores (int, optional) – The number of cores xTB should use.

  • calculate_free_energy (bool, optional) – Whether to calculate the total free energy and vibrational frequencies. Setting this to True can drastically increase calculation time and memory requirements.

  • electronic_temperature (int, optional) – Electronic temperature in Kelvin.

  • solvent (str, optional) – Solvent to use in GBSA implicit solvation method. For details see https://xtb-docs.readthedocs.io/en/latest/gbsa.html.

  • solvent_grid (str, optional) – Grid level to use in SASA calculations for GBSA implicit solvent. Can be one of 'normal', 'tight', 'verytight' or 'extreme'. For details see https://xtb-docs.readthedocs.io/en/latest/gbsa.html.

  • charge (int, optional) – Formal molecular charge.

  • num_unpaired_electrons (int, optional) – Number of unpaired electrons.

  • unlimited_memory – If True energy() will be run without constraints on the stack size. If memory issues are encountered, this should be True, however this may raise issues on clusters.

  • use_cache (bool, optional) – If True energy() will not run twice on the same molecule.

add_to_cache(self, mol, value=None)

Add a molecule to the cache.

Parameters
  • mol (Molecule) – The molecule to be added to the cache.

  • value (class:object, optional) – The cached value associated with the molecule.

Returns

The calculator.

Return type

MoleculeCalculator

get_cached_value(self, mol)

Return the value stored in the cache for mol.

Parameters

mol (Molecule) – The molecule whose cached value is to be returned.

Returns

The cached value.

Return type

object

get_energy(self, mol)

Calculate the energy of mol.

Parameters

mol (Molecule) – The Molecule whose energy is to be calculated.

Returns

The energy.

Return type

float

is_caching(self)

True if the calculator has caching turned on.

Returns

True if the calculator has caching turned on.

Return type

bool

is_in_cache(self, mol)

Return True if mol is cached.

Parameters

mol (Molecule) – The molecule being checked.

Returns

True if mol is cached.

Return type

bool

set_cache_use(self, use_cache)

Set cache use on or off.

Parameters

use_cache (bool) – True if the cache is to be used.

Returns

The calculator.

Return type

MoleculeCalculator