Skip to content

elastic

Elastic constants by finite strain.

C_ij = (1/V) d2E / de_i de_j is computed by straining the cell in each direction, relaxing the atoms at fixed cell, and differencing the stress.

  • Relaxed atoms. relax_atoms=True (the default) relaxes the atoms at every strained geometry. Clamped-atom constants can be much stiffer, particularly for molecular crystals.
  • Strain selection. Since C (R e R^T) = R (C e) R^T, one strain gives the response for its whole point-group orbit. Only strains not already covered are applied (2 for cubic, 3 for hexagonal, 6 for triclinic), and the tensor is a least-squares fit over all rotated responses.
  • Subgroup relaxation. A strain keeps the operations with R eps R^T = eps, and the atoms relax within that subgroup (chmpy.opt.symmetry.InvariantAtomic). This cannot find a lower-symmetry minimum if the reference is a saddle point in P1; tensor.is_stable() will usually flag that, and symmetry=False relaxes in P1.
  • Projection. The result is projected onto the tensors the point group allows. symmetry_residual reports the larger of the fit misfit and the size of that projection, and asymmetry the largest |C_ij - C_ji|; both are noise estimates.

method="hessian" gets the same relaxed-ion tensor without relaxing anything: C = C0 - L^T Phi^+ L / V from the clamped-ion constants, the internal-strain tensor and the Gamma-point Hessian, every piece one central difference and the lot one batch of evaluations. See hessian_elastic_tensor.

ElasticResult dataclass

An elastic tensor and how much to believe it.

Attributes:

Name Type Description
tensor object

the chmpy.ext.elastic_tensor.ElasticTensor, in GPa

evaluations int

calculator evaluations used

relaxed_atoms bool

whether the atoms were relaxed at each strain

residual_stress float

largest stress component of the reference structure in GPa. Elastic constants are defined at equilibrium; a large value here means the answer is not the quantity it is called.

asymmetry float

largest |C_ij - C_ji| before the tensor was symmetrised, in GPa. The two are computed from different strain columns and must agree for a conservative model, so their difference is noise. This estimate exists for every crystal system.

symmetry_residual float

how far the measured stresses are from what the point group allows, in GPa (fit misfit or projection size, whichever is larger). Always zero for triclinic.

n_independent int

independent elastic constants the point group allows

strain float

the engineering strain used

strains tuple

Voigt indices actually applied

method str

"strain" (finite strain, atoms relaxed at each) or "hessian" (clamped-ion constants corrected through the internal-strain tensor and the Gamma-point Hessian)

internal_strain_noise float | None

for "hessian", the disagreement between the internal-strain tensor measured from strained cells and from displaced ones, propagated into the constants, in GPa

clamped ndarray | None

for "hessian", the clamped-ion tensor C0 in GPa

