Skip to content

Optimisation

UFF4MOF geometry optimisation via gulp_setup's atom-typing backend: cage_isomer_builder.utils.optimise.

For organic molecules the energy matches RDKit's UFF implementation, term by term. The tests check this on 16 molecules.

UFF4MOF geometry optimisation, built directly from an explicit bond-order matrix rather than distances alone.

Unlike GFN-xTB (see :mod:cage_isomer_builder.utils.tblite_optimise), UFF is a classical, topology-based force field: every energy term (bond, angle, torsion, van der Waals) is enumerated from the bond matrix and an explicit per-atom UFF type name, so the intended connectivity from the STK-constructed cage is respected exactly even when interatomic distances are atypical (bulky multi-atom nodes, expanded cages, ...). xTB needs no bond matrix, but it also cannot be held to one.

UFF4MOFCalculator evaluates energies and forces with OpenMM (openmm.CustomBondForce / CustomAngleForce / CustomTorsionForce for bond, angle and torsion terms, CustomCompoundBondForce for the out-of-plane inversion term, and CustomNonbondedForce for van der Waals and Coulomb beyond 1-3 neighbours), using the combining rules in :mod:cage_isomer_builder.utils.uff4mof_params. The energy matches RDKit's UFF implementation for organic molecules (see tests/test_uff4mof_backend.py).

UFF4MOFCalculator

UFF4MOFCalculator(bond_matrix, mmtypes, uff_db, charges=None, platform=None, precision='mixed', **kwargs)

Bases: Calculator

ASE Calculator evaluating the UFF4MOF energy/forces via OpenMM.

Parameters:

Name Type Description Default
bond_matrix (ndarray, shape(n_atoms, n_atoms))

Symmetric bond-order matrix (0 = no bond).

required
mmtypes sequence of str

UFF4MOF type name for each atom (e.g. "C_3", "Zr3+4"), as returned by :func:gulp_setup.mmanalysis.analyze_mm.

required
uff_db dict[str, UFFAtomParams]

Parameter table from :func:cage_isomer_builder.utils.uff4mof_params.load_uff4mof_db.

required
charges (ndarray, shape(n_atoms))

Fixed partial charges (elementary charges). When given, a Coulomb term ke*qi*qj/r is added over the same non-bonded pairs as the van der Waals term (more than two bonds apart). UFF, and so UFF4MOF, assumes such an electrostatic term; without it the attraction between charged fragments (e.g. carboxylates and a metal cluster) is missing. The charges are not updated during the optimisation, as is usual for UFF with QEq charges. None (default) adds no Coulomb term.

None
platform str

OpenMM platform name ("Reference", "CPU", "OpenCL", "CUDA"). Defaults to the fastest one available.

None
precision str

Precision for platforms that support it (OpenCL, CUDA): "single", "mixed" or "double". "mixed" computes forces in single precision and adds them up in double precision. The Reference platform is always double precision.

"mixed"

Examples:

>>> import numpy as np
>>> from ase.build import molecule
>>> methane = molecule("CH4")
>>> bonds = np.zeros((5, 5))
>>> bonds[0, 1:] = bonds[1:, 0] = 1.0              # four C-H bonds
>>> from gulp_setup.mmanalysis import analyze_mm
>>> from cage_isomer_builder.utils.optimise import UFF4MOFCalculator
>>> from cage_isomer_builder.utils.uff4mof_params import load_uff4mof_db
>>> _, types = analyze_mm(methane, bond_order=bonds)
>>> methane.calc = UFF4MOFCalculator(bonds, types, load_uff4mof_db())
>>> [str(t) for t in types], methane.get_forces().shape
(['C_3', 'H_', 'H_', 'H_', 'H_'], (5, 3))
Source code in cage_isomer_builder/utils/optimise.py
def __init__(self, bond_matrix, mmtypes, uff_db, charges=None,
             platform=None, precision="mixed", **kwargs):
    super().__init__(**kwargs)
    self.bond_matrix = np.asarray(bond_matrix, dtype=float)
    self.mmtypes = np.asarray(mmtypes)
    self.uff_db = uff_db
    self.charges = None if charges is None else np.asarray(charges, dtype=float)
    self.platform = platform
    self.precision = precision
    self._context = None

calculate

calculate(atoms=None, properties=('energy', 'forces'), system_changes=all_changes)

Evaluate the UFF4MOF energy (eV) and forces (eV/Angstrom) with OpenMM (ASE calculator interface).

Examples:

