Skip to content

pymatgen

Convert an OPTIMADE structure, in the format of StructureResource to a pymatgen Molecule or Structure object.

This conversion function relies on the pymatgen package.

For more information on the pymatgen code see their documentation.

from_pymatgen(pmg_structure)

Convert a pymatgen Structure (3D) into an OPTIMADE StructureResourceAttributes model.

Parameters:

Name Type Description Default
pmg_structure Structure

The pymatgen Structure to convert.

required

Returns:

Type Description
StructureResourceAttributes

An OPTIMADE StructureResourceAttributes model, which can be converted to a raw Python dictionary with .dict() or to JSON with .json().

Source code in optimade/adapters/structures/pymatgen.py
def from_pymatgen(pmg_structure: Structure) -> StructureResourceAttributes:
    """Convert a pymatgen `Structure` (3D) into an OPTIMADE `StructureResourceAttributes` model.

    Parameters:
        pmg_structure: The pymatgen `Structure` to convert.

    Returns:
        An OPTIMADE `StructureResourceAttributes` model, which can be converted to a raw Python
            dictionary with `.dict()` or to JSON with `.json()`.

    """

    if not isinstance(pmg_structure, Structure):
        raise RuntimeError(
            f"Cannot convert type {type(pmg_structure)} into an OPTIMADE `StructureResourceAttributes` model."
        )

    attributes = {}
    attributes["cartesian_site_positions"] = pmg_structure.lattice.get_cartesian_coords(
        pmg_structure.frac_coords
    ).tolist()
    attributes["lattice_vectors"] = pmg_structure.lattice.matrix.tolist()
    attributes["species_at_sites"] = [_.symbol for _ in pmg_structure.species]
    attributes["species"] = [
        {"name": _.symbol, "chemical_symbols": [_.symbol], "concentration": [1]}
        for _ in set(pmg_structure.composition.elements)
    ]
    attributes["dimension_types"] = [int(_) for _ in pmg_structure.lattice.pbc]
    attributes["nperiodic_dimensions"] = sum(attributes["dimension_types"])
    attributes["nelements"] = len(pmg_structure.composition.elements)
    attributes["chemical_formula_anonymous"] = anonymize_formula(
        pmg_structure.composition.formula
    )
    attributes["elements"] = sorted(
        [_.symbol for _ in pmg_structure.composition.elements]
    )
    attributes["chemical_formula_reduced"] = reduce_formula(
        pmg_structure.composition.formula
    )
    attributes["chemical_formula_descriptive"] = pmg_structure.composition.formula
    attributes["elements_ratios"] = [
        pmg_structure.composition.get_atomic_fraction(e) for e in attributes["elements"]
    ]
    attributes["nsites"] = len(attributes["species_at_sites"])

    attributes["last_modified"] = None
    attributes["immutable_id"] = None
    attributes["structure_features"] = []

    return StructureResourceAttributes(**attributes)

get_pymatgen(optimade_structure)

Get pymatgen Structure or Molecule from OPTIMADE structure.

This function will return either a pymatgen Structure or Molecule based on the periodicity or periodic dimensionality of OPTIMADE structure.

For structures that are periodic in one or more dimensions, a pymatgen Structure is returned when valid lattice_vectors are given. This means, if the any of the values in the dimension_types attribute is 1s or if nperiodic_dimesions > 0.

Otherwise, a pymatgen Molecule is returned.

Parameters:

Name Type Description Default
optimade_structure StructureResource

OPTIMADE structure.

required

Returns:

Type Description
Union[pymatgen.core.structure.Structure, pymatgen.core.structure.Molecule]

A pymatgen Structure or Molecule based on the periodicity of the OPTIMADE structure.

Source code in optimade/adapters/structures/pymatgen.py
def get_pymatgen(optimade_structure: OptimadeStructure) -> Union[Structure, Molecule]:
    """Get pymatgen `Structure` or `Molecule` from OPTIMADE structure.

    This function will return either a pymatgen `Structure` or `Molecule` based
    on the periodicity or periodic dimensionality of OPTIMADE structure.

    For structures that are periodic in one or more dimensions, a pymatgen `Structure` is returned when valid lattice_vectors are given.
    This means, if the any of the values in the [`dimension_types`][optimade.models.structures.StructureResourceAttributes.dimension_types]
    attribute is `1`s or if [`nperiodic_dimesions`][optimade.models.structures.StructureResourceAttributes.nperiodic_dimensions] > 0.

    Otherwise, a pymatgen `Molecule` is returned.

    Parameters:
        optimade_structure: OPTIMADE structure.

    Returns:
        A pymatgen `Structure` or `Molecule` based on the periodicity of the
        OPTIMADE structure.

    """
    if "optimade.adapters" in repr(globals().get("Structure")):
        warn(PYMATGEN_NOT_FOUND, AdapterPackageNotFound)
        return None

    if valid_lattice_vector(optimade_structure.attributes.lattice_vectors) and (  # type: ignore[arg-type]
        optimade_structure.attributes.nperiodic_dimensions > 0  # type: ignore[operator]
        or any(optimade_structure.attributes.dimension_types)  # type: ignore[arg-type]
    ):
        return _get_structure(optimade_structure)

    return _get_molecule(optimade_structure)