Source code in chmpy/opt/elastic.py
@dataclass
class ElasticResult:
    """An elastic tensor and how much to believe it.

    Attributes:
        tensor: the `chmpy.ext.elastic_tensor.ElasticTensor`, in GPa
        evaluations: calculator evaluations used
        relaxed_atoms: whether the atoms were relaxed at each strain
        residual_stress: largest stress component of the reference structure in
            GPa. Elastic constants are defined at equilibrium; a large value
            here means the answer is not the quantity it is called.
        asymmetry: largest `|C_ij - C_ji|` before the tensor was symmetrised,
            in GPa. The two are computed from different strain columns and must
            agree for a conservative model, so their difference is noise. This
            estimate exists for every crystal system.
        symmetry_residual: how far the measured stresses are from what the
            point group allows, in GPa (fit misfit or projection size, whichever
            is larger). Always zero for triclinic.
        n_independent: independent elastic constants the point group allows
        strain: the engineering strain used
        strains: Voigt indices actually applied
        method: "strain" (finite strain, atoms relaxed at each) or "hessian"
            (clamped-ion constants corrected through the internal-strain
            tensor and the Gamma-point Hessian)
        internal_strain_noise: for "hessian", the disagreement between the
            internal-strain tensor measured from strained cells and from
            displaced ones, propagated into the constants, in GPa
        clamped: for "hessian", the clamped-ion tensor C0 in GPa
    """

    tensor: object
    evaluations: int
    relaxed_atoms: bool
    residual_stress: float
    asymmetry: float
    symmetry_residual: float
    n_independent: int
    strain: float
    relaxations: list = field(default_factory=list)
    strains: tuple = (0, 1, 2, 3, 4, 5)
    method: str = "strain"
    internal_strain_noise: float | None = None
    clamped: np.ndarray | None = None

    @property
    def c_voigt(self) -> np.ndarray:
        "(6, 6) elastic constants in GPa"
        return self.tensor.c_voigt

    @property
    def noise(self) -> float:
        "The largest of the free error estimates, in GPa"
        return max(
            self.asymmetry, self.symmetry_residual, self.internal_strain_noise or 0.0
        )

    @property
    def noise_fraction(self) -> float:
        """Estimated noise as a fraction of the largest constant.

        Two measurements come free with the calculation, and the larger is
        taken. Above a few percent the tensor is not converged: the strain was
        too small for the stress response to clear the calculator's noise, or
        the atomic relaxation was not run hard enough, or both.
        """
        largest = float(np.abs(self.c_voigt).max())
        return self.noise / largest if largest > 0 else 0.0

    def __repr__(self) -> str:
        return (
            f"<ElasticResult {self.method}, {self.n_independent} independent "
            f"constants, {len(self.strains)} strains, {self.evaluations} "
            f"evaluations, symmetry residual {self.symmetry_residual:.3g} GPa>"
        )

    def __str__(self) -> str:
        averages = self.tensor.averages()
        return "\n".join(
            [
                repr(self),
                repr(self.tensor),
                f"bulk modulus  (Hill) {averages['bulk_modulus_avg']['hill']:8.3f} GPa",
                f"shear modulus (Hill) {averages['shear_modulus_avg']['hill']:8.3f} GPa",
                f"stable: {self.tensor.is_stable()}, "
                f"noise {100 * self.noise_fraction:.1f}% of the largest constant",
            ]
        )

c_voigt property

(6, 6) elastic constants in GPa

noise property

The largest of the free error estimates, in GPa

noise_fraction property

Estimated noise as a fraction of the largest constant.

Two measurements come free with the calculation, and the larger is taken. Above a few percent the tensor is not converged: the strain was too small for the stress response to clear the calculator's noise, or the atomic relaxation was not run hard enough, or both.

StrainPoint dataclass

One strained cell of a finite-strain elastic tensor.

Attributes:

Name Type Description
index int

engineering Voigt component, 0-5 (xx yy zz yz xz xy)

sign int

+1 or -1

strain float

the engineering strain magnitude

system System

the reference cell under this strain, atoms carried affinely and not yet relaxed

Source code in chmpy/opt/elastic.py
@dataclass(frozen=True)
class StrainPoint:
    """One strained cell of a finite-strain elastic tensor.

    Attributes:
        index: engineering Voigt component, 0-5 (xx yy zz yz xz xy)
        sign: +1 or -1
        strain: the engineering strain magnitude
        system: the reference cell under this strain, atoms carried affinely
            and not yet relaxed
    """

    index: int
    sign: int
    strain: float
    system: System

    @property
    def name(self) -> str:
        "A label fit for a directory name, e.g. 'voigt3_minus'"
        return f"voigt{self.index}_{'plus' if self.sign > 0 else 'minus'}"

name property

A label fit for a directory name, e.g. 'voigt3_minus'

elastic_from_stresses(stresses, *, strain, rotations=None, reference_stress=None, relaxed_atoms=True)

Fit an elastic tensor to stresses computed elsewhere.

The counterpart of strain_points: every Voigt index present must have both its + and - stress, and together they must cover the strains independent_strains(rotations) asks for. Extra indices are used in the fit.

Parameters:

Name Type Description Default
stresses

mapping of (voigt index, sign) to the (3, 3) stress in eV/A^3, ASE sign convention ((1/V) dE/deps, negative under compression)

required
strain float

the engineering strain the cells were built with

required
rotations

(M, 3, 3) Cartesian point operations in the frame of the strained cells; None or empty for no symmetry

None
reference_stress

(3, 3) stress of the unstrained cell in eV/A^3, if computed; reported as residual_stress

None
relaxed_atoms bool

whether the atoms were relaxed at each strained cell, recorded on the result

True

Returns:

Type Description
ElasticResult

ElasticResult, with evaluations the number of stresses used

