Skip to content

relax

Relaxing a structure to a local minimum.

from chmpy import Crystal
from chmpy.calc import Calculator
from chmpy.opt import relax

crystal = Crystal.load("structure.cif")
result = relax(crystal, calculator, fmax=0.01, smax=0.05)
result.structure.save("relaxed.cif")

relax picks the parameterisation: a Crystal varies its asymmetric unit and the strains its space group allows, a Molecule varies its atoms, and a System varies atoms and cell if it has one. Anything more particular is a Coordinates object and a TrustRegion built by hand.

It runs a sequence of Stages, and by default that sequence is one. The familiar protocol of settling the internal coordinates at fixed cell before relaxing everything together is available as stages="two-stage" but is not the default, because neither argument for it holds here. The first is that the stress is expensive and should be deferred: for a model that differentiates its energy it comes out of the same backward pass as the forces, measured at under two percent of the call. The second is that the cell should not chase a geometry that is still moving, which describes an optimiser that cannot tell the two kinds of freedom apart; these are scaled to a common unit and the trust region handles them together. Measured on a molecular crystal, splitting the relaxation costs more calls than it saves.

A split still earns its keep when the stages differ in something other than which freedoms move -- a cheap potential for the first pass and an expensive one for the second -- and the Stage list is the right shape for that.

Stage dataclass

One step of a relaxation protocol.

Attributes:

Name Type Description
cell bool

vary the cell during this stage

fmax float

force convergence for this stage, eV/A

smax float

stress convergence for this stage, GPa; ignored at fixed cell

steps int

maximum iterations for this stage

hessian object

"model" builds a stretch model from the geometry, "identity" starts blind, "carry" continues from the previous stage's learned curvature (falling back to "model" for the first stage), or pass an array

name str

what to call it in the log

Source code in chmpy/opt/relax.py
@dataclass
class Stage:
    """One step of a relaxation protocol.

    Attributes:
        cell: vary the cell during this stage
        fmax: force convergence for this stage, eV/A
        smax: stress convergence for this stage, GPa; ignored at fixed cell
        steps: maximum iterations for this stage
        hessian: "model" builds a stretch model from the geometry, "identity"
            starts blind, "carry" continues from the previous stage's learned
            curvature (falling back to "model" for the first stage), or pass an
            array
        name: what to call it in the log
    """

    cell: bool = True
    fmax: float = 0.01
    smax: float = 0.05
    steps: int = 200
    hessian: object = "model"
    name: str = ""

coordinates_for(structure, cell=True, symmetry=True, fixed=None, info=None)

The degrees of freedom to relax a structure with.

Parameters:

Name Type Description Default
structure

a Crystal, Molecule or System

required
cell bool

vary the cell. Ignored for anything not periodic.

True
symmetry bool

for a Crystal, vary the asymmetric unit and the strains its space group allows. With this off the crystal is relaxed in P1 and its symmetry is free to break.

True
fixed

boolean mask of atoms to hold still -- over the asymmetric unit when symmetry is on, over the unit cell otherwise

None
info

model inputs that are not geometry, e.g. a charge or a spin, carried on the System the calculator sees

None

Returns:

Type Description

a Coordinates

Source code in chmpy/opt/relax.py
def coordinates_for(
    structure, cell: bool = True, symmetry: bool = True, fixed=None, info=None
):
    """The degrees of freedom to relax a structure with.

    Args:
        structure: a `Crystal`, `Molecule` or `System`
        cell: vary the cell. Ignored for anything not periodic.
        symmetry: for a `Crystal`, vary the asymmetric unit and the strains its
            space group allows. With this off the crystal is relaxed in P1 and
            its symmetry is free to break.
        fixed: boolean mask of atoms to hold still -- over the asymmetric unit
            when symmetry is on, over the unit cell otherwise
        info: model inputs that are not geometry, e.g. a charge or a spin,
            carried on the `System` the calculator sees

    Returns:
        a `Coordinates`
    """
    if symmetry and hasattr(structure, "space_group"):
        return SymmetryAdapted(structure, cell=cell, fixed=fixed, info=info)

    system = _as_system(structure, info)
    if not system.periodic or not cell:
        return Atomic(system, fixed=fixed)
    basis = strain_basis_for(structure, symmetry=symmetry)
    return AtomicStrain(system, basis=basis, fixed=fixed)

relax(structure, calculator, *, cell=True, symmetry=True, fixed=None, info=None, fmax=0.01, smax=0.05, steps=200, pressure=0.0, options=None, hessian='model', stages=None, progress=None)

Relax a structure to a local minimum.

Parameters:

Name Type Description Default
structure

a Crystal, Molecule or System

required
calculator

a chmpy.calc.Calculator

required
cell bool

vary the cell as well as the atoms

True
symmetry bool

keep a crystal's space group, exactly, by making the asymmetric unit the degrees of freedom

True
fixed

boolean mask of atoms to hold still

None
info

model inputs that are not geometry -- a charge, a spin, an external field -- carried on the System the calculator sees. Models that need them fail without them.

None
fmax float

force convergence in eV/A

0.01
smax float

stress convergence in GPa

0.05
steps int

maximum iterations per stage

200
pressure float

external hydrostatic pressure in GPa, so the objective is the enthalpy E + PV rather than the energy

