Hybrid engine UseLowestEnergy#

You can use the Hybrid engine to calculate the energy of a structure with many different engines or engine settings.

By setting UseLowestEnergy, the engine that gives the lowest energy is used for the energy (and forces).

This can be useful, for example, to determine the lowest-energy spin configuration of a molecule.

Purpose#

Example showing the UseLowestEnergy feature of the Hybrid engine and the OptimizeSpinRound feature of the ADF engine.

A bond scan is performed on hydrogen peroxide with UFF. The resulting structures are then recalculated with DFT using four different setups. In particular, one setup uses the Hybrid engine with DynamicFactors=UseLowestEnergy. Another uses the ADF engine with OptimizeSpinRound in combination with an ElectronicTemperature.

All four setups use a 300 K electronic temperature to stabilize orbital occupations as the O-O bond is stretched. The same smearing is used for a consistent comparison, with MESA acceleration and up to 300 SCF iterations. These settings change the electronic occupations slightly relative to a zero-temperature calculation.

In the end, the results of energy vs. bond length are plotted.

Initial imports#

import matplotlib.pyplot as plt
from scm.base import ChemicalSystem
from scm.inputs import ADF, AMS, ForceField, Hybrid
from scm.plams import AMSJob, Units

Helper functions#

def initial_pesscan():
    """Run a bond scan for hydrogen peroxide with UFF. Returns the finished job"""
    # Match the unoptimized single conformer used by PLAMS from_smiles.
    mol = ChemicalSystem.from_smiles("OO", optimize_with_uff=False, num_trial_conformers=1)
    mol.set_distance(0, 1, 1.2, unit="angstrom")  # Match the first scan point; indices are zero-based.
    s = AMS(Task="PESScan", Engine=ForceField(Type="UFF"))
    # Scan O-O bond length (atoms 1 and 2) between 1.2 and 2.5 Å
    s.PESScan.ScanCoordinate = [{"nPoints": 7, "Distance": ["2 1 1.2 2.5"]}]
    job = AMSJob(settings=s, molecule=mol, name="initial_pesscan")
    job.run()
    return job


def singlet_settings(engine_id=None):
    s = ADF(id=engine_id)
    s.Unrestricted = False
    s.XC.GGA = "PBE"
    s.Basis.Type = "DZP"
    s.SCF.Iterations = 300
    s.SCF.AccelerationMethod = "MESA"
    s.Occupations = "ElectronicTemperature=300"
    return s


def triplet_settings(engine_id=None):
    s = ADF(id=engine_id)
    s.Unrestricted = True
    s.SpinPolarization = 2
    s.XC.GGA = "PBE"
    s.Basis.Type = "DZP"
    s.SCF.Iterations = 300
    s.SCF.AccelerationMethod = "MESA"
    s.Occupations = "ElectronicTemperature=300"
    return s


def hybrid_settings():
    """Look at the file plams_workdir/hybrid/hybrid.in to see how the below is translated into text input for the hybrid engine"""
    return Hybrid(
        Energy={
            "DynamicFactors": "UseLowestEnergy",
            "Term": [
                {"Region": "*", "EngineID": "Singlet"},
                {"Region": "*", "EngineID": "Triplet"},
            ],
        },
        Engine=[singlet_settings("Singlet"), triplet_settings("Triplet")],
    )


def replay_job(rkf, engine="hybrid"):
    """Replay the structures from the UFF pesscan with ADF. Use three different engines:
    Hybrid: This will run all structures with both Singlet and Triplet and pick the lowest energy
    Singlet: This runs all structures using the Singlet settings
    Triplet: This runs all structures using the Triplet settings

    Returns the finished job
    """
    if engine == "hybrid":
        engine_settings = hybrid_settings()
    elif engine == "singlet":
        engine_settings = singlet_settings()
    elif engine == "triplet":
        engine_settings = triplet_settings()
    elif engine == "optimizespin":
        engine_settings = triplet_settings()
        engine_settings.Occupations = "ElectronicTemperature=300 OptimizeSpinRound=0.05"

    s = AMS(Task="Replay", Engine=engine_settings)
    s.Replay.File = rkf

    job = AMSJob(settings=s, name=engine)
    job.run()
    return job