Source code in chmpy/opt/elastic.py
def elastic_from_stresses(
    stresses,
    *,
    strain: float,
    rotations=None,
    reference_stress=None,
    relaxed_atoms: bool = True,
) -> ElasticResult:
    """Fit an elastic tensor to stresses computed elsewhere.

    The counterpart of `strain_points`: every Voigt index present must have
    both its `+` and `-` stress, and together they must cover the strains
    `independent_strains(rotations)` asks for. Extra indices are used in the
    fit.

    Args:
        stresses: mapping of `(voigt index, sign)` to the (3, 3) stress in
            eV/A^3, ASE sign convention (`(1/V) dE/deps`, negative under
            compression)
        strain: the engineering strain the cells were built with
        rotations: (M, 3, 3) Cartesian point operations in the frame of the
            strained cells; None or empty for no symmetry
        reference_stress: (3, 3) stress of the unstrained cell in eV/A^3, if
            computed; reported as `residual_stress`
        relaxed_atoms: whether the atoms were relaxed at each strained cell,
            recorded on the result

    Returns:
        ElasticResult, with `evaluations` the number of stresses used
    """
    rotations = _rotations_for(None, rotations, True)
    indices = sorted({index for index, _ in stresses})
    unpaired = [i for i in indices if (i, 1) not in stresses or (i, -1) not in stresses]
    if unpaired:
        raise ValueError(
            f"Voigt strains {unpaired} have only one of their +/- stresses"
        )
    missing = sorted(set(independent_strains(rotations)) - set(indices))
    if missing:
        raise ValueError(
            f"the stresses do not cover Voigt strains {missing}, which the point "
            "group needs"
        )
    responses = []
    for index in indices:
        plus = np.asarray(stresses[(index, 1)], dtype=float)
        minus = np.asarray(stresses[(index, -1)], dtype=float)
        response = _stress_voigt(plus - minus) / (2.0 * strain)
        responses.append((index, response * EV_PER_ANGSTROM3_TO_GPA))

    basis = invariant_elastic_basis(rotations)
    voigt, asymmetry, symmetry_residual = _fit_and_project(responses, rotations, basis)
    largest = float(np.abs(voigt).max())
    noise = max(asymmetry, symmetry_residual)
    if largest > 0 and noise > NOISE_WARNING * largest:
        _warn_about_noise(noise, largest, strain, float("nan"))

    residual = float("nan")
    if reference_stress is not None:
        residual = float(np.abs(reference_stress).max() * EV_PER_ANGSTROM3_TO_GPA)

    from chmpy.ext.elastic_tensor import ElasticTensor

    return ElasticResult(
        tensor=ElasticTensor(voigt),
        evaluations=2 * len(indices),
        relaxed_atoms=relaxed_atoms,
        residual_stress=residual,
        asymmetry=asymmetry,
        symmetry_residual=symmetry_residual,
        n_independent=len(basis),
        strain=float(strain),
        strains=tuple(indices),
    )

elastic_tensor(structure, calculator, *, strain=DEFAULT_STRAIN, relax_atoms=True, symmetry=True, rotations=None, info=None, fmax=0.01, steps=200, progress=None, method='strain', displacement=DEFAULT_DISPLACEMENT, force_constants=None)

Compute the elastic tensor of a relaxed structure.

The structure should already be relaxed: elastic constants are second derivatives at a minimum, and a residual stress makes them ambiguous. residual_stress on the result says how well that held.

Parameters:

Name Type Description Default
structure

a relaxed Crystal or System

required
calculator

a chmpy.calc.Calculator

required
strain float

engineering strain magnitude for the finite difference, or "auto" to try successively larger ones until the tensor's own noise estimate falls below a few percent. A strain too small for the stress response to clear the calculator's noise is the usual reason an elastic tensor comes out wrong, and how small is too small depends on the calculator, not on the structure.

DEFAULT_STRAIN
relax_atoms bool

relax the atoms at each strained cell. Leave this on unless you specifically want clamped-atom constants.

True
symmetry bool

use the point group to choose the strains, relax the atoms within the subgroup each strain preserves, and project the result onto the tensors the point group allows. When False, all six strains are applied and the atoms relax in P1.

True
rotations

(M, 3, 3) Cartesian point operations. Taken from a Crystal's space group by default. With a System they are used for strain selection and projection only; the atoms relax in P1.

None
info

model inputs that are not geometry, carried on every System the calculator sees