0.0
options

TrustRegionOptions, or None for the defaults

None
hessian

the starting curvature model for a single-stage run: "model", "identity", or an array

'model'
stages

a list of Stage, or "two-stage" for the fixed-cell-then- variable-cell protocol. The default is a single stage, which was measured to be as good or better -- see the module docstring.

None
progress

True to print each step, or a callable given a chmpy.opt.progress.Progress per event; see chmpy.opt.progress

None

Returns:

Type Description
Relaxation

a Relaxation, whose structure is of the same kind as the input and

Relaxation

whose stages holds one Relaxation per stage that ran -- one for the

Relaxation

default protocol, and none for stages skipped as having no freedoms

Source code in chmpy/opt/relax.py
def relax(
    structure,
    calculator,
    *,
    cell: bool = True,
    symmetry: bool = True,
    fixed=None,
    info=None,
    fmax: float = 0.01,
    smax: float = 0.05,
    steps: int = 200,
    pressure: float = 0.0,
    options=None,
    hessian="model",
    stages=None,
    progress=None,
) -> Relaxation:
    """Relax a structure to a local minimum.

    Args:
        structure: a `Crystal`, `Molecule` or `System`
        calculator: a `chmpy.calc.Calculator`
        cell: vary the cell as well as the atoms
        symmetry: keep a crystal's space group, exactly, by making the
            asymmetric unit the degrees of freedom
        fixed: boolean mask of atoms to hold still
        info: model inputs that are not geometry -- a charge, a spin, an
            external field -- carried on the `System` the calculator sees.
            Models that need them fail without them.
        fmax: force convergence in eV/A
        smax: stress convergence in GPa
        steps: maximum iterations per stage
        pressure: external hydrostatic pressure in GPa, so the objective is the
            enthalpy `E + PV` rather than the energy
        options: `TrustRegionOptions`, or None for the defaults
        hessian: the starting curvature model for a single-stage run: "model",
            "identity", or an array
        stages: a list of `Stage`, or "two-stage" for the fixed-cell-then-
            variable-cell protocol. The default is a single stage, which was
            measured to be as good or better -- see the module docstring.
        progress: True to print each step, or a callable given a
            `chmpy.opt.progress.Progress` per event; see `chmpy.opt.progress`

    Returns:
        a `Relaxation`, whose `structure` is of the same kind as the input and
        whose `stages` holds one `Relaxation` per stage that ran -- one for the
        default protocol, and none for stages skipped as having no freedoms
    """
    _check_hessian(hessian)
    plan = _plan(stages, structure, cell, fmax, smax, steps, hessian)

    report = reporter(progress)
    current = structure
    carried = None
    finished = []
    for number, stage in enumerate(plan):
        coordinates = coordinates_for(
            current, cell=stage.cell, symmetry=symmetry, fixed=fixed, info=info
        )
        if coordinates.n_dof == 0:
            # nothing to vary -- a fixed-cell stage for a structure whose atoms
            # are all on special positions, say. Evaluating it would cost a
            # call to say so.
            continue
        # only label and count stages when there is more than one
        staged = len(plan) > 1
        name = stage.name or f"stage {number + 1}"
        report(
            "relax",
            name,
            f"relax {name}: {coordinates!r}" if staged else f"relax {coordinates!r}",
            index=number if staged else None,
            total=len(plan) if staged else None,
        )
        optimiser = TrustRegion(
            coordinates,
            calculator,
            options=options,
            pressure=pressure,
            hessian=_starting_hessian(stage.hessian, coordinates, carried),
        )
        outcome = optimiser.run(
            fmax=stage.fmax,
            smax=stage.smax,
            steps=stage.steps,
            progress=report.nested("relax", name),
        )
        if staged:
            report(
                "relax", name, f"{outcome!r}", index=number, total=len(plan), done=True
            )
        outcome.structure = _rebuild(current, coordinates)
        current = outcome.structure
        carried = outcome.model
        finished.append(outcome)

    if not finished:
        raise ValueError(
            "this structure has no degrees of freedom to relax: every atom is "
            "fixed or on a special position, and the cell is not being varied"
        )
    return _combine(finished)

two_stage(fmax=0.01, smax=0.05, steps=200)

Settle the atoms at fixed cell, then relax the cell with them.

Parameters:

Name Type Description Default
fmax float

final force convergence, eV/A

0.01
smax float

final stress convergence, GPa

0.05
steps int

maximum iterations per stage

200

Returns:

Type Description
list[Stage]

two Stages

Source code in chmpy/opt/relax.py
def two_stage(fmax: float = 0.01, smax: float = 0.05, steps: int = 200) -> list[Stage]:
    """Settle the atoms at fixed cell, then relax the cell with them.

    Args:
        fmax: final force convergence, eV/A
        smax: final stress convergence, GPa
        steps: maximum iterations per stage

    Returns:
        two `Stage`s
    """
    return [
        Stage(
            cell=False,
            fmax=PRERELAX_FACTOR * fmax,
            steps=steps,
            hessian="model",
            name="fixed cell",
        ),
        Stage(
            cell=True,
            fmax=fmax,
            smax=smax,
            steps=steps,
            hessian="carry",
            name="variable cell",
        ),
    ]