def plot_results(singlet_job, triplet_job, hybrid_job, optimizespin_job):
    """
    Generate a plot of the energy vs. bond length for the four different jobs. Saves a plot to pesplot.png.
    """
    for job in (singlet_job, triplet_job, hybrid_job, optimizespin_job):
        if job.results.grep_output("SCF NOT CONVERGED|ENGINE FAILED TO SOLVE", options="-E"):
            raise RuntimeError(f"SCF nonconvergence reported by {job.name}; inspect its output before plotting.")

    bondlengths = singlet_job.results.get_pesscan_results()["RaveledPESCoords"][0]
    bondlengths = Units.convert(bondlengths, "bohr", "angstrom")

    singlet_pes = singlet_job.results.get_pesscan_results()["PES"]
    triplet_pes = triplet_job.results.get_pesscan_results()["PES"]
    hybrid_pes = hybrid_job.results.get_pesscan_results()["PES"]
    hybrid_pes = [
        x - 0.005 for x in hybrid_pes
    ]  # slightly downshift for visual clarity when plotting
    optimizespin_pes = optimizespin_job.results.get_pesscan_results()["PES"]
    optimizespin_pes = [
        x - 0.010 for x in optimizespin_pes
    ]  # slightly downshift for visual clarity when plotting

    fig, ax = plt.subplots()
    ax.plot(bondlengths, singlet_pes)
    ax.plot(bondlengths, triplet_pes)
    ax.plot(bondlengths, hybrid_pes)
    ax.plot(bondlengths, optimizespin_pes)
    ax.set_title("PES Scan for hydrogen peroxide")
    ax.set_xlabel("O-O bond length (Å)")
    ax.set_ylabel("Energy (hartree)")
    ax.legend(
        [
            "Singlet",
            "Triplet",
            "Hybrid: Lowest energy (slightly shifted)",
            "ADF: optimized spin (slightly shifted)",
        ]
    )
    fig.savefig("pesplot.png")
    return ax

Run the job#

pesscan_job = initial_pesscan()
rkf = pesscan_job.results.rkfpath()
singlet_job = replay_job(rkf, "singlet")
triplet_job = replay_job(rkf, "triplet")
hybrid_job = replay_job(rkf, "hybrid")
optimizespin_job = replay_job(rkf, "optimizespin")
# or load the finished jobs from disk:
# pesscan_job = AMSJob.load_external('plams_workdir.002/initial_pesscan/ams.rkf')
# rkf = pesscan_job.results.rkfpath()
# singlet_job = AMSJob.load_external('plams_workdir.002/singlet/ams.rkf')
# triplet_job = AMSJob.load_external('plams_workdir.002/triplet/ams.rkf')
# hybrid_job = AMSJob.load_external('plams_workdir.002/hybrid/ams.rkf')
# optimizespin_job = AMSJob.load_external('plams_workdir.002/optimizespin/ams.rkf')
[19.11|12:11:28] JOB initial_pesscan STARTED
[19.11|12:11:28] JOB initial_pesscan RUNNING
[19.11|12:11:29] JOB initial_pesscan FINISHED
[19.11|12:11:29] JOB initial_pesscan SUCCESSFUL
[19.11|12:11:29] JOB singlet STARTED
[19.11|12:11:29] JOB singlet RUNNING
[19.11|12:11:34] JOB singlet FINISHED
[19.11|12:11:34] JOB singlet SUCCESSFUL
[19.11|12:11:34] JOB triplet STARTED
[19.11|12:11:34] JOB triplet RUNNING
[19.11|12:11:40] JOB triplet FINISHED
[19.11|12:11:40] JOB triplet SUCCESSFUL
[19.11|12:11:40] JOB hybrid STARTED
[19.11|12:11:40] JOB hybrid RUNNING
[19.11|12:11:48] JOB hybrid FINISHED
[19.11|12:11:48] JOB hybrid SUCCESSFUL
[19.11|12:11:48] JOB optimizespin STARTED
[19.11|12:11:48] JOB optimizespin RUNNING
[19.11|12:12:02] JOB optimizespin FINISHED
[19.11|12:12:02] JOB optimizespin SUCCESSFUL