None
fmax float

force convergence for the atomic relaxations, eV/A

0.01
steps int

iteration cap for each atomic relaxation

200
progress

True to print progress, or a callable given a chmpy.opt.progress.Progress per event. Each strain point is a stage; the atomic relaxation at it is nested inside.

None
method str

"strain" relaxes the atoms at each strained cell. "hessian" relaxes none: it takes the clamped-ion constants from strained cells and corrects them with the internal-strain tensor and the Gamma-point Hessian, C = C0 - L^T Phi^+ L / V, all from one batch of finite differences. Much cheaper, and exact to second order; see hessian_elastic_tensor.

'strain'
displacement float

atomic finite-difference step for method="hessian", A

DEFAULT_DISPLACEMENT
force_constants

for method="hessian", ForceConstants already measured for this structure (any supercell); only the strained cells are then computed

None

Returns:

Type Description
ElasticResult

ElasticResult

Source code in chmpy/opt/elastic.py
def elastic_tensor(
    structure,
    calculator,
    *,
    strain: float = DEFAULT_STRAIN,
    relax_atoms: bool = True,
    symmetry: bool = True,
    rotations=None,
    info=None,
    fmax: float = 0.01,
    steps: int = 200,
    progress=None,
    method: str = "strain",
    displacement: float = DEFAULT_DISPLACEMENT,
    force_constants=None,
) -> ElasticResult:
    """Compute the elastic tensor of a relaxed structure.

    The structure should already be relaxed: elastic constants are second
    derivatives *at* a minimum, and a residual stress makes them ambiguous.
    `residual_stress` on the result says how well that held.

    Args:
        structure: a relaxed `Crystal` or `System`
        calculator: a `chmpy.calc.Calculator`
        strain: engineering strain magnitude for the finite difference, or
            "auto" to try successively larger ones until the tensor's own
            noise estimate falls below a few percent. A strain too small for
            the stress response to clear the calculator's noise is the usual
            reason an elastic tensor comes out wrong, and how small is too
            small depends on the calculator, not on the structure.
        relax_atoms: relax the atoms at each strained cell. Leave this on unless
            you specifically want clamped-atom constants.
        symmetry: use the point group to choose the strains, relax the atoms
            within the subgroup each strain preserves, and project the result
            onto the tensors the point group allows. When False, all six
            strains are applied and the atoms relax in P1.
        rotations: (M, 3, 3) Cartesian point operations. Taken from a
            `Crystal`'s space group by default. With a `System` they are used
            for strain selection and projection only; the atoms relax in P1.
        info: model inputs that are not geometry, carried on every `System`
            the calculator sees
        fmax: force convergence for the atomic relaxations, eV/A
        steps: iteration cap for each atomic relaxation
        progress: True to print progress, or a callable given a
            `chmpy.opt.progress.Progress` per event. Each strain point is a
            stage; the atomic relaxation at it is nested inside.
        method: "strain" relaxes the atoms at each strained cell. "hessian"
            relaxes none: it takes the clamped-ion constants from strained
            cells and corrects them with the internal-strain tensor and the
            Gamma-point Hessian, `C = C0 - L^T Phi^+ L / V`, all from one batch
            of finite differences. Much cheaper, and exact to second order;
            see `hessian_elastic_tensor`.
        displacement: atomic finite-difference step for method="hessian", A
        force_constants: for method="hessian", `ForceConstants` already
            measured for this structure (any supercell); only the strained
            cells are then computed

    Returns:
        ElasticResult
    """
    if method == "hessian":
        return hessian_elastic_tensor(
            structure,
            calculator,
            strain=HESSIAN_STRAIN if strain == "auto" else strain,
            displacement=displacement,
            symmetry=symmetry,
            rotations=rotations,
            info=info,
            force_constants=force_constants,
            progress=progress,
        )
    if method != "strain":
        raise ValueError(f"unknown method {method!r}, expected 'strain' or 'hessian'")
    system = _as_system(structure, info)
    if not system.periodic:
        raise ValueError("elastic constants need a periodic structure")

    rotations = _rotations_for(structure, rotations, symmetry)
    basis = invariant_elastic_basis(rotations)
    atom_map = (
        crystal_atom_map(structure, system)
        if symmetry and hasattr(structure, "space_group")
        else None
    )
    strains = independent_strains(rotations)

    reference_cell = np.array(system.cell)
    reference_scaled = system.scaled_positions
    started = calculator.stats.calls

    reference = calculator(system, ("energy", "stress"))
    residual = reference.smax
    if residual > RESIDUAL_STRESS_WARNING:
        LOG.warning(
            "the reference structure carries %.3f GPa of stress; elastic "
            "constants are defined at equilibrium, so relax it first",
            residual,
        )

    report = reporter(progress)
    report(
        "elastic",
        "setup",
        f"elastic tensor: {len(strains)} of 6 strains needed "
        f"(Voigt {', '.join(str(index) for index in strains)}), "
        f"{len(basis)} independent constants",
    )

    attempts = AUTO_STRAINS if strain == "auto" else (float(strain),)
    for attempt, size in enumerate(attempts):
        responses, relaxations = _strain_sweep(
            system,
            calculator,
            reference_cell,
            reference_scaled,
            strains,
            size,
            relax_atoms,
            fmax,
            steps,
            report,
            atom_map,
        )
        voigt, asymmetry, symmetry_residual = _fit_and_project(
            responses, rotations, basis
        )

        largest = float(np.abs(voigt).max())
        noise = max(asymmetry, symmetry_residual)
        converged = largest > 0 and noise <= NOISE_WARNING * largest
        if converged or attempt == len(attempts) - 1:
            break
        LOG.info(
            "strain %.3f left %.0f%% noise in the elastic tensor; trying %.3f",
            size,
            100 * noise / largest,
            attempts[attempt + 1],
        )
        report(
            "elastic",
            "auto strain",
            f"strain {size:g} left {100 * noise / largest:.0f}% noise; "
            f"trying {attempts[attempt + 1]:g}",
        )

    if not converged:
        _warn_about_noise(noise, largest, size, fmax)

    from chmpy.ext.elastic_tensor import ElasticTensor

    return ElasticResult(
        tensor=ElasticTensor(voigt),
        evaluations=calculator.stats.calls - started,
        relaxed_atoms=relax_atoms,
        residual_stress=residual,
        asymmetry=asymmetry,
        symmetry_residual=symmetry_residual,
        n_independent=len(basis),
        strain=size,
        relaxations=relaxations,
        strains=tuple(strains),
    )