>>> import numpy as np
>>> from ase.build import molecule
>>> water = molecule("H2O")
>>> bonds = np.array([[0, 1, 1], [1, 0, 0], [1, 0, 0]], dtype=float)
>>> from gulp_setup.mmanalysis import analyze_mm
>>> from cage_isomer_builder.utils.optimise import UFF4MOFCalculator
>>> from cage_isomer_builder.utils.uff4mof_params import load_uff4mof_db
>>> _, types = analyze_mm(water, bond_order=bonds)
>>> water.calc = UFF4MOFCalculator(bonds, types, load_uff4mof_db())
>>> isinstance(water.get_potential_energy(), float)      # calls calculate()
True
Source code in cage_isomer_builder/utils/optimise.py
def calculate(self, atoms=None, properties=("energy", "forces"), system_changes=all_changes):
    """
    Evaluate the UFF4MOF energy (eV) and forces (eV/Angstrom) with
    OpenMM (ASE calculator interface).

    Examples
    --------
    >>> import numpy as np
    >>> from ase.build import molecule
    >>> water = molecule("H2O")
    >>> bonds = np.array([[0, 1, 1], [1, 0, 0], [1, 0, 0]], dtype=float)
    >>> from gulp_setup.mmanalysis import analyze_mm
    >>> from cage_isomer_builder.utils.optimise import UFF4MOFCalculator
    >>> from cage_isomer_builder.utils.uff4mof_params import load_uff4mof_db
    >>> _, types = analyze_mm(water, bond_order=bonds)
    >>> water.calc = UFF4MOFCalculator(bonds, types, load_uff4mof_db())
    >>> isinstance(water.get_potential_energy(), float)      # calls calculate()
    True
    """
    super().calculate(atoms, properties, system_changes)
    from openmm import unit

    if self._context is None:
        self._build_context(self.atoms)

    positions_nm = self.atoms.get_positions() * NM_PER_ANGSTROM
    self._context.setPositions(positions_nm * unit.nanometer)
    state = self._context.getState(getEnergy=True, getForces=True)

    energy_kjmol = state.getPotentialEnergy().value_in_unit(unit.kilojoule_per_mole)
    forces_kjmolnm = state.getForces(asNumpy=True).value_in_unit(
        unit.kilojoule_per_mole / unit.nanometer
    )

    self.results["energy"] = energy_kjmol * ase_units.kJ / ase_units.mol
    self.results["forces"] = (
        np.asarray(forces_kjmolnm) * (ase_units.kJ / ase_units.mol) / ase_units.nm
    )

run_uff4mof_optimisation

run_uff4mof_optimisation(atoms, bond_matrix, fmax: float = 0.05, steps: int = 500, optimizer_cls=None, trajectory: Optional[str] = None, charges: Optional[ndarray] = None, logfile: Optional[str] = '-')

Relax a molecular geometry with ASE using a UFF4MOF (OpenMM) calculator.

UFF atom types are assigned automatically from bond_matrix via :func:gulp_setup.mmanalysis.analyze_mm (a heuristic cost function over local coordination number, angle and radius); the bond matrix is used as given, never re-derived from the geometry.

Parameters:

Name Type Description Default
atoms Atoms

Starting geometry. Any constraint already set on atoms (e.g. FixRigidBodies) is preserved through the optimisation.

required
bond_matrix (ndarray, shape(len(atoms), len(atoms)))

Symmetric bond-order matrix, e.g. from :func:cage_isomer_builder.utils.read_write.stk_2_ase_atoms.

required
fmax float

Force convergence threshold in eV/Angstrom.

0.05
steps int

Maximum number of optimisation steps.

500
optimizer_cls ASE optimizer class

Any ASE Optimizer subclass (LBFGS, BFGS, FIRE, ...). Defaults to LBFGS.

None
trajectory str

File path for an ASE .traj trajectory.

None
charges (ndarray, shape(len(atoms)))

Fixed partial charges, passed to :class:UFF4MOFCalculator for its Coulomb term. None (default) runs without electrostatics.

None
logfile str or None

Where the optimiser writes its step log: "-" for the terminal, a file path, or None for no output.

"-"

Returns:

Type Description
Atoms

Optimised structure (a copy; the input atoms is not modified).

Examples:

>>> import numpy as np
>>> from ase.build import molecule
>>> methane = molecule("CH4")
>>> bonds = np.zeros((5, 5))
>>> bonds[0, 1:] = bonds[1:, 0] = 1.0              # four C-H bonds
>>> from cage_isomer_builder.utils.optimise import run_uff4mof_optimisation
>>> relaxed = run_uff4mof_optimisation(methane, bonds, logfile=None)
>>> round(float(relaxed.get_distance(0, 1)), 2), round(float(relaxed.get_angle(1, 0, 2)), 1)
(1.11, 109.5)
Source code in cage_isomer_builder/utils/optimise.py
def run_uff4mof_optimisation(
    atoms,
    bond_matrix,
    fmax: float = 0.05,
    steps: int = 500,
    optimizer_cls=None,
    trajectory: Optional[str] = None,
    charges: Optional[np.ndarray] = None,
    logfile: Optional[str] = "-",
):
    """
    Relax a molecular geometry with ASE using a UFF4MOF (OpenMM) calculator.

    UFF atom types are assigned automatically from ``bond_matrix`` via
    :func:`gulp_setup.mmanalysis.analyze_mm` (a heuristic cost function over
    local coordination number, angle and radius); the bond matrix is used as
    given, never re-derived from the geometry.

    Parameters
    ----------
    atoms : ase.Atoms
        Starting geometry. Any constraint already set on ``atoms``
        (e.g. ``FixRigidBodies``) is preserved through the optimisation.
    bond_matrix : np.ndarray, shape (len(atoms), len(atoms))
        Symmetric bond-order matrix, e.g. from
        :func:`cage_isomer_builder.utils.read_write.stk_2_ase_atoms`.
    fmax : float, default 0.05
        Force convergence threshold in eV/Angstrom.
    steps : int, default 500
        Maximum number of optimisation steps.
    optimizer_cls : ASE optimizer class, optional
        Any ASE ``Optimizer`` subclass (LBFGS, BFGS, FIRE, ...).
        Defaults to ``LBFGS``.
    trajectory : str, optional
        File path for an ASE ``.traj`` trajectory.
    charges : np.ndarray, shape (len(atoms),), optional
        Fixed partial charges, passed to :class:`UFF4MOFCalculator` for its
        Coulomb term. ``None`` (default) runs without electrostatics.
    logfile : str or None, default "-"
        Where the optimiser writes its step log: ``"-"`` for the terminal,
        a file path, or ``None`` for no output.

    Returns
    -------
    ase.Atoms
        Optimised structure (a copy; the input ``atoms`` is not modified).

    Examples
    --------
    >>> import numpy as np
    >>> from ase.build import molecule
    >>> methane = molecule("CH4")
    >>> bonds = np.zeros((5, 5))
    >>> bonds[0, 1:] = bonds[1:, 0] = 1.0              # four C-H bonds
    >>> from cage_isomer_builder.utils.optimise import run_uff4mof_optimisation
    >>> relaxed = run_uff4mof_optimisation(methane, bonds, logfile=None)
    >>> round(float(relaxed.get_distance(0, 1)), 2), round(float(relaxed.get_angle(1, 0, 2)), 1)
    (1.11, 109.5)
    """
    import warnings

    from gulp_setup.mmanalysis import analyze_mm

    from cage_isomer_builder.__data__.uff4mof_data import DERIVED_UFF4MOF_DATA, UFF4MOF_DATA
    from cage_isomer_builder.utils.uff4mof_params import load_uff4mof_db

    if optimizer_cls is None:
        optimizer_cls = LBFGS

    opt_atoms = atoms.copy()
    opt_atoms.pbc = False

    _, mmtypes = analyze_mm(opt_atoms, bond_order=np.asarray(bond_matrix, dtype=float))
    uff_db = load_uff4mof_db()
    unknown = sorted({str(t) for t in mmtypes if t not in uff_db})
    if unknown:
        raise ValueError(
            f"no UFF4MOF parameters for atom type(s) {unknown} assigned by "
            "gulp_setup; use method='GFN2-xTB' for this structure."
        )

    published = {tuple(v) for v in UFF4MOF_DATA.values()}
    # Derived types identical to a published one (O_HH = O_3, H_OH = H_,
    # N_3+4 = N_3, K = K_, W_3f4 = W_3f2) are aliases: nothing to warn about.
    derived = sorted({str(t) for t in mmtypes if t in DERIVED_UFF4MOF_DATA
                      and tuple(DERIVED_UFF4MOF_DATA[t]) not in published})
    if derived:
        warnings.warn(
            f"UFF4MOF type(s) {derived} have no published parameter set; using "
            "parameters derived from the same element's type (see "
            "DERIVED_UFF4MOF_DATA in cage_isomer_builder/__data__/uff4mof_data.py)."
        )
    opt_atoms.calc = UFF4MOFCalculator(
        bond_matrix=bond_matrix, mmtypes=mmtypes, uff_db=uff_db, charges=charges
    )

    opt = optimizer_cls(opt_atoms, trajectory=trajectory, logfile=logfile)
    opt.run(fmax=fmax, steps=steps)

    return opt_atoms