Plot the result#

The Hybrid engine (green) selects the lower energy from the specified singlet and triplet calculations at each geometry. ADF’s OptimizeSpinRound (red) instead searches for a stationary spin polarization and rounds the spin populations to integers. It can converge to a different electronic state and is not guaranteed to find the same minimum as the Hybrid comparison, particularly for stretched bonds. The green and red curves are shifted down slightly for visual clarity.

plot_results(singlet_job, triplet_job, hybrid_job, optimizespin_job);
image generated from notebook

See also#

Python Script#

#!/usr/bin/env python
# coding: utf-8

# ## Purpose
# Example showing the `UseLowestEnergy` feature of the Hybrid engine and the `OptimizeSpinRound` feature of the ADF engine.
# 
# A bond scan is performed on hydrogen peroxide with UFF. The resulting
# structures are then recalculated with DFT using four different setups. In
# particular, one setup uses the Hybrid engine with DynamicFactors=UseLowestEnergy.
# Another uses the ADF engine with `OptimizeSpinRound` in combination with an `ElectronicTemperature`.
# 
# All four setups use a 300 K electronic temperature to stabilize orbital occupations as the O-O bond is stretched. The same smearing is used for a consistent comparison, with MESA acceleration and up to 300 SCF iterations. These settings change the electronic occupations slightly relative to a zero-temperature calculation.
# 
# In the end, the results of energy vs. bond length are plotted.
# 
# ## Initial imports

import matplotlib.pyplot as plt
from scm.base import ChemicalSystem
from scm.inputs import ADF, AMS, ForceField, Hybrid
from scm.plams import AMSJob, Units


# ## Helper functions

def initial_pesscan():
    """Run a bond scan for hydrogen peroxide with UFF. Returns the finished job"""
    # Match the unoptimized single conformer used by PLAMS from_smiles.
    mol = ChemicalSystem.from_smiles("OO", optimize_with_uff=False, num_trial_conformers=1)
    mol.set_distance(0, 1, 1.2, unit="angstrom")  # Match the first scan point; indices are zero-based.
    s = AMS(Task="PESScan", Engine=ForceField(Type="UFF"))
    # Scan O-O bond length (atoms 1 and 2) between 1.2 and 2.5 Å
    s.PESScan.ScanCoordinate = [{"nPoints": 7, "Distance": ["2 1 1.2 2.5"]}]
    job = AMSJob(settings=s, molecule=mol, name="initial_pesscan")
    job.run()
    return job


def singlet_settings(engine_id=None):
    s = ADF(id=engine_id)
    s.Unrestricted = False
    s.XC.GGA = "PBE"
    s.Basis.Type = "DZP"
    s.SCF.Iterations = 300
    s.SCF.AccelerationMethod = "MESA"
    s.Occupations = "ElectronicTemperature=300"
    return s


def triplet_settings(engine_id=None):
    s = ADF(id=engine_id)
    s.Unrestricted = True
    s.SpinPolarization = 2
    s.XC.GGA = "PBE"
    s.Basis.Type = "DZP"
    s.SCF.Iterations = 300
    s.SCF.AccelerationMethod = "MESA"
    s.Occupations = "ElectronicTemperature=300"
    return s


def hybrid_settings():
    """Look at the file plams_workdir/hybrid/hybrid.in to see how the below is translated into text input for the hybrid engine"""
    return Hybrid(
        Energy={
            "DynamicFactors": "UseLowestEnergy",
            "Term": [
                {"Region": "*", "EngineID": "Singlet"},
                {"Region": "*", "EngineID": "Triplet"},
            ],
        },
        Engine=[singlet_settings("Singlet"), triplet_settings("Triplet")],
    )