fit_elastic(responses, rotations)

Least-squares Voigt tensor from strain responses and their rotations.

Each (index, response) is the stress per unit engineering strain along Voigt direction index; each rotation adds the pair (R e R^T, R s R^T).

Returns:

Type Description

(raw (6, 6) tensor, largest residual of the fit). The residual is

nonzero only when responses disagree with the symmetry.

Source code in chmpy/opt/elastic.py
def fit_elastic(responses, rotations):
    """Least-squares Voigt tensor from strain responses and their rotations.

    Each `(index, response)` is the stress per unit engineering strain along
    Voigt direction `index`; each rotation adds the pair `(R e R^T, R s R^T)`.

    Returns:
        (raw (6, 6) tensor, largest residual of the fit). The residual is
        nonzero only when responses disagree with the symmetry.
    """
    rotations = _with_identity(rotations)
    strains, stresses = [], []
    for index, response in responses:
        strain = voigt_strain(index, 1.0)
        stress = _tensor_from_voigt(response)
        for rotation in rotations:
            strains.append(_engineering_voigt(rotation @ strain @ rotation.T))
            stresses.append(_stress_voigt(rotation @ stress @ rotation.T))
    strains, stresses = np.array(strains).T, np.array(stresses).T
    tensor = stresses @ np.linalg.pinv(strains)
    misfit = float(np.abs(tensor @ strains - stresses).max(initial=0.0))
    return tensor, misfit

hessian_elastic_tensor(structure, calculator, *, strain=HESSIAN_STRAIN, displacement=DEFAULT_DISPLACEMENT, symmetry=True, rotations=None, info=None, force_constants=None, progress=None)

Relaxed-ion elastic constants from second derivatives, without relaxing.

Expanding the energy to second order in the strain e and the internal displacements u and minimising over u gives

C = C0 - (1/V) L^T Phi^+ L

with C0 the clamped-ion constants (stress response at fixed fractional coordinates), Phi the Gamma-point Hessian of the cell, and L = d2E/du de the internal-strain tensor. Every piece is a central difference, so the whole calculation is one batch of independent evaluations: the symmetry-unique displacements of the unit cell for Phi, and twelve strained cells for C0 and L.

L is measured twice -- as -dF/de on every atom from the strained cells, and as d(virial)/du from the displaced ones, completed by symmetry -- and the two have to agree. Their average is used, and half the difference between the tensors each gives is internal_strain_noise on the result. The three uniform translations are projected out of Phi before it is inverted, which is where the acoustic sum rule comes in.

Parameters:

Name Type Description Default
structure

a relaxed Crystal or System

required
calculator

a chmpy.calc.Calculator; every evaluation goes through one calculator.batch call, which falls back to evaluating one at a time for calculators without a native batch path

required
strain float

engineering strain for C0 and L

HESSIAN_STRAIN
displacement float

atomic step for Phi, Angstroms

DEFAULT_DISPLACEMENT
symmetry bool

displace only symmetry-unique atoms, fold L onto the space group, and project C onto the point group

True
rotations

(M, 3, 3) Cartesian point operations, as for elastic_tensor

None
info

model inputs that are not geometry

None
force_constants

ForceConstants already measured for this structure; their Gamma-point Hessian is used and only the strained cells are computed

None
progress

as for elastic_tensor

None

Returns:

Type Description
ElasticResult

ElasticResult with method="hessian"

Source code in chmpy/opt/elastic.py
def hessian_elastic_tensor(
    structure,
    calculator,
    *,
    strain: float = HESSIAN_STRAIN,
    displacement: float = DEFAULT_DISPLACEMENT,
    symmetry: bool = True,
    rotations=None,
    info=None,
    force_constants=None,
    progress=None,
) -> ElasticResult:
    """Relaxed-ion elastic constants from second derivatives, without relaxing.

    Expanding the energy to second order in the strain `e` and the internal
    displacements `u` and minimising over `u` gives

        C = C0 - (1/V) L^T Phi^+ L

    with `C0` the clamped-ion constants (stress response at fixed fractional
    coordinates), `Phi` the Gamma-point Hessian of the cell, and
    `L = d2E/du de` the internal-strain tensor. Every piece is a central
    difference, so the whole calculation is one batch of independent
    evaluations: the symmetry-unique displacements of the unit cell for
    `Phi`, and twelve strained cells for `C0` and `L`.

    `L` is measured twice -- as `-dF/de` on every atom from the strained
    cells, and as `d(virial)/du` from the displaced ones, completed by
    symmetry -- and the two have to agree. Their average is used, and half
    the difference between the tensors each gives is `internal_strain_noise`
    on the result. The three uniform translations are projected out of `Phi`
    before it is inverted, which is where the acoustic sum rule comes in.

    Args:
        structure: a relaxed `Crystal` or `System`
        calculator: a `chmpy.calc.Calculator`; every evaluation goes through
            one `calculator.batch` call, which falls back to evaluating one
            at a time for calculators without a native batch path
        strain: engineering strain for `C0` and `L`
        displacement: atomic step for `Phi`, Angstroms
        symmetry: displace only symmetry-unique atoms, fold `L` onto the
            space group, and project `C` onto the point group
        rotations: (M, 3, 3) Cartesian point operations, as for
            `elastic_tensor`
        info: model inputs that are not geometry
        force_constants: `ForceConstants` already measured for this
            structure; their Gamma-point Hessian is used and only the strained
            cells are computed
        progress: as for `elastic_tensor`

    Returns:
        ElasticResult with method="hessian"
    """
    from chmpy.ext.elastic_tensor import ElasticTensor
    from chmpy.vib.force_constants import DisplacementPlan

    system = _as_system(structure, info)
    if not system.periodic:
        raise ValueError("elastic constants need a periodic structure")
    n = len(system)
    volume = system.volume
    rotations = _rotations_for(structure, rotations, symmetry)
    basis = invariant_elastic_basis(rotations)
    has_group = symmetry and hasattr(structure, "space_group")
    started = calculator.stats.calls

    reference = calculator(system, ("energy", "stress"))
    residual = reference.smax
    if residual > RESIDUAL_STRESS_WARNING:
        LOG.warning(
            "the reference structure carries %.3f GPa of stress; elastic "
            "constants are defined at equilibrium, so relax it first",
            residual,
        )

    cell, scaled = np.array(system.cell), system.scaled_positions
    strained = []
    for index in range(6):
        for sign in (1, -1):
            deformation = np.eye(3) + voigt_strain(index, sign * strain)
            strained.append(
                System(
                    system.numbers,
                    scaled @ (cell @ deformation),
                    cell @ deformation,
                    True,
                    dict(system.info),
                )
            )
    plan = None
    displaced = []
    if force_constants is None:
        plan = DisplacementPlan(structure, system, (1, 1, 1), symmetry, displacement)
        displaced = plan.systems()

    report = reporter(progress)
    report(
        "elastic",
        "setup",
        f"elastic tensor from the Hessian: {len(displaced)} displaced and "
        f"{len(strained)} strained cells in one batch, "
        f"{len(basis)} independent constants",
    )
    results = calculator.batch(displaced + strained, ("energy", "forces", "stress"))
    moved, deformed = results[: len(displaced)], results[len(displaced) :]

    if plan is not None:
        force_constants = plan.solve([result.forces for result in moved])
    hessian = force_constants.gamma_hessian()
    if hessian.shape != (3 * n, 3 * n):
        raise ValueError(
            f"the force constants are for {hessian.shape[0] // 3} atoms, the "
            f"structure has {n}"
        )

    # clamped-ion constants and the internal-strain tensor, one strain column
    # at a time
    clamped = np.zeros((6, 6))
    internal = np.zeros((3 * n, 6))
    for index in range(6):
        plus, minus = deformed[2 * index], deformed[2 * index + 1]
        clamped[:, index] = (plus.stress_voigt - minus.stress_voigt) / (2 * strain)
        internal[:, index] = -(plus.forces - minus.forces).ravel() / (2 * strain)
    if has_group:
        from .symmetry import crystal_atom_map

        internal = _symmetrise_internal_strain(
            internal, crystal_atom_map(structure, system), cell
        )

    # the same tensor from the other side: d(virial)/du along each
    # displacement made, completed by symmetry. The two estimates of C differ
    # only through L, so half their difference is what L's noise costs.
    correction = _relaxation_correction(hessian, internal, n) / volume
    internal_noise = None
    if plan is not None:
        from_displacements = _internal_strain_from_displacements(plan, moved, volume)
        if has_group:
            from_displacements = _symmetrise_internal_strain(
                from_displacements, plan.atom_map, cell
            )
        other = _relaxation_correction(hessian, from_displacements, n) / volume
        internal_noise = (
            0.5 * float(np.abs(other - correction).max()) * EV_PER_ANGSTROM3_TO_GPA
        )
        correction = (
            _relaxation_correction(hessian, 0.5 * (internal + from_displacements), n)
            / volume
        )

    raw = (clamped - correction) * EV_PER_ANGSTROM3_TO_GPA
    asymmetry = float(np.abs(raw - raw.T).max())
    voigt = 0.5 * (raw + raw.T)
    symmetry_residual = 0.0
    if symmetry:
        projected = elastic_to_voigt(project_elastic(elastic_from_voigt(voigt), basis))
        symmetry_residual = float(np.abs(projected - voigt).max())
        voigt = projected

    result = ElasticResult(
        tensor=ElasticTensor(voigt),
        evaluations=calculator.stats.calls - started,
        relaxed_atoms=True,
        residual_stress=residual,
        asymmetry=asymmetry,
        symmetry_residual=symmetry_residual,
        n_independent=len(basis),
        strain=strain,
        method="hessian",
        internal_strain_noise=internal_noise,
        clamped=0.5 * (clamped + clamped.T) * EV_PER_ANGSTROM3_TO_GPA,
    )
    largest = float(np.abs(voigt).max())
    if largest > 0 and result.noise > NOISE_WARNING * largest:
        _warn_about_noise(result.noise, largest, strain, float("nan"))
    return result