def replay_job(rkf, engine="hybrid"):
    """Replay the structures from the UFF pesscan with ADF. Use three different engines:
    Hybrid: This will run all structures with both Singlet and Triplet and pick the lowest energy
    Singlet: This runs all structures using the Singlet settings
    Triplet: This runs all structures using the Triplet settings

    Returns the finished job
    """
    if engine == "hybrid":
        engine_settings = hybrid_settings()
    elif engine == "singlet":
        engine_settings = singlet_settings()
    elif engine == "triplet":
        engine_settings = triplet_settings()
    elif engine == "optimizespin":
        engine_settings = triplet_settings()
        engine_settings.Occupations = "ElectronicTemperature=300 OptimizeSpinRound=0.05"

    s = AMS(Task="Replay", Engine=engine_settings)
    s.Replay.File = rkf

    job = AMSJob(settings=s, name=engine)
    job.run()
    return job


def plot_results(singlet_job, triplet_job, hybrid_job, optimizespin_job):
    """
    Generate a plot of the energy vs. bond length for the four different jobs. Saves a plot to pesplot.png.
    """
    for job in (singlet_job, triplet_job, hybrid_job, optimizespin_job):
        if job.results.grep_output("SCF NOT CONVERGED|ENGINE FAILED TO SOLVE", options="-E"):
            raise RuntimeError(f"SCF nonconvergence reported by {job.name}; inspect its output before plotting.")

    bondlengths = singlet_job.results.get_pesscan_results()["RaveledPESCoords"][0]
    bondlengths = Units.convert(bondlengths, "bohr", "angstrom")

    singlet_pes = singlet_job.results.get_pesscan_results()["PES"]
    triplet_pes = triplet_job.results.get_pesscan_results()["PES"]
    hybrid_pes = hybrid_job.results.get_pesscan_results()["PES"]
    hybrid_pes = [
        x - 0.005 for x in hybrid_pes
    ]  # slightly downshift for visual clarity when plotting
    optimizespin_pes = optimizespin_job.results.get_pesscan_results()["PES"]
    optimizespin_pes = [
        x - 0.010 for x in optimizespin_pes
    ]  # slightly downshift for visual clarity when plotting

    fig, ax = plt.subplots()
    ax.plot(bondlengths, singlet_pes)
    ax.plot(bondlengths, triplet_pes)
    ax.plot(bondlengths, hybrid_pes)
    ax.plot(bondlengths, optimizespin_pes)
    ax.set_title("PES Scan for hydrogen peroxide")
    ax.set_xlabel("O-O bond length (Å)")
    ax.set_ylabel("Energy (hartree)")
    ax.legend(
        [
            "Singlet",
            "Triplet",
            "Hybrid: Lowest energy (slightly shifted)",
            "ADF: optimized spin (slightly shifted)",
        ]
    )
    fig.savefig("pesplot.png")
    return ax


# ## Run the job

pesscan_job = initial_pesscan()
rkf = pesscan_job.results.rkfpath()
singlet_job = replay_job(rkf, "singlet")
triplet_job = replay_job(rkf, "triplet")
hybrid_job = replay_job(rkf, "hybrid")
optimizespin_job = replay_job(rkf, "optimizespin")
# or load the finished jobs from disk:
# pesscan_job = AMSJob.load_external('plams_workdir.002/initial_pesscan/ams.rkf')
# rkf = pesscan_job.results.rkfpath()
# singlet_job = AMSJob.load_external('plams_workdir.002/singlet/ams.rkf')
# triplet_job = AMSJob.load_external('plams_workdir.002/triplet/ams.rkf')
# hybrid_job = AMSJob.load_external('plams_workdir.002/hybrid/ams.rkf')
# optimizespin_job = AMSJob.load_external('plams_workdir.002/optimizespin/ams.rkf')


# ## Plot the result
# 
# The Hybrid engine (green) selects the lower energy from the specified singlet and triplet calculations at each geometry. ADF's `OptimizeSpinRound` (red) instead searches for a stationary spin polarization and rounds the spin populations to integers. It can converge to a different electronic state and is not guaranteed to find the same minimum as the Hybrid comparison, particularly for stretched bonds. The green and red curves are shifted down slightly for visual clarity.

plot_results(singlet_job, triplet_job, hybrid_job, optimizespin_job);