independent_strains(rotations)

The Voigt strains to apply, skipping any already spanned by the point-group orbits of earlier ones. Cubic gives [0, 3], hexagonal [0, 2, 3], triclinic all six.

Parameters:

Name Type Description Default
rotations

(M, 3, 3) Cartesian point operations, or empty for none

required

Returns:

Type Description
list[int]

Voigt indices, in increasing order

Source code in chmpy/opt/elastic.py
def independent_strains(rotations) -> list[int]:
    """The Voigt strains to apply, skipping any already spanned by the
    point-group orbits of earlier ones. Cubic gives `[0, 3]`, hexagonal
    `[0, 2, 3]`, triclinic all six.

    Args:
        rotations: (M, 3, 3) Cartesian point operations, or empty for none

    Returns:
        Voigt indices, in increasing order
    """
    rotations = _with_identity(rotations)
    chosen, span, rank = [], np.zeros((0, 6)), 0
    for index in range(6):
        strain = voigt_strain(index, 1.0)
        orbit = to_vector(np.einsum("rij,jk,rlk->ril", rotations, strain, rotations))
        extended = np.vstack([span, orbit])
        extended_rank = np.linalg.matrix_rank(extended, tol=STRAIN_RANK_TOLERANCE)
        if extended_rank == rank:
            continue
        chosen.append(index)
        span, rank = extended, extended_rank
        if rank == 6:
            break
    return chosen

strain_points(structure, *, strain=DEFAULT_STRAIN, symmetry=True, rotations=None, info=None)

The strained cells elastic_tensor would visit, for another code to run.

Relax the atoms of each at fixed cell (or not, for clamped-ion constants), take the final stress, and pass the stresses to elastic_from_stresses with the same strain and rotations. Only the point-group-independent strains are listed, a + and - cell for each.

Parameters:

Name Type Description Default
structure

a relaxed Crystal or periodic System

required
strain float

engineering strain magnitude

DEFAULT_STRAIN
symmetry bool

reduce the strains with the point group; False gives all six

True
rotations

(M, 3, 3) Cartesian point operations, taken from a Crystal's space group by default

None
info

model inputs carried on every System

None

Returns:

Type Description
list[StrainPoint]

list of StrainPoint, + before - for each Voigt index

Source code in chmpy/opt/elastic.py
def strain_points(
    structure,
    *,
    strain: float = DEFAULT_STRAIN,
    symmetry: bool = True,
    rotations=None,
    info=None,
) -> list[StrainPoint]:
    """The strained cells `elastic_tensor` would visit, for another code to run.

    Relax the atoms of each at fixed cell (or not, for clamped-ion constants),
    take the final stress, and pass the stresses to `elastic_from_stresses`
    with the same `strain` and `rotations`. Only the point-group-independent
    strains are listed, a `+` and `-` cell for each.

    Args:
        structure: a relaxed `Crystal` or periodic `System`
        strain: engineering strain magnitude
        symmetry: reduce the strains with the point group; False gives all six
        rotations: (M, 3, 3) Cartesian point operations, taken from a
            `Crystal`'s space group by default
        info: model inputs carried on every `System`

    Returns:
        list of `StrainPoint`, `+` before `-` for each Voigt index
    """
    system = _as_system(structure, info)
    if not system.periodic:
        raise ValueError("elastic constants need a periodic structure")
    rotations = _rotations_for(structure, rotations, symmetry)
    cell = np.array(system.cell)
    scaled = system.scaled_positions
    return [
        StrainPoint(
            index,
            sign,
            float(strain),
            _strained(system, cell, scaled, index, sign * strain),
        )
        for index in independent_strains(rotations)
        for sign in (1, -1)
    ]

voigt_strain(index, magnitude)

The strain tensor for one engineering Voigt component.

Voigt order is xx, yy, zz, yz, xz, xy, and the shear components carry the engineering factor of two: e_3 = 2 * eps_yz, so a unit of e_3 is half a unit in each of the two off-diagonal entries.

Parameters:

Name Type Description Default
index int

0-5

required
magnitude float

the engineering strain

required

Returns:

Type Description
ndarray

(3, 3) symmetric strain tensor

Source code in chmpy/opt/elastic.py
def voigt_strain(index: int, magnitude: float) -> np.ndarray:
    """The strain tensor for one engineering Voigt component.

    Voigt order is xx, yy, zz, yz, xz, xy, and the shear components carry the
    engineering factor of two: `e_3 = 2 * eps_yz`, so a unit of `e_3` is half a
    unit in each of the two off-diagonal entries.

    Args:
        index: 0-5
        magnitude: the engineering strain

    Returns:
        (3, 3) symmetric strain tensor
    """
    strain = np.zeros((3, 3))
    if index < 3:
        strain[index, index] = magnitude
    else:
        a, b = ((1, 2), (0, 2), (0, 1))[index - 3]
        strain[a, b] = strain[b, a] = 0.5 * magnitude
    return strain