Skip to content

Python API Reference

The public API of amorphouspy is defined by what is importable directly from the top-level package:

from amorphouspy import *

The rest of the package is considered internal implementation and can be subject to breaking changes even in minor releases.


amorphouspy

amorphouspy - workflows for atomistic modeling of oxide glasses.

Classes

DsfConfig

Bases: InteractionConfig

Damped Shifted Force electrostatics.

Emitted as coul/dsf <alpha> <long_range_cutoff>.

Source code in amorphouspy/src/amorphouspy/lammps/potentials/_config.py
class DsfConfig(InteractionConfig):
    """Damped Shifted Force electrostatics.

    Emitted as ``coul/dsf <alpha> <long_range_cutoff>``.
    """

    lammps_keyword: Literal["dsf"] = "dsf"
    long_range_cutoff: float | None = Field(default=None, description="Coulomb cutoff in Å", gt=0)
    alpha: float | None = Field(default=None, description="Damping parameter (Å⁻¹)", gt=0)

    def coul_pair_style(self, cutoff: float, alpha: float | None = None) -> str:
        if alpha is None:
            msg = "alpha is required for DSF electrostatics"
            raise ValueError(msg)
        return f"coul/{self.lammps_keyword} {alpha} {cutoff}"

EwaldConfig

Bases: InteractionConfig

Ewald summation electrostatics.

Emits coul/long <long_range_cutoff> plus a kspace_style ewald line.

Source code in amorphouspy/src/amorphouspy/lammps/potentials/_config.py
class EwaldConfig(InteractionConfig):
    """Ewald summation electrostatics.

    Emits ``coul/long <long_range_cutoff>`` plus a ``kspace_style ewald`` line.
    """

    lammps_keyword: Literal["ewald"] = "ewald"
    long_range_cutoff: float | None = Field(default=None, description="Coulomb cutoff in Å", gt=0)
    kspace_accuracy: float = Field(default=1e-5, description="Relative accuracy for the k-space sum", gt=0, le=1)

    def coul_pair_style(self, cutoff: float) -> str:
        return f"coul/long {cutoff}"

    def kspace_line(self) -> str:
        return f"kspace_style {self.lammps_keyword} {self.kspace_accuracy}"

InteractionConfig

Bases: BaseModel

Base class for LAMMPS Coulomb solver settings.

Source code in amorphouspy/src/amorphouspy/lammps/potentials/_config.py
class InteractionConfig(BaseModel):
    """Base class for LAMMPS Coulomb solver settings."""

    def kspace_line(self) -> str | None:
        return None

PppmConfig

Bases: InteractionConfig

PPPM (Particle-Particle Particle-Mesh) electrostatics.

Emits coul/long <long_range_cutoff> plus a kspace_style pppm line.

Source code in amorphouspy/src/amorphouspy/lammps/potentials/_config.py
class PppmConfig(InteractionConfig):
    """PPPM (Particle-Particle Particle-Mesh) electrostatics.

    Emits ``coul/long <long_range_cutoff>`` plus a ``kspace_style pppm`` line.
    """

    lammps_keyword: Literal["pppm"] = "pppm"
    long_range_cutoff: float | None = Field(default=None, description="Coulomb cutoff in Å", gt=0)
    kspace_accuracy: float = Field(default=1e-5, description="Relative accuracy for the k-space sum", gt=0, le=1)

    def coul_pair_style(self, cutoff: float) -> str:
        return f"coul/long {cutoff}"

    def kspace_line(self) -> str:
        return f"kspace_style {self.lammps_keyword} {self.kspace_accuracy}"

WolfConfig

Bases: InteractionConfig

Wolf summation electrostatics.

Emitted as coul/wolf <alpha> <long_range_cutoff>.

Source code in amorphouspy/src/amorphouspy/lammps/potentials/_config.py
class WolfConfig(InteractionConfig):
    """Wolf summation electrostatics.

    Emitted as ``coul/wolf <alpha> <long_range_cutoff>``.
    """

    lammps_keyword: Literal["wolf"] = "wolf"
    long_range_cutoff: float | None = Field(default=None, description="Coulomb cutoff in Å", gt=0)
    alpha: float | None = Field(default=None, description="Damping parameter (Å⁻¹)", gt=0)

    def coul_pair_style(self, cutoff: float, alpha: float | None = None) -> str:
        if alpha is None:
            msg = "alpha is required for Wolf electrostatics"
            raise ValueError(msg)
        return f"coul/{self.lammps_keyword} {alpha} {cutoff}"

Functions:

analyze_structure(atoms: Atoms | list[Atoms], *, frame_averaging: bool = False, compute_rings: bool = True, n_jobs: int = 1, r_max: float = 10.0, n_bins: int = 500) -> tuple[StructureData, StructureData]

Perform a comprehensive structural analysis of an atomic configuration.

Parameters:

Name Type Description Default
atoms Atoms | list[Atoms]

Atomic configuration to analyze, or a list of frames when frame_averaging=True.

required
frame_averaging bool

If True, average results over all frames in atoms (list[Atoms]). Returns a tuple (mean_data, sem_data) where both are StructureData instances. Ring statistics are computed on the first frame only; all other properties are averaged over all frames.

False
compute_rings bool

Whether to run the ring statistics analysis.

True
n_jobs int

Number of worker processes for frame averaging. Used only when frame_averaging=True. n_jobs=1 runs serially. Values larger than the available frame count are capped automatically.

1
r_max float

Maximum radius in Å for RDF calculation (default 10.0).

10.0
n_bins int

Number of bins for RDF calculation (default 500).

500

Returns:

Name Type Description
StructureData StructureData

Object containing structured analysis results.

StructureData

When frame_averaging=True, returns tuple[StructureData, StructureData] — (mean, sem).

Example

structure_data = analyze_structure(my_atoms) print(structure_data.density)

Source code in amorphouspy/src/amorphouspy/properties/structural/all.py
def analyze_structure(
    atoms: Atoms | list[Atoms],
    *,
    frame_averaging: bool = False,
    compute_rings: bool = True,
    n_jobs: int = 1,
    r_max: float = 10.0,
    n_bins: int = 500,
) -> tuple[StructureData, StructureData]:
    """Perform a comprehensive structural analysis of an atomic configuration.

    Args:
        atoms: Atomic configuration to analyze, or a list of frames when frame_averaging=True.
        frame_averaging: If True, average results over all frames in atoms (list[Atoms]).
            Returns a tuple (mean_data, sem_data) where both are StructureData instances.
            Ring statistics are computed on the first frame only; all other properties
            are averaged over all frames.
        compute_rings: Whether to run the ring statistics analysis.
        n_jobs: Number of worker processes for frame averaging. Used only when
            ``frame_averaging=True``. ``n_jobs=1`` runs serially. Values larger
            than the available frame count are capped automatically.
        r_max: Maximum radius in Å for RDF calculation (default 10.0).
        n_bins: Number of bins for RDF calculation (default 500).

    Returns:
        StructureData: Object containing structured analysis results.
        When frame_averaging=True, returns tuple[StructureData, StructureData] — (mean, sem).

    Example:
        >>> structure_data = analyze_structure(my_atoms)
        >>> print(structure_data.density)

    """
    if frame_averaging:
        if isinstance(atoms, list) and len(atoms) == 0:
            msg = "frame_averaging=True requires a non-empty list[Atoms]"
            raise ValueError(msg)
        if n_jobs < 1:
            msg = "n_jobs must be >= 1"
            raise ValueError(msg)
        frames = cast("list[Atoms]", atoms if isinstance(atoms, list) else [atoms])

        effective_jobs = min(n_jobs, len(frames))

        if effective_jobs == 1:
            per_frame_results = [
                analyze_structure(frame_atoms, compute_rings=compute_rings and i == 0, r_max=r_max, n_bins=n_bins)[0]
                for i, frame_atoms in enumerate(frames)
            ]
            return _build_sem_structure_data(per_frame_results)

        # Frame 0 is analyzed with rings; remaining frames skip rings and are
        # distributed dynamically across workers.
        analyze_first = partial(_analyze_frame, compute_rings=compute_rings, r_max=r_max, n_bins=n_bins)
        analyze_rest = partial(_analyze_frame, compute_rings=False, r_max=r_max, n_bins=n_bins)
        with ProcessPoolExecutor(max_workers=effective_jobs) as executor:
            frame0_future = executor.submit(analyze_first, frames[0])
            per_frame_results_rest = list(executor.map(analyze_rest, frames[1:]))
        per_frame_results = [frame0_future.result(), *per_frame_results_rest]
        return _build_sem_structure_data(per_frame_results)
    if isinstance(atoms, list):
        atoms = cast("Atoms", atoms[0])

    unique_z = np.unique(atoms.get_atomic_numbers())
    density = _compute_density(atoms)
    type_map, network_formers, modifiers, _oxygen_present = _classify_elements(unique_z)
    former_types = _network_former_types(type_map, network_formers)
    modifier_types = [z for z, sym in type_map.items() if sym in modifiers]
    o_type = [z for z, sym in type_map.items() if sym == "O"]

    r, rdfs, cumcn = compute_rdf(atoms, r_max=r_max, n_bins=n_bins)
    cutoff_map = _build_cutoff_map(unique_z, type_map, former_types, o_type, r, rdfs)

    o_coord, former_coords, modifier_coords = _compute_coordination_data(
        atoms, type_map, network_formers, modifiers, former_types, modifier_types, o_type, cutoff_map
    )
    qn_dist, qn_dist_partial, network_connectivity, oxygen_class_counts, oxygen_class_ids = _compute_network_data(
        atoms, network_formers, former_types, o_type, cutoff_map, type_map
    )
    bond_angle_distributions, ring_statistics_data = _compute_distributions(
        atoms, type_map, network_formers, o_type, cutoff_map, compute_rings=compute_rings
    )

    def to_list(data: np.ndarray | list[float]) -> list[float]:
        return data.tolist() if isinstance(data, np.ndarray) else list(data)

    bond_angle_distributions_serializable = {
        former: (to_list(angles), to_list(counts)) for former, (angles, counts) in bond_angle_distributions.items()
    }
    r_list, rdfs_serializable, cumcn_serializable = _serialize_rdfs(type_map, r, rdfs, cumcn)
    structure_factor_data = _compute_structure_factor_data(atoms, type_map)

    mean_data = StructureData(
        density=density,
        coordination=CoordinationData(oxygen=o_coord, formers=former_coords, modifiers=modifier_coords),
        network=NetworkData(
            Qn_distribution={k: float(v) for k, v in qn_dist.items()},
            Qn_distribution_partial={
                outer: {inner: float(v) for inner, v in inner_d.items()} for outer, inner_d in qn_dist_partial.items()
            },
            connectivity=network_connectivity,
        ),
        distributions=StructuralDistributions(
            bond_angles=bond_angle_distributions_serializable, rings=ring_statistics_data
        ),
        rdfs=RadialDistributionData(r=r_list, rdfs=rdfs_serializable, cumulative_coordination=cumcn_serializable),
        structure_factor=structure_factor_data,
        elements=ElementInfo(
            formers=list(network_formers),
            modifiers=list(modifiers),
            cutoffs=cutoff_map,
            oxygen_classes=oxygen_class_counts,
            oxygen_ids=oxygen_class_ids,
        ),
    )
    _, sem_data = _build_sem_structure_data([mean_data])
    return mean_data, sem_data

average_over_frames(func: Callable[..., tuple], frames: list[Atoms], **kwargs: object) -> tuple[tuple, tuple]

Call a per-frame analysis function on each frame, return mean and SEM for every output.

Parameters:

Name Type Description Default
func Callable[..., tuple]

Analysis function taking a single Atoms frame as first argument and returning a tuple.

required
frames list[Atoms]

List of Atoms frames to average over.

required
**kwargs object

Keyword arguments forwarded to func.

{}

Returns:

Type Description
tuple[tuple, tuple]

(means, sems) — both tuples have the same length as func's return tuple.

Example

means, sems = average_over_frames(compute_rdf, frames, r_max=8.0, n_bins=500) r, rdf_mean, cn_mean = means _, rdf_sem, cn_sem = sems

Source code in amorphouspy/src/amorphouspy/properties/structural/averaging.py
def average_over_frames(
    func: Callable[..., tuple],
    frames: list[Atoms],
    **kwargs: object,
) -> tuple[tuple, tuple]:
    """Call a per-frame analysis function on each frame, return mean and SEM for every output.

    Args:
        func: Analysis function taking a single Atoms frame as first argument and returning a tuple.
        frames: List of Atoms frames to average over.
        **kwargs: Keyword arguments forwarded to func.

    Returns:
        (means, sems) — both tuples have the same length as func's return tuple.

    Example:
        >>> means, sems = average_over_frames(compute_rdf, frames, r_max=8.0, n_bins=500)
        >>> r, rdf_mean, cn_mean = means
        >>> _, rdf_sem, cn_sem = sems
    """
    if not frames:
        msg = "average_over_frames requires a non-empty list of frames"
        raise ValueError(msg)
    raw = [func(frame, **kwargs) for frame in frames]
    # Normalize: a bare non-tuple result (e.g. a plain dict) is treated as a 1-element tuple
    results = [r if isinstance(r, tuple) else (r,) for r in raw]
    n_frames = len(results)
    ddof = 1 if n_frames > 1 else 0

    means: list[Any] = list(results[-1])
    sems: list[Any] = [None] * len(means)

    for idx in range(len(means)):
        values = [r[idx] for r in results]
        means[idx], sems[idx] = _avg_sem(values, ddof, n_frames)

    return tuple(means), tuple(sems)

charges_from_potential(potential: pd.DataFrame, structure: Atoms) -> np.ndarray

Return the charge that a potential assigns to every atom of a structure.

The potentials of :func:generate_potential set one fixed charge per atom type with lines set type N charge q in their Config, and LAMMPS numbers the types in the order of Species. This reads those lines back, so the charges are the ones the simulation uses, including a charge that depends on the composition such as the oxygen charge of SHIK.

Parameters:

Name Type Description Default
potential DataFrame

The potential DataFrame with the columns Species and Config, e.g. from :func:generate_potential.

required
structure Atoms

The structure whose atoms are to be charged.

required

Returns:

Type Description
ndarray

The charges in units of the elementary charge, shape (len(structure),), in the order of the atoms.

Raises:

Type Description
ValueError

If the potential is empty, has no set type N charge q line, or does not define a charge for an element of the structure.

Example

potential = generate_potential(struct_dict, potential_type="pmmcs") charges = charges_from_potential(potential, structure)

Source code in amorphouspy/src/amorphouspy/lammps/potentials/potential.py
def charges_from_potential(potential: pd.DataFrame, structure: "Atoms") -> np.ndarray:
    """Return the charge that a potential assigns to every atom of a structure.

    The potentials of :func:`generate_potential` set one fixed charge per atom type with lines
    ``set type N charge q`` in their ``Config``, and LAMMPS numbers the types in the order of ``Species``. This
    reads those lines back, so the charges are the ones the simulation uses, including a charge that depends on
    the composition such as the oxygen charge of SHIK.

    Args:
        potential: The potential DataFrame with the columns ``Species`` and ``Config``, e.g. from
            :func:`generate_potential`.
        structure: The structure whose atoms are to be charged.

    Returns:
        The charges in units of the elementary charge, shape ``(len(structure),)``, in the order of the atoms.

    Raises:
        ValueError: If the potential is empty, has no ``set type N charge q`` line, or does not define a charge
            for an element of the structure.

    Example:
        >>> potential = generate_potential(struct_dict, potential_type="pmmcs")
        >>> charges = charges_from_potential(potential, structure)

    """
    if potential.empty:
        msg = "No matching potential found for the given configuration."
        raise ValueError(msg)
    species = list(potential["Species"].iloc[0])
    by_type = {}
    for line in potential["Config"].iloc[0]:
        match = _SET_CHARGE.match(line)
        if match:
            by_type[int(match.group(1))] = float(match.group(2))
    if not by_type:
        msg = "The potential sets no charges (no 'set type N charge q' line in its Config); pass charges explicitly."
        raise ValueError(msg)
    by_element = {element: by_type[number] for number, element in enumerate(species, start=1) if number in by_type}
    symbols = structure.get_chemical_symbols()
    missing = sorted(set(symbols) - set(by_element))
    if missing:
        msg = f"The potential defines no charge for {', '.join(missing)}; its species are {species}."
        raise ValueError(msg)
    return np.array([by_element[symbol] for symbol in symbols], dtype=np.float64)

check_neutral_oxide(oxide: str) -> None

Check if an oxide formula is charge neutral based on standard oxidation states.

Parameters:

Name Type Description Default
oxide str

The chemical formula of the oxide (e.g., "Al2O3").

required

Raises:

Type Description
ValueError

If the oxide is invalid, oxidation states cannot be determined, or the net charge is not zero.

Source code in amorphouspy/src/amorphouspy/fabrication/composition.py
def check_neutral_oxide(oxide: str) -> None:
    """Check if an oxide formula is charge neutral based on standard oxidation states.

    Args:
        oxide: The chemical formula of the oxide (e.g., "Al2O3").

    Raises:
        ValueError: If the oxide is invalid, oxidation states cannot be determined,
            or the net charge is not zero.

    """
    try:
        comp = Composition(oxide)
    except Exception as e:
        error_msg = f"Invalid oxide formula: '{oxide}'"
        raise ValueError(error_msg) from e

    oxi_guesses = comp.oxi_state_guesses()
    if not oxi_guesses:
        error_msg = f"Cannot determine oxidation states for '{oxide}'"
        raise ValueError(error_msg)

    total_charge = sum(oxi * comp[el] for el, oxi in oxi_guesses[0].items())

    if total_charge != 0:
        error_msg = f"Oxide '{oxide}' is not charge neutral (net charge {total_charge})"
        raise ValueError(error_msg)

classify_oxygens(structure: Atoms, cutoff: CutoffSpec, former_types: list[int], o_type: int) -> dict[int, str]

Classify each oxygen atom as bridging (BO), non-bridging (NBO), free, or triclustered.

Convenience wrapper around :func:compute_qn_and_classify that returns only the oxygen classification.

Parameters:

Name Type Description Default
structure Atoms

The atomic structure as ASE object.

required
cutoff CutoffSpec

Cutoff radius for former-O neighbor search (Å), either a scalar or a per-pair dict {(z_i, z_j): r_cut}.

required
former_types list[int]

Atom types (atomic numbers) considered as formers.

required
o_type int

Atom type (atomic number) considered as oxygen.

required

Returns:

Type Description
dict[int, str]

A mapping from real atom ID to oxygen class string:

dict[int, str]

"BO" (bridging, 2 former neighbours), "NBO" (non-bridging, 1),

dict[int, str]

"free" (0), or "tri" (≥ 3 triclustered).

Example

o_classes = classify_oxygens(atoms, cutoff=2.0, former_types=[14], o_type=8)

Source code in amorphouspy/src/amorphouspy/properties/structural/qn.py
def classify_oxygens(
    structure: Atoms,
    cutoff: CutoffSpec,
    former_types: list[int],
    o_type: int,
) -> dict[int, str]:
    """Classify each oxygen atom as bridging (BO), non-bridging (NBO), free, or triclustered.

    Convenience wrapper around :func:`compute_qn_and_classify` that returns
    only the oxygen classification.

    Args:
        structure: The atomic structure as ASE object.
        cutoff: Cutoff radius for former-O neighbor search (Å), either a
            scalar or a per-pair dict ``{(z_i, z_j): r_cut}``.
        former_types: Atom types (atomic numbers) considered as formers.
        o_type: Atom type (atomic number) considered as oxygen.

    Returns:
        A mapping from real atom ID to oxygen class string:
        ``"BO"`` (bridging, 2 former neighbours), ``"NBO"`` (non-bridging, 1),
        ``"free"`` (0), or ``"tri"`` (≥ 3 triclustered).

    Example:
        >>> o_classes = classify_oxygens(atoms, cutoff=2.0, former_types=[14], o_type=8)

    """
    _total_qn, _partial_qn, o_classes = compute_qn_and_classify(structure, cutoff, former_types, o_type)
    return o_classes

classify_vibrational_groups(structure: Atoms, cutoff: CutoffSpec | None = None, former_types: list[int] | None = None, o_type: int = 8) -> dict[str, dict[str, np.ndarray]]

Label every atom by element, oxygen class and network-former Q^n for partial VDOS.

Oxygen classes and Q^n come from :func:compute_qn_and_classify and :func:compute_qn_per_atom. Missing cutoff and former_types are derived as in :func:analyze_structure: formers are the glass formers and intermediates present, and each former-O cutoff is the first minimum of its RDF (r_max=10.0, n_bins=500), with the same fallbacks.

Parameters:

Name Type Description Default
structure Atoms

The atomic structure as ASE object. Atom IDs are read from the "id" array if present, else taken as 1-based indices; the returned indices are always 0-based positions in structure.

required
cutoff CutoffSpec | None

Former-O cutoff in Å, either a scalar or a per-pair dict {(z_i, z_j): r_cut}. Derived from the RDF if None.

None
former_types list[int] | None

Atomic numbers of the network formers. Derived from the composition if None.

None
o_type int

Atomic number of oxygen.

8

Returns:

Type Description
dict[str, dict[str, ndarray]]

A dict with three groupings, each mapping a label to a sorted int64 array of 0-based positions: "element": element symbol, e.g. "Si", "O", "Na". "oxygen": "O_BO", "O_NBO", "O_free", "O_tri". "qn": former symbol and number of bridging oxygens, e.g. "Si_Q3", "B_Q4".

dict[str, dict[str, ndarray]]

Labels without atoms are omitted. Without oxygen, "oxygen" and "qn" are empty; with oxygen but

dict[str, dict[str, ndarray]]

no formers, "qn" is empty and every oxygen is "O_free".

Raises:

Type Description
ValueError

If the "id" array contains duplicate IDs.

Example
>>> from ase import Atoms
>>> d = 1.6
>>> positions = [[10, 10, 10], [10 + 2 * d, 10, 10], [10 + d, 10, 10],
...              [10 - d, 10, 10], [10, 10 + d, 10], [10, 10, 10 + d],
...              [10 + 3 * d, 10, 10], [10 + 2 * d, 10 + d, 10], [10 + 2 * d, 10, 10 + d]]
>>> dimer = Atoms("Si2O7", positions=positions, cell=[30, 30, 30], pbc=True)
>>> groups = classify_vibrational_groups(dimer, cutoff=2.0, former_types=[14])
>>> groups["element"]["Si"].tolist(), groups["oxygen"]["O_BO"].tolist(), groups["qn"]["Si_Q1"].tolist()
([0, 1], [2], [0, 1])
Source code in amorphouspy/src/amorphouspy/properties/vibrational/classification.py
def classify_vibrational_groups(
    structure: "Atoms",
    cutoff: CutoffSpec | None = None,
    former_types: list[int] | None = None,
    o_type: int = 8,
) -> dict[str, dict[str, np.ndarray]]:
    """Label every atom by element, oxygen class and network-former Q^n for partial VDOS.

    Oxygen classes and Q^n come from :func:`compute_qn_and_classify` and :func:`compute_qn_per_atom`. Missing
    ``cutoff`` and ``former_types`` are derived as in :func:`analyze_structure`: formers are the glass formers and
    intermediates present, and each former-O cutoff is the first minimum of its RDF (``r_max=10.0``,
    ``n_bins=500``), with the same fallbacks.

    Args:
        structure: The atomic structure as ASE object. Atom IDs are read from the ``"id"`` array if present,
            else taken as 1-based indices; the returned indices are always 0-based positions in ``structure``.
        cutoff: Former-O cutoff in Å, either a scalar or a per-pair dict ``{(z_i, z_j): r_cut}``. Derived from
            the RDF if ``None``.
        former_types: Atomic numbers of the network formers. Derived from the composition if ``None``.
        o_type: Atomic number of oxygen.

    Returns:
        A dict with three groupings, each mapping a label to a sorted int64 array of 0-based positions:
            ``"element"``: element symbol, e.g. ``"Si"``, ``"O"``, ``"Na"``.
            ``"oxygen"``: ``"O_BO"``, ``"O_NBO"``, ``"O_free"``, ``"O_tri"``.
            ``"qn"``: former symbol and number of bridging oxygens, e.g. ``"Si_Q3"``, ``"B_Q4"``.
        Labels without atoms are omitted. Without oxygen, ``"oxygen"`` and ``"qn"`` are empty; with oxygen but
        no formers, ``"qn"`` is empty and every oxygen is ``"O_free"``.

    Raises:
        ValueError: If the ``"id"`` array contains duplicate IDs.

    Example:
        ```pycon
        >>> from ase import Atoms
        >>> d = 1.6
        >>> positions = [[10, 10, 10], [10 + 2 * d, 10, 10], [10 + d, 10, 10],
        ...              [10 - d, 10, 10], [10, 10 + d, 10], [10, 10, 10 + d],
        ...              [10 + 3 * d, 10, 10], [10 + 2 * d, 10 + d, 10], [10 + 2 * d, 10, 10 + d]]
        >>> dimer = Atoms("Si2O7", positions=positions, cell=[30, 30, 30], pbc=True)
        >>> groups = classify_vibrational_groups(dimer, cutoff=2.0, former_types=[14])
        >>> groups["element"]["Si"].tolist(), groups["oxygen"]["O_BO"].tolist(), groups["qn"]["Si_Q1"].tolist()
        ([0, 1], [2], [0, 1])

        ```
    """
    n_atoms = len(structure)
    if "id" in structure.arrays:
        atom_ids = structure.arrays["id"].astype(np.int64)
    else:
        atom_ids = np.arange(1, n_atoms + 1, dtype=np.int64)
    if len(np.unique(atom_ids)) != n_atoms:
        msg = "The 'id' array contains duplicate atom IDs."
        raise ValueError(msg)
    id_to_position = {int(atom_id): position for position, atom_id in enumerate(atom_ids)}

    symbols = np.array(structure.get_chemical_symbols())
    groups: dict[str, dict[str, np.ndarray]] = {
        "element": {str(sym): np.flatnonzero(symbols == sym).astype(np.int64) for sym in sorted(set(symbols))},
        "oxygen": {},
        "qn": {},
    }
    atomic_numbers = structure.get_atomic_numbers()
    if o_type not in atomic_numbers:
        return groups

    unique_z = np.unique(atomic_numbers)
    type_map, network_formers, _modifiers, _oxygen_present = _classify_elements(unique_z)
    if former_types is None:
        former_types = _network_former_types(type_map, network_formers)
    if not former_types:
        groups["oxygen"] = {"O_free": np.flatnonzero(atomic_numbers == o_type).astype(np.int64)}
        return groups
    if cutoff is None:
        r, rdfs, _cumcn = compute_rdf(structure, r_max=10.0, n_bins=500)
        cutoff_map = _build_cutoff_map(unique_z, type_map, former_types, [o_type], r, rdfs)
        cutoff = _former_oxygen_pair_cutoffs(former_types, o_type, type_map, cutoff_map)

    _total_qn, _partial_qn, oxygen_classes = compute_qn_and_classify(structure, cutoff, former_types, o_type)
    qn_per_atom = compute_qn_per_atom(structure, cutoff, former_types, o_type)
    id_to_symbol = {int(atom_id): str(sym) for atom_id, sym in zip(atom_ids, symbols, strict=True)}
    groups["oxygen"] = _positions_by_label({aid: f"O_{cls}" for aid, cls in oxygen_classes.items()}, id_to_position)
    groups["qn"] = _positions_by_label(
        {aid: f"{id_to_symbol[aid]}_Q{n}" for aid, n in qn_per_atom.items()}, id_to_position
    )
    return groups

compute_angles(structure: Atoms | list[Atoms], center_type: int, neighbor_type: int, cutoff: float, bins: int = 180) -> tuple[np.ndarray, np.ndarray]

Compute bond angle distribution between triplets of neighbor_type-center-neighbor_type.

Parameters:

Name Type Description Default
structure Atoms | list[Atoms]

Atomic structure. Pass a list to use the first frame.

required
center_type int

Atom type at the angle center.

required
neighbor_type int

Atom type forming the angle with center.

required
cutoff float

Neighbor search cutoff.

required
bins int

Number of histogram bins. Defaults to 180.

180

Returns:

Type Description
tuple[ndarray, ndarray]

A 2-tuple containing: bin_centers: Bin centers (degrees). angle_hist: Normalized angle histogram.

Example

bins, hist = compute_angles(structure, center_type=1, neighbor_type=2, cutoff=3.0)

Source code in amorphouspy/src/amorphouspy/properties/structural/bond_angles.py
def compute_angles(
    structure: Atoms | list[Atoms],
    center_type: int,
    neighbor_type: int,
    cutoff: float,
    bins: int = 180,
) -> tuple[np.ndarray, np.ndarray]:
    """Compute bond angle distribution between triplets of neighbor_type-center-neighbor_type.

    Args:
        structure: Atomic structure. Pass a list to use the first frame.
        center_type: Atom type at the angle center.
        neighbor_type: Atom type forming the angle with center.
        cutoff: Neighbor search cutoff.
        bins: Number of histogram bins. Defaults to 180.

    Returns:
        A 2-tuple containing:
            bin_centers: Bin centers (degrees).
            angle_hist: Normalized angle histogram.

    Example:
        >>> bins, hist = compute_angles(structure, center_type=1, neighbor_type=2, cutoff=3.0)

    """
    if isinstance(structure, list):
        structure = cast("Atoms", structure[0])
    # Wrap and extract positions/cell once — needed for minimum-image vectors
    structure_wrapped = structure.copy()
    structure_wrapped.wrap()
    coords = structure_wrapped.get_positions()
    cell = structure_wrapped.get_cell().array
    is_orthogonal = np.allclose(cell - np.diag(np.diag(cell)), 0.0, atol=1e-10)

    # Build ID → array index map to look up coordinates by real atom ID
    if "id" in structure_wrapped.arrays:
        raw_ids = structure_wrapped.arrays["id"]
    else:
        raw_ids = np.arange(1, len(structure_wrapped) + 1)
    id_to_idx = {int(aid): i for i, aid in enumerate(raw_ids)}

    # get_neighbors returns List[Tuple[central_id, List[neighbor_ids]]]
    neighbors = get_neighbors(
        structure,
        cutoff=cutoff,
        target_types=[center_type],
        neighbor_types=[neighbor_type],
    )

    angles = []

    for central_id, nn_ids in neighbors:
        if len(nn_ids) < MIN_NEIGHBORS_FOR_ANGLE:
            continue

        ci = id_to_idx[central_id]
        center_coord = coords[ci]

        # Resolve neighbor coordinates by real ID — shape (k, 3)
        nn_indices = np.array([id_to_idx[nid] for nid in nn_ids], dtype=np.int32)
        vecs = coords[nn_indices] - center_coord  # (k, 3)

        # Minimum-image correction — vectorized for all neighbor vectors at once
        if is_orthogonal:
            box = np.diag(cell)
            vecs -= box * np.round(vecs / box)
        else:
            # Lattice vectors are rows, so fractional coordinates are vecs @ inv(cell).
            inv_cell = np.linalg.inv(cell)
            delta_frac = vecs @ inv_cell
            delta_frac -= np.round(delta_frac)
            vecs = delta_frac @ cell

        # Normalise all vectors at once
        norms = np.linalg.norm(vecs, axis=1)  # (k,)
        valid = norms > 0
        if valid.sum() < MIN_NEIGHBORS_FOR_ANGLE:
            continue
        vecs = vecs[valid]
        norms = norms[valid]
        unit_vecs = vecs / norms[:, np.newaxis]  # (k, 3)

        # Compute all unique pair cosines via matrix multiply: (k, k)
        # Upper triangle gives each unique i<j pair
        cos_mat = np.clip(unit_vecs @ unit_vecs.T, -1.0, 1.0)
        i_idx, j_idx = np.triu_indices(len(unit_vecs), k=1)
        cos_angles = cos_mat[i_idx, j_idx]
        angles.extend(np.degrees(np.arccos(cos_angles)).tolist())

    angle_hist, bin_edges = np.histogram(
        angles,
        bins=bins,
        range=(0, 180),
        density=True,
    )
    bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
    return bin_centers, angle_hist

compute_cavities(structure: Atoms, resolution: int = 128, cutoff_radii: dict[str, float] | float | str | None = None, probe_radius: float = 0.0) -> dict[str, np.ndarray]

Compute cavity distribution and shape properties for a glass structure.

Domain-based cavity detection following pyMolDyn (Meyer et al. 2017). The simulation box is discretised into a 3D voxel grid; voxels whose centre lies within the atomic radius of any atom are marked as occupied. Connected regions of empty voxels -- detected with full 26-connectivity and periodic-boundary-condition awareness -- constitute cavities (domains).

Unlike pyMolDyn and sovapy, atoms are not snapped to the nearest voxel and radii are not rounded to whole voxels: every voxel is tested against the true atom position and radius, with the same rule for orthogonal and triclinic cells. The empty-voxel volume is therefore an unbiased estimate of the free volume at any resolution, and values differ from pyMolDyn and sovapy at the same resolution.

The grid spans exactly one periodic cell. Cavities that cross a cell face are joined to their continuation on the opposite face (including edges and corners) with a union-find merge that tracks periodic images, so every cavity is found regardless of where the cell boundary cuts it.

A cavity that connects to its own periodic image wraps around the cell and is infinite under PBC (percolating). It is kept, with its volume and surface area per cell, flagged in 'percolating', and its shape descriptors set to NaN. Every empty voxel belongs to exactly one cavity, so volumes.sum() is the total unoccupied volume of the cell.

The boundary of the empty space consists of the parts of the atom spheres not covered by other atoms. Surface areas are the areas of these exposed patches, sampled with 20 Shrake-Rupley points per A^2 (each atom's point set randomly rotated with a fixed seed), and each point is assigned to the cavity of the nearest empty voxel within 3 voxels along each axis. The resolution decides which cavity a patch belongs to and affects the total only through the dropped area: points with no empty voxel that close border crevices the grid does not resolve, and their area is dropped (0.07 % of the total for a 10,020-atom sodium silicate glass at resolution 128; 0.002 % at resolution 64, where the 3-voxel search reaches farther).

The total free volume converges quickly with resolution, but cavity counts, percolation and the split of volume and area between cavities converge more slowly: channels and necks narrower than about one voxel are not resolved. Check them at two resolutions.

Only domains are computed. pyMolDyn additionally offers center-based and surface-based cavities, which extend each domain into the atom spheres (to points nearer to a domain centre or domain surface point than to the nearest atom); those are not implemented here.

With probe_radius > 0 (e.g. 1.20 A, the Van der Waals radius of a neutral H atom), every atom radius is increased by the probe radius, so the cavities are the regions where the probe centre fits: each one holds at least one probe, and a percolating one lets the probe cross the cell. 'volumes' and 'surface_areas' then describe the space of the probe centre (accessible volume and surface). The accessible volume converges with resolution, but in dense glasses most sites are pockets smaller than a voxel, so the number of sites keeps growing with resolution (180, 236 and 301 at resolutions 128, 256 and 384 for H in a sodium silicate glass with ionic radii); the space the probe body can fill is not computed. The result depends strongly on the atom radii: with Van der Waals radii almost no site in a dense silicate glass fits an H atom.

Parameters:

Name Type Description Default
structure Atoms

ASE Atoms object with atomic coordinates and cell.

required
resolution int

Number of voxels along the longest box dimension (default 128). Higher values resolve narrower channels and crevices between cavities and finer cavity shapes, at the cost of memory and runtime.

128
cutoff_radii dict[str, float] | float | str | None

Atomic radius specification. Four forms are accepted:

  • None (default): element-specific ASE Van der Waals radii, with ASE covalent radii as fallback.
  • a number (int or float, not bool): uniform radius in A applied to every atom (e.g. cutoff_radii=2.8, sovapy's default radius).
  • dict[str, float]: per-element overrides in A (e.g. {'Si': 2.1, 'O': 1.52}); elements not in the dict fall back to ASE covalent radii.
  • "ionic": Shannon (1976) ionic radii via pymatgen for two-coordinated O2-, tetrahedral network formers (Si, B, Al, P, Ge, Zn), octahedral Ti and modifiers (Na, K, Mg, Ca, Sr, Ba) and tetrahedral Li; other elements raise ValueError.
None
probe_radius float

Radius in A of a probe sphere (default 0, no probe).

0.0

Returns:

Type Description
dict[str, ndarray]

Dictionary of 1D arrays, one entry per detected cavity, with keys: - 'volumes': cavity volumes in A^3 (per cell for percolating ones). - 'surface_areas': cavity surface areas in A^2 (per cell for percolating ones): exposed atom-sphere area bounding the cavity. Totals are within 0.1 % of analytic values for overlapping-sphere test geometries; small cavities carry point-sampling noise (about 7 % at the 90th percentile for 2-10 A^2 cavities). - 'asphericities': asphericity eta in [0, 1] (NaN if percolating). - 'acylindricities': acylindricity c in [0, 1] (NaN if percolating). - 'anisotropies': relative shape anisotropy kappa in [0, 1] (NaN if percolating). - 'percolating': bool, True for cavities that wrap around the cell. - 'max_inscribed_radii': radius in A of the largest sphere centred on a cavity voxel that touches no atom (largest included sphere), sampled at voxel centres, so low by up to half a voxel diagonal.

Raises:

Type Description
TypeError

If cutoff_radii is a bool.

ValueError

If probe_radius is negative, or cutoff_radii is an unknown string or "ionic" with an element without ionic radius.

Examples:

>>> from ase.io import read
>>> structure = read('glass.xyz')
>>> cavities = compute_cavities(structure, resolution=128)
>>> free_volume_fraction = cavities['volumes'].sum() / structure.get_volume()
Source code in amorphouspy/src/amorphouspy/properties/structural/cavities.py
def compute_cavities(
    structure: Atoms,
    resolution: int = 128,
    cutoff_radii: dict[str, float] | float | str | None = None,
    probe_radius: float = 0.0,
) -> dict[str, np.ndarray]:
    """Compute cavity distribution and shape properties for a glass structure.

    Domain-based cavity detection following pyMolDyn (Meyer et al. 2017). The
    simulation box is discretised into a 3D voxel grid; voxels whose centre
    lies within the atomic radius of any atom are marked as occupied.
    Connected regions of empty voxels -- detected with full 26-connectivity
    and periodic-boundary-condition awareness -- constitute cavities (domains).

    Unlike pyMolDyn and sovapy, atoms are not snapped to the nearest voxel and
    radii are not rounded to whole voxels: every voxel is tested against the
    true atom position and radius, with the same rule for orthogonal and
    triclinic cells. The empty-voxel volume is therefore an unbiased estimate
    of the free volume at any resolution, and values differ from pyMolDyn and
    sovapy at the same resolution.

    The grid spans exactly one periodic cell. Cavities that cross a cell face
    are joined to their continuation on the opposite face (including edges and
    corners) with a union-find merge that tracks periodic images, so every
    cavity is found regardless of where the cell boundary cuts it.

    A cavity that connects to its own periodic image wraps around the cell and
    is infinite under PBC (percolating). It is kept, with its volume and
    surface area per cell, flagged in ``'percolating'``, and its shape
    descriptors set to NaN. Every empty voxel belongs to exactly one cavity, so
    ``volumes.sum()`` is the total unoccupied volume of the cell.

    The boundary of the empty space consists of the parts of the atom spheres
    not covered by other atoms. Surface areas are the areas of these exposed
    patches, sampled with 20 Shrake-Rupley points per A^2 (each atom's point
    set randomly rotated with a fixed seed), and each point is assigned to
    the cavity of the nearest empty voxel within 3 voxels along each axis.
    The resolution decides which cavity a patch belongs to and affects the
    total only through the dropped area: points with no empty voxel that
    close border crevices the grid does not resolve, and their area is
    dropped (0.07 % of the total for a 10,020-atom sodium silicate glass at
    resolution 128; 0.002 % at resolution 64, where the 3-voxel search
    reaches farther).

    The total free volume converges quickly with resolution, but cavity
    counts, percolation and the split of volume and area between cavities
    converge more slowly: channels and necks narrower than about one voxel
    are not resolved. Check them at two resolutions.

    Only domains are computed. pyMolDyn additionally offers center-based and
    surface-based cavities, which extend each domain into the atom spheres
    (to points nearer to a domain centre or domain surface point than to the
    nearest atom); those are not implemented here.

    With ``probe_radius`` > 0 (e.g. 1.20 A, the Van der Waals radius of a
    neutral H atom), every atom radius is increased by the probe radius, so
    the cavities are the regions where the probe centre fits: each one holds
    at least one probe, and a percolating one lets the probe cross the cell.
    ``'volumes'`` and ``'surface_areas'`` then describe the space of the probe
    centre (accessible volume and surface). The accessible volume converges
    with resolution, but in dense glasses most sites are pockets smaller than
    a voxel, so the number of sites keeps growing with resolution (180, 236
    and 301 at resolutions 128, 256 and 384 for H in a sodium silicate glass
    with ionic radii); the space the probe body can fill is not computed.
    The result depends strongly on the atom radii: with Van der Waals radii
    almost no site in a dense silicate glass fits an H atom.

    Args:
        structure: ASE Atoms object with atomic coordinates and cell.
        resolution: Number of voxels along the longest box dimension
            (default 128). Higher values resolve narrower channels and
            crevices between cavities and finer cavity shapes, at the cost of
            memory and runtime.
        cutoff_radii: Atomic radius specification. Four forms are accepted:

            - ``None`` (default): element-specific ASE Van der Waals radii,
              with ASE covalent radii as fallback.
            - a number (int or float, not bool): uniform radius in A applied
              to every atom (e.g. ``cutoff_radii=2.8``, sovapy's default
              radius).
            - ``dict[str, float]``: per-element overrides in A
              (e.g. ``{'Si': 2.1, 'O': 1.52}``); elements not in the dict
              fall back to ASE covalent radii.
            - ``"ionic"``: Shannon (1976) ionic radii via pymatgen for
              two-coordinated O2-, tetrahedral network formers (Si, B, Al,
              P, Ge, Zn), octahedral Ti and modifiers (Na, K, Mg, Ca, Sr, Ba)
              and tetrahedral Li; other elements raise ValueError.

        probe_radius: Radius in A of a probe sphere (default 0, no probe).

    Returns:
        Dictionary of 1D arrays, one entry per detected cavity, with keys:
            - ``'volumes'``: cavity volumes in A^3 (per cell for percolating ones).
            - ``'surface_areas'``: cavity surface areas in A^2 (per cell for
              percolating ones): exposed atom-sphere area bounding the cavity.
              Totals are within 0.1 % of analytic values for overlapping-sphere
              test geometries; small cavities carry point-sampling noise
              (about 7 % at the 90th percentile for 2-10 A^2 cavities).
            - ``'asphericities'``: asphericity eta in [0, 1] (NaN if percolating).
            - ``'acylindricities'``: acylindricity c in [0, 1] (NaN if percolating).
            - ``'anisotropies'``: relative shape anisotropy kappa in [0, 1]
              (NaN if percolating).
            - ``'percolating'``: bool, True for cavities that wrap around the cell.
            - ``'max_inscribed_radii'``: radius in A of the largest sphere centred
              on a cavity voxel that touches no atom (largest included sphere),
              sampled at voxel centres, so low by up to half a voxel diagonal.

    Raises:
        TypeError: If ``cutoff_radii`` is a bool.
        ValueError: If ``probe_radius`` is negative, or ``cutoff_radii`` is an
            unknown string or ``"ionic"`` with an element without ionic radius.

    Examples:
        >>> from ase.io import read
        >>> structure = read('glass.xyz')
        >>> cavities = compute_cavities(structure, resolution=128)
        >>> free_volume_fraction = cavities['volumes'].sum() / structure.get_volume()
    """
    (
        void_labels,
        _occupied_grid,
        cell_array,
        percolating_labels,
        raw_labels,
        image_offsets,
        distance_field,
    ) = _build_cavity_grid(structure, resolution, cutoff_radii, probe_radius)
    number_of_voids = int(void_labels.max())
    grid_shape = np.array(void_labels.shape, dtype=float)

    if number_of_voids == 0:
        empty: np.ndarray = np.array([], dtype=np.float64)
        return {
            "volumes": empty,
            "surface_areas": empty,
            "asphericities": empty,
            "acylindricities": empty,
            "anisotropies": empty,
            "percolating": np.array([], dtype=bool),
            "max_inscribed_radii": empty,
        }

    # Voxel volume: exact cell volume divided by total voxel count.
    voxel_volume = abs(float(np.linalg.det(cell_array))) / float(np.prod(grid_shape))
    grid_shape_int = np.array(void_labels.shape, dtype=np.int64)

    radii = _atom_radii(structure.get_atomic_numbers(), cutoff_radii)
    surface_points, surface_weights = _exposed_surface_points(
        structure.get_positions(),
        structure.get_atomic_numbers(),
        radii + probe_radius,
        cell_array,
    )
    surface_areas = _assign_points_to_cavities(surface_points, surface_weights, void_labels, cell_array)[1:]

    # Largest included sphere. The field is exact below its cap, so rebuild it with a doubled cap until no
    # cavity reaches the cap; this ends once the cap exceeds the largest distance to an atom.
    cavity_indices = np.arange(1, number_of_voids + 1)
    cap = _voxel_diagonal(void_labels.shape, cell_array)
    deepest = np.asarray(ndimage.maximum(distance_field, void_labels, index=cavity_indices), dtype=np.float64)
    while len(structure) > 0 and np.any(deepest >= np.float32(cap)):
        cap *= 2.0
        deeper_field = _build_distance_field(
            structure.get_scaled_positions(),
            structure.get_atomic_numbers(),
            void_labels.shape,
            cutoff_radii,
            cell_array,
            probe_radius,
            cap,
        )
        deepest = np.asarray(ndimage.maximum(deeper_field, void_labels, index=cavity_indices), dtype=np.float64)
    max_inscribed_radii = deepest + probe_radius if len(structure) > 0 else np.full(number_of_voids, np.inf)

    volumes = np.zeros(number_of_voids, dtype=np.float64)
    asphericities = np.zeros(number_of_voids, dtype=np.float64)
    acylindricities = np.zeros(number_of_voids, dtype=np.float64)
    anisotropies = np.zeros(number_of_voids, dtype=np.float64)
    percolating = np.zeros(number_of_voids, dtype=bool)

    for void_index, voxel_indices, image_shifts in _iter_cavity_voxels(void_labels, raw_labels, image_offsets):
        volumes[void_index - 1] = len(voxel_indices) * voxel_volume

        if void_index in percolating_labels:
            percolating[void_index - 1] = True
            asphericities[void_index - 1] = acylindricities[void_index - 1] = anisotropies[void_index - 1] = np.nan
            continue

        unwrapped_indices = voxel_indices + image_shifts * grid_shape_int
        if len(unwrapped_indices) >= 3:  # noqa: PLR2004
            cavity_voxel_coordinates = (unwrapped_indices / grid_shape) @ cell_array
            (
                asphericities[void_index - 1],
                acylindricities[void_index - 1],
                anisotropies[void_index - 1],
            ) = _compute_gyration_tensor_descriptors(cavity_voxel_coordinates)

    return {
        "volumes": volumes,
        "surface_areas": surface_areas,
        "asphericities": asphericities,
        "acylindricities": acylindricities,
        "anisotropies": anisotropies,
        "percolating": percolating,
        "max_inscribed_radii": max_inscribed_radii,
    }

compute_coordination(structure: Atoms | list[Atoms], target_type: int, cutoff: float, neighbor_types: list[int] | None = None) -> dict[int, float]

Compute coordination number distribution for atoms of a target type.

Parameters:

Name Type Description Default
structure Atoms | list[Atoms]

The atomic structure as ASE object. Pass a list to use the first frame.

required
target_type int

Atom type (atomic number) for which to compute coordination.

required
cutoff float

Cutoff radius in Å.

required
neighbor_types list[int] | None

Valid neighbor atomic numbers. None means all types.

None

Returns:

Type Description
dict[int, float]

Mapping from coordination number to atom count.

Example

structure = read('glass.xyz') dist = compute_coordination(structure, target_type=14, cutoff=2.0)

Source code in amorphouspy/src/amorphouspy/properties/structural/rdf.py
def compute_coordination(
    structure: Atoms | list[Atoms],
    target_type: int,
    cutoff: float,
    neighbor_types: list[int] | None = None,
) -> dict[int, float]:
    """Compute coordination number distribution for atoms of a target type.

    Args:
        structure: The atomic structure as ASE object. Pass a list to use the first frame.
        target_type: Atom type (atomic number) for which to compute coordination.
        cutoff: Cutoff radius in Å.
        neighbor_types: Valid neighbor atomic numbers. None means all types.

    Returns:
        Mapping from coordination number to atom count.

    Example:
        >>> structure = read('glass.xyz')
        >>> dist = compute_coordination(structure, target_type=14, cutoff=2.0)

    """
    if isinstance(structure, list):
        structure = cast("Atoms", structure[0])
    neighbors = get_neighbors(
        structure,
        cutoff=cutoff,
        target_types=[target_type],
        neighbor_types=neighbor_types,
    )

    # Precompute the set of real IDs that belong to target_type once,
    # avoiding a per-atom np.where search inside the comprehension.
    types = structure.get_atomic_numbers()
    raw_ids = structure.arrays["id"] if "id" in structure.arrays else np.arange(1, len(structure) + 1)
    target_id_set: set[int] = {int(aid) for aid, t in zip(raw_ids, types, strict=False) if int(t) == target_type}

    # coord_numbers is keyed by real atom ID (matches OVITO IDs)
    coord_numbers = {
        central_id: len(nn_ids) for central_id, nn_ids in neighbors if len(nn_ids) > 0 or central_id in target_id_set
    }

    coord_numbers_distribution = count_distribution(coord_numbers)
    return {k: float(v) for k, v in sorted(coord_numbers_distribution.items())}

compute_debye_level(structure: Atoms, bulk_modulus_gpa: float, shear_modulus_gpa: float, *, normalization: VdosNormalization = 'unit') -> dict[str, float]

Compute the Debye level of the reduced VDOS from elastic moduli and the density of a structure.

The isotropic elastic continuum with bulk modulus \(B\), shear modulus \(G\) and mass density \(\rho\) has the longitudinal and transverse sound velocities

\[v_L = \sqrt{\frac{B + 4G/3}{\rho}}, \quad v_T = \sqrt{\frac{G}{\rho}},\]

in m/s for \(B\), \(G\) in GPa and \(\rho\) in g/cm\(^3\) (1 GPa / (1 g/cm\(^3\)) = \(10^6\) m\(^2\)/s\(^2\)). With the number density \(n\), the Debye frequency and temperature are

\[\nu_D^3 = \frac{9 n}{4 \pi \left(1 / v_L^3 + 2 / v_T^3\right)}, \quad \theta_D = \frac{h \nu_D}{k_B},\]

and the Debye VDOS \(g_D(\nu) = 3 \nu^2 / \nu_D^3\) (\(\nu \le \nu_D\), normalised to 1) gives the Debye level \(g_D(\nu) / \nu^2 = 3 / \nu_D^3\) in THz\(^{-3}\), the low-frequency limit of the reduced VDOS of an isotropic solid. For "3N" the level is \(3N\) times larger, matching a VDOS that integrates to \(3N\).

The moduli are taken as given: no fit of the VDOS is made, so without moduli there is no Debye level. Use moduli of the same model and state as the VDOS, e.g. elastic_simulation(...)["moduli"]["B"] and ["G"], which are in GPa. Only the masses (structure.get_masses(), in amu) and the cell volume enter \(\rho\) and \(n\); the positions are not used.

The lowest frequency the periodic box supports is \(\nu_\mathrm{min} = v_T / L_\mathrm{max}\), the transverse acoustic mode whose wavelength is the largest perpendicular cell height \(L_\mathrm{max}\) (the edge \(L\) of a cubic box). The box has no acoustic modes below it, so the reduced VDOS there does not represent the bulk glass. Taking \(L_\mathrm{max}\) as the longest wavelength is exact for orthogonal boxes and assumes a cell that is not strongly skewed otherwise.

Parameters:

Name Type Description Default
structure Atoms

Periodic structure as an ASE object, with a 3-D cell of positive volume.

required
bulk_modulus_gpa float

Bulk modulus \(B\) in GPa.

required
shear_modulus_gpa float

Shear modulus \(G\) in GPa.

required
normalization VdosNormalization

"unit" (default) or "3N", the normalisation of the VDOS the level is compared with, as in :func:compute_vdos_from_velocities. "none" is rejected: a power spectral density has no Debye level.

'unit'

Returns:

Type Description
dict[str, float]

A dict of floats: "longitudinal_velocity_m_s" and "transverse_velocity_m_s": \(v_L\) and \(v_T\) in m/s. "debye_frequency_thz": \(\nu_D\) in THz. "debye_temperature_k": \(\theta_D\) in K. "debye_level_thz-3": \(3 / \nu_D^3\) ("unit") or \(9N / \nu_D^3\) ("3N") in THz\(^{-3}\). "lowest_box_frequency_thz": \(\nu_\mathrm{min} = v_T / L_\mathrm{max}\) in THz. "density_g_cm3": \(\rho\) in g/cm\(^3\). "number_density_per_a3": \(n\) in atoms/Å\(^3\).

Raises:

Type Description
ValueError

If a modulus is not positive and finite, normalization is not "unit" or "3N", structure has no atoms, is not periodic in all three directions, or its cell volume is not positive.

Example
>>> from ase import Atoms
>>> silica = Atoms("Si1000O2000", cell=[35.661] * 3, pbc=True)  # 2.2 g/cm^3
>>> debye = compute_debye_level(silica, bulk_modulus_gpa=36.7, shear_modulus_gpa=31.2)
>>> round(debye["density_g_cm3"], 3), round(debye["transverse_velocity_m_s"])
(2.2, 3766)
>>> round(debye["debye_frequency_thz"], 2), round(debye["debye_temperature_k"])
(10.4, 499)
>>> round(debye["lowest_box_frequency_thz"], 3)
1.056
Source code in amorphouspy/src/amorphouspy/properties/vibrational/debye.py
def compute_debye_level(
    structure: "Atoms",
    bulk_modulus_gpa: float,
    shear_modulus_gpa: float,
    *,
    normalization: VdosNormalization = "unit",
) -> dict[str, float]:
    r"""Compute the Debye level of the reduced VDOS from elastic moduli and the density of a structure.

    The isotropic elastic continuum with bulk modulus $B$, shear modulus $G$ and mass density $\rho$ has the
    longitudinal and transverse sound velocities

    $$v_L = \sqrt{\frac{B + 4G/3}{\rho}}, \quad v_T = \sqrt{\frac{G}{\rho}},$$

    in m/s for $B$, $G$ in GPa and $\rho$ in g/cm$^3$ (1 GPa / (1 g/cm$^3$) = $10^6$ m$^2$/s$^2$). With the number
    density $n$, the Debye frequency and temperature are

    $$\nu_D^3 = \frac{9 n}{4 \pi \left(1 / v_L^3 + 2 / v_T^3\right)}, \quad \theta_D = \frac{h \nu_D}{k_B},$$

    and the Debye VDOS $g_D(\nu) = 3 \nu^2 / \nu_D^3$ ($\nu \le \nu_D$, normalised to 1) gives the Debye level
    $g_D(\nu) / \nu^2 = 3 / \nu_D^3$ in THz$^{-3}$, the low-frequency limit of the reduced VDOS of an isotropic solid.
    For ``"3N"`` the level is $3N$ times larger, matching a VDOS that integrates to $3N$.

    The moduli are taken as given: no fit of the VDOS is made, so without moduli there is no Debye level. Use moduli of
    the same model and state as the VDOS, e.g. ``elastic_simulation(...)["moduli"]["B"]`` and ``["G"]``, which are in
    GPa. Only the masses (``structure.get_masses()``, in amu) and the cell volume enter $\rho$ and $n$; the positions
    are not used.

    The lowest frequency the periodic box supports is $\nu_\mathrm{min} = v_T / L_\mathrm{max}$, the transverse
    acoustic mode whose wavelength is the largest perpendicular cell height $L_\mathrm{max}$ (the edge $L$ of a cubic
    box). The box has no acoustic modes below it, so the reduced VDOS there does not represent the bulk glass. Taking
    $L_\mathrm{max}$ as the longest wavelength is exact for orthogonal boxes and assumes a cell that is not strongly
    skewed otherwise.

    Args:
        structure: Periodic structure as an ASE object, with a 3-D cell of positive volume.
        bulk_modulus_gpa: Bulk modulus $B$ in GPa.
        shear_modulus_gpa: Shear modulus $G$ in GPa.
        normalization: ``"unit"`` (default) or ``"3N"``, the normalisation of the VDOS the level is compared with, as
            in :func:`compute_vdos_from_velocities`. ``"none"`` is rejected: a power spectral density has no Debye
            level.

    Returns:
        A dict of floats:
            ``"longitudinal_velocity_m_s"`` and ``"transverse_velocity_m_s"``: $v_L$ and $v_T$ in m/s.
            ``"debye_frequency_thz"``: $\nu_D$ in THz.
            ``"debye_temperature_k"``: $\theta_D$ in K.
            ``"debye_level_thz-3"``: $3 / \nu_D^3$ (``"unit"``) or $9N / \nu_D^3$ (``"3N"``) in THz$^{-3}$.
            ``"lowest_box_frequency_thz"``: $\nu_\mathrm{min} = v_T / L_\mathrm{max}$ in THz.
            ``"density_g_cm3"``: $\rho$ in g/cm$^3$.
            ``"number_density_per_a3"``: $n$ in atoms/Å$^3$.

    Raises:
        ValueError: If a modulus is not positive and finite, ``normalization`` is not ``"unit"`` or ``"3N"``,
            ``structure`` has no atoms, is not periodic in all three directions, or its cell volume is not positive.

    Example:
        ```pycon
        >>> from ase import Atoms
        >>> silica = Atoms("Si1000O2000", cell=[35.661] * 3, pbc=True)  # 2.2 g/cm^3
        >>> debye = compute_debye_level(silica, bulk_modulus_gpa=36.7, shear_modulus_gpa=31.2)
        >>> round(debye["density_g_cm3"], 3), round(debye["transverse_velocity_m_s"])
        (2.2, 3766)
        >>> round(debye["debye_frequency_thz"], 2), round(debye["debye_temperature_k"])
        (10.4, 499)
        >>> round(debye["lowest_box_frequency_thz"], 3)
        1.056

        ```
    """
    for name, modulus in (("bulk_modulus_gpa", bulk_modulus_gpa), ("shear_modulus_gpa", shear_modulus_gpa)):
        if not (_is_real_number(modulus) and np.isfinite(modulus) and modulus > 0):
            msg = f"{name} must be positive and finite, got {modulus}."
            raise ValueError(msg)
    if normalization not in ("unit", "3N"):
        msg = (
            f"Unknown normalization {normalization!r}; allowed values are 'unit' and '3N' "
            "(a power spectral density has no Debye level)."
        )
        raise ValueError(msg)
    n_atoms = len(structure)
    if n_atoms == 0:
        msg = "structure contains no atoms."
        raise ValueError(msg)
    if not np.all(structure.pbc):
        msg = "structure must be periodic in all three directions."
        raise ValueError(msg)
    volume_a3 = float(structure.cell.volume)
    if not volume_a3 > 0:
        msg = "structure must have a 3-D cell with positive volume."
        raise ValueError(msg)

    # amu -> g and A^3 -> cm^3.
    density_g_cm3 = float(structure.get_masses().sum()) * atomic_mass * 1e3 / (volume_a3 * 1e-24)
    number_density_per_a3 = n_atoms / volume_a3
    longitudinal_modulus_gpa = bulk_modulus_gpa + 4 * shear_modulus_gpa / 3
    v_longitudinal = float(np.sqrt(longitudinal_modulus_gpa / density_g_cm3 * _GPA_PER_G_CM3_TO_M2_S2))
    v_transverse = float(np.sqrt(shear_modulus_gpa / density_g_cm3 * _GPA_PER_G_CM3_TO_M2_S2))
    # Number density in m^-3 and velocities in m/s give the Debye frequency in Hz.
    debye_frequency_hz = (
        9 * number_density_per_a3 * 1e30 / (4 * np.pi * (1 / v_longitudinal**3 + 2 / v_transverse**3))
    ) ** (1 / 3)
    debye_frequency_thz = debye_frequency_hz * 1e-12
    scale = 1.0 if normalization == "unit" else 3.0 * n_atoms
    largest_height_a = float(cell_perpendicular_heights(structure.cell.array).max())
    return {
        "longitudinal_velocity_m_s": v_longitudinal,
        "transverse_velocity_m_s": v_transverse,
        "debye_frequency_thz": debye_frequency_thz,
        "debye_temperature_k": h * debye_frequency_hz / Boltzmann,
        "debye_level_thz-3": scale * 3 / debye_frequency_thz**3,
        "lowest_box_frequency_thz": v_transverse / (largest_height_a * 1e-10) * 1e-12,
        "density_g_cm3": density_g_cm3,
        "number_density_per_a3": number_density_per_a3,
    }

compute_dielectric_from_velocities(velocities: NDArray, masses: NDArray, charges: ArrayLike, dt_fs: float, volume_a3: float, *, groups: dict[str, dict[str, NDArray]] | None = None, eps_inf: float = 1.0, window: VdosWindow = 'hann', n_lag_frames: int | None = None, remove_com: bool = True) -> dict[str, Any]

Compute the isotropic dielectric function from the charge-current fluctuations of an MD trajectory.

The charges \(Z_i\) moving with the velocities \(v_i\) carry the current \(J(t) = \sum_i Z_i\, v_i(t)\), the time derivative of the dipole moment of the cell (which, unlike the dipole itself, is well defined in a periodic box). Linear response gives the conductivity of the cell of volume \(V\) from the equilibrium fluctuations of \(J\),

\[\sigma(\nu) = \frac{1}{3 V k_B T} \int_0^\infty \langle J(0) \cdot J(t) \rangle\, e^{i 2\pi\nu t}\, dt, \qquad \varepsilon(\nu) = \varepsilon_\infty + \frac{i\, \sigma(\nu)}{2\pi\nu\, \varepsilon_0},\]

with the same sign convention as :func:compute_dielectric_function (\(\operatorname{Im} \varepsilon \ge 0\) for absorption). The transform is one-sided, so the real and imaginary parts obey the Kramers-Kronig relations.

The temperature is taken from the trajectory itself, \(k_B T = \langle \sum_i m_i |v_i|^2 \rangle / n_\mathrm{dof}\) with \(n_\mathrm{dof} = 3N - 3\) when the centre-of-mass velocity is removed and \(3N\) otherwise, so the unit of the velocities cancels and no temperature is passed. For a harmonic solid at equipartition the result is that of :func:compute_dielectric_function with the strengths of :func:compute_ir_oscillator_strengths: each mode contributes \(f_m\) to \(\langle J \cdot J \rangle / 3 k_B T\), and because the response of a harmonic oscillator is the same in classical and quantum mechanics, no quantum correction applies. Anharmonicity enters through the dynamics, as the temperature-dependent position and width of the peaks.

The correlation function is the unbiased estimate over all time origins for the lags \(0 \ldots n_\mathrm{lag} - 1\). It is multiplied by the decaying half of window (1 at zero lag), which smooths the spectrum over about \(1 / (n_\mathrm{lag}\, \Delta t)\), and transformed on the grid np.fft.rfftfreq(2 * n_lag_frames, dt_fs * 1e-3): the cosine part with the trapezoid rule over the frames, the sine part over the band-limited interpolation on a 16 times finer time grid, without which \(\operatorname{Re} \varepsilon\) below a mode at \(\nu_0\) would be too large by about \((2\pi\nu_0 \Delta t)^2 / 12\). The integral of \(\operatorname{Re} \sigma\) is fixed by the zero-lag value alone (the f-sum rule), whatever the window. A window with negative side lobes, and above all None, can make \(\operatorname{Im} \varepsilon\) slightly negative next to a sharp peak.

At \(\nu = 0\) the dielectric function is NaN: there \(\sigma\) is the DC ionic conductivity, which is finite when modifier ions diffuse during the run, and \(\varepsilon\) diverges.

With groups the current of every group \(G\) gives, for each pair of labels of one grouping, the part of \(\varepsilon - \varepsilon_\infty\) that comes from \(\langle J_G(0) \cdot J_{G'}(t) \rangle\) and \(\langle J_{G'}(0) \cdot J_G(t) \rangle\). The cross terms can be negative. Over the unordered pairs of a grouping that holds every atom once they sum to \(\varepsilon - \varepsilon_\infty\).

Parameters:

Name Type Description Default
velocities NDArray

Velocities, shape \((n_\mathrm{frames}, N, 3)\), in any unit, sampled every dt_fs.

required
masses NDArray

Atomic masses, shape \((N,)\), in the order of the atoms.

required
charges ArrayLike

Atomic charges in units of the elementary charge: shape \((N,)\) for scalar charges or \((N, 3, 3)\) for charge tensors \(Z_{i,\alpha\beta}\).

required
dt_fs float

Time between frames in fs.

required
volume_a3 float

The volume of the cell in Å\(^3\).

required
groups dict[str, dict[str, NDArray]] | None

Atom groups as {grouping: {label: indices}} with 0-based positions, e.g. from :func:classify_vibrational_groups.

None
eps_inf float

The high-frequency dielectric constant \(\varepsilon_\infty\); see :func:compute_dielectric_function.

1.0
window VdosWindow

The window whose decaying half multiplies the correlation function: "hann", "hamming", "blackmanharris", ("gaussian", std) with std in frames, or None for a sharp cut.

'hann'
n_lag_frames int | None

The number of lags kept. Defaults to n_frames // 2.

None
remove_com bool

Whether to subtract the centre-of-mass velocity of every frame.

True

Returns:

Type Description
dict[str, Any]

A dictionary with: "frequencies_thz": The \(n_\mathrm{lag} + 1\) frequencies in THz. "epsilon": The complex dielectric function, NaN at zero frequency. "conductivity_s_per_m": The complex conductivity \(\sigma(\nu)\) in S/m. "partial_susceptibility": {grouping: {"A-B": complex array}} for every unordered pair of labels, in the order of the labels, only with groups. "n_lag_frames", "eps_inf": The values used.

Raises:

Type Description
ValueError

If the trajectory, masses or dt_fs are invalid (see :func:compute_vdos_from_velocities), the velocities are all zero, charges is not finite with shape \((N,)\) or \((N, 3, 3)\), volume_a3 or eps_inf is not positive and finite, window is unknown, n_lag_frames is not an integer in \([2, n_\mathrm{frames} - 1]\), or groups has no labels or invalid positions.

Warns:

Type Description
UserWarning

If the charges do not sum to zero over the atoms.

Example
>>> dielectric = compute_dielectric_from_velocities(  # doctest: +SKIP
...     velocities, structure.get_masses(), charges, dt_fs=5.0, volume_a3=structure.cell.volume
... )
>>> dielectric["frequencies_thz"], dielectric["epsilon"].imag  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/infrared.py
def compute_dielectric_from_velocities(
    velocities: NDArray,
    masses: NDArray,
    charges: ArrayLike,
    dt_fs: float,
    volume_a3: float,
    *,
    groups: dict[str, dict[str, NDArray]] | None = None,
    eps_inf: float = 1.0,
    window: VdosWindow = "hann",
    n_lag_frames: int | None = None,
    remove_com: bool = True,
) -> dict[str, Any]:
    r"""Compute the isotropic dielectric function from the charge-current fluctuations of an MD trajectory.

    The charges $Z_i$ moving with the velocities $v_i$ carry the current $J(t) = \sum_i Z_i\, v_i(t)$, the time
    derivative of the dipole moment of the cell (which, unlike the dipole itself, is well defined in a periodic
    box). Linear response gives the conductivity of the cell of volume $V$ from the equilibrium fluctuations of $J$,

    $$\sigma(\nu) = \frac{1}{3 V k_B T} \int_0^\infty \langle J(0) \cdot J(t) \rangle\, e^{i 2\pi\nu t}\, dt,
    \qquad \varepsilon(\nu) = \varepsilon_\infty + \frac{i\, \sigma(\nu)}{2\pi\nu\, \varepsilon_0},$$

    with the same sign convention as :func:`compute_dielectric_function` ($\operatorname{Im} \varepsilon \ge 0$ for
    absorption). The transform is one-sided, so the real and imaginary parts obey the Kramers-Kronig relations.

    The temperature is taken from the trajectory itself, $k_B T = \langle \sum_i m_i |v_i|^2 \rangle / n_\mathrm{dof}$
    with $n_\mathrm{dof} = 3N - 3$ when the centre-of-mass velocity is removed and $3N$ otherwise, so the unit of
    the velocities cancels and no temperature is passed. For a harmonic solid at equipartition the result is that of
    :func:`compute_dielectric_function` with the strengths of :func:`compute_ir_oscillator_strengths`: each mode
    contributes $f_m$ to $\langle J \cdot J \rangle / 3 k_B T$, and because the response of a harmonic oscillator is
    the same in classical and quantum mechanics, no quantum correction applies. Anharmonicity enters through the
    dynamics, as the temperature-dependent position and width of the peaks.

    The correlation function is the unbiased estimate over all time origins for the lags
    $0 \ldots n_\mathrm{lag} - 1$. It is multiplied by the decaying half of ``window`` (1 at zero lag), which
    smooths the spectrum over about $1 / (n_\mathrm{lag}\, \Delta t)$, and transformed on the grid
    ``np.fft.rfftfreq(2 * n_lag_frames, dt_fs * 1e-3)``: the cosine part with the trapezoid rule over the frames,
    the sine part over the band-limited interpolation on a 16 times finer time grid, without which
    $\operatorname{Re} \varepsilon$ below a mode at $\nu_0$ would be too large by about
    $(2\pi\nu_0 \Delta t)^2 / 12$. The integral of $\operatorname{Re} \sigma$ is fixed by the zero-lag value alone
    (the f-sum rule), whatever the window. A window with negative side lobes, and above all ``None``, can make
    $\operatorname{Im} \varepsilon$ slightly negative next to a sharp peak.

    At $\nu = 0$ the dielectric function is NaN: there $\sigma$ is the DC ionic conductivity, which is finite when
    modifier ions diffuse during the run, and $\varepsilon$ diverges.

    With ``groups`` the current of every group $G$ gives, for each pair of labels of one grouping, the part of
    $\varepsilon - \varepsilon_\infty$ that comes from $\langle J_G(0) \cdot J_{G'}(t) \rangle$ and
    $\langle J_{G'}(0) \cdot J_G(t) \rangle$. The cross terms can be negative. Over the unordered pairs of a
    grouping that holds every atom once they sum to $\varepsilon - \varepsilon_\infty$.

    Args:
        velocities: Velocities, shape $(n_\mathrm{frames}, N, 3)$, in any unit, sampled every ``dt_fs``.
        masses: Atomic masses, shape $(N,)$, in the order of the atoms.
        charges: Atomic charges in units of the elementary charge: shape $(N,)$ for scalar charges or
            $(N, 3, 3)$ for charge tensors $Z_{i,\alpha\beta}$.
        dt_fs: Time between frames in fs.
        volume_a3: The volume of the cell in Å$^3$.
        groups: Atom groups as ``{grouping: {label: indices}}`` with 0-based positions, e.g. from
            :func:`classify_vibrational_groups`.
        eps_inf: The high-frequency dielectric constant $\varepsilon_\infty$; see
            :func:`compute_dielectric_function`.
        window: The window whose decaying half multiplies the correlation function: ``"hann"``, ``"hamming"``,
            ``"blackmanharris"``, ``("gaussian", std)`` with ``std`` in frames, or ``None`` for a sharp cut.
        n_lag_frames: The number of lags kept. Defaults to ``n_frames // 2``.
        remove_com: Whether to subtract the centre-of-mass velocity of every frame.

    Returns:
        A dictionary with:
            ``"frequencies_thz"``: The $n_\mathrm{lag} + 1$ frequencies in THz.
            ``"epsilon"``: The complex dielectric function, NaN at zero frequency.
            ``"conductivity_s_per_m"``: The complex conductivity $\sigma(\nu)$ in S/m.
            ``"partial_susceptibility"``: ``{grouping: {"A-B": complex array}}`` for every unordered pair of
                labels, in the order of the labels, only with ``groups``.
            ``"n_lag_frames"``, ``"eps_inf"``: The values used.

    Raises:
        ValueError: If the trajectory, masses or ``dt_fs`` are invalid (see :func:`compute_vdos_from_velocities`),
            the velocities are all zero, ``charges`` is not finite with shape $(N,)$ or $(N, 3, 3)$,
            ``volume_a3`` or ``eps_inf`` is not positive and finite, ``window`` is unknown, ``n_lag_frames`` is
            not an integer in $[2, n_\mathrm{frames} - 1]$, or ``groups`` has no labels or invalid positions.

    Warns:
        UserWarning: If the charges do not sum to zero over the atoms.

    Example:
        ```pycon
        >>> dielectric = compute_dielectric_from_velocities(  # doctest: +SKIP
        ...     velocities, structure.get_masses(), charges, dt_fs=5.0, volume_a3=structure.cell.volume
        ... )
        >>> dielectric["frequencies_thz"], dielectric["epsilon"].imag  # doctest: +SKIP

        ```
    """
    velocities, masses = _validate_trajectory(velocities, masses, dt_fs)
    n_frames, n_atoms, _ = velocities.shape
    charges = _validate_charges(charges, n_atoms)
    _validate_positive("volume_a3", volume_a3)
    _validate_positive("eps_inf", eps_inf)
    _validate_window(window)
    if n_lag_frames is None:
        n_lag_frames = n_frames // 2
    if isinstance(n_lag_frames, bool) or not (
        isinstance(n_lag_frames, int | np.integer) and _MIN_LAG_FRAMES <= n_lag_frames <= n_frames - 1
    ):
        msg = f"n_lag_frames must be an integer in [{_MIN_LAG_FRAMES}, {n_frames - 1}], got {n_lag_frames!r}."
        raise ValueError(msg)

    # Column 0 sums over every atom (the total); with groups, one column per group label follows.
    membership = np.ones((n_atoms, 1))
    keys: list[tuple[str, str]] = []
    if groups is not None:
        keys, selections = _group_selections(groups)
        membership = np.hstack([membership, _membership(selections, n_atoms)])
    com_velocity, _, kinetic_sum = _trajectory_statistics(velocities, masses, None, remove_com=remove_com)
    thermal = kinetic_sum / (n_frames * _N_COMPONENTS * (n_atoms - 1 if remove_com else n_atoms))  # k_B T
    currents = _charge_currents(velocities, charges, com_velocity, membership)

    # Zero padding to 2N makes the correlations linear, as in the VACF.
    spectrum = scipy.fft.rfft(currents, n=2 * n_frames, axis=0)
    dt_ps = dt_fs * 1e-3
    frequencies = np.fft.rfftfreq(2 * n_lag_frames, d=dt_ps)
    origins = n_frames - np.arange(n_lag_frames)
    taper = 1.0 if window is None else scipy.signal.get_window(window, 2 * n_lag_frames)[n_lag_frames:]

    def response(first: int, second: int) -> NDArray[np.complex128]:
        """One-sided transform of <J_first(0) . J_second(t)> + <J_second(0) . J_first(t)>, halved, over 3 k_B T."""
        power = np.einsum("fa,fa->f", spectrum[:, first].real, spectrum[:, second].real)
        power += np.einsum("fa,fa->f", spectrum[:, first].imag, spectrum[:, second].imag)
        correlation = scipy.fft.irfft(power, n=2 * n_frames)[:n_lag_frames] / origins
        correlation *= taper / (_N_COMPONENTS * thermal)
        # Real part: half the spectrum of the even extension, exact for the sampled correlation (trapezoid rule).
        even = np.concatenate([correlation, [0.0], correlation[:0:-1]])
        real = 0.5 * dt_ps * scipy.fft.rfft(even).real
        # Imaginary part: the sine transform of the band-limited interpolation on a finer time grid. On the frames
        # themselves the sum would replace 1 / x by (dt / 2) cot(x dt / 2) and overestimate the response below a
        # mode at nu0 by a factor of about 1 + (2 pi nu0 dt)^2 / 12.
        fine = scipy.signal.resample(even, even.size * _LAG_OVERSAMPLING)[: n_lag_frames * _LAG_OVERSAMPLING]
        imaginary = -scipy.fft.rfft(fine, n=even.size * _LAG_OVERSAMPLING).imag[: n_lag_frames + 1]
        return real + 1j * (dt_ps / _LAG_OVERSAMPLING) * imaginary

    def susceptibility(current_response: NDArray[np.complex128]) -> NDArray[np.complex128]:
        with np.errstate(divide="ignore", invalid="ignore"):
            chi = (2j * math.pi * _IR_THZ2_A3 / volume_a3) * current_response / frequencies
        chi[0] = np.nan
        return chi

    total = response(0, 0)
    result: dict[str, Any] = {
        "frequencies_thz": frequencies,
        "epsilon": eps_inf + susceptibility(total),
        "conductivity_s_per_m": total * (_S_PER_M_A3 / volume_a3),
    }
    if groups is not None:
        column_of = {key: column for column, key in enumerate(keys, start=1)}
        result["partial_susceptibility"] = {
            grouping: {
                f"{first}-{second}": susceptibility(
                    response(column_of[grouping, first], column_of[grouping, second]) * (1 if first == second else 2)
                )
                for position, first in enumerate(labels)
                for second in list(labels)[position:]
            }
            for grouping, labels in groups.items()
        }
    result.update({"n_lag_frames": int(n_lag_frames), "eps_inf": float(eps_inf)})
    return result

compute_dielectric_function(frequencies_thz: ArrayLike, strengths: ArrayLike, volume_a3: float, *, frequency_grid_thz: ArrayLike | None = None, eps_inf: float = 1.0, damping_thz: float = 0.5) -> dict[str, Any]

Compute the isotropic dielectric function of damped harmonic modes from their oscillator strengths.

Every mode of frequency \(\nu_m\) and oscillator strength \(f_m\) (:func:compute_ir_oscillator_strengths) responds to a field as a damped oscillator, and the modes of a cell of volume \(V\) add up to

\[\varepsilon(\nu) = \varepsilon_\infty + \frac{e^2}{4\pi^2 \varepsilon_0 V} \sum_m \frac{f_m}{\nu_m^2 - \nu^2 - i \gamma \nu},\]

with the time dependence \(e^{-i 2\pi\nu t}\), so that absorption is \(\operatorname{Im} \varepsilon \ge 0\). The prefactor is \(44224.5\ \mathrm{THz^2\,Å^3\,amu}/e^2\). The peaks of \(\operatorname{Im} \varepsilon\) are the transverse optical modes; those of the loss function of :func:compute_optical_response the longitudinal ones.

\(\varepsilon_\infty\) is the electronic contribution, which a model of rigid ions does not have: 1 leaves it out, and the square of the optical refractive index (about 2.1 for silica) adds the measured one. The damping \(\gamma\) is the full width at half maximum of the peaks of \(\operatorname{Im} \varepsilon\); in a harmonic calculation it is a numerical broadening that joins the discrete modes of a finite cell into a spectrum, not a physical linewidth.

Modes with \(\nu_m \le 0\) (imaginary modes, reported as negative frequencies) are left out and counted.

Parameters:

Name Type Description Default
frequencies_thz ArrayLike

The mode frequencies in THz, shape \((M,)\), e.g. "frequencies_thz" of :func:diagonalize_dynamical_matrix.

required
strengths ArrayLike

The oscillator strengths in \(e^2/\mathrm{amu}\), shape \((M,)\), e.g. "strengths" of :func:compute_ir_oscillator_strengths. They may be negative: a pair strength of its "partial_strengths" gives that pair's share of \(\varepsilon - \varepsilon_\infty\) once eps_inf is subtracted from the result.

required
volume_a3 float

The volume of the cell in Å\(^3\).

required
frequency_grid_thz ArrayLike | None

The frequencies in THz at which to evaluate, 1-D and strictly increasing. Defaults to a grid from 0 to the highest mode plus \(5\gamma\) in steps of \(\gamma / 5\).

None
eps_inf float

The high-frequency dielectric constant \(\varepsilon_\infty\).

1.0
damping_thz float

The damping \(\gamma\) in THz.

0.5

Returns:

Type Description
dict[str, Any]

A dictionary with: "frequencies_thz": The grid in THz. "epsilon": The complex dielectric function on the grid. "epsilon_static": The undamped static limit \(\varepsilon_\infty + (e^2 / 4\pi^2\varepsilon_0 V) \sum_m f_m / \nu_m^2\). "n_modes_excluded": The number of modes with \(\nu_m \le 0\) left out. "eps_inf", "damping_thz": The values used.

Raises:

Type Description
ValueError

If frequencies_thz is not a non-empty finite 1-D array, strengths is not finite with the same shape, volume_a3, eps_inf or damping_thz is not positive and finite, or the grid is not 1-D, finite and strictly increasing with at least 2 points.

Example
>>> infrared = compute_ir_oscillator_strengths(  # doctest: +SKIP
...     modes["eigenvectors"], minimised.get_masses(), charges
... )
>>> dielectric = compute_dielectric_function(  # doctest: +SKIP
...     modes["frequencies_thz"], infrared["strengths"], minimised.cell.volume, eps_inf=2.1
... )
>>> dielectric["epsilon"].imag  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/infrared.py
def compute_dielectric_function(
    frequencies_thz: ArrayLike,
    strengths: ArrayLike,
    volume_a3: float,
    *,
    frequency_grid_thz: ArrayLike | None = None,
    eps_inf: float = 1.0,
    damping_thz: float = 0.5,
) -> dict[str, Any]:
    r"""Compute the isotropic dielectric function of damped harmonic modes from their oscillator strengths.

    Every mode of frequency $\nu_m$ and oscillator strength $f_m$ (:func:`compute_ir_oscillator_strengths`) responds
    to a field as a damped oscillator, and the modes of a cell of volume $V$ add up to

    $$\varepsilon(\nu) = \varepsilon_\infty + \frac{e^2}{4\pi^2 \varepsilon_0 V}
    \sum_m \frac{f_m}{\nu_m^2 - \nu^2 - i \gamma \nu},$$

    with the time dependence $e^{-i 2\pi\nu t}$, so that absorption is $\operatorname{Im} \varepsilon \ge 0$. The
    prefactor is $44224.5\ \mathrm{THz^2\,Å^3\,amu}/e^2$. The peaks of $\operatorname{Im} \varepsilon$ are the
    transverse optical modes; those of the loss function of :func:`compute_optical_response` the longitudinal ones.

    $\varepsilon_\infty$ is the electronic contribution, which a model of rigid ions does not have: 1 leaves it out, and
    the square of the optical refractive index (about 2.1 for silica) adds the measured one. The damping $\gamma$ is
    the full width at half maximum of the peaks of $\operatorname{Im} \varepsilon$; in a harmonic calculation it is a
    numerical broadening that joins the discrete modes of a finite cell into a spectrum, not a physical linewidth.

    Modes with $\nu_m \le 0$ (imaginary modes, reported as negative frequencies) are left out and counted.

    Args:
        frequencies_thz: The mode frequencies in THz, shape $(M,)$, e.g. ``"frequencies_thz"`` of
            :func:`diagonalize_dynamical_matrix`.
        strengths: The oscillator strengths in $e^2/\mathrm{amu}$, shape $(M,)$, e.g. ``"strengths"`` of
            :func:`compute_ir_oscillator_strengths`. They may be negative: a pair strength of its
            ``"partial_strengths"`` gives that pair's share of $\varepsilon - \varepsilon_\infty$ once ``eps_inf``
            is subtracted from the result.
        volume_a3: The volume of the cell in Å$^3$.
        frequency_grid_thz: The frequencies in THz at which to evaluate, 1-D and strictly increasing. Defaults to
            a grid from 0 to the highest mode plus $5\gamma$ in steps of $\gamma / 5$.
        eps_inf: The high-frequency dielectric constant $\varepsilon_\infty$.
        damping_thz: The damping $\gamma$ in THz.

    Returns:
        A dictionary with:
            ``"frequencies_thz"``: The grid in THz.
            ``"epsilon"``: The complex dielectric function on the grid.
            ``"epsilon_static"``: The undamped static limit
                $\varepsilon_\infty + (e^2 / 4\pi^2\varepsilon_0 V) \sum_m f_m / \nu_m^2$.
            ``"n_modes_excluded"``: The number of modes with $\nu_m \le 0$ left out.
            ``"eps_inf"``, ``"damping_thz"``: The values used.

    Raises:
        ValueError: If ``frequencies_thz`` is not a non-empty finite 1-D array, ``strengths`` is not finite with the
            same shape, ``volume_a3``, ``eps_inf`` or ``damping_thz`` is not positive and finite, or the grid is not
            1-D, finite and strictly increasing with at least 2 points.

    Example:
        ```pycon
        >>> infrared = compute_ir_oscillator_strengths(  # doctest: +SKIP
        ...     modes["eigenvectors"], minimised.get_masses(), charges
        ... )
        >>> dielectric = compute_dielectric_function(  # doctest: +SKIP
        ...     modes["frequencies_thz"], infrared["strengths"], minimised.cell.volume, eps_inf=2.1
        ... )
        >>> dielectric["epsilon"].imag  # doctest: +SKIP

        ```
    """
    frequencies = np.asarray(frequencies_thz, dtype=np.float64)
    if frequencies.ndim != 1 or frequencies.size == 0 or not np.all(np.isfinite(frequencies)):
        msg = f"frequencies_thz must be a non-empty 1-D array of finite values, got shape {frequencies.shape}."
        raise ValueError(msg)
    strengths = np.asarray(strengths, dtype=np.float64)
    if strengths.shape != frequencies.shape or not np.all(np.isfinite(strengths)):
        msg = f"strengths must hold {frequencies.size} finite values, one per mode, got shape {strengths.shape}."
        raise ValueError(msg)
    _validate_positive("volume_a3", volume_a3)
    _validate_positive("eps_inf", eps_inf)
    _validate_positive("damping_thz", damping_thz)
    if frequency_grid_thz is None:
        grid = _harmonic_grid(None, frequencies, damping_thz)
    else:
        grid = _validate_frequency_grid(frequency_grid_thz)

    kept = frequencies > 0
    squares, kept_strengths = frequencies[kept] ** 2, strengths[kept]
    scale = _IR_THZ2_A3 / volume_a3
    shift = grid**2 + 1j * damping_thz * grid
    epsilon = np.full(grid.size, eps_inf, dtype=np.complex128)
    step = max(1, _common._CHUNK_BYTES // (grid.size * epsilon.itemsize))  # noqa: SLF001
    for start in range(0, squares.size, step):
        block = slice(start, start + step)
        epsilon += scale * ((1 / (squares[None, block] - shift[:, None])) @ kept_strengths[block])
    return {
        "frequencies_thz": grid,
        "epsilon": epsilon,
        "epsilon_static": float(eps_inf + scale * np.sum(kept_strengths / squares)),
        "n_modes_excluded": int(frequencies.size - np.count_nonzero(kept)),
        "eps_inf": float(eps_inf),
        "damping_thz": float(damping_thz),
    }

compute_guttmann_rings(structure: Atoms | list[Atoms], bond_lengths: dict[tuple[str, str], float], max_size: int = 24, n_cpus: int = 1) -> tuple[dict[int, float], float]

Compute the Guttman ring size distribution and mean ring size.

The ring associated with each T-O bond is the shortest cycle containing it. The search runs on the bipartite T-O atom network, so oxygen triclusters cannot masquerade as small rings and edge-sharing polyhedra are detected. Under periodic boundary conditions only cycles that close in real space are counted; see the module docstring for the full criterion.

Ring size is the number of network-former atoms (T atoms) in the ring, following Guttman's original convention. The smallest reportable ring is 2, two formers bridged by two distinct oxygens.

Parameters:

Name Type Description Default
structure Atoms | list[Atoms]

ASE Atoms object containing atomic coordinates and types. Pass a list to use the first frame.

required
bond_lengths dict[tuple[str, str], float]

Maximum bond lengths for each element pair, e.g. {('Si', 'O'): 1.8, ('Al', 'O'): 1.95}. All T-O pairs must be specified; T-T and O-O pairs are ignored.

required
max_size int

Maximum ring size (number of T atoms) to search for.

24
n_cpus int

Number of worker processes for parallel ring search. Only very large networks (>100 000 T-O bonds, roughly a 10⁵-atom cell) benefit; below that the search runs sequentially whatever is asked for, because starting worker processes costs more than it saves. 1 — sequential execution (default). N — distribute the bond loop across N worker processes. -1 — use all logical CPUs.

1

Returns:

Name Type Description
histogram dict[int, float]

Mapping from ring size to ring count.

mean_ring_size float

Mean ring size weighted by count.

Raises:

Type Description
ValueError

If bond_lengths contains no T-O pairs (i.e. all pairs involve only oxygen or only formers).

Examples:

>>> from ase.io import read
>>> structure = read('glass.xyz')
>>> histogram, mean_size = compute_guttmann_rings(
...     structure,
...     bond_lengths={('Si', 'O'): 1.8},
...     max_size=12,
... )
>>> # Parallel on 4 cores
>>> histogram, mean_size = compute_guttmann_rings(
...     structure,
...     bond_lengths={('Si', 'O'): 1.8},
...     n_cpus=4,
... )
Source code in amorphouspy/src/amorphouspy/properties/structural/rings.py
def compute_guttmann_rings(
    structure: Atoms | list[Atoms],
    bond_lengths: dict[tuple[str, str], float],
    max_size: int = 24,
    n_cpus: int = 1,
) -> tuple[dict[int, float], float]:
    """Compute the Guttman ring size distribution and mean ring size.

    The ring associated with each T-O bond is the shortest cycle containing it.
    The search runs on the bipartite T-O atom network, so oxygen triclusters
    cannot masquerade as small rings and edge-sharing polyhedra are detected.
    Under periodic boundary conditions only cycles that close in real space are
    counted; see the module docstring for the full criterion.

    Ring size is the number of network-former atoms (T atoms) in the ring,
    following Guttman's original convention. The smallest reportable ring is 2,
    two formers bridged by two distinct oxygens.

    Args:
        structure: ASE Atoms object containing atomic coordinates and types.
            Pass a list to use the first frame.
        bond_lengths: Maximum bond lengths for each element pair, e.g.
            ``{('Si', 'O'): 1.8, ('Al', 'O'): 1.95}``. All T-O pairs must
            be specified; T-T and O-O pairs are ignored.
        max_size: Maximum ring size (number of T atoms) to search for.
        n_cpus: Number of worker processes for parallel ring search. Only
            very large networks (>100 000 T-O bonds, roughly a 10⁵-atom cell)
            benefit; below that the search runs sequentially whatever is asked
            for, because starting worker processes costs more than it saves.
            ``1``  — sequential execution (default).
            ``N``  — distribute the bond loop across N worker processes.
            ``-1`` — use all logical CPUs.

    Returns:
        histogram: Mapping from ring size to ring count.
        mean_ring_size: Mean ring size weighted by count.

    Raises:
        ValueError: If ``bond_lengths`` contains no T-O pairs (i.e. all
            pairs involve only oxygen or only formers).

    Examples:
        >>> from ase.io import read
        >>> structure = read('glass.xyz')
        >>> histogram, mean_size = compute_guttmann_rings(
        ...     structure,
        ...     bond_lengths={('Si', 'O'): 1.8},
        ...     max_size=12,
        ... )
        >>> # Parallel on 4 cores
        >>> histogram, mean_size = compute_guttmann_rings(
        ...     structure,
        ...     bond_lengths={('Si', 'O'): 1.8},
        ...     n_cpus=4,
        ... )
    """
    if isinstance(structure, list):
        structure = cast("Atoms", structure[0])
    z_cutoffs, former_atomic_numbers = _symbols_to_z_cutoffs(bond_lengths)

    if not former_atomic_numbers:
        error_message = (
            "bond_lengths contains no network-former species. Provide at least one T-O pair such as ('Si', 'O')."
        )
        raise ValueError(error_message)

    wrapped_structure = structure.copy()
    wrapped_structure.wrap()

    adjacency, bond_vectors = _build_bipartite_network(
        wrapped_structure,
        z_cutoffs,
        former_atomic_numbers,
        _OXYGEN_ATOMIC_NUMBER,
    )

    ring_counts, exhausted_bonds, truncated_bonds = _find_guttman_rings(
        adjacency, bond_vectors, max_size, n_cpus=n_cpus
    )

    if exhausted_bonds:
        warnings.warn(
            f"Ring search abandoned {exhausted_bonds} bond(s) after exhausting the deepening budget of "
            f"{_DEEPENING_STATE_BUDGET} states; their rings are missing from the histogram. This happens when a "
            f"bond's neighbourhood wraps the periodic cell without closing — a larger cell or a smaller max_size "
            f"avoids it.",
            RuntimeWarning,
            stacklevel=2,
        )

    if truncated_bonds:
        warnings.warn(
            f"Ring search capped the closure enumeration at {_MAX_CLOSURES_PER_BOND} for {truncated_bonds} bond(s); "
            f"some rings through them are missing from the histogram. This means the network is far more degenerate "
            f"than a glass or an ordinary crystal — check the bond cutoffs.",
            RuntimeWarning,
            stacklevel=2,
        )

    if not ring_counts:
        return {}, 0.0

    total_rings = sum(ring_counts.values())
    mean_ring_size = sum(size * count for size, count in ring_counts.items()) / total_rings
    ring_counts_float: dict[int, float] = {k: float(v) for k, v in ring_counts.items()}
    return ring_counts_float, float(mean_ring_size)

compute_harmonic_vdos(frequencies_thz: ArrayLike, eigenvectors: NDArray[np.float64] | None = None, *, groups: dict[str, dict[str, NDArray]] | None = None, frequency_grid_thz: ArrayLike | None = None, broadening_thz: float = 0.2, normalization: HarmonicNormalization = 'unit') -> dict[str, Any]

Compute the harmonic VDOS and its group partials from the modes of :func:diagonalize_dynamical_matrix.

The input is the \(M = 3N - 3\) kept modes: frequencies \(\nu_k\) in THz (negative for imaginary modes) and the mass-weighted eigenvectors \(e_k\), orthonormal columns with row \(3i + \alpha\) for atom \(i\) and direction \(\alpha\). The weight of atom \(i\) in mode \(k\) and of a group \(G\) are

\[a_{ik} = \sum_\alpha e_{3i+\alpha,k}^2, \quad \sum_i a_{ik} = 1, \qquad w_{kG} = \sum_{i \in G} a_{ik},\]

and the VDOS and its partials are sums of unit-area Gaussians of standard deviation \(\sigma\) (broadening_thz),

\[g(\nu) = c \sum_{k:\, \nu_k \ge 0} G_\sigma(\nu - \nu_k), \quad g_G(\nu) = c \sum_{k:\, \nu_k \ge 0} w_{kG}\, G_\sigma(\nu - \nu_k), \quad G_\sigma(x) = \frac{e^{-x^2 / 2\sigma^2}}{\sigma \sqrt{2\pi}}.\]

Partials within a grouping that covers every atom once (e.g. "element") sum to the total, and the classes of a grouping that covers a subset sum to that subset's partial (e.g. the "oxygen" classes to "O").

Normalisation:

  • "unit" (default): \(c = 1/M\), so the total integrates to 1 over all modes.
  • "3N": \(c = 3N/M\), so the total integrates to \(3N\), as with the VACF route, although the three translations were dropped: each kept mode carries \(3N/M\) instead of 1.

What is not counted:

  • Imaginary modes (\(\nu_k < 0\), any negative value, unlike the imaginary_threshold_thz of :func:diagonalize_dynamical_matrix) are excluded from all sums and counted in "n_imaginary_excluded". They stay in \(M\), so the integral falls short of 1 (or \(3N\)) by their share, "imaginary_weight" \(= n/M\).
  • Gaussian weight below or above the grid is not renormalised either: the default grid starts at 0, so modes within a few \(\sigma\) of 0 lose part of their weight. "grid_integral" is the trapezoid integral of the total on the grid. A grid spacing up to \(\sigma/2\) integrates a Gaussian to better than \(10^{-10}\).

Completeness: summed over all \(3N\) modes, \(\sum_k w_{kG} = 3 N_G\). The translations are the mass-weighted rigid shifts \(\sqrt{m_i / m_\mathrm{tot}}\), so over the kept modes it is \(3 N_G - 3 m_G / m_\mathrm{tot}\), with \(N_G\) the atom count and \(m_G\) the mass of the group.

Relation to the VACF route: in mode \(k\), atom \(i\) carries the share \(a_{ik}\) of the mode's kinetic energy, since its mass-weighted velocity is proportional to \(e_{3i+\alpha,k}\). A partial of :func:compute_partial_vdos is the group's share of the mass-weighted velocity power, so with every mode at the same mean kinetic energy (classical equipartition in a harmonic solid) the two routes use the same partial definition, and the same normalisations.

The eigenvectors are not checked for orthonormality, which would cost a full \((M, M)\) matrix product; columns that are not orthonormal break \(\sum_i a_{ik} = 1\) and the sums above.

Memory: the eigenvectors are read in blocks of columns of _CHUNK_BYTES (64 MB), each reduced at once to the groups, and the Gaussians are evaluated in blocks of modes of the same size. Neither a squared copy of the eigenvectors nor an \((N, M)\) weight array is built.

Parameters:

Name Type Description Default
frequencies_thz ArrayLike

The \(M = 3N - 3\) mode frequencies in THz, negative for imaginary modes, e.g. "frequencies_thz" of :func:diagonalize_dynamical_matrix.

required
eigenvectors NDArray[float64] | None

The \((3N, M)\) float64 eigenvectors with orthonormal columns in the order of frequencies_thz, e.g. "eigenvectors" of :func:diagonalize_dynamical_matrix (any memory order; no cast or copy is made). Only needed for groups, and for "3N" it gives \(N\).

None
groups dict[str, dict[str, NDArray]] | None

{grouping: {label: indices}} with 0-based atom positions in the order of the matrix rows, e.g. the output of :func:classify_vibrational_groups on the minimised structure. Needs eigenvectors.

None
frequency_grid_thz ArrayLike | None

The frequencies in THz at which the VDOS is evaluated: 1-D, finite, strictly increasing, at least 2 points. None (default): from 0 in steps of exactly \(\sigma/5\) up to the first point at or above \(\max(\nu_k, 0) + 5\sigma\).

None
broadening_thz float

The standard deviation \(\sigma\) of the Gaussians in THz (not the FWHM, which is \(2.355\sigma\)).

0.2
normalization HarmonicNormalization

"unit" or "3N", see above.

'unit'

Returns:

Type Description
dict[str, Any]

A dictionary with: "frequencies_thz": the grid in THz. "vdos": {"total": g} and, with groups, {grouping: {label: g_G}} (the layout of :func:vdos_simulation), each a float64 array on the grid in 1/THz. "mode_weights": {grouping: {label: w}} with the \((M,)\) weights \(w_{kG}\) of every mode, imaginary ones included; only with groups. "n_modes": \(M\). "n_imaginary_excluded": the number of modes with \(\nu_k < 0\). "imaginary_weight": their share of the normalisation, n_imaginary_excluded / n_modes. "grid_integral": the trapezoid integral of the total on the grid. "broadening_thz": \(\sigma\) in THz. "normalization": "unit" or "3N".

Raises:

Type Description
ValueError

If frequencies_thz is empty, not 1-D or not finite; eigenvectors is not 2-D float64 or not \((M + 3, M)\) with \(M\) a multiple of 3; broadening_thz is not positive and finite; normalization is unknown, or "3N" without eigenvectors and \(M\) not a multiple of 3; groups is given without eigenvectors, has no labels or has invalid indices; frequency_grid_thz is not 1-D, finite and strictly increasing with at least 2 points.

Warns:

Type Description
UserWarning

If the largest spacing of frequency_grid_thz exceeds \(\sigma/2\).

Example
>>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin")  # doctest: +SKIP
>>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"])  # doctest: +SKIP
>>> modes = diagonalize_dynamical_matrix(  # doctest: +SKIP
...     matrix, masses=minimised.get_masses(), overwrite_matrix=True
... )
>>> groups = classify_vibrational_groups(minimised)  # doctest: +SKIP
>>> vdos = compute_harmonic_vdos(  # doctest: +SKIP
...     modes["frequencies_thz"], modes["eigenvectors"], groups=groups, broadening_thz=0.1
... )
>>> vdos["vdos"]["oxygen"]["O_NBO"], vdos["grid_integral"], vdos["n_imaginary_excluded"]  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/harmonic.py
def compute_harmonic_vdos(
    frequencies_thz: ArrayLike,
    eigenvectors: NDArray[np.float64] | None = None,
    *,
    groups: dict[str, dict[str, NDArray]] | None = None,
    frequency_grid_thz: ArrayLike | None = None,
    broadening_thz: float = 0.2,
    normalization: HarmonicNormalization = "unit",
) -> dict[str, Any]:
    r"""Compute the harmonic VDOS and its group partials from the modes of :func:`diagonalize_dynamical_matrix`.

    The input is the $M = 3N - 3$ kept modes: frequencies $\nu_k$ in THz (negative for imaginary modes) and the
    mass-weighted eigenvectors $e_k$, orthonormal columns with row $3i + \alpha$ for atom $i$ and direction $\alpha$.
    The weight of atom $i$ in mode $k$ and of a group $G$ are

    $$a_{ik} = \sum_\alpha e_{3i+\alpha,k}^2, \quad \sum_i a_{ik} = 1, \qquad w_{kG} = \sum_{i \in G} a_{ik},$$

    and the VDOS and its partials are sums of unit-area Gaussians of standard deviation $\sigma$ (``broadening_thz``),

    $$g(\nu) = c \sum_{k:\, \nu_k \ge 0} G_\sigma(\nu - \nu_k), \quad
    g_G(\nu) = c \sum_{k:\, \nu_k \ge 0} w_{kG}\, G_\sigma(\nu - \nu_k), \quad
    G_\sigma(x) = \frac{e^{-x^2 / 2\sigma^2}}{\sigma \sqrt{2\pi}}.$$

    Partials within a grouping that covers every atom once (e.g. ``"element"``) sum to the total, and the classes of
    a grouping that covers a subset sum to that subset's partial (e.g. the ``"oxygen"`` classes to ``"O"``).

    Normalisation:

    - ``"unit"`` (default): $c = 1/M$, so the total integrates to 1 over all modes.
    - ``"3N"``: $c = 3N/M$, so the total integrates to $3N$, as with the VACF route, although the three translations
      were dropped: each kept mode carries $3N/M$ instead of 1.

    What is not counted:

    - Imaginary modes ($\nu_k < 0$, any negative value, unlike the ``imaginary_threshold_thz`` of
      :func:`diagonalize_dynamical_matrix`) are excluded from all sums and counted in ``"n_imaginary_excluded"``. They
      stay in $M$, so the integral falls short of 1 (or $3N$) by their share, ``"imaginary_weight"`` $= n/M$.
    - Gaussian weight below or above the grid is not renormalised either: the default grid starts at 0, so modes within
      a few $\sigma$ of 0 lose part of their weight. ``"grid_integral"`` is the trapezoid integral of the total on the
      grid. A grid spacing up to $\sigma/2$ integrates a Gaussian to better than $10^{-10}$.

    Completeness: summed over all $3N$ modes, $\sum_k w_{kG} = 3 N_G$. The translations are the mass-weighted rigid
    shifts $\sqrt{m_i / m_\mathrm{tot}}$, so over the kept modes it is $3 N_G - 3 m_G / m_\mathrm{tot}$, with $N_G$
    the atom count and $m_G$ the mass of the group.

    Relation to the VACF route: in mode $k$, atom $i$ carries the share $a_{ik}$ of the mode's kinetic energy, since
    its mass-weighted velocity is proportional to $e_{3i+\alpha,k}$. A partial of
    :func:`compute_partial_vdos` is the group's share of the mass-weighted velocity power, so with every mode at the
    same mean kinetic energy (classical equipartition in a harmonic solid) the two routes use the same partial
    definition, and the same normalisations.

    The eigenvectors are not checked for orthonormality, which would cost a full $(M, M)$ matrix product; columns that
    are not orthonormal break $\sum_i a_{ik} = 1$ and the sums above.

    Memory: the eigenvectors are read in blocks of columns of ``_CHUNK_BYTES`` (64 MB), each reduced at once to the
    groups, and the Gaussians are evaluated in blocks of modes of the same size. Neither a squared copy of the
    eigenvectors nor an $(N, M)$ weight array is built.

    Args:
        frequencies_thz: The $M = 3N - 3$ mode frequencies in THz, negative for imaginary modes, e.g.
            ``"frequencies_thz"`` of :func:`diagonalize_dynamical_matrix`.
        eigenvectors: The $(3N, M)$ float64 eigenvectors with orthonormal columns in the order of
            ``frequencies_thz``, e.g. ``"eigenvectors"`` of :func:`diagonalize_dynamical_matrix` (any memory order;
            no cast or copy is made). Only needed for ``groups``, and for ``"3N"`` it gives $N$.
        groups: ``{grouping: {label: indices}}`` with 0-based atom positions in the order of the matrix rows, e.g. the
            output of :func:`classify_vibrational_groups` on the minimised structure. Needs ``eigenvectors``.
        frequency_grid_thz: The frequencies in THz at which the VDOS is evaluated: 1-D, finite, strictly increasing,
            at least 2 points. ``None`` (default): from 0 in steps of exactly $\sigma/5$ up to the first point at or
            above $\max(\nu_k, 0) + 5\sigma$.
        broadening_thz: The standard deviation $\sigma$ of the Gaussians in THz (not the FWHM, which is
            $2.355\sigma$).
        normalization: ``"unit"`` or ``"3N"``, see above.

    Returns:
        A dictionary with:
            ``"frequencies_thz"``: the grid in THz.
            ``"vdos"``: ``{"total": g}`` and, with ``groups``, ``{grouping: {label: g_G}}`` (the layout of
            :func:`vdos_simulation`), each a float64 array on the grid in 1/THz.
            ``"mode_weights"``: ``{grouping: {label: w}}`` with the $(M,)$ weights $w_{kG}$ of every mode,
            imaginary ones included; only with ``groups``.
            ``"n_modes"``: $M$.
            ``"n_imaginary_excluded"``: the number of modes with $\nu_k < 0$.
            ``"imaginary_weight"``: their share of the normalisation, ``n_imaginary_excluded / n_modes``.
            ``"grid_integral"``: the trapezoid integral of the total on the grid.
            ``"broadening_thz"``: $\sigma$ in THz.
            ``"normalization"``: ``"unit"`` or ``"3N"``.

    Raises:
        ValueError: If ``frequencies_thz`` is empty, not 1-D or not finite; ``eigenvectors`` is not 2-D float64 or
            not $(M + 3, M)$ with $M$ a multiple of 3; ``broadening_thz`` is not positive and finite;
            ``normalization`` is unknown, or ``"3N"`` without eigenvectors and $M$ not a multiple of 3;
            ``groups`` is given without ``eigenvectors``, has no labels or has invalid indices;
            ``frequency_grid_thz`` is not 1-D, finite and strictly increasing with at least 2 points.

    Warns:
        UserWarning: If the largest spacing of ``frequency_grid_thz`` exceeds $\sigma/2$.

    Example:
        ```pycon
        >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin")  # doctest: +SKIP
        >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"])  # doctest: +SKIP
        >>> modes = diagonalize_dynamical_matrix(  # doctest: +SKIP
        ...     matrix, masses=minimised.get_masses(), overwrite_matrix=True
        ... )
        >>> groups = classify_vibrational_groups(minimised)  # doctest: +SKIP
        >>> vdos = compute_harmonic_vdos(  # doctest: +SKIP
        ...     modes["frequencies_thz"], modes["eigenvectors"], groups=groups, broadening_thz=0.1
        ... )
        >>> vdos["vdos"]["oxygen"]["O_NBO"], vdos["grid_integral"], vdos["n_imaginary_excluded"]  # doctest: +SKIP

        ```
    """
    frequencies, eigenvectors, n_atoms = _validate_harmonic_inputs(
        frequencies_thz, eigenvectors, groups, broadening_thz, normalization
    )
    grid = _harmonic_grid(frequency_grid_thz, frequencies, broadening_thz)
    n_modes = frequencies.size
    kept = frequencies >= 0

    # Column 0 weighs every mode by 1 (the total); with groups, one column per group label follows.
    weights = np.ones((n_modes, 1))
    keys: list[tuple[str, str]] = []
    if groups is not None and eigenvectors is not None:
        keys, selections = _group_selections(groups)
        membership = _membership(selections, n_atoms)
        weights = np.ones((n_modes, 1 + membership.shape[1]))
        for columns, atom_weights in _mode_atom_weights(eigenvectors, n_atoms):
            weights[columns, 1:] = atom_weights.T @ membership

    centres, kept_weights = frequencies[kept], weights[kept]
    spectra = np.zeros((grid.size, weights.shape[1]))
    step = max(1, _common._CHUNK_BYTES // (grid.size * grid.itemsize))  # noqa: SLF001
    buffer = np.empty((grid.size, min(step, centres.size)))  # one block, reused for every chunk of modes
    for start in range(0, centres.size, step):
        gaussians = buffer[:, : min(step, centres.size - start)]
        np.subtract(grid[:, None], centres[None, start : start + step], out=gaussians)
        gaussians /= broadening_thz
        np.square(gaussians, out=gaussians)
        gaussians *= -0.5
        np.exp(gaussians, out=gaussians)
        spectra += gaussians @ kept_weights[start : start + step]
    spectra *= (1.0 if normalization == "unit" else 3.0 * n_atoms) / (n_modes * broadening_thz * math.sqrt(2 * math.pi))

    total = np.ascontiguousarray(spectra[:, 0])
    result: dict[str, Any] = {"frequencies_thz": grid, "vdos": {"total": total}}
    if groups is not None:
        result["vdos"] = {"total": total, **_columns_by_group(groups, keys, spectra[:, 1:])}
        result["mode_weights"] = _columns_by_group(groups, keys, weights[:, 1:])
    n_imaginary = n_modes - int(np.count_nonzero(kept))
    result.update(
        {
            "n_modes": n_modes,
            "n_imaginary_excluded": n_imaginary,
            "imaginary_weight": n_imaginary / n_modes,
            "grid_integral": float(np.trapezoid(total, grid)),
            "broadening_thz": float(broadening_thz),
            "normalization": normalization,
        }
    )
    return result

compute_ir_oscillator_strengths(eigenvectors: NDArray[np.float64], masses: ArrayLike, charges: ArrayLike, *, groups: dict[str, dict[str, NDArray]] | None = None) -> dict[str, Any]

Compute the infrared oscillator strength of every mode from its eigenvector and the atomic charges.

A mode \(m\) with mass-weighted eigenvector \(e_{3i+\beta,m}\) displaces atom \(i\) by \(e_{3i+\beta,m} / \sqrt{m_i}\) per unit normal coordinate. With the charge tensor \(Z_{i,\alpha\beta}\) of atom \(i\) (the dipole along \(\alpha\) created by a unit displacement along \(\beta\)), the dipole per unit normal coordinate, called the mode effective charge, is

\[\tilde Z_{m,\alpha} = \sum_i \sum_\beta \frac{Z_{i,\alpha\beta}\, e_{3i+\beta,m}}{\sqrt{m_i}},\]

and the isotropic oscillator strength, the orientational average of \(\tilde Z_{m,\alpha} \tilde Z_{m,\beta}\), is

\[f_m = \tfrac{1}{3} \sum_\alpha \tilde Z_{m,\alpha}^2 .\]

Scalar charges \(q_i\) stand for \(Z_{i,\alpha\beta} = q_i \delta_{\alpha\beta}\): the rigid-ion model, in which the fixed charges of the potential move with the atoms and nothing polarises. Its peak positions are those of the potential, but its intensities are qualitative; Born effective charge tensors from an electronic-structure calculation can be passed instead.

For a full orthonormal set of \(3N\) modes the strengths obey the sum rule \(\sum_m \tilde Z_{m,\alpha} \tilde Z_{m,\beta} = \sum_i (Z_i Z_i^T)_{\alpha\beta} / m_i\); the three rigid translations hold \((\sum_i Z_i)(\sum_i Z_i)^T / \sum_i m_i\) of it, which is zero for a neutral cell.

With groups the sum over atoms is restricted to each group \(G\), giving \(\tilde Z^G_m\), and every pair of labels of one grouping gets the strength

\[f^{GG'}_m = \frac{2 - \delta_{GG'}}{3} \sum_\alpha \tilde Z^G_{m,\alpha} \tilde Z^{G'}_{m,\alpha},\]

whose cross terms (\(G \neq G'\)) can be negative. Over the unordered pairs of a grouping that holds every atom once, such as "element" of :func:classify_vibrational_groups, they sum to \(f_m\).

Parameters:

Name Type Description Default
eigenvectors NDArray[float64]

The \((3N, K)\) float64 eigenvectors of the mass-weighted dynamical matrix, one orthonormal mode per column with row \(3i + \alpha\) for atom \(i\) and direction \(\alpha\), e.g. "eigenvectors" of :func:diagonalize_dynamical_matrix (any memory order; no cast or copy is made).

required
masses ArrayLike

Atomic masses in amu, shape \((N,)\), in the order of the rows, e.g. minimised.get_masses().

required
charges ArrayLike

Atomic charges in units of the elementary charge, in the order of the rows: shape \((N,)\) for scalar charges or \((N, 3, 3)\) for charge tensors \(Z_{i,\alpha\beta}\).

required
groups dict[str, dict[str, NDArray]] | None

Atom groups as {grouping: {label: indices}} with 0-based positions, e.g. from :func:classify_vibrational_groups.

None

Returns:

Type Description
dict[str, Any]

A dictionary with: "mode_charges": The \((K, 3)\) mode effective charges \(\tilde Z_{m,\alpha}\) in \(e/\sqrt{\mathrm{amu}}\). "strengths": The \((K,)\) isotropic oscillator strengths \(f_m\) in \(e^2/\mathrm{amu}\). "partial_mode_charges": {grouping: {label: (K, 3) array}}, only with groups. "partial_strengths": {grouping: {"A-B": (K,) array}} for every unordered pair of labels, in the order of the labels, only with groups.

Raises:

Type Description
ValueError

If eigenvectors is not a 2-D float64 array, its row count is not a positive multiple of 3, it has no columns or it contains NaN or inf; if masses does not hold \(N\) positive finite values; if charges is not finite with shape \((N,)\) or \((N, 3, 3)\); if groups has no labels or a label has invalid positions.

Warns:

Type Description
UserWarning

If the charges do not sum to zero over the atoms.

Example
>>> modes = diagonalize_dynamical_matrix(matrix, masses=minimised.get_masses())  # doctest: +SKIP
>>> infrared = compute_ir_oscillator_strengths(  # doctest: +SKIP
...     modes["eigenvectors"], minimised.get_masses(), charges
... )
>>> infrared["strengths"]  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/infrared.py
def compute_ir_oscillator_strengths(
    eigenvectors: NDArray[np.float64],
    masses: ArrayLike,
    charges: ArrayLike,
    *,
    groups: dict[str, dict[str, NDArray]] | None = None,
) -> dict[str, Any]:
    r"""Compute the infrared oscillator strength of every mode from its eigenvector and the atomic charges.

    A mode $m$ with mass-weighted eigenvector $e_{3i+\beta,m}$ displaces atom $i$ by $e_{3i+\beta,m} / \sqrt{m_i}$ per
    unit normal coordinate. With the charge tensor $Z_{i,\alpha\beta}$ of atom $i$ (the dipole along $\alpha$ created
    by a unit displacement along $\beta$), the dipole per unit normal coordinate, called the mode effective charge, is

    $$\tilde Z_{m,\alpha} = \sum_i \sum_\beta \frac{Z_{i,\alpha\beta}\, e_{3i+\beta,m}}{\sqrt{m_i}},$$

    and the isotropic oscillator strength, the orientational average of $\tilde Z_{m,\alpha} \tilde Z_{m,\beta}$, is

    $$f_m = \tfrac{1}{3} \sum_\alpha \tilde Z_{m,\alpha}^2 .$$

    Scalar charges $q_i$ stand for $Z_{i,\alpha\beta} = q_i \delta_{\alpha\beta}$: the rigid-ion model, in which the
    fixed charges of the potential move with the atoms and nothing polarises. Its peak positions are those of the
    potential, but its intensities are qualitative; Born effective charge tensors from an electronic-structure
    calculation can be passed instead.

    For a full orthonormal set of $3N$ modes the strengths obey the sum rule
    $\sum_m \tilde Z_{m,\alpha} \tilde Z_{m,\beta} = \sum_i (Z_i Z_i^T)_{\alpha\beta} / m_i$; the three rigid
    translations hold $(\sum_i Z_i)(\sum_i Z_i)^T / \sum_i m_i$ of it, which is zero for a neutral cell.

    With ``groups`` the sum over atoms is restricted to each group $G$, giving $\tilde Z^G_m$, and every pair of labels
    of one grouping gets the strength

    $$f^{GG'}_m = \frac{2 - \delta_{GG'}}{3} \sum_\alpha \tilde Z^G_{m,\alpha} \tilde Z^{G'}_{m,\alpha},$$

    whose cross terms ($G \neq G'$) can be negative. Over the unordered pairs of a grouping that holds every atom once,
    such as ``"element"`` of :func:`classify_vibrational_groups`, they sum to $f_m$.

    Args:
        eigenvectors: The $(3N, K)$ float64 eigenvectors of the mass-weighted dynamical matrix, one orthonormal mode
            per column with row $3i + \alpha$ for atom $i$ and direction $\alpha$, e.g. ``"eigenvectors"`` of
            :func:`diagonalize_dynamical_matrix` (any memory order; no cast or copy is made).
        masses: Atomic masses in amu, shape $(N,)$, in the order of the rows, e.g. ``minimised.get_masses()``.
        charges: Atomic charges in units of the elementary charge, in the order of the rows: shape $(N,)$ for scalar
            charges or $(N, 3, 3)$ for charge tensors $Z_{i,\alpha\beta}$.
        groups: Atom groups as ``{grouping: {label: indices}}`` with 0-based positions, e.g. from
            :func:`classify_vibrational_groups`.

    Returns:
        A dictionary with:
            ``"mode_charges"``: The $(K, 3)$ mode effective charges $\tilde Z_{m,\alpha}$ in $e/\sqrt{\mathrm{amu}}$.
            ``"strengths"``: The $(K,)$ isotropic oscillator strengths $f_m$ in $e^2/\mathrm{amu}$.
            ``"partial_mode_charges"``: ``{grouping: {label: (K, 3) array}}``, only with ``groups``.
            ``"partial_strengths"``: ``{grouping: {"A-B": (K,) array}}`` for every unordered pair of labels, in the
                order of the labels, only with ``groups``.

    Raises:
        ValueError: If ``eigenvectors`` is not a 2-D float64 array, its row count is not a positive multiple of 3, it
            has no columns or it contains NaN or inf; if ``masses`` does not hold $N$ positive finite values; if
            ``charges`` is not finite with shape $(N,)$ or $(N, 3, 3)$; if ``groups`` has no labels or a label has
            invalid positions.

    Warns:
        UserWarning: If the charges do not sum to zero over the atoms.

    Example:
        ```pycon
        >>> modes = diagonalize_dynamical_matrix(matrix, masses=minimised.get_masses())  # doctest: +SKIP
        >>> infrared = compute_ir_oscillator_strengths(  # doctest: +SKIP
        ...     modes["eigenvectors"], minimised.get_masses(), charges
        ... )
        >>> infrared["strengths"]  # doctest: +SKIP

        ```
    """
    eigenvectors, masses, n_atoms = _validate_modes(eigenvectors, masses)
    n_rows, n_modes = eigenvectors.shape
    charges = _validate_charges(charges, n_atoms)

    # Column 0 sums over every atom (the total); with groups, one column per group label follows.
    membership = np.ones((n_atoms, 1))
    keys: list[tuple[str, str]] = []
    if groups is not None:
        keys, selections = _group_selections(groups)
        membership = np.hstack([membership, _membership(selections, n_atoms)])
    scalar = charges.ndim == _SCALAR_CHARGE_NDIM
    # Charge per unit mass-weighted displacement: Z_i / sqrt(m_i).
    weights = charges / np.sqrt(masses).reshape(-1, *([1] * (charges.ndim - 1)))
    if scalar:
        membership = membership * weights[:, None]

    mode_charges = np.empty((membership.shape[1], _N_COMPONENTS, n_modes))
    step = max(1, _common._CHUNK_BYTES // (n_rows * eigenvectors.itemsize))  # noqa: SLF001
    for start in range(0, n_modes, step):
        columns = slice(start, min(start + step, n_modes))
        block = eigenvectors[:, columns].reshape(n_atoms, _N_COMPONENTS, -1)
        if not scalar:
            block = np.einsum("iab,ibk->iak", weights, block)
        mode_charges[:, :, columns] = np.einsum("ig,iak->gak", membership, block)
    if not np.all(np.isfinite(mode_charges)):
        msg = "eigenvectors contain NaN or inf."
        raise ValueError(msg)
    mode_charges = np.ascontiguousarray(mode_charges.transpose(0, 2, 1))  # (columns, modes, 3)

    result: dict[str, Any] = {
        "mode_charges": mode_charges[0],
        "strengths": np.einsum("ka,ka->k", mode_charges[0], mode_charges[0]) / _N_COMPONENTS,
    }
    if groups is not None:
        column_of = {key: column for column, key in enumerate(keys, start=1)}
        partial_charges: dict[str, dict[str, NDArray[np.float64]]] = {}
        partial_strengths: dict[str, dict[str, NDArray[np.float64]]] = {}
        for grouping, labels in groups.items():
            names = list(labels)
            partial_charges[grouping] = {name: mode_charges[column_of[grouping, name]] for name in names}
            partial_strengths[grouping] = {
                f"{first}-{second}": np.einsum(
                    "ka,ka->k", partial_charges[grouping][first], partial_charges[grouping][second]
                )
                * ((1 if first == second else 2) / _N_COMPONENTS)
                for position, first in enumerate(names)
                for second in names[position:]
            }
        result["partial_mode_charges"] = partial_charges
        result["partial_strengths"] = partial_strengths
    return result

compute_msd(frames: list[Atoms], *, timestep: float = 1.0, output_frequency: int = 1, max_lag: int | None = None, remove_com_drift: bool = True, per_species: bool = True, method: str = 'fft') -> dict[str, Any]

Compute the mean-squared displacement from a trajectory.

With method="fft" (default) the multi-time-origin Fast Correlation Algorithm is used, which requires uniformly-spaced frames and gives the best statistics. With method="single_origin" the MSD is <|r(t) - r(0)|^2> referenced to the first frame; this is noisier but works on a non-uniformly sampled trajectory (e.g. a log-then-linear dump), using each frame's actual time from atoms.info["step"] when present. If every frame carries an "unwrapped_positions" array (LAMMPS image-flag unwrapping) it is used directly; otherwise the trajectory is unwrapped on the fly from wrapped positions and per-frame cells.

Parameters:

Name Type Description Default
frames list[Atoms]

Trajectory as a list of :class:ase.Atoms, atoms in a consistent order across frames (LAMMPS dumps must use dump_modify ... sort id).

required
timestep float

MD integration timestep in femtoseconds.

1.0
output_frequency int

MD steps between successive frames (used for the time axis when frames carry no info["step"]).

1
max_lag int | None

Largest lag (in frames) to report. Defaults to len(frames) - 1.

None
remove_com_drift bool

Subtract the per-frame mass-weighted centre-of-mass displacement.

True
per_species bool

Also report MSD resolved per chemical element.

True
method str

"fft" (multi-origin, uniform sampling) or "single_origin" (non-uniform-safe).

'fft'

Returns:

Type Description
dict[str, Any]

Dict with "lag_time_ps" and "msd_total" (Angstrom^2) plus "temperature" (K). When

dict[str, Any]

per_species is set, also "msd_per_species" and "n_atoms_per_species".

Example
>>> from amorphouspy import diffusion_simulation  # doctest: +SKIP
>>> out = diffusion_simulation(structure, potential, thermostat="nose_hoover")  # doctest: +SKIP
>>> msd = compute_msd(out["frames"], timestep=1.0, output_frequency=100)  # doctest: +SKIP
>>> msd["msd_total"][0]  # doctest: +SKIP
0.0
Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
def compute_msd(
    frames: list[Atoms],
    *,
    timestep: float = 1.0,
    output_frequency: int = 1,
    max_lag: int | None = None,
    remove_com_drift: bool = True,
    per_species: bool = True,
    method: str = "fft",
) -> dict[str, Any]:
    """Compute the mean-squared displacement from a trajectory.

    With ``method="fft"`` (default) the multi-time-origin Fast Correlation Algorithm is used, which
    requires uniformly-spaced frames and gives the best statistics. With ``method="single_origin"``
    the MSD is ``<|r(t) - r(0)|^2>`` referenced to the first frame; this is noisier but works on a
    **non-uniformly** sampled trajectory (e.g. a log-then-linear dump), using each frame's actual time
    from ``atoms.info["step"]`` when present. If every frame carries an ``"unwrapped_positions"`` array
    (LAMMPS image-flag unwrapping) it is used directly; otherwise the trajectory is unwrapped on the
    fly from wrapped positions and per-frame cells.

    Args:
        frames: Trajectory as a list of :class:`ase.Atoms`, atoms in a consistent order across frames
            (LAMMPS dumps must use ``dump_modify ... sort id``).
        timestep: MD integration timestep in femtoseconds.
        output_frequency: MD steps between successive frames (used for the time axis when frames carry
            no ``info["step"]``).
        max_lag: Largest lag (in frames) to report. Defaults to ``len(frames) - 1``.
        remove_com_drift: Subtract the per-frame mass-weighted centre-of-mass displacement.
        per_species: Also report MSD resolved per chemical element.
        method: ``"fft"`` (multi-origin, uniform sampling) or ``"single_origin"`` (non-uniform-safe).

    Returns:
        Dict with ``"lag_time_ps"`` and ``"msd_total"`` (Angstrom^2) plus ``"temperature"`` (K). When
        *per_species* is set, also ``"msd_per_species"`` and ``"n_atoms_per_species"``.

    Example:
        ```pycon
        >>> from amorphouspy import diffusion_simulation  # doctest: +SKIP
        >>> out = diffusion_simulation(structure, potential, thermostat="nose_hoover")  # doctest: +SKIP
        >>> msd = compute_msd(out["frames"], timestep=1.0, output_frequency=100)  # doctest: +SKIP
        >>> msd["msd_total"][0]  # doctest: +SKIP
        0.0

        ```
    """
    positions, numbers, temperature = _build_trajectory(frames, remove_com_drift=remove_com_drift)
    n_frames = positions.shape[0]
    lag_limit = n_frames - 1 if max_lag is None else int(min(max_lag, n_frames - 1))

    if method == "single_origin":
        times_ps = _frame_times_ps(frames, timestep=timestep, output_frequency=output_frequency)
        lag_time_ps = (times_ps - times_ps[0])[: lag_limit + 1]

        def per_group(group: NDArray[np.float64]) -> NDArray[np.float64]:
            return _msd_single_origin(group)[: lag_limit + 1]
    elif method == "fft":
        lag_time_ps = np.arange(lag_limit + 1) * (timestep * output_frequency / 1000.0)

        def per_group(group: NDArray[np.float64]) -> NDArray[np.float64]:
            return _msd_fft_multi(group)[: lag_limit + 1]
    else:
        msg = f"Unknown method {method!r}; use 'fft' or 'single_origin'."
        raise ValueError(msg)

    result: dict[str, Any] = {
        "lag_time_ps": lag_time_ps.tolist(),
        "msd_total": per_group(positions).tolist(),
        "temperature": temperature,
    }

    if per_species:
        msd_per_species: dict[str, list[float]] = {}
        n_atoms_per_species: dict[str, int] = {}
        for atomic_number, symbol in sorted(type_to_dict(numbers).items()):
            mask = numbers == atomic_number
            msd_per_species[symbol] = per_group(positions[:, mask, :]).tolist()
            n_atoms_per_species[symbol] = int(mask.sum())
        result["msd_per_species"] = msd_per_species
        result["n_atoms_per_species"] = n_atoms_per_species

    return result

compute_network_connectivity(qn_dist: dict[int, int | float]) -> float

Compute average network connectivity based on Qn distribution.

Parameters:

Name Type Description Default
qn_dist dict[int, int | float]

Qn distribution histogram.

required

Returns:

Type Description
float

Average network connectivity.

Raises:

Type Description
ValueError

If qn_dist is empty or sum of counts is zero.

Example

qn_dist = {0: 10, 1: 50, 2: 100, 3: 200, 4: 50} connectivity = compute_network_connectivity(qn_dist)

Source code in amorphouspy/src/amorphouspy/properties/structural/qn.py
def compute_network_connectivity(qn_dist: dict[int, int | float]) -> float:
    """Compute average network connectivity based on Qn distribution.

    Args:
        qn_dist: Qn distribution histogram.

    Returns:
        Average network connectivity.

    Raises:
        ValueError: If qn_dist is empty or sum of counts is zero.

    Example:
        >>> qn_dist = {0: 10, 1: 50, 2: 100, 3: 200, 4: 50}
        >>> connectivity = compute_network_connectivity(qn_dist)

    """
    total_formers = sum(qn_dist.values())
    if total_formers == 0:
        msg = "total_formers is zero, cannot compute network connectivity."
        raise ValueError(msg)

    return sum(n * (count / total_formers) for n, count in qn_dist.items())

compute_optical_response(frequencies_thz: ArrayLike, epsilon: ArrayLike) -> dict[str, Any]

Compute the optical constants, absorption coefficient, reflectivity and loss function from \(\varepsilon(\nu)\).

The complex refractive index is \(n + i k = \sqrt{\varepsilon}\) (the root with \(n \ge 0\)). It gives the absorption coefficient of the intensity, \(I(x) = I_0 e^{-\alpha x}\), the reflectivity of a thick sample at normal incidence in vacuum, and the energy loss function, whose peaks mark the longitudinal optical modes:

\[\alpha = 4\pi \tilde\nu k, \qquad R = \left|\frac{\sqrt{\varepsilon} - 1}{\sqrt{\varepsilon} + 1}\right|^2, \qquad L = \operatorname{Im}\left(-\frac{1}{\varepsilon}\right),\]

with the wavenumber \(\tilde\nu = \nu / c\) in cm\(^{-1}\). NaN in epsilon (the zero-frequency bin of :func:compute_dielectric_from_velocities) gives NaN at the same points.

Parameters:

Name Type Description Default
frequencies_thz ArrayLike

The frequencies in THz, 1-D, finite and non-negative.

required
epsilon ArrayLike

The complex dielectric function at these frequencies, e.g. "epsilon" of :func:compute_dielectric_function.

required

Returns:

Type Description
dict[str, Any]

A dictionary with one array per frequency: "refractive_index": \(n\). "extinction": \(k\). "absorption_cm": \(\alpha\) in cm\(^{-1}\). "reflectivity": \(R\). "loss_function": \(L\).

Raises:

Type Description
ValueError

If frequencies_thz is not a non-empty 1-D array of finite non-negative values, or epsilon does not have the same shape or contains inf.

Example
>>> optics = compute_optical_response(dielectric["frequencies_thz"], dielectric["epsilon"])  # doctest: +SKIP
>>> optics["reflectivity"]  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/infrared.py
def compute_optical_response(frequencies_thz: ArrayLike, epsilon: ArrayLike) -> dict[str, Any]:
    r"""Compute the optical constants, absorption coefficient, reflectivity and loss function from $\varepsilon(\nu)$.

    The complex refractive index is $n + i k = \sqrt{\varepsilon}$ (the root with $n \ge 0$). It gives the
    absorption coefficient of the intensity, $I(x) = I_0 e^{-\alpha x}$, the reflectivity of a thick sample at normal
    incidence in vacuum, and the energy loss function, whose peaks mark the longitudinal optical modes:

    $$\alpha = 4\pi \tilde\nu k, \qquad
    R = \left|\frac{\sqrt{\varepsilon} - 1}{\sqrt{\varepsilon} + 1}\right|^2, \qquad
    L = \operatorname{Im}\left(-\frac{1}{\varepsilon}\right),$$

    with the wavenumber $\tilde\nu = \nu / c$ in cm$^{-1}$. NaN in ``epsilon`` (the zero-frequency bin of
    :func:`compute_dielectric_from_velocities`) gives NaN at the same points.

    Args:
        frequencies_thz: The frequencies in THz, 1-D, finite and non-negative.
        epsilon: The complex dielectric function at these frequencies, e.g. ``"epsilon"`` of
            :func:`compute_dielectric_function`.

    Returns:
        A dictionary with one array per frequency:
            ``"refractive_index"``: $n$.
            ``"extinction"``: $k$.
            ``"absorption_cm"``: $\alpha$ in cm$^{-1}$.
            ``"reflectivity"``: $R$.
            ``"loss_function"``: $L$.

    Raises:
        ValueError: If ``frequencies_thz`` is not a non-empty 1-D array of finite non-negative values, or
            ``epsilon`` does not have the same shape or contains inf.

    Example:
        ```pycon
        >>> optics = compute_optical_response(dielectric["frequencies_thz"], dielectric["epsilon"])  # doctest: +SKIP
        >>> optics["reflectivity"]  # doctest: +SKIP

        ```
    """
    frequencies = np.asarray(frequencies_thz, dtype=np.float64)
    if frequencies.ndim != 1 or frequencies.size == 0 or not np.all(np.isfinite(frequencies) & (frequencies >= 0)):
        msg = (
            "frequencies_thz must be a non-empty 1-D array of finite non-negative values, "
            f"got shape {frequencies.shape}."
        )
        raise ValueError(msg)
    epsilon = np.asarray(epsilon, dtype=np.complex128)
    if epsilon.shape != frequencies.shape or np.any(np.isinf(epsilon)):
        msg = f"epsilon must hold {frequencies.size} values without inf, one per frequency, got shape {epsilon.shape}."
        raise ValueError(msg)
    root = np.sqrt(epsilon)
    with np.errstate(invalid="ignore"):  # NaN in epsilon stays NaN
        reflectivity = np.abs((root - 1) / (root + 1)) ** 2
        loss_function = (-1 / epsilon).imag
    return {
        "refractive_index": root.real,
        "extinction": root.imag,
        "absorption_cm": 4 * math.pi * convert_frequency(frequencies, "THz", "cm-1") * root.imag,
        "reflectivity": reflectivity,
        "loss_function": loss_function,
    }

compute_partial_vacf(velocities: NDArray, masses: NDArray, dt_fs: float, groups: dict[str, dict[str, NDArray]], *, max_lag_frames: int | None = None, normalization: VacfNormalization = 'unit', remove_com: bool = True) -> tuple[NDArray[np.float64], dict[str, dict[str, NDArray[np.float64]]]]

Compute partial VACFs for many atom groups with one transform per atom.

Each partial is exactly what :func:compute_vacf_from_velocities returns with indices set to the group (same centre-of-mass treatment, lags, normalisation and units), but every atom is transformed once, however many groups it belongs to. groups has the layout returned by :func:classify_vibrational_groups. Within one grouping that covers every atom once (e.g. "element"), the partials add up to the total VACF.

Parameters:

Name Type Description Default
velocities NDArray

Velocities of shape (n_frames, n_atoms, 3) in any unit.

required
masses NDArray

Atomic masses of shape (n_atoms,) in amu.

required
dt_fs float

Time between consecutive frames in fs (the dump interval, not the MD timestep).

required
groups dict[str, dict[str, NDArray]]

{grouping: {label: indices}} with 0-based atom positions, e.g. the output of :func:classify_vibrational_groups. Atoms may appear in several groupings.

required
max_lag_frames int | None

Largest lag in frames, as in :func:compute_vacf_from_velocities.

None
normalization VacfNormalization

"unit" or "none", as in :func:compute_vacf_from_velocities.

'unit'
remove_com bool

Subtract the centre-of-mass velocity of the whole system from every frame.

True

Returns:

Type Description
NDArray[float64]

A tuple (lag_ps, partial): the lags in ps and {grouping: {label: vacf}} with the same keys as

dict[str, dict[str, NDArray[float64]]]

groups, each a float64 array of length max_lag_frames + 1.

Raises:

Type Description
ValueError

As :func:compute_vacf_from_velocities, for any group's indices, or if groups has no labels.

Example
>>> rng = np.random.default_rng(0)
>>> velocities = rng.normal(size=(100, 3, 3))
>>> masses = np.array([28.085, 15.999, 15.999])
>>> groups = {"element": {"Si": np.array([0]), "O": np.array([1, 2])}}
>>> lag_ps, partial = compute_partial_vacf(velocities, masses, 5.0, groups)
>>> _, total = compute_vacf_from_velocities(velocities, masses, 5.0)
>>> bool(np.allclose(partial["element"]["Si"] + partial["element"]["O"], total))
True
Source code in amorphouspy/src/amorphouspy/properties/vibrational/vacf.py
def compute_partial_vacf(
    velocities: NDArray,
    masses: NDArray,
    dt_fs: float,
    groups: dict[str, dict[str, NDArray]],
    *,
    max_lag_frames: int | None = None,
    normalization: VacfNormalization = "unit",
    remove_com: bool = True,
) -> tuple[NDArray[np.float64], dict[str, dict[str, NDArray[np.float64]]]]:
    """Compute partial VACFs for many atom groups with one transform per atom.

    Each partial is exactly what :func:`compute_vacf_from_velocities` returns with ``indices`` set to the group
    (same centre-of-mass treatment, lags, normalisation and units), but every atom is transformed once, however many
    groups it belongs to. ``groups`` has the layout returned by :func:`classify_vibrational_groups`. Within one
    grouping that covers every atom once (e.g. ``"element"``), the partials add up to the total VACF.

    Args:
        velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit.
        masses: Atomic masses of shape ``(n_atoms,)`` in amu.
        dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep).
        groups: ``{grouping: {label: indices}}`` with 0-based atom positions, e.g. the output of
            :func:`classify_vibrational_groups`. Atoms may appear in several groupings.
        max_lag_frames: Largest lag in frames, as in :func:`compute_vacf_from_velocities`.
        normalization: ``"unit"`` or ``"none"``, as in :func:`compute_vacf_from_velocities`.
        remove_com: Subtract the centre-of-mass velocity of the whole system from every frame.

    Returns:
        A tuple ``(lag_ps, partial)``: the lags in ps and ``{grouping: {label: vacf}}`` with the same keys as
        ``groups``, each a float64 array of length ``max_lag_frames + 1``.

    Raises:
        ValueError: As :func:`compute_vacf_from_velocities`, for any group's indices, or if ``groups`` has no labels.

    Example:
        ```pycon
        >>> rng = np.random.default_rng(0)
        >>> velocities = rng.normal(size=(100, 3, 3))
        >>> masses = np.array([28.085, 15.999, 15.999])
        >>> groups = {"element": {"Si": np.array([0]), "O": np.array([1, 2])}}
        >>> lag_ps, partial = compute_partial_vacf(velocities, masses, 5.0, groups)
        >>> _, total = compute_vacf_from_velocities(velocities, masses, 5.0)
        >>> bool(np.allclose(partial["element"]["Si"] + partial["element"]["O"], total))
        True

        ```
    """
    keys, selections = _group_selections(groups)
    lag_ps, columns = _vacf_columns(
        velocities, masses, dt_fs, selections, max_lag_frames, normalization, remove_com=remove_com
    )
    return lag_ps, _columns_by_group(groups, keys, columns)

compute_partial_vdos(velocities: NDArray, masses: NDArray, dt_fs: float, groups: dict[str, dict[str, NDArray]], *, normalization: VdosNormalization = 'unit', remove_com: bool = True, window: VdosWindow = None) -> tuple[NDArray[np.float64], dict[str, dict[str, NDArray[np.float64]]]]

Compute partial VDOS for many atom groups with one transform per atom.

Each partial is exactly what :func:compute_vdos_from_velocities returns with indices set to the group (same centre-of-mass treatment, window, normalisation and units), but every atom is transformed once, however many groups it belongs to. groups has the layout returned by :func:classify_vibrational_groups: classify once, then reuse the indices for any number of trajectories or blocks. Within one grouping that covers every atom once (e.g. "element"), the partials add up to the total VDOS computed with the same window and normalisation.

Parameters:

Name Type Description Default
velocities NDArray

Velocities of shape (n_frames, n_atoms, 3) in any unit.

required
masses NDArray

Atomic masses of shape (n_atoms,) in amu.

required
dt_fs float

Time between consecutive frames in fs (the dump interval, not the MD timestep).

required
groups dict[str, dict[str, NDArray]]

{grouping: {label: indices}} with 0-based atom positions, e.g. the output of :func:classify_vibrational_groups. Atoms may appear in several groupings.

required
normalization VdosNormalization

"unit", "3N" or "none", as in :func:compute_vdos_from_velocities.

'unit'
remove_com bool

Subtract the centre-of-mass velocity of the whole system from every frame.

True
window VdosWindow

"hann", "hamming", "blackmanharris", ("gaussian", std) or None (default), as in :func:compute_vdos_from_velocities.

None

Returns:

Type Description
NDArray[float64]

A tuple (frequencies_thz, partial): the frequencies in THz and {grouping: {label: vdos}} with the

dict[str, dict[str, NDArray[float64]]]

same keys as groups, each a float64 array of length n_frames // 2 + 1.

Raises:

Type Description
ValueError

As :func:compute_vdos_from_velocities (including an unknown window), for any group's indices, or if groups has no labels.

Example
>>> rng = np.random.default_rng(0)
>>> velocities = rng.normal(size=(100, 3, 3))
>>> masses = np.array([28.085, 15.999, 15.999])
>>> groups = {"element": {"Si": np.array([0]), "O": np.array([1, 2])}}
>>> frequencies_thz, partial = compute_partial_vdos(velocities, masses, 5.0, groups)
>>> _, total = compute_vdos_from_velocities(velocities, masses, 5.0)
>>> bool(np.allclose(partial["element"]["Si"] + partial["element"]["O"], total))
True
Source code in amorphouspy/src/amorphouspy/properties/vibrational/vdos.py
def compute_partial_vdos(
    velocities: NDArray,
    masses: NDArray,
    dt_fs: float,
    groups: dict[str, dict[str, NDArray]],
    *,
    normalization: VdosNormalization = "unit",
    remove_com: bool = True,
    window: VdosWindow = None,
) -> tuple[NDArray[np.float64], dict[str, dict[str, NDArray[np.float64]]]]:
    """Compute partial VDOS for many atom groups with one transform per atom.

    Each partial is exactly what :func:`compute_vdos_from_velocities` returns with ``indices`` set to the group
    (same centre-of-mass treatment, window, normalisation and units), but every atom is transformed once, however many
    groups it belongs to. ``groups`` has the layout returned by :func:`classify_vibrational_groups`: classify once, then
    reuse the indices for any number of trajectories or blocks. Within one grouping that covers every atom once (e.g.
    ``"element"``), the partials add up to the total VDOS computed with the same window and normalisation.

    Args:
        velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit.
        masses: Atomic masses of shape ``(n_atoms,)`` in amu.
        dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep).
        groups: ``{grouping: {label: indices}}`` with 0-based atom positions, e.g. the output of
            :func:`classify_vibrational_groups`. Atoms may appear in several groupings.
        normalization: ``"unit"``, ``"3N"`` or ``"none"``, as in :func:`compute_vdos_from_velocities`.
        remove_com: Subtract the centre-of-mass velocity of the whole system from every frame.
        window: ``"hann"``, ``"hamming"``, ``"blackmanharris"``, ``("gaussian", std)`` or ``None`` (default), as in
            :func:`compute_vdos_from_velocities`.

    Returns:
        A tuple ``(frequencies_thz, partial)``: the frequencies in THz and ``{grouping: {label: vdos}}`` with the
        same keys as ``groups``, each a float64 array of length ``n_frames // 2 + 1``.

    Raises:
        ValueError: As :func:`compute_vdos_from_velocities` (including an unknown ``window``), for any group's
            indices, or if ``groups`` has no labels.

    Example:
        ```pycon
        >>> rng = np.random.default_rng(0)
        >>> velocities = rng.normal(size=(100, 3, 3))
        >>> masses = np.array([28.085, 15.999, 15.999])
        >>> groups = {"element": {"Si": np.array([0]), "O": np.array([1, 2])}}
        >>> frequencies_thz, partial = compute_partial_vdos(velocities, masses, 5.0, groups)
        >>> _, total = compute_vdos_from_velocities(velocities, masses, 5.0)
        >>> bool(np.allclose(partial["element"]["Si"] + partial["element"]["O"], total))
        True

        ```
    """
    keys, selections = _group_selections(groups)
    frequencies_thz, columns = _vdos_columns(
        velocities, masses, dt_fs, selections, normalization, remove_com=remove_com, window=window
    )
    return frequencies_thz, _columns_by_group(groups, keys, columns)

compute_participation_ratio(eigenvectors: NDArray[np.float64], masses: ArrayLike) -> NDArray[np.float64]

Compute the participation ratio of every mode from the displacements of its mass-weighted eigenvector.

The eigenvectors \(e_{3i+\alpha,k}\) of the mass-weighted dynamical matrix (atom \(i\), direction \(\alpha\), mode \(k\)) give the atomic displacements \(u_{3i+\alpha,k} \propto e_{3i+\alpha,k} / \sqrt{m_i}\). With the squared displacement of atom \(i\), the participation ratio is (Taraskin and Elliott, Phys. Rev. B 56, 8605 (1997), Eq. 16, a definition they attribute to Bell and Dean)

\[b_{ik} = \frac{1}{m_i} \sum_\alpha e_{3i+\alpha,k}^2, \qquad P_k = \frac{\left(\sum_i b_{ik}\right)^2}{N \sum_i b_{ik}^2}.\]

The ratio form makes \(P_k\) independent of the scale and sign of each column, so the displacements need no normalisation. \(P_k = 1\) when every atom moves by the same amount (a rigid translation, whatever the masses), \(1/N\) for a mode on one atom and \(n/N\) for a mode shared equally by \(n\) atoms. The per-atom weight is summed over the three directions before squaring, so \(P_k\) does not depend on the orientation of the axes. Unlike the kinetic-energy share \(m_i b_{ik}\) used by :func:compute_harmonic_vdos, \(b_{ik}\) counts atoms by amplitude; the two coincide for a single element.

An extended mode has \(P\) of order 1 at any size, but a mode on a fixed number of atoms has \(P \propto 1/N\), and in a small box the two can be hard to tell apart: a claim that a mode is localised needs the same band compared across box sizes.

Parameters:

Name Type Description Default
eigenvectors NDArray[float64]

The \((3N, K)\) float64 eigenvectors of the mass-weighted dynamical matrix, one mode per column with row \(3i + \alpha\) for atom \(i\) and direction \(\alpha\), e.g. "eigenvectors" of :func:diagonalize_dynamical_matrix (any memory order; no cast or copy is made). Columns need not be normalised.

required
masses ArrayLike

Atomic masses, shape \((N,)\), in the order of the rows, e.g. minimised.get_masses(). Only their ratios matter.

required

Returns:

Type Description
NDArray[float64]

The \((K,)\) float64 participation ratios, in the order of the columns, between \(1/N\) and 1.

Raises:

Type Description
ValueError

If eigenvectors is not a 2-D float64 array, its row count is not a positive multiple of 3, it has no columns, or a column is zero or contains NaN or inf; if masses does not hold \(N\) positive finite values.

Example
>>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin")  # doctest: +SKIP
>>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"])  # doctest: +SKIP
>>> modes = diagonalize_dynamical_matrix(  # doctest: +SKIP
...     matrix, masses=minimised.get_masses(), overwrite_matrix=True
... )
>>> ratios = compute_participation_ratio(modes["eigenvectors"], minimised.get_masses())  # doctest: +SKIP
>>> bands = np.digitize(modes["frequencies_thz"], [8.0, 20.0, 28.0])  # doctest: +SKIP
>>> np.bincount(bands, weights=ratios) / np.bincount(bands)  # mean P per band  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/harmonic.py
def compute_participation_ratio(eigenvectors: NDArray[np.float64], masses: ArrayLike) -> NDArray[np.float64]:
    r"""Compute the participation ratio of every mode from the displacements of its mass-weighted eigenvector.

    The eigenvectors $e_{3i+\alpha,k}$ of the mass-weighted dynamical matrix (atom $i$, direction $\alpha$, mode $k$)
    give the atomic displacements $u_{3i+\alpha,k} \propto e_{3i+\alpha,k} / \sqrt{m_i}$. With the squared displacement
    of atom $i$, the participation ratio is (Taraskin and Elliott, Phys. Rev. B 56, 8605 (1997), Eq. 16, a definition
    they attribute to Bell and Dean)

    $$b_{ik} = \frac{1}{m_i} \sum_\alpha e_{3i+\alpha,k}^2, \qquad
    P_k = \frac{\left(\sum_i b_{ik}\right)^2}{N \sum_i b_{ik}^2}.$$

    The ratio form makes $P_k$ independent of the scale and sign of each column, so the displacements need no
    normalisation. $P_k = 1$ when every atom moves by the same amount (a rigid translation, whatever the masses),
    $1/N$ for a mode on one atom and $n/N$ for a mode shared equally by $n$ atoms. The per-atom weight is summed over
    the three directions before squaring, so $P_k$ does not depend on the orientation of the axes. Unlike the
    kinetic-energy share $m_i b_{ik}$ used by :func:`compute_harmonic_vdos`, $b_{ik}$ counts atoms by amplitude; the
    two coincide for a single element.

    An extended mode has $P$ of order 1 at any size, but a mode on a fixed number of atoms has $P \propto 1/N$, and in a
    small box the two can be hard to tell apart: a claim that a mode is localised needs the same band compared across
    box sizes.


    Args:
        eigenvectors: The $(3N, K)$ float64 eigenvectors of the mass-weighted dynamical matrix, one mode per column
            with row $3i + \alpha$ for atom $i$ and direction $\alpha$, e.g. ``"eigenvectors"`` of
            :func:`diagonalize_dynamical_matrix` (any memory order; no cast or copy is made). Columns need not be
            normalised.
        masses: Atomic masses, shape $(N,)$, in the order of the rows, e.g. ``minimised.get_masses()``. Only their
            ratios matter.

    Returns:
        The $(K,)$ float64 participation ratios, in the order of the columns, between $1/N$ and 1.

    Raises:
        ValueError: If ``eigenvectors`` is not a 2-D float64 array, its row count is not a positive multiple of 3,
            it has no columns, or a column is zero or contains NaN or inf; if ``masses`` does not hold $N$ positive
            finite values.

    Example:
        ```pycon
        >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin")  # doctest: +SKIP
        >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"])  # doctest: +SKIP
        >>> modes = diagonalize_dynamical_matrix(  # doctest: +SKIP
        ...     matrix, masses=minimised.get_masses(), overwrite_matrix=True
        ... )
        >>> ratios = compute_participation_ratio(modes["eigenvectors"], minimised.get_masses())  # doctest: +SKIP
        >>> bands = np.digitize(modes["frequencies_thz"], [8.0, 20.0, 28.0])  # doctest: +SKIP
        >>> np.bincount(bands, weights=ratios) / np.bincount(bands)  # mean P per band  # doctest: +SKIP

        ```
    """
    eigenvectors = np.asarray(eigenvectors)
    if eigenvectors.ndim != _MATRIX_NDIM or eigenvectors.dtype != np.float64:
        msg = (
            "eigenvectors must be a 2-D float64 array (a cast would copy it), "
            f"got {eigenvectors.ndim}-D {eigenvectors.dtype}."
        )
        raise ValueError(msg)
    n_rows, n_modes = eigenvectors.shape
    if n_rows == 0 or n_rows % _N_COMPONENTS or n_modes == 0:
        msg = f"eigenvectors must have 3N rows (N >= 1) and at least one column, got shape {eigenvectors.shape}."
        raise ValueError(msg)
    n_atoms = n_rows // _N_COMPONENTS
    masses = np.asarray(masses, dtype=np.float64)
    if masses.shape != (n_atoms,) or not np.all(np.isfinite(masses) & (masses > 0)):
        msg = f"masses must be {n_atoms} positive finite values, one per atom, got shape {masses.shape}."
        raise ValueError(msg)
    ratios = np.empty(n_modes)
    for columns, atom_weights in _mode_atom_weights(eigenvectors, n_atoms):
        np.divide(atom_weights, masses[:, None], out=atom_weights)  # squared displacements, in place in our block
        # The weights are non-negative, so NaN or inf anywhere in a column makes its sum of squares non-finite.
        squares = np.einsum("ik,ik->k", atom_weights, atom_weights)
        if not np.all(np.isfinite(squares)):
            msg = f"eigenvectors contain NaN or inf (mode {columns.start + int(np.argmin(np.isfinite(squares)))})."
            raise ValueError(msg)
        if np.any(squares == 0):
            msg = f"eigenvectors has a zero column (mode {columns.start + int(np.argmax(squares == 0))})."
            raise ValueError(msg)
        ratios[columns] = atom_weights.sum(axis=0) ** 2 / (n_atoms * squares)
    return ratios

compute_projected_rdf(frames: Atoms | list[Atoms], deformation_axis: Literal['x', 'y', 'z'] | None = None, shear_plane: Literal['xy', 'xz', 'yz'] | None = None, r_max: float = 10.0, n_bins: int = 500, type_pairs: list[tuple[int, int]] | None = None) -> tuple[np.ndarray, dict[tuple[int, int], np.ndarray] | None, dict[tuple[int, int], np.ndarray] | None]

Compute the uniaxial and shear projected radial distribution functions.

Expands the pair correlation function onto the l=2 spherical harmonic components that carry the deformation signal:

  • uniaxial_rdf: the Y20-based component along deformation_axis. Vanishes for isotropic structures; grows with uniaxial strain.
  • shear_rdf: the Y21 or Y22 component for shear_plane. Vanishes for isotropic structures; grows with shear.

At least one of deformation_axis or shear_plane must be provided. Omit the one you do not need, its slot in the return tuple will be None.

For multiple frames the per-frame normalised values are averaged, so NPT trajectories with varying cell geometries are handled correctly.

Performance: Numba-JIT kernels accumulate all five needed Y*_lm components in a single i<j pass. On first call Numba compiles the kernels (~5 s); subsequent calls use cached bytecode.

Parameters:

Name Type Description Default
frames Atoms | list[Atoms]

Single ASE Atoms object or list of frames for trajectory averaging.

required
deformation_axis Literal['x', 'y', 'z'] | None

Axis along which uniaxial deformation was applied ('x', 'y', or 'z'). Determines which linear combination of Y20 and Re Y22 is returned as the uniaxial signal. None skips uniaxial extraction and returns None for uniaxial_rdf.

None
shear_plane Literal['xy', 'xz', 'yz'] | None

Plane in which shear deformation was applied ('xy', 'xz', or 'yz'). Determines which Y21/Y22 component is returned as the shear signal. None skips shear extraction and returns None for shear_rdf.

None
r_max float

Maximum distance in Angstrom (default 10.0). Automatically clamped to floor(min_perpendicular_height / 2) with a warning if exceeded.

10.0
n_bins int

Number of radial bins (default 500).

500
type_pairs list[tuple[int, int]] | None

List of (atomic_number_a, atomic_number_b) pairs to compute. None computes all unique unordered combinations present in the first frame.

None

Returns:

Name Type Description
r ndarray

Radial bin centres in Angstrom, shape (n_bins,).

uniaxial_rdf dict[tuple[int, int], ndarray] | None

Dict keyed by (type1, type2) -> real array of shape (n_bins,), or None if deformation_axis was not provided.

shear_rdf dict[tuple[int, int], ndarray] | None

Dict keyed by (type1, type2) -> real array of shape (n_bins,), or None if shear_plane was not provided.

Raises:

Type Description
ValueError

If both deformation_axis and shear_plane are None.

ValueError

If r_max after clamping would be <= 0.

Example

from ase.build import bulk atoms = bulk("Si", "diamond", a=5.43) * (4, 4, 4)

Uniaxial only -- no shear plane needed

r, uniaxial, _ = compute_projected_rdf( ... atoms, deformation_axis="z", r_max=6.0 ... ) signal_SiSi = uniaxial[(14, 14)] # near zero for undeformed bulk

Source code in amorphouspy/src/amorphouspy/properties/structural/projected_rdf.py
def compute_projected_rdf(
    frames: Atoms | list[Atoms],
    deformation_axis: Literal["x", "y", "z"] | None = None,
    shear_plane: Literal["xy", "xz", "yz"] | None = None,
    r_max: float = 10.0,
    n_bins: int = 500,
    type_pairs: list[tuple[int, int]] | None = None,
) -> tuple[
    np.ndarray,
    dict[tuple[int, int], np.ndarray] | None,
    dict[tuple[int, int], np.ndarray] | None,
]:
    r"""Compute the uniaxial and shear projected radial distribution functions.

    Expands the pair correlation function onto the l=2 spherical harmonic
    components that carry the deformation signal:

    - **uniaxial_rdf**: the Y20-based component along ``deformation_axis``.
      Vanishes for isotropic structures; grows with uniaxial strain.
    - **shear_rdf**: the Y21 or Y22 component for ``shear_plane``.
      Vanishes for isotropic structures; grows with shear.

    At least one of ``deformation_axis`` or ``shear_plane`` must be provided.
    Omit the one you do not need, its slot in the return tuple will be ``None``.

    For multiple frames the per-frame normalised values are averaged, so NPT
    trajectories with varying cell geometries are handled correctly.

    Performance: Numba-JIT kernels accumulate all five needed Y*_lm components
    in a single i<j pass. On first call Numba compiles the kernels (~5 s);
    subsequent calls use cached bytecode.

    Args:
        frames: Single ASE Atoms object or list of frames for trajectory averaging.
        deformation_axis: Axis along which uniaxial deformation was applied
            ('x', 'y', or 'z'). Determines which linear combination of Y20
            and Re Y22 is returned as the uniaxial signal. ``None`` skips
            uniaxial extraction and returns ``None`` for ``uniaxial_rdf``.
        shear_plane: Plane in which shear deformation was applied
            ('xy', 'xz', or 'yz'). Determines which Y21/Y22 component is
            returned as the shear signal. ``None`` skips shear extraction and
            returns ``None`` for ``shear_rdf``.
        r_max: Maximum distance in Angstrom (default 10.0). Automatically clamped to
            floor(min_perpendicular_height / 2) with a warning if exceeded.
        n_bins: Number of radial bins (default 500).
        type_pairs: List of (atomic_number_a, atomic_number_b) pairs to compute.
            None computes all unique unordered combinations present in the first frame.

    Returns:
        r: Radial bin centres in Angstrom, shape (n_bins,).
        uniaxial_rdf: Dict keyed by (type1, type2) -> real array of shape (n_bins,),
            or ``None`` if ``deformation_axis`` was not provided.
        shear_rdf: Dict keyed by (type1, type2) -> real array of shape (n_bins,),
            or ``None`` if ``shear_plane`` was not provided.

    Raises:
        ValueError: If both ``deformation_axis`` and ``shear_plane`` are ``None``.
        ValueError: If r_max after clamping would be <= 0.

    Example:
        >>> from ase.build import bulk
        >>> atoms = bulk("Si", "diamond", a=5.43) * (4, 4, 4)
        >>> # Uniaxial only -- no shear plane needed
        >>> r, uniaxial, _ = compute_projected_rdf(
        ...     atoms, deformation_axis="z", r_max=6.0
        ... )
        >>> signal_SiSi = uniaxial[(14, 14)]   # near zero for undeformed bulk

    """
    if deformation_axis is None and shear_plane is None:
        msg = "At least one of deformation_axis or shear_plane must be provided."
        raise ValueError(msg)

    if isinstance(frames, Atoms):
        frames = [frames]

    r_max = _resolve_r_max(frames[0], r_max)
    canonical_pairs, pair_lut = _build_pair_lut(frames[0], type_pairs)

    n_pairs = len(canonical_pairs)
    bin_edges = np.linspace(0.0, r_max, n_bins + 1)
    bin_centers = 0.5 * (bin_edges[1:] + bin_edges[:-1])
    bin_width = float(bin_edges[1] - bin_edges[0])
    shell_volumes = 4.0 * np.pi * bin_centers**2 * bin_width

    accumulated_Y20 = np.zeros((n_pairs, n_bins), dtype=np.float64)
    accumulated_Y21_real = np.zeros((n_pairs, n_bins), dtype=np.float64)
    accumulated_Y21_imag = np.zeros((n_pairs, n_bins), dtype=np.float64)
    accumulated_Y22_real = np.zeros((n_pairs, n_bins), dtype=np.float64)
    accumulated_Y22_imag = np.zeros((n_pairs, n_bins), dtype=np.float64)

    for atoms in frames:
        _accumulate_frame(
            atoms,
            canonical_pairs,
            pair_lut,
            r_max,
            bin_width,
            n_bins,
            shell_volumes,
            accumulated_Y20,
            accumulated_Y21_real,
            accumulated_Y21_imag,
            accumulated_Y22_real,
            accumulated_Y22_imag,
        )

    n_frames = len(frames)
    uniaxial_rdf: dict[tuple[int, int], np.ndarray] | None = {} if deformation_axis is not None else None
    shear_rdf: dict[tuple[int, int], np.ndarray] | None = {} if shear_plane is not None else None

    for pair_idx, (type1, type2) in enumerate(canonical_pairs):
        g20 = accumulated_Y20[pair_idx] / n_frames
        g21_real = accumulated_Y21_real[pair_idx] / n_frames
        g21_imag = accumulated_Y21_imag[pair_idx] / n_frames
        g22_real = accumulated_Y22_real[pair_idx] / n_frames
        g22_imag = accumulated_Y22_imag[pair_idx] / n_frames

        if deformation_axis is not None and uniaxial_rdf is not None:
            uniaxial_rdf[(type1, type2)] = _extract_uniaxial_signal(g20, g22_real, deformation_axis)
        if shear_plane is not None and shear_rdf is not None:
            shear_rdf[(type1, type2)] = _extract_shear_signal(g21_real, g21_imag, g22_imag, shear_plane)

    return bin_centers, uniaxial_rdf, shear_rdf

compute_qn(structure: Atoms | list[Atoms], cutoff: CutoffSpec, former_types: list[int], o_type: int) -> tuple[dict[int, float], dict[int, dict[int, float]]]

Calculate Qn distribution.

The Q^n distribution characterizes connectivity of tetrahedral network-forming units based on bridging oxygens (BOs) count.

Parameters:

Name Type Description Default
structure Atoms | list[Atoms]

The atomic structure as ASE object. Pass a list to use the first frame.

required
cutoff CutoffSpec

Cutoff radius for former-O neighbor search, either a scalar or a per-pair dict {(z_i, z_j): r_cut}.

required
former_types list[int]

Atom types considered as formers.

required
o_type int

Atom type considered as oxygen.

required

Returns:

Type Description
tuple[dict[int, float], dict[int, dict[int, float]]]

A 2-tuple containing: total_qn: Total Qn distribution. partial_qn: Partial Qn by former type.

Example

structure = read('glass.xyz') total_qn, partial_qn = compute_qn(structure, cutoff=2.0, former_types=[14], o_type=8)

Source code in amorphouspy/src/amorphouspy/properties/structural/qn.py
def compute_qn(
    structure: Atoms | list[Atoms],
    cutoff: CutoffSpec,
    former_types: list[int],
    o_type: int,
) -> tuple[dict[int, float], dict[int, dict[int, float]]]:
    """Calculate Qn distribution.

    The Q^n distribution characterizes connectivity of tetrahedral
    network-forming units based on bridging oxygens (BOs) count.

    Args:
        structure: The atomic structure as ASE object. Pass a list to use the first frame.
        cutoff: Cutoff radius for former-O neighbor search, either a scalar
            or a per-pair dict ``{(z_i, z_j): r_cut}``.
        former_types: Atom types considered as formers.
        o_type: Atom type considered as oxygen.

    Returns:
        A 2-tuple containing:
            total_qn: Total Qn distribution.
            partial_qn: Partial Qn by former type.

    Example:
        >>> structure = read('glass.xyz')
        >>> total_qn, partial_qn = compute_qn(structure, cutoff=2.0, former_types=[14], o_type=8)

    """
    if isinstance(structure, list):
        structure = cast("Atoms", structure[0])
    total_qn, partial_qn, _o_classes = compute_qn_and_classify(structure, cutoff, former_types, o_type)
    return total_qn, partial_qn

compute_qn_and_classify(structure: Atoms | list[Atoms], cutoff: CutoffSpec, former_types: list[int], o_type: int) -> tuple[dict[int, float], dict[int, dict[int, float]], dict[int, str]]

Calculate Qn distribution and classify each oxygen as BO/NBO/free/tri.

Performs a single neighbour search pass to compute both the Q^n distribution and the per-oxygen classification.

Parameters:

Name Type Description Default
structure Atoms | list[Atoms]

The atomic structure as ASE object. Pass a list to use the first frame.

required
cutoff CutoffSpec

Cutoff radius for former-O neighbor search (Å), either a scalar or a per-pair dict {(z_i, z_j): r_cut}.

required
former_types list[int]

Atom types (atomic numbers) considered as formers.

required
o_type int

Atom type (atomic number) considered as oxygen.

required

Returns:

Type Description
tuple[dict[int, float], dict[int, dict[int, float]], dict[int, str]]

A 3-tuple containing: total_qn: Total Qn distribution. partial_qn: Partial Qn by former type. oxygen_classes: Mapping from real atom ID to oxygen class string.

Example

total_qn, partial_qn, o_classes = compute_qn_and_classify( ... structure, cutoff=2.0, former_types=[14], o_type=8 ... )

Source code in amorphouspy/src/amorphouspy/properties/structural/qn.py
def compute_qn_and_classify(
    structure: Atoms | list[Atoms],
    cutoff: CutoffSpec,
    former_types: list[int],
    o_type: int,
) -> tuple[dict[int, float], dict[int, dict[int, float]], dict[int, str]]:
    """Calculate Qn distribution and classify each oxygen as BO/NBO/free/tri.

    Performs a single neighbour search pass to compute both the Q^n
    distribution *and* the per-oxygen classification.

    Args:
        structure: The atomic structure as ASE object. Pass a list to use the first frame.
        cutoff: Cutoff radius for former-O neighbor search (Å), either a
            scalar or a per-pair dict ``{(z_i, z_j): r_cut}``.
        former_types: Atom types (atomic numbers) considered as formers.
        o_type: Atom type (atomic number) considered as oxygen.

    Returns:
        A 3-tuple containing:
            total_qn: Total Qn distribution.
            partial_qn: Partial Qn by former type.
            oxygen_classes: Mapping from real atom ID to oxygen class string.

    Example:
        >>> total_qn, partial_qn, o_classes = compute_qn_and_classify(
        ...     structure, cutoff=2.0, former_types=[14], o_type=8
        ... )

    """
    if isinstance(structure, list):
        structure = cast("Atoms", structure[0])
    total_qn_norm, partial_plain, oxygen_classes, _qn_per_atom = _qn_single_pass(
        structure, cutoff, former_types, o_type
    )
    total_qn_float: dict[int, float] = {n: float(v) for n, v in total_qn_norm.items()}
    partial_float: dict[int, dict[int, float]] = {
        f: {n: float(v) for n, v in qn.items()} for f, qn in partial_plain.items()
    }
    return total_qn_float, partial_float, oxygen_classes

compute_qn_per_atom(structure: Atoms, cutoff: CutoffSpec, former_types: list[int], o_type: int) -> dict[int, int]

Return the Qn (number of bridging oxygens) of every network-former atom.

Uses the same neighbour search pass as :func:compute_qn_and_classify, so the histogram of the returned values reproduces its Q^n distribution.

Parameters:

Name Type Description Default
structure Atoms

The atomic structure as ASE object.

required
cutoff CutoffSpec

Cutoff radius for former-O neighbor search (Å), either a scalar or a per-pair dict {(z_i, z_j): r_cut}.

required
former_types list[int]

Atom types (atomic numbers) considered as formers.

required
o_type int

Atom type (atomic number) considered as oxygen.

required

Returns:

Type Description
dict[int, int]

A mapping from real atom ID (the "id" array if present, else

dict[int, int]

1-based indices) to the number of bridging oxygens ("BO" or

dict[int, int]

"tri") bonded to that former. Every former atom is included,

dict[int, int]

formers without oxygen neighbours as 0. Values are not capped,

dict[int, int]

so counts above 6 are returned as-is.

Example

qn_per_atom = compute_qn_per_atom(atoms, cutoff=2.0, former_types=[14], o_type=8)

Source code in amorphouspy/src/amorphouspy/properties/structural/qn.py
def compute_qn_per_atom(
    structure: Atoms,
    cutoff: CutoffSpec,
    former_types: list[int],
    o_type: int,
) -> dict[int, int]:
    """Return the Qn (number of bridging oxygens) of every network-former atom.

    Uses the same neighbour search pass as :func:`compute_qn_and_classify`, so
    the histogram of the returned values reproduces its Q^n distribution.

    Args:
        structure: The atomic structure as ASE object.
        cutoff: Cutoff radius for former-O neighbor search (Å), either a
            scalar or a per-pair dict ``{(z_i, z_j): r_cut}``.
        former_types: Atom types (atomic numbers) considered as formers.
        o_type: Atom type (atomic number) considered as oxygen.

    Returns:
        A mapping from real atom ID (the ``"id"`` array if present, else
        1-based indices) to the number of bridging oxygens (``"BO"`` or
        ``"tri"``) bonded to that former. Every former atom is included,
        formers without oxygen neighbours as ``0``. Values are not capped,
        so counts above 6 are returned as-is.

    Example:
        >>> qn_per_atom = compute_qn_per_atom(atoms, cutoff=2.0, former_types=[14], o_type=8)

    """
    _total_qn, _partial_qn, _o_classes, qn_per_atom = _qn_single_pass(structure, cutoff, former_types, o_type)
    return qn_per_atom

compute_rdf(structure: Atoms | list[Atoms], r_max: float = 10.0, n_bins: int = 500, type_pairs: list[tuple[int, int]] | None = None) -> tuple[np.ndarray, dict[tuple[int, int], np.ndarray], dict[tuple[int, int], np.ndarray]]

Compute radial distribution functions (RDFs) and cumulative coordination numbers.

Calculates the pair-wise radial distribution function g(r) for specified atom-type pairs under periodic boundary conditions (orthogonal and triclinic), along with the cumulative coordination number n(r).

Parameters:

Name Type Description Default
structure Atoms | list[Atoms]

ASE Atoms object. Pass a list to use the first frame.

required
r_max float

Maximum distance in Å (default 10.0).

10.0
n_bins int

Number of radial bins (default 500).

500
type_pairs list[tuple[int, int]] | None

List of (atomic_number_1, atomic_number_2) pairs. None -> all unique unordered combinations of present types plus all same-type pairs.

None

Returns:

Type Description
tuple[ndarray, dict[tuple[int, int], ndarray], dict[tuple[int, int], ndarray]]

A 3-tuple containing: r: Radial bin centres in Å, shape (n_bins,). rdfs: Normalised g(r) for each type pair. cn_cumulative: Cumulative coordination numbers.

Notes
  • If r_max exceeds half the smallest perpendicular cell height, it is automatically reduced to the largest integer value that does not exceed that limit, and a warning message is printed.
  • If the adjusted r_max would be zero or negative (cell too small), a ValueError is raised instead.
  • This function operates on array indices internally (not atom IDs) because it only needs type information and distances, not ID lookup.
  • Periodic boundaries are handled via the minimum-image convention in fractional space, so both orthogonal and triclinic cells are correct.
Example

structure = read('glass.xyz') r, rdfs, cn = compute_rdf(structure, r_max=10.0, n_bins=500) g_SiO = rdfs[(8, 14)] cn_SiO = cn[(8, 14)] # O around Si cn_OSi = cn[(14, 8)] # Si around O

Source code in amorphouspy/src/amorphouspy/properties/structural/rdf.py
def compute_rdf(
    structure: Atoms | list[Atoms],
    r_max: float = 10.0,
    n_bins: int = 500,
    type_pairs: list[tuple[int, int]] | None = None,
) -> tuple[
    np.ndarray,
    dict[tuple[int, int], np.ndarray],
    dict[tuple[int, int], np.ndarray],
]:
    """Compute radial distribution functions (RDFs) and cumulative coordination numbers.

    Calculates the pair-wise radial distribution function g(r) for specified
    atom-type pairs under periodic boundary conditions (orthogonal and
    triclinic), along with the cumulative coordination number n(r).

    Args:
        structure:  ASE Atoms object. Pass a list to use the first frame.
        r_max:      Maximum distance in Å (default 10.0).
        n_bins:     Number of radial bins (default 500).
        type_pairs: List of (atomic_number_1, atomic_number_2) pairs.
                    None -> all unique unordered combinations of present types
                    plus all same-type pairs.

    Returns:
        A 3-tuple containing:
            r: Radial bin centres in Å, shape (n_bins,).
            rdfs: Normalised g(r) for each type pair.
            cn_cumulative: Cumulative coordination numbers.

    Notes:
        - If r_max exceeds half the smallest perpendicular cell height, it is
          automatically reduced to the largest integer value that does not
          exceed that limit, and a warning message is printed.
        - If the adjusted r_max would be zero or negative (cell too small),
          a ValueError is raised instead.
        - This function operates on array indices internally (not atom IDs)
          because it only needs type information and distances, not ID lookup.
        - Periodic boundaries are handled via the minimum-image convention in
          fractional space, so both orthogonal and triclinic cells are correct.

    Example:
        >>> structure = read('glass.xyz')
        >>> r, rdfs, cn = compute_rdf(structure, r_max=10.0, n_bins=500)
        >>> g_SiO = rdfs[(8, 14)]
        >>> cn_SiO = cn[(8, 14)]   # O around Si
        >>> cn_OSi = cn[(14, 8)]   # Si around O

    """
    if isinstance(structure, list):
        structure = cast("Atoms", structure[0])
    types = structure.get_atomic_numbers()
    unique_types = np.unique(types)
    type_counts = {int(t): int(np.sum(types == t)) for t in unique_types}
    cell = structure.get_cell().array
    volume = abs(np.linalg.det(cell))

    heights = cell_perpendicular_heights(cell)
    r_max_allowed = float(heights.min()) / 2.0
    if r_max > r_max_allowed:
        r_max_adjusted = float(math.floor(r_max_allowed))
        if r_max_adjusted <= 0.0:
            msg = (
                f"r_max_allowed={r_max_allowed:.4f} Å is less than 1 Å; no valid "
                "integer cutoff exists. Use a larger simulation box."
            )
            raise ValueError(msg)
        warnings.warn(
            f"r_max={r_max:.4f} Å exceeds half the smallest perpendicular "
            f"cell height ({r_max_allowed:.4f} Å). r_max has been automatically "
            f"adjusted to {r_max_adjusted:.1f} Å (largest integer not exceeding "
            f"the limit).",
            UserWarning,
            stacklevel=2,
        )
        r_max = r_max_adjusted

    if type_pairs is None:
        unordered_pairs = [(int(a), int(b)) for a, b in combinations_with_replacement(unique_types, 2)]
        requested_ordered = []
        for a, b in unordered_pairs:
            requested_ordered.append((a, b))
            if a != b:
                requested_ordered.append((b, a))
    else:
        valid_pairs = [(a, b) for a, b in type_pairs if a in type_counts and b in type_counts]
        unordered_pairs = list({(min(a, b), max(a, b)) for a, b in valid_pairs})
        requested_ordered = list(dict.fromkeys(valid_pairs))

    bin_edges = np.linspace(0, r_max, n_bins + 1)
    r = 0.5 * (bin_edges[1:] + bin_edges[:-1])
    dr = bin_edges[1] - bin_edges[0]
    shell_volumes = 4.0 * np.pi * r**2 * dr

    distances, i_idx, j_idx = _compute_distances(structure, r_max, types, unordered_pairs)
    type_i = types[i_idx]
    type_j = types[j_idx]

    rdfs, hist_directed = _compute_rdf_histograms(
        unordered_pairs,
        type_i,
        type_j,
        distances,
        type_counts,
        volume,
        bin_edges,
        shell_volumes,
    )
    cn_cumulative = _compute_cn_cumulative(requested_ordered, hist_directed, type_counts)

    return r, rdfs, cn_cumulative

compute_reduced_vdos(frequencies_thz: NDArray, vdos: NDArray, *, peak_range_thz: tuple[float, float] = (0.5, 5.0), debye: dict[str, float] | None = None) -> dict[str, Any]

Compute the reduced VDOS \(g(\nu) / \nu^2\), the boson-peak position and its height over the Debye level.

The boson peak is the raw maximum of \(g(\nu) / \nu^2\) within peak_range_thz, with no smoothing or fit, so pass a block-averaged VDOS (e.g. a Hann-windowed mean over blocks); the maximum of a single noisy spectrum is mostly noise. The default range of 0.5 to 5 THz is a generic choice for oxide glasses (silica peaks near 1 THz); set it for the system at hand. A maximum on the first or last bin of the range ("peak_at_range_edge") means no peak was found inside it, e.g. a reduced VDOS that rises steeply towards zero frequency.

With debye (the output of :func:compute_debye_level), the peak height is also divided by the Debye level, and every frequency below the lowest one the box supports is marked unreliable. The level is only compared, never fitted: without debye none of these keys is returned. The VDOS and debye must use the same normalisation ("unit" or "3N").

Any VDOS works, including a partial VDOS, but the Debye comparison is meaningful for the total VDOS only.

Parameters:

Name Type Description Default
frequencies_thz NDArray

Frequencies in THz, 1-D, non-negative and strictly increasing, e.g. from :func:compute_vdos_from_velocities.

required
vdos NDArray

VDOS on frequencies_thz, 1-D of the same length, in 1/THz.

required
peak_range_thz tuple[float, float]

(low, high) in THz, both ends included, in which the boson peak is searched. The frequency 0 is never part of the range.

(0.5, 5.0)
debye dict[str, float] | None

The dict returned by :func:compute_debye_level, or None (default).

None

Returns:

Type Description
dict[str, Any]

A dict with: "reduced_vdos": \(g(\nu) / \nu^2\) in THz\(^{-3}\), a float64 array of the input length, NaN at \(\nu = 0\). "boson_peak_thz": frequency of the maximum within peak_range_thz, in THz. "boson_peak_height": reduced VDOS at that frequency, in THz\(^{-3}\). "peak_at_range_edge": True if the maximum is on the first or last bin of the range.

dict[str, Any]

With debye also: "debye_level_thz-3": the Debye level from debye. "boson_peak_over_debye": boson_peak_height divided by the Debye level. "reliable": boolean array, True where the frequency is at or above the lowest box frequency. "peak_below_box_limit": True if the boson peak lies below the lowest box frequency.

Raises:

Type Description
ValueError

If frequencies_thz and vdos are not 1-D arrays of the same length, contain NaN or inf, a frequency is negative, the frequencies are not strictly increasing, peak_range_thz does not satisfy low < high, or the range contains no frequency above 0.

Example
>>> from ase import Atoms
>>> silica = Atoms("Si1000O2000", cell=[35.661] * 3, pbc=True)  # 2.2 g/cm^3
>>> debye = compute_debye_level(silica, bulk_modulus_gpa=36.7, shear_modulus_gpa=31.2)
>>> frequencies_thz = np.linspace(0.0, 10.0, 201)
>>> excess = 1 + np.exp(-0.5 * ((frequencies_thz - 1.2) / 0.4) ** 2)
>>> vdos = debye["debye_level_thz-3"] * frequencies_thz**2 * excess  # Debye VDOS with an excess at 1.2 THz
>>> result = compute_reduced_vdos(frequencies_thz, vdos, debye=debye)
>>> round(result["boson_peak_thz"], 3), result["peak_at_range_edge"], round(result["boson_peak_over_debye"], 3)
(1.2, False, 2.0)
>>> bool(np.isnan(result["reduced_vdos"][0])), result["reduced_vdos"].shape
(True, (201,))
>>> round(float(frequencies_thz[result["reliable"]][0]), 3), result["peak_below_box_limit"]
(1.1, False)
Source code in amorphouspy/src/amorphouspy/properties/vibrational/debye.py
def compute_reduced_vdos(
    frequencies_thz: NDArray,
    vdos: NDArray,
    *,
    peak_range_thz: tuple[float, float] = (0.5, 5.0),
    debye: dict[str, float] | None = None,
) -> dict[str, Any]:
    r"""Compute the reduced VDOS $g(\nu) / \nu^2$, the boson-peak position and its height over the Debye level.

    The boson peak is the raw maximum of $g(\nu) / \nu^2$ within ``peak_range_thz``, with no smoothing or fit, so pass
    a block-averaged VDOS (e.g. a Hann-windowed mean over blocks); the maximum of a single noisy spectrum is mostly
    noise. The default range of 0.5 to 5 THz is a generic choice for oxide glasses (silica peaks near 1 THz); set it
    for the system at hand. A maximum on the first or last bin of the range (``"peak_at_range_edge"``) means no peak
    was found inside it, e.g. a reduced VDOS that rises steeply towards zero frequency.

    With ``debye`` (the output of :func:`compute_debye_level`), the peak height is also divided by the Debye level, and
    every frequency below the lowest one the box supports is marked unreliable. The level is only compared, never
    fitted: without ``debye`` none of these keys is returned. The VDOS and ``debye`` must use the same normalisation
    (``"unit"`` or ``"3N"``).

    Any VDOS works, including a partial VDOS, but the Debye comparison is meaningful for the total VDOS only.

    Args:
        frequencies_thz: Frequencies in THz, 1-D, non-negative and strictly increasing, e.g. from
            :func:`compute_vdos_from_velocities`.
        vdos: VDOS on ``frequencies_thz``, 1-D of the same length, in 1/THz.
        peak_range_thz: ``(low, high)`` in THz, both ends included, in which the boson peak is searched. The
            frequency 0 is never part of the range.
        debye: The dict returned by :func:`compute_debye_level`, or ``None`` (default).

    Returns:
        A dict with:
            ``"reduced_vdos"``: $g(\nu) / \nu^2$ in THz$^{-3}$, a float64 array of the input length, NaN at
            $\nu = 0$.
            ``"boson_peak_thz"``: frequency of the maximum within ``peak_range_thz``, in THz.
            ``"boson_peak_height"``: reduced VDOS at that frequency, in THz$^{-3}$.
            ``"peak_at_range_edge"``: True if the maximum is on the first or last bin of the range.
        With ``debye`` also:
            ``"debye_level_thz-3"``: the Debye level from ``debye``.
            ``"boson_peak_over_debye"``: ``boson_peak_height`` divided by the Debye level.
            ``"reliable"``: boolean array, True where the frequency is at or above the lowest box frequency.
            ``"peak_below_box_limit"``: True if the boson peak lies below the lowest box frequency.

    Raises:
        ValueError: If ``frequencies_thz`` and ``vdos`` are not 1-D arrays of the same length, contain NaN or inf,
            a frequency is negative, the frequencies are not strictly increasing, ``peak_range_thz`` does not satisfy
            ``low < high``, or the range contains no frequency above 0.

    Example:
        ```pycon
        >>> from ase import Atoms
        >>> silica = Atoms("Si1000O2000", cell=[35.661] * 3, pbc=True)  # 2.2 g/cm^3
        >>> debye = compute_debye_level(silica, bulk_modulus_gpa=36.7, shear_modulus_gpa=31.2)
        >>> frequencies_thz = np.linspace(0.0, 10.0, 201)
        >>> excess = 1 + np.exp(-0.5 * ((frequencies_thz - 1.2) / 0.4) ** 2)
        >>> vdos = debye["debye_level_thz-3"] * frequencies_thz**2 * excess  # Debye VDOS with an excess at 1.2 THz
        >>> result = compute_reduced_vdos(frequencies_thz, vdos, debye=debye)
        >>> round(result["boson_peak_thz"], 3), result["peak_at_range_edge"], round(result["boson_peak_over_debye"], 3)
        (1.2, False, 2.0)
        >>> bool(np.isnan(result["reduced_vdos"][0])), result["reduced_vdos"].shape
        (True, (201,))
        >>> round(float(frequencies_thz[result["reliable"]][0]), 3), result["peak_below_box_limit"]
        (1.1, False)

        ```
    """
    frequencies_thz = np.asarray(frequencies_thz, dtype=np.float64)
    vdos = np.asarray(vdos, dtype=np.float64)
    if frequencies_thz.ndim != 1 or vdos.shape != frequencies_thz.shape:
        msg = (
            "frequencies_thz and vdos must be 1-D arrays of the same length, "
            f"got shapes {frequencies_thz.shape} and {vdos.shape}."
        )
        raise ValueError(msg)
    if not (np.all(np.isfinite(frequencies_thz)) and np.all(np.isfinite(vdos))):
        msg = "frequencies_thz and vdos must not contain NaN or inf."
        raise ValueError(msg)
    if np.any(frequencies_thz < 0):
        msg = "frequencies_thz must not be negative."
        raise ValueError(msg)
    if np.any(np.diff(frequencies_thz) <= 0):
        msg = "frequencies_thz must be strictly increasing."
        raise ValueError(msg)
    low, high = peak_range_thz
    if not low < high:
        msg = f"peak_range_thz must satisfy low < high, got {peak_range_thz}."
        raise ValueError(msg)

    positive = frequencies_thz > 0
    reduced = np.full_like(vdos, np.nan)
    np.divide(vdos, frequencies_thz**2, out=reduced, where=positive)
    in_range = np.flatnonzero(positive & (frequencies_thz >= low) & (frequencies_thz <= high))
    if in_range.size == 0:
        msg = f"peak_range_thz {peak_range_thz} contains no frequency bins above 0 THz."
        raise ValueError(msg)
    peak = in_range[np.argmax(reduced[in_range])]
    result: dict[str, Any] = {
        "reduced_vdos": reduced,
        "boson_peak_thz": float(frequencies_thz[peak]),
        "boson_peak_height": float(reduced[peak]),
        "peak_at_range_edge": bool(peak in (in_range[0], in_range[-1])),
    }
    if debye is not None:
        level = float(debye["debye_level_thz-3"])
        lowest_thz = float(debye["lowest_box_frequency_thz"])
        result["debye_level_thz-3"] = level
        result["boson_peak_over_debye"] = result["boson_peak_height"] / level
        result["reliable"] = frequencies_thz >= lowest_thz
        result["peak_below_box_limit"] = bool(frequencies_thz[peak] < lowest_thz)
    return result

compute_structure_factor(structure: Atoms | list[Atoms], q_min: float = 0.5, q_max: float = 20.0, n_q: int = 500, r_max: float = 10.0, n_bins: int = 2000, radiation: str = 'neutron', *, lorch_damping: bool = True, type_pairs: list[tuple[int, int]] | None = None) -> tuple[np.ndarray, np.ndarray, dict[tuple[int, int], np.ndarray]]

Compute the 1D isotropic structure factor S(q) and Faber-Ziman partials.

Uses the Faber-Ziman formalism to compute partial structure factors S_ab(q) from partial radial distribution functions g_ab(r) via the sine transform, then combines them into the total S(q) weighted by coherent neutron scattering lengths or q-dependent X-ray form factors.

Neutron diffraction (Faber-Ziman total structure factor):

S(q) = 1 + sum_{a<=b} (2 - d_ab) * c_a * c_b * b_a * b_b * [S_ab(q) - 1] / <b>^2

where c_a is the atomic concentration, b_a the coherent scattering length (from NIST), and = sum_a c_a * b_a.

X-ray diffraction: b_a is replaced by the q-dependent International Tables form factor f_a(q) (four-Gaussian fit via pymatgen), making the weights q-dependent.

Parameters:

Name Type Description Default
structure Atoms | list[Atoms]

ASE Atoms object with periodic boundary conditions. Pass a list to use the first frame.

required
q_min float

Minimum momentum transfer in Angstroms^-1 (default 0.5).

0.5
q_max float

Maximum momentum transfer in Angstroms^-1 (default 20.0).

20.0
n_q int

Number of q-grid points (default 500).

500
r_max float

Real-space cutoff in Angstroms for the underlying RDF (default 10.0).

10.0
n_bins int

Number of radial bins for the RDF (default 2000).

2000
radiation str

Scattering probe: "neutron" uses tabulated NIST coherent scattering lengths; "xray" uses the International Tables four-Gaussian form factors via pymatgen (default "neutron").

'neutron'
lorch_damping bool

Apply the Lorch modification function M(r) = sinc(r/r_max) to suppress termination ripples from the finite r_max cutoff (default True).

True
type_pairs list[tuple[int, int]] | None

List of (Z_a, Z_b) pairs for which to compute partials. None computes all unique unordered pairs present in the structure.

None

Returns:

Name Type Description
q ndarray

Momentum transfer grid in Angstroms^-1, shape (n_q,).

sq_total ndarray

Total structure factor S(q), shape (n_q,).

sq_partials dict[tuple[int, int], ndarray]

Faber-Ziman partial structure factors S_ab(q), keyed by the canonical pair (min(Z_a, Z_b), max(Z_a, Z_b)), each with shape (n_q,).

Raises:

Type Description
ValueError

If radiation is not "neutron" or "xray".

KeyError

If a scattering length or form factor is not available for an element present in the structure.

Example

from ase.io import read structure = read("sodium_silicate.extxyz") q, sq, sq_partials = compute_structure_factor(structure, q_max=20.0) sq_SiO = sq_partials[(8, 14)] # partial S_SiO(q)

Source code in amorphouspy/src/amorphouspy/properties/structural/structure_factor.py
def compute_structure_factor(
    structure: Atoms | list[Atoms],
    q_min: float = 0.5,
    q_max: float = 20.0,
    n_q: int = 500,
    r_max: float = 10.0,
    n_bins: int = 2000,
    radiation: str = "neutron",
    *,
    lorch_damping: bool = True,
    type_pairs: list[tuple[int, int]] | None = None,
) -> tuple[np.ndarray, np.ndarray, dict[tuple[int, int], np.ndarray]]:
    """Compute the 1D isotropic structure factor S(q) and Faber-Ziman partials.

    Uses the Faber-Ziman formalism to compute partial structure factors S_ab(q)
    from partial radial distribution functions g_ab(r) via the sine transform,
    then combines them into the total S(q) weighted by coherent neutron scattering
    lengths or q-dependent X-ray form factors.

    Neutron diffraction (Faber-Ziman total structure factor):

        S(q) = 1 + sum_{a<=b} (2 - d_ab) * c_a * c_b * b_a * b_b * [S_ab(q) - 1] / <b>^2

    where c_a is the atomic concentration, b_a the coherent scattering length
    (from NIST), and <b> = sum_a c_a * b_a.

    X-ray diffraction: b_a is replaced by the q-dependent International Tables
    form factor f_a(q) (four-Gaussian fit via pymatgen), making the weights q-dependent.

    Args:
        structure: ASE Atoms object with periodic boundary conditions. Pass a list to use the first frame.
        q_min: Minimum momentum transfer in Angstroms^-1 (default 0.5).
        q_max: Maximum momentum transfer in Angstroms^-1 (default 20.0).
        n_q: Number of q-grid points (default 500).
        r_max: Real-space cutoff in Angstroms for the underlying RDF (default 10.0).
        n_bins: Number of radial bins for the RDF (default 2000).
        radiation: Scattering probe: ``"neutron"`` uses tabulated NIST coherent
            scattering lengths; ``"xray"`` uses the International Tables
            four-Gaussian form factors via pymatgen (default ``"neutron"``).
        lorch_damping: Apply the Lorch modification function M(r) = sinc(r/r_max)
            to suppress termination ripples from the finite r_max cutoff
            (default True).
        type_pairs: List of (Z_a, Z_b) pairs for which to compute partials.
            ``None`` computes all unique unordered pairs present in the structure.

    Returns:
        q: Momentum transfer grid in Angstroms^-1, shape (n_q,).
        sq_total: Total structure factor S(q), shape (n_q,).
        sq_partials: Faber-Ziman partial structure factors S_ab(q), keyed by
            the canonical pair (min(Z_a, Z_b), max(Z_a, Z_b)), each with
            shape (n_q,).

    Raises:
        ValueError: If ``radiation`` is not ``"neutron"`` or ``"xray"``.
        KeyError: If a scattering length or form factor is not available for
            an element present in the structure.

    Example:
        >>> from ase.io import read
        >>> structure = read("sodium_silicate.extxyz")
        >>> q, sq, sq_partials = compute_structure_factor(structure, q_max=20.0)
        >>> sq_SiO = sq_partials[(8, 14)]  # partial S_SiO(q)

    """
    if isinstance(structure, list):
        structure = cast("Atoms", structure[0])
    if radiation not in ("neutron", "xray"):
        msg = f"radiation must be 'neutron' or 'xray', got {radiation!r}."
        raise ValueError(msg)

    types = structure.get_atomic_numbers()
    unique_types = sorted({int(t) for t in types})
    total_atoms = len(structure)
    cell = structure.get_cell().array
    volume = float(abs(np.linalg.det(cell)))
    number_density = total_atoms / volume  # Angstrom^-3

    concentrations = {t: float(np.sum(types == t)) / total_atoms for t in unique_types}

    # --- Radial distribution functions ----------------------------------------
    r, rdfs, _ = compute_rdf(structure, r_max=r_max, n_bins=n_bins, type_pairs=type_pairs)
    unordered_pairs = list(rdfs.keys())

    # --- Momentum transfer grid -----------------------------------------------
    q_values = np.linspace(q_min, q_max, n_q)

    # --- Partial structure factors --------------------------------------------
    sq_partials: dict[tuple[int, int], np.ndarray] = {
        pair: _sine_transform_rdf(r, rdfs[pair], q_values, number_density, lorch_damping=lorch_damping)
        for pair in unordered_pairs
    }

    # --- Scattering weights and total S(q) ------------------------------------
    if radiation == "neutron":
        scattering_lengths = {t: _neutron_scattering_length(t) for t in unique_types}
        mean_b = sum(concentrations[t] * scattering_lengths[t] for t in unique_types)
        mean_b_sq = mean_b**2

        sq_total = np.zeros(n_q)
        for t1, t2 in unordered_pairs:
            b1 = scattering_lengths[t1]
            b2 = scattering_lengths[t2]
            symmetry_factor = 1.0 if t1 == t2 else 2.0
            weight = symmetry_factor * concentrations[t1] * concentrations[t2] * b1 * b2
            sq_total += weight * (sq_partials[(t1, t2)] - 1.0)
        sq_total = 1.0 + sq_total / mean_b_sq

    else:  # xray
        form_factors = {t: _xray_form_factor(t, q_values) for t in unique_types}
        # mean_f(q) = sum_a c_a * f_a(q), shape (n_q,)
        mean_f = np.sum(
            [concentrations[t] * form_factors[t] for t in unique_types],
            axis=0,
        )
        mean_f_sq = mean_f**2

        sq_total = np.zeros(n_q)
        for t1, t2 in unordered_pairs:
            f1 = form_factors[t1]
            f2 = form_factors[t2]
            symmetry_factor = 1.0 if t1 == t2 else 2.0
            weight = symmetry_factor * concentrations[t1] * concentrations[t2] * f1 * f2
            sq_total += weight * (sq_partials[(t1, t2)] - 1.0)
        sq_total = 1.0 + sq_total / mean_f_sq

    return q_values, sq_total, sq_partials

compute_vacf_from_velocities(velocities: NDArray, masses: NDArray, dt_fs: float, *, indices: NDArray | None = None, max_lag_frames: int | None = None, normalization: VacfNormalization = 'unit', remove_com: bool = True) -> tuple[NDArray[np.float64], NDArray[np.float64]]

Compute the mass-weighted velocity autocorrelation function (VACF) from an MD velocity trajectory.

The VACF is

\[C(t_k) = \frac{\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle} {\sum_i m_i \langle |\mathbf{v}_i|^2 \rangle}, \quad t_k = k \Delta t,\]

where \(\langle \cdot \rangle\) is the average over all time origins with the unbiased estimator: lag \(k\) averages the \(N - k\) available products,

\[\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle = \frac{1}{N - k} \sum_{t=0}^{N-1-k} \sum_i m_i\, \mathbf{v}_i(t) \cdot \mathbf{v}_i(t + k),\]

for \(k = 0, \dots,\) max_lag_frames, with \(N\) frames. Fewer origins enter at larger lags, so the statistical noise grows with the lag; the default max_lag_frames = N // 2 keeps at least \(N/2\) origins at every lag.

The sums over origins are computed with FFTs (scipy.fft). Every velocity component of every atom is zero-padded to \(2N\) frames before the forward transform, so the correlation is linear, not circular (no wrap-around from the end of the trajectory to its start). The squared transforms are weighted by the masses and summed over the atoms, and the sum is transformed back once, which is exact because the inverse transform is linear. No window is applied: the VACF always uses the unwindowed velocities.

With remove_com=True (default), the instantaneous mass-weighted centre-of-mass velocity of the whole system, \(\mathbf{v}_\mathrm{COM}(t) = \sum_i m_i \mathbf{v}_i(t) / \sum_i m_i\), is subtracted from every atom in every frame first, also when indices selects a subset, exactly as in :func:compute_vdos_from_velocities. With remove_com=False the velocities are used as given; a constant centre-of-mass velocity \(\mathbf{V}\) then adds \(\sum_i m_i |\mathbf{V}|^2\) to the unnormalised total VACF at every lag.

Normalisation:

  • "unit" (default): divided by the total VACF at zero lag, the time average of \(\sum_i m_i |\mathbf{v}_i - \mathbf{v}_\mathrm{COM}|^2\) (of \(\sum_i m_i |\mathbf{v}_i|^2\) with remove_com=False), so the total \(C(0) = 1\) to rounding. Dimensionless.
  • "none": the numerator \(\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle\) in amu (velocity unit)\(^2\). Its value at zero lag is the time average of \(\sum_i m_i |\mathbf{v}_i - \mathbf{v}_\mathrm{COM}|^2\) (twice the mean internal kinetic energy).

A partial VACF (indices given) sums the numerator over the selected atoms only and, with "unit", is divided by the same denominator as the total, so partials over disjoint selections add up to the total VACF, and a partial's \(C(0)\) is the selection's share of the centred kinetic sum. The denominator comes from the statistics read over all atoms, so a partial only transforms the selected atoms. Use :func:compute_partial_vacf for many groups.

Relation to the VDOS: by the Wiener-Khinchin theorem the VDOS is the Fourier transform of the unnormalised VACF. For a finite trajectory, the "none" spectral density of :func:compute_vdos_from_velocities (no window, same remove_com) on its grid \(\nu_j = j / (N \Delta t)\) is exactly

\[S(\nu_j) = 2 \Delta t \left[C(0) + 2 \sum_{k=1}^{N-1} \left(1 - \frac{k}{N}\right) C(t_k) \cos\left(\frac{2 \pi j k}{N}\right)\right],\]

with \(C\) the "none" VACF up to max_lag_frames = N - 1 and \(\Delta t\) in ps: the transform over all lags with a triangular weight. The library computes the VDOS directly from the velocity spectrum, not from this function; transforming a VACF truncated at a shorter lag gives a lower-resolution spectrum.

Memory: as in :func:compute_vdos_from_velocities, the trajectory is read twice in chunks of atoms, once for the centre-of-mass velocity, the normalisation and the finiteness check, and once for the transforms, with chunks sized for the padded length \(2N\). float32 input is transformed in single precision (no float64 copy); the correlation is accumulated in float64. The input is never modified, and it may be a read-only np.memmap.

Parameters:

Name Type Description Default
velocities NDArray

Velocities of shape (n_frames, n_atoms, 3) in any unit; "unit" removes the scale.

required
masses NDArray

Atomic masses of shape (n_atoms,) in amu.

required
dt_fs float

Time between consecutive frames in fs (the dump interval, not the MD timestep).

required
indices NDArray | None

0-based positions of the atoms in a partial VACF, e.g. one entry of :func:classify_vibrational_groups. None (default) gives the total VACF.

None
max_lag_frames int | None

Largest lag in frames, from 1 to n_frames - 1. None (default) means n_frames // 2.

None
normalization VacfNormalization

"unit" or "none", see above.

'unit'
remove_com bool

Subtract the centre-of-mass velocity of the whole system from every frame.

True

Returns:

Type Description
NDArray[float64]

A tuple (lag_ps, vacf) of float64 arrays of length max_lag_frames + 1: the lags

NDArray[float64]

np.arange(max_lag_frames + 1) * dt_fs * 1e-3 in ps and the VACF (dimensionless for "unit", amu

tuple[NDArray[float64], NDArray[float64]]

(velocity unit)\(^2\) for "none").

Raises:

Type Description
ValueError

If velocities is not (n_frames, n_atoms, 3) with at least one atom, masses does not have shape (n_atoms,), there are fewer than 2 frames, dt_fs is not a positive finite number, any mass is not positive and finite, velocities is not real numeric or contains NaN or inf, normalization is unknown, max_lag_frames is not an integer from 1 to n_frames - 1, indices is empty, not 1-D integer, out of range or has duplicates, or there is no motion (all velocities zero, or none left after centre-of-mass removal).

Example
>>> from amorphouspy import get_atomic_mass
>>> dt_fs, n_frames = 5.0, 2000
>>> t_ps = np.arange(n_frames) * dt_fs * 1e-3
>>> velocities = np.zeros((n_frames, 2, 3))
>>> velocities[:, 0, 0] = np.cos(2 * np.pi * 10.0 * t_ps)
>>> velocities[:, 1, 0] = -velocities[:, 0, 0]
>>> masses = np.full(2, get_atomic_mass("Si"))
>>> lag_ps, vacf = compute_vacf_from_velocities(velocities, masses, dt_fs)
>>> lag_ps.shape, round(float(lag_ps[10]), 6)
((1001,), 0.05)
>>> round(float(vacf[0]), 6), round(float(vacf[10]), 6)  # half a 10 THz period after 0.05 ps
(1.0, -1.0)
>>> _, partial = compute_vacf_from_velocities(velocities, masses, dt_fs, indices=np.array([0]))
>>> round(float(partial[0]), 6)
0.5
Source code in amorphouspy/src/amorphouspy/properties/vibrational/vacf.py
def compute_vacf_from_velocities(
    velocities: NDArray,
    masses: NDArray,
    dt_fs: float,
    *,
    indices: NDArray | None = None,
    max_lag_frames: int | None = None,
    normalization: VacfNormalization = "unit",
    remove_com: bool = True,
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
    r"""Compute the mass-weighted velocity autocorrelation function (VACF) from an MD velocity trajectory.

    The VACF is

    $$C(t_k) = \frac{\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle}
    {\sum_i m_i \langle |\mathbf{v}_i|^2 \rangle}, \quad t_k = k \Delta t,$$

    where $\langle \cdot \rangle$ is the average over all time origins with the unbiased estimator: lag $k$ averages
    the $N - k$ available products,

    $$\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle
    = \frac{1}{N - k} \sum_{t=0}^{N-1-k} \sum_i m_i\, \mathbf{v}_i(t) \cdot \mathbf{v}_i(t + k),$$

    for $k = 0, \dots,$ ``max_lag_frames``, with $N$ frames. Fewer origins enter at larger lags, so the statistical
    noise grows with the lag; the default ``max_lag_frames = N // 2`` keeps at least $N/2$ origins at every lag.

    The sums over origins are computed with FFTs (``scipy.fft``). Every velocity component of every atom is
    zero-padded to $2N$ frames before the forward transform, so the correlation is linear, not circular (no
    wrap-around from the end of the trajectory to its start). The squared transforms are weighted by the masses and
    summed over the atoms, and the sum is transformed back once, which is exact because the inverse transform is
    linear. No window is applied: the VACF always uses the unwindowed velocities.

    With ``remove_com=True`` (default), the instantaneous mass-weighted centre-of-mass velocity of the whole system,
    $\mathbf{v}_\mathrm{COM}(t) = \sum_i m_i \mathbf{v}_i(t) / \sum_i m_i$, is subtracted from every atom in every
    frame first, also when ``indices`` selects a subset, exactly as in :func:`compute_vdos_from_velocities`. With
    ``remove_com=False`` the velocities are used as given; a constant centre-of-mass velocity $\mathbf{V}$ then adds
    $\sum_i m_i |\mathbf{V}|^2$ to the unnormalised total VACF at every lag.

    Normalisation:

    - ``"unit"`` (default): divided by the total VACF at zero lag, the time average of
      $\sum_i m_i |\mathbf{v}_i - \mathbf{v}_\mathrm{COM}|^2$ (of $\sum_i m_i |\mathbf{v}_i|^2$ with
      ``remove_com=False``), so the total $C(0) = 1$ to rounding. Dimensionless.
    - ``"none"``: the numerator $\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle$ in amu
      (velocity unit)$^2$. Its value at zero lag is the time average of
      $\sum_i m_i |\mathbf{v}_i - \mathbf{v}_\mathrm{COM}|^2$ (twice the mean internal kinetic energy).

    A partial VACF (``indices`` given) sums the numerator over the selected atoms only and, with ``"unit"``, is divided
    by the same denominator as the total, so partials over disjoint selections add up to the total VACF, and a
    partial's $C(0)$ is the selection's share of the centred kinetic sum. The denominator comes from the
    statistics read over all atoms, so a partial only transforms the selected atoms. Use
    :func:`compute_partial_vacf` for many groups.

    Relation to the VDOS: by the Wiener-Khinchin theorem the VDOS is the Fourier transform of the unnormalised VACF.
    For a finite trajectory, the ``"none"`` spectral density of :func:`compute_vdos_from_velocities` (no window, same
    ``remove_com``) on its grid $\nu_j = j / (N \Delta t)$ is exactly

    $$S(\nu_j) = 2 \Delta t \left[C(0) + 2 \sum_{k=1}^{N-1} \left(1 - \frac{k}{N}\right) C(t_k)
    \cos\left(\frac{2 \pi j k}{N}\right)\right],$$

    with $C$ the ``"none"`` VACF up to ``max_lag_frames = N - 1`` and $\Delta t$ in ps: the transform over all lags
    with a triangular weight. The library computes the VDOS directly from the velocity spectrum, not from this
    function; transforming a VACF truncated at a shorter lag gives a lower-resolution spectrum.

    Memory: as in :func:`compute_vdos_from_velocities`, the trajectory is read twice in chunks of atoms, once for the
    centre-of-mass velocity, the normalisation and the finiteness check, and once for the transforms, with chunks
    sized for the padded length $2N$. float32 input is transformed in single precision (no float64 copy); the
    correlation is accumulated in float64. The input is never modified, and it may be a read-only ``np.memmap``.

    Args:
        velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit; ``"unit"`` removes the scale.
        masses: Atomic masses of shape ``(n_atoms,)`` in amu.
        dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep).
        indices: 0-based positions of the atoms in a partial VACF, e.g. one entry of
            :func:`classify_vibrational_groups`. ``None`` (default) gives the total VACF.
        max_lag_frames: Largest lag in frames, from 1 to ``n_frames - 1``. ``None`` (default) means
            ``n_frames // 2``.
        normalization: ``"unit"`` or ``"none"``, see above.
        remove_com: Subtract the centre-of-mass velocity of the whole system from every frame.

    Returns:
        A tuple ``(lag_ps, vacf)`` of float64 arrays of length ``max_lag_frames + 1``: the lags
        ``np.arange(max_lag_frames + 1) * dt_fs * 1e-3`` in ps and the VACF (dimensionless for ``"unit"``, amu
        (velocity unit)$^2$ for ``"none"``).

    Raises:
        ValueError: If ``velocities`` is not ``(n_frames, n_atoms, 3)`` with at least one atom, ``masses`` does not
            have shape ``(n_atoms,)``, there are fewer than 2 frames, ``dt_fs`` is not a positive finite number, any
            mass is not positive and finite, ``velocities`` is not real numeric or contains NaN or inf,
            ``normalization`` is unknown, ``max_lag_frames`` is not an integer from 1 to ``n_frames - 1``,
            ``indices`` is empty, not 1-D integer, out of range or has duplicates, or there is no motion (all
            velocities zero, or none left after centre-of-mass removal).

    Example:
        ```pycon
        >>> from amorphouspy import get_atomic_mass
        >>> dt_fs, n_frames = 5.0, 2000
        >>> t_ps = np.arange(n_frames) * dt_fs * 1e-3
        >>> velocities = np.zeros((n_frames, 2, 3))
        >>> velocities[:, 0, 0] = np.cos(2 * np.pi * 10.0 * t_ps)
        >>> velocities[:, 1, 0] = -velocities[:, 0, 0]
        >>> masses = np.full(2, get_atomic_mass("Si"))
        >>> lag_ps, vacf = compute_vacf_from_velocities(velocities, masses, dt_fs)
        >>> lag_ps.shape, round(float(lag_ps[10]), 6)
        ((1001,), 0.05)
        >>> round(float(vacf[0]), 6), round(float(vacf[10]), 6)  # half a 10 THz period after 0.05 ps
        (1.0, -1.0)
        >>> _, partial = compute_vacf_from_velocities(velocities, masses, dt_fs, indices=np.array([0]))
        >>> round(float(partial[0]), 6)
        0.5

        ```
    """
    selections = None if indices is None else {"indices": indices}
    lag_ps, columns = _vacf_columns(
        velocities, masses, dt_fs, selections, max_lag_frames, normalization, remove_com=remove_com
    )
    return lag_ps, np.ascontiguousarray(columns[:, 0])

compute_vdos_from_velocities(velocities: NDArray, masses: NDArray, dt_fs: float, *, indices: NDArray | None = None, normalization: VdosNormalization = 'unit', remove_com: bool = True, window: VdosWindow = None) -> tuple[NDArray[np.float64], NDArray[np.float64]]

Compute the vibrational density of states from an MD velocity trajectory.

The VDOS is the mass-weighted velocity power spectrum

\[g(\nu_k) \propto \sum_{i} m_i \sum_{\alpha} |V_{i\alpha}(\nu_k)|^2, \quad V_{i\alpha}(\nu_k) = \sum_{t=0}^{N-1} v_{i\alpha}(t)\, e^{-2\pi \mathrm{i} k t / N},\]

the unnormalised forward DFT along time (the np.fft.rfft convention; computed with scipy.fft.rfft), on the one-sided grid \(\nu_k = k / (N \Delta t)\), \(k = 0, \dots, \lfloor N/2 \rfloor\), in THz. The frequency resolution is \(1 / (N \Delta t)\) and the highest frequency is the Nyquist frequency \(1 / (2 \Delta t)\). No zero padding or per-atom mean subtraction is applied, and no window unless window is set.

With a window, the (centre-of-mass-free) velocities are multiplied by \(w_t\), \(t = 0, \dots, N-1\), before the transform. All windows are periodic (scipy.signal.get_window(window, N)):

  • "hann": \(w_t = \tfrac{1}{2}\left(1 - \cos(2\pi t / N)\right)\).
  • "hamming": \(w_t = 0.54 - 0.46 \cos(2\pi t / N)\). Lower first sidelobe than Hann, but the edges are not zero (0.08), so leakage far from a peak decays more slowly.
  • "blackmanharris": the 4-term Blackman-Harris window \(w_t = \sum_{j=0}^{3} (-1)^j a_j \cos(2\pi j t / N)\), \(a = (0.35875, 0.48829, 0.14128, 0.01168)\), with sidelobes below \(-92\) dB.
  • ("gaussian", std): \(w_t = \exp\left(-\tfrac{1}{2}\left((t - N/2) / \sigma\right)^2\right)\) with \(\sigma\) = std in frames, so its width relative to the block depends on \(N\). It is truncated at the edges (edge value \(e^{-8} \approx 3 \times 10^{-4}\) for \(\sigma = N/8\)). A narrow window (\(\sigma \ll N/8\)) widens every peak and can spread power further than no window at all.

A window suppresses spectral leakage from the finite trajectory length at the cost of resolution. The effective resolution is \(\mathrm{ENBW} / (N \Delta t)\) with the equivalent noise bandwidth \(\mathrm{ENBW} = N \sum_t w_t^2 / (\sum_t w_t)^2\) bins: 1.5 (Hann), 1.36 (Hamming), 2.0 (Blackman-Harris) and about \(N / (2 \sqrt{\pi} \sigma)\) (Gaussian, \(\sigma \ll N\)). For 10 ps blocks that is 0.15, 0.14 and 0.20 THz, and 0.23 THz for a Gaussian with \(\sigma = N/8\). With window=None (default) the full \(1 / (N \Delta t)\) resolution is kept, and a peak between grid points leaks into distant bins.

With remove_com=True (default), the instantaneous mass-weighted centre-of-mass velocity of the whole system, \(\mathbf{v}_\mathrm{COM}(t) = \sum_i m_i \mathbf{v}_i(t) / \sum_i m_i\), is subtracted from every atom in every frame before the transform, also when indices selects a subset. With remove_com=False the velocities are transformed as given, and any centre-of-mass drift appears at and near zero frequency.

Normalisation (all integrals are trapezoidal over the returned grid):

  • "unit" (default): the total VDOS integrates to 1 (units 1/THz).
  • "3N": the total VDOS integrates to 3 * n_atoms (the number of degrees of freedom, including the 3 removed with the centre of mass).
  • "none": the power spectral density \(S(\nu_k) = (2 \Delta t / N) \sum_i m_i \sum_\alpha |V_{i\alpha}|^2\) in amu (velocity unit)\(^2\) ps. For an even number of frames its integral equals the time average of \(\sum_i m_i |\mathbf{v}_i|^2\) (twice the mean kinetic energy) exactly, by Parseval's theorem; for an odd number it is lower by half the last bin. With a window, \(V_{i\alpha}\) is the transform of the windowed velocities and the prefactor is \(2 \Delta t / \sum_t w_t^2\) instead of \(2 \Delta t / N\); the integral is then the \(w^2\)-weighted time average \(\sum_t w_t^2 \sum_i m_i |\mathbf{v}_i(t)|^2 / \sum_t w_t^2\) (exact for an even number of frames).

With a window, "unit" and "3N" are applied to the windowed total VDOS, which still integrates to exactly 1 and 3 * n_atoms.

A partial VDOS (indices given) is the same spectrum summed over the selected atoms only and is scaled by the total VDOS's normalisation, so partials over disjoint selections add up to the total. Its integral is the selection's share of the total kinetic energy, which is close to its share of atoms by equipartition: about 3 * len(indices) for "3N". The integral of the total spectrum comes from Parseval's theorem in the time domain, so a partial only transforms the selected atoms. Use :func:compute_partial_vdos for many groups.

Memory: the trajectory is read twice in chunks of atoms (about 64 MB each), once for the centre-of-mass velocity, the normalisation and the finiteness check, and once for the transforms. Besides the input, peak memory is about two chunks. float32 input is transformed in single precision (no float64 copy); the spectrum is accumulated in float64. The input is never modified, and it may be a read-only np.memmap (e.g. np.load(path, mmap_mode="r")), in which case only the chunks being processed are read from disk.

Parameters:

Name Type Description Default
velocities NDArray

Velocities of shape (n_frames, n_atoms, 3) in any unit; "unit" and "3N" remove the scale.

required
masses NDArray

Atomic masses of shape (n_atoms,) in amu.

required
dt_fs float

Time between consecutive frames in fs (the dump interval, not the MD timestep).

required
indices NDArray | None

0-based positions of the atoms in a partial VDOS, e.g. one entry of :func:classify_vibrational_groups. None (default) gives the total VDOS.

None
normalization VdosNormalization

"unit", "3N" or "none", see above.

'unit'
remove_com bool

Subtract the centre-of-mass velocity of the whole system from every frame.

True
window VdosWindow

"hann", "hamming", "blackmanharris", ("gaussian", std) with std > 0 in frames, or None (default) for no window, see above.

None

Returns:

Type Description
NDArray[float64]

A tuple (frequencies_thz, vdos) of float64 arrays of length n_frames // 2 + 1: the frequencies in THz

NDArray[float64]

from np.fft.rfftfreq(n_frames, d=dt_fs * 1e-3) and the VDOS in 1/THz ("unit", "3N") or the power

tuple[NDArray[float64], NDArray[float64]]

spectral density ("none").

Raises:

Type Description
ValueError

If velocities is not (n_frames, n_atoms, 3) with at least one atom, masses does not have shape (n_atoms,), there are fewer than 2 frames, dt_fs is not a positive finite number, any mass is not positive and finite, velocities is not real numeric or contains NaN or inf, normalization or window is unknown, indices is empty, not 1-D integer, out of range or has duplicates, or the spectrum vanishes (all velocities zero, no motion left after centre-of-mass removal, e.g. every atom moves with the same velocity, or, with "unit" or "3N", no motion left after the window).

Example
>>> from amorphouspy import get_atomic_mass
>>> dt_fs, n_frames = 5.0, 2000
>>> t_ps = np.arange(n_frames) * dt_fs * 1e-3
>>> velocities = np.zeros((n_frames, 2, 3))
>>> velocities[:, 0, 0] = np.cos(2 * np.pi * 10.0 * t_ps)
>>> velocities[:, 1, 0] = -velocities[:, 0, 0]
>>> masses = np.full(2, get_atomic_mass("Si"))
>>> frequencies_thz, vdos = compute_vdos_from_velocities(velocities, masses, dt_fs)
>>> float(frequencies_thz[np.argmax(vdos)])
10.0
>>> round(float(np.trapezoid(vdos, frequencies_thz)), 6)
1.0
>>> _, partial = compute_vdos_from_velocities(
...     velocities, masses, dt_fs, indices=np.array([0]), normalization="3N"
... )
>>> round(float(np.trapezoid(partial, frequencies_thz)), 6)
3.0
>>> _, vdos_hann = compute_vdos_from_velocities(velocities, masses, dt_fs, window="hann")
>>> float(frequencies_thz[np.argmax(vdos_hann)]), round(float(np.trapezoid(vdos_hann, frequencies_thz)), 6)
(10.0, 1.0)
Source code in amorphouspy/src/amorphouspy/properties/vibrational/vdos.py
def compute_vdos_from_velocities(
    velocities: NDArray,
    masses: NDArray,
    dt_fs: float,
    *,
    indices: NDArray | None = None,
    normalization: VdosNormalization = "unit",
    remove_com: bool = True,
    window: VdosWindow = None,
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
    r"""Compute the vibrational density of states from an MD velocity trajectory.

    The VDOS is the mass-weighted velocity power spectrum

    $$g(\nu_k) \propto \sum_{i} m_i \sum_{\alpha} |V_{i\alpha}(\nu_k)|^2,
    \quad V_{i\alpha}(\nu_k) = \sum_{t=0}^{N-1} v_{i\alpha}(t)\, e^{-2\pi \mathrm{i} k t / N},$$

    the unnormalised forward DFT along time (the ``np.fft.rfft`` convention; computed with ``scipy.fft.rfft``), on the
    one-sided grid
    $\nu_k = k / (N \Delta t)$, $k = 0, \dots, \lfloor N/2 \rfloor$, in THz. The frequency resolution is
    $1 / (N \Delta t)$ and the highest frequency is the Nyquist frequency $1 / (2 \Delta t)$. No zero padding or
    per-atom mean subtraction is applied, and no window unless ``window`` is set.

    With a window, the (centre-of-mass-free) velocities are multiplied by $w_t$, $t = 0, \dots, N-1$, before the
    transform. All windows are periodic (``scipy.signal.get_window(window, N)``):

    - ``"hann"``: $w_t = \tfrac{1}{2}\left(1 - \cos(2\pi t / N)\right)$.
    - ``"hamming"``: $w_t = 0.54 - 0.46 \cos(2\pi t / N)$. Lower first sidelobe than Hann, but the edges are not
      zero (0.08), so leakage far from a peak decays more slowly.
    - ``"blackmanharris"``: the 4-term Blackman-Harris window $w_t = \sum_{j=0}^{3} (-1)^j a_j \cos(2\pi j t / N)$,
      $a = (0.35875, 0.48829, 0.14128, 0.01168)$, with sidelobes below $-92$ dB.
    - ``("gaussian", std)``: $w_t = \exp\left(-\tfrac{1}{2}\left((t - N/2) / \sigma\right)^2\right)$ with
      $\sigma$ = ``std`` in frames, so its width relative to the block depends on $N$. It is truncated at the edges
      (edge value $e^{-8} \approx 3 \times 10^{-4}$ for $\sigma = N/8$). A narrow window ($\sigma \ll N/8$) widens
      every peak and can spread power further than no window at all.

    A window suppresses spectral leakage from the finite trajectory length at the cost of resolution. The effective
    resolution is $\mathrm{ENBW} / (N \Delta t)$ with the equivalent noise bandwidth
    $\mathrm{ENBW} = N \sum_t w_t^2 / (\sum_t w_t)^2$ bins: 1.5 (Hann), 1.36 (Hamming), 2.0 (Blackman-Harris) and
    about $N / (2 \sqrt{\pi} \sigma)$ (Gaussian, $\sigma \ll N$). For 10 ps blocks that is 0.15, 0.14 and 0.20 THz,
    and 0.23 THz for a Gaussian with $\sigma = N/8$. With ``window=None`` (default) the full $1 / (N \Delta t)$
    resolution is kept, and a peak between grid points leaks into distant bins.

    With ``remove_com=True`` (default), the instantaneous mass-weighted centre-of-mass velocity of the whole system,
    $\mathbf{v}_\mathrm{COM}(t) = \sum_i m_i \mathbf{v}_i(t) / \sum_i m_i$, is subtracted from every atom in every
    frame before the transform, also when ``indices`` selects a subset. With ``remove_com=False`` the velocities are
    transformed as given, and any centre-of-mass drift appears at and near zero frequency.

    Normalisation (all integrals are trapezoidal over the returned grid):

    - ``"unit"`` (default): the total VDOS integrates to 1 (units 1/THz).
    - ``"3N"``: the total VDOS integrates to ``3 * n_atoms`` (the number of degrees of freedom, including the 3
      removed with the centre of mass).
    - ``"none"``: the power spectral density $S(\nu_k) = (2 \Delta t / N) \sum_i m_i \sum_\alpha |V_{i\alpha}|^2$ in
      amu (velocity unit)$^2$ ps. For an even number of frames its integral equals the time average of
      $\sum_i m_i |\mathbf{v}_i|^2$ (twice the mean kinetic energy) exactly, by Parseval's theorem; for an odd number
      it is lower by half the last bin. With a window, $V_{i\alpha}$ is the transform of the windowed velocities and
      the prefactor is $2 \Delta t / \sum_t w_t^2$ instead of $2 \Delta t / N$; the integral is then the
      $w^2$-weighted time average $\sum_t w_t^2 \sum_i m_i |\mathbf{v}_i(t)|^2 / \sum_t w_t^2$ (exact for an even
      number of frames).

    With a window, ``"unit"`` and ``"3N"`` are applied to the windowed total VDOS, which still integrates to exactly 1
    and ``3 * n_atoms``.

    A partial VDOS (``indices`` given) is the same spectrum summed over the selected atoms only and is scaled by the
    total VDOS's normalisation, so partials over disjoint selections add up to the total. Its integral is the
    selection's share of the total kinetic energy, which is close to its share of atoms by equipartition: about
    ``3 * len(indices)`` for ``"3N"``. The integral of the total spectrum comes from Parseval's theorem in the time
    domain, so a partial only transforms the selected atoms. Use :func:`compute_partial_vdos` for many groups.

    Memory: the trajectory is read twice in chunks of atoms (about 64 MB each), once for the centre-of-mass velocity,
    the normalisation and the finiteness check, and once for the transforms. Besides the input, peak memory is about
    two chunks. float32 input is transformed in single precision (no float64 copy); the spectrum is accumulated in
    float64. The input is never modified, and it may be a read-only ``np.memmap`` (e.g. ``np.load(path,
    mmap_mode="r")``), in which case only the chunks being processed are read from disk.

    Args:
        velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit; ``"unit"`` and ``"3N"`` remove the
            scale.
        masses: Atomic masses of shape ``(n_atoms,)`` in amu.
        dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep).
        indices: 0-based positions of the atoms in a partial VDOS, e.g. one entry of
            :func:`classify_vibrational_groups`. ``None`` (default) gives the total VDOS.
        normalization: ``"unit"``, ``"3N"`` or ``"none"``, see above.
        remove_com: Subtract the centre-of-mass velocity of the whole system from every frame.
        window: ``"hann"``, ``"hamming"``, ``"blackmanharris"``, ``("gaussian", std)`` with ``std > 0`` in frames,
            or ``None`` (default) for no window, see above.

    Returns:
        A tuple ``(frequencies_thz, vdos)`` of float64 arrays of length ``n_frames // 2 + 1``: the frequencies in THz
        from ``np.fft.rfftfreq(n_frames, d=dt_fs * 1e-3)`` and the VDOS in 1/THz (``"unit"``, ``"3N"``) or the power
        spectral density (``"none"``).

    Raises:
        ValueError: If ``velocities`` is not ``(n_frames, n_atoms, 3)`` with at least one atom, ``masses`` does not
            have shape ``(n_atoms,)``, there are fewer than 2 frames, ``dt_fs`` is not a positive finite number, any
            mass is not positive and finite, ``velocities`` is not real numeric or contains NaN or inf,
            ``normalization`` or ``window`` is unknown, ``indices`` is empty, not 1-D integer, out of range or has
            duplicates, or the spectrum vanishes (all velocities zero, no motion left after centre-of-mass removal,
            e.g. every atom moves with the same velocity, or, with ``"unit"`` or ``"3N"``, no motion left after the
            window).

    Example:
        ```pycon
        >>> from amorphouspy import get_atomic_mass
        >>> dt_fs, n_frames = 5.0, 2000
        >>> t_ps = np.arange(n_frames) * dt_fs * 1e-3
        >>> velocities = np.zeros((n_frames, 2, 3))
        >>> velocities[:, 0, 0] = np.cos(2 * np.pi * 10.0 * t_ps)
        >>> velocities[:, 1, 0] = -velocities[:, 0, 0]
        >>> masses = np.full(2, get_atomic_mass("Si"))
        >>> frequencies_thz, vdos = compute_vdos_from_velocities(velocities, masses, dt_fs)
        >>> float(frequencies_thz[np.argmax(vdos)])
        10.0
        >>> round(float(np.trapezoid(vdos, frequencies_thz)), 6)
        1.0
        >>> _, partial = compute_vdos_from_velocities(
        ...     velocities, masses, dt_fs, indices=np.array([0]), normalization="3N"
        ... )
        >>> round(float(np.trapezoid(partial, frequencies_thz)), 6)
        3.0
        >>> _, vdos_hann = compute_vdos_from_velocities(velocities, masses, dt_fs, window="hann")
        >>> float(frequencies_thz[np.argmax(vdos_hann)]), round(float(np.trapezoid(vdos_hann, frequencies_thz)), 6)
        (10.0, 1.0)

        ```
    """
    selections = None if indices is None else {"indices": indices}
    frequencies_thz, columns = _vdos_columns(
        velocities, masses, dt_fs, selections, normalization, remove_com=remove_com, window=window
    )
    return frequencies_thz, np.ascontiguousarray(columns[:, 0])

compute_vibrational_thermodynamics(frequencies_thz: NDArray, vdos: NDArray, temperatures_k: ArrayLike, *, lowest_frequency_thz: float | None = None) -> dict[str, Any]

Compute the harmonic heat capacity, entropy and energies from a VDOS, with a lower temperature bound.

Each mode of frequency \(\nu\) is a quantum harmonic oscillator. With \(x = h \nu / (k_B T)\) it contributes

\[C_V = k_B \frac{x^2 e^x}{(e^x - 1)^2}, \quad S = k_B \left[\frac{x}{e^x - 1} - \ln\left(1 - e^{-x}\right)\right],\]
\[U = \frac{h \nu}{2} + \frac{h \nu}{e^x - 1}, \quad F = \frac{h \nu}{2} + k_B T \ln\left(1 - e^{-x}\right), \quad E_\mathrm{ZP} = \frac{h \nu}{2},\]

and a quantity per atom is \(Q(T) = 3 \int g(\nu)\, q(\nu, T)\, d\nu\) (three modes per atom), integrated with the trapezoid rule on the given grid, as the VDOS functions of this module normalise. The VDOS must therefore be normalised to 1 (normalization="unit" in :func:compute_vdos_from_velocities); this is not enforced, and "vdos_integral" lets the caller check it. A partial VDOS from :func:compute_partial_vdos with "unit" gives that group's additive contribution per atom of the whole system, so the partials sum to the total. At \(T = 0\) the exact limits are returned: \(C_V = S = 0\) and \(U = F = E_\mathrm{ZP}\). Large \(x\) is evaluated in forms that cannot overflow (with np.expm1 and np.log1p(-np.exp(-x))).

\(S\) and \(F\) diverge as \(\nu \to 0\), so only \(\nu > 0\) is integrated: the integrand is set to zero at every grid point with \(\nu \le 0\) (the zero-frequency bin of the VACF route, and imaginary harmonic modes stored as negative frequencies) and the trapezoid rule runs over the full grid. Nothing is dropped silently: "vdos_integral" is the integral of \(g\) over the full grid, and "excluded_weight" is that integral minus the integral of \(g\) with the points at \(\nu \le 0\) set to zero, i.e. the share of modes left out. At high \(T\), \(C_V\) tends to \(3 \, (\mathrm{vdos\_integral} - \mathrm{excluded\_weight})\) k\(_B\) per atom.

At low temperature the values depend on the low-frequency VDOS, which a finite box or a short trajectory does not resolve. Below \(T_\mathrm{min} = h \nu_\mathrm{low} / k_B\) (1 THz corresponds to 48 K) the values are flagged as unreliable, not removed. Usual choices of \(\nu_\mathrm{low}\) (lowest_frequency_thz) are debye["lowest_box_frequency_thz"] from :func:compute_debye_level (the lowest acoustic mode of the box), the frequency resolution \(1 / (N \Delta t)\) of the VACF route, or the lowest non-zero mode of the harmonic route. With None the first positive grid frequency is used, which is only the resolution of the grid, not the box limit, so the bound is then too optimistic for a small box. \(T = 0\) is always flagged.

Parameters:

Name Type Description Default
frequencies_thz NDArray

Frequencies in THz, 1-D and strictly increasing. Zero and negative values are allowed and excluded from the integrals.

required
vdos NDArray

VDOS on frequencies_thz, 1-D of the same length, non-negative, in 1/THz and normalised to 1.

required
temperatures_k ArrayLike

Temperatures in K, a scalar, a list or a 1-D array of finite values \(\ge 0\).

required
lowest_frequency_thz float | None

\(\nu_\mathrm{low}\) in THz for the temperature bound, positive and finite, or None (default) for the first positive grid frequency.

None

Returns:

Type Description
dict[str, Any]

A dict with: "temperatures_k": the temperatures as a float64 array (length 1 for a scalar). "heat_capacity_kb_per_atom": \(C_V\) in k\(_B\) per atom, an array of the same length. "entropy_kb_per_atom": \(S\) in k\(_B\) per atom. "internal_energy_mev_per_atom": \(U\) in meV per atom, including the zero-point energy. "free_energy_mev_per_atom": \(F\) in meV per atom, including the zero-point energy. "zero_point_energy_mev_per_atom": \(E_\mathrm{ZP}\) in meV per atom, a float. "temperature_bound_k": \(T_\mathrm{min}\) in K, a float. "reliable": boolean array, True where \(T \ge T_\mathrm{min}\). "lowest_frequency_thz": \(\nu_\mathrm{low}\) in THz. "lowest_frequency_source": "caller" or "grid". "vdos_integral": trapezoid integral of vdos over the full grid. "excluded_weight": the part of "vdos_integral" at \(\nu \le 0\) that is left out.

Raises:

Type Description
ValueError

If frequencies_thz and vdos are not 1-D arrays of the same length with at least 2 points, contain NaN or inf, vdos is negative anywhere, the frequencies are not strictly increasing or none is above 0, a temperature is negative or not finite, or lowest_frequency_thz is not positive and finite.

Example
>>> frequencies_thz = np.linspace(0.0, 10.0, 1001)
>>> vdos = 3 * frequencies_thz**2 / 10.0**3  # Debye VDOS with nu_D = 10 THz (theta_D = 480 K)
>>> thermo = compute_vibrational_thermodynamics(
...     frequencies_thz, vdos, [0.0, 300.0, 3000.0], lowest_frequency_thz=1.0
... )
>>> thermo["heat_capacity_kb_per_atom"].round(3)
array([0.   , 2.649, 2.996])
>>> round(thermo["temperature_bound_k"], 1), thermo["reliable"].tolist()
(48.0, [False, True, True])
>>> round(thermo["zero_point_energy_mev_per_atom"], 2)  # 9/8 h nu_D
46.53
Source code in amorphouspy/src/amorphouspy/properties/vibrational/thermodynamics.py
def compute_vibrational_thermodynamics(
    frequencies_thz: NDArray,
    vdos: NDArray,
    temperatures_k: ArrayLike,
    *,
    lowest_frequency_thz: float | None = None,
) -> dict[str, Any]:
    r"""Compute the harmonic heat capacity, entropy and energies from a VDOS, with a lower temperature bound.

    Each mode of frequency $\nu$ is a quantum harmonic oscillator. With $x = h \nu / (k_B T)$ it contributes

    $$C_V = k_B \frac{x^2 e^x}{(e^x - 1)^2}, \quad
    S = k_B \left[\frac{x}{e^x - 1} - \ln\left(1 - e^{-x}\right)\right],$$

    $$U = \frac{h \nu}{2} + \frac{h \nu}{e^x - 1}, \quad F = \frac{h \nu}{2} + k_B T \ln\left(1 - e^{-x}\right),
    \quad E_\mathrm{ZP} = \frac{h \nu}{2},$$

    and a quantity per atom is $Q(T) = 3 \int g(\nu)\, q(\nu, T)\, d\nu$ (three modes per atom), integrated with the
    trapezoid rule on the given grid, as the VDOS functions of this module normalise. The VDOS must therefore be
    normalised to 1 (``normalization="unit"`` in :func:`compute_vdos_from_velocities`); this is not enforced, and
    ``"vdos_integral"`` lets the caller check it. A partial VDOS from :func:`compute_partial_vdos` with ``"unit"`` gives
    that group's additive contribution per atom of the whole system, so the partials sum to the total. At $T = 0$ the
    exact limits are returned: $C_V = S = 0$ and $U = F = E_\mathrm{ZP}$. Large $x$ is evaluated in forms that cannot
    overflow (with ``np.expm1`` and ``np.log1p(-np.exp(-x))``).

    $S$ and $F$ diverge as $\nu \to 0$, so only $\nu > 0$ is integrated: the integrand is set to zero at every grid
    point with $\nu \le 0$ (the zero-frequency bin of the VACF route, and imaginary harmonic modes stored as negative
    frequencies) and the trapezoid rule runs over the full grid. Nothing is dropped silently: ``"vdos_integral"`` is the
    integral of $g$ over the full grid, and ``"excluded_weight"`` is that integral minus the integral of $g$ with the
    points at $\nu \le 0$ set to zero, i.e. the share of modes left out. At high $T$, $C_V$ tends to
    $3 \, (\mathrm{vdos\_integral} - \mathrm{excluded\_weight})$ k$_B$ per atom.

    At low temperature the values depend on the low-frequency VDOS, which a finite box or a short trajectory does not
    resolve. Below $T_\mathrm{min} = h \nu_\mathrm{low} / k_B$ (1 THz corresponds to 48 K) the values are flagged as
    unreliable, not removed. Usual choices of $\nu_\mathrm{low}$ (``lowest_frequency_thz``) are
    ``debye["lowest_box_frequency_thz"]`` from :func:`compute_debye_level` (the lowest acoustic mode of the box), the
    frequency resolution $1 / (N \Delta t)$ of the VACF route, or the lowest non-zero mode of the harmonic route. With
    ``None`` the first positive grid frequency is used, which is only the resolution of the grid, not the box limit, so
    the bound is then too optimistic for a small box. $T = 0$ is always flagged.

    Args:
        frequencies_thz: Frequencies in THz, 1-D and strictly increasing. Zero and negative values are allowed and
            excluded from the integrals.
        vdos: VDOS on ``frequencies_thz``, 1-D of the same length, non-negative, in 1/THz and normalised to 1.
        temperatures_k: Temperatures in K, a scalar, a list or a 1-D array of finite values $\ge 0$.
        lowest_frequency_thz: $\nu_\mathrm{low}$ in THz for the temperature bound, positive and finite, or ``None``
            (default) for the first positive grid frequency.

    Returns:
        A dict with:
            ``"temperatures_k"``: the temperatures as a float64 array (length 1 for a scalar).
            ``"heat_capacity_kb_per_atom"``: $C_V$ in k$_B$ per atom, an array of the same length.
            ``"entropy_kb_per_atom"``: $S$ in k$_B$ per atom.
            ``"internal_energy_mev_per_atom"``: $U$ in meV per atom, including the zero-point energy.
            ``"free_energy_mev_per_atom"``: $F$ in meV per atom, including the zero-point energy.
            ``"zero_point_energy_mev_per_atom"``: $E_\mathrm{ZP}$ in meV per atom, a float.
            ``"temperature_bound_k"``: $T_\mathrm{min}$ in K, a float.
            ``"reliable"``: boolean array, True where $T \ge T_\mathrm{min}$.
            ``"lowest_frequency_thz"``: $\nu_\mathrm{low}$ in THz.
            ``"lowest_frequency_source"``: ``"caller"`` or ``"grid"``.
            ``"vdos_integral"``: trapezoid integral of ``vdos`` over the full grid.
            ``"excluded_weight"``: the part of ``"vdos_integral"`` at $\nu \le 0$ that is left out.

    Raises:
        ValueError: If ``frequencies_thz`` and ``vdos`` are not 1-D arrays of the same length with at least 2 points,
            contain NaN or inf, ``vdos`` is negative anywhere, the frequencies are not strictly increasing or none is
            above 0, a temperature is negative or not finite, or ``lowest_frequency_thz`` is not positive and finite.

    Example:
        ```pycon
        >>> frequencies_thz = np.linspace(0.0, 10.0, 1001)
        >>> vdos = 3 * frequencies_thz**2 / 10.0**3  # Debye VDOS with nu_D = 10 THz (theta_D = 480 K)
        >>> thermo = compute_vibrational_thermodynamics(
        ...     frequencies_thz, vdos, [0.0, 300.0, 3000.0], lowest_frequency_thz=1.0
        ... )
        >>> thermo["heat_capacity_kb_per_atom"].round(3)
        array([0.   , 2.649, 2.996])
        >>> round(thermo["temperature_bound_k"], 1), thermo["reliable"].tolist()
        (48.0, [False, True, True])
        >>> round(thermo["zero_point_energy_mev_per_atom"], 2)  # 9/8 h nu_D
        46.53

        ```
    """
    frequencies_thz, vdos, temperatures_k = _validate_thermodynamics_inputs(frequencies_thz, vdos, temperatures_k)
    positive = frequencies_thz > 0
    if lowest_frequency_thz is None:
        lowest_thz = float(frequencies_thz[positive][0])
        source = "grid"
    else:
        is_number = _is_real_number(lowest_frequency_thz)
        if not (is_number and np.isfinite(lowest_frequency_thz) and lowest_frequency_thz > 0):
            msg = f"lowest_frequency_thz must be positive and finite, got {lowest_frequency_thz}."
            raise ValueError(msg)
        lowest_thz = float(lowest_frequency_thz)
        source = "caller"

    # Trapezoid weights of the full grid, so that sum(weights * f) is np.trapezoid(f, frequencies_thz). Keeping only the
    # points with nu > 0 integrates the integrand set to zero at nu <= 0. Three modes per atom.
    spacing = np.diff(frequencies_thz)
    weights = np.zeros_like(frequencies_thz)
    weights[:-1] += spacing / 2
    weights[1:] += spacing / 2
    mode_weights = 3 * (weights * vdos)[positive]
    mode_k = frequencies_thz[positive] * _THZ_TO_K
    mode_mev = frequencies_thz[positive] * _THZ_TO_UNIT["meV"]
    vdos_integral = float(np.trapezoid(vdos, frequencies_thz))
    positive_integral = float(np.trapezoid(np.where(positive, vdos, 0.0), frequencies_thz))

    zero_point = float(mode_weights @ mode_mev) / 2
    heat_capacity = np.zeros_like(temperatures_k)
    entropy = np.zeros_like(temperatures_k)
    internal_energy = np.full_like(temperatures_k, zero_point)
    free_energy = np.full_like(temperatures_k, zero_point)
    for i in np.flatnonzero(temperatures_k > 0):
        # Capped where exp(-x / 2) is already exactly 0, so an overflow of x at a subnormal T cannot give inf * 0.
        with np.errstate(over="ignore"):
            x = np.minimum(mode_k / temperatures_k[i], _MAX_REDUCED_FREQUENCY)
        exp_neg = np.exp(-x)
        one_minus_exp_neg = -np.expm1(-x)
        occupation = exp_neg / one_minus_exp_neg  # 1 / (e^x - 1) without overflow
        log_term = np.log1p(-exp_neg)  # ln(1 - e^-x)
        # x^2 e^x / (e^x - 1)^2 written so that neither e^x nor x^2 is formed.
        heat_capacity[i] = mode_weights @ (x * np.exp(-x / 2) / one_minus_exp_neg) ** 2
        entropy[i] = mode_weights @ (x * occupation - log_term)
        internal_energy[i] += mode_weights @ (mode_mev * occupation)
        free_energy[i] += _K_TO_MEV * temperatures_k[i] * (mode_weights @ log_term)

    temperature_bound_k = lowest_thz * _THZ_TO_K
    return {
        "temperatures_k": temperatures_k,
        "heat_capacity_kb_per_atom": heat_capacity,
        "entropy_kb_per_atom": entropy,
        "internal_energy_mev_per_atom": internal_energy,
        "free_energy_mev_per_atom": free_energy,
        "zero_point_energy_mev_per_atom": zero_point,
        "temperature_bound_k": temperature_bound_k,
        "reliable": temperatures_k >= temperature_bound_k,
        "lowest_frequency_thz": lowest_thz,
        "lowest_frequency_source": source,
        "vdos_integral": vdos_integral,
        "excluded_weight": vdos_integral - positive_integral,
    }

convert_frequency(values: float | NDArray, from_unit: FrequencyUnit, to_unit: FrequencyUnit) -> float | NDArray[np.float64]

Convert frequencies between THz, cm^-1, meV and rad/ps.

The conversion goes through THz. Negative values (the convention for imaginary harmonic modes) keep their sign.

Parameters:

Name Type Description Default
values float | NDArray

Frequency or array of frequencies in from_unit.

required
from_unit FrequencyUnit

Unit of values: "THz", "cm-1", "meV" or "rad/ps".

required
to_unit FrequencyUnit

Target unit, one of the same four.

required

Returns:

Type Description
float | NDArray[float64]

A float for scalar input, otherwise a new float64 array of the same shape as values. The input is never

float | NDArray[float64]

modified; from_unit == to_unit returns a copy.

Raises:

Type Description
ValueError

If from_unit or to_unit is not one of the allowed units.

Example

round(convert_frequency(1.0, "THz", "cm-1"), 5) 33.35641 convert_frequency(np.array([-1.0, 2.0]), "THz", "rad/ps").round(4) array([-6.2832, 12.5664])

Source code in amorphouspy/src/amorphouspy/properties/vibrational/units.py
def convert_frequency(
    values: float | NDArray, from_unit: FrequencyUnit, to_unit: FrequencyUnit
) -> float | NDArray[np.float64]:
    """Convert frequencies between THz, cm^-1, meV and rad/ps.

    The conversion goes through THz. Negative values (the convention for imaginary harmonic modes) keep their sign.

    Args:
        values: Frequency or array of frequencies in ``from_unit``.
        from_unit: Unit of ``values``: ``"THz"``, ``"cm-1"``, ``"meV"`` or ``"rad/ps"``.
        to_unit: Target unit, one of the same four.

    Returns:
        A float for scalar input, otherwise a new float64 array of the same shape as ``values``. The input is never
        modified; ``from_unit == to_unit`` returns a copy.

    Raises:
        ValueError: If ``from_unit`` or ``to_unit`` is not one of the allowed units.

    Example:
        >>> round(convert_frequency(1.0, "THz", "cm-1"), 5)
        33.35641
        >>> convert_frequency(np.array([-1.0, 2.0]), "THz", "rad/ps").round(4)
        array([-6.2832, 12.5664])
    """
    for unit in (from_unit, to_unit):
        if unit not in _THZ_TO_UNIT:
            msg = f"Unknown frequency unit {unit!r}; allowed units are {list(_THZ_TO_UNIT)}."
            raise ValueError(msg)
    converted = np.asarray(values, dtype=np.float64) * (_THZ_TO_UNIT[to_unit] / _THZ_TO_UNIT[from_unit])
    if converted.ndim == 0:
        return float(converted)
    return converted

count_distribution(coord_numbers: dict[int, int]) -> dict[int, int]

Convert coordination numbers to a histogram distribution.

Parameters:

Name Type Description Default
coord_numbers dict[int, int]

Mapping from atom ID to coordination number.

required

Returns:

Type Description
dict[int, int]

Coordination number frequency histogram.

Example

dist = count_distribution({1: 4, 2: 4, 3: 3})

Source code in amorphouspy/src/amorphouspy/atoms/shared.py
def count_distribution(coord_numbers: dict[int, int]) -> dict[int, int]:
    """Convert coordination numbers to a histogram distribution.

    Args:
        coord_numbers: Mapping from atom ID to coordination number.

    Returns:
        Coordination number frequency histogram.

    Example:
        >>> dist = count_distribution({1: 4, 2: 4, 3: 3})

    """
    dist = {}
    for cn in coord_numbers.values():
        dist[cn] = dist.get(cn, 0) + 1
    return dist

create_random_atoms(composition: dict[str, float], n_molecules: int | None = None, target_atoms: int | None = None, mode: str = 'molar', stoichiometry: dict[str, dict[str, int]] | None = None, box_length: float = 50.0, min_distance: float = 1.6, seed: int = 42, max_attempts_per_atom: int = 100000) -> tuple[list[dict[str, str | list[float]]], dict[str, int]]

Generate random atom positions for a glass system in a periodic cubic box.

Supports specifying system size either by total number of molecules (n_molecules) or total number of atoms (target_atoms).

Parameters:

Name Type Description Default
composition dict[str, float]

A dictionary mapping oxide formulas to their fractions, e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}.

required
n_molecules int | None

The desired total number of molecules. Mutually exclusive with target_atoms.

None
target_atoms int | None

The desired target number of atoms. Mutually exclusive with n_molecules.

None
mode str

The composition interpretation mode ("molar" or "weight"). Defaults to "molar".

'molar'
stoichiometry dict[str, dict[str, int]] | None

Optional pre-calculated stoichiometry dictionary.

None
box_length float

The length of the cubic simulation box in Angstroms. Defaults to 50.0.

50.0
min_distance float

The minimum allowed distance between any two atoms in Angstroms. Defaults to 1.6.

1.6
seed int

Random seed for reproducibility. Defaults to 42.

42
max_attempts_per_atom int

Maximum attempts to place a single atom before failing. Defaults to 100000.

100000

Returns:

Type Description
tuple[list[dict[str, str | list[float]]], dict[str, int]]

A tuple containing: - A list of atom dictionaries, each with "element" and "position". - A dictionary of total counts per element.

Raises:

Type Description
ValueError

If composition sum is invalid or target mode is ambiguous.

RuntimeError

If atom placement fails due to overcrowding (max attempts reached).

Example

atoms_list, atom_counts = create_random_atoms( ... composition={"SiO2": 0.8, "Na2O": 0.2}, ... target_atoms=500, ... box_length=20.0 ... )

Source code in amorphouspy/src/amorphouspy/fabrication/geometry.py
def create_random_atoms(
    composition: dict[str, float],
    n_molecules: int | None = None,
    target_atoms: int | None = None,
    mode: str = "molar",
    stoichiometry: dict[str, dict[str, int]] | None = None,
    box_length: float = 50.0,
    min_distance: float = 1.6,
    seed: int = 42,
    max_attempts_per_atom: int = 100000,
) -> tuple[list[dict[str, str | list[float]]], dict[str, int]]:
    """Generate random atom positions for a glass system in a periodic cubic box.

    Supports specifying system size either by total number of molecules (`n_molecules`)
    or total number of atoms (`target_atoms`).

    Args:
        composition: A dictionary mapping oxide formulas to their fractions,
            e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}.
        n_molecules: The desired total number of molecules. Mutually exclusive with `target_atoms`.
        target_atoms: The desired target number of atoms. Mutually exclusive with `n_molecules`.
        mode: The composition interpretation mode ("molar" or "weight"). Defaults to "molar".
        stoichiometry: Optional pre-calculated stoichiometry dictionary.
        box_length: The length of the cubic simulation box in Angstroms. Defaults to 50.0.
        min_distance: The minimum allowed distance between any two atoms in Angstroms. Defaults to 1.6.
        seed: Random seed for reproducibility. Defaults to 42.
        max_attempts_per_atom: Maximum attempts to place a single atom before failing. Defaults to 100000.

    Returns:
        A tuple containing:
            - A list of atom dictionaries, each with "element" and "position".
            - A dictionary of total counts per element.

    Raises:
        ValueError: If composition sum is invalid or target mode is ambiguous.
        RuntimeError: If atom placement fails due to overcrowding (max attempts reached).

    Example:
        >>> atoms_list, atom_counts = create_random_atoms(
        ...     composition={"SiO2": 0.8, "Na2O": 0.2},
        ...     target_atoms=500,
        ...     box_length=20.0
        ... )

    """
    # Independent on operating system. Might break reproducibility across different Python/numpy versions
    rng = Generator(PCG64(seed))

    validate_target_mode(n_molecules, target_atoms)

    if stoichiometry is None:
        stoichiometry = extract_stoichiometry(composition)

    if target_atoms is not None:
        system_plan = plan_system(composition, target_atoms, mode=mode, target_type="atoms")
        atom_counts = system_plan["element_counts"]
    else:
        assert n_molecules is not None
        _, atom_counts = _counts_from_n_molecules(composition, n_molecules, mode, stoichiometry)

    atoms = _place_atoms(atom_counts, box_length, min_distance, rng, max_attempts_per_atom)
    return atoms, atom_counts

cte_from_fluctuations_simulation(structure: Atoms, potential: pd.DataFrame, temperature: float = 300, npt_pressure: float = 0.0001, timestep: float = 1.0, equilibration_steps: int = 100000, production_steps: int = 200000, min_production_runs: int = 5, max_production_runs: int = 25, CTE_uncertainty_criterion: float = 1e-06, n_dump: int | None = None, n_print_thermo: int = 10, server_kwargs: dict[str, Any] | None = None, *, aniso: bool = False, seed: int | None = 12345, tmp_working_directory: str | Path | None = None) -> dict[str, Any]

Perform a LAMMPS-based cte simulation protocol based on fluctuations.

This workflow equilibrates a structure at a target temperature and performs a production MD run to collect the instantaneous total energy, pressure and volume, needed to compute the CTE via H-V fluctuation analysis or V-T data, depending if only one temperature or multiple temperatures should be probed.

The number of steps used here is only for testing purposes. It is assumed in this workflow that the given in structure is pre-equilibrated.

Parameters:

Name Type Description Default
structure Atoms

Input structure (assumed pre-equilibrated).

required
potential DataFrame

LAMMPS potential file.

required
temperature float

Simulation temperature in Kelvin (default 300 K).

300
npt_pressure float

Target pressure in GPa (use pyiron units here!) for NPT simulations (default: 10-4 GPa = 10^5 Pa = 1 bar).

0.0001
timestep float

MD integration timestep in femtoseconds (default 1.0 fs).

1.0
equilibration_steps int

Number of MD steps for the equilibration run (default 100,000).

100000
production_steps int

Number of MD steps for the production runs (default 200,000).

200000
min_production_runs int

Minimum number of production runs to perform before checking for convergence (default 2).

5
max_production_runs int

Maximum number of production runs to perform before checking for convergence (default 10).

25
CTE_uncertainty_criterion float

Convergence criterion for the uncertainty of the linear CTE (default 1e-6/K).

1e-06
n_dump int | None

Interval of structure dumping in MD steps. If set to None, only the last step of the production runs is dumped (default None).

None
n_print_thermo int

Interval of printing thermodynamic output in MD steps (default 10).

10
server_kwargs dict[str, Any] | None

Additional server configuration arguments for pyiron.

None
aniso bool

If false, an isotropic NPT calculation is performed and the simulation box is scaled uniformly. If True, anisotropic NPT calculation is performed and the simulation box can change shape and size independently along each axis (default False).

False
seed int | None

Random seed for velocity initialization (default 12345). If None, a random seed is used.

12345
tmp_working_directory str | Path | None

Temporary directory for job execution.

None

Returns:

Type Description
dict[str, Any]

Nested dictionary containing the "summary" and "data" keys. In the "summary" section the CTE

dict[str, Any]

values and their uncertainties are returned together with info whether CTE_uncertainty_criterion was

dict[str, Any]

reached within the max_production_runs.

dict[str, Any]

The "data" holds the collected data from all individual production runs. "run_index" is to

dict[str, Any]

clearly identify which production run the data belongs to. "steps" contains the number of steps

dict[str, Any]

for each run. Thermodynamic and structural data are averaged over each production run and these

dict[str, Any]

averages are listed under the respective key. Example:

dict[str, Any]

{ 'summary' : {"CTE_V_mean" : ..., "CTE_x_mean" : ..., "CTE_y_mean" : ..., "CTE_z_mean" : ..., "CTE_V_uncertainty" : ..., "CTE_x_uncertainty" : ..., "CTE_y_uncertainty" : ..., "CTE_z_uncertainty" : ..., "is_converged" : "True" or "False", "convergence_criterion" : float },

dict[str, Any]

'data': {"run_index" : [1, 2, 3, ...], "steps" : [...], "T" : [...], "E_tot" : [...], "ptot" : [...], "pxx" : [...], "pyy" : [...], "pzz" : [...], "V" : [...], "Lx" : [...], "Ly" : [...], "Lz" : [...], "CTE_V" : [...], "CTE_x" : [...], "CTE_y" : [...], "CTE_z" : [...], }

dict[str, Any]

}

Notes
  • The structure is first pre-equilibrated with a short, hard-coded 10 ps NVT run. Only then follows the user-defined NPT equilibration and production runs.
  • The simulation is only marked as converged if the uncertainty criterion is reached for all four CTE values (CTE_V, CTE_x, CTE_y, CTE_z) at the same time. The CTE_uncertainty_criterion is applied to as-is to the linear CTEs. How this is treated for the CTE_V, see next point.
  • How to chose the uncertainty criterion for the volumetric CTE? Should it be the same as the defined CTE_uncertainty_criterion applied to the linear CTEs? Consider this: The volumetric CTE is approximately the sum of the linear CTEs along x, y, and z. If three variables x, y and z were uncorrelated and have known uncertainties sigma_x, sigma_y, and sigma_z, the uncertainty of the sum of them would be: sigma_V = sqrt( sigma_x2 + sigma_y2 + sigma_z*2 ). If we assume that the uncertainty criterion is reached at roughly the same time for all three variables, the uncertainty of the volumetric CTE can be approximated as sqrt(3)CTE_uncertainty_criterion. However, x, y and z are typically not uncorrelated. If calculated from the actual simulation data, the uncertainty of CTE_V is found to be approximately the same as the individual uncertainties of the linear CTEs. To be not too strict here, we keep the sqrt(3)*CTE_uncertainty_criterion for CTE_V.
Example

result = cte_from_fluctuations_simulation( ... structure=my_atoms, ... potential=my_potential, ... temperature=300, ... equilibration_steps=500_000, ... production_steps=200_000, ... min_production_runs=10, ... max_production_runs=50, ... CTE_uncertainty_criterion=1e-6, ... )

Source code in amorphouspy/src/amorphouspy/properties/cte.py
def cte_from_fluctuations_simulation(
    structure: Atoms,
    potential: pd.DataFrame,
    temperature: float = 300,
    npt_pressure: float = 1e-4,
    timestep: float = 1.0,
    equilibration_steps: int = 100_000,
    production_steps: int = 200_000,
    # n=5 corresponds to relative uncertainty of the standard deviation
    # delta sigma/sigma = (2(n-1))**-0.5 of ~35%
    min_production_runs: int = 5,
    max_production_runs: int = 25,
    CTE_uncertainty_criterion: float = 1e-6,
    n_dump: int | None = None,
    n_print_thermo: int = 10,
    server_kwargs: dict[str, Any] | None = None,
    *,
    aniso: bool = False,
    seed: int | None = 12345,
    tmp_working_directory: str | Path | None = None,
) -> dict[str, Any]:  # pylint: disable=too-many-positional-arguments
    """Perform a LAMMPS-based cte simulation protocol based on fluctuations.

    This workflow equilibrates a structure at a target temperature and performs a
    production MD run to collect the instantaneous total energy, pressure and volume,
    needed to compute the CTE via H-V fluctuation analysis or V-T data, depending
    if only one temperature or multiple temperatures should be probed.

    The number of steps used here is only for testing purposes.
    It is assumed in this workflow that the given in structure is pre-equilibrated.

    Args:
        structure: Input structure (assumed pre-equilibrated).
        potential: LAMMPS potential file.
        temperature: Simulation temperature in Kelvin (default 300 K).
        npt_pressure: Target pressure in GPa (use pyiron units here!) for NPT simulations
            (default: 10-4 GPa = 10^5 Pa = 1 bar).
        timestep: MD integration timestep in femtoseconds (default 1.0 fs).
        equilibration_steps: Number of MD steps for the equilibration run (default 100,000).
        production_steps: Number of MD steps for the production runs (default 200,000).
        min_production_runs: Minimum number of production runs to perform before checking for
            convergence (default 2).
        max_production_runs: Maximum number of production runs to perform before checking for
            convergence (default 10).
        CTE_uncertainty_criterion: Convergence criterion for the uncertainty of the linear
            CTE (default 1e-6/K).
        n_dump: Interval of structure dumping in MD steps. If set to `None`, only the last
            step of the production runs is dumped (default None).
        n_print_thermo: Interval of printing thermodynamic output in MD steps (default 10).
        server_kwargs: Additional server configuration arguments for pyiron.
        aniso: If false, an isotropic NPT calculation is performed and the simulation box is
              scaled uniformly. If True, anisotropic NPT calculation is performed and the simulation
              box can change shape and size independently along each axis (default False).
        seed: Random seed for velocity initialization (default 12345). If None, a random seed is used.
        tmp_working_directory: Temporary directory for job execution.

    Returns:
        Nested dictionary containing the "summary" and "data" keys. In the "summary" section the CTE
        values and their uncertainties are returned together with info whether CTE_uncertainty_criterion was
        reached within the max_production_runs.
        The "data" holds the collected data from all individual production runs. "run_index" is to
        clearly identify which production run the data belongs to. "steps" contains the number of steps
        for each run. Thermodynamic and structural data are averaged over each production run and these
        averages are listed under the respective key. Example:
        { 'summary' : {"CTE_V_mean" : ..., "CTE_x_mean" : ...,
                       "CTE_y_mean" : ..., "CTE_z_mean" : ...,
                       "CTE_V_uncertainty" : ..., "CTE_x_uncertainty" : ...,
                       "CTE_y_uncertainty" : ..., "CTE_z_uncertainty" : ...,
                       "is_converged" : "True" or "False",
                       "convergence_criterion" : float
                       },
        'data':  {"run_index" : [1, 2, 3, ...],
                    "steps" : [...],
                    "T" : [...],
                    "E_tot" : [...],
                    "ptot" : [...],
                    "pxx" : [...],
                    "pyy" : [...],
                    "pzz" : [...],
                    "V" : [...],
                    "Lx" : [...],
                    "Ly" : [...],
                    "Lz" : [...],
                    "CTE_V" : [...],
                    "CTE_x" : [...],
                    "CTE_y" : [...],
                    "CTE_z" : [...],
                    }
        }

    Notes:
        - The structure is first pre-equilibrated with a short, hard-coded 10 ps NVT run. Only then
          follows the user-defined NPT equilibration and production runs.
        - The simulation is only marked as converged if the uncertainty criterion is reached for all four CTE
          values (CTE_V, CTE_x, CTE_y, CTE_z) at the same time. The CTE_uncertainty_criterion is applied to
          as-is to the linear CTEs. How this is treated for the CTE_V, see next point.
        - How to chose the uncertainty criterion for the volumetric CTE? Should it be the same as the defined
          CTE_uncertainty_criterion applied to the linear CTEs? Consider this: The volumetric CTE is approximately
          the sum of the linear CTEs along x, y, and z. If three variables x, y and z were uncorrelated and
          have known uncertainties sigma_x, sigma_y, and sigma_z, the uncertainty of the sum of them would
          be: sigma_V = sqrt( sigma_x**2 + sigma_y**2 + sigma_z**2 ). If we assume that the uncertainty
          criterion is reached at roughly the same time for all three variables, the uncertainty of the
          volumetric CTE can be approximated as sqrt(3)*CTE_uncertainty_criterion. However, x, y and z are
          typically not uncorrelated. If calculated from the actual simulation data, the uncertainty of CTE_V
          is found to be approximately the same as the individual uncertainties of the linear CTEs. To be not
          too strict here, we keep the sqrt(3)*CTE_uncertainty_criterion for CTE_V.


    Example:
        >>> result = cte_from_fluctuations_simulation(
        ...     structure=my_atoms,
        ...     potential=my_potential,
        ...     temperature=300,
        ...     equilibration_steps=500_000,
        ...     production_steps=200_000,
        ...     min_production_runs=10,
        ...     max_production_runs=50,
        ...     CTE_uncertainty_criterion=1e-6,
        ... )

    """
    # Logging setup
    logger = _create_logger()

    # Check and adjust input parameters if necessary
    production_steps, min_production_runs, max_production_runs, N_for_averaging, equilibration_steps = (
        _fluctuation_simulation_input_checker(
            production_steps,
            min_production_runs,
            max_production_runs,
            n_print_thermo,
            timestep,
            equilibration_steps,
            logger,
        )
    )

    # Set pressure to anisotropic if requested
    sim_pressure = [npt_pressure, npt_pressure, npt_pressure, None, None, None] if aniso else npt_pressure

    # initial structure used. Afterwards, it is updated after each temperature
    structure0 = structure

    # Stage 1: Short equilibration in NVT at T for 10 ps
    logger.info("Starting 10 ps (hardcoded) NVT equilibration at %.2f K.", temperature)

    structure1, _ = _run_lammps_md(
        structure=structure0,
        potential=potential,
        tmp_working_directory=tmp_working_directory,
        temperature=temperature,
        n_ionic_steps=10_000,
        timestep=timestep,
        n_dump=10_000,
        n_print_thermo=100,
        input_control_file=CTE_INPUT_CONTROL_FILE,
        initial_temperature=temperature,
        ensemble="nvt",
        seed=seed,
        server_kwargs=server_kwargs,
    )

    # Stage 2: NPT equilibration runs at T,p.
    equilibration_time = equilibration_steps / timestep / 1000
    logger.info(
        "Starting %.1f ps NPT equilibration at %.2f K and %.2e GPa.", equilibration_time, temperature, npt_pressure
    )

    structure2, parsed_output = _run_lammps_md(
        structure=structure1,
        potential=potential,
        tmp_working_directory=tmp_working_directory,
        temperature=temperature,
        npt_pressure=sim_pressure,
        n_ionic_steps=equilibration_steps,
        timestep=timestep,
        n_dump=equilibration_steps,
        n_print_thermo=n_print_thermo,
        input_control_file=CTE_INPUT_CONTROL_FILE,
        initial_temperature=0,
        ensemble="npt_langevin",
        server_kwargs=server_kwargs,
    )

    # Collect the tail of the equilibration data to prepend to the first production run.
    # This avoids losing one window of data (half a window at both the start and end) of every production run.
    equil_sim_data = _collect_sim_data(parsed_output, counter_production_run=0)
    tail_data = _get_tail_data(equil_sim_data, N_for_averaging)

    # Stage 3: NPT production runs (loop) at T,p.
    results = _initialize_datadict(with_CTE_keys=True)
    cte_summary: dict[str, float | str] = {}
    counter_production_run = 1
    production_time = production_steps / timestep / 1000
    while counter_production_run <= max_production_runs:
        # to keep track of multiple production runs, print status message
        logger.info(
            "Starting %.1f ps NPT production run #%03d at %.2f K and %.2e GPa.",
            production_time,
            counter_production_run,
            temperature,
            npt_pressure,
        )

        # actual production run
        structure_production, parsed_output = _run_lammps_md(
            structure=structure2,
            potential=potential,
            tmp_working_directory=tmp_working_directory,
            temperature=temperature,
            npt_pressure=sim_pressure,
            n_ionic_steps=production_steps,
            timestep=timestep,
            n_dump=n_dump,
            n_print_thermo=n_print_thermo,
            input_control_file=CTE_INPUT_CONTROL_FILE,
            initial_temperature=0,
            ensemble="npt_langevin",
            server_kwargs=server_kwargs,
        )

        # parse and check the output of the production run
        _sim_data = _collect_sim_data(parsed_output, counter_production_run)
        _sanity_check_sim_data(sim_data=_sim_data, T_target=temperature, p_target=npt_pressure, logger=logger)

        # Prepend the tail of the previous run (or equilibration) so that the running-mean
        # window can cover the boundary and no data is lost at the start of each production run.
        _sim_data_with_tail = _prepend_tail_data(_sim_data, tail_data)

        # Calculate cte based on the data of the current production run (with prepended tail)
        _cte_results = _fluctuation_simulation_cte_calculation(
            sim_data=_sim_data_with_tail,
            temperature=temperature,
            p=npt_pressure,
            use_running_mean=True,
            N_points=N_for_averaging,
        )

        # Save the tail of the current production run for the next iteration
        tail_data = _get_tail_data(_sim_data, N_for_averaging)

        # merge results to have the averages over all production runs so far
        results = _fluctuation_simulation_merge_results(
            previous_data=results, new_sim_data=_sim_data, new_cte_data=_cte_results
        )

        # start checking for convergence once the min number of production runs have been executed
        if counter_production_run >= min_production_runs:
            converge_bool, cte_summary = _fluctuation_simulation_uncertainty_check(results, CTE_uncertainty_criterion)
            logger.info(
                "Production run #%03d finished. Current CTE_V = %.4e +/- %.4e 1/K.",
                counter_production_run,
                cte_summary["CTE_V_mean"],
                cte_summary["CTE_V_uncertainty"],
            )

            # If converged, break the loop and update the summary accordingly
            if converge_bool:
                cte_summary.update({"is_converged": "True", "convergence_criterion": CTE_uncertainty_criterion})
                msg = f"All CTEs converged after production run #{counter_production_run:03d}."
                msg += "\nFINISHED SUCCESSFULLY."
                logger.info(msg)
                break

            # Also break the loop if max number of production runs is reached without convergence and update summary
            if counter_production_run == max_production_runs:
                cte_summary.update({"is_converged": "False", "convergence_criterion": CTE_uncertainty_criterion})
                msg = f"Maximum number of production runs ({max_production_runs}) reached without CTE convergence."
                msg += "\nFINISHED WITHOUT CONVERGENCE."
                logger.info(msg)
                break

        # In all other cases, continue with the next production run
        counter_production_run += 1
        structure2 = structure_production

    return {"summary": cte_summary, "data": results}

cte_from_npt_fluctuations(temperature: float | list | np.ndarray, enthalpy: list | np.ndarray, volume: list | np.ndarray, N_points: int = 1000, *, use_running_mean: bool = False) -> float

Compute the CTE from enthalpy-volume cross-correlations.

Data needs to be obtained from a constant pressure, constant temperature NPT simulation. Formula used can be found in See Tildesley, Computer Simulation of Liquids, Eq. 2.94.

Parameters:

Name Type Description Default
temperature float | list | ndarray

Target temperature (defining the ensemble) in K. Can be specified as a single value (int/float). If provided as list or array-like, the mean will be used as target temperature.

required
enthalpy list | ndarray

"Instantaneous enthalpy" in eV, list or np.ndarray. Not that the instantaneous enthalpy is given by H = U + pV, where U is the instantaneous internal energy (i.e., kinetic + potential of every timestep), p the pressure defining the ensemble and V the average volume. Note that this is not the same quantity as the enthalpy obtained from LAMMPS directly via the 'enthalpy' output from thermo_modify. The latter uses the instantaneous pressure at the given timestep instead of the average (or ensemble-defining) pressure.

required
volume list | ndarray

Instantaneous volume in Ang^3, list or np.ndarray. Here, one can also feed individual cell lengths for anisotropic CTE calculations.

required
N_points int

Window size for running mean calculation if running_mean is True. Defaults to 1000.

1000
use_running_mean bool

Conventionally, fluctuations are calculated as difference from the mean of the whole trajectory. If use_running_mean is True, running mean values are used to determine fluctuations. This can be useful for non-stationary data where drift in volume and energy is still observed. Defaults to False.

False

Returns:

Type Description
float

The calculated CTE value in 1/K.

Example

cte = cte_from_npt_fluctuations( ... temperature=300.0, ... enthalpy=enthalpy_array, ... volume=volume_array ... )

Notes
  • If temperature is provided as int/float, it will be used as-is for the target temperature to compute the CTE.
  • If temperature is provided as list/array-like, the mean of the temperature data will be used as target temperature for the CTE calculation. See below how this is slightly changed if running mean is used.
  • If running_mean is set to True used, a part of the volume and enthalpy data at the beginning and end of the arrays cannot be used because it is required to calculate the running mean values. To ensure that the data for the calculation of the fluctuations is consistent with the mean volume and target temperature (in case this was provided as list/array-like), also this data will be trimmed correspondingly.
Source code in amorphouspy/src/amorphouspy/properties/cte_analysis.py
def cte_from_npt_fluctuations(
    temperature: float | list | np.ndarray,
    enthalpy: list | np.ndarray,
    volume: list | np.ndarray,
    N_points: int = 1000,
    *,
    use_running_mean: bool = False,
) -> float:
    """Compute the CTE from enthalpy-volume cross-correlations.

    Data needs to be obtained from a constant pressure, constant temperature NPT simulation. Formula used
    can be found in See Tildesley, Computer Simulation of Liquids, Eq. 2.94.

    Args:
        temperature: Target temperature (defining the ensemble) in K. Can be specified as a single value (int/float).
            If provided as list or array-like, the mean will be used as target temperature.
        enthalpy: "Instantaneous enthalpy" in eV, list or np.ndarray. Not that the instantaneous enthalpy is given by
            H = U + pV, where U is the instantaneous internal energy (i.e., kinetic + potential of every timestep),
            p the pressure defining the ensemble and V the average volume. Note that this is not the same quantity
            as the enthalpy obtained from LAMMPS directly via the 'enthalpy' output from thermo_modify. The latter
            uses the instantaneous pressure at the given timestep instead of the average (or ensemble-defining)
            pressure.
        volume: Instantaneous volume in Ang^3, list or np.ndarray. Here, one can also feed individual cell lengths for
            anisotropic CTE calculations.
        N_points: Window size for running mean calculation if running_mean is True. Defaults to 1000.
        use_running_mean: Conventionally, fluctuations are calculated as difference from the mean of the whole
            trajectory. If use_running_mean is True, running mean values are used to determine fluctuations. This
            can be useful for non-stationary data where drift in volume and energy is still observed. Defaults to False.

    Returns:
        The calculated CTE value in 1/K.

    Example:
        >>> cte = cte_from_npt_fluctuations(
        ...     temperature=300.0,
        ...     enthalpy=enthalpy_array,
        ...     volume=volume_array
        ... )

    Notes:
        - If temperature is provided as int/float, it will be used as-is for the target temperature to compute the CTE.
        - If temperature is provided as list/array-like, the mean of the temperature data will be used as target
          temperature for the CTE calculation. See below how this is slightly changed if running mean is used.
        - If running_mean is set to True used, a part of the volume and enthalpy data at the beginning and end of the
          arrays cannot be used because it is required to calculate the running mean values. To ensure that the data for
          the calculation of the fluctuations is consistent with the mean volume and target temperature (in case this
          was provided as list/array-like), also this data will be trimmed correspondingly.
    """

    def _input_checks(
        enthalpy: list | np.ndarray,
        volume: list | np.ndarray,
        temperature: float | list | np.ndarray,
        N_points: int,
        *,
        use_running_mean: bool,
    ) -> tuple[int | None, int | None]:
        """Checks the input beyond simple type checks and determines the padding for the running mean if required.

        Args:
            enthalpy: See main function.
            volume: See main function.
            temperature: See main function.
            N_points: See main function.
            use_running_mean: See main function.

        Returns:
            padL: Number of points to be trimmed at the beginning of the enthalpy and volume arrays if use_running_mean
                is True. None otherwise. Will also be used for trimming the temperature if provided as list or
                array-like to ensure consistency with the mean volume and target temperature.
            padR: Number of points to be trimmed at the end of the enthalpy and volume arrays if use_running_mean is
                True. None otherwise. Will also be used for trimming the temperature if provided as list or array-like
                to ensure consistency with the mean volume and target temperature.
        """
        if isinstance(temperature, (int, float)):
            if len(enthalpy) != len(volume):
                msg = (
                    "If temperature is provided as int or float, enthalpy and volume arrays must have the same length."
                )
                raise ValueError(msg)
        elif len(temperature) != len(enthalpy) or len(enthalpy) != len(volume):
            msg = "If temperature is provided as list or array-like,"
            msg += " it must have the same length as the enthalpy and volume arrays."
            raise ValueError(msg)

        if use_running_mean:
            if N_points < 1:
                msg = "N_points must be a positive integer >= 1."
                raise ValueError(msg)
            if N_points >= len(enthalpy):
                msg = "N_points must be smaller than the length of the enthalpy and volume arrays."
                raise ValueError(msg)
            padL, padR = int(N_points / 2), N_points - int(N_points / 2) - 1
            return padL, padR
        return None, None

    # if use_running_mean = False, padL and padR will both be None
    padL, padR = _input_checks(enthalpy, volume, temperature, N_points, use_running_mean=use_running_mean)

    if use_running_mean:
        assert padR is not None
        assert padL is not None
        H_fluctuations = np.array(np.array(enthalpy) - running_mean(enthalpy, N_points))[padL:-padR]
        V_fluctuations = np.array(np.array(volume) - running_mean(volume, N_points))[padL:-padR]
    else:
        H_fluctuations = np.array(enthalpy) - np.mean(enthalpy)
        V_fluctuations = np.array(volume) - np.mean(volume)

    V_mean = np.mean(volume) if padL is None or padR is None else np.mean(volume[padL:-padR])
    T_target = (
        temperature
        if isinstance(temperature, (int, float))
        else (np.mean(temperature) if padL is None or padR is None else np.mean(temperature[padL:-padR]))
    )

    kB = 8.617333262145e-5  # eV/K
    CTE = (np.mean(H_fluctuations * V_fluctuations)) / (V_mean * kB * T_target**2)
    return float(CTE)

cte_from_volume_temperature_data(temperature: list | np.ndarray, volume: list | np.ndarray, reference_volume: float | None = None) -> tuple[float, float]

Compute the CTE from slope of a linear fit to volume-temperature data.

This can be done from by performing various constant pressure, constant temperature NPT simulation at different temperatures. Afterwards, collect the averaged volume and fit linearly to the temperature. Divide slope by the volume belonging to the lowest temperature to obtain the CTE. If specified, the volume-temperature plot is shown and the fitted line is overlaid.

Parameters:

Name Type Description Default
temperature list | ndarray

Temperature in K.

required
volume list | ndarray

Volume in Angstrom^3 or other structural quantity of interest. E.g., for anisotropic CTE calculations, one can also use individual cell lengths in Angstroms here.

required
reference_volume optional

Reference of the volume (or structural quantity of interest) the CTE will be calculated from. If not otherwise specified, the volume corresponding to the lowest temperature is used as reference.

None

Returns:

Type Description
tuple[float, float]

The calculated CTE value in 1/K and the R^2 value of the linear fit.

Note
  • This function is currently not in use in the workflows. But it might be used for cross-checking.
  • If volume-temperature data is used, the CTE needs to be divided by 3 to obtain the linear CTE.
Example

cte = cte_from_volume_temperature_data( ... temperature=[300, 400, 500], ... volume=[100.0, 100.1, 100.2] ... )

Source code in amorphouspy/src/amorphouspy/properties/cte_analysis.py
def cte_from_volume_temperature_data(
    temperature: list | np.ndarray,
    volume: list | np.ndarray,
    reference_volume: float | None = None,
) -> tuple[float, float]:
    """Compute the CTE from slope of a linear fit to volume-temperature data.

    This can be done from by performing various constant pressure, constant temperature NPT simulation
    at different temperatures. Afterwards, collect the averaged volume and fit linearly to the temperature.
    Divide slope by the volume belonging to the lowest temperature to obtain the CTE.
    If specified, the volume-temperature plot is shown and the fitted line is overlaid.

    Args:
        temperature: Temperature in K.
        volume: Volume in Angstrom^3 or other structural quantity of interest. E.g., for anisotropic CTE
            calculations, one can also use individual cell lengths in Angstroms here.
        reference_volume (optional): Reference of the volume (or structural quantity of interest) the CTE
            will be calculated from. If not otherwise specified, the volume corresponding to the lowest
            temperature is used as reference.

    Returns:
        The calculated CTE value in 1/K and the R^2 value of the linear fit.

    Note:
        - This function is currently not in use in the workflows. But it might be used for cross-checking.
        - If volume-temperature data is used, the CTE needs to be divided by 3 to obtain the linear CTE.

    Example:
        >>> cte = cte_from_volume_temperature_data(
        ...     temperature=[300, 400, 500],
        ...     volume=[100.0, 100.1, 100.2]
        ... )

    """
    MIN_POINTS = 2

    temperature_arr = np.asarray(temperature, dtype=np.float64)
    volume_arr = np.asarray(volume, dtype=np.float64)

    # input checks
    if temperature_arr.ndim != 1 or volume_arr.ndim != 1:
        msg = "temperature and volume must be one-dimensional arrays."
        raise ValueError(msg)
    if temperature_arr.size != volume_arr.size:
        msg = "temperature and volume must have the same length."
        raise ValueError(msg)
    if temperature_arr.size < MIN_POINTS:
        msg = f"At least {MIN_POINTS} temperature-volume points are required."
        raise ValueError(msg)

    # Set reference volume corresponding to the lowest temperature if not provided.
    if reference_volume is None:
        index_lowest_T = int(np.argmin(temperature_arr))
        ref_volume = float(volume_arr[index_lowest_T])
    else:
        ref_volume = float(reference_volume)

    if np.isclose(ref_volume, 0.0):
        msg = "reference_volume must be non-zero."
        raise ValueError(msg)

    # Fit and calculate CTE
    slope = float(np.polyfit(temperature_arr, volume_arr, 1)[0])
    r_value = float(np.corrcoef(temperature_arr, volume_arr)[0, 1])
    cte = slope / ref_volume
    r2 = r_value**2

    return float(cte), float(r2)

diagonalize_dynamical_matrix(matrix: NDArray[np.float64], *, masses: ArrayLike | None = None, overwrite_matrix: bool = False, eigenvectors: bool = True, driver: EigenDriver = 'evr', imaginary_threshold_thz: float = 0.01) -> dict[str, Any]

Symmetrise and diagonalise a mass-weighted dynamical matrix and drop the three translational modes.

The input is the dynamical matrix of :func:read_dynamical_matrix,

\[D_{i\alpha, j\beta} = \frac{\Phi_{i\alpha, j\beta}}{\sqrt{m_i m_j}}\]

in eV/Ų/amu, \((3N, 3N)\), row and column \(3i + \alpha\) for atom \(i\) and direction \(\alpha\). An eigenvalue \(\lambda\) gives the frequency \(\nu = \sqrt{\lambda} / (2\pi)\), which is \(\nu = 15.633\ \mathrm{THz} \times \sqrt{\lambda / (\mathrm{eV/Å^2/amu})}\) (the factor is \(\sqrt{e / (10^{-20}\, m_\mathrm{u})} / (2\pi) / 10^{12}\) from scipy.constants). An imaginary mode, \(\lambda < 0\), is reported as a negative frequency \(\nu = -\sqrt{|\lambda|} / (2\pi)\).

Steps:

  1. Asymmetry of the raw matrix, \(\max|D - D^\mathsf{T}| / \max|D|\), and the atom pair \((i, j)\), \(i \le j\), of the worst entry. A finite-difference matrix is symmetric only to the difference error. A pair that crosses a cutoff where the force jumps during a displacement \(h\) (an energy-shifted pair style such as the PMMCS pedone term at 5.5 Å) gets a spurious term of about jump / (2h) in one entry but not in its transpose, so a large asymmetry points at such corrupted entries, and the atom pair tells where. It is measured before symmetrising, in blocks of rows, together with the check for NaN and inf.
  2. Symmetrisation to \((D + D^\mathsf{T}) / 2\) in place, in the same blocks. With overwrite_matrix=False this works on one copy of the input; with True on the input itself.
  3. Diagonalisation with scipy.linalg.eigh(..., overwrite_a=True, driver=driver). This deliberately replaces the numpy.linalg.eigh of the original plan: numpy always copies the matrix and uses the divide-and-conquer driver, which with eigenvectors needs four matrices besides the input, against one for "evr" (see Memory).
  4. The three translational modes are dropped: the three eigenvalues of smallest \(|\lambda|\), which are three consecutive ones of the ascending spectrum. With masses, each dropped mode's squared projection on the span of the mass-weighted rigid translations \(t_\alpha = \sqrt{m_i}\, e_\alpha / \sqrt{\sum_i m_i}\) is reported; it is 1 for a pure translation. A value below 0.9 warns: a soft mode is mixed in, or the translations are not the smallest \(|\lambda|\) (a sum-rule violation that lifts them, or an isolated cluster, whose rotations are zero modes too).
  5. Kept frequencies below -imaginary_threshold_thz count as imaginary and warn, with the asymmetry atoms.

Memory (benchmark: a 3000-atom spring network, n = 9000, OpenBLAS 0.3.34 on 12 Apple M-series cores; peak allocations, confirmed by the peak process RSS; scaled as \(n^2\) to \(N\) = 6000 and 10,000 atoms, where one matrix is 2.6 GB and 7.2 GB). Totals include the input matrix; overwrite_matrix=False adds one copy:

  • eigenvalues only, any driver: 1 matrix, 2.6 / 7.2 GB (2 matrices, 5.2 / 14.4 GB without overwrite).
  • "evr" with eigenvectors: 2 matrices (the eigenvectors are a new array), 5.2 / 14.4 GB (7.8 / 21.6 GB).
  • "evx" with eigenvectors: the same as "evr".
  • "evd" with eigenvectors: 3 matrices (the eigenvectors overwrite the input, plus two of workspace), 7.8 / 21.6 GB (10.4 / 28.8 GB).
  • "ev" with eigenvectors: 1 matrix (the eigenvectors overwrite the input), 2.6 / 7.2 GB (5.2 / 14.4 GB).
  • For comparison, numpy.linalg.eigh: 5 matrices, 13 / 36 GB.

The asymmetry and symmetrisation passes add up to about 0.2 GB of row blocks (_CHUNK_BYTES each), independent of \(N\), and LAPACK \(O(n)\) workspace.

Time at n = 9000, with eigenvectors (scaled as \(n^3\), by 8 and 37, to 6000 and 10,000 atoms): "evr" 33 s (4.4 min, 20 min), "evd" 27 s (3.6 min, 16 min; 66 s in a first, disturbed run), "evx" 316 s (42 min, 3.2 h), "ev" 339 s (45 min, 3.5 h). Eigenvalues only: about 10 s with every driver (1.3 min, 6 min). "evr" is the default: within about 20 % of the fastest, "evd", at one matrix less, and memory is the limit at 10,000 atoms.

With overwrite_matrix=True the input's contents are undefined afterwards (LAPACK overwrites it); with "ev" or "evd" the returned eigenvectors share its memory. Only a writable C- or F-contiguous array can be used without a copy, which is checked.

Parameters:

Name Type Description Default
matrix NDArray[float64]

The \((3N, 3N)\) mass-weighted dynamical matrix in eV/Ų/amu, float64 (no cast is made, since a cast would copy it). Not symmetrised.

required
masses ArrayLike | None

Atomic masses in amu, shape \((N,)\), in the order of the matrix rows. Only used for the translational overlap, so it needs eigenvectors=True.

None
overwrite_matrix bool

Symmetrise and diagonalise matrix itself instead of a copy, saving one matrix of memory. Its contents are undefined afterwards.

False
eigenvectors bool

Also return the eigenvectors of the kept modes.

True
driver EigenDriver

The LAPACK driver of scipy.linalg.eigh: "evr" (MRRR), "evd" (divide and conquer), "ev" (QR iteration) or "evx" (bisection and inverse iteration).

'evr'
imaginary_threshold_thz float

Kept frequencies below minus this value, in THz, count as imaginary.

0.01

Returns:

Type Description
dict[str, Any]

A dictionary with: "frequencies_thz": the \(3N - 3\) kept frequencies in THz, ascending, negative for imaginary modes. "eigenvectors": \((3N, 3N - 3)\) array whose orthonormal columns are the kept modes, in the order of "frequencies_thz" (a view of the LAPACK output), or None with eigenvectors=False. "translational_frequencies_thz": the three dropped frequencies in THz, ascending. "translational_overlap": the dropped modes' squared projections on the rigid translations, shape (3,), or None without masses. "asymmetry": \(\max|D - D^\mathsf{T}| / \max|D|\) of the raw matrix (0.0 if exactly symmetric). "asymmetry_atoms": the atom pair \((i, j)\), \(i \le j\), of the largest \(|D - D^\mathsf{T}|\), or None if the matrix is exactly symmetric. \(i = j\) when the worst entry lies in an atom's own \(3 \times 3\) block; after a cutoff crossing that atom is one of the crossing pair. "n_imaginary": the number of kept frequencies below -imaginary_threshold_thz. "min_frequency_thz": the lowest kept frequency in THz. "n_atoms": \(N\). "driver": the LAPACK driver used.

Raises:

Type Description
ValueError

If matrix is not square and 2-D, its size is not \(3N\) with \(N \ge 2\), it is not float64, it contains NaN or inf, or with overwrite_matrix=True it is read-only or not C- or F-contiguous; if masses does not hold \(N\) positive finite values or is given with eigenvectors=False; if driver is unknown or imaginary_threshold_thz is negative.

Warns:

Type Description
UserWarning

If a dropped mode overlaps the rigid translations by less than 0.9, or if any kept frequency is imaginary.

Example
>>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin")  # doctest: +SKIP
>>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"])  # doctest: +SKIP
>>> modes = diagonalize_dynamical_matrix(  # doctest: +SKIP
...     matrix, masses=minimised.get_masses(), overwrite_matrix=True
... )
>>> modes["asymmetry"], modes["n_imaginary"], modes["translational_overlap"]  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/dynamical_matrix.py
def diagonalize_dynamical_matrix(
    matrix: NDArray[np.float64],
    *,
    masses: ArrayLike | None = None,
    overwrite_matrix: bool = False,
    eigenvectors: bool = True,
    driver: EigenDriver = "evr",
    imaginary_threshold_thz: float = 0.01,
) -> dict[str, Any]:
    r"""Symmetrise and diagonalise a mass-weighted dynamical matrix and drop the three translational modes.

    The input is the dynamical matrix of :func:`read_dynamical_matrix`,

    $$D_{i\alpha, j\beta} = \frac{\Phi_{i\alpha, j\beta}}{\sqrt{m_i m_j}}$$

    in eV/Ų/amu, $(3N, 3N)$, row and column $3i + \alpha$ for atom $i$ and direction $\alpha$. An eigenvalue
    $\lambda$ gives the frequency $\nu = \sqrt{\lambda} / (2\pi)$, which is
    $\nu = 15.633\ \mathrm{THz} \times \sqrt{\lambda / (\mathrm{eV/Å^2/amu})}$ (the factor is
    $\sqrt{e / (10^{-20}\, m_\mathrm{u})} / (2\pi) / 10^{12}$ from ``scipy.constants``). An imaginary mode,
    $\lambda < 0$, is reported as a negative frequency $\nu = -\sqrt{|\lambda|} / (2\pi)$.

    Steps:

    1. Asymmetry of the raw matrix, $\max|D - D^\mathsf{T}| / \max|D|$, and the atom pair $(i, j)$, $i \le j$, of the
       worst entry. A finite-difference matrix is symmetric only to the difference error. A pair that crosses a cutoff
       where the force jumps during a displacement $h$ (an energy-shifted pair style such as the PMMCS ``pedone`` term
       at 5.5 Å) gets a spurious term of about jump / (2h) in one entry but not in its transpose, so a large asymmetry
       points at such corrupted entries, and the atom pair tells where. It is measured before symmetrising, in blocks
       of rows, together with the check for NaN and inf.
    2. Symmetrisation to $(D + D^\mathsf{T}) / 2$ in place, in the same blocks. With ``overwrite_matrix=False`` this
       works on one copy of the input; with True on the input itself.
    3. Diagonalisation with ``scipy.linalg.eigh(..., overwrite_a=True, driver=driver)``. This deliberately replaces
       the ``numpy.linalg.eigh`` of the original plan: numpy always copies the matrix and uses the divide-and-conquer
       driver, which with eigenvectors needs four matrices besides the input, against one for ``"evr"`` (see Memory).
    4. The three translational modes are dropped: the three eigenvalues of smallest $|\lambda|$, which are three
       consecutive ones of the ascending spectrum. With ``masses``, each dropped mode's squared projection on the span
       of the mass-weighted rigid translations $t_\alpha = \sqrt{m_i}\, e_\alpha / \sqrt{\sum_i m_i}$ is reported; it
       is 1 for a pure translation. A value below 0.9 warns: a soft mode is mixed in, or the translations are not the
       smallest $|\lambda|$ (a sum-rule violation that lifts them, or an isolated cluster, whose rotations are zero
       modes too).
    5. Kept frequencies below ``-imaginary_threshold_thz`` count as imaginary and warn, with the asymmetry atoms.

    Memory (benchmark: a 3000-atom spring network, n = 9000, OpenBLAS 0.3.34 on 12 Apple M-series cores; peak
    allocations, confirmed by the peak process RSS; scaled as $n^2$ to $N$ = 6000 and 10,000 atoms, where one matrix
    is 2.6 GB and 7.2 GB). Totals include the input matrix; ``overwrite_matrix=False`` adds one copy:

    - eigenvalues only, any driver: 1 matrix, 2.6 / 7.2 GB (2 matrices, 5.2 / 14.4 GB without overwrite).
    - ``"evr"`` with eigenvectors: 2 matrices (the eigenvectors are a new array), 5.2 / 14.4 GB (7.8 / 21.6 GB).
    - ``"evx"`` with eigenvectors: the same as ``"evr"``.
    - ``"evd"`` with eigenvectors: 3 matrices (the eigenvectors overwrite the input, plus two of workspace),
      7.8 / 21.6 GB (10.4 / 28.8 GB).
    - ``"ev"`` with eigenvectors: 1 matrix (the eigenvectors overwrite the input), 2.6 / 7.2 GB (5.2 / 14.4 GB).
    - For comparison, ``numpy.linalg.eigh``: 5 matrices, 13 / 36 GB.

    The asymmetry and symmetrisation passes add up to about 0.2 GB of row blocks (``_CHUNK_BYTES`` each), independent
    of $N$, and LAPACK $O(n)$ workspace.

    Time at n = 9000, with eigenvectors (scaled as $n^3$, by 8 and 37, to 6000 and 10,000 atoms): ``"evr"`` 33 s
    (4.4 min, 20 min), ``"evd"`` 27 s (3.6 min, 16 min; 66 s in a first, disturbed run), ``"evx"`` 316 s (42 min,
    3.2 h), ``"ev"`` 339 s (45 min, 3.5 h). Eigenvalues only: about 10 s with every driver (1.3 min, 6 min).
    ``"evr"`` is the default: within about 20 % of the fastest, ``"evd"``, at one matrix less, and memory is the limit
    at 10,000 atoms.

    With ``overwrite_matrix=True`` the input's contents are undefined afterwards (LAPACK overwrites it); with
    ``"ev"`` or ``"evd"`` the returned eigenvectors share its memory. Only a writable C- or F-contiguous array can
    be used without a copy, which is checked.

    Args:
        matrix: The $(3N, 3N)$ mass-weighted dynamical matrix in eV/Ų/amu, float64 (no cast is made, since a cast
            would copy it). Not symmetrised.
        masses: Atomic masses in amu, shape $(N,)$, in the order of the matrix rows. Only used for the
            translational overlap, so it needs ``eigenvectors=True``.
        overwrite_matrix: Symmetrise and diagonalise ``matrix`` itself instead of a copy, saving one matrix of memory.
            Its contents are undefined afterwards.
        eigenvectors: Also return the eigenvectors of the kept modes.
        driver: The LAPACK driver of ``scipy.linalg.eigh``: ``"evr"`` (MRRR), ``"evd"`` (divide and conquer),
            ``"ev"`` (QR iteration) or ``"evx"`` (bisection and inverse iteration).
        imaginary_threshold_thz: Kept frequencies below minus this value, in THz, count as imaginary.

    Returns:
        A dictionary with:
            ``"frequencies_thz"``: the $3N - 3$ kept frequencies in THz, ascending, negative for imaginary modes.
            ``"eigenvectors"``: $(3N, 3N - 3)$ array whose orthonormal columns are the kept modes, in the order of
            ``"frequencies_thz"`` (a view of the LAPACK output), or None with ``eigenvectors=False``.
            ``"translational_frequencies_thz"``: the three dropped frequencies in THz, ascending.
            ``"translational_overlap"``: the dropped modes' squared projections on the rigid translations, shape
            (3,), or None without ``masses``.
            ``"asymmetry"``: $\max|D - D^\mathsf{T}| / \max|D|$ of the raw matrix (0.0 if exactly symmetric).
            ``"asymmetry_atoms"``: the atom pair $(i, j)$, $i \le j$, of the largest $|D - D^\mathsf{T}|$, or None if
            the matrix is exactly symmetric. $i = j$ when the worst entry lies in an atom's own $3 \times 3$ block;
            after a cutoff crossing that atom is one of the crossing pair.
            ``"n_imaginary"``: the number of kept frequencies below ``-imaginary_threshold_thz``.
            ``"min_frequency_thz"``: the lowest kept frequency in THz.
            ``"n_atoms"``: $N$.
            ``"driver"``: the LAPACK driver used.

    Raises:
        ValueError: If ``matrix`` is not square and 2-D, its size is not $3N$ with $N \ge 2$, it is not float64, it
            contains NaN or inf, or with ``overwrite_matrix=True`` it is read-only or not C- or F-contiguous; if
            ``masses`` does not hold $N$ positive finite values or is given with ``eigenvectors=False``; if
            ``driver`` is unknown or ``imaginary_threshold_thz`` is negative.

    Warns:
        UserWarning: If a dropped mode overlaps the rigid translations by less than 0.9, or if any kept frequency is
            imaginary.

    Example:
        ```pycon
        >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin")  # doctest: +SKIP
        >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"])  # doctest: +SKIP
        >>> modes = diagonalize_dynamical_matrix(  # doctest: +SKIP
        ...     matrix, masses=minimised.get_masses(), overwrite_matrix=True
        ... )
        >>> modes["asymmetry"], modes["n_imaginary"], modes["translational_overlap"]  # doctest: +SKIP

        ```
    """
    matrix = np.asarray(matrix)
    masses = _validate_dynamical_matrix_input(
        matrix,
        masses,
        overwrite_matrix=overwrite_matrix,
        eigenvectors=eigenvectors,
        driver=driver,
        imaginary_threshold_thz=imaginary_threshold_thz,
    )
    n_dof = matrix.shape[0]
    asymmetry, asymmetry_atoms = _asymmetry(matrix)
    work = matrix if overwrite_matrix else np.array(matrix)
    _symmetrise_in_place(work)
    # LAPACK works on Fortran-ordered arrays; f2py copies anything else. The transpose of a C-ordered symmetric
    # matrix is the same matrix in Fortran order, so passing it avoids the copy.
    lapack_input = work.T if work.flags.c_contiguous else work
    del work
    result = scipy.linalg.eigh(
        lapack_input, overwrite_a=True, check_finite=False, driver=driver, eigvals_only=not eigenvectors
    )
    del lapack_input
    eigenvalues, vectors = result if eigenvectors else (result, None)

    # The eigenvalues are ascending, so the three of smallest |λ| are three consecutive ones: the window
    # [first, first + 3) with the smallest max |λ| (the first such window on an exact tie).
    magnitudes = np.abs(eigenvalues)
    first = int(np.argmin(np.maximum(np.maximum(magnitudes[:-2], magnitudes[1:-1]), magnitudes[2:])))
    dropped = slice(first, first + _N_TRANSLATIONS)
    translational_frequencies = _eigenvalues_to_thz(eigenvalues[dropped])
    frequencies = _eigenvalues_to_thz(np.delete(eigenvalues, dropped))

    translational_overlap = None
    if vectors is not None:
        if masses is not None:
            weights = np.sqrt(masses) / math.sqrt(masses.sum())
            projections = np.einsum("i,iam->am", weights, vectors[:, dropped].reshape(-1, 3, _N_TRANSLATIONS))
            translational_overlap = (projections**2).sum(axis=0)
            if translational_overlap.min() < _MIN_TRANSLATIONAL_OVERLAP:
                warnings.warn(
                    f"The dropped modes at {np.array2string(translational_frequencies, precision=4)} THz overlap the "
                    f"rigid translations by only {np.array2string(translational_overlap, precision=3)} (< "
                    f"{_MIN_TRANSLATIONAL_OVERLAP}): a soft mode is mixed in, or the translations are not the three "
                    "smallest |eigenvalues|.",
                    UserWarning,
                    stacklevel=2,
                )
        # Instead of copying the (3N, 3N - 3) kept columns, shift the `first` columns before the translations (the
        # modes below them, usually the few imaginary ones) three to the right, over the translations. Every column
        # after the translations is already in place, so the kept modes are then columns 3 onwards, in their original
        # order: a view. numpy buffers the overlapping assignment, which costs `first` columns, not the matrix.
        vectors[:, _N_TRANSLATIONS : first + _N_TRANSLATIONS] = vectors[:, :first]
        vectors = vectors[:, _N_TRANSLATIONS:]

    n_imaginary = int(np.count_nonzero(frequencies < -imaginary_threshold_thz))
    min_frequency = float(frequencies[0])
    if n_imaginary:
        warnings.warn(
            f"{n_imaginary} imaginary mode(s) below -{imaginary_threshold_thz} THz; the most negative is "
            f"{min_frequency:.4g} THz. Raw-matrix asymmetry {asymmetry:.3g}, largest between atoms {asymmetry_atoms}.",
            UserWarning,
            stacklevel=2,
        )
    return {
        "frequencies_thz": frequencies,
        "eigenvectors": vectors,
        "translational_frequencies_thz": translational_frequencies,
        "translational_overlap": translational_overlap,
        "asymmetry": asymmetry,
        "asymmetry_atoms": asymmetry_atoms,
        "n_imaginary": n_imaginary,
        "min_frequency_thz": min_frequency,
        "n_atoms": n_dof // 3,
        "driver": driver,
    }

diffusion_simulation(structure: Atoms, potential: pd.DataFrame, temperature_sim: float = 3000.0, timestep: float = 1.0, production_steps: int = 1000000, n_print_thermo: int = 100, server_kwargs: dict[str, Any] | None = None, *, equilibration_steps: int = 100000, thermostat: Thermostat, seed: int = 12345, tmp_working_directory: str | Path | None = None, max_lag: int | None = None, remove_com_drift: bool = True, crossover_ps: float = 100.0, points_per_decade: int = 9, linear_interval_ps: float = 10.0, save_trajectory: str | Path | None = None) -> dict[str, Any]

Run an MD production trajectory and compute self-diffusion from the MSD.

Equilibrates the structure (Langevin then NVT) and runs an NVT production stage that dumps on a log-then-linear schedule to keep the trajectory small: decade-log below crossover_ps (with the default points_per_decade=9 the dumped steps are 1, 2, ..., 9, 10, 20, ..., 90, 100, ...) and uniform every linear_interval_ps above it. The MSD is computed single-origin (the non-uniform grid cannot use a multi-time-origin FFT estimator).

Equilibration and production are run at constant volume, so the simulation keeps the density of the input structure. Pass a structure pre-equilibrated at the desired density/pressure to control it.

Parameters:

Name Type Description Default
structure Atoms

Input structure (a melt or pre-equilibrated glass); its cell sets the run density.

required
potential DataFrame

LAMMPS potential as a pandas DataFrame.

required
temperature_sim float

Production temperature in Kelvin.

3000.0
timestep float

MD timestep in femtoseconds.

1.0
production_steps int

Number of MD steps in the production stage.

1000000
n_print_thermo int

Thermo/log output interval in MD steps.

100
server_kwargs dict[str, Any] | None

Additional arguments for the LAMMPS server (e.g. {"cores": 4}).

None
equilibration_steps int

Length of the constant-volume equilibration stage in MD steps (use a small value for quick demos, the default for production-quality runs).

100000
thermostat Thermostat

Thermostat of the equilibration and production runs, "nose_hoover" or "langevin".

required
seed int

Random seed for velocity initialization.

12345
tmp_working_directory str | Path | None

Directory for temporary simulation files.

None
max_lag int | None

Largest lag (frames) reported in the MSD.

None
remove_com_drift bool

Subtract the centre-of-mass drift before computing the MSD.

True
crossover_ps float

Log/linear crossover time in ps.

100.0
points_per_decade int

Decade-log dump points per decade below the crossover (9 → 1..9, 10..90, ...).

9
linear_interval_ps float

Uniform dump interval in ps above the crossover.

10.0
save_trajectory str | Path | None

If given, write the trajectory to this path (gzipped extXYZ when it ends in .gz) via :func:save_frames.

None

Returns:

Type Description
dict[str, Any]

Dict with "result" (parsed LAMMPS production output), "structure" (final Atoms),

dict[str, Any]

"frames" (trajectory), "msd" (:func:compute_msd output), "diffusion"

dict[str, Any]

(:func:get_diffusion output) and "trajectory_path" (or None).

Example
>>> out = diffusion_simulation(  # doctest: +SKIP
...     structure, potential, temperature_sim=3000.0, thermostat="nose_hoover"
... )
>>> out["diffusion"]["per_species"]["Na"]["diffusion_cm2_s"]  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
def diffusion_simulation(
    structure: Atoms,
    potential: pd.DataFrame,
    temperature_sim: float = 3000.0,
    timestep: float = 1.0,
    production_steps: int = 1_000_000,
    n_print_thermo: int = 100,
    server_kwargs: dict[str, Any] | None = None,
    *,
    equilibration_steps: int = 100_000,
    thermostat: Thermostat,
    seed: int = 12345,
    tmp_working_directory: str | Path | None = None,
    max_lag: int | None = None,
    remove_com_drift: bool = True,
    crossover_ps: float = 100.0,
    points_per_decade: int = 9,
    linear_interval_ps: float = 10.0,
    save_trajectory: str | Path | None = None,
) -> dict[str, Any]:
    """Run an MD production trajectory and compute self-diffusion from the MSD.

    Equilibrates the structure (Langevin then NVT) and runs an NVT production stage that dumps on a
    **log-then-linear** schedule to keep the trajectory small: decade-log below *crossover_ps* (with
    the default ``points_per_decade=9`` the dumped steps are 1, 2, ..., 9, 10, 20, ..., 90, 100, ...)
    and uniform every *linear_interval_ps* above it. The MSD is computed single-origin (the non-uniform
    grid cannot use a multi-time-origin FFT estimator).

    Equilibration and production are run at constant volume, so the simulation keeps the density of
    the input structure. Pass a structure pre-equilibrated at the desired density/pressure to control it.

    Args:
        structure: Input structure (a melt or pre-equilibrated glass); its cell sets the run density.
        potential: LAMMPS potential as a pandas DataFrame.
        temperature_sim: Production temperature in Kelvin.
        timestep: MD timestep in femtoseconds.
        production_steps: Number of MD steps in the production stage.
        n_print_thermo: Thermo/log output interval in MD steps.
        server_kwargs: Additional arguments for the LAMMPS server (e.g. ``{"cores": 4}``).
        equilibration_steps: Length of the constant-volume equilibration stage in MD steps
            (use a small value for quick demos, the default for production-quality runs).
        thermostat: Thermostat of the equilibration and production runs, ``"nose_hoover"`` or ``"langevin"``.
        seed: Random seed for velocity initialization.
        tmp_working_directory: Directory for temporary simulation files.
        max_lag: Largest lag (frames) reported in the MSD.
        remove_com_drift: Subtract the centre-of-mass drift before computing the MSD.
        crossover_ps: Log/linear crossover time in ps.
        points_per_decade: Decade-log dump points per decade below the crossover (9 → 1..9, 10..90, ...).
        linear_interval_ps: Uniform dump interval in ps above the crossover.
        save_trajectory: If given, write the trajectory to this path (gzipped extXYZ when it ends in
            ``.gz``) via :func:`save_frames`.

    Returns:
        Dict with ``"result"`` (parsed LAMMPS production output), ``"structure"`` (final Atoms),
        ``"frames"`` (trajectory), ``"msd"`` (:func:`compute_msd` output), ``"diffusion"``
        (:func:`get_diffusion` output) and ``"trajectory_path"`` (or ``None``).

    Example:
        ```pycon
        >>> out = diffusion_simulation(  # doctest: +SKIP
        ...     structure, potential, temperature_sim=3000.0, thermostat="nose_hoover"
        ... )
        >>> out["diffusion"]["per_species"]["Na"]["diffusion_cm2_s"]  # doctest: +SKIP

        ```
    """
    if potential.empty:
        msg = "No matching potential found for the given configuration."
        raise ValueError(msg)

    nvt_ensemble, _ = thermostat_ensembles(thermostat)
    structure0, _ = _run_lammps_md(
        structure=structure,
        potential=potential,
        tmp_working_directory=tmp_working_directory,
        temperature=temperature_sim,
        n_ionic_steps=10_000,
        timestep=timestep,
        n_print_thermo=1000,
        initial_temperature=temperature_sim,
        ensemble="nvt_langevin",
        seed=seed,
        server_kwargs=server_kwargs,
    )

    # NVT (constant volume) equilibration: it preserves the input density. A zero-pressure NPT stage
    # is deliberately avoided here because at high melt temperatures it lets the box expand without
    # bound (vaporisation), leaving the production stage with non-interacting, free-flying atoms and a
    # spurious ballistic MSD. To run at a relaxed density, pass a pre-equilibrated structure instead.
    structure1, _ = _run_lammps_md(
        structure=structure0,
        potential=potential,
        tmp_working_directory=tmp_working_directory,
        temperature=temperature_sim,
        n_ionic_steps=equilibration_steps,
        timestep=timestep,
        n_print_thermo=1000,
        initial_temperature=temperature_sim,
        ensemble=nvt_ensemble,
        seed=seed,
        server_kwargs=server_kwargs,
    )

    crossover_steps = round(crossover_ps * 1000.0 / timestep)
    linear_interval_steps = max(1, round(linear_interval_ps * 1000.0 / timestep))
    schedule = log_linear_dump_steps(
        production_steps,
        crossover_steps=crossover_steps,
        points_per_decade=points_per_decade,
        linear_interval_steps=linear_interval_steps,
    )
    variable_line = _log_linear_dump_variable(crossover_steps, points_per_decade, linear_interval_steps)
    # The variable is placed first in the Config (before LAMMPS' dump line) and reset_timestep last,
    # so the schedule references a production timestep starting at 0.
    production_potential = potential.copy()
    production_potential["Config"] = production_potential["Config"].apply(
        lambda lines: [variable_line, *list(lines), "reset_timestep 0"]
    )

    structure_final, parsed_output = _run_lammps_md(
        structure=structure1,
        potential=production_potential,
        tmp_working_directory=tmp_working_directory,
        temperature=temperature_sim,
        n_ionic_steps=production_steps,
        timestep=timestep,
        n_print_thermo=n_print_thermo,
        initial_temperature=0,
        ensemble=nvt_ensemble,
        server_kwargs=server_kwargs,
        input_control_file={"dump_modify": "1 every v_amx_dump first yes sort id"},
    )

    result = parsed_output.get("generic", None)
    frames = frames_from_melt_quench_result({"structure": structure_final, "result": [result]}, structure)

    # The parser overwrites the dump-frame steps with thermo steps, so assign the exact dump times from
    # the (bit-identical) Python schedule. Align defensively if the frame count differs.
    n_assign = min(len(frames), len(schedule))
    if len(frames) != len(schedule):
        warnings.warn(
            f"log_linear dump produced {len(frames)} frames but the schedule has {len(schedule)}; "
            "using the overlapping frames.",
            stacklevel=2,
        )
    frames = frames[:n_assign]
    for frame, step in zip(frames, schedule[:n_assign], strict=False):
        frame.info["step"] = step

    msd = compute_msd(
        frames, timestep=timestep, max_lag=max_lag, remove_com_drift=remove_com_drift, method="single_origin"
    )
    diffusion = get_diffusion(msd)

    trajectory_path = str(save_frames(frames, save_trajectory)) if save_trajectory is not None else None

    return {
        "result": result,
        "structure": structure_final,
        "frames": frames,
        "msd": msd,
        "diffusion": diffusion,
        "trajectory_path": trajectory_path,
    }

elastic_simulation(structure: Atoms, potential: pd.DataFrame, temperature_sim: float = 300.0, npt_pressure: float | None = None, timestep: float = 1.0, equilibration_steps: int = 1000000, production_steps: int = 10000, n_dump: int | None = None, n_print_thermo: int | None = 1, strain: float = 0.001, server_kwargs: dict[str, Any] | None = None, *, ensemble: Ensemble, seed: int = 12345, tmp_working_directory: str | Path | None = None) -> dict[str, Any]

Perform a LAMMPS-based elastic constant simulation via the stress-strain method.

This workflow calculates the elastic stiffness tensor (Cij) using finite differences. It equilibrates the structure, applies small normal and shear strains, and measures the resulting stress response to determine the elastic constants.

Parameters:

Name Type Description Default
structure Atoms

Input structure (assumed pre-equilibrated).

required
potential DataFrame

LAMMPS potential file.

required
temperature_sim float

Simulation temperature in Kelvin (default 300.0 K).

300.0
npt_pressure float | None

Target pressure in GPa. Required for the "npt" and "npt_langevin" ensembles, not allowed otherwise.

None
timestep float

MD integration timestep in femtoseconds (default 1.0 fs).

1.0
equilibration_steps int

Number of steps for the initial equilibration phase (default 1,000,000).

1000000
production_steps int

Number of MD steps for the production run (default 10,000).

10000
n_dump int | None

Dump output frequency (default None, i.e., dump only at final step).

None
n_print_thermo int | None

Thermodynamic output frequency (default 1).

1
strain float

Magnitude of the strain applied for finite differences (default 1e-3).

0.001
server_kwargs dict[str, Any] | None

Additional server configuration arguments.

None
ensemble Ensemble

Ensemble of the equilibration and production runs, one of "nvt", "npt", "nvt_langevin" or "npt_langevin".

required
seed int

Random seed for velocity initialization (default 12345).

12345
tmp_working_directory str | Path | None

Temporary directory for job execution.

None

Returns:

Type Description
dict[str, Any]

Dictionary containing the results. Key "result" contains the "Cij" 6x6 matrix.

Raises:

Type Description
ValueError

If ensemble is "nve", or npt_pressure does not fit ensemble.

Notes
  • The structure is first equilibrated (NPT/NVT).
  • Positive and negative strains are applied to cancel lower-order errors (central difference).
  • Calculated Cij values assume Voigt notation.
  • For production simulations, system size, cooling rate, equilibration time, and strain magnitude should be tested to ensure the robustness of the results.
Example

result = elastic_simulation( ... structure=my_atoms, ... potential=my_potential, ... temperature_sim=300.0, ... ensemble="nvt", ... strain=0.001 ... )

Source code in amorphouspy/src/amorphouspy/properties/elastic.py
def elastic_simulation(
    structure: Atoms,
    potential: pd.DataFrame,
    temperature_sim: float = 300.0,
    npt_pressure: float | None = None,
    timestep: float = 1.0,
    equilibration_steps: int = 1_000_000,
    production_steps: int = 10_000,
    n_dump: int | None = None,
    n_print_thermo: int | None = 1,
    strain: float = 1e-3,
    server_kwargs: dict[str, Any] | None = None,
    *,
    ensemble: Ensemble,
    seed: int = 12345,
    tmp_working_directory: str | Path | None = None,
) -> dict[str, Any]:  # pylint: disable=too-many-positional-arguments
    """Perform a LAMMPS-based elastic constant simulation via the stress-strain method.

    This workflow calculates the elastic stiffness tensor (Cij) using finite differences.
    It equilibrates the structure, applies small normal and shear strains, and measures
    the resulting stress response to determine the elastic constants.

    Args:
        structure: Input structure (assumed pre-equilibrated).
        potential: LAMMPS potential file.
        temperature_sim: Simulation temperature in Kelvin (default 300.0 K).
        npt_pressure: Target pressure in GPa. Required for the ``"npt"`` and ``"npt_langevin"`` ensembles,
            not allowed otherwise.
        timestep: MD integration timestep in femtoseconds (default 1.0 fs).
        equilibration_steps: Number of steps for the initial equilibration phase (default 1,000,000).
        production_steps: Number of MD steps for the production run (default 10,000).
        n_dump: Dump output frequency (default None, i.e., dump only at final step).
        n_print_thermo: Thermodynamic output frequency (default 1).
        strain: Magnitude of the strain applied for finite differences (default 1e-3).
        server_kwargs: Additional server configuration arguments.
        ensemble: Ensemble of the equilibration and production runs, one of ``"nvt"``, ``"npt"``,
            ``"nvt_langevin"`` or ``"npt_langevin"``.
        seed: Random seed for velocity initialization (default 12345).
        tmp_working_directory: Temporary directory for job execution.

    Returns:
        Dictionary containing the results. Key "result" contains the "Cij" 6x6 matrix.

    Raises:
        ValueError: If ``ensemble`` is ``"nve"``, or ``npt_pressure`` does not fit ``ensemble``.

    Notes:
        - The structure is first equilibrated (NPT/NVT).
        - Positive and negative strains are applied to cancel lower-order errors (central difference).
        - Calculated Cij values assume Voigt notation.
        - For production simulations, system size, cooling rate, equilibration time,
        and strain magnitude should be tested to ensure the robustness of the results.

    Example:
        >>> result = elastic_simulation(
        ...     structure=my_atoms,
        ...     potential=my_potential,
        ...     temperature_sim=300.0,
        ...     ensemble="nvt",
        ...     strain=0.001
        ... )

    """
    if ensemble == "nve":
        msg = "elastic_simulation needs a thermostat; ensemble 'nve' is not supported."
        raise ValueError(msg)

    # Stage 0: INITIAL EQUILIBRATION
    structure0, res = _run_lammps_md(
        structure=structure,
        potential=potential,
        tmp_working_directory=tmp_working_directory,
        temperature=temperature_sim,
        n_ionic_steps=equilibration_steps,
        timestep=timestep,
        initial_temperature=temperature_sim,
        npt_pressure=npt_pressure,
        seed=seed,
        ensemble=ensemble,
        server_kwargs=server_kwargs,
        n_dump=n_dump,
        n_print_thermo=n_print_thermo,
    )

    structure_npt = structure0.copy()

    # Enforce cubic average cell

    gen0 = res.get("generic")
    assert gen0 is not None
    vol_array = np.array(gen0["volume"])
    slice_start = len(vol_array) // 2
    avg_l = np.mean(vol_array[slice_start:]) ** (1.0 / 3.0)

    structure_npt.set_cell([[avg_l, 0, 0], [0, avg_l, 0], [0, 0, avg_l]], scale_atoms=True)

    # Shared settings for all production runs
    md_kwargs = {
        "potential": potential,
        "tmp_working_directory": tmp_working_directory,
        "temperature": temperature_sim,
        "n_ionic_steps": production_steps,
        "timestep": timestep,
        "initial_temperature": temperature_sim,
        "npt_pressure": npt_pressure,
        "ensemble": ensemble,
        "seed": seed,
        "server_kwargs": server_kwargs,
        "n_dump": n_dump,
        "n_print_thermo": n_print_thermo,
    }

    cij = np.zeros((6, 6))
    denom = 2 * strain

    # Normal strains (C11, C22, C33 and off-diagonals)
    for i in range(3):
        strain_mat = np.zeros((3, 3))
        strain_mat[i, i] = strain
        stress_diff = _run_strained_md(structure_npt, strain_mat, md_kwargs)
        cij[i, 0] = stress_diff[0, 0] / denom
        cij[i, 1] = stress_diff[1, 1] / denom
        cij[i, 2] = stress_diff[2, 2] / denom

    # Shear strains (C44, C55, C66)
    shear_indices = [(1, 2), (0, 2), (0, 1)]  # yz, xz, xy
    for i, (idx1, idx2) in enumerate(shear_indices):
        strain_mat = np.zeros((3, 3))
        strain_mat[idx1, idx2] = strain / 2
        strain_mat[idx2, idx1] = strain / 2
        stress_diff = _run_strained_md(structure_npt, strain_mat, md_kwargs)
        voigt = 3 + i
        cij[voigt, voigt] = stress_diff[idx1, idx2] / denom

    moduli = isotropic_moduli_from_Cij(cij)

    result = {"Cij": cij, "moduli": moduli}

    # After calculating all Cij
    if not np.allclose(cij[0, 0], cij[1, 1]) or not np.allclose(cij[1, 1], cij[2, 2]):
        warnings.warn("System may not be cubic: C11 != C22 != C33", stacklevel=2)
    if not np.allclose(cij[3, 3], cij[4, 4]) or not np.allclose(cij[4, 4], cij[5, 5]):
        warnings.warn("System may not be cubic: C44 != C55 != C66", stacklevel=2)

    return result

extract_composition(composition: dict[str, float], tolerance: float = COMPOSITION_TOLERANCE) -> dict[str, float]

Validate and normalize a composition dictionary.

Handles both fractional (0.0-1.0) and percentage (0-100) inputs. Always returns fractions summing to 1.0.

Parameters:

Name Type Description Default
composition dict[str, float]

A dictionary mapping oxide formulas to their fractions, e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}.

required
tolerance float

Maximum allowed fractional deviation from 1.0. Defaults to COMPOSITION_TOLERANCE.

COMPOSITION_TOLERANCE

Returns:

Type Description
dict[str, float]

A dictionary mapping oxide formulas to their molar fractions.

Raises:

Type Description
ValueError

If the composition is empty, contains invalid elements, non-neutral oxides, or sums to an invalid total.

Source code in amorphouspy/src/amorphouspy/fabrication/composition.py
def extract_composition(
    composition: dict[str, float],
    tolerance: float = COMPOSITION_TOLERANCE,
) -> dict[str, float]:
    """Validate and normalize a composition dictionary.

    Handles both fractional (0.0-1.0) and percentage (0-100) inputs. Always returns
    fractions summing to 1.0.

    Args:
        composition: A dictionary mapping oxide formulas to their fractions,
            e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}.
        tolerance: Maximum allowed fractional deviation from 1.0. Defaults to
            ``COMPOSITION_TOLERANCE``.

    Returns:
        A dictionary mapping oxide formulas to their molar fractions.

    Raises:
        ValueError: If the composition is empty, contains invalid elements,
            non-neutral oxides, or sums to an invalid total.

    """
    if not composition:
        error_msg = "Empty composition"
        raise ValueError(error_msg)

    valid_elements = set(chemical_symbols[1:])
    comp_dict = {}
    total = 0.0

    for oxide, frac in composition.items():
        if frac < 0:
            error_msg = f"Negative fraction for '{oxide}': {frac}"
            raise ValueError(error_msg)

        matches = ELEMENT.findall(oxide)
        for element, _ in matches:
            if element not in valid_elements:
                error_msg = f"Invalid element '{element}' in oxide '{oxide}'"
                raise ValueError(error_msg)

        check_neutral_oxide(oxide)

        comp_dict[oxide] = frac
        total += frac

    if total == 0:
        error_msg = "Total composition sum is zero"
        raise ValueError(error_msg)

    pct_tol = 100 * tolerance

    if abs(total - 100) <= pct_tol or abs(total - 1.0) <= tolerance:
        comp_dict = {oxide: frac / total for oxide, frac in comp_dict.items()}
    elif total > 100 + pct_tol:
        error_msg = f"Total exceeds 100% + {pct_tol}% tolerance: {total:.2f}%"
        raise ValueError(error_msg)
    elif total < 1.0 - tolerance:
        error_msg = f"Component sum ({total:.4f}) is less than allowed minimum"
        raise ValueError(error_msg)
    else:
        error_msg = f"Invalid composition sum ({total:.4f}). Expected ~100 mol% or ~1.0 fractional."
        raise ValueError(error_msg)

    return comp_dict

extract_equilibration_frames(final_structure: Atoms, simulation_history: list[dict[str, Any]] | None = None) -> list[Atoms]

Reconstruct Atoms snapshots from the final equilibration stage.

Falls back to a single-element list with final_structure when no simulation history is available or the history contains no position data.

Parameters:

Name Type Description Default
final_structure Atoms

The quenched structure from the melt-quench pipeline.

required
simulation_history list[dict[str, Any]] | None

Full stage-by-stage MD history (optional).

None

Returns:

Type Description
list[Atoms]

List of ASE Atoms frames suitable for averaging.

Source code in amorphouspy/src/amorphouspy/fabrication/meltquench.py
def extract_equilibration_frames(
    final_structure: Atoms,
    simulation_history: list[dict[str, Any]] | None = None,
) -> list[Atoms]:
    """Reconstruct Atoms snapshots from the final equilibration stage.

    Falls back to a single-element list with *final_structure* when no
    simulation history is available or the history contains no position data.

    Args:
        final_structure: The quenched structure from the melt-quench pipeline.
        simulation_history: Full stage-by-stage MD history (optional).

    Returns:
        List of ASE Atoms frames suitable for averaging.
    """
    if not simulation_history:
        return [final_structure]

    last_stage = next((s for s in reversed(simulation_history) if s is not None), None)
    if last_stage is None or "positions" not in last_stage:
        return [final_structure]

    positions = last_stage["positions"]
    cells = last_stage["cells"]
    n_frames = len(positions)

    if n_frames <= 1:
        return [final_structure]

    frames: list[Atoms] = []
    for i in range(n_frames):
        frame = final_structure.copy()
        frame.set_positions(positions[i])
        frame.set_cell(cells[i])
        frame.set_pbc(True)
        frame.wrap()
        frames.append(frame)

    return frames

find_rdf_minimum(r: np.ndarray, rdf_data: np.ndarray, sigma: float = 2.0, window_length: int = 21, polyorder: int = 3) -> float | None

Identify the first minimum in a radial distribution function (RDF) curve.

The function applies Gaussian and Savitzky-Golay smoothing to reduce noise, detects the first peak, and searches for the first subsequent minimum using gradient sign changes. If no valid minimum is found, it falls back to detecting where the RDF drops below 1.0 after the peak.

Parameters:

Name Type Description Default
r ndarray

Array of radial distances (Å), assumed to be uniformly spaced.

required
rdf_data ndarray

RDF values corresponding to r.

required
sigma float

Standard deviation for Gaussian smoothing.

2.0
window_length int

Window length for Savitzky-Golay filter. Must be odd.

21
polyorder int

Polynomial order for Savitzky-Golay filter.

3

Returns:

Type Description
float | None

The radial distance of the first minimum (Å) if found, otherwise None.

Example

r = np.linspace(0, 10, 100) rdf = np.sin(r) + 1.0 # Dummy data min_r = find_rdf_minimum(r, rdf)

Source code in amorphouspy/src/amorphouspy/properties/structural/all.py
def find_rdf_minimum(
    r: np.ndarray, rdf_data: np.ndarray, sigma: float = 2.0, window_length: int = 21, polyorder: int = 3
) -> float | None:
    """Identify the first minimum in a radial distribution function (RDF) curve.

    The function applies Gaussian and Savitzky-Golay smoothing to reduce noise,
    detects the first peak, and searches for the first subsequent minimum using
    gradient sign changes. If no valid minimum is found, it falls back to
    detecting where the RDF drops below 1.0 after the peak.

    Args:
        r: Array of radial distances (Å), assumed to be uniformly spaced.
        rdf_data: RDF values corresponding to `r`.
        sigma: Standard deviation for Gaussian smoothing.
        window_length: Window length for Savitzky-Golay filter. Must be odd.
        polyorder: Polynomial order for Savitzky-Golay filter.

    Returns:
        The radial distance of the first minimum (Å) if found, otherwise `None`.

    Example:
        >>> r = np.linspace(0, 10, 100)
        >>> rdf = np.sin(r) + 1.0  # Dummy data
        >>> min_r = find_rdf_minimum(r, rdf)

    """
    rdf_smooth1 = gaussian_filter1d(rdf_data, sigma=sigma)
    rdf_smooth2 = np.asarray(
        savgol_filter(rdf_smooth1, window_length=window_length, polyorder=polyorder),
        dtype=np.float64,
    )

    first_peak_idx = int(np.argmax(rdf_smooth2))
    dr = r[1] - r[0]  # assuming uniform spacing
    gradient = np.gradient(rdf_smooth2, dr)

    # PERF401 fix: list comprehension instead of appending in a loop
    sign_changes = [i for i in range(first_peak_idx + 1, len(gradient) - 1) if gradient[i] < 0 and gradient[i + 1] > 0]

    if sign_changes:
        first_min_idx = sign_changes[0]
        peak_height = rdf_smooth2[first_peak_idx]
        min_height = rdf_smooth2[first_min_idx]
        if (peak_height - min_height) > 0.1 * peak_height:
            return r[first_min_idx]

    for i in range(first_peak_idx + 1, len(rdf_smooth2)):
        if rdf_smooth2[i] < 1.0:
            return r[i]

    return None

fit_arrhenius(temperatures: NDArray[np.float64] | list[float], diffusivities: NDArray[np.float64] | list[float]) -> tuple[tuple[float, float], NDArray[np.float64]]

Fit an Arrhenius law D(T) = D0 * exp(-Ea / (kB T)) to diffusion data.

Performs a linear fit of ln D versus 1/T.

Parameters:

Name Type Description Default
temperatures NDArray[float64] | list[float]

Temperatures in Kelvin (length >= 2).

required
diffusivities NDArray[float64] | list[float]

Diffusion coefficients at each temperature (any consistent unit; D0 is returned in that same unit). Must be strictly positive.

required

Returns:

Type Description
tuple[float, float]

Tuple ((D0, Ea_eV), covariance) where Ea_eV is the activation energy in eV and

NDArray[float64]

covariance is the 2x2 covariance matrix of the linear fit.

Example

import numpy as np kb = 8.617333262e-5 temps = np.array([2000.0, 2500.0, 3000.0, 3500.0]) d0_true, ea_true = 1e-3, 1.2 d_vals = d0_true * np.exp(-ea_true / (kb * temps)) (d0, ea), _ = fit_arrhenius(temps, d_vals) bool(np.isclose(ea, ea_true, atol=1e-6)) True

Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
def fit_arrhenius(
    temperatures: NDArray[np.float64] | list[float],
    diffusivities: NDArray[np.float64] | list[float],
) -> tuple[tuple[float, float], NDArray[np.float64]]:
    """Fit an Arrhenius law ``D(T) = D0 * exp(-Ea / (kB T))`` to diffusion data.

    Performs a linear fit of ``ln D`` versus ``1/T``.

    Args:
        temperatures: Temperatures in Kelvin (length >= 2).
        diffusivities: Diffusion coefficients at each temperature (any consistent unit; ``D0`` is
            returned in that same unit). Must be strictly positive.

    Returns:
        Tuple ``((D0, Ea_eV), covariance)`` where ``Ea_eV`` is the activation energy in eV and
        ``covariance`` is the 2x2 covariance matrix of the linear fit.

    Example:
        >>> import numpy as np
        >>> kb = 8.617333262e-5
        >>> temps = np.array([2000.0, 2500.0, 3000.0, 3500.0])
        >>> d0_true, ea_true = 1e-3, 1.2
        >>> d_vals = d0_true * np.exp(-ea_true / (kb * temps))
        >>> (d0, ea), _ = fit_arrhenius(temps, d_vals)
        >>> bool(np.isclose(ea, ea_true, atol=1e-6))
        True
    """
    temperature = np.asarray(temperatures, dtype=float)
    diffusion = np.asarray(diffusivities, dtype=float)
    if temperature.size < _MIN_POINTS or diffusion.size != temperature.size:
        msg = "fit_arrhenius requires at least two matching (temperature, diffusivity) pairs."
        raise ValueError(msg)
    if np.any(diffusion <= 0) or np.any(temperature <= 0):
        msg = "Temperatures and diffusivities must be strictly positive for an Arrhenius fit."
        raise ValueError(msg)

    (slope, intercept), covariance = np.polyfit(1.0 / temperature, np.log(diffusion), 1, cov=True)
    activation_energy_ev = -slope * _KB_EV
    prefactor = float(np.exp(intercept))
    return (prefactor, float(activation_energy_ev)), covariance

fit_vft(T_data: ArrayLike, log10_eta_data: ArrayLike, initial_guess: tuple[float, float, float] = (-3, 1000, 200)) -> tuple[tuple[float, float, float], NDArray[np.float64]]

Fits viscosity data to the Vogel-Fulcher-Tammann (VFT) model.

Parameters:

Name Type Description Default
T_data ArrayLike

Temperatures in Kelvin.

required
log10_eta_data ArrayLike

log10(viscosity) values.

required
initial_guess tuple[float, float, float]

Initial guess for (log10_eta0, B, T0).

(-3, 1000, 200)

Returns:

Type Description
tuple[tuple[float, float, float], NDArray[float64]]

A tuple containing the best-fit parameters and the covariance matrix.

Example

params, cov = fit_vft(temps, log_visc_data) log10_eta0, B, T0 = params

Source code in amorphouspy/src/amorphouspy/properties/viscosity.py
def fit_vft(
    T_data: ArrayLike, log10_eta_data: ArrayLike, initial_guess: tuple[float, float, float] = (-3, 1000, 200)
) -> tuple[tuple[float, float, float], NDArray[np.float64]]:
    """Fits viscosity data to the Vogel-Fulcher-Tammann (VFT) model.

    Args:
        T_data: Temperatures in Kelvin.
        log10_eta_data: log10(viscosity) values.
        initial_guess: Initial guess for (log10_eta0, B, T0).

    Returns:
        A tuple containing the best-fit parameters and the covariance matrix.

    Example:
        >>> params, cov = fit_vft(temps, log_visc_data)
        >>> log10_eta0, B, T0 = params

    """
    popt, pcov = curve_fit(vft_model, T_data, log10_eta_data, p0=initial_guess, maxfev=1000000)
    return popt, pcov

formula_mass_g_per_mol(formula: str) -> float

Calculate the molar mass of a compound using ASE atomic masses.

Parameters:

Name Type Description Default
formula str

A string representing the chemical formula (e.g., "SiO2").

required

Returns:

Type Description
float

The molar mass of the compound in grams per mole.

Source code in amorphouspy/src/amorphouspy/fabrication/composition.py
def formula_mass_g_per_mol(formula: str) -> float:
    """Calculate the molar mass of a compound using ASE atomic masses.

    Args:
        formula: A string representing the chemical formula (e.g., "SiO2").

    Returns:
        The molar mass of the compound in grams per mole.

    """
    return sum(get_atomic_mass(el) * cnt for el, cnt in parse_formula(formula).items())

frames_from_melt_quench_result(result: dict, initial_structure: Atoms, *, stage: int = -1, stride: int = 1) -> list[Atoms]

Extract trajectory frames from a melt_quench_simulation result dict.

Parameters:

Name Type Description Default
result dict

The dict returned by :func:melt_quench_simulation (keys "structure" and "result").

required
initial_structure Atoms

The Atoms object passed as input to the simulation. It carries the correct atomic numbers, which are used to label each frame.

required
stage int

Index into result["result"] selecting which protocol stage to extract. Defaults to -1 (the final low-temperature equilibration).

-1
stride int

Take every stride-th frame. Defaults to 1 (all frames).

1

Returns:

Type Description
list[Atoms]

A list of :class:ase.Atoms objects, one per selected frame, with

list[Atoms]

per-frame thermo data stored in atoms.info and per-atom arrays

list[Atoms]

(forces, velocities, unwrapped positions) in atoms.arrays.

Example

result = melt_quench_simulation(atoms, potential, thermostat="nose_hoover") frames = frames_from_melt_quench_result(result, atoms) (r, rdfs_mean, cumcn_mean, rdfs_sem, cumcn_sem), _ = average_over_frames( ... compute_rdf, frames, r_max=8.0 ... )

Source code in amorphouspy/src/amorphouspy/lammps/io.py
def frames_from_melt_quench_result(
    result: dict,
    initial_structure: Atoms,
    *,
    stage: int = -1,
    stride: int = 1,
) -> list[Atoms]:
    """Extract trajectory frames from a ``melt_quench_simulation`` result dict.

    Args:
        result: The dict returned by :func:`melt_quench_simulation`
            (keys ``"structure"`` and ``"result"``).
        initial_structure: The ``Atoms`` object passed as input to the simulation.
            It carries the correct atomic numbers, which are used to label each frame.
        stage: Index into ``result["result"]`` selecting which protocol stage to
            extract. Defaults to ``-1`` (the final low-temperature equilibration).
        stride: Take every *stride*-th frame. Defaults to ``1`` (all frames).

    Returns:
        A list of :class:`ase.Atoms` objects, one per selected frame, with
        per-frame thermo data stored in ``atoms.info`` and per-atom arrays
        (forces, velocities, unwrapped positions) in ``atoms.arrays``.

    Example:
        >>> result = melt_quench_simulation(atoms, potential, thermostat="nose_hoover")
        >>> frames = frames_from_melt_quench_result(result, atoms)
        >>> (r, rdfs_mean, cumcn_mean, rdfs_sem, cumcn_sem), _ = average_over_frames(
        ...     compute_rdf, frames, r_max=8.0
        ... )

    """
    stage_data = result["result"][stage]
    n_frames = len(stage_data["positions"])
    indices = range(0, n_frames, stride)
    frames: list[Atoms] = []
    for i in indices:
        atoms = initial_structure.copy()
        atoms.set_positions(stage_data["positions"][i])
        atoms.set_cell(stage_data["cells"][i])
        atoms.set_pbc(True)
        if "velocities" in stage_data:
            atoms.set_velocities(stage_data["velocities"][i])
        if "indices" in stage_data:
            atoms.set_array("indices", stage_data["indices"][i])
        # Thermo-derived scalars are logged on a separate (thermo) cadence, so they can be shorter than
        # the per-frame dump arrays (e.g. with a log-spaced dump schedule); guard each access.
        for info_key, data_key in (
            ("temperature", "temperature"),
            ("energy_pot", "energy_pot"),
            ("energy_tot", "energy_tot"),
            ("volume", "volume"),
            ("pressure", "pressures"),
            ("step", "steps"),
        ):
            if data_key in stage_data and i < len(stage_data[data_key]):
                atoms.info[info_key] = stage_data[data_key][i]
        if "forces" in stage_data:
            atoms.arrays["forces"] = stage_data["forces"][i]
        if "unwrapped_positions" in stage_data:
            atoms.arrays["unwrapped_positions"] = stage_data["unwrapped_positions"][i]
        frames.append(atoms)
    return frames

generate_bond_length_dict(atoms: Atoms, specific_cutoffs: dict[tuple[str, str], float] | None = None, default_cutoff: float = 0.0) -> dict[tuple[str, str], float]

Generate all symmetric element pairs and assign bond length cutoffs.

Parameters:

Name Type Description Default
atoms Atoms

ASE Atoms object whose species determine the pair set.

required
specific_cutoffs dict[tuple[str, str], float] | None

Optional cutoff overrides for specific element pairs. Both orderings ('A','B') and ('B','A') are recognised.

None
default_cutoff float

Fallback bond length for pairs not in specific_cutoffs. The default of 0.0 marks every unlisted pair as never bonded, so only the pairs named in specific_cutoffs can form a bond.

0.0

Returns:

Type Description
dict[tuple[str, str], float]

Dictionary mapping every symmetric element pair to its cutoff.

Examples:

>>> from ase.io import read
>>> structure = read('glass.xyz')
>>> bond_lengths = generate_bond_length_dict(
...     structure,
...     specific_cutoffs={('Si', 'O'): 1.8},
...     default_cutoff=2.0,
... )
Source code in amorphouspy/src/amorphouspy/properties/structural/rings.py
def generate_bond_length_dict(
    atoms: Atoms,
    specific_cutoffs: dict[tuple[str, str], float] | None = None,
    default_cutoff: float = 0.0,
) -> dict[tuple[str, str], float]:
    """Generate all symmetric element pairs and assign bond length cutoffs.

    Args:
        atoms: ASE Atoms object whose species determine the pair set.
        specific_cutoffs: Optional cutoff overrides for specific element
            pairs. Both orderings ``('A','B')`` and ``('B','A')`` are
            recognised.
        default_cutoff: Fallback bond length for pairs not in
            ``specific_cutoffs``. The default of 0.0 marks every unlisted
            pair as never bonded, so only the pairs named in
            ``specific_cutoffs`` can form a bond.

    Returns:
        Dictionary mapping every symmetric element pair to its cutoff.

    Examples:
        >>> from ase.io import read
        >>> structure = read('glass.xyz')
        >>> bond_lengths = generate_bond_length_dict(
        ...     structure,
        ...     specific_cutoffs={('Si', 'O'): 1.8},
        ...     default_cutoff=2.0,
        ... )
    """
    if specific_cutoffs is None:
        specific_cutoffs = {}

    atomic_numbers = atoms.get_atomic_numbers()
    type_dict = type_to_dict(atomic_numbers)
    elements = list(type_dict.values())
    bond_dict: dict[tuple[str, str], float] = {}

    for element_a, element_b in combinations_with_replacement(elements, 2):
        cutoff = specific_cutoffs.get(
            (element_a, element_b),
            specific_cutoffs.get((element_b, element_a), default_cutoff),
        )
        bond_dict[(element_a, element_b)] = cutoff

    return bond_dict

generate_potential(atoms_dict: dict, potential_type: str = 'pmmcs', *, electrostatics: InteractionConfig | None = None, use_three_body: bool = False, model_path: str | Path | None = None) -> pd.DataFrame

Generate LAMMPS potential configuration for glass simulations.

Parameters:

Name Type Description Default
atoms_dict dict

Structure dict from get_structure_dict().

required
potential_type str

One of "pmmcs", "bjp", "shik", "du_teter", "bmp-harmonic", "bmp-screened-harmonic", "yang2026", or "grace".

'pmmcs'
electrostatics InteractionConfig | None

Coulomb solver settings. Defaults to DSF with each potential's built-in cutoffs and damping parameter.

None
use_three_body bool

For du_teter potential, include Stillinger-Weber three-body terms for O-P-O / P-O-P interactions (requires P in composition). No effect for other potentials.

False
model_path str | Path | None

For the grace potential, an explicit path to an already-exported native GRACE-FS YAML file; None uses the default cache location. Only valid when potential_type="grace".

None

Returns:

Type Description
DataFrame

DataFrame with columns Name, Filename, Model, Species, Config.

Raises:

Type Description
ValueError

If use_three_body is True for a non-du_teter potential, or if model_path is given for a non-grace potential.

Example

potential = generate_potential(struct_dict, potential_type="shik") potential = generate_potential(struct_dict, potential_type="bmp-harmonic") potential = generate_potential(struct_dict, potential_type="bmp-screened-harmonic") potential = generate_potential(struct_dict, potential_type="du_teter", use_three_body=True) potential = generate_potential(struct_dict, potential_type="yang2026") potential = generate_potential(struct_dict, potential_type="grace") potential = generate_potential(struct_dict, potential_type="grace", model_path="/data/models/FS_model.yaml")

Source code in amorphouspy/src/amorphouspy/lammps/potentials/potential.py
def generate_potential(  # noqa: PLR0911
    atoms_dict: dict,
    potential_type: str = "pmmcs",
    *,
    electrostatics: InteractionConfig | None = None,
    use_three_body: bool = False,
    model_path: str | Path | None = None,
) -> pd.DataFrame:
    """Generate LAMMPS potential configuration for glass simulations.

    Args:
        atoms_dict: Structure dict from ``get_structure_dict()``.
        potential_type: One of ``"pmmcs"``, ``"bjp"``, ``"shik"``, ``"du_teter"``,
            ``"bmp-harmonic"``, ``"bmp-screened-harmonic"``, ``"yang2026"``, or ``"grace"``.
        electrostatics: Coulomb solver settings. Defaults to DSF with each
            potential's built-in cutoffs and damping parameter.
        use_three_body: For du_teter potential, include Stillinger-Weber three-body
            terms for O-P-O / P-O-P interactions (requires P in composition).
            No effect for other potentials.
        model_path: For the grace potential, an explicit path to an already-exported
            native GRACE-FS YAML file; None uses the default cache location. Only valid
            when ``potential_type="grace"``.

    Returns:
        DataFrame with columns Name, Filename, Model, Species, Config.

    Raises:
        ValueError: If use_three_body is True for a non-du_teter potential, or if
            model_path is given for a non-grace potential.

    Example:
        >>> potential = generate_potential(struct_dict, potential_type="shik")
        >>> potential = generate_potential(struct_dict, potential_type="bmp-harmonic")
        >>> potential = generate_potential(struct_dict, potential_type="bmp-screened-harmonic")
        >>> potential = generate_potential(struct_dict, potential_type="du_teter", use_three_body=True)
        >>> potential = generate_potential(struct_dict, potential_type="yang2026")
        >>> potential = generate_potential(struct_dict, potential_type="grace")
        >>> potential = generate_potential(struct_dict, potential_type="grace", model_path="/data/models/FS_model.yaml")

    """
    # Validate that use_three_body is only set for du_teter potentials
    if use_three_body and potential_type.lower() not in ("du_teter", "du_teter_dbx_generalized"):
        msg = f"use_three_body is only supported for du_teter potential, got '{potential_type}'"
        raise ValueError(msg)

    if model_path is not None and potential_type.lower() != "grace":
        msg = f"model_path is only supported for the grace potential, got '{potential_type}'"
        raise ValueError(msg)

    if potential_type.lower() == "pmmcs":
        return pmmcs.generate_pmmcs_potential(atoms_dict, electrostatics=electrostatics)
    if potential_type.lower() == "bjp":
        return bjp.generate_bjp_potential(atoms_dict, electrostatics=electrostatics)
    if potential_type.lower() == "shik":
        return shik.generate_shik_potential(atoms_dict, electrostatics=electrostatics)
    if potential_type.lower() in ("du_teter", "du_teter_dbx_generalized"):
        n4_model = "dbx_generalized" if potential_type.lower() == "du_teter_dbx_generalized" else "dbx"
        return du_teter.generate_du_teter_potential(atoms_dict, n4_model=n4_model, use_three_body=use_three_body)
    if potential_type.lower() in ("bmp-harmonic", "bmp-screened-harmonic"):
        variant = "harmonic" if potential_type.lower() == "bmp-harmonic" else "screened-harmonic"
        return bmp.generate_bmp_potential(atoms_dict, variant=variant, electrostatics=electrostatics)
    if potential_type.lower() == "yang2026":
        return yang2026.generate_yang2026_potential(atoms_dict, electrostatics=electrostatics)
    if potential_type.lower() == "grace":
        return grace.generate_grace_potential(atoms_dict, model_path=model_path)
    msg = f"Unsupported potential type: {potential_type}"
    raise ValueError(msg)

generate_structure(composition: dict[str, float], n_atoms: int = 6000, potential_type: str = 'pmmcs', density: float | None = None, structure_seed: int = 42, *, electrostatics_config: InteractionConfig | None = None, use_three_body: bool = False, model_path: str | Path | None = None) -> dict[str, Any]

Generate an initial random structure and matching LAMMPS potential.

Parameters:

Name Type Description Default
composition dict[str, float]

Oxide composition as {oxide: mol%}.

required
n_atoms int

Target number of atoms.

6000
potential_type str

Name of the interatomic potential to generate.

'pmmcs'
density float | None

Target density in g/cm³; None uses the Fluegel model.

None
structure_seed int

Random seed for atom placement.

42
electrostatics_config InteractionConfig | None

Electrostatics configuration (e.g. DsfConfig).

None
use_three_body bool

For du_teter potential, include Stillinger-Weber three-body terms for O-P-O / P-O-P interactions (requires P in composition).

False
model_path str | Path | None

For the grace potential, an explicit path to an already-exported native GRACE-FS YAML file. Only valid when potential_type="grace".

None

Returns:

Type Description
dict[str, Any]

Dict with atoms_dict, structure (ASE Atoms), and potential.

Source code in amorphouspy/src/amorphouspy/pipelines/meltquench.py
def generate_structure(
    composition: dict[str, float],
    n_atoms: int = 6000,
    potential_type: str = "pmmcs",
    density: float | None = None,
    structure_seed: int = 42,
    *,
    electrostatics_config: InteractionConfig | None = None,
    use_three_body: bool = False,
    model_path: str | Path | None = None,
) -> dict[str, Any]:
    """Generate an initial random structure and matching LAMMPS potential.

    Args:
        composition: Oxide composition as ``{oxide: mol%}``.
        n_atoms: Target number of atoms.
        potential_type: Name of the interatomic potential to generate.
        density: Target density in g/cm³; ``None`` uses the Fluegel model.
        structure_seed: Random seed for atom placement.
        electrostatics_config: Electrostatics configuration (e.g. ``DsfConfig``).
        use_three_body: For du_teter potential, include Stillinger-Weber three-body
            terms for O-P-O / P-O-P interactions (requires P in composition).
        model_path: For the grace potential, an explicit path to an already-exported
            native GRACE-FS YAML file. Only valid when ``potential_type="grace"``.

    Returns:
        Dict with ``atoms_dict``, ``structure`` (ASE Atoms), and ``potential``.
    """
    atoms_dict = get_structure_dict(
        composition=composition,
        target_atoms=n_atoms,
        density=density,
        random_seed=structure_seed,
    )
    structure = get_ase_structure(atoms_dict=atoms_dict)
    potential = generate_potential(
        atoms_dict=atoms_dict,
        potential_type=potential_type,
        electrostatics=electrostatics_config,
        use_three_body=use_three_body,
        model_path=model_path,
    )

    return {
        "atoms_dict": atoms_dict,
        "structure": structure,
        "potential": potential,
    }

get_ase_structure(atoms_dict: dict, replicate: tuple[int, int, int] = (1, 1, 1)) -> Atoms

Generate a LAMMPS data file format string and read into an ASE Atoms object.

Based on the specifications in the provided atoms_dict, this function generates a LAMMPS data file format string, which is then read into an ASE Atoms object. The ASE Atoms object is then returned. atoms_dict is expected to specify a cubic box. Triclinic boxes are not supported.

Parameters:

Name Type Description Default
atoms_dict dict

Dictionary that must contain the atom counts and box dimensions under the keys "atoms" and "box".

required
replicate tuple[int, int, int]

Replication factors for the box in x, y, and z directions. Default is (1, 1, 1), meaning no replication.

(1, 1, 1)

Returns:

Type Description
Atoms

ASE Atoms object of the specified structure.

Example

struct_dict = get_structure_dict({"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}, target_atoms=1000) atoms = get_ase_structure(struct_dict)

Source code in amorphouspy/src/amorphouspy/fabrication/geometry.py
def get_ase_structure(atoms_dict: dict, replicate: tuple[int, int, int] = (1, 1, 1)) -> Atoms:
    """Generate a LAMMPS data file format string and read into an ASE Atoms object.

    Based on the specifications in the provided atoms_dict,
    this function generates a LAMMPS data file
    format string, which is then read into an ASE Atoms object.
    The ASE Atoms object is then returned.
    atoms_dict is expected to specify a cubic box.
    Triclinic boxes are not supported.

    Args:
        atoms_dict: Dictionary that must contain the atom counts and box dimensions under the
            keys "atoms" and "box".
        replicate: Replication factors for the box in x, y, and z directions.
            Default is (1, 1, 1), meaning no replication.

    Returns:
        ASE Atoms object of the specified structure.

    Example:
        >>> struct_dict = get_structure_dict({"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}, target_atoms=1000)
        >>> atoms = get_ase_structure(struct_dict)

    """
    atoms = atoms_dict["atoms"]
    box_length = atoms_dict["box"]
    nx, ny, nz = replicate
    n_atoms_orig = len(atoms)

    element_to_type = get_element_types_dict(atoms)
    n_types = len(element_to_type)

    list_of_lines = []
    list_of_lines.append("LAMMPS data file via create_random_atoms and write_lammps_data\n\n")

    n_atoms = n_atoms_orig * nx * ny * nz
    list_of_lines.append(f"{n_atoms} atoms\n")
    list_of_lines.append(f"{n_types} atom types\n\n")

    new_box_length_x = box_length * nx
    new_box_length_y = box_length * ny
    new_box_length_z = box_length * nz

    list_of_lines.append(f"0.0 {new_box_length_x} xlo xhi\n")
    list_of_lines.append(f"0.0 {new_box_length_y} ylo yhi\n")
    list_of_lines.append(f"0.0 {new_box_length_z} zlo zhi\n\n")

    list_of_lines.append("Masses\n\n")
    for elem, type_id in element_to_type.items():
        mass = get_atomic_mass(elem)
        list_of_lines.append(f"{type_id} {mass} # {elem}\n")

    list_of_lines.append("\nAtoms\n\n")

    atom_id = 1
    for ix in range(nx):
        for iy in range(ny):
            for iz in range(nz):
                for atom in atoms:
                    elem = atom["element"]
                    type_id = element_to_type[elem]
                    x, y, z = atom["position"]
                    x_shifted = x + ix * box_length
                    y_shifted = y + iy * box_length
                    z_shifted = z + iz * box_length
                    q = 0.0
                    list_of_lines.append(
                        f"{atom_id} {type_id} {q:.6f} {x_shifted:.6f} {y_shifted:.6f} {z_shifted:.6f}\n"
                    )
                    atom_id += 1

    atoms_obj = read(
        filename=StringIO("".join(list_of_lines)),
        format="lammps-data",
        atom_style="charge",
    )
    if isinstance(atoms_obj, list):
        return cast("Atoms", atoms_obj[0])
    return atoms_obj

get_atomic_mass(element: str | int) -> float

Get the atomic mass of an element.

Parameters:

Name Type Description Default
element str | int

Chemical symbol or atomic number. Multi-valence BMP labels like "Fe3" or "Ce4" are resolved to their base symbol ("Fe", "Ce").

required

Returns:

Type Description
float

Atomic mass in g/mol.

Example

mass = get_atomic_mass("Si") print(mass) 28.085

Source code in amorphouspy/src/amorphouspy/atoms/mass.py
def get_atomic_mass(element: str | int) -> float:
    """Get the atomic mass of an element.

    Args:
        element: Chemical symbol or atomic number. Multi-valence BMP labels like
            "Fe3" or "Ce4" are resolved to their base symbol ("Fe", "Ce").

    Returns:
        Atomic mass in g/mol.

    Example:
        >>> mass = get_atomic_mass("Si")
        >>> print(mass)
        28.085

    """
    if isinstance(element, str):
        symbol = element.rstrip("0123456789") or element
        atomic_number = chemical_symbols.index(symbol)
    else:
        atomic_number = element
    return atomic_masses_iupac2016[atomic_number]

get_composition(composition: dict[str, float], mode: str = 'molar') -> dict[str, float]

Convert a composition dictionary into normalized molar fractions.

Parameters:

Name Type Description Default
composition dict[str, float]

A dictionary mapping oxide formulas to their fractions, e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}.

required
mode str

The interpretation mode, either 'molar' or 'weight'. Defaults to "molar".

'molar'

Returns:

Type Description
dict[str, float]

A dictionary mapping oxide formulas to their molar fractions.

Raises:

Type Description
ValueError

If mode is not 'molar' or 'weight'.

Source code in amorphouspy/src/amorphouspy/fabrication/composition.py
def get_composition(composition: dict[str, float], mode: str = "molar") -> dict[str, float]:
    """Convert a composition dictionary into normalized molar fractions.

    Args:
        composition: A dictionary mapping oxide formulas to their fractions,
            e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}.
        mode: The interpretation mode, either 'molar' or 'weight'. Defaults to "molar".

    Returns:
        A dictionary mapping oxide formulas to their molar fractions.

    Raises:
        ValueError: If `mode` is not 'molar' or 'weight'.

    """
    if mode.lower() not in ("molar", "weight"):
        error_msg = f"Invalid mode: {mode}. Supported modes are 'molar' and 'weight'."
        raise ValueError(error_msg)
    raw = extract_composition(composition)
    if mode.lower() == "weight":
        return weight_percent_to_mol_fraction(raw)
    return normalize(raw)

get_diffusion(msd_result: dict[str, Any], *, fit_start_frac: float = 0.2, fit_end_frac: float = 0.8, dimensionality: int = 3) -> dict[str, Any]

Estimate self-diffusion coefficients from an MSD via the Einstein relation.

Fits MSD = 2 * d * D * t over the diffusive window and reports D in cm^2/s and m^2/s. A warning is emitted if the log-log MSD slope in the window deviates from 1 (sub-diffusive).

Parameters:

Name Type Description Default
msd_result dict[str, Any]

Output of :func:compute_msd.

required
fit_start_frac float

Start of the fit window as a fraction of the number of lags.

0.2
fit_end_frac float

End of the fit window as a fraction of the number of lags.

0.8
dimensionality int

Spatial dimensionality d (3 for bulk glasses).

3

Returns:

Type Description
dict[str, Any]

Dict with "total" diffusion data, "temperature" (K), and "per_species" when the

dict[str, Any]

input was species-resolved. Each entry holds diffusion_cm2_s, diffusion_m2_s,

dict[str, Any]

slope_a2_ps, fit_residual_cm2_s, fit_window_ps and loglog_slope.

Example
>>> msd = {"lag_time_ps": [0, 1, 2, 3, 4], "msd_total": [0.0, 6.0, 12.0, 18.0, 24.0]}
>>> out = get_diffusion(msd, fit_start_frac=0.0, fit_end_frac=1.0)
>>> round(out["total"]["diffusion_cm2_s"], 6)
0.0001
Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
def get_diffusion(
    msd_result: dict[str, Any],
    *,
    fit_start_frac: float = 0.2,
    fit_end_frac: float = 0.8,
    dimensionality: int = 3,
) -> dict[str, Any]:
    """Estimate self-diffusion coefficients from an MSD via the Einstein relation.

    Fits ``MSD = 2 * d * D * t`` over the diffusive window and reports ``D`` in cm^2/s and m^2/s. A
    warning is emitted if the log-log MSD slope in the window deviates from 1 (sub-diffusive).

    Args:
        msd_result: Output of :func:`compute_msd`.
        fit_start_frac: Start of the fit window as a fraction of the number of lags.
        fit_end_frac: End of the fit window as a fraction of the number of lags.
        dimensionality: Spatial dimensionality ``d`` (3 for bulk glasses).

    Returns:
        Dict with ``"total"`` diffusion data, ``"temperature"`` (K), and ``"per_species"`` when the
        input was species-resolved. Each entry holds ``diffusion_cm2_s``, ``diffusion_m2_s``,
        ``slope_a2_ps``, ``fit_residual_cm2_s``, ``fit_window_ps`` and ``loglog_slope``.

    Example:
        ```pycon
        >>> msd = {"lag_time_ps": [0, 1, 2, 3, 4], "msd_total": [0.0, 6.0, 12.0, 18.0, 24.0]}
        >>> out = get_diffusion(msd, fit_start_frac=0.0, fit_end_frac=1.0)
        >>> round(out["total"]["diffusion_cm2_s"], 6)
        0.0001

        ```
    """
    lag_time_ps = np.asarray(msd_result["lag_time_ps"], dtype=float)

    def _one(msd: list[float]) -> dict[str, Any]:
        return _fit_diffusion(
            lag_time_ps,
            np.asarray(msd, dtype=float),
            fit_start_frac=fit_start_frac,
            fit_end_frac=fit_end_frac,
            dimensionality=dimensionality,
        )

    output: dict[str, Any] = {
        "temperature": msd_result.get("temperature"),
        "total": _one(msd_result["msd_total"]),
    }
    if "msd_per_species" in msd_result:
        output["per_species"] = {symbol: _one(msd) for symbol, msd in msd_result["msd_per_species"].items()}
    return output

get_glass_density_from_model(composition: dict[str, float]) -> float

Calculate the room-temperature glass density using Fluegel's empirical model.

The model uses a polynomial expansion based on mole percentages of oxides. Source: Fluegel, A. "Global Model for Calculating Room-Temperature Glass Density from the Composition", J. Am. Ceram. Soc., 90 [8] 2622-2635 (2007).

Parameters:

Name Type Description Default
composition dict[str, float]

A dictionary mapping oxide formulas to their fractions.

required

Returns:

Type Description
float

The calculated density in g/cm^3.

Raises:

Type Description
ValueError

If the composition contains components unsupported by the model or if the format is invalid.

Example

density = get_glass_density_from_model({"SiO2": 0.75, "Na2O": 0.25})

Source code in amorphouspy/src/amorphouspy/fabrication/density.py
def get_glass_density_from_model(composition: dict[str, float]) -> float:  # noqa: C901, PLR0912
    """Calculate the room-temperature glass density using Fluegel's empirical model.

    The model uses a polynomial expansion based on mole percentages of oxides.
    Source: Fluegel, A. "Global Model for Calculating Room-Temperature Glass Density from the Composition",
    J. Am. Ceram. Soc., 90 [8] 2622-2635 (2007).

    Args:
        composition: A dictionary mapping oxide formulas to their fractions.

    Returns:
        The calculated density in g/cm^3.

    Raises:
        ValueError: If the composition contains components unsupported by the model
            or if the format is invalid.

    Example:
        >>> density = get_glass_density_from_model({"SiO2": 0.75, "Na2O": 0.25})

    """
    COEFFICIENTS = {
        "b0": 2.121560704,
        "Al2O3": 0.010525974,
        "Al2O3_2": -0.000076924,
        "B2O3": 0.00579283,
        "B2O3_2": 0.000129174,
        "B2O3_3": -0.000019887,
        "Li2O": 0.012848733,
        "Li2O_2": -0.000276404,
        "Li2O_3": 0.00000259,
        "Na2O": 0.018129123,
        "Na2O_2": -0.000264838,
        "Na2O_3": 0.000001614,
        "K2O": 0.019177312,
        "K2O_2": -0.000319863,
        "K2O_3": 0.00000191,
        "MgO": 0.01210604,
        "MgO_2": -0.000061159,
        "CaO": 0.017992367,
        "CaO_2": -0.00005478,
        "SrO": 0.034630735,
        "SrO_2": -0.000086939,
        "BaO": 0.049879597,
        "BaO_2": -0.000168063,
        "ZnO": 0.025221567,
        "ZnO_2": 0.000099961,
        "PbO": 0.070020298,
        "PbO_2": 0.000214424,
        "PbO_3": -0.000001502,
        "FexOy": 0.036995747,
        "MnxOy": 0.016648722,
        "TiO2": 0.018820343,
        "ZrO2": 0.043059714,
        "ZrO2_2": -0.000779078,
        "CexOy": 0.061277268,
        "CdO": 0.052945783,
        "La2O3": 0.10643194,
        "Nd2O3": 0.090134135,
        "NiO": 0.024289113,
        "ThO2": 0.090253734,
        "UxOy": 0.063297404,
        "SbxOy": 0.044258719,
        "SO3": -0.044488661,
        "F": 0.00109839,
        "Cl": -0.006092537,
        "Remainder": 0.02514614,
        "Na2O_K2O": -0.000395491,
        "Na2O_Li2O": -0.00031449,
        "K2O_Li2O": -0.000329725,
        "Na2O_B2O3": 0.000242157,
        "K2O_B2O3": 0.000259927,
        "Li2O_B2O3": 0.000106359,
        "MgO_B2O3": -0.000206488,
        "CaO_B2O3": -0.000032258,
        "PbO_B2O3": -0.000186195,
        "FexOy_B2O3": -0.000720268,
        "ZrO2_B2O3": -0.000697195,
        "Al2O3_B2O3": -0.000735749,
        "Li2O_Al2O3": -0.000116227,
        "Na2O_Al2O3": -0.000253454,
        "K2O_Al2O3": -0.000371858,
        "MgO_CaO": 0.000057248,
        "MgO_Al2O3": 0.000167218,
        "MgO_ZnO": 0.000220766,
        "Li2O_CaO": -0.00008792,
        "Na2O_MgO": -0.000300745,
        "Na2O_CaO": -0.000228249,
        "Na2O_SrO": -0.00023137,
        "Na2O_BaO": -0.000171693,
        "K2O_MgO": -0.000337747,
        "K2O_CaO": -0.000349578,
        "K2O_SrO": -0.000425589,
        "K2O_BaO": -0.000392897,
        "Al2O3_CaO": -0.000102444,
        "Al2O3_PbO": -0.000651745,
        "Al2O3_TiO2": -0.000563594,
        "Al2O3_BaO": -0.000273835,
        "Al2O3_SrO": -0.000177761,
        "Al2O3_ZnO": -0.000109968,
        "Al2O3_ZrO2": -0.002381651,
        "Na2O_PbO": -0.000036455,
        "Na2O_TiO2": -0.00014331,
        "Na2O_ZnO": -0.000155275,
        "Na2O_ZrO2": -0.000126728,
        "Na2O_FexOy": -0.000371343,
        "K2O_PbO": -0.000525213,
        "K2O_TiO2": -0.000386587,
        "K2O_ZnO": -0.000329812,
        "CaO_PbO": -0.00084145,
        "ZnO_FexOy": -0.001536804,
        "Na2O_K2O_B2O3": -0.000032967,
        "Na2O_MgO_CaO": -0.000009143,
        "Na2O_MgO_Al2O3": -0.000012286,
        "Na2O_CaO_Al2O3": -0.000005106,
        "Na2O_CaO_PbO": 0.000100796,
        "K2O_MgO_CaO": -0.00001217,
        "K2O_MgO_Al2O3": -0.000041908,
        "K2O_CaO_Al2O3": -0.000012421,
        "K2O_CaO_PbO": 0.000125759,
        "MgO_CaO_Al2O3": -0.000011236,
        "CaO_Al2O3_Li2O": -0.000016177,
        "Al2O3_B2O3_PbO": 0.000030116,
    }
    try:
        mole_fractions = extract_composition(composition)
    except (ValueError, TypeError) as e:
        error_msg = f"Invalid composition {composition!r}: {e}"
        raise ValueError(error_msg) from e

    concentrations = {oxide: frac * 100 for oxide, frac in mole_fractions.items()}
    remainder_conc = 0.0
    main_components = []

    for oxide, conc in concentrations.items():
        if conc < 0:
            error_msg = f"Negative concentration for '{oxide}': {conc}"
            raise ValueError(error_msg)

        if oxide == "SiO2":
            continue

        if oxide in TRACE_OXIDES:
            remainder_conc += conc
        else:
            main_components.append(oxide)

    if remainder_conc > 0 and "Remainder" not in COEFFICIENTS:
        error_msg = "Trace oxides present but 'Remainder' coefficient missing"
        raise ValueError(error_msg)

    valid_components = set(COEFFICIENTS.keys()) - {"b0", "Remainder"}
    for comp in main_components:
        if comp not in valid_components:
            error_msg = f"Component '{comp}' not in density model coefficients and cannot be calculated automatically."
            error_msg += " Density must be provided by the user."
            raise ValueError(error_msg)

    density = COEFFICIENTS.get("b0", 0)
    if remainder_conc > 0:
        density += COEFFICIENTS.get("Remainder", 0) * remainder_conc

    for comp in main_components:
        conc = concentrations[comp]
        if comp in COEFFICIENTS:
            density += COEFFICIENTS[comp] * conc
        quad_key = f"{comp}_2"
        if quad_key in COEFFICIENTS:
            density += COEFFICIENTS[quad_key] * (conc**2)
        cube_key = f"{comp}_3"
        if cube_key in COEFFICIENTS:
            density += COEFFICIENTS[cube_key] * (conc**3)

    TWO_WAY_KEY_PARTS = 1
    THREE_WAY_KEY_PARTS = 2
    two_way_keys = {k for k in COEFFICIENTS if k.count("_") == TWO_WAY_KEY_PARTS and not k.endswith(("_2", "_3"))}
    three_way_keys = {k for k in COEFFICIENTS if k.count("_") == THREE_WAY_KEY_PARTS}

    for key in two_way_keys:
        comp1, comp2 = key.split("_")
        if comp1 in main_components and comp2 in main_components:
            density += COEFFICIENTS[key] * concentrations[comp1] * concentrations[comp2]

    for key in three_way_keys:
        comp1, comp2, comp3 = key.split("_")
        if comp1 in main_components and comp2 in main_components and comp3 in main_components:
            density += COEFFICIENTS[key] * concentrations[comp1] * concentrations[comp2] * concentrations[comp3]

    return density

get_neighbors(atoms: Atoms | tuple[np.ndarray, np.ndarray, np.ndarray], cutoff: float | dict[tuple[int, int], float], target_types: int | list[int] | None = None, neighbor_types: int | list[int] | None = None, *, return_vectors: bool = False, use_numba: bool | None = None) -> list[tuple]

Find all neighbors within cutoff for each atom.

Returns a list of tuples where all IDs are the real atom IDs from the structure file (e.g. non-sequential LAMMPS/XYZ ids), not array indices.

Parameters:

Name Type Description Default
atoms Atoms | tuple[ndarray, ndarray, ndarray]

Either an ASE Atoms object or a tuple (coords, types, cell_matrix) where cell_matrix is a (3,3) array with lattice vectors as rows. For an Atoms object atoms.pbc is honoured per lattice vector (slabs, wires and isolated molecules are handled); the tuple form is treated as fully periodic. Coordinates need not be wrapped.

required
cutoff float | dict[tuple[int, int], float]

Cutoff radius in Angstrom. Either: - A single float applied uniformly to all pairs. - A dict mapping (atomic_number_i, atomic_number_j) to a pair-specific cutoff in Angstrom. Symmetric: (8, 14) and (14, 8) are equivalent. Pairs not listed default to the maximum cutoff in the dict. The cell list is built on the maximum cutoff so only one build is needed.

required
target_types int | list[int] | None

Atomic numbers of atoms to find neighbors for. A bare atomic number is accepted and treated as a one-element list. None means all atoms.

None
neighbor_types int | list[int] | None

Atomic numbers that count as valid neighbors. A bare atomic number is accepted. None means all types.

None
return_vectors bool

If True, each output tuple gains a third element — a (k, 3) float64 array of Cartesian minimum-image bond vectors r_i - r_j in Angstrom, i.e. pointing from the neighbour to the central atom (the opposite sign of ASE's neighbor_list "D"). Scalar distances are np.linalg.norm(vectors, axis=1).

False
use_numba bool | None

Force Numba on/off. None = auto-detect.

None

Returns:

Type Description
list[tuple]

If return_vectors=False (default): [(central_id, [neighbor_ids]), ...]

list[tuple]

If return_vectors=True: [(central_id, [neighbor_ids], vectors_shape_k3), ...]

Examples:

Scalar cutoff (backward compatible)::

>>> neighbors = get_neighbors(atoms, cutoff=3.5)
>>> for central_id, nn_ids in neighbors:
...     print(central_id, nn_ids)

Per-pair cutoffs for a Na2O-Al2O3-SiO2 glass::

>>> cutoff = {(14, 8): 2.0, (13, 8): 1.9, (11, 8): 2.7}
>>> neighbors = get_neighbors(atoms, cutoff=cutoff)

With bond vectors for Steinhardt parameters::

>>> result = get_neighbors(atoms, cutoff=3.5, return_vectors=True)
>>> for central_id, nn_ids, vecs in result:
...     distances = np.linalg.norm(vecs, axis=1)
...     print(f"atom {central_id}: mean bond length = {distances.mean():.3f} A")

Quick lookup by original atom ID::

>>> nl = {cid: nn for cid, nn, *_ in get_neighbors(atoms, cutoff=3.5)}
>>> nl[43586]
Source code in amorphouspy/src/amorphouspy/atoms/neighbors.py
def get_neighbors(
    atoms: Atoms | tuple[np.ndarray, np.ndarray, np.ndarray],
    cutoff: float | dict[tuple[int, int], float],
    target_types: int | list[int] | None = None,
    neighbor_types: int | list[int] | None = None,
    *,
    return_vectors: bool = False,
    use_numba: bool | None = None,
) -> list[tuple]:
    """Find all neighbors within cutoff for each atom.

    Returns a list of tuples where all IDs are the real atom IDs from the
    structure file (e.g. non-sequential LAMMPS/XYZ ids), not array indices.

    Args:
        atoms: Either an ASE Atoms object or a tuple (coords, types, cell_matrix)
               where cell_matrix is a (3,3) array with lattice vectors as rows.
               For an Atoms object ``atoms.pbc`` is honoured per lattice vector
               (slabs, wires and isolated molecules are handled); the tuple form
               is treated as fully periodic. Coordinates need not be wrapped.
        cutoff: Cutoff radius in Angstrom. Either:
                  - A single float applied uniformly to all pairs.
                  - A dict mapping (atomic_number_i, atomic_number_j) to a
                    pair-specific cutoff in Angstrom. Symmetric: (8, 14) and
                    (14, 8) are equivalent. Pairs not listed default to the
                    maximum cutoff in the dict. The cell list is built on the
                    maximum cutoff so only one build is needed.
        target_types: Atomic numbers of atoms to find neighbors for. A bare
                      atomic number is accepted and treated as a one-element
                      list. None means all atoms.
        neighbor_types: Atomic numbers that count as valid neighbors. A bare
                        atomic number is accepted. None means all types.
        return_vectors: If True, each output tuple gains a third element — a
                        (k, 3) float64 array of Cartesian minimum-image bond
                        vectors r_i - r_j in Angstrom, i.e. pointing from the
                        neighbour to the central atom (the opposite sign of
                        ASE's neighbor_list "D"). Scalar distances are
                        np.linalg.norm(vectors, axis=1).
        use_numba: Force Numba on/off. None = auto-detect.

    Returns:
        If return_vectors=False (default):
            [(central_id, [neighbor_ids]), ...]

        If return_vectors=True:
            [(central_id, [neighbor_ids], vectors_shape_k3), ...]

    Examples:
        Scalar cutoff (backward compatible)::

            >>> neighbors = get_neighbors(atoms, cutoff=3.5)
            >>> for central_id, nn_ids in neighbors:
            ...     print(central_id, nn_ids)

        Per-pair cutoffs for a Na2O-Al2O3-SiO2 glass::

            >>> cutoff = {(14, 8): 2.0, (13, 8): 1.9, (11, 8): 2.7}
            >>> neighbors = get_neighbors(atoms, cutoff=cutoff)

        With bond vectors for Steinhardt parameters::

            >>> result = get_neighbors(atoms, cutoff=3.5, return_vectors=True)
            >>> for central_id, nn_ids, vecs in result:
            ...     distances = np.linalg.norm(vecs, axis=1)
            ...     print(f"atom {central_id}: mean bond length = {distances.mean():.3f} A")

        Quick lookup by original atom ID::

            >>> nl = {cid: nn for cid, nn, *_ in get_neighbors(atoms, cutoff=3.5)}
            >>> nl[43586]
    """
    if use_numba is None:
        use_numba = NUMBA_AVAILABLE

    target_types = _normalize_type_filter(target_types, "target_types")
    neighbor_types = _normalize_type_filter(neighbor_types, "neighbor_types")

    # ------------------------------------------------------------------
    # Parse input
    # ------------------------------------------------------------------
    atom_ids = _extract_atom_ids(atoms)

    if not isinstance(atoms, Atoms):
        coords, types, cell = atoms
        coords = np.asarray(coords, dtype=np.float64)
        types = np.asarray(types, dtype=np.int32)
        cell = np.asarray(cell, dtype=np.float64)
        pbc = np.ones(3, dtype=bool)
    else:
        coords = atoms.get_positions()
        types = atoms.get_atomic_numbers().astype(np.int32)
        cell = np.array(atoms.get_cell().array, dtype=np.float64)
        pbc = np.asarray(atoms.pbc, dtype=bool)

    n_atoms = len(coords)
    _validate_coords(coords)

    # ------------------------------------------------------------------
    # Parse cutoff
    # ------------------------------------------------------------------
    max_cutoff, pair_types, pair_cutoffs_sq, use_pair_cutoffs = _parse_cutoff(cutoff, types)
    cutoff_sq = max_cutoff * max_cutoff
    if n_atoms == 0:
        return []

    target_arr = np.array(target_types, dtype=np.int32) if target_types is not None else np.empty(0, dtype=np.int32)
    neighbor_arr = (
        np.array(neighbor_types, dtype=np.int32) if neighbor_types is not None else np.empty(0, dtype=np.int32)
    )
    use_target_filter = target_types is not None
    use_neighbor_filter = neighbor_types is not None

    # ------------------------------------------------------------------
    # Geometry: estimate density on the real cell, then pad non-periodic axes
    # ------------------------------------------------------------------
    initial_max_neighbors = _estimate_max_neighbors(coords, cell, max_cutoff)
    cell, coords = _pad_nonperiodic(cell, coords, pbc, max_cutoff)
    _validate_cell(cell)
    _warn_if_cutoff_exceeds_minimum_image(cell, max_cutoff, pbc)
    is_orthogonal, box_size, coords_frac, atom_cells, n_cells, cell_start, cell_atoms = _build_cell_list(
        coords, cell, max_cutoff
    )

    # ------------------------------------------------------------------
    # Build neighbor list
    # ------------------------------------------------------------------
    if use_numba and NUMBA_AVAILABLE:
        stencil_start, stencil_count = _cell_offsets(n_cells)
        kwargs: dict[str, Any] = {
            "types": types,
            "atom_cells": atom_cells,
            "n_cells": n_cells,
            "cell_start": cell_start,
            "cell_atoms": cell_atoms,
            "stencil_start": stencil_start,
            "stencil_count": stencil_count,
            "cutoff_sq": cutoff_sq,
            "target_types": target_arr,
            "neighbor_types": neighbor_arr,
            "use_target_filter": use_target_filter,
            "use_neighbor_filter": use_neighbor_filter,
            "max_neighbors": initial_max_neighbors,
            "pair_types": pair_types,
            "pair_cutoffs_sq": pair_cutoffs_sq,
            "use_pair_cutoffs": use_pair_cutoffs,
            "return_vectors": return_vectors,
        }
        if is_orthogonal:
            build_fn = _build_nl_ortho_numba
            kwargs.update(coords=coords, box_size=box_size)
        else:
            build_fn = _build_nl_tri_numba
            kwargs.update(
                coords_frac=coords_frac,
                cell=cell,
                half_height_sq=_image_search_bound(cell, n_cells),
            )
        neighbor_list, counts, vector_list = _grow_until_fits(build_fn, kwargs)
        flat_j, flat_vecs = _padded_to_csr(neighbor_list, counts, vector_list, return_vectors)
    else:
        flat_j, counts, flat_vecs = _numpy_fallback(
            coords=coords,
            coords_frac=coords_frac,
            types=types,
            cell=cell,
            box_size=box_size,
            atom_cells=atom_cells,
            n_cells=n_cells,
            cutoff_sq=cutoff_sq,
            pair_types=pair_types,
            pair_cutoffs_sq=pair_cutoffs_sq,
            use_pair_cutoffs=use_pair_cutoffs,
            use_target_filter=use_target_filter,
            use_neighbor_filter=use_neighbor_filter,
            target_types=target_types,
            neighbor_types=neighbor_types,
            n_atoms=n_atoms,
            return_vectors=return_vectors,
            is_orthogonal=is_orthogonal,
        )

    return _build_neighbor_output(flat_j, counts, flat_vecs, atom_ids, return_vectors)

get_structure_dict(composition: dict[str, float], n_molecules: int | None = None, target_atoms: int | None = None, mode: str = 'molar', density: float | None = None, min_distance: float = 1.6, max_attempts_per_atom: int = 10000, random_seed: int = 42) -> dict

Generate a structure dictionary for a given composition.

Supports both n_molecules and target_atoms input modes, and both molar and weight composition modes.

Parameters:

Name Type Description Default
composition dict[str, float]

A dictionary mapping oxide formulas to their fractions, e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}.

required
n_molecules int | None

Total number of molecules (traditional mode).

None
target_atoms int | None

Target number of atoms (new mode).

None
mode str

Composition mode: "molar" for mol%, "weight" for weight%.

'molar'
density float | None

Density in g/cm^3, default is calculated from model.

None
min_distance float

Minimum distance between any two atoms in angstroms, default is 1.6 Å.

1.6
max_attempts_per_atom int

Maximum attempts to place an atom before giving up, default is 10000.

10000
random_seed int

Random seed for reproducibility, default is 42.

42

Returns:

Type Description
dict

A dictionary containing: - "atoms": A list of atom dictionaries with keys "element" and "position" - "box": The length of the cubic box in angstroms - "formula_units": Dictionary of oxide formula units - "total_atoms": Total number of atoms - "element_counts": Dictionary of element counts (if target_atoms mode) - "mol_fraction": Dictionary of molar fractions (if target_atoms mode)

Example

struct_dict = get_structure_dict( ... composition={"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}, ... target_atoms=1000, ... mode="molar" ... )

Source code in amorphouspy/src/amorphouspy/fabrication/geometry.py
def get_structure_dict(
    composition: dict[str, float],
    n_molecules: int | None = None,
    target_atoms: int | None = None,
    mode: str = "molar",
    density: float | None = None,
    min_distance: float = 1.6,
    max_attempts_per_atom: int = 10000,
    random_seed: int = 42,
) -> dict:
    """Generate a structure dictionary for a given composition.

    Supports both n_molecules and target_atoms input modes,
    and both molar and weight composition modes.

    Args:
        composition: A dictionary mapping oxide formulas to their fractions,
            e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}.
        n_molecules: Total number of molecules (traditional mode).
        target_atoms: Target number of atoms (new mode).
        mode: Composition mode: "molar" for mol%, "weight" for weight%.
        density: Density in g/cm^3, default is calculated from model.
        min_distance: Minimum distance between any two atoms in angstroms, default is 1.6 Å.
        max_attempts_per_atom: Maximum attempts to place an atom before giving up, default is 10000.
        random_seed: Random seed for reproducibility, default is 42.

    Returns:
        A dictionary containing:
            - "atoms": A list of atom dictionaries with keys "element" and "position"
            - "box": The length of the cubic box in angstroms
            - "formula_units": Dictionary of oxide formula units
            - "total_atoms": Total number of atoms
            - "element_counts": Dictionary of element counts (if target_atoms mode)
            - "mol_fraction": Dictionary of molar fractions (if target_atoms mode)

    Example:
        >>> struct_dict = get_structure_dict(
        ...     composition={"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5},
        ...     target_atoms=1000,
        ...     mode="molar"
        ... )

    """
    validate_target_mode(n_molecules, target_atoms)

    stoichiometry = extract_stoichiometry(composition)

    box_length = get_box_from_density(
        composition,
        n_molecules=n_molecules,
        target_atoms=target_atoms,
        mode=mode,
        density=density,
        stoichiometry=stoichiometry,
    )

    atoms_list, _ = create_random_atoms(
        composition,
        n_molecules=n_molecules,
        target_atoms=target_atoms,
        mode=mode,
        box_length=box_length,
        min_distance=min_distance,
        max_attempts_per_atom=max_attempts_per_atom,
        stoichiometry=stoichiometry,
        seed=random_seed,
    )

    if target_atoms is not None:
        system_plan = plan_system(composition, target_atoms, mode=mode, target_type="atoms")
        molecule_counts = system_plan["formula_units"]
        total_atoms = system_plan["total_atoms"]
        element_counts = system_plan["element_counts"]
        mol_fraction = system_plan["mol_fraction"]
    else:
        assert n_molecules is not None
        composition_dict = extract_composition(composition)
        molecule_counts = {oxide: round(frac * n_molecules) for oxide, frac in composition_dict.items()}
        diff = n_molecules - sum(molecule_counts.values())
        if diff:
            main = max(composition_dict, key=lambda ox: composition_dict[ox])
            molecule_counts[main] += diff

        total_atoms = 0
        element_counts: dict[str, int] = {}
        for ox, mol_cnt in molecule_counts.items():
            stoich = stoichiometry.get(ox)
            if stoich is None:
                error_msg = f"Unknown oxide formula: {ox}"
                raise KeyError(error_msg)
            for elem, num in stoich.items():
                element_counts[elem] = element_counts.get(elem, 0) + num * mol_cnt
            total_atoms += sum(stoich.values()) * mol_cnt

        mol_fraction = get_composition(composition, mode=mode)

    return {
        "atoms": atoms_list,
        "box": box_length,
        "formula_units": molecule_counts,
        "total_atoms": total_atoms,
        "element_counts": element_counts,
        "mol_fraction": mol_fraction,
    }

get_viscosity(result: dict[str, Any], timestep: float = 1.0, output_frequency: int = 1, max_lag: int | None = 1000000, cutoff_method: str = 'noise_threshold') -> dict[str, float]

Compute viscosity using the Green-Kubo formalism from MD stress data.

Parameters:

Name Type Description Default
result dict[str, Any]

Parsed output dictionary from viscosity_simulation.

required
timestep float

MD integration time step in femtoseconds.

1.0
output_frequency int

Number of MD steps between stored frames in the output.

1
max_lag int | None

Maximum correlation lag (number of steps). Defaults to 1,000,000.

1000000
cutoff_method str

Method passed to auto_cutoff for τ_acf detection. One of 'noise_threshold', 'cumulative_integral', or 'self_consistent'. Defaults to 'noise_threshold'.

'noise_threshold'

Returns:

Type Description
dict[str, float]

A dictionary containing: - temperature: Mean simulation temperature (K) - viscosity: Computed viscosity (Pa·s) - max_lag: Cutoff time per stress component (ps) - lag_time_ps: Array of lag times in picoseconds - sacf: Averaged normalized stress autocorrelation function - viscosity_integral: Cumulative viscosity integral (Pa·s) vs lag time

Example

result_dict = get_viscosity(simulation_output, timestep=1.0, output_frequency=1, max_lag=1000000) print(result_dict['viscosity']) print(result_dict['sacf']) print(result_dict['viscosity_integral'])

Source code in amorphouspy/src/amorphouspy/properties/viscosity.py
def get_viscosity(  # noqa: PLR0915
    result: dict[str, Any],
    timestep: float = 1.0,  # fs (MD integration timestep)
    output_frequency: int = 1,  # number of MD steps between stored frames
    max_lag: int | None = 1_000_000,
    cutoff_method: str = "noise_threshold",
) -> dict[str, float]:
    """Compute viscosity using the Green-Kubo formalism from MD stress data.

    Args:
        result: Parsed output dictionary from `viscosity_simulation`.
        timestep: MD integration time step in femtoseconds.
        output_frequency: Number of MD steps between stored frames in the output.
        max_lag: Maximum correlation lag (number of steps). Defaults to 1,000,000.
        cutoff_method: Method passed to ``auto_cutoff`` for τ_acf detection. One of
            ``'noise_threshold'``, ``'cumulative_integral'``, or ``'self_consistent'``.
            Defaults to ``'noise_threshold'``.

    Returns:
        A dictionary containing:
            - temperature: Mean simulation temperature (K)
            - viscosity: Computed viscosity (Pa·s)
            - max_lag: Cutoff time per stress component (ps)
            - lag_time_ps: Array of lag times in picoseconds
            - sacf: Averaged normalized stress autocorrelation function
            - viscosity_integral: Cumulative viscosity integral (Pa·s) vs lag time

    Example:
        >>> result_dict = get_viscosity(simulation_output, timestep=1.0, output_frequency=1, max_lag=1000000)
        >>> print(result_dict['viscosity'])
        >>> print(result_dict['sacf'])
        >>> print(result_dict['viscosity_integral'])

    """
    kB = 1.380649e-23  # m^2 kg s^-2 K^-1
    A2m = 1e-10  # Å → m

    # --- Extract data ---
    pressures = result["result"]["pressures"]
    pxy = pressures[::output_frequency, 0, 1] * 1e9  # Pa
    pxz = pressures[::output_frequency, 0, 2] * 1e9  # Pa
    pyz = pressures[::output_frequency, 1, 2] * 1e9  # Pa

    volume = np.mean(result["result"]["volume"]) * A2m**3  # m^3
    temperature = np.mean(result["result"]["temperature"])  # K

    # --- Correct effective timestep ---
    dt_s = timestep * output_frequency * 1e-15  # seconds

    scale = volume / (kB * temperature)

    if max_lag is None:
        max_lag = len(pxy)

    # --- First ACF pass ---
    acfxy = autocorrelation_fft(pxy, max_lag)
    acfxz = autocorrelation_fft(pxz, max_lag)
    acfyz = autocorrelation_fft(pyz, max_lag)

    # enforce consistent length
    n = min(len(acfxy), len(acfxz), len(acfyz))
    acfxy = acfxy[:n]
    acfxz = acfxz[:n]
    acfyz = acfyz[:n]

    lag_time_s = np.arange(n) * dt_s
    lag_time_ps = lag_time_s * 1e12

    # --- Auto cutoff detection (with per-component fallback) ---
    cut_times_ps: list[float | tuple[float, int]] = []
    _detection_succeeded: list[bool] = []
    for _acf_norm, _label in [
        (acfxy / acfxy[0], "pxy"),
        (acfxz / acfxz[0], "pxz"),
        (acfyz / acfyz[0], "pyz"),
    ]:
        try:
            _c = auto_cutoff(_acf_norm, lag_time_ps, method=cutoff_method, epsilon=1e-4, min_cutoff=10)
            cut_times_ps.append(_c)
            _detection_succeeded.append(True)
        except ValueError:
            cut_times_ps.append(lag_time_ps[-1])  # fall back to last lag time
            _detection_succeeded.append(False)

    if not any(_detection_succeeded):
        msg = "tau_acf detection failed for all stress components"
        raise ValueError(msg)

    _successful_cut_times = [
        _cutoff_time_ps(c) for c, ok in zip(cut_times_ps, _detection_succeeded, strict=False) if ok
    ]
    tau_acf_ps = float(np.max(_successful_cut_times))

    # --- Convert cutoff times to lag indices ---
    total_time_ps = len(pxy) * timestep * output_frequency / 1000

    max_lag_1 = [
        get_closest_divisor(int(total_time_ps), int(_cutoff_time_ps(cut_times_ps[0]))) * 2,
        get_closest_divisor(int(total_time_ps), int(_cutoff_time_ps(cut_times_ps[1]))) * 2,
        get_closest_divisor(int(total_time_ps), int(_cutoff_time_ps(cut_times_ps[2]))) * 2,
    ]

    # convert ps → steps
    max_lag = int(np.max(max_lag_1) / (timestep * output_frequency / 1000))

    # --- Second ACF pass (final integration window) ---
    acfxy = autocorrelation_fft(pxy, max_lag)
    acfxz = autocorrelation_fft(pxz, max_lag)
    acfyz = autocorrelation_fft(pyz, max_lag)

    n = min(len(acfxy), len(acfxz), len(acfyz))
    acfxy = acfxy[:n]
    acfxz = acfxz[:n]
    acfyz = acfyz[:n]

    lag_time_s = np.arange(n) * dt_s
    lag_time_ps = lag_time_s * 1e12

    # --- Green-Kubo integration ---
    eta_xy = scale * cumulative_trapezoid(acfxy, dt=dt_s)
    eta_xz = scale * cumulative_trapezoid(acfxz, dt=dt_s)
    eta_yz = scale * cumulative_trapezoid(acfyz, dt=dt_s)

    eta_avg = (eta_xy + eta_xz + eta_yz) / 3
    viscosity = eta_avg[-1]

    # --- Normalized SACF ---
    sacf_xy = acfxy / acfxy[0]
    sacf_xz = acfxz / acfxz[0]
    sacf_yz = acfyz / acfyz[0]
    sacf_avg = ((sacf_xy + sacf_xz + sacf_yz) / 3).tolist()

    return {
        "temperature": temperature,
        "viscosity": viscosity,
        "max_lag": int(np.max(max_lag_1)),
        "lag_time_ps": lag_time_ps.tolist(),
        "sacf": sacf_avg,
        "viscosity_integral": eta_avg.tolist(),
        "tau_acf_ps": tau_acf_ps,
    }

harmonic_vdos_simulation(structure: Atoms, potential: pd.DataFrame, server_kwargs: dict[str, Any] | None = None, *, max_atoms: int = 10000, displacement: float = 1e-05, force_tolerance: float = 1e-06, max_iter: int = 100000, broadening_thz: float = 0.2, frequency_grid_thz: ArrayLike | None = None, normalization: HarmonicNormalization = 'unit', temperatures_k: ArrayLike | None = None, cutoff: CutoffSpec | None = None, former_types: list[int] | None = None, o_type: int = 8, driver: EigenDriver = 'evr', imaginary_threshold_thz: float = 0.01, tmp_working_directory: str | Path | None = None, keep_dynamical_matrix: bool = False, keep_eigenvectors: bool = False, infrared: bool = False, charges: ArrayLike | None = None, eps_inf: float = 1.0, ir_damping_thz: float = 0.5) -> dict[str, Any]

Minimise a structure, compute its finite-difference dynamical matrix and return the harmonic VDOS and modes.

The harmonic counterpart of :func:vdos_simulation: the VDOS of the 0 K inherent structure from its normal modes, with no MD and no statistical noise. Steps:

  1. Minimisation at fixed cell and the dynamical matrix, both in LAMMPS (_run_lammps_dynamical_matrix).
  2. The atom groups (element, oxygen class, \(\mathrm{Q}^n\)) with :func:classify_vibrational_groups and the masses, both from the minimised structure.
  3. The matrix is read with :func:read_dynamical_matrix and diagonalised in place with :func:diagonalize_dynamical_matrix, which drops the three translations.
  4. The broadened VDOS and its group partials with :func:compute_harmonic_vdos, the participation ratio of every mode with :func:compute_participation_ratio and, with temperatures_k, the harmonic thermodynamics with :func:compute_vibrational_thermodynamics.

The structure is used as given. Preparing it (melt-quench, NPT relaxation to the target pressure) is the caller's job; this function adds only the minimisation. The minimisation uses FIRE at fixed cell (min_style="fire", no box/relax) down to force_tolerance, the LAMMPS ftol: the 2-norm of the global force vector in eV/Å, not a per-atom maximum. A fixed cell leaves a residual pressure, reported in "minimization" ("pressure_gpa" and "mean_pressure_gpa"; for FIRE they also hold the kinetic term of the residual velocities), together with the iteration count, the stopping criterion and the final forces. If the tolerance is not reached, the minimiser warns and the result is still returned; the step-0 forces of the structure that was differentiated are in "dynamical_matrix" ("max_force_ev_per_a").

Finite differences: each entry of the matrix is a central difference of the forces with step displacement.

Imaginary modes are reported as negative frequencies in "mode_frequencies_thz". Those below -imaginary_threshold_thz are counted in "diagonalization" ("n_imaginary", with a warning that names the asymmetry atoms); they point at an incomplete minimisation or a corrupted entry. Every negative frequency is left out of the VDOS ("n_imaginary_excluded" and "imaginary_weight") and of the thermodynamics.

max_atoms guards against an accidental large run: above it the function raises before anything runs, and the message gives the matrix size and the expected peak. It can be raised deliberately.

The groups are classified on the minimised structure, the one whose modes are computed. Errors in cutoff, former_types or o_type therefore surface only after the LAMMPS runs.

The thermodynamics is computed from the broadened total VDOS on the frequency grid, not from a sum over the modes, with lowest_frequency_thz set to the smallest positive mode frequency, the lowest mode the box supports: the values below its temperature are flagged as unreliable. With normalization="3N" the total is divided by 3N first, as :func:compute_vibrational_thermodynamics needs a VDOS normalised to 1. On the 300-atom PMMCS glass at 300 K with the default 0.2 THz broadening, the values differ from an exact sum over the modes by -1.3e-5 (C_V), 8.5e-4 (S), 3.0e-5 (U) and -3.7e-4 (F), relative. The default grid starts at 0, so modes within a few broadening_thz of 0 lose part of their weight ("excluded_weight" and "vdos_integral" report it).

Disk and memory: the matrix file takes 9 N² x 8 bytes (2.6 GB at 6000 atoms, 7.2 GB at 10,000) and is deleted once it is read unless keep_dynamical_matrix. It is written under tmp_working_directory or, if that is None, under the system temporary directory (tempfile.gettempdir(), set by TMPDIR); the free space there is checked before anything runs. The peak in memory is still 2 matrices, during the diagonalisation. Without the eigenvectors, the result holds only O(M x number of labels) floats (the mode frequencies, participation ratios and group weights) plus the VDOS curves on the frequency grid. An eigenvector-based analysis later needs keep_eigenvectors=True or a rerun.

Parameters:

Name Type Description Default
structure Atoms

The structure, e.g. a quenched and NPT-relaxed glass, used as given. It is not modified.

required
potential DataFrame

LAMMPS potential as a pandas DataFrame.

required
server_kwargs dict[str, Any] | None

Additional arguments for the LAMMPS server (e.g. {"cores": 4}), used by both LAMMPS runs.

None
max_atoms int

Largest number of atoms accepted, a positive integer.

10000
displacement float

Finite-difference displacement in Å.

1e-05
force_tolerance float

FIRE stops when the 2-norm of the global force vector is below this, in eV/Å.

1e-06
max_iter int

Maximum number of FIRE iterations.

100000
broadening_thz float

Standard deviation of the Gaussian broadening of each mode in THz (not the FWHM).

0.2
frequency_grid_thz ArrayLike | None

Frequencies in THz at which the VDOS is evaluated, 1-D, finite and strictly increasing. None: from 0 in steps of broadening_thz / 5 up to the highest mode plus 5 broadening_thz.

None
normalization HarmonicNormalization

"unit" (the total VDOS integrates to 1, in 1/THz) or "3N" (to 3 * n_atoms), each short by the share of imaginary modes.

'unit'
temperatures_k ArrayLike | None

Temperatures in K for the harmonic thermodynamics, a scalar or a 1-D array of finite values

= 0. None skips it.

None
cutoff CutoffSpec | None

Former-O cutoff in Å for the groups, as in :func:classify_vibrational_groups. Derived from the RDF of the minimised structure if None.

None
former_types list[int] | None

Atomic numbers of the network formers. Derived from the composition if None.

None
o_type int

Atomic number of oxygen.

8
driver EigenDriver

LAPACK driver of scipy.linalg.eigh: "evr" (default), "evd", "evx" or "ev"; see :func:diagonalize_dynamical_matrix for their memory and time.

'evr'
imaginary_threshold_thz float

A mode below -imaginary_threshold_thz counts as imaginary in "diagonalization".

0.01
tmp_working_directory str | Path | None

Directory for the LAMMPS runs and the matrix file. The run directories, with their logs, input and data files, are kept. The matrix file goes to its own harmonic_vdos_* subdirectory, which is removed once the matrix is read unless keep_dynamical_matrix; nothing else in the directory is removed. If None, every run and the matrix file are removed.

None
keep_dynamical_matrix bool

Keep the matrix file, in harmonic_vdos_*/dynamical_matrix.bin under tmp_working_directory, instead of deleting it once read. Needs a tmp_working_directory.

False
keep_eigenvectors bool

Return the eigenvectors in "eigenvectors", one matrix in memory, instead of dropping them once the VDOS, the group partials and the participation ratios are computed.

False
infrared bool

Also compute the infrared response of the modes: oscillator strengths, dielectric function and optical constants, returned in "infrared".

False
charges ArrayLike | None

Atomic charges in units of the elementary charge for the infrared response, shape \((N,)\) or Born tensors \((N, 3, 3)\), in the order of the atoms. None reads the fixed charges of potential with :func:charges_from_potential. Ignored without infrared.

None
eps_inf float

The high-frequency dielectric constant \(\varepsilon_\infty\) of the infrared response; see :func:compute_dielectric_function.

1.0
ir_damping_thz float

The damping \(\gamma\) of the dielectric function in THz; see :func:compute_dielectric_function.

0.5

Returns:

Type Description
dict[str, Any]

A dict with: "frequencies_thz": the frequency grid in THz. "vdos": {"total": array, "element": {...}, "oxygen": {...}, "qn": {...}} with the labels of "groups", in 1/THz, the layout of :func:vdos_simulation. "groups": the output of :func:classify_vibrational_groups on the minimised structure. "structure": the minimised structure. "normalization": the VDOS normalisation. "broadening_thz": the broadening in THz. "mode_frequencies_thz": the \(M = 3N - 3\) mode frequencies in THz, ascending, negative for imaginary modes. "participation_ratio": the participation ratio of every mode, shape \((M,)\). "mode_weights": {grouping: {label: w}}, each group's \((M,)\) share of every mode, as in :func:compute_harmonic_vdos. "n_imaginary_excluded": the number of modes with a negative frequency, left out of the VDOS. "imaginary_weight": their share of the normalisation. "grid_integral": the trapezoid integral of the total VDOS on the grid. "eigenvectors": the \((3N, M)\) mass-weighted eigenvectors, one mode per column; None unless keep_eigenvectors. "dynamical_matrix": the summary of the LAMMPS dynamical-matrix run ("matrix_path", "matrix_bytes", "n_atoms", "displacement_a", "style", the step-0 "max_force_ev_per_a" and "force_norm_ev_per_a", "minimization" and "wall_time_s"). "matrix_path" is the absolute path of the kept file; None unless keep_dynamical_matrix. "minimization": the FIRE summary: "converged", "stopping_criterion", "n_iterations", "max_force_ev_per_a", "force_norm_ev_per_a", "pressure_gpa", "mean_pressure_gpa", the energies and volumes. "diagonalization": "asymmetry", "asymmetry_atoms", "translational_frequencies_thz", "translational_overlap", "n_imaginary", "min_frequency_thz" and "driver". "thermodynamics": the output of :func:compute_vibrational_thermodynamics, or None without temperatures_k or when no mode has a positive frequency (with a warning). "displacement_a": the finite-difference displacement in Å. "wall_time_s": {"lammps", "diagonalization", "analysis"} in s: both LAMMPS runs; reading and diagonalising the matrix; the groups, VDOS, participation ratios and thermodynamics. "infrared": None without infrared, else a dict on the grid of the VDOS ("frequencies_thz"): "mode_charges", "strengths" and "partial_strengths" of :func:compute_ir_oscillator_strengths for the groups of "groups"; "epsilon", "epsilon_static" and "n_modes_excluded" of :func:compute_dielectric_function for the volume of the minimised cell; "partial_susceptibility", {grouping: {"A-B": complex array}}, the share of every pair of labels in \(\varepsilon - \varepsilon_\infty\); "refractive_index", "extinction", "absorption_cm", "reflectivity" and "loss_function" of :func:compute_optical_response; and the "charges", "volume_a3", "eps_inf" and "damping_thz" used.

Raises:

Type Description
ValueError

Before any LAMMPS run, if max_atoms is not a positive integer, the structure has more than max_atoms atoms, the potential is empty, displacement is not positive and finite, force_tolerance is negative, zero or not finite, max_iter is not a positive integer, broadening_thz is not positive and finite, normalization is unknown, frequency_grid_thz is not 1-D, finite and strictly increasing with at least 2 points, temperatures_k is not finite and >= 0, driver is unknown, imaginary_threshold_thz is not >= 0, keep_dynamical_matrix is True without a tmp_working_directory, the directory of the matrix file has less free space than the file needs, or, with infrared, eps_inf or ir_damping_thz is not positive and finite, the cell has no volume, charges does not have shape \((N,)\) or \((N, 3, 3)\) or the potential defines no charge for an element. After the LAMMPS runs, if cutoff, former_types or o_type is invalid for :func:classify_vibrational_groups.

RuntimeError

If a LAMMPS run fails or the matrix file is missing or has the wrong size.

Warns:

Type Description
UserWarning

If the minimisation stops on a criterion other than the force or energy tolerance, the diagonalisation finds imaginary modes or dropped modes that are not translations, a caller's frequency_grid_thz is coarser than broadening_thz / 2, or temperatures_k is given but no mode has a positive frequency.

Example
>>> out = harmonic_vdos_simulation(glass, potential, temperatures_k=[300.0])  # doctest: +SKIP
>>> out["minimization"]["converged"], out["diagonalization"]["asymmetry"]  # doctest: +SKIP
>>> out["diagonalization"]["n_imaginary"], out["grid_integral"]  # doctest: +SKIP
>>> out["vdos"]["oxygen"]["O_BO"]  # doctest: +SKIP
>>> out["thermodynamics"]["heat_capacity_kb_per_atom"]  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/harmonic_simulation.py
def harmonic_vdos_simulation(
    structure: "Atoms",
    potential: pd.DataFrame,
    server_kwargs: dict[str, Any] | None = None,
    *,
    max_atoms: int = 10_000,
    displacement: float = 1e-5,
    force_tolerance: float = 1e-6,
    max_iter: int = 100_000,
    broadening_thz: float = 0.2,
    frequency_grid_thz: ArrayLike | None = None,
    normalization: HarmonicNormalization = "unit",
    temperatures_k: ArrayLike | None = None,
    cutoff: CutoffSpec | None = None,
    former_types: list[int] | None = None,
    o_type: int = 8,
    driver: EigenDriver = "evr",
    imaginary_threshold_thz: float = 0.01,
    tmp_working_directory: str | Path | None = None,
    keep_dynamical_matrix: bool = False,
    keep_eigenvectors: bool = False,
    infrared: bool = False,
    charges: ArrayLike | None = None,
    eps_inf: float = 1.0,
    ir_damping_thz: float = 0.5,
) -> dict[str, Any]:
    r"""Minimise a structure, compute its finite-difference dynamical matrix and return the harmonic VDOS and modes.

    The harmonic counterpart of :func:`vdos_simulation`: the VDOS of the 0 K inherent structure from its normal modes,
    with no MD and no statistical noise. Steps:

    1. Minimisation at fixed cell and the dynamical matrix, both in LAMMPS (``_run_lammps_dynamical_matrix``).
    2. The atom groups (element, oxygen class, $\mathrm{Q}^n$) with :func:`classify_vibrational_groups` and the
       masses, both from the minimised structure.
    3. The matrix is read with :func:`read_dynamical_matrix` and diagonalised in place with
       :func:`diagonalize_dynamical_matrix`, which drops the three translations.
    4. The broadened VDOS and its group partials with :func:`compute_harmonic_vdos`, the participation ratio of every
       mode with :func:`compute_participation_ratio` and, with ``temperatures_k``, the harmonic thermodynamics with
       :func:`compute_vibrational_thermodynamics`.

    The structure is used as given. Preparing it (melt-quench, NPT relaxation to the target pressure) is the caller's
    job; this function adds only the minimisation. The minimisation uses FIRE at fixed cell
    (``min_style="fire"``, no ``box/relax``) down to ``force_tolerance``, the LAMMPS ``ftol``: the 2-norm of the global
    force vector in eV/Å, not a per-atom maximum. A fixed cell leaves a residual pressure, reported in
    ``"minimization"`` (``"pressure_gpa"`` and ``"mean_pressure_gpa"``; for FIRE they also hold the kinetic term of
    the residual velocities), together with the iteration count, the stopping criterion and the final forces. If the
    tolerance is not reached, the minimiser warns and the result is still returned; the step-0 forces of the
    structure that was differentiated are in ``"dynamical_matrix"`` (``"max_force_ev_per_a"``).

    Finite differences: each entry of the matrix is a central difference of the forces with step ``displacement``.

    Imaginary modes are reported as negative frequencies in ``"mode_frequencies_thz"``. Those below
    ``-imaginary_threshold_thz`` are counted in ``"diagonalization"`` (``"n_imaginary"``, with a warning that names
    the asymmetry atoms); they point at an incomplete minimisation or a corrupted entry. Every negative frequency is
    left out of the VDOS (``"n_imaginary_excluded"`` and ``"imaginary_weight"``) and of the thermodynamics.

    ``max_atoms`` guards against an accidental large run: above it the function raises before anything runs, and the
    message gives the matrix size and the expected peak. It can be raised deliberately.

    The groups are classified on the minimised structure, the one whose modes are computed. Errors in ``cutoff``,
    ``former_types`` or ``o_type`` therefore surface only after the LAMMPS runs.

    The thermodynamics is computed from the broadened total VDOS on the frequency grid, not from a sum over the modes,
    with ``lowest_frequency_thz`` set to the smallest positive mode frequency, the lowest mode the box supports: the
    values below its temperature are flagged as unreliable. With ``normalization="3N"`` the total is divided by 3N
    first, as :func:`compute_vibrational_thermodynamics` needs a VDOS normalised to 1. On the 300-atom PMMCS glass at
    300 K with the default 0.2 THz broadening, the values differ from an exact sum over the modes by -1.3e-5 (C_V),
    8.5e-4 (S), 3.0e-5 (U) and -3.7e-4 (F), relative. The default grid starts at 0, so modes within a few
    ``broadening_thz`` of 0 lose part of their weight (``"excluded_weight"`` and ``"vdos_integral"`` report it).

    Disk and memory: the matrix file takes 9 N² x 8 bytes (2.6 GB at 6000 atoms, 7.2 GB at 10,000) and is deleted once
    it is read unless ``keep_dynamical_matrix``. It is written under ``tmp_working_directory`` or, if that is None,
    under the system temporary directory (``tempfile.gettempdir()``, set by ``TMPDIR``); the free space there is
    checked before anything runs. The peak in memory is still 2 matrices, during the diagonalisation.
    Without the eigenvectors, the result holds only O(M x number of labels) floats (the mode frequencies, participation
    ratios and group weights) plus the VDOS curves on the frequency grid. An eigenvector-based analysis later needs
    ``keep_eigenvectors=True`` or a rerun.

    Args:
        structure: The structure, e.g. a quenched and NPT-relaxed glass, used as given. It is not modified.
        potential: LAMMPS potential as a pandas DataFrame.
        server_kwargs: Additional arguments for the LAMMPS server (e.g. ``{"cores": 4}``), used by both LAMMPS runs.
        max_atoms: Largest number of atoms accepted, a positive integer.
        displacement: Finite-difference displacement in Å.
        force_tolerance: FIRE stops when the 2-norm of the global force vector is below this, in eV/Å.
        max_iter: Maximum number of FIRE iterations.
        broadening_thz: Standard deviation of the Gaussian broadening of each mode in THz (not the FWHM).
        frequency_grid_thz: Frequencies in THz at which the VDOS is evaluated, 1-D, finite and strictly increasing.
            ``None``: from 0 in steps of ``broadening_thz / 5`` up to the highest mode plus 5 ``broadening_thz``.
        normalization: ``"unit"`` (the total VDOS integrates to 1, in 1/THz) or ``"3N"`` (to ``3 * n_atoms``), each
            short by the share of imaginary modes.
        temperatures_k: Temperatures in K for the harmonic thermodynamics, a scalar or a 1-D array of finite values
            >= 0. ``None`` skips it.
        cutoff: Former-O cutoff in Å for the groups, as in :func:`classify_vibrational_groups`. Derived from the RDF
            of the minimised structure if ``None``.
        former_types: Atomic numbers of the network formers. Derived from the composition if ``None``.
        o_type: Atomic number of oxygen.
        driver: LAPACK driver of ``scipy.linalg.eigh``: ``"evr"`` (default), ``"evd"``, ``"evx"`` or ``"ev"``; see
            :func:`diagonalize_dynamical_matrix` for their memory and time.
        imaginary_threshold_thz: A mode below ``-imaginary_threshold_thz`` counts as imaginary in
            ``"diagonalization"``.
        tmp_working_directory: Directory for the LAMMPS runs and the matrix file. The run directories, with their
            logs, input and data files, are kept. The matrix file goes to its own ``harmonic_vdos_*`` subdirectory,
            which is removed once the matrix is read unless ``keep_dynamical_matrix``; nothing else in the directory is
            removed. If None, every run and the matrix file are removed.
        keep_dynamical_matrix: Keep the matrix file, in ``harmonic_vdos_*/dynamical_matrix.bin`` under
            ``tmp_working_directory``, instead of deleting it once read. Needs a ``tmp_working_directory``.
        keep_eigenvectors: Return the eigenvectors in ``"eigenvectors"``, one matrix in memory, instead of dropping
            them once the VDOS, the group partials and the participation ratios are computed.
        infrared: Also compute the infrared response of the modes: oscillator strengths, dielectric function and
            optical constants, returned in ``"infrared"``.
        charges: Atomic charges in units of the elementary charge for the infrared response, shape $(N,)$ or Born
            tensors $(N, 3, 3)$, in the order of the atoms. ``None`` reads the fixed charges of ``potential`` with
            :func:`charges_from_potential`. Ignored without ``infrared``.
        eps_inf: The high-frequency dielectric constant $\varepsilon_\infty$ of the infrared response; see
            :func:`compute_dielectric_function`.
        ir_damping_thz: The damping $\gamma$ of the dielectric function in THz; see
            :func:`compute_dielectric_function`.

    Returns:
        A dict with:
            ``"frequencies_thz"``: the frequency grid in THz.
            ``"vdos"``: ``{"total": array, "element": {...}, "oxygen": {...}, "qn": {...}}`` with the labels of
            ``"groups"``, in 1/THz, the layout of :func:`vdos_simulation`.
            ``"groups"``: the output of :func:`classify_vibrational_groups` on the minimised structure.
            ``"structure"``: the minimised structure.
            ``"normalization"``: the VDOS normalisation.
            ``"broadening_thz"``: the broadening in THz.
            ``"mode_frequencies_thz"``: the $M = 3N - 3$ mode frequencies in THz, ascending, negative for imaginary
            modes.
            ``"participation_ratio"``: the participation ratio of every mode, shape $(M,)$.
            ``"mode_weights"``: ``{grouping: {label: w}}``, each group's $(M,)$ share of every mode, as in
            :func:`compute_harmonic_vdos`.
            ``"n_imaginary_excluded"``: the number of modes with a negative frequency, left out of the VDOS.
            ``"imaginary_weight"``: their share of the normalisation.
            ``"grid_integral"``: the trapezoid integral of the total VDOS on the grid.
            ``"eigenvectors"``: the $(3N, M)$ mass-weighted eigenvectors, one mode per column; None unless
            ``keep_eigenvectors``.
            ``"dynamical_matrix"``: the summary of the LAMMPS dynamical-matrix run (``"matrix_path"``,
            ``"matrix_bytes"``, ``"n_atoms"``, ``"displacement_a"``, ``"style"``, the step-0 ``"max_force_ev_per_a"``
            and ``"force_norm_ev_per_a"``, ``"minimization"`` and ``"wall_time_s"``). ``"matrix_path"`` is the
            absolute path of the kept file; None unless ``keep_dynamical_matrix``.
            ``"minimization"``: the FIRE summary: ``"converged"``, ``"stopping_criterion"``, ``"n_iterations"``,
            ``"max_force_ev_per_a"``, ``"force_norm_ev_per_a"``, ``"pressure_gpa"``, ``"mean_pressure_gpa"``, the
            energies and volumes.
            ``"diagonalization"``: ``"asymmetry"``, ``"asymmetry_atoms"``, ``"translational_frequencies_thz"``,
            ``"translational_overlap"``, ``"n_imaginary"``, ``"min_frequency_thz"`` and ``"driver"``.
            ``"thermodynamics"``: the output of :func:`compute_vibrational_thermodynamics`, or None without
            ``temperatures_k`` or when no mode has a positive frequency (with a warning).
            ``"displacement_a"``: the finite-difference displacement in Å.
            ``"wall_time_s"``: ``{"lammps", "diagonalization", "analysis"}`` in s: both LAMMPS runs; reading and
            diagonalising the matrix; the groups, VDOS, participation ratios and thermodynamics.
            ``"infrared"``: None without ``infrared``, else a dict on the grid of the VDOS (``"frequencies_thz"``):
            ``"mode_charges"``, ``"strengths"`` and ``"partial_strengths"`` of
            :func:`compute_ir_oscillator_strengths` for the groups of ``"groups"``; ``"epsilon"``,
            ``"epsilon_static"`` and ``"n_modes_excluded"`` of :func:`compute_dielectric_function` for the volume
            of the minimised cell; ``"partial_susceptibility"``, ``{grouping: {"A-B": complex array}}``, the share
            of every pair of labels in $\varepsilon - \varepsilon_\infty$; ``"refractive_index"``,
            ``"extinction"``, ``"absorption_cm"``, ``"reflectivity"`` and ``"loss_function"`` of
            :func:`compute_optical_response`; and the ``"charges"``, ``"volume_a3"``, ``"eps_inf"`` and
            ``"damping_thz"`` used.

    Raises:
        ValueError: Before any LAMMPS run, if ``max_atoms`` is not a positive integer, the structure has more than
            ``max_atoms`` atoms, the potential is empty, ``displacement`` is not positive and finite,
            ``force_tolerance`` is negative, zero or not finite, ``max_iter`` is not a positive integer,
            ``broadening_thz`` is not positive and finite, ``normalization`` is unknown, ``frequency_grid_thz`` is not
            1-D, finite and strictly increasing with at least 2 points, ``temperatures_k`` is not finite and >= 0,
            ``driver`` is unknown, ``imaginary_threshold_thz`` is not >= 0, ``keep_dynamical_matrix`` is True
            without a ``tmp_working_directory``, the directory of the matrix file has less free space than the
            file needs, or, with ``infrared``, ``eps_inf`` or ``ir_damping_thz`` is not positive and finite, the cell
            has no volume, ``charges`` does not have shape $(N,)$ or $(N, 3, 3)$ or the potential defines no
            charge for an element. After the LAMMPS runs, if ``cutoff``, ``former_types`` or ``o_type``
            is invalid for :func:`classify_vibrational_groups`.
        RuntimeError: If a LAMMPS run fails or the matrix file is missing or has the wrong size.

    Warns:
        UserWarning: If the minimisation stops on a criterion other than the force or energy tolerance, the
            diagonalisation finds imaginary modes or dropped modes that are not translations, a caller's
            ``frequency_grid_thz`` is coarser than ``broadening_thz / 2``, or ``temperatures_k`` is given but no
            mode has a positive frequency.

    Example:
        ```pycon
        >>> out = harmonic_vdos_simulation(glass, potential, temperatures_k=[300.0])  # doctest: +SKIP
        >>> out["minimization"]["converged"], out["diagonalization"]["asymmetry"]  # doctest: +SKIP
        >>> out["diagonalization"]["n_imaginary"], out["grid_integral"]  # doctest: +SKIP
        >>> out["vdos"]["oxygen"]["O_BO"]  # doctest: +SKIP
        >>> out["thermodynamics"]["heat_capacity_kb_per_atom"]  # doctest: +SKIP

        ```
    """
    _harmonic_simulation_settings(
        structure,
        potential,
        max_atoms,
        displacement,
        force_tolerance,
        max_iter,
        broadening_thz,
        frequency_grid_thz,
        normalization,
        temperatures_k,
        driver,
        imaginary_threshold_thz,
        tmp_working_directory=tmp_working_directory,
        keep_dynamical_matrix=keep_dynamical_matrix,
    )
    infrared_settings = None
    if infrared:
        _validate_positive("ir_damping_thz", ir_damping_thz)
        _validate_positive("The cell volume", float(structure.cell.volume))
        infrared_settings = _infrared_settings(charges, eps_inf, potential, structure)
    with (
        contextlib.nullcontext(tempfile.mkdtemp(prefix="harmonic_vdos_", dir=tmp_working_directory))
        if keep_dynamical_matrix
        else tempfile.TemporaryDirectory(prefix="harmonic_vdos_", dir=tmp_working_directory)
    ) as matrix_dir:
        start = time.perf_counter()
        minimised, summary = _run_lammps_dynamical_matrix(
            structure,
            potential,
            Path(matrix_dir) / _HARMONIC_MATRIX_FILE,
            displacement=displacement,
            minimize=True,
            minimize_kwargs={
                "min_style": "fire",
                "pressure": None,
                "force_tolerance": force_tolerance,
                "max_iter": max_iter,
            },
            server_kwargs=server_kwargs,
            tmp_working_directory=tmp_working_directory,
        )
        lammps_s = time.perf_counter() - start
        start = time.perf_counter()
        groups = classify_vibrational_groups(minimised, cutoff, former_types, o_type)
        masses = minimised.get_masses()
        groups_s = time.perf_counter() - start
        start = time.perf_counter()
        matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"])
    if not keep_dynamical_matrix:
        summary = {**summary, "matrix_path": None}
    # Diagonalised in place; dropping the only reference afterwards frees the overwritten matrix, so the peak is the
    # matrix plus its eigenvectors and only the eigenvectors stay.
    modes = diagonalize_dynamical_matrix(
        matrix,
        masses=masses,
        overwrite_matrix=True,
        eigenvectors=True,
        driver=driver,
        imaginary_threshold_thz=imaginary_threshold_thz,
    )
    del matrix
    diagonalization_s = time.perf_counter() - start

    start = time.perf_counter()
    mode_frequencies, eigenvectors = modes["frequencies_thz"], modes.pop("eigenvectors")
    vdos = compute_harmonic_vdos(
        mode_frequencies,
        eigenvectors,
        groups=groups,
        frequency_grid_thz=frequency_grid_thz,
        broadening_thz=broadening_thz,
        normalization=normalization,
    )
    participation_ratio = compute_participation_ratio(eigenvectors, masses)
    infrared_result = None
    if infrared_settings is not None:
        infrared_result = _harmonic_infrared(
            mode_frequencies,
            eigenvectors,
            masses,
            groups,
            float(minimised.cell.volume),
            vdos["frequencies_thz"],
            ir_damping_thz,
            infrared_settings,
        )
    if not keep_eigenvectors:
        # The last reference to the eigenvector buffer: dropping it frees one matrix before the thermodynamics.
        eigenvectors = None
    thermodynamics = None
    positive_modes = mode_frequencies[mode_frequencies > 0]
    if temperatures_k is not None and positive_modes.size == 0:
        warnings.warn(
            "No mode has a positive frequency, so the thermodynamics are not computed ('thermodynamics' is None); "
            f"the lowest mode is {modes['min_frequency_thz']:.4g} THz. Check the minimisation and the asymmetry.",
            UserWarning,
            stacklevel=2,
        )
    elif temperatures_k is not None:
        total = vdos["vdos"]["total"] if normalization == "unit" else vdos["vdos"]["total"] / (3 * len(minimised))
        thermodynamics = compute_vibrational_thermodynamics(
            vdos["frequencies_thz"],
            total,
            temperatures_k,
            lowest_frequency_thz=float(positive_modes.min()),
        )
    analysis_s = groups_s + time.perf_counter() - start

    return {
        "frequencies_thz": vdos["frequencies_thz"],
        "vdos": vdos["vdos"],
        "groups": groups,
        "structure": minimised,
        "normalization": normalization,
        "broadening_thz": vdos["broadening_thz"],
        "mode_frequencies_thz": mode_frequencies,
        "participation_ratio": participation_ratio,
        "mode_weights": vdos["mode_weights"],
        "n_imaginary_excluded": vdos["n_imaginary_excluded"],
        "imaginary_weight": vdos["imaginary_weight"],
        "grid_integral": vdos["grid_integral"],
        "eigenvectors": eigenvectors,
        "dynamical_matrix": summary,
        "minimization": summary["minimization"],
        "diagonalization": {
            key: modes[key]
            for key in (
                "asymmetry",
                "asymmetry_atoms",
                "translational_frequencies_thz",
                "translational_overlap",
                "n_imaginary",
                "min_frequency_thz",
                "driver",
            )
        },
        "thermodynamics": thermodynamics,
        "displacement_a": summary["displacement_a"],
        "wall_time_s": {"lammps": lammps_s, "diagonalization": diagonalization_s, "analysis": analysis_s},
        "infrared": infrared_result,
    }

load_lammps_dump(path: str | Path, type_map: dict[int, str] | None = None, *, frame: int | None = None, start: int | None = None, stop: int | None = None, step: int | None = None, return_atoms_dict: bool = False) -> Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]

Read a LAMMPS dump file and return ASE Atoms object(s) with correct chemical symbols.

By default the full trajectory is returned as a list. Pass frame to get a single frame, or start / stop / step to slice the trajectory.

Parameters:

Name Type Description Default
path str | Path

Path to the LAMMPS dump file.

required
type_map dict[int, str] | None

Mapping from LAMMPS integer type to element symbol, e.g. {1: "O", 2: "Si"}. When None, the element column stored in the dump file is used.

None
frame int | None

Zero-based index of a single frame to read. Mutually exclusive with start / stop / step.

None
start int | None

First frame index of the slice (inclusive, default 0).

None
stop int | None

Last frame index of the slice (exclusive, default end of file).

None
step int | None

Stride between selected frames (default 1).

None
return_atoms_dict bool

When True, also return amorphouspy atoms_dict objects alongside the ase.Atoms objects (default False).

False

Returns:

Type Description
Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]
  • Single frame (frame given, return_atoms_dict False): Atoms
Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]
  • Single frame (frame given, return_atoms_dict True): (Atoms, dict)
Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]
  • Multiple frames (return_atoms_dict False): list[Atoms]
Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]
  • Multiple frames (return_atoms_dict True): list[tuple[Atoms, dict]]
Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]

Each atoms_dict contains "atoms", "box", and "total_atoms".

Raises:

Type Description
ValueError

If frame is combined with start / stop / step.

ValueError

If type_map is None and the dump file does not contain an element column.

Example
Full trajectory

frames = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"})

Single frame

ase_atoms = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"}, frame=0)

Frames 30-49

frames = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"}, start=30, stop=50)

Every 10th frame from 0 to 99

frames = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"}, start=0, stop=100, step=10)

Source code in amorphouspy/src/amorphouspy/lammps/io.py
def load_lammps_dump(
    path: str | Path,
    type_map: dict[int, str] | None = None,
    *,
    frame: int | None = None,
    start: int | None = None,
    stop: int | None = None,
    step: int | None = None,
    return_atoms_dict: bool = False,
) -> Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]:
    """Read a LAMMPS dump file and return ASE Atoms object(s) with correct chemical symbols.

    By default the full trajectory is returned as a list.  Pass *frame* to get a
    single frame, or *start* / *stop* / *step* to slice the trajectory.

    Args:
        path: Path to the LAMMPS dump file.
        type_map: Mapping from LAMMPS integer type to element symbol,
            e.g. ``{1: "O", 2: "Si"}``. When ``None``, the ``element``
            column stored in the dump file is used.
        frame: Zero-based index of a single frame to read.  Mutually exclusive
            with *start* / *stop* / *step*.
        start: First frame index of the slice (inclusive, default 0).
        stop: Last frame index of the slice (exclusive, default end of file).
        step: Stride between selected frames (default 1).
        return_atoms_dict: When ``True``, also return amorphouspy ``atoms_dict``
            objects alongside the ``ase.Atoms`` objects (default ``False``).

    Returns:
        - Single frame (``frame`` given, *return_atoms_dict* ``False``): ``Atoms``
        - Single frame (``frame`` given, *return_atoms_dict* ``True``): ``(Atoms, dict)``
        - Multiple frames (*return_atoms_dict* ``False``): ``list[Atoms]``
        - Multiple frames (*return_atoms_dict* ``True``): ``list[tuple[Atoms, dict]]``

        Each ``atoms_dict`` contains ``"atoms"``, ``"box"``, and ``"total_atoms"``.

    Raises:
        ValueError: If *frame* is combined with *start* / *stop* / *step*.
        ValueError: If *type_map* is ``None`` and the dump file does not contain
            an ``element`` column.

    Example:
        >>> # Full trajectory
        >>> frames = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"})
        >>> # Single frame
        >>> ase_atoms = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"}, frame=0)
        >>> # Frames 30-49
        >>> frames = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"}, start=30, stop=50)
        >>> # Every 10th frame from 0 to 99
        >>> frames = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"}, start=0, stop=100, step=10)

    """
    if frame is not None and any(x is not None for x in (start, stop, step)):
        msg = "'frame' cannot be combined with 'start', 'stop', or 'step'"
        raise ValueError(msg)

    single_frame = frame is not None
    index: int | slice = frame if frame is not None else slice(start, stop, step)

    raw = ase.io.read(str(path), format="lammps-dump-text", index=index)
    if single_frame:
        frames_list: list[Atoms] = [cast("Atoms", raw)]
    else:
        frames_list = [cast("Atoms", a) for a in (raw if isinstance(raw, list) else [raw])]

    def _apply_symbols(atoms: Atoms) -> None:
        if type_map is not None:
            atoms.set_chemical_symbols([type_map[int(t)] for t in atoms.arrays["type"]])
        elif "element" in atoms.arrays:
            atoms.set_chemical_symbols(list(atoms.arrays["element"]))
        else:
            msg = (
                "type_map is required when the dump file does not contain an 'element' column. "
                "Either pass type_map={1: 'O', 2: 'Si', ...} or add "
                "'dump_modify element O Si ...' to your LAMMPS input script."
            )
            raise ValueError(msg)

    for atoms in frames_list:
        _apply_symbols(atoms)

    if not return_atoms_dict:
        return frames_list[0] if single_frame else frames_list

    def _to_dict(atoms: Atoms) -> dict[str, Any]:
        box_length = float(atoms.get_cell()[0][0])
        atoms_list = [
            {"element": sym, "position": list(pos)}
            for sym, pos in zip(atoms.get_chemical_symbols(), atoms.get_positions(), strict=True)
        ]
        return {"atoms": atoms_list, "box": box_length, "total_atoms": len(atoms_list)}

    pairs = [(atoms, _to_dict(atoms)) for atoms in frames_list]
    return pairs[0] if single_frame else pairs

log_linear_dump_steps(total_steps: int, *, crossover_steps: int, points_per_decade: int = 9, linear_interval_steps: int, first_step: int = 0) -> list[int]

Return the timesteps of a log-then-linear dump schedule.

Below crossover_steps the spacing is decade-logarithmic (the LAMMPS logfreq pattern): with the default points_per_decade=9 the steps are 1, 2, ..., 9, 10, 20, ..., 90, 100, 200, ...; at and above the crossover the spacing is uniform (linear_interval_steps). This reproduces, bit-for-bit, the schedule realised in LAMMPS by :func:_log_linear_dump_variable, so it can be used to recover the exact per-frame times of a log-dumped trajectory.

Parameters:

Name Type Description Default
total_steps int

Number of production MD steps.

required
crossover_steps int

Step count corresponding to the log/linear crossover.

required
points_per_decade int

Log-spaced points per decade below the crossover (9 gives 1..9, 10..90, ...).

9
linear_interval_steps int

Uniform dump interval (in steps) at and above the crossover.

required
first_step int

First dumped step (usually 0).

0

Returns:

Type Description
list[int]

Sorted list of dump timesteps (inclusive of first_step, up to total_steps).

Example
>>> log_linear_dump_steps(100000, crossover_steps=100000, points_per_decade=9, linear_interval_steps=1000)[:12]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20]
Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
def log_linear_dump_steps(
    total_steps: int,
    *,
    crossover_steps: int,
    points_per_decade: int = 9,
    linear_interval_steps: int,
    first_step: int = 0,
) -> list[int]:
    """Return the timesteps of a log-then-linear dump schedule.

    Below *crossover_steps* the spacing is decade-logarithmic (the LAMMPS ``logfreq`` pattern): with
    the default ``points_per_decade=9`` the steps are 1, 2, ..., 9, 10, 20, ..., 90, 100, 200, ...; at
    and above the crossover the spacing is uniform (*linear_interval_steps*). This reproduces,
    bit-for-bit, the schedule realised in LAMMPS by :func:`_log_linear_dump_variable`, so it can be
    used to recover the exact per-frame times of a log-dumped trajectory.

    Args:
        total_steps: Number of production MD steps.
        crossover_steps: Step count corresponding to the log/linear crossover.
        points_per_decade: Log-spaced points per decade below the crossover (9 gives 1..9, 10..90, ...).
        linear_interval_steps: Uniform dump interval (in steps) at and above the crossover.
        first_step: First dumped step (usually 0).

    Returns:
        Sorted list of dump timesteps (inclusive of *first_step*, up to *total_steps*).

    Example:
        ```pycon
        >>> log_linear_dump_steps(100000, crossover_steps=100000, points_per_decade=9, linear_interval_steps=1000)[:12]
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20]

        ```
    """
    steps = [int(first_step)]
    current = first_step
    while current < total_steps:
        if current < crossover_steps:
            base = 10 ** (len(str(max(current, 1))) - 1)
            increment = max(1, int(base * 9 / points_per_decade + 0.5))
            nxt = current + increment
        else:
            nxt = current + linear_interval_steps
        current = int(nxt)
        if current <= total_steps:
            steps.append(current)
    return steps

md_simulation(structure: Atoms, potential: pd.DataFrame, temperature_sim: float | None = None, timestep: float = 1.0, production_steps: int = 10000000, n_dump: int | None = 1000, n_print_thermo: int | None = None, server_kwargs: dict | None = None, *, ensemble: Ensemble, temperature_end: float | None = None, npt_pressure: float | None = None, npt_pressure_end: float | None = None, seed: int = 12345, tmp_working_directory: str | Path | None = None, input_control_file: dict | None = None) -> dict

Perform a molecular dynamics simulation using LAMMPS.

This function equilibrates a structure at a predefined temperature and pressure, with optional linear ramps for temperature and/or pressure over the course of the simulation.

Parameters:

Name Type Description Default
structure Atoms

The initial atomic structure to be melted and quenched.

required
potential DataFrame

The potential file to be used for the simulation.

required
temperature_sim float | None

Start temperature in K (or constant temperature when temperature_end is None). Required for every ensemble except "nve", where it must be None.

None
timestep float

Time step for integration in femtoseconds (default is 1.0 fs).

1.0
production_steps int

The number of steps for the production.

10000000
n_dump int | None

Interval in MD steps for dumping. If None, only the last frame is dumped.

1000
n_print_thermo int | None

Interval in MD steps for printing thermodynamic information. If None, uses n_dump.

None
server_kwargs dict | None

Additional arguments for the server.

None
ensemble Ensemble

Thermodynamic ensemble, one of "nve", "nvt", "npt", "nvt_langevin" or "npt_langevin". "nve" runs unthermostatted dynamics starting from the velocities carried by structure, which must be non-zero (e.g. the output structure of a previous NVT run).

required
temperature_end float | None

End temperature in K for a linear ramp from temperature_sim. If None, temperature is held constant at temperature_sim. Not allowed for "nve".

None
npt_pressure float | None

Start pressure in GPa. Required for "npt" and "npt_langevin", not allowed otherwise.

None
npt_pressure_end float | None

End pressure in GPa for a linear pressure ramp ("npt" only). If None, pressure is held constant at npt_pressure.

None
seed int

Random seed for velocity initialization (default is 12345). Ignored if initial_temperature is 0.

12345
tmp_working_directory str | Path | None

Specifies the location of the temporary directory to run the simulations. Per default (None), the directory is located in the operating systems location for temporary files and is removed automatically once the run finishes. With the specification of tmp_working_directory, a uniquely-named sub-directory is created inside it and left in place afterwards (the caller owns it and is responsible for removing it), so the run artefacts such as log.lammps and the dump files remain available. tmp_working_directory needs to exist beforehand.

None
input_control_file dict | None

Optional LAMMPS input overrides merged on top of the default generated controls.

None

Returns:

Type Description
dict

A dictionary containing the simulation steps and temperature data.

Source code in amorphouspy/src/amorphouspy/lammps/md.py
def md_simulation(
    structure: Atoms,
    potential: pd.DataFrame,
    temperature_sim: float | None = None,
    timestep: float = 1.0,
    production_steps: int = 10_000_000,
    n_dump: int | None = 1000,
    n_print_thermo: int | None = None,
    server_kwargs: dict | None = None,
    *,
    ensemble: Ensemble,
    temperature_end: float | None = None,
    npt_pressure: float | None = None,
    npt_pressure_end: float | None = None,
    seed: int = 12345,
    tmp_working_directory: str | Path | None = None,
    input_control_file: dict | None = None,
) -> dict:  # pylint: disable=too-many-positional-arguments
    """Perform a molecular dynamics simulation using LAMMPS.

    This function equilibrates a structure at a predefined temperature and pressure, with optional
    linear ramps for temperature and/or pressure over the course of the simulation.

    Args:
        structure: The initial atomic structure to be melted and quenched.
        potential: The potential file to be used for the simulation.
        temperature_sim: Start temperature in K (or constant temperature when ``temperature_end`` is None).
            Required for every ensemble except ``"nve"``, where it must be None.
        timestep: Time step for integration in femtoseconds (default is 1.0 fs).
        production_steps: The number of steps for the production.
        n_dump: Interval in MD steps for dumping. If None, only the last frame is dumped.
        n_print_thermo: Interval in MD steps for printing thermodynamic information.
            If None, uses ``n_dump``.
        server_kwargs: Additional arguments for the server.
        ensemble: Thermodynamic ensemble, one of ``"nve"``, ``"nvt"``, ``"npt"``, ``"nvt_langevin"`` or
            ``"npt_langevin"``. ``"nve"`` runs unthermostatted dynamics starting from the velocities carried by
            ``structure``, which must be non-zero (e.g. the output structure of a previous NVT run).
        temperature_end: End temperature in K for a linear ramp from ``temperature_sim``.
            If None, temperature is held constant at ``temperature_sim``. Not allowed for ``"nve"``.
        npt_pressure: Start pressure in GPa. Required for ``"npt"`` and ``"npt_langevin"``, not allowed otherwise.
        npt_pressure_end: End pressure in GPa for a linear pressure ramp (``"npt"`` only).
            If None, pressure is held constant at ``npt_pressure``.
        seed: Random seed for velocity initialization (default is 12345). Ignored if ``initial_temperature`` is 0.
        tmp_working_directory: Specifies the location of the temporary directory to run the simulations.
            Per default (None), the directory is located in the operating systems location for temporary files
            and is removed automatically once the run finishes.
            With the specification of tmp_working_directory, a uniquely-named sub-directory is created inside
            it and left in place afterwards (the caller owns it and is responsible for removing it), so the run
            artefacts such as ``log.lammps`` and the dump files remain available. tmp_working_directory needs to
            exist beforehand.
        input_control_file: Optional LAMMPS input overrides merged on top of the
            default generated controls.

    Returns:
        A dictionary containing the simulation steps and temperature data.

    """
    if potential.empty:
        msg = "No matching potential found for the given configuration."
        raise ValueError(msg)
    structure_final, parsed_output = _run_lammps_md(
        structure=structure,
        potential=potential,
        tmp_working_directory=tmp_working_directory,
        temperature=temperature_sim,
        temperature_end=temperature_end,
        n_ionic_steps=production_steps,
        timestep=timestep,
        initial_temperature=None if ensemble == "nve" else temperature_sim,
        npt_pressure=npt_pressure,
        npt_pressure_end=npt_pressure_end,
        n_dump=n_dump,
        n_print_thermo=n_print_thermo,
        ensemble=ensemble,
        seed=seed,
        server_kwargs=server_kwargs,
        input_control_file=input_control_file,
    )

    result = parsed_output.get("generic", None)

    return {"structure": structure_final, "result": result}

melt_quench_simulation(structure: Atoms, potential: pd.DataFrame, temperature_high: float | None = None, temperature_low: float = 300.0, timestep: float = 1.0, cooling_rate: float | None = None, n_dump: int | None = None, n_print_thermo: int | None = 100, equilibration_steps: int | None = None, *, server_kwargs: dict | None = None, thermostat: Thermostat, seed: int = 12345, tmp_working_directory: str | Path | None = None, pre_equilibrate: bool = True, pre_equilibration_seed: int = DEFAULT_PRE_EQUILIBRATION_SEED) -> dict

Perform a melt-quench simulation using LAMMPS.

This function equilibrates the liquid directly at a high temperature and then cools it down to a low temperature, simulating a melt-quench process. There is no heating ramp: every protocol optionally pre-equilibrates the random structure at temperature_high (stage 0) and then equilibrates the melt at that temperature. The cooling rate is given in K/s, and the conversion into simulation steps is done automatically.

Parameters:

Name Type Description Default
structure Atoms

The initial atomic structure to be melted and quenched.

required
potential DataFrame

The potential file to be used for the simulation.

required
temperature_high float | None

The melt temperature at which the liquid is equilibrated. If None, the protocol's default melt temperature is used (e.g. 4000 K for SHIK, 5000 K for others).

None
temperature_low float

The low temperature to which the structure will be cooled.

300.0
timestep float

Time step for integration in femtoseconds.

1.0
cooling_rate float | None

The rate at which the temperature is decreased during the cooling phase, in K/s. If None, the protocol's default cooling rate is used (1e13 K/s for GRACE, 1e12 K/s for others).

None
n_dump int | None

Dump frequency in simulation steps. If None, falls back to the final step so only the last structure is dumped.

None
n_print_thermo int | None

Thermodynamic print frequency in simulation steps. If None, uses n_dump.

100
equilibration_steps int | None

Override for all fixed equilibration stages inside the protocol. If None, each protocol uses its own hardcoded defaults.

None
server_kwargs dict | None

Additional keyword arguments for the server.

None
thermostat Thermostat

Thermostat of all protocol stages, "nose_hoover" or "langevin".

required
seed int

Random seed for velocity initialization. Ignored if initial_temperature is 0.

12345
tmp_working_directory str | Path | None

Specifies the location of the temporary directory to run the simulations.

None
pre_equilibrate bool

Run a Langevin + nve/limit pre-equilibration block at temperature_high before the first stage. Needed for randomly placed structures; set to False when the starting structure is already equilibrated.

True
pre_equilibration_seed int

Seed of the Langevin random forces of the pre-equilibration stage. Independent of seed, which initializes the velocities of the melt stage.

DEFAULT_PRE_EQUILIBRATION_SEED

Returns:

Type Description
dict

A dictionary containing the simulation steps and temperature data.

Raises:

Type Description
ValueError

If the resolved temperature_high equals temperature_low (zero cooling steps would otherwise be sent to LAMMPS).

Example

result = melt_quench_simulation( ... structure=my_atoms, ... potential=my_potential, ... temperature_high=5000.0, ... temperature_low=300.0, ... cooling_rate=1e12, ... thermostat="nose_hoover", ... )

Source code in amorphouspy/src/amorphouspy/fabrication/meltquench.py
def melt_quench_simulation(
    structure: Atoms,
    potential: pd.DataFrame,
    temperature_high: float | None = None,
    temperature_low: float = 300.0,
    timestep: float = 1.0,
    cooling_rate: float | None = None,
    n_dump: int | None = None,
    n_print_thermo: int | None = 100,
    equilibration_steps: int | None = None,
    *,
    server_kwargs: dict | None = None,
    thermostat: Thermostat,
    seed: int = 12345,
    tmp_working_directory: str | Path | None = None,
    pre_equilibrate: bool = True,
    pre_equilibration_seed: int = DEFAULT_PRE_EQUILIBRATION_SEED,
) -> dict:  # pylint: disable=too-many-positional-arguments
    """Perform a melt-quench simulation using LAMMPS.

    This function equilibrates the liquid directly at a high temperature and
    then cools it down to a low temperature, simulating a melt-quench process.
    There is no heating ramp: every protocol optionally pre-equilibrates the
    random structure at `temperature_high` (stage 0) and then equilibrates the
    melt at that temperature. The cooling rate is given in K/s, and the
    conversion into simulation steps is done automatically.

    Args:
        structure: The initial atomic structure to be melted and quenched.
        potential: The potential file to be used for the simulation.
        temperature_high: The melt temperature at which the liquid is equilibrated.
            If None, the protocol's default melt temperature is used (e.g. 4000 K for SHIK, 5000 K for others).
        temperature_low: The low temperature to which the structure will be cooled.
        timestep: Time step for integration in femtoseconds.
        cooling_rate: The rate at which the temperature is decreased during the cooling phase,
            in K/s. If None, the protocol's default cooling rate is used (1e13 K/s for GRACE,
            1e12 K/s for others).
        n_dump: Dump frequency in simulation steps. If None, falls back to the
            final step so only the last structure is dumped.
        n_print_thermo: Thermodynamic print frequency in simulation steps.
            If None, uses n_dump.
        equilibration_steps: Override for all fixed equilibration stages inside the protocol.
            If None, each protocol uses its own hardcoded defaults.
        server_kwargs: Additional keyword arguments for the server.
        thermostat: Thermostat of all protocol stages, ``"nose_hoover"`` or ``"langevin"``.
        seed: Random seed for velocity initialization. Ignored if `initial_temperature` is 0.
        tmp_working_directory: Specifies the location of the temporary directory to run the simulations.
        pre_equilibrate: Run a Langevin + nve/limit pre-equilibration block at
            `temperature_high` before the first stage. Needed for randomly placed
            structures; set to False when the starting structure is already equilibrated.
        pre_equilibration_seed: Seed of the Langevin random forces of the pre-equilibration
            stage. Independent of `seed`, which initializes the velocities of the melt stage.

    Returns:
        A dictionary containing the simulation steps and temperature data.

    Raises:
        ValueError: If the resolved `temperature_high` equals `temperature_low`
            (zero cooling steps would otherwise be sent to LAMMPS).

    Example:
        >>> result = melt_quench_simulation(
        ...     structure=my_atoms,
        ...     potential=my_potential,
        ...     temperature_high=5000.0,
        ...     temperature_low=300.0,
        ...     cooling_rate=1e12,
        ...     thermostat="nose_hoover",
        ... )

    """
    seconds_to_femtos = 1e15
    potential_name = str(potential.loc[0, "Name"]).lower()

    if temperature_high is None:
        temperature_high = DEFAULT_MELT_TEMPERATURES.get(potential_name, 5000.0)
    if cooling_rate is None:
        cooling_rate = DEFAULT_COOLING_RATES.get(potential_name, 1e12)

    if temperature_high == temperature_low:
        msg = (
            f"temperature_high must differ from temperature_low (both are {temperature_high} K): "
            "cooling requires a nonzero temperature range."
        )
        raise ValueError(msg)

    cooling_steps = int(((temperature_high - temperature_low) / (timestep * cooling_rate)) * seconds_to_femtos)

    if potential_name in {"bmp-screened-harmonic", "bmp-harmonic"}:
        potential_name = "bmp"  # both variants share the same MD protocol

    # Check if protocol exists
    elif potential_name not in PROTOCOL_MAP:
        available = ", ".join(PROTOCOL_MAP.keys())
        msg = f"Unknown potential: {potential_name}. Available protocols: {available}"
        raise ValueError(msg)

    # Create parameters dataclass
    params = MeltQuenchParams(
        structure=structure,
        potential=potential,
        temperature_high=temperature_high,
        temperature_low=temperature_low,
        cooling_steps=cooling_steps,
        timestep=timestep,
        n_dump=n_dump,
        n_print_thermo=n_print_thermo,
        thermostat=thermostat,
        seed=seed,
        server_kwargs=server_kwargs,
        tmp_working_directory=tmp_working_directory,
        equilibration_steps=equilibration_steps,
        pre_equilibrate=pre_equilibrate,
        pre_equilibration_seed=pre_equilibration_seed,
    )

    # Run the protocol using the function-based approach
    protocol_func = PROTOCOL_MAP[potential_name]
    structure_final, history = protocol_func(_run_lammps_md, params)

    return {
        "structure": structure_final,
        "result": history,
    }

parse_formula(formula: str) -> dict[str, int]

Parse a chemical formula and returns a dictionary of element counts.

Parameters:

Name Type Description Default
formula str

A string representing the chemical formula (e.g., "Al2O3").

required

Returns:

Name Type Description
dict[str, int]

A dictionary mapping element symbols to their counts.

Example dict[str, int]

{"Al": 2, "O": 3} for "Al2O3".

Source code in amorphouspy/src/amorphouspy/fabrication/composition.py
def parse_formula(formula: str) -> dict[str, int]:
    """Parse a chemical formula and returns a dictionary of element counts.

    Args:
        formula: A string representing the chemical formula (e.g., "Al2O3").

    Returns:
        A dictionary mapping element symbols to their counts.
        Example: {"Al": 2, "O": 3} for "Al2O3".

    """
    counts: dict[str, int] = {}
    for elem, cnt_str in ELEMENT.findall(formula):
        cnt = int(cnt_str) if cnt_str else 1
        counts[elem] = counts.get(elem, 0) + cnt
    return counts

plan_system(composition: dict[str, float], target: int, mode: str = 'molar', target_type: str = 'atoms') -> dict

Generate a comprehensive plan for the system composition and size.

This unified planner handles both 'atoms' and 'molecules' target types, converting them into a concrete allocation of formula units and atoms.

Parameters:

Name Type Description Default
composition dict[str, float]

A dictionary mapping oxide formulas to their fractions.

required
target int

The target count (atoms or molecules depending on target_type).

required
mode str

The composition mode ('molar' or 'weight'). Defaults to "molar".

'molar'
target_type str

The type of target ('atoms' or 'molecules'). Defaults to "atoms".

'atoms'

Returns:

Type Description
dict

A dictionary containing: - "mol_fraction": Dictionary of molar fractions. - "formula_units": Dictionary of allocated integer formula units. - "total_atoms": The actual total number of atoms. - "element_counts": Dictionary of total counts per element.

Raises:

Type Description
ValueError

If target_type is not 'atoms' or 'molecules'.

Source code in amorphouspy/src/amorphouspy/fabrication/planner.py
def plan_system(composition: dict[str, float], target: int, mode: str = "molar", target_type: str = "atoms") -> dict:
    """Generate a comprehensive plan for the system composition and size.

    This unified planner handles both 'atoms' and 'molecules' target types,
    converting them into a concrete allocation of formula units and atoms.

    Args:
        composition: A dictionary mapping oxide formulas to their fractions.
        target: The target count (atoms or molecules depending on `target_type`).
        mode: The composition mode ('molar' or 'weight'). Defaults to "molar".
        target_type: The type of target ('atoms' or 'molecules'). Defaults to "atoms".

    Returns:
        A dictionary containing:
            - "mol_fraction": Dictionary of molar fractions.
            - "formula_units": Dictionary of allocated integer formula units.
            - "total_atoms": The actual total number of atoms.
            - "element_counts": Dictionary of total counts per element.

    Raises:
        ValueError: If `target_type` is not 'atoms' or 'molecules'.

    """
    mol_frac = get_composition(composition, mode=mode)

    if target_type == "atoms":
        target_atoms = target
    elif target_type == "molecules":
        total_atoms_per_mol = sum(fraction * sum(parse_formula(oxide).values()) for oxide, fraction in mol_frac.items())
        target_atoms = round(target * total_atoms_per_mol)
    else:
        error_msg = f"Invalid target_type: {target_type}. Supported types are 'atoms' and 'molecules'."
        raise ValueError(error_msg)

    ni, n_atoms = allocate_formula_units_to_target_atoms(mol_frac, target_atoms)
    elem_counts = element_counts_from_formula_units(ni)
    return {
        "mol_fraction": mol_frac,
        "formula_units": ni,
        "total_atoms": n_atoms,
        "element_counts": elem_counts,
    }

plot_analysis_results_plotly(structure_data: StructureData) -> go.Figure

Generate interactive Plotly plots for structural analysis results.

Parameters:

Name Type Description Default
structure_data StructureData

Structural analysis results.

required

Returns:

Type Description
Figure

Interactive Plotly figure object.

Example

fig = plot_analysis_results_plotly(structure_data) fig.show()

Source code in amorphouspy/src/amorphouspy/properties/structural/all.py
def plot_analysis_results_plotly(structure_data: StructureData) -> go.Figure:
    """Generate interactive Plotly plots for structural analysis results.

    Args:
        structure_data: Structural analysis results.

    Returns:
        Interactive Plotly figure object.

    Example:
        >>> fig = plot_analysis_results_plotly(structure_data)
        >>> fig.show()

    """
    # Create subplot layout (4x3 grid)
    fig = make_subplots(
        rows=4,
        cols=3,
        subplot_titles=[
            "Oxygen Coordination",
            "Former Coordination",
            "Modifier Coordination",
            "Q^n Distribution",
            "Bond Angles",
            "Ring Statistics",
            "O-O RDF",
            "Former-O RDFs",
            "Modifier-O RDFs",
            "Total S(q) — Neutron",
            "Total S(q) — X-ray",
            "Partial S(q)",
        ],
        specs=[
            [{"type": "bar"}, {"type": "bar"}, {"type": "bar"}],
            [{"type": "bar"}, {"type": "scatter"}, {"type": "bar"}],
            [{"type": "scatter"}, {"type": "scatter"}, {"type": "scatter"}],
            [{"type": "scatter"}, {"type": "scatter"}, {"type": "scatter"}],
        ],
        vertical_spacing=0.08,
        horizontal_spacing=0.08,
    )

    fig.update_annotations(font_size=12, font_family="Arial, sans-serif")

    colors = ["#0072B2", "#E69F00", "#009E73", "#D55E00", "#CC79A7", "#56B4E9", "#F0E442"]

    _add_coordination_plots(fig, structure_data, colors)
    _add_network_plots(fig, structure_data, colors)
    _add_ring_plots(fig, structure_data, colors)
    _add_rdf_plots(fig, structure_data, colors)
    _add_structure_factor_plots(fig, structure_data, colors)

    # Position legends inside each subplot (top-right corner)
    axis_to_legend: dict[str, str] = {}
    legend_layout: dict[str, dict] = {}

    for idx in range(1, 13):
        ax_suffix = str(idx) if idx > 1 else ""
        x_ref = f"x{ax_suffix}"
        legend_name = f"legend{idx}" if idx > 1 else "legend"

        x_domain = getattr(fig.layout, f"xaxis{ax_suffix}").domain
        y_domain = getattr(fig.layout, f"yaxis{ax_suffix}").domain

        axis_to_legend[x_ref] = legend_name
        legend_layout[legend_name] = {
            "x": x_domain[1],
            "y": y_domain[1],
            "xanchor": "right",
            "yanchor": "top",
            "bgcolor": "rgba(255,255,255,0.7)",
            "font": {"size": 10},
        }

    for trace in fig.data:
        x_ref = trace.xaxis or "x"
        if x_ref in axis_to_legend:
            trace.update(legend=axis_to_legend[x_ref])

    # Update layout and axes
    fig.update_layout(
        height=1300,
        width=1300,
        showlegend=True,
        template="plotly_white",
        font={"family": "Arial, sans-serif", "size": 12},
        **legend_layout,
    )

    # Row 1: Coordination plots
    fig.update_xaxes(title_text="O_n", row=1, col=1)
    fig.update_yaxes(title_text="Percentage", row=1, col=1)
    fig.update_xaxes(title_text="Former_n", row=1, col=2)
    fig.update_yaxes(title_text="Percentage", row=1, col=2)
    fig.update_xaxes(title_text="Modifier_n", row=1, col=3)
    fig.update_yaxes(title_text="Percentage", row=1, col=3)

    # Row 2: Q^n, Bond angles, Ring statistics
    fig.update_xaxes(title_text="Q^n", row=2, col=1)
    fig.update_yaxes(title_text="Percentage", row=2, col=1)
    fig.update_xaxes(title_text="Angle (degrees)", row=2, col=2)
    fig.update_yaxes(title_text="Frequency", row=2, col=2)
    fig.update_xaxes(title_text="Former atoms in ring", row=2, col=3)
    fig.update_yaxes(title_text="Normalized count", row=2, col=3)

    # Row 3: RDF plots
    for col in [1, 2, 3]:
        fig.update_xaxes(title_text="r (Å)", range=[0, 10], row=3, col=col)
        fig.update_yaxes(title_text="g(r), CN(r)", range=[0, 25], row=3, col=col)

    # Row 4: Structure factor
    fig.update_xaxes(title_text="q (Å⁻¹)", row=4, col=1)
    fig.update_yaxes(title_text="S(q)", row=4, col=1)
    fig.update_xaxes(title_text="q (Å⁻¹)", row=4, col=2)
    fig.update_yaxes(title_text="S(q)", row=4, col=2)
    fig.update_xaxes(title_text="q (Å⁻¹)", row=4, col=3)
    fig.update_yaxes(title_text="S(q)", row=4, col=3)

    # Global grid and axis line styling (applied last so it doesn't conflict with per-axis overrides)
    fig.update_xaxes(showgrid=True, gridcolor="rgba(180,180,180,0.3)", zeroline=False, showline=True, mirror=False)
    fig.update_yaxes(showgrid=True, gridcolor="rgba(180,180,180,0.3)", zeroline=False, showline=True, mirror=False)

    return fig

read_dynamical_matrix(path: str | Path, n_atoms: int, *, binary: bool = True, style: DynamicalMatrixStyle = 'regular') -> NDArray[np.float64]

Read a dynamical-matrix file written by the LAMMPS dynamical_matrix command.

The dynamical matrix is the mass-weighted Hessian

\[D_{i\alpha, j\beta} = \frac{\Phi_{i\alpha, j\beta}}{\sqrt{m_i m_j}}, \quad \Phi_{i\alpha, j\beta} = \frac{\partial^2 E}{\partial r_{i\alpha}\, \partial r_{j\beta}},\]

with \(E\) the potential energy, \(r_{i\alpha}\) the coordinates and \(m_i\) the masses. It is returned in eV/Ų/amu (LAMMPS regular in metal units). An eigenvalue \(\lambda\) of \(D\) gives the angular frequency \(\omega = \sqrt{\lambda}\) and the frequency \(\nu = \sqrt{\lambda} / (2\pi)\), where \(\sqrt{1\ \mathrm{eV/Å^2/amu}}\) corresponds to \(\nu = 15.633\) THz. Row and column \(3i + \alpha\) belong to atom \(i\) (0-based, the LAMMPS atom id minus one) and \(\alpha \in \{x, y, z\}\) (\(0, 1, 2\)), so the atom order is the LAMMPS id order. For files written by _run_lammps_dynamical_matrix that is the order of the atoms in the structure.

The matrix is returned as written, NOT symmetrised. A finite-difference matrix is symmetric only to the difference error, and a larger asymmetry \(\max|D - D^\mathsf{T}| / \max|D|\) flags corrupted entries, for example a pair that crosses a cutoff with a force jump during a displacement. The asymmetry is therefore left for the caller to measure before symmetrising.

File formats (verified on LAMMPS 29 Aug 2024):

  • binary=True (binary yes): raw float64 in native byte order, no header, exactly \(9 N^2 \times 8\) bytes. It is read with np.fromfile and reshaped without a copy.
  • binary=False (binary no): three values per line in %.8f, one line per atom of a row, so each matrix row spans \(N\) lines. Eight fixed decimals limit the precision to \(5 \times 10^{-9}\) eV/Ų/amu absolute. The text is parsed with np.loadtxt, which is about six times faster than np.fromfile(sep=" ") here.

With style="eskm" the file holds the matrix in 10 J/mol/Ų/(g/mol); it is divided in place by 9648.5, the factor LAMMPS uses (the CODATA value \(e N_\mathrm{A} / 10 = 9648.533\) differs by \(3.4 \times 10^{-6}\)), and returned in eV/Ų/amu.

Memory: the result is one array of \(9 N^2 \times 8\) bytes, 2.6 GB at 6000 atoms and 7.2 GB at 10,000. A binary read needs nothing more. Parsing text peaks at about 2.2 times the matrix (numpy allocations measured at 1000 and 2000 atoms), about 16 GB at 10,000 atoms. Non-finite values are checked in blocks of rows, so the check adds at most _CHUNK_BYTES / 8 bytes.

Parameters:

Name Type Description Default
path str | Path

The dynamical-matrix file.

required
n_atoms int

Number of atoms \(N\) in the structure the matrix was computed on.

required
binary bool

True for a file written with binary yes, False for binary no.

True
style DynamicalMatrixStyle

The LAMMPS style the file was written with, "regular" or "eskm".

'regular'

Returns:

Type Description
NDArray[float64]

The \((3N, 3N)\) dynamical matrix in eV/Ų/amu, float64, C-contiguous and writable.

Raises:

Type Description
ValueError

If n_atoms is not a positive integer, style is unknown, the file does not hold \(9 N^2\) values (the size is checked before a binary file is read), or the matrix contains NaN or inf.

FileNotFoundError

If path does not exist.

Example
>>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin")  # doctest: +SKIP
>>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"])  # doctest: +SKIP
>>> asymmetry = np.abs(matrix - matrix.T).max() / np.abs(matrix).max()  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/dynamical_matrix.py
def read_dynamical_matrix(
    path: str | Path,
    n_atoms: int,
    *,
    binary: bool = True,
    style: DynamicalMatrixStyle = "regular",
) -> NDArray[np.float64]:
    r"""Read a dynamical-matrix file written by the LAMMPS ``dynamical_matrix`` command.

    The dynamical matrix is the mass-weighted Hessian

    $$D_{i\alpha, j\beta} = \frac{\Phi_{i\alpha, j\beta}}{\sqrt{m_i m_j}}, \quad
    \Phi_{i\alpha, j\beta} = \frac{\partial^2 E}{\partial r_{i\alpha}\, \partial r_{j\beta}},$$

    with $E$ the potential energy, $r_{i\alpha}$ the coordinates and $m_i$ the masses. It is returned in eV/Ų/amu
    (LAMMPS ``regular`` in metal units). An eigenvalue $\lambda$ of $D$ gives the angular frequency
    $\omega = \sqrt{\lambda}$ and the frequency $\nu = \sqrt{\lambda} / (2\pi)$, where
    $\sqrt{1\ \mathrm{eV/Å^2/amu}}$ corresponds to $\nu = 15.633$ THz. Row and column $3i + \alpha$ belong to atom
    $i$ (0-based, the LAMMPS atom id minus one) and $\alpha \in \{x, y, z\}$ ($0, 1, 2$), so the atom order is the
    LAMMPS id order. For files written by ``_run_lammps_dynamical_matrix`` that is the order of the atoms in the
    structure.

    The matrix is returned as written, NOT symmetrised. A finite-difference matrix is symmetric only to the
    difference error, and a larger asymmetry $\max|D - D^\mathsf{T}| / \max|D|$ flags corrupted entries, for example
    a pair that crosses a cutoff with a force jump during a displacement. The asymmetry is therefore left for the
    caller to measure before symmetrising.

    File formats (verified on LAMMPS 29 Aug 2024):

    - ``binary=True`` (``binary yes``): raw float64 in native byte order, no header, exactly $9 N^2 \times 8$ bytes.
      It is read with ``np.fromfile`` and reshaped without a copy.
    - ``binary=False`` (``binary no``): three values per line in ``%.8f``, one line per atom of a row, so each matrix
      row spans $N$ lines. Eight fixed decimals limit the precision to $5 \times 10^{-9}$ eV/Ų/amu absolute. The
      text is parsed with ``np.loadtxt``, which is about six times faster than ``np.fromfile(sep=" ")`` here.

    With ``style="eskm"`` the file holds the matrix in 10 J/mol/Ų/(g/mol); it is divided in place by 9648.5, the
    factor LAMMPS uses (the CODATA value $e N_\mathrm{A} / 10 = 9648.533$ differs by $3.4 \times 10^{-6}$), and
    returned in eV/Ų/amu.

    Memory: the result is one array of $9 N^2 \times 8$ bytes, 2.6 GB at 6000 atoms and 7.2 GB at 10,000. A binary
    read needs nothing more. Parsing text peaks at about 2.2 times the matrix (numpy allocations measured at 1000 and
    2000 atoms), about 16 GB at 10,000 atoms. Non-finite values are checked in blocks of rows, so the check adds at
    most ``_CHUNK_BYTES / 8`` bytes.

    Args:
        path: The dynamical-matrix file.
        n_atoms: Number of atoms $N$ in the structure the matrix was computed on.
        binary: True for a file written with ``binary yes``, False for ``binary no``.
        style: The LAMMPS style the file was written with, ``"regular"`` or ``"eskm"``.

    Returns:
        The $(3N, 3N)$ dynamical matrix in eV/Ų/amu, float64, C-contiguous and writable.

    Raises:
        ValueError: If ``n_atoms`` is not a positive integer, ``style`` is unknown, the file does not hold $9 N^2$
            values (the size is checked before a binary file is read), or the matrix contains NaN or inf.
        FileNotFoundError: If ``path`` does not exist.

    Example:
        ```pycon
        >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin")  # doctest: +SKIP
        >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"])  # doctest: +SKIP
        >>> asymmetry = np.abs(matrix - matrix.T).max() / np.abs(matrix).max()  # doctest: +SKIP
        ```
    """
    if isinstance(n_atoms, bool) or not isinstance(n_atoms, int | np.integer) or n_atoms < 1:
        msg = f"n_atoms must be a positive integer, got {n_atoms!r}."
        raise ValueError(msg)
    if style not in _DYNAMICAL_MATRIX_STYLES:
        msg = f"Unknown style {style!r}; allowed styles are {list(_DYNAMICAL_MATRIX_STYLES)}."
        raise ValueError(msg)
    n_dof = 3 * int(n_atoms)
    if binary:
        n_bytes = Path(path).stat().st_size
        itemsize = np.dtype(np.float64).itemsize
        if n_bytes % itemsize:
            msg = f"The binary file {path} has {n_bytes} bytes, not a whole number of float64 values."
            raise ValueError(msg)
        _check_value_count(n_bytes // itemsize, n_atoms, f"The binary file {path}")
        values = np.fromfile(path, dtype=np.float64)
    else:
        values = np.loadtxt(path, dtype=np.float64).ravel()
        _check_value_count(values.size, n_atoms, f"The text file {path}")
    matrix = values.reshape(n_dof, n_dof)
    rows_per_chunk = max(1, _common._CHUNK_BYTES // (n_dof * matrix.itemsize))  # noqa: SLF001
    for start in range(0, n_dof, rows_per_chunk):
        if not np.isfinite(matrix[start : start + rows_per_chunk]).all():
            msg = (
                f"The dynamical matrix in {path} contains NaN or inf "
                f"in rows {start} to {min(start + rows_per_chunk, n_dof) - 1}."
            )
            raise ValueError(msg)
    if style == "eskm":
        matrix /= _ESKM_PER_REGULAR
    return matrix

run_melt_quench(structure: Atoms, potential: pd.DataFrame, *, potential_type: str = 'pmmcs', cooling_rate: float | None = None, timestep: float = 1.0, temperature_high: float | None = None, temperature_low: float = 300.0, equilibration_steps: int | None = None, n_dump: int | None = 100000, n_print_thermo: int | None = None, server_kwargs: dict[str, Any] | None = None, pre_equilibrate: bool = True) -> dict[str, Any]

Run a LAMMPS melt-quench simulation.

Parameters:

Name Type Description Default
structure Atoms

Initial ASE Atoms object.

required
potential DataFrame

LAMMPS potential object from generate_potential.

required
potential_type str

Potential name, used for default temperature_high and cooling_rate lookup.

'pmmcs'
cooling_rate float | None

Cooling rate in K/s; None uses the protocol default.

None
timestep float

MD timestep in fs.

1.0
temperature_high float | None

Melt temperature in K; None uses the protocol default.

None
temperature_low float

Final quench temperature in K.

300.0
equilibration_steps int | None

Override for equilibration step count; None = protocol default.

None
n_dump int | None

Trajectory dump frequency (steps). None uses the final step only.

100000
n_print_thermo int | None

Thermodynamic output frequency (steps). None uses n_dump.

None
server_kwargs dict[str, Any] | None

LAMMPS server/resource configuration.

None
pre_equilibrate bool

Run a Langevin + nve/limit pre-equilibration block at temperature_high before the first stage. Needed for randomly placed structures; set to False when the starting structure is already equilibrated.

True

Returns:

Type Description
dict[str, Any]

Dict with final_structure, mean_temperature, simulation_steps,

dict[str, Any]

composition, trajectory data, and simulation parameters.

Source code in amorphouspy/src/amorphouspy/pipelines/meltquench.py
def run_melt_quench(
    structure: Atoms,
    potential: pd.DataFrame,
    *,
    potential_type: str = "pmmcs",
    cooling_rate: float | None = None,
    timestep: float = 1.0,
    temperature_high: float | None = None,
    temperature_low: float = 300.0,
    equilibration_steps: int | None = None,
    n_dump: int | None = 100_000,
    n_print_thermo: int | None = None,
    server_kwargs: dict[str, Any] | None = None,
    pre_equilibrate: bool = True,
) -> dict[str, Any]:
    """Run a LAMMPS melt-quench simulation.

    Args:
        structure: Initial ASE Atoms object.
        potential: LAMMPS potential object from ``generate_potential``.
        potential_type: Potential name, used for default ``temperature_high`` and ``cooling_rate`` lookup.
        cooling_rate: Cooling rate in K/s; ``None`` uses the protocol default.
        timestep: MD timestep in fs.
        temperature_high: Melt temperature in K; ``None`` uses the protocol default.
        temperature_low: Final quench temperature in K.
        equilibration_steps: Override for equilibration step count; ``None`` = protocol default.
        n_dump: Trajectory dump frequency (steps). ``None`` uses the final step only.
        n_print_thermo: Thermodynamic output frequency (steps). ``None`` uses ``n_dump``.

        server_kwargs: LAMMPS server/resource configuration.
        pre_equilibrate: Run a Langevin + nve/limit pre-equilibration block at
            ``temperature_high`` before the first stage. Needed for randomly placed
            structures; set to ``False`` when the starting structure is already equilibrated.

    Returns:
        Dict with ``final_structure``, ``mean_temperature``, ``simulation_steps``,
        ``composition``, trajectory data, and simulation parameters.
    """
    if server_kwargs is None:
        server_kwargs = {}

    if temperature_high is None:
        temperature_high = DEFAULT_MELT_TEMPERATURES.get(potential_type, 5000.0)
    if cooling_rate is None:
        cooling_rate = DEFAULT_COOLING_RATES.get(potential_type, 1e12)

    mq = melt_quench_simulation(
        structure=structure,
        potential=potential,
        n_dump=n_dump,
        n_print_thermo=n_print_thermo,
        cooling_rate=int(cooling_rate),
        timestep=timestep,
        temperature_high=temperature_high,
        temperature_low=temperature_low,
        equilibration_steps=equilibration_steps,
        thermostat="nose_hoover",
        server_kwargs=server_kwargs,
        pre_equilibrate=pre_equilibrate,
    )

    # Extract only the data of the last stage of the melt-quench simulation to
    # compute selected summaries for the final output. "simulation_history" will
    # still contain the full trajectory of all stages at this point.
    last_stage = next((s for s in reversed(mq["result"]) if s is not None), {})

    return {
        "final_structure": mq["structure"],
        "mean_temperature": float(np.mean(last_stage["temperature"])),
        "simulation_steps": len(last_stage["steps"]),
        "temperature_trajectory": [float(t) for t in last_stage["temperature"]],
        "steps_trajectory": [int(s) for s in last_stage["steps"]],
        "simulation_history": mq["result"],
        "timestep": timestep,
        "cooling_rate": int(cooling_rate),
        "temperature_high": temperature_high,
        "temperature_low": temperature_low,
        "n_dump": n_dump,
        "n_print_thermo": (n_dump if n_print_thermo is None else n_print_thermo),
    }

run_structural_analysis(final_structure: Atoms, potential: LammpsPotential | None = None, timestep: float = 1.0, n_averaging_frames: int = 1, n_jobs: int | None = None, temperature: float = 300.0, server_kwargs: dict[str, Any] | None = None, r_max: float = 10.0, n_bins: int = 500) -> tuple[StructureData, StructureData | None, int, list[dict[str, Any]] | None]

Run structural analysis, optionally averaging over trajectory frames.

Parameters:

Name Type Description Default
final_structure Atoms

Structure to be analyzed or to use as starting structure for a NVT simulation.

required
potential LammpsPotential | None

LAMMPS potential (str, pd.DataFrame, or dict). Required when n_averaging_frames > 1.

None
timestep float

MD timestep in fs.

1.0
n_averaging_frames int

Number of frames to collect for averaging. If set to 1, then no MD simulation and only the provided structure is analyzed. If set to >1, then an additional NVT simulation is run to collect frames for averaging.

1
n_jobs int | None

Number of worker processes for frame-averaging post-processing. None auto-selects a conservative value based on about half of the allocated LAMMPS cores, defaulting to one core when no allocation is configured. Explicit values must be at least 1. Both explicit and automatic values are capped by the allocated LAMMPS cores and by n_averaging_frames + 1 (+1 accounts for frame 0).

None
temperature float

Temperature (K) for NVT equilibration/production simulation.

300.0
server_kwargs dict[str, Any] | None

LAMMPS server configuration dict.

None
r_max float

Maximum radius in Å for RDF calculation (default 10.0).

10.0
n_bins int

Number of bins for RDF calculation (default 500).

500

Returns:

Type Description
StructureData

Tuple of (mean_data, sem_data, n_frames, sampling_history) where

StructureData | None

sem_data is always returned as StructureData (for one frame, SEM

int

values are computed from a single sample and are typically zero) and

list[dict[str, Any]] | None

sampling_history is the raw NVT parsed output wrapped as a single

tuple[StructureData, StructureData | None, int, list[dict[str, Any]] | None]

stage list when n_averaging_frames > 1.

Source code in amorphouspy/src/amorphouspy/properties/structural/all.py
def run_structural_analysis(
    final_structure: Atoms,
    potential: LammpsPotential | None = None,
    timestep: float = 1.0,
    n_averaging_frames: int = 1,
    n_jobs: int | None = None,
    temperature: float = 300.0,
    server_kwargs: dict[str, Any] | None = None,
    r_max: float = 10.0,
    n_bins: int = 500,
) -> tuple[StructureData, StructureData | None, int, list[dict[str, Any]] | None]:
    """Run structural analysis, optionally averaging over trajectory frames.

    Args:
        final_structure: Structure to be analyzed or to use as starting structure for a NVT simulation.
        potential: LAMMPS potential (str, pd.DataFrame, or dict). Required when ``n_averaging_frames > 1``.
        timestep: MD timestep in fs.
        n_averaging_frames: Number of frames to collect for averaging. If set to 1, then no MD
            simulation and only the provided structure is analyzed. If set to >1, then an additional NVT
            simulation is run to collect frames for averaging.
        n_jobs: Number of worker processes for frame-averaging post-processing.
            ``None`` auto-selects a conservative value based on about half of
            the allocated LAMMPS cores, defaulting to one core when no allocation
            is configured. Explicit values must be at least 1.
            Both explicit and automatic values are capped by the allocated
            LAMMPS cores and by ``n_averaging_frames + 1`` (``+1`` accounts for
            frame 0).
        temperature: Temperature (K) for NVT equilibration/production simulation.
        server_kwargs: LAMMPS server configuration dict.
        r_max: Maximum radius in Å for RDF calculation (default 10.0).
        n_bins: Number of bins for RDF calculation (default 500).

    Returns:
        Tuple of ``(mean_data, sem_data, n_frames, sampling_history)`` where
        *sem_data* is always returned as ``StructureData`` (for one frame, SEM
        values are computed from a single sample and are typically zero) and
        *sampling_history* is the raw NVT parsed output wrapped as a single
        stage list when ``n_averaging_frames > 1``.
    """
    sampling_history: list[dict[str, Any]] | None = None

    if final_structure is None:
        msg = "final_structure must be provided"
        raise ValueError(msg)
    if n_averaging_frames < 1:
        msg = "n_averaging_frames must be >= 1"
        raise ValueError(msg)
    effective_n_jobs = _resolve_effective_n_jobs(
        n_jobs=n_jobs,
        n_averaging_frames=n_averaging_frames,
        server_kwargs=server_kwargs,
    )

    if n_averaging_frames > 1:
        if potential is None:
            msg = "potential must be provided when n_averaging_frames > 1"
            raise ValueError(msg)

        logger.info(
            "Running NVT simulation at %.1f K to collect %d frames for averaging",
            temperature,
            n_averaging_frames,
        )

        # Frame collection timing: 1000 fs (1 ps) between frames for thermal decorrelation
        SAMPLING_DUMP_INTERVAL_FS = 1000.0
        dump_interval = int(SAMPLING_DUMP_INTERVAL_FS / timestep)
        n_ionic_steps = n_averaging_frames * dump_interval

        structure_final, parsed_output = _run_lammps_md(
            structure=final_structure,
            potential=potential,
            temperature=temperature,
            n_ionic_steps=n_ionic_steps,
            timestep=timestep,
            initial_temperature=temperature,  # Reset velocities for equilibration
            n_dump=dump_interval,
            n_print_thermo=dump_interval,
            server_kwargs=server_kwargs or {},
            ensemble="nvt",
        )

        trajectory_output = parsed_output.get("generic", parsed_output)
        if not isinstance(trajectory_output, dict):
            msg = "NVT sampling output missing required 'positions'/'cells' for frame averaging"
            raise ValueError(msg)

        frames = _frames_from_nvt_output(structure_final, parsed_output)
        sampling_history = [trajectory_output]

    # This is for n_averaging_frames == 1 -> only analyze final_structure
    else:
        frames = [final_structure]

    n_frames = len(frames)

    if n_frames > 1:
        logger.info("Frame-averaging structural analysis over %d frames", n_frames)
        mean_data, sem_data = analyze_structure(
            atoms=frames, frame_averaging=True, n_jobs=effective_n_jobs, r_max=r_max, n_bins=n_bins
        )
    else:
        mean_data, sem_data = analyze_structure(atoms=frames[0], r_max=r_max, n_bins=n_bins)

    return mean_data, sem_data, n_frames, sampling_history

running_mean(data: list | np.ndarray, n: int) -> np.ndarray

Calculate running mean of an array-like dataset.

The initial and final values of the returned array are NaN, as the running mean is not defined for those points.

Parameters:

Name Type Description Default
data list | ndarray

Input data for which the running mean should be calculated.

required
n int

Width of the averaging window.

required

Returns:

Type Description
ndarray

Array of same size as input data containing the running mean values.

Source code in amorphouspy/src/amorphouspy/atoms/shared.py
def running_mean(data: list | np.ndarray, n: int) -> np.ndarray:
    """Calculate running mean of an array-like dataset.

    The initial and final values of the returned array are NaN, as the running mean is not defined
    for those points.

    Args:
        data: Input data for which the running mean should be calculated.
        n: Width of the averaging window.

    Returns:
        Array of same size as input data containing the running mean values.

    """
    data = np.asarray(data)
    if n == 1:
        return data
    ret_array = np.full(data.size, np.nan)
    pad_left = int(n / 2)
    pad_right = n - pad_left - 1
    ret_array[pad_left:-pad_right] = np.convolve(data, np.ones((n,)) / n, mode="valid")
    return ret_array

save_frames(frames: list[Atoms], path: str | Path) -> Path

Write a trajectory to extended XYZ (gzipped when path ends in .gz).

Per-atom arrays (including unwrapped_positions) and per-frame info (step, temperature) are preserved, so the file round-trips back into :func:compute_msd.

Parameters:

Name Type Description Default
frames list[Atoms]

Trajectory as a list of :class:ase.Atoms.

required
path str | Path

Output path; a .gz suffix triggers gzip compression.

required

Returns:

Type Description
Path

The path written.

Example

save_frames(out["frames"], "trajectory.xyz.gz") # doctest: +SKIP

Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
def save_frames(frames: list[Atoms], path: str | Path) -> Path:
    """Write a trajectory to extended XYZ (gzipped when *path* ends in ``.gz``).

    Per-atom arrays (including ``unwrapped_positions``) and per-frame ``info`` (``step``,
    ``temperature``) are preserved, so the file round-trips back into :func:`compute_msd`.

    Args:
        frames: Trajectory as a list of :class:`ase.Atoms`.
        path: Output path; a ``.gz`` suffix triggers gzip compression.

    Returns:
        The path written.

    Example:
        >>> save_frames(out["frames"], "trajectory.xyz.gz")  # doctest: +SKIP
    """
    path = Path(path)
    if path.suffix == ".gz":
        with gzip.open(path, "wt") as handle:
            ase.io.write(handle, frames, format="extxyz")
    else:
        ase.io.write(str(path), frames, format="extxyz")
    return path

structure_from_parsed_output(initial_structure: Atoms, parsed_output: dict, *, wrap: bool = False) -> Atoms

Construct an Atoms object from parsed output data.

Parameters:

Name Type Description Default
initial_structure Atoms

The initial atomic structure to use as a template.

required
parsed_output dict

Parsed output containing atomic positions, cell, and indices.

required
wrap bool

Whether to wrap the atomic positions to the simulation cell (default is False). Keeping the unwrapped positions is more beneficial if structures are passed between different LAMMPS simulations in one workflow to ensure continuity.

False

Returns:

Type Description
Atoms

An Atoms object with updated positions and cell.

Example

new_atoms = structure_from_parsed_output(atoms, lammps_output)

Source code in amorphouspy/src/amorphouspy/lammps/io.py
def structure_from_parsed_output(initial_structure: Atoms, parsed_output: dict, *, wrap: bool = False) -> Atoms:
    """Construct an `Atoms` object from parsed output data.

    Args:
        initial_structure: The initial atomic structure to use as a template.
        parsed_output: Parsed output containing atomic positions, cell, and indices.
        wrap: Whether to wrap the atomic positions to the simulation cell (default is False).
            Keeping the unwrapped positions is more beneficial if structures are passed between
            different LAMMPS simulations in one workflow to ensure continuity.

    Returns:
        An `Atoms` object with updated positions and cell.

    Example:
        >>> new_atoms = structure_from_parsed_output(atoms, lammps_output)

    """
    # Take a copy of the initial structure as template and update the relevant properties
    atoms_copy = initial_structure.copy()
    atoms_copy.set_array("indices", parsed_output["generic"]["indices"][-1])
    atoms_copy.set_positions(parsed_output["generic"]["positions"][-1])
    atoms_copy.set_velocities(parsed_output["generic"]["velocities"][-1])
    atoms_copy.set_cell(parsed_output["generic"]["cells"][-1])
    atoms_copy.set_pbc(True)
    if wrap:
        atoms_copy.wrap()

    return atoms_copy

temperature_scan_simulation(structure: Atoms, potential: pd.DataFrame, temperature: list[int | float] | None = None, npt_pressure: float = 0.0001, timestep: float = 1.0, equilibration_steps: int = 100000, production_steps: int = 200000, n_dump: int | None = None, n_print_thermo: int = 10, server_kwargs: dict[str, Any] | None = None, *, aniso: bool = False, seed: int | None = 12345, tmp_working_directory: str | Path | None = None) -> dict[Any, Any]

Perform a temperature scan and collect structural data.

This workflow performs a temperature scan at the given list of temperatures. For each temperature, it equilibrates the structure at the target temperature and pressure and then performs a production MD run to collect the average volume and box lengths, needed to compute the CTE via V-T data. There differen CTEs often discussed, for example: - CTE20-300: Computed between solely as the slope from the two datapoints at 20°C and 300°C. - CTE20-600: Computed between solely as the slope from the two datapoints at 20°C and 600°C. - CTE over other arbitrary temperature range - CTE at a specific temperature based on the slope of the V-T curve at this temperature. This is often doen by fitting a linear model or higher polynomials fit to the V-T data and then taking the derivative at the temperature of interest. Because of the various options and methods to compute the CTE from V-T data, and because the actual CTE calculation is rather straightforward once the data is collected, we do not compute it directly in this workflow, but rather return the collected data for each temperature and leave the actual CTE calculation to the user.

Parameters:

Name Type Description Default
structure Atoms

Input structure (assumed pre-equilibrated).

required
potential DataFrame

LAMMPS potential file.

required
temperature list[int | float] | None

Simulation temperature in Kelvin (default 300 K).

None
npt_pressure float

Target pressure in GPa for NPT simulations. (default 10-4 GPa = 10^5 Pa = 1 bar).

0.0001
timestep float

MD integration timestep in femtoseconds (default 1.0 fs).

1.0
equilibration_steps int

Number of MD steps for the equilibration runs (default 100,000).

100000
production_steps int

Number of MD steps for the production runs (default 200,000).

200000
n_dump int | None

Interval for structure dumping in MD steps for the production run. If set to None (default), only the last frame of the production run is dumped.

None
n_print_thermo int

Interval for writing thermodynamic data in MD steps (default 10).

10
server_kwargs dict[str, Any] | None

Additional server configuration arguments.

None
aniso bool

If false, an isotropic NPT calculation is performed and the simulation box is scaled uniformly. If True, anisotropic NPT calculation is performed and the simulation box can change shape and size independently along each axis (default False).

False
seed int | None

Random seed for velocity initialization (default 12345).

12345
tmp_working_directory str | Path | None

Temporary directory for job execution.

None

Returns:

Type Description
dict[Any, Any]

Dictionary containing the "data" key. The "data" holds the collected thermodynamic and

dict[Any, Any]

structural data from the production run at each temperature. "run_index" identifies which

dict[Any, Any]

temperature step the data belongs to (1, 2, 3, ...). Thermodynamic and structural quantities

dict[Any, Any]

are averaged over each production run and these averages are listed under the respective key.

dict[Any, Any]

The CTE is not computed in this workflow — the returned data is intended for subsequent

dict[Any, Any]

CTE analysis by the user. Example:

dict[Any, Any]

{ 'data': {"run_index" : [1, 2, 3, ...], "steps" : [...], "T" : [...], "E_tot" : [...], "ptot" : [...], "pxx" : [...], "pyy" : [...], "pzz" : [...], "V" : [...], "Lx" : [...], "Ly" : [...], "Lz" : [...], }

dict[Any, Any]

}

Notes
  • For every temperature, the structure is first pre-equilibrated with short (10 ps) NVT.
  • Simulation settings for the NVT equilibration run are hard-coded.
  • Temperatures are simulated sequentially. Alternatively, multiple jobs with independent temperatures can be submitted to achieve parallelization.
Example

result = temperature_scan_simulation( ... structure=my_atoms, ... potential=my_potential, ... temperature=[300, 400, 500], ... production_steps=500000 ... )

Source code in amorphouspy/src/amorphouspy/properties/cte.py
def temperature_scan_simulation(
    structure: Atoms,
    potential: pd.DataFrame,
    temperature: list[int | float] | None = None,
    npt_pressure: float = 1e-4,
    timestep: float = 1.0,
    equilibration_steps: int = 100_000,
    production_steps: int = 200_000,
    n_dump: int | None = None,
    n_print_thermo: int = 10,
    server_kwargs: dict[str, Any] | None = None,
    *,
    aniso: bool = False,
    seed: int | None = 12345,
    tmp_working_directory: str | Path | None = None,
) -> dict[Any, Any]:  # pylint: disable=too-many-positional-arguments
    """Perform a temperature scan and collect structural data.

    This workflow performs a temperature scan at the given list of temperatures. For each temperature, it
    equilibrates the structure at the target temperature and pressure and then performs a production MD
    run to collect the average volume and box lengths, needed to compute the CTE via V-T data.
    There differen CTEs often discussed, for example:
    - CTE20-300: Computed between solely as the slope from the two datapoints at 20°C and 300°C.
    - CTE20-600: Computed between solely as the slope from the two datapoints at 20°C and 600°C.
    - CTE over other arbitrary temperature range
    - CTE at a specific temperature based on the slope of the V-T curve at this temperature. This is often
      doen by fitting a linear model or higher polynomials fit to the V-T data and then taking the derivative
      at the temperature of interest.
    Because of the various options and methods to compute the CTE from V-T data, and because the actual CTE
    calculation is rather straightforward once the data is collected, we do not compute it directly in this
    workflow, but rather return the collected data for each temperature and leave the actual CTE calculation
    to the user.

    Args:
        structure: Input structure (assumed pre-equilibrated).
        potential: LAMMPS potential file.
        temperature: Simulation temperature in Kelvin (default 300 K).
        npt_pressure: Target pressure in GPa for NPT simulations.
            (default 10-4 GPa = 10^5 Pa = 1 bar).
        timestep: MD integration timestep in femtoseconds (default 1.0 fs).
        equilibration_steps: Number of MD steps for the equilibration runs (default 100,000).
        production_steps: Number of MD steps for the production runs (default 200,000).
        n_dump: Interval for structure dumping in MD steps for the production run. If set
            to None (default), only the last frame of the production run is dumped.
        n_print_thermo: Interval for writing thermodynamic data in MD steps (default 10).
        server_kwargs: Additional server configuration arguments.
        aniso: If false, an isotropic NPT calculation is performed and the simulation box is scaled uniformly.
            If True, anisotropic NPT calculation is performed and the simulation box can change shape and
            size independently along each axis (default False).
        seed: Random seed for velocity initialization (default 12345).
        tmp_working_directory: Temporary directory for job execution.

    Returns:
        Dictionary containing the "data" key. The "data" holds the collected thermodynamic and
        structural data from the production run at each temperature. "run_index" identifies which
        temperature step the data belongs to (1, 2, 3, ...). Thermodynamic and structural quantities
        are averaged over each production run and these averages are listed under the respective key.
        The CTE is *not* computed in this workflow — the returned data is intended for subsequent
        CTE analysis by the user. Example:
        { 'data':  {"run_index" : [1, 2, 3, ...],
                    "steps" : [...],
                    "T" : [...],
                    "E_tot" : [...],
                    "ptot" : [...],
                    "pxx" : [...],
                    "pyy" : [...],
                    "pzz" : [...],
                    "V" : [...],
                    "Lx" : [...],
                    "Ly" : [...],
                    "Lz" : [...],
                    }
        }

    Notes:
        - For every temperature, the structure is first pre-equilibrated with short (10 ps) NVT.
        - Simulation settings for the NVT equilibration run are hard-coded.
        - Temperatures are simulated sequentially. Alternatively, multiple jobs with independent
          temperatures can be submitted to achieve parallelization.

    Example:
        >>> result = temperature_scan_simulation(
        ...     structure=my_atoms,
        ...     potential=my_potential,
        ...     temperature=[300, 400, 500],
        ...     production_steps=500000
        ... )

    """
    # Logging setup
    logger = _create_logger()

    if temperature is None:
        temperature = [300, 400, 500, 600]

    # Check input parameters
    _temperature_scan_input_checker(temperature, logger)

    # Set pressure to lampps "aniso" if requested
    sim_pressure = [npt_pressure, npt_pressure, npt_pressure, None, None, None] if aniso else npt_pressure

    # initial structure used. Afterwards, it is updated after each temperature
    structure0 = structure.copy()

    # Initialize results dictionary. CTE values will be calculated later
    results = _initialize_datadict(with_CTE_keys=False)

    # Loop over all temperatures
    for counter_run, T in enumerate(temperature, start=1):
        # Stage 1: Short equilibration in NVT at T for 10,000 steps
        nvt_equilibration_time = 10_000 / timestep / 1000
        msg = f"Starting {nvt_equilibration_time:.1f} ps (10,000 steps hardcoded) NVT equilibration at {T:.2f} K."
        logger.info(msg)

        structure1, _ = _run_lammps_md(
            structure=structure0,
            potential=potential,
            tmp_working_directory=tmp_working_directory,
            temperature=T,
            n_ionic_steps=10_000,
            timestep=timestep,
            n_dump=None,
            n_print_thermo=100,
            input_control_file=CTE_INPUT_CONTROL_FILE,
            initial_temperature=T,
            ensemble="nvt",
            seed=seed,
            server_kwargs=server_kwargs,
        )

        # Stage 2: NPT equilibration runs at T,p.
        equilibration_time = equilibration_steps / timestep / 1000
        msg = f"Starting {equilibration_time:.1f} ps NPT equilibration at {T:.2f} K and {npt_pressure:.2e} GPa."
        logger.info(msg)

        structure2, _ = _run_lammps_md(
            structure=structure1,
            potential=potential,
            tmp_working_directory=tmp_working_directory,
            temperature=T,
            npt_pressure=sim_pressure,
            n_ionic_steps=equilibration_steps,
            timestep=timestep,
            n_dump=None,
            n_print_thermo=n_print_thermo,
            input_control_file=CTE_INPUT_CONTROL_FILE,
            initial_temperature=0,
            ensemble="npt_langevin",
            server_kwargs=server_kwargs,
        )

        # Stage 3: NPT production run
        production_time = production_steps / timestep / 1000
        msg = f"Starting {production_time:.1f} ps NPT production run at {T:.2f} K and {npt_pressure:.2e} GPa."
        logger.info(msg)

        structure_production, parsed_output = _run_lammps_md(
            structure=structure2,
            potential=potential,
            tmp_working_directory=tmp_working_directory,
            temperature=T,
            npt_pressure=sim_pressure,
            n_ionic_steps=production_steps,
            timestep=timestep,
            n_dump=n_dump,
            n_print_thermo=n_print_thermo,
            input_control_file=CTE_INPUT_CONTROL_FILE,
            initial_temperature=0,
            ensemble="npt_langevin",
            server_kwargs=server_kwargs,
        )

        # parse and check the output of the production run
        _sim_data = _collect_sim_data(parsed_output, counter_run)

        _sanity_check_sim_data(sim_data=_sim_data, T_target=T, p_target=npt_pressure, logger=logger)

        # Collect results
        results = _temperature_scan_merge_results(previous_data=results, new_sim_data=_sim_data)

        # Use this structure as starting point for next temperature
        structure0 = structure_production

    msg = "FINISHED SUCCESSFULLY."
    logger.info(msg)
    return {"data": results}

type_to_dict(types: np.ndarray) -> dict[int, str]

Generate a dictionary mapping atomic numbers (types) to element symbols from an ASE Atoms structure.

Parameters:

Name Type Description Default
types ndarray

Array containing atom types in the simulation.

required

Returns:

Type Description
dict[int, str]

Dictionary mapping atomic numbers to corresponding element symbols.

Example

type_map = type_to_dict(np.array([14, 8]))

Source code in amorphouspy/src/amorphouspy/atoms/shared.py
def type_to_dict(types: np.ndarray) -> dict[int, str]:
    """Generate a dictionary mapping atomic numbers (types) to element symbols from an ASE Atoms structure.

    Args:
        types: Array containing atom types in the simulation.

    Returns:
        Dictionary mapping atomic numbers to corresponding element symbols.

    Example:
        >>> type_map = type_to_dict(np.array([14, 8]))

    """
    # Extract unique atomic types from structure
    unique_types = np.unique(types)

    # Map atomic numbers to element symbols using ASE's periodic table
    element_symbols: list[str] = [chemical_symbols[z] for z in unique_types]

    # Create the type-to-symbol dictionary
    type_dict: dict[int, str] = dict(zip(unique_types, element_symbols, strict=True))

    return type_dict

vdos_simulation(structure: Atoms, potential: pd.DataFrame, temperature_sim: float = 300.0, timestep: float = 1.0, server_kwargs: dict[str, Any] | None = None, *, thermostat: Thermostat, equilibration_steps: int = 100000, production_ps: float = 200.0, block_ps: float = 10.0, dump_every: int = 5, normalization: Literal['unit', '3N'] = 'unit', window: VdosWindow = 'hann', cutoff: CutoffSpec | None = None, former_types: list[int] | None = None, o_type: int = 8, seed: int = 12345, tmp_working_directory: str | Path | None = None, keep_trajectory: bool = False, infrared: bool = False, charges: ArrayLike | None = None, eps_inf: float = 1.0) -> dict[str, Any]

Equilibrate a structure, run consecutive NVE blocks and average their VDOS and VACF, total and per atom group.

Three MD stages run in LAMMPS at the constant volume of the input cell:

  1. Langevin thermalisation at temperature_sim for 10,000 steps, with velocities created at temperature_sim (as in :func:diffusion_simulation).
  2. NVT equilibration with thermostat for equilibration_steps steps, with velocities created again at temperature_sim. equilibration_steps=0 skips this stage.
  3. NVE production of production_ps, run as n_blocks = production_steps // block_steps consecutive blocks of block_ps, i.e. block_steps = block_ps * 1000 / timestep steps each, with velocities and thermo output every dump_every steps. The first block starts from the velocities of the previous stage and every later block from the end of the block before it, as a new LAMMPS run.

The production is microcanonical because a thermostat perturbs the velocities and distorts the spectrum. LAMMPS also writes the frame of step 0 of every block, which is the end state of the previous stage or block. It is dropped, so the kept frames of consecutive blocks do not overlap. Each block holds n_frames = block_steps // dump_every frames spaced by dt_fs = timestep * dump_every fs, and the frequency resolution is exactly 1 / block_ps THz. If the parsed output of a block does not hold n_frames + 1 frames, a RuntimeError is raised; no frame is trimmed silently. The Nyquist frequency is 1 / (2 dt_fs): 100 THz for the defaults (1 fs, every 5 steps).

From the kept frames of each block (velocities in Å/fs, masses from structure.get_masses() in amu) the function computes:

  • The VDOS without a window and, unless window is None, with window (Hann by default), both with :func:compute_partial_vdos, the given normalization and one shared frequency axis. The total is computed as the partial VDOS of a group of all atoms, so it is the total VDOS of :func:compute_vdos_from_velocities and integrates to 1 ("unit") or 3 * n_atoms ("3N"); within each grouping the partials add up to it.
  • The VACF with :func:compute_partial_vacf, unwindowed, normalised so that the total \(C(0) = 1\), with lags up to half the block.

The centre-of-mass velocity of the whole system is removed from every frame in both.

Every returned curve is the mean over blocks, with the block standard error std(ddof=1) / sqrt(n_blocks) in "vdos_sem" and "vacf_sem"; with one block the standard error is NaN. Each block's VDOS and VACF are normalised by that block's own kinetic energy, so the mean of the block curves integrates exactly to the normalisation, the total VACF has \(C(0) = 1\) exactly, and within each grouping the mean partials still add up to the mean total. The standard errors are not additive: the standard error of a total is not the sum of those of its partials.

The standard error is the scatter between the blocks of this run, and it assumes that they are independent. The blocks come from one NVE trajectory of one glass, so it contains no glass-to-glass variation at all, and nothing that stays constant over the run: neither the energy of the run nor a nearly harmonic mode that keeps its energy between blocks. A calibration compared the means of two independent thermal histories of one 300-atom \(\mathrm{SiO_2}\) glass (PMMCS, 300 K, 10 blocks of 10 ps each), where exact standard errors put 94 % of the bins within two combined standard errors. Between 5 and 34 THz this held for 93 % (no window) and 95 % (Hann) of the bins. Below 5 THz it held for 96 % and 98 %, so no low-frequency underestimate was seen, although 50 bins would not show a small one. Between 34 and 40 THz, above the top of the spectrum, it held for only 75 % and 78 %: the weight there differed by 4 to 5 %, as did the temperature of the two runs. The lag-1 correlation of the block residuals was close to the -0.1 of independent blocks, but a part that is constant over the run cannot show up in it. One pair of runs says nothing about larger boxes, lower temperatures or shorter blocks.

The atom groups (element, oxygen class, \(\mathrm{Q}^n\)) come from :func:classify_vibrational_groups on the input structure, before any MD, so thermal motion of bonds near the cutoff cannot change them. They stay fixed for all blocks.

Memory: the velocities of one block take n_frames * n_atoms * 3 * 8 bytes as float64, e.g. 0.29 GB for 2000 frames (10 ps at 5 fs) of 6000 atoms. The parsed LAMMPS output holds three more arrays of that size (positions, unwrapped positions and forces), and parsing it needs more still: a 10 ps block of 5400 atoms peaked 4.5 GB above the baseline, 17 times its velocities (measured). The peak scales with one block, not with the whole production: a block's parsed output is freed before the next block starts, and only the spectra and the thermo output accumulate. Not all freed memory goes back to the system, though: over 8 blocks of 2 ps the resident size levelled off at 1.7 times the peak of the first block (measured on macOS).

Disk: with tmp_working_directory=None every run removes its files. In a caller-supplied directory every run keeps a sub-directory, and each NVE block runs in its own vdos_nve_block_<block>_<random> directory. Its dump (dump.out, 88 bytes per atom per frame, measured: 0.47 MB per frame and 0.95 GB per 10 ps block at 5400 atoms) is deleted once the block's spectra and thermo output are extracted, before the next block starts, so at most one dump is on disk at a time. log.lammps, the input script and the data file stay, as do all files of the Langevin and NVT stages. keep_trajectory=True keeps every dump (20 for the defaults). A block that fails keeps its dump, and the error names it. If no dump is found to delete, a warning is raised and the result is still returned.

Drift: "nve_drift" reports the energy and temperature of the kept NVE frames, frame k (0-based over all blocks) at t = (k + 1) * dt_fs fs. Each block restarts from the positions and velocities of the previous block's dump, written with 6 significant digits, so the total energy can jump at a block boundary. The jump is measured between the last kept frame of a block and the step-0 frame of the next, which hold the same state, so it is the restart loss alone. The thermo output has 8 significant digits, so energies are resolved to about |E_tot| / N * 1e-5 meV/atom, one unit in the last digit (measured for \(\mathrm{SiO_2}\) with PMMCS: 3.3e-4 meV/atom at 300 atoms, 1.9e-4 at 5400). In those runs (300 K, blocks of 2 and 10 ps) every jump was within two such units, at most 6.7e-4 meV/atom, and smaller than the drift within any block over the block length.

Parameters:

Name Type Description Default
structure Atoms

Input structure, e.g. a quenched glass. Its cell sets the volume of every stage, and the atom groups and masses are taken from it.

required
potential DataFrame

LAMMPS potential as a pandas DataFrame.

required
temperature_sim float

Temperature of the Langevin and NVT stages in K.

300.0
timestep float

MD timestep in fs.

1.0
server_kwargs dict[str, Any] | None

Additional arguments for the LAMMPS server (e.g. {"cores": 4}).

None
thermostat Thermostat

Thermostat of the NVT stage, "nose_hoover" or "langevin".

required
equilibration_steps int

Length of the NVT stage in MD steps; 0 skips it. Use a small value for quick demos and the default for production-quality runs.

100000
production_ps float

Total length of the NVE production in ps, a whole number of timesteps and a multiple of block_ps; nothing is truncated.

200.0
block_ps float

Length of one NVE block in ps, a whole number of timesteps. It sets the resolution 1 / block_ps THz.

10.0
dump_every int

Interval between dumped frames in MD steps, a positive integer that divides the block.

5
normalization Literal['unit', '3N']

"unit" (the total VDOS integrates to 1, in 1/THz) or "3N" (to 3 * n_atoms). The VACF is always normalised to \(C(0) = 1\).

'unit'
window VdosWindow

Window of the second VDOS, as in :func:compute_partial_vdos: "hann" (default), "hamming", "blackmanharris", ("gaussian", std) with std > 0 in frames (dt_fs apart, so 250 frames are 1.25 ps at the defaults), or None to compute only the unwindowed VDOS.

'hann'
cutoff CutoffSpec | None

Former-O cutoff in Å for the groups, as in :func:classify_vibrational_groups. Derived from the RDF if None.

None
former_types list[int] | None

Atomic numbers of the network formers. Derived from the composition if None.

None
o_type int

Atomic number of oxygen.

8
seed int

Random seed for the velocities created in the Langevin and NVT stages.

12345
tmp_working_directory str | Path | None

Directory for temporary simulation files. If None, every run removes its files.

None
keep_trajectory bool

Keep the dump of every NVE block in tmp_working_directory instead of deleting it once its spectra are computed. Requires tmp_working_directory.

False
infrared bool

Also compute the infrared response from the charge current of every block, with window as the lag window (None cuts the correlation function sharply and makes the spectrum ring), returned in "infrared".

False
charges ArrayLike | None

Atomic charges in units of the elementary charge for the infrared response, shape \((N,)\) or Born tensors \((N, 3, 3)\), in the order of the atoms. None reads the fixed charges of potential with :func:charges_from_potential. Ignored without infrared.

None
eps_inf float

The high-frequency dielectric constant \(\varepsilon_\infty\) of the infrared response; see :func:compute_dielectric_function.

1.0

Returns:

Type Description
dict[str, Any]

A dict with: "frequencies_thz": frequency axis in THz, length n_frames // 2 + 1, shared by both VDOS. "vdos": mean over blocks, {"no_window": ..., "windowed": ...} (no "windowed" entry for window=None), each {"total": array, "element": {...}, "oxygen": {...}, "qn": {...}} with the labels of "groups", in 1/THz. "vdos_sem": block standard error of "vdos", same layout and units; NaN for one block. "lag_ps": VACF lags in ps, length n_frames // 2 + 1. "vacf": mean over blocks, {"total": array, "element": {...}, "oxygen": {...}, "qn": {...}}, dimensionless. "vacf_sem": block standard error of "vacf", same layout; NaN for one block. "groups": the output of :func:classify_vibrational_groups on the input structure. "structure": the final structure of the last NVE block. "temperature": thermo temperature in K of each kept frame of all blocks, as parsed, length n_blocks * n_frames. "energy_tot": total energy in eV of each kept frame of all blocks, as parsed, length n_blocks * n_frames. "nve_drift": a dict over all kept NVE frames, energies per atom (N atoms): "energy_drift_mev_per_atom_ps", the least-squares slope of E_tot / N in meV/atom/ps over all blocks, boundary jumps included; "block_energy_drift_mev_per_atom_ps", the same slope within each block, array of length n_blocks; "boundary_energy_jump_mev_per_atom", E_tot / N of the step-0 frame of block b + 1 minus that of the last kept frame of block b in meV/atom, array of length n_blocks - 1; "max_energy_deviation_mev_per_atom", the largest |E_tot - E_tot[0]| / N in meV/atom from the first kept frame; "temperature_mean_k" and "temperature_std_k" (population standard deviation, ddof=0) in K; and "temperature_drift_k_per_ps", the least-squares slope in K/ps. "dt_fs": time between frames in fs. "n_blocks": number of NVE blocks. "n_frames": number of kept frames per block. "resolution_thz": 1 / block_ps. "nyquist_thz": 1 / (2 dt_fs) in THz. "normalization": the VDOS normalisation. "window": the window of vdos["windowed"], as passed. "infrared": None without infrared, else a dict of means over blocks on its own grid "frequencies_thz" (length n_frames // 2 + 1): "epsilon", "conductivity_s_per_m" and "partial_susceptibility" of :func:compute_dielectric_from_velocities for the groups of "groups" and the volume of the cell; their block standard errors "epsilon_sem", "conductivity_sem_s_per_m" and "partial_susceptibility_sem", complex with the errors of the real and imaginary parts, NaN for one block; "refractive_index", "extinction", "absorption_cm", "reflectivity" and "loss_function" of :func:compute_optical_response for the mean "epsilon"; and the "n_lag_frames", "charges", "volume_a3" and "eps_inf" used.

Raises:

Type Description
ValueError

Before any MD, if the potential is empty, temperature_sim, timestep, block_ps or production_ps is not positive and finite, dump_every is not a positive integer, equilibration_steps is negative or not an integer, normalization is not "unit" or "3N", window is unknown, block_ps or production_ps is not a whole number of timesteps, the block is not a multiple of dump_every or holds fewer than 2 frames, the production is not a multiple of the block, thermostat is unknown, keep_trajectory is True without a tmp_working_directory, or, with infrared, a block holds fewer than 4 frames, eps_inf is not positive and finite, the cell has no volume, charges does not have shape \((N,)\) or \((N, 3, 3)\) or the potential defines no charge for an element.

RuntimeError

If the output of an NVE block does not hold n_frames + 1 frames of velocities, temperature and total energy. The message names the block and, with a tmp_working_directory, its kept dump; no later block is run.

Warns:

Type Description
UserWarning

If the Nyquist frequency is below 50 THz, or if no dump of a block is found to delete.

Example
>>> out = vdos_simulation(structure, potential, thermostat="nose_hoover")  # doctest: +SKIP
>>> out["n_blocks"], out["n_frames"], out["resolution_thz"], out["nyquist_thz"]  # doctest: +SKIP
(20, 2000, 0.1, 100.0)
>>> out["vdos"]["windowed"]["element"]["Si"]  # doctest: +SKIP
>>> out["vdos_sem"]["windowed"]["element"]["Si"]  # doctest: +SKIP
>>> out["nve_drift"]["energy_drift_mev_per_atom_ps"]  # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/simulation.py
def vdos_simulation(
    structure: "Atoms",
    potential: pd.DataFrame,
    temperature_sim: float = 300.0,
    timestep: float = 1.0,
    server_kwargs: dict[str, Any] | None = None,
    *,
    thermostat: Thermostat,
    equilibration_steps: int = 100_000,
    production_ps: float = 200.0,
    block_ps: float = 10.0,
    dump_every: int = 5,
    normalization: Literal["unit", "3N"] = "unit",
    window: VdosWindow = "hann",
    cutoff: CutoffSpec | None = None,
    former_types: list[int] | None = None,
    o_type: int = 8,
    seed: int = 12345,
    tmp_working_directory: str | Path | None = None,
    keep_trajectory: bool = False,
    infrared: bool = False,
    charges: ArrayLike | None = None,
    eps_inf: float = 1.0,
) -> dict[str, Any]:
    r"""Equilibrate a structure, run consecutive NVE blocks and average their VDOS and VACF, total and per atom group.

    Three MD stages run in LAMMPS at the constant volume of the input cell:

    1. Langevin thermalisation at ``temperature_sim`` for 10,000 steps, with velocities created at ``temperature_sim``
       (as in :func:`diffusion_simulation`).
    2. NVT equilibration with ``thermostat`` for ``equilibration_steps`` steps, with velocities created again at
       ``temperature_sim``. ``equilibration_steps=0`` skips this stage.
    3. NVE production of ``production_ps``, run as ``n_blocks = production_steps // block_steps`` consecutive blocks of
       ``block_ps``, i.e. ``block_steps = block_ps * 1000 / timestep`` steps each, with velocities and thermo output
       every ``dump_every`` steps. The first block starts from the velocities of the previous stage and every later
       block from the end of the block before it, as a new LAMMPS run.

    The production is microcanonical because a thermostat perturbs the velocities and distorts the spectrum. LAMMPS
    also writes the frame of step 0 of every block, which is the end state of the previous stage or block. It is
    dropped, so the kept frames of consecutive blocks do not overlap. Each block holds ``n_frames = block_steps //
    dump_every`` frames spaced by ``dt_fs = timestep * dump_every`` fs, and the frequency resolution is exactly
    ``1 / block_ps`` THz. If the parsed output of a block does not hold ``n_frames + 1`` frames, a ``RuntimeError`` is
    raised; no frame is trimmed silently. The Nyquist frequency is ``1 / (2 dt_fs)``: 100 THz for the defaults (1 fs,
    every 5 steps).

    From the kept frames of each block (velocities in Å/fs, masses from ``structure.get_masses()`` in amu) the function
    computes:

    - The VDOS without a window and, unless ``window`` is ``None``, with ``window`` (Hann by default), both with
      :func:`compute_partial_vdos`, the given ``normalization`` and one shared frequency axis. The total is computed
      as the partial VDOS of a group of all atoms, so it is the total VDOS of :func:`compute_vdos_from_velocities`
      and integrates to 1 (``"unit"``) or ``3 * n_atoms`` (``"3N"``); within each grouping the partials add up to it.
    - The VACF with :func:`compute_partial_vacf`, unwindowed, normalised so that the total $C(0) = 1$, with lags up to
      half the block.

    The centre-of-mass velocity of the whole system is removed from every frame in both.

    Every returned curve is the mean over blocks, with the block standard error ``std(ddof=1) / sqrt(n_blocks)`` in
    ``"vdos_sem"`` and ``"vacf_sem"``; with one block the standard error is NaN. Each block's VDOS and VACF are
    normalised by that block's own kinetic energy, so the mean of the block curves integrates exactly to the
    normalisation, the total VACF has $C(0) = 1$ exactly, and within each grouping the mean partials still add up to
    the mean total. The standard errors are not additive: the standard error of a total is not the sum of those of
    its partials.

    The standard error is the scatter between the blocks of this run, and it assumes that they are independent. The
    blocks come from one NVE trajectory of one glass, so it contains no glass-to-glass variation at all, and nothing
    that stays constant over the run: neither the energy of the run nor a nearly harmonic mode that keeps its energy
    between blocks. A calibration compared the means of two independent thermal histories of one 300-atom
    $\mathrm{SiO_2}$ glass (PMMCS, 300 K, 10 blocks of 10 ps each), where exact standard errors put 94 % of the bins
    within two combined standard errors. Between 5 and 34 THz this held for 93 % (no window) and 95 % (Hann) of the
    bins. Below 5 THz it held for 96 % and 98 %, so no low-frequency underestimate was seen, although 50 bins would not
    show a small one. Between 34 and 40 THz, above the top of the spectrum, it held for only 75 % and 78 %: the weight
    there differed by 4 to 5 %, as did the temperature of the two runs. The lag-1 correlation of the block residuals
    was close to the -0.1 of independent blocks, but a part that is constant over the run cannot show up in it. One
    pair of runs says nothing about larger boxes, lower temperatures or shorter blocks.

    The atom groups (element, oxygen class, $\mathrm{Q}^n$) come from :func:`classify_vibrational_groups` on the input
    ``structure``, before any MD, so thermal motion of bonds near the cutoff cannot change them. They stay fixed for
    all blocks.

    Memory: the velocities of one block take ``n_frames * n_atoms * 3 * 8`` bytes as float64, e.g. 0.29 GB for 2000
    frames (10 ps at 5 fs) of 6000 atoms. The parsed LAMMPS output holds three more arrays of that size (positions,
    unwrapped positions and forces), and parsing it needs more still: a 10 ps block of 5400 atoms peaked 4.5 GB above
    the baseline, 17 times its velocities (measured). The peak scales with one block, not with the whole production: a
    block's parsed output is freed before the next block starts, and only the spectra and the thermo output accumulate.
    Not all freed memory goes back to the system, though: over 8 blocks of 2 ps the resident size levelled off at 1.7
    times the peak of the first block (measured on macOS).

    Disk: with ``tmp_working_directory=None`` every run removes its files. In a caller-supplied directory every run
    keeps a sub-directory, and each NVE block runs in its own ``vdos_nve_block_<block>_<random>`` directory. Its dump
    (``dump.out``, 88 bytes per atom per frame, measured: 0.47 MB per frame and 0.95 GB per 10 ps block at 5400 atoms)
    is deleted once the block's spectra and thermo output are extracted, before the next block starts, so at most one
    dump is on disk at a time. ``log.lammps``, the input script and the data file stay, as do all files of the Langevin
    and NVT stages. ``keep_trajectory=True`` keeps every dump (20 for the defaults). A block that fails keeps its dump,
    and the error names it. If no dump is found to delete, a warning is raised and the result is still returned.

    Drift: ``"nve_drift"`` reports the energy and temperature of the kept NVE frames, frame ``k`` (0-based over all
    blocks) at ``t = (k + 1) * dt_fs`` fs. Each block restarts from the positions and velocities of the previous
    block's dump, written with 6 significant digits, so the total energy can jump at a block boundary. The jump is
    measured between the last kept frame of a block and the step-0 frame of the next, which hold the same state, so it
    is the restart loss alone. The thermo output has 8 significant digits, so energies are resolved to about
    ``|E_tot| / N * 1e-5`` meV/atom, one unit in the last digit (measured for $\mathrm{SiO_2}$ with PMMCS: 3.3e-4
    meV/atom at 300 atoms, 1.9e-4 at 5400). In those runs (300 K, blocks of 2 and 10 ps) every jump was within two
    such units, at most 6.7e-4 meV/atom, and smaller than the drift within any block over the block length.

    Args:
        structure: Input structure, e.g. a quenched glass. Its cell sets the volume of every stage, and the atom
            groups and masses are taken from it.
        potential: LAMMPS potential as a pandas DataFrame.
        temperature_sim: Temperature of the Langevin and NVT stages in K.
        timestep: MD timestep in fs.
        server_kwargs: Additional arguments for the LAMMPS server (e.g. ``{"cores": 4}``).
        thermostat: Thermostat of the NVT stage, ``"nose_hoover"`` or ``"langevin"``.
        equilibration_steps: Length of the NVT stage in MD steps; 0 skips it. Use a small value for quick demos and
            the default for production-quality runs.
        production_ps: Total length of the NVE production in ps, a whole number of timesteps and a multiple of
            ``block_ps``; nothing is truncated.
        block_ps: Length of one NVE block in ps, a whole number of timesteps. It sets the resolution 1 / ``block_ps``
            THz.
        dump_every: Interval between dumped frames in MD steps, a positive integer that divides the block.
        normalization: ``"unit"`` (the total VDOS integrates to 1, in 1/THz) or ``"3N"`` (to ``3 * n_atoms``). The
            VACF is always normalised to $C(0) = 1$.
        window: Window of the second VDOS, as in :func:`compute_partial_vdos`: ``"hann"`` (default), ``"hamming"``,
            ``"blackmanharris"``, ``("gaussian", std)`` with ``std > 0`` in frames (``dt_fs`` apart, so 250 frames
            are 1.25 ps at the defaults), or ``None`` to compute only the unwindowed VDOS.
        cutoff: Former-O cutoff in Å for the groups, as in :func:`classify_vibrational_groups`. Derived from the RDF
            if ``None``.
        former_types: Atomic numbers of the network formers. Derived from the composition if ``None``.
        o_type: Atomic number of oxygen.
        seed: Random seed for the velocities created in the Langevin and NVT stages.
        tmp_working_directory: Directory for temporary simulation files. If None, every run removes its files.
        keep_trajectory: Keep the dump of every NVE block in ``tmp_working_directory`` instead of deleting it once its
            spectra are computed. Requires ``tmp_working_directory``.
        infrared: Also compute the infrared response from the charge current of every block, with ``window`` as
            the lag window (``None`` cuts the correlation function sharply and makes the spectrum ring), returned
            in ``"infrared"``.
        charges: Atomic charges in units of the elementary charge for the infrared response, shape $(N,)$ or Born
            tensors $(N, 3, 3)$, in the order of the atoms. ``None`` reads the fixed charges of ``potential`` with
            :func:`charges_from_potential`. Ignored without ``infrared``.
        eps_inf: The high-frequency dielectric constant $\varepsilon_\infty$ of the infrared response; see
            :func:`compute_dielectric_function`.

    Returns:
        A dict with:
            ``"frequencies_thz"``: frequency axis in THz, length ``n_frames // 2 + 1``, shared by both VDOS.
            ``"vdos"``: mean over blocks, ``{"no_window": ..., "windowed": ...}`` (no ``"windowed"`` entry for
            ``window=None``), each ``{"total": array, "element": {...}, "oxygen": {...}, "qn": {...}}`` with the labels
            of ``"groups"``, in 1/THz.
            ``"vdos_sem"``: block standard error of ``"vdos"``, same layout and units; NaN for one block.
            ``"lag_ps"``: VACF lags in ps, length ``n_frames // 2 + 1``.
            ``"vacf"``: mean over blocks, ``{"total": array, "element": {...}, "oxygen": {...}, "qn": {...}}``,
            dimensionless.
            ``"vacf_sem"``: block standard error of ``"vacf"``, same layout; NaN for one block.
            ``"groups"``: the output of :func:`classify_vibrational_groups` on the input structure.
            ``"structure"``: the final structure of the last NVE block.
            ``"temperature"``: thermo temperature in K of each kept frame of all blocks, as parsed, length
            ``n_blocks * n_frames``.
            ``"energy_tot"``: total energy in eV of each kept frame of all blocks, as parsed, length
            ``n_blocks * n_frames``.
            ``"nve_drift"``: a dict over all kept NVE frames, energies per atom (``N`` atoms):
            ``"energy_drift_mev_per_atom_ps"``, the least-squares slope of ``E_tot / N`` in meV/atom/ps over all
            blocks, boundary jumps included; ``"block_energy_drift_mev_per_atom_ps"``, the same slope within each
            block, array of length ``n_blocks``; ``"boundary_energy_jump_mev_per_atom"``, ``E_tot / N`` of the step-0
            frame of block ``b + 1`` minus that of the last kept frame of block ``b`` in meV/atom, array of length
            ``n_blocks - 1``; ``"max_energy_deviation_mev_per_atom"``, the largest ``|E_tot - E_tot[0]| / N`` in
            meV/atom from the first kept frame; ``"temperature_mean_k"`` and ``"temperature_std_k"`` (population
            standard deviation, ddof=0) in K; and ``"temperature_drift_k_per_ps"``, the least-squares slope in K/ps.
            ``"dt_fs"``: time between frames in fs.
            ``"n_blocks"``: number of NVE blocks.
            ``"n_frames"``: number of kept frames per block.
            ``"resolution_thz"``: 1 / ``block_ps``.
            ``"nyquist_thz"``: 1 / (2 ``dt_fs``) in THz.
            ``"normalization"``: the VDOS normalisation.
            ``"window"``: the window of ``vdos["windowed"]``, as passed.
            ``"infrared"``: None without ``infrared``, else a dict of means over blocks on its own grid
            ``"frequencies_thz"`` (length ``n_frames // 2 + 1``): ``"epsilon"``, ``"conductivity_s_per_m"`` and
            ``"partial_susceptibility"`` of :func:`compute_dielectric_from_velocities` for the groups of
            ``"groups"`` and the volume of the cell; their block standard errors ``"epsilon_sem"``,
            ``"conductivity_sem_s_per_m"`` and ``"partial_susceptibility_sem"``, complex with the errors of the
            real and imaginary parts, NaN for one block; ``"refractive_index"``, ``"extinction"``,
            ``"absorption_cm"``, ``"reflectivity"`` and ``"loss_function"`` of :func:`compute_optical_response`
            for the mean ``"epsilon"``; and the ``"n_lag_frames"``, ``"charges"``, ``"volume_a3"`` and
            ``"eps_inf"`` used.

    Raises:
        ValueError: Before any MD, if the potential is empty, ``temperature_sim``, ``timestep``, ``block_ps`` or
            ``production_ps`` is not positive and finite, ``dump_every`` is not a positive integer,
            ``equilibration_steps`` is negative or not an integer, ``normalization`` is not ``"unit"`` or ``"3N"``,
            ``window`` is unknown, ``block_ps`` or ``production_ps`` is not a whole number of timesteps, the block is
            not a multiple of ``dump_every`` or holds fewer than 2 frames, the production is not a multiple of the
            block, ``thermostat`` is unknown, ``keep_trajectory`` is True without a ``tmp_working_directory``, or,
            with ``infrared``, a block holds fewer than 4 frames, ``eps_inf`` is not positive and finite, the cell
            has no volume, ``charges`` does not have shape $(N,)$ or $(N, 3, 3)$ or the potential defines no
            charge for an element.
        RuntimeError: If the output of an NVE block does not hold ``n_frames + 1`` frames of velocities, temperature
            and total energy. The message names the block and, with a ``tmp_working_directory``, its kept dump; no
            later block is run.

    Warns:
        UserWarning: If the Nyquist frequency is below 50 THz, or if no dump of a block is found to delete.

    Example:
        ```pycon
        >>> out = vdos_simulation(structure, potential, thermostat="nose_hoover")  # doctest: +SKIP
        >>> out["n_blocks"], out["n_frames"], out["resolution_thz"], out["nyquist_thz"]  # doctest: +SKIP
        (20, 2000, 0.1, 100.0)
        >>> out["vdos"]["windowed"]["element"]["Si"]  # doctest: +SKIP
        >>> out["vdos_sem"]["windowed"]["element"]["Si"]  # doctest: +SKIP
        >>> out["nve_drift"]["energy_drift_mev_per_atom_ps"]  # doctest: +SKIP

        ```
    """
    if keep_trajectory and tmp_working_directory is None:
        msg = "keep_trajectory=True needs a tmp_working_directory; without one every run removes its files."
        raise ValueError(msg)
    block_steps, block_frames, n_blocks, dt_fs = _vdos_simulation_settings(
        potential,
        temperature_sim,
        timestep,
        production_ps,
        block_ps,
        dump_every,
        equilibration_steps,
        normalization,
        window,
    )
    nyquist_thz = 500.0 / dt_fs
    if nyquist_thz < _MIN_NYQUIST_THZ:
        warnings.warn(
            f"The Nyquist frequency is {nyquist_thz:g} THz (timestep {timestep} fs, dump_every {dump_every}), below "
            f"{_MIN_NYQUIST_THZ:g} THz; silicate spectra reach about 40 THz, so the highest modes are cut and aliased.",
            UserWarning,
            stacklevel=2,
        )
    nvt_ensemble, _ = thermostat_ensembles(thermostat)
    groups = classify_vibrational_groups(structure, cutoff, former_types, o_type)
    masses = structure.get_masses()
    infrared_settings = None
    if infrared:
        if block_frames < _MIN_INFRARED_FRAMES:
            msg = f"infrared=True needs at least {_MIN_INFRARED_FRAMES} frames per block, got {block_frames}."
            raise ValueError(msg)
        volume_a3 = float(structure.cell.volume)
        _validate_positive("The cell volume", volume_a3)
        infrared_settings = {
            **_infrared_settings(charges, eps_inf, potential, structure),
            "volume_a3": volume_a3,
            "groups": groups,
        }

    equilibrated, _ = _run_lammps_md(
        structure=structure,
        potential=potential,
        tmp_working_directory=tmp_working_directory,
        temperature=temperature_sim,
        n_ionic_steps=10_000,
        timestep=timestep,
        n_print_thermo=1000,
        initial_temperature=temperature_sim,
        ensemble="nvt_langevin",
        seed=seed,
        server_kwargs=server_kwargs,
    )
    if equilibration_steps > 0:
        equilibrated, _ = _run_lammps_md(
            structure=equilibrated,
            potential=potential,
            tmp_working_directory=tmp_working_directory,
            temperature=temperature_sim,
            n_ionic_steps=equilibration_steps,
            timestep=timestep,
            n_print_thermo=1000,
            initial_temperature=temperature_sim,
            ensemble=nvt_ensemble,
            seed=seed,
            server_kwargs=server_kwargs,
        )
    # No temperature and no initial temperature: plain fix nve from the velocities of the previous stage.
    nve_kwargs = {
        "potential": potential,
        "temperature": None,
        "initial_temperature": None,
        "n_ionic_steps": block_steps,
        "timestep": timestep,
        "n_dump": dump_every,
        "ensemble": "nve",
        "seed": seed,
        "server_kwargs": server_kwargs,
    }
    spectral_groups = {"total": {"all": np.arange(len(structure))}, **groups}
    structure_final = equilibrated
    spectra, temperatures, energies, step0_energies = [], [], [], []
    for block in range(1, n_blocks + 1):
        # Own directory per block, so its dump can be found and deleted; a random suffix avoids collisions on reuse.
        block_dir = (
            None
            if tmp_working_directory is None
            else tempfile.mkdtemp(prefix=f"vdos_nve_block_{block:03d}_", dir=tmp_working_directory)
        )
        structure_final, block_spectra, temperature, energy_tot, step0_energy = _nve_block(
            structure_final,
            nve_kwargs,
            block,
            n_blocks,
            block_frames,
            masses,
            dt_fs,
            spectral_groups,
            normalization,
            window,
            block_dir,
            keep_trajectory=keep_trajectory,
            infrared=infrared_settings,
        )
        spectra.append(block_spectra)
        temperatures.append(temperature)
        energies.append(energy_tot)
        step0_energies.append(step0_energy)

    vdos, vdos_sem = _block_statistics([block_spectra["vdos"] for block_spectra in spectra])
    vacf, vacf_sem = _block_statistics([block_spectra["vacf"] for block_spectra in spectra])
    temperature, energy_tot = np.concatenate(temperatures), np.concatenate(energies)
    infrared_result = None
    if infrared_settings is not None:
        blocks = [block_spectra["infrared"] for block_spectra in spectra]
        infrared_result = _averaged_infrared(
            blocks, *_block_statistics([block["curves"] for block in blocks]), infrared_settings
        )

    return {
        "frequencies_thz": spectra[0]["frequencies_thz"],
        "vdos": vdos,
        "vdos_sem": vdos_sem,
        "lag_ps": spectra[0]["lag_ps"],
        "vacf": vacf,
        "vacf_sem": vacf_sem,
        "groups": groups,
        "structure": structure_final,
        "temperature": temperature,
        "energy_tot": energy_tot,
        "nve_drift": _nve_drift(temperature, energy_tot, step0_energies, len(structure), dt_fs),
        "dt_fs": dt_fs,
        "n_blocks": n_blocks,
        "n_frames": block_frames,
        "resolution_thz": 1.0 / block_ps,
        "nyquist_thz": nyquist_thz,
        "normalization": normalization,
        "window": window,
        "infrared": infrared_result,
    }

viscosity_ensemble(structure: Atoms, potential: pd.DataFrame, n_replicas: int = 3, seeds: list[int] | None = None, base_seed: int = 12345, temperature_sim: float = 5000.0, timestep: float = 1.0, initial_production_steps: int = 10000000, n_dump: int | None = None, n_print_thermo: int | None = 1, max_total_time_ns: float = 50.0, max_iterations: int = 40, eta_rel_tol: float = 0.05, eta_stable_iters: int = 3, server_kwargs: dict[str, Any] | None = None, *, thermostat: Thermostat, parallel: bool = False, executor: Executor | None = None, tmp_working_directory: str | Path | None = None) -> dict[str, Any]

Run multiple independent viscosity simulations and return ensemble-averaged results.

Each replica starts from the same structure but uses a different random seed for velocity initialisation, producing statistically independent trajectories. The viscosity (and other properties) are averaged across replicas and the inter-replica standard deviation is reported as the uncertainty.

Execution modes (mutually exclusive; executor takes priority):

  • executor provided — each replica is submitted via the executor's .submit() method. Pass any executorlib executor (SlurmJobExecutor, SlurmClusterExecutor, SingleNodeExecutor, …) to run replicas on an HPC cluster. The executor's resource_dict is automatically populated with the MPI core count from server_kwargs["cores"]. The executor's lifecycle is managed by the caller.
  • parallel=True — replicas run simultaneously on the local machine using ThreadPoolExecutor. Requires n_replicas * server_kwargs["cores"] total cores to be available.
  • default (sequential) — replicas run one after another on the local machine.

Seeds are written to tmp_working_directory/viscosity_ensemble_seeds.json immediately after generation so they are preserved even if the run is interrupted.

Parameters:

Name Type Description Default
structure Atoms

Input structure (assumed pre-equilibrated).

required
potential DataFrame

LAMMPS potential DataFrame.

required
n_replicas int

Number of independent replicas to run. Default 3.

3
seeds list[int] | None

Explicit list of integer seeds, one per replica. If None, seeds are auto-generated from base_seed using a NumPy RNG.

None
base_seed int

Master seed used to generate per-replica seeds when seeds is None. Default 12345.

12345
temperature_sim float

Simulation temperature in Kelvin.

5000.0
timestep float

MD timestep in fs.

1.0
initial_production_steps int

Steps for the first production run per replica.

10000000
n_dump int | None

Dump output frequency.

None
n_print_thermo int | None

Thermodynamic output frequency.

1
max_total_time_ns float

Maximum total production time per replica in nanoseconds.

50.0
max_iterations int

Maximum number of 100 ps extension iterations per replica.

40
eta_rel_tol float

Relative change threshold for eta-stability check.

0.05
eta_stable_iters int

Consecutive stable iterations required per replica.

3
server_kwargs dict[str, Any] | None

Additional server arguments forwarded to LAMMPS (e.g. {"cores": 6} sets the MPI process count per replica).

None
thermostat Thermostat

Thermostat of the equilibration and production runs, "nose_hoover" or "langevin".

required
parallel bool

If True, run all replicas simultaneously using threads. Requires enough cores for all replicas at once. Default False. Ignored when executor is provided.

False
executor Executor | None

Optional executorlib (or compatible) executor. When provided, each replica is submitted as executor.submit(_run_replica, i, seed, resource_dict={"cores": N}). Example::

from executorlib import SlurmJobExecutor
with SlurmJobExecutor(max_workers=100) as exe:
    result = viscosity_ensemble(..., executor=exe)
None
tmp_working_directory str | Path | None

Directory for LAMMPS runs and seed file.

None

Returns:

Type Description
dict[str, Any]

A dictionary containing: - viscosity: Mean shear viscosity across replicas (Pa·s) - viscosity_fit_residual: Sample standard deviation across replicas (Pa·s, ddof=1) - viscosity_sem: Standard error of the mean (Pa·s) - shear_modulus_inf: Mean infinite-frequency shear modulus (Pa) - bulk_viscosity: Mean bulk viscosity (Pa·s) - maxwell_relaxation_time_ps: Mean Maxwell relaxation time (ps) - mean_pressure_gpa: Mean pressure averaged across replicas (GPa) - temperature: Mean temperature across all replicas (K) - n_replicas: Number of replicas run - seeds: List of seeds actually used - viscosities: Per-replica shear viscosity values (Pa·s) - converged: Per-replica convergence flags - results: Full viscosity_simulation output dicts per replica

Example

out = viscosity_ensemble( ... structure=my_atoms, ... potential=my_potential_df, ... n_replicas=3, ... temperature_sim=4000.0, ... n_print_thermo=10, ... server_kwargs={"cores": 4}, ... thermostat="nose_hoover", ... ) print(out["viscosity"], "±", out["viscosity_sem"], "Pa·s")

Source code in amorphouspy/src/amorphouspy/properties/viscosity.py
def viscosity_ensemble(  # noqa: C901
    structure: Atoms,
    potential: pd.DataFrame,
    n_replicas: int = 3,
    seeds: list[int] | None = None,
    base_seed: int = 12345,
    temperature_sim: float = 5000.0,
    timestep: float = 1.0,
    initial_production_steps: int = 10_000_000,
    n_dump: int | None = None,
    n_print_thermo: int | None = 1,
    max_total_time_ns: float = 50.0,
    max_iterations: int = 40,
    eta_rel_tol: float = 0.05,
    eta_stable_iters: int = 3,
    server_kwargs: dict[str, Any] | None = None,
    *,
    thermostat: Thermostat,
    parallel: bool = False,
    executor: Executor | None = None,
    tmp_working_directory: str | Path | None = None,
) -> dict[str, Any]:
    """Run multiple independent viscosity simulations and return ensemble-averaged results.

    Each replica starts from the same structure but uses a different random seed for
    velocity initialisation, producing statistically independent trajectories.  The
    viscosity (and other properties) are averaged across replicas and the inter-replica
    standard deviation is reported as the uncertainty.

    **Execution modes** (mutually exclusive; ``executor`` takes priority):

    * ``executor`` provided — each replica is submitted via the executor's ``.submit()``
      method.  Pass any executorlib executor (``SlurmJobExecutor``, ``SlurmClusterExecutor``,
      ``SingleNodeExecutor``, …) to run replicas on an HPC cluster.  The executor's
      ``resource_dict`` is automatically populated with the MPI core count from
      ``server_kwargs["cores"]``.  The executor's lifecycle is managed by the caller.
    * ``parallel=True`` — replicas run simultaneously on the local machine using
      ``ThreadPoolExecutor``.  Requires ``n_replicas * server_kwargs["cores"]`` total
      cores to be available.
    * default (sequential) — replicas run one after another on the local machine.

    Seeds are written to ``tmp_working_directory/viscosity_ensemble_seeds.json``
    immediately after generation so they are preserved even if the run is interrupted.

    Args:
        structure: Input structure (assumed pre-equilibrated).
        potential: LAMMPS potential DataFrame.
        n_replicas: Number of independent replicas to run. Default 3.
        seeds: Explicit list of integer seeds, one per replica.  If ``None``, seeds are
            auto-generated from ``base_seed`` using a NumPy RNG.
        base_seed: Master seed used to generate per-replica seeds when ``seeds`` is
            ``None``.  Default 12345.
        temperature_sim: Simulation temperature in Kelvin.
        timestep: MD timestep in fs.
        initial_production_steps: Steps for the first production run per replica.
        n_dump: Dump output frequency.
        n_print_thermo: Thermodynamic output frequency.
        max_total_time_ns: Maximum total production time per replica in nanoseconds.
        max_iterations: Maximum number of 100 ps extension iterations per replica.
        eta_rel_tol: Relative change threshold for eta-stability check.
        eta_stable_iters: Consecutive stable iterations required per replica.
        server_kwargs: Additional server arguments forwarded to LAMMPS (e.g.
            ``{"cores": 6}`` sets the MPI process count per replica).
        thermostat: Thermostat of the equilibration and production runs, ``"nose_hoover"`` or ``"langevin"``.
        parallel: If ``True``, run all replicas simultaneously using threads.
            Requires enough cores for all replicas at once. Default ``False``.
            Ignored when ``executor`` is provided.
        executor: Optional executorlib (or compatible) executor.  When provided,
            each replica is submitted as ``executor.submit(_run_replica, i, seed,
            resource_dict={"cores": N})``.  Example::

                from executorlib import SlurmJobExecutor
                with SlurmJobExecutor(max_workers=100) as exe:
                    result = viscosity_ensemble(..., executor=exe)

        tmp_working_directory: Directory for LAMMPS runs and seed file.

    Returns:
        A dictionary containing:
            - viscosity: Mean shear viscosity across replicas (Pa·s)
            - viscosity_fit_residual: Sample standard deviation across replicas (Pa·s, ddof=1)
            - viscosity_sem: Standard error of the mean (Pa·s)
            - shear_modulus_inf: Mean infinite-frequency shear modulus (Pa)
            - bulk_viscosity: Mean bulk viscosity (Pa·s)
            - maxwell_relaxation_time_ps: Mean Maxwell relaxation time (ps)
            - mean_pressure_gpa: Mean pressure averaged across replicas (GPa)
            - temperature: Mean temperature across all replicas (K)
            - n_replicas: Number of replicas run
            - seeds: List of seeds actually used
            - viscosities: Per-replica shear viscosity values (Pa·s)
            - converged: Per-replica convergence flags
            - results: Full ``viscosity_simulation`` output dicts per replica

    Example:
        >>> out = viscosity_ensemble(
        ...     structure=my_atoms,
        ...     potential=my_potential_df,
        ...     n_replicas=3,
        ...     temperature_sim=4000.0,
        ...     n_print_thermo=10,
        ...     server_kwargs={"cores": 4},
        ...     thermostat="nose_hoover",
        ... )
        >>> print(out["viscosity"], "±", out["viscosity_sem"], "Pa·s")

    """
    if seeds is None:
        rng = np.random.default_rng(base_seed)
        seeds_list: list[int] = rng.integers(1, 900_000_000, size=n_replicas).tolist()
    else:
        seeds_list = list(seeds)

    if len(seeds_list) != n_replicas:
        msg = f"len(seeds)={len(seeds_list)} does not match n_replicas={n_replicas}"
        raise ValueError(msg)

    if tmp_working_directory is not None:
        seeds_path = Path(tmp_working_directory) / "viscosity_ensemble_seeds.json"
        seeds_path.parent.mkdir(parents=True, exist_ok=True)
        seeds_path.write_text(json.dumps({"base_seed": base_seed, "seeds": seeds_list}, indent=2))
        warnings.warn(
            f"viscosity_ensemble: seeds saved to {seeds_path}",
            stacklevel=2,
        )

    def _run_replica(i: int, seed: int) -> dict[str, Any]:
        warnings.warn(
            f"viscosity_ensemble: starting replica {i + 1}/{n_replicas}, seed={seed}",
            stacklevel=6,
        )
        if tmp_working_directory is not None:
            replica_workdir: Path | None = Path(tmp_working_directory) / f"replica_{i}"
            replica_workdir.mkdir(parents=True, exist_ok=True)
        else:
            replica_workdir = None
        result_i = viscosity_simulation(
            structure=structure,
            potential=potential,
            temperature_sim=temperature_sim,
            timestep=timestep,
            initial_production_steps=initial_production_steps,
            n_dump=n_dump,
            n_print_thermo=n_print_thermo,
            max_total_time_ns=max_total_time_ns,
            max_iterations=max_iterations,
            eta_rel_tol=eta_rel_tol,
            eta_stable_iters=eta_stable_iters,
            server_kwargs=server_kwargs,
            thermostat=thermostat,
            seed=int(seed),
            tmp_working_directory=replica_workdir,
        )
        result_i["seed"] = int(seed)
        return result_i

    replica_results: list[dict[str, Any]] = []
    if executor is not None:
        # Submit each replica as a separate job via the provided executor.
        # The executor (e.g. SlurmJobExecutor) handles SLURM script generation and
        # job submission automatically.  Configure resource requirements (cores,
        # partition, memory) on the executor itself at construction time.
        ordered_results: list[dict[str, Any]] = [{}] * n_replicas
        replica_futures = {executor.submit(_run_replica, i, seed): i for i, seed in enumerate(seeds_list)}
        for completed_future in as_completed(replica_futures):
            replica_index = replica_futures[completed_future]
            ordered_results[replica_index] = completed_future.result()
        replica_results = ordered_results
    elif parallel:
        # Run all replicas simultaneously on the local machine using threads.
        # Each LAMMPS process is MPI-parallel and releases the GIL, so threads
        # do not compete for the Python interpreter.
        ordered_results = [{}] * n_replicas
        with ThreadPoolExecutor(max_workers=n_replicas) as thread_pool:
            replica_futures = {thread_pool.submit(_run_replica, i, seed): i for i, seed in enumerate(seeds_list)}
            for completed_future in as_completed(replica_futures):
                replica_index = replica_futures[completed_future]
                ordered_results[replica_index] = completed_future.result()
        replica_results = ordered_results
    else:
        replica_results = [_run_replica(i, seed) for i, seed in enumerate(seeds_list)]

    per_replica_viscosity_data = [r["viscosity_data"] for r in replica_results]

    shear_viscosities = np.array([data["viscosity"] for data in per_replica_viscosity_data])
    mean_viscosity = float(np.mean(shear_viscosities))
    std_viscosity = float(np.std(shear_viscosities, ddof=1)) if n_replicas > 1 else 0.0
    sem_viscosity = std_viscosity / math.sqrt(n_replicas) if n_replicas > 1 else 0.0

    def _mean_across_replicas(key: str) -> float:
        return float(np.mean([data[key] for data in per_replica_viscosity_data]))

    return {
        "viscosity": mean_viscosity,
        "viscosity_fit_residual": std_viscosity,
        "viscosity_sem": sem_viscosity,
        "shear_modulus_inf": _mean_across_replicas("shear_modulus_inf"),
        "bulk_viscosity": _mean_across_replicas("bulk_viscosity"),
        "maxwell_relaxation_time_ps": _mean_across_replicas("maxwell_relaxation_time_ps"),
        "mean_pressure_gpa": _mean_across_replicas("mean_pressure_gpa"),
        "temperature": _mean_across_replicas("temperature"),
        "n_replicas": n_replicas,
        "seeds": seeds_list,
        "viscosities": shear_viscosities.tolist(),
        "converged": [r["converged"] for r in replica_results],
        "results": replica_results,
    }

viscosity_simulation(structure: Atoms, potential: pd.DataFrame, temperature_sim: float = 5000.0, timestep: float = 1.0, initial_production_steps: int = 10000000, n_dump: int | None = None, n_print_thermo: int | None = 1, max_total_time_ns: float = 50.0, max_iterations: int = 40, eta_rel_tol: float = 0.05, eta_stable_iters: int = 3, server_kwargs: dict[str, Any] | None = None, *, thermostat: Thermostat, seed: int = 12345, tmp_working_directory: str | Path | None = None) -> dict[str, Any]

Perform an autonomous viscosity simulation using the Helfand moment method.

Runs an initial NVT production MD (default 10 ns) and iteratively extends it by 100 ps until viscosity converges or limits are reached.

Convergence requires both conditions to be true simultaneously:

  1. eta-stability - |eta_new - eta_prev| / eta_prev < eta_rel_tol for eta_stable_iters consecutive iterations.
  2. MSD linearity - the local slope of the Helfand moment MSD is flat in the last 30 % of the lag window (_viscosity_plateaued check), confirming that the diffusive regime has been reached.

Extensions stop when either max_total_time_ns or max_iterations is exhausted. get_viscosity is retained as a legacy cross-check in the return dict.

Parameters:

Name Type Description Default
structure Atoms

Input structure (assumed pre-equilibrated).

required
potential DataFrame

LAMMPS potential DataFrame.

required
temperature_sim float

Simulation temperature in Kelvin.

5000.0
timestep float

MD timestep in fs.

1.0
initial_production_steps int

Steps for the first production run. Default 10,000,000 (= 10 ns at 1 fs timestep).

10000000
n_dump int | None

Dump output frequency.

None
n_print_thermo int | None

Thermodynamic output frequency.

1
max_total_time_ns float

Maximum total production time in nanoseconds. Default 50 ns.

50.0
max_iterations int

Maximum number of 100 ps extension iterations. Default 40.

40
eta_rel_tol float

Relative change threshold for eta-stability check. Default 0.05 (5 %).

0.05
eta_stable_iters int

Consecutive stable iterations required. Default 3.

3
server_kwargs dict[str, Any] | None

Additional server arguments forwarded to LAMMPS.

None
thermostat Thermostat

Thermostat of the equilibration and production runs, "nose_hoover" or "langevin".

required
seed int

Random seed for velocity initialization.

12345
tmp_working_directory str | Path | None

Temporary directory for LAMMPS runs.

None

Returns:

Type Description
dict[str, Any]

A dictionary containing: - viscosity_data: Output of helfand_viscosity from the final iteration. - result: Accumulated raw MD arrays (pressures, volume, temperature). - structure: Final ASE Atoms object. - total_production_steps: Total production steps completed. - iterations: Number of iterations run. - converged: True if both convergence criteria were satisfied.

Raises:

Type Description
ValueError

If the potential DataFrame is empty.

Example

result = viscosity_simulation( ... structure=my_atoms, ... potential=my_potential_df, ... temperature_sim=3000.0, ... thermostat="nose_hoover", ... ) converged = result["converged"] print(converged)

Source code in amorphouspy/src/amorphouspy/properties/viscosity.py
def viscosity_simulation(
    structure: Atoms,
    potential: pd.DataFrame,
    temperature_sim: float = 5000.0,
    timestep: float = 1.0,
    initial_production_steps: int = 10_000_000,
    n_dump: int | None = None,
    n_print_thermo: int | None = 1,
    max_total_time_ns: float = 50.0,
    max_iterations: int = 40,
    eta_rel_tol: float = 0.05,
    eta_stable_iters: int = 3,
    server_kwargs: dict[str, Any] | None = None,
    *,
    thermostat: Thermostat,
    seed: int = 12345,
    tmp_working_directory: str | Path | None = None,
) -> dict[str, Any]:
    """Perform an autonomous viscosity simulation using the Helfand moment method.

    Runs an initial NVT production MD (default 10 ns) and iteratively extends
    it by 100 ps until viscosity converges or limits are reached.

    Convergence requires both conditions to be true simultaneously:

    1. **eta-stability** - ``|eta_new - eta_prev| / eta_prev < eta_rel_tol``
       for ``eta_stable_iters`` consecutive iterations.
    2. **MSD linearity** - the local slope of the Helfand moment MSD is flat
       in the last 30 % of the lag window (``_viscosity_plateaued`` check),
       confirming that the diffusive regime has been reached.

    Extensions stop when either ``max_total_time_ns`` or ``max_iterations``
    is exhausted.  ``get_viscosity`` is retained as a legacy cross-check in
    the return dict.

    Args:
        structure: Input structure (assumed pre-equilibrated).
        potential: LAMMPS potential DataFrame.
        temperature_sim: Simulation temperature in Kelvin.
        timestep: MD timestep in fs.
        initial_production_steps: Steps for the first production run.
            Default 10,000,000 (= 10 ns at 1 fs timestep).
        n_dump: Dump output frequency.
        n_print_thermo: Thermodynamic output frequency.
        max_total_time_ns: Maximum total production time in nanoseconds.
            Default 50 ns.
        max_iterations: Maximum number of 100 ps extension iterations.
            Default 40.
        eta_rel_tol: Relative change threshold for eta-stability check.
            Default 0.05 (5 %).
        eta_stable_iters: Consecutive stable iterations required.
            Default 3.
        server_kwargs: Additional server arguments forwarded to LAMMPS.
        thermostat: Thermostat of the equilibration and production runs, ``"nose_hoover"`` or ``"langevin"``.
        seed: Random seed for velocity initialization.
        tmp_working_directory: Temporary directory for LAMMPS runs.

    Returns:
        A dictionary containing:
            - viscosity_data: Output of ``helfand_viscosity`` from the final iteration.
            - result: Accumulated raw MD arrays (pressures, volume, temperature).
            - structure: Final ASE ``Atoms`` object.
            - total_production_steps: Total production steps completed.
            - iterations: Number of iterations run.
            - converged: True if both convergence criteria were satisfied.

    Raises:
        ValueError: If the potential DataFrame is empty.

    Example:
        >>> result = viscosity_simulation(
        ...     structure=my_atoms,
        ...     potential=my_potential_df,
        ...     temperature_sim=3000.0,
        ...     thermostat="nose_hoover",
        ... )
        >>> converged = result["converged"]
        >>> print(converged)

    """
    max_steps = int(max_total_time_ns * 1e6 / timestep)
    ext_steps = int(100_000.0 / timestep)  # 100 ps per extension

    warnings.warn(
        f"viscosity_simulation: starting initial run "
        f"({initial_production_steps:,} steps, T={temperature_sim} K, "
        f"timestep={timestep} fs)",
        stacklevel=2,
    )

    sim_result = _viscosity_simulation(
        structure=structure,
        potential=potential,
        temperature_sim=temperature_sim,
        timestep=timestep,
        production_steps=initial_production_steps,
        n_dump=n_dump,
        n_print_thermo=n_print_thermo,
        server_kwargs=server_kwargs,
        thermostat=thermostat,
        seed=seed,
        tmp_working_directory=tmp_working_directory,
    )

    output_frequency = n_print_thermo if n_print_thermo is not None else n_dump
    if output_frequency is None:
        output_frequency = 1

    accumulated_md_data: dict[str, Any] = {
        "pressures": sim_result["result"]["pressures"],
        "volume": sim_result["result"]["volume"],
        "temperature": sim_result["result"]["temperature"],
    }
    current_structure: Atoms = sim_result["structure"]
    total_production_steps: int = initial_production_steps
    iterations: int = 1
    converged: bool = False
    helfand_data: dict[str, Any] = {}
    eta_prev: float | None = None
    stable_count: int = 0

    while iterations <= max_iterations:
        t_total_ps = total_production_steps * timestep / 1000.0

        helfand_data = helfand_viscosity(
            {"result": accumulated_md_data},
            timestep=timestep,
            output_frequency=output_frequency,
        )
        eta_curr = float(helfand_data["viscosity"])

        # Secondary check: MSD must be in the linear diffusive regime.
        # np.diff of the MSD gives the local slope; if that slope is itself
        # flat (_viscosity_plateaued), the MSD is linear.
        msd_arr = np.asarray(helfand_data["msd"])
        msd_linear = _viscosity_plateaued(
            np.diff(msd_arr),
            tail_fraction=0.3,
            rel_slope_tol=0.05,
        )

        if eta_prev is not None and eta_prev != 0.0:
            rel_change = abs(eta_curr - eta_prev) / abs(eta_prev)
            if rel_change < eta_rel_tol:
                stable_count += 1
            else:
                stable_count = 0

            warnings.warn(
                f"viscosity_simulation: iter {iterations}, "
                f"eta={eta_curr:.4e} Pa.s, rel_change={rel_change:.3f} "
                f"(tol={eta_rel_tol}), stable={stable_count}/{eta_stable_iters}, "
                f"msd_linear={msd_linear}, t={t_total_ps:.1f} ps",
                stacklevel=2,
            )

            if stable_count >= eta_stable_iters and msd_linear:
                warnings.warn(
                    f"viscosity_simulation: CONVERGED at iteration {iterations} "
                    f"(eta_rel={rel_change:.3f}, msd_linear={msd_linear})",
                    stacklevel=2,
                )
                converged = True
                break
        else:
            warnings.warn(
                f"viscosity_simulation: iter {iterations}, "
                f"eta={eta_curr:.4e} Pa.s (first estimate), t={t_total_ps:.1f} ps",
                stacklevel=2,
            )

        eta_prev = eta_curr

        if total_production_steps >= max_steps:
            warnings.warn(
                f"viscosity_simulation: time budget exhausted ({t_total_ps:.1f} ps).",
                stacklevel=2,
            )
            break

        _ext = min(ext_steps, max_steps - total_production_steps)

        warnings.warn(
            f"viscosity_simulation: extending by {_ext:,} steps ({_ext * timestep / 1000:.0f} ps).",
            stacklevel=2,
        )

        current_structure = _extend_viscosity_production_and_accumulate(
            current_structure=current_structure,
            potential=potential,
            accumulated_md_data=accumulated_md_data,
            extension_steps=_ext,
            temperature_sim=temperature_sim,
            timestep=timestep,
            thermostat=thermostat,
            server_kwargs=server_kwargs,
            n_dump=n_dump,
            n_print_thermo=n_print_thermo,
            tmp_working_directory=tmp_working_directory,
        )

        total_production_steps += _ext
        iterations += 1

    warnings.warn(
        f"viscosity_simulation: finished. converged={converged}, "
        f"iterations={iterations}, total_steps={total_production_steps:,}",
        stacklevel=2,
    )

    return {
        "viscosity_data": helfand_data,
        "result": accumulated_md_data,
        "structure": current_structure,
        "total_production_steps": total_production_steps,
        "iterations": iterations,
        "converged": converged,
    }

write_angle_distribution(bin_centers: np.ndarray, angle_hist: np.ndarray, composition: float, filepath: str, *, append: bool = False) -> None

Write angle distribution to a text file.

Parameters:

Name Type Description Default
bin_centers ndarray

Angle bin centers in degrees.

required
angle_hist ndarray

Normalized angle histogram.

required
composition float

Composition value (e.g., % modifier).

required
filepath str

Output filepath.

required
append bool

Whether to append to file.

False
Example

write_angle_distribution(centers, hist, 0.5, "angles.txt")

Source code in amorphouspy/src/amorphouspy/atoms/io.py
def write_angle_distribution(
    bin_centers: np.ndarray,
    angle_hist: np.ndarray,
    composition: float,
    filepath: str,
    *,
    append: bool = False,
) -> None:
    """Write angle distribution to a text file.

    Args:
        bin_centers: Angle bin centers in degrees.
        angle_hist: Normalized angle histogram.
        composition: Composition value (e.g., % modifier).
        filepath: Output filepath.
        append: Whether to append to file.

    Example:
        >>> write_angle_distribution(centers, hist, 0.5, "angles.txt")

    """
    mode = "a" if append else "w"
    write_header = not append or not Path(filepath).exists()
    with Path(filepath).open(mode, encoding="utf-8") as f:
        if write_header:
            f.write("Composition " + " ".join(f"{b:.1f}" for b in bin_centers) + "\n")
        f.write(f"{composition} " + " ".join(f"{v:.6f}" for v in angle_hist) + "\n")

write_distribution_to_file(composition: float | str, filepath: str, dist: dict[int, int], label: str, *, append: bool = False) -> None

Write a coordination/Qn histogram to a text file.

Parameters:

Name Type Description Default
composition float | str

Composition value to label row.

required
filepath str

Output filepath.

required
dist dict[int, int]

Histogram data.

required
label str

Prefix for headers (e.g., Si or Q).

required
append bool

Append mode; writes header only if file does not exist.

False
Example

write_distribution_to_file(0.5, "qn.txt", qn_dist, "Q")

Source code in amorphouspy/src/amorphouspy/atoms/io.py
def write_distribution_to_file(
    composition: float | str,
    filepath: str,
    dist: dict[int, int],
    label: str,
    *,
    append: bool = False,
) -> None:
    """Write a coordination/Qn histogram to a text file.

    Args:
        composition: Composition value to label row.
        filepath: Output filepath.
        dist: Histogram data.
        label: Prefix for headers (e.g., Si or Q).
        append: Append mode; writes header only if file does not exist.

    Example:
        >>> write_distribution_to_file(0.5, "qn.txt", qn_dist, "Q")

    """
    max_n = max(dist.keys(), default=0)
    total = sum(dist.values())
    headers = [f"{label}_{i}" for i in range(max_n + 1)] + [f"{label}_tot"]
    values = [dist.get(i, 0) for i in range(max_n + 1)] + [total]
    mode = "a" if append else "w"
    write_header = not append or not Path(filepath).exists()
    with Path(filepath).open(mode, encoding="utf-8") as f:
        if write_header:
            f.write("Composition " + " ".join(headers) + "\n")
        f.write(str(composition) + " " + " ".join(map(str, values)) + "\n")

write_xyz(filename: str, coords: np.ndarray, types: np.ndarray, box_size: np.ndarray | None = None, type_dict: dict[int, str] | None = None) -> None

Write atomic configuration to an XYZ file.

Parameters:

Name Type Description Default
filename str

Output XYZ file name.

required
coords ndarray

Atomic coordinates.

required
types ndarray

Atomic types as integers.

required
box_size ndarray | None

Simulation box size in x, y, z.

None
type_dict dict[int, str] | None

Dictionary mapping atomic type integers to element symbols.

None
Example

write_xyz("output.xyz", coords, types, box, {14: "Si", 8: "O"})

Source code in amorphouspy/src/amorphouspy/atoms/io.py
def write_xyz(
    filename: str,
    coords: np.ndarray,
    types: np.ndarray,
    box_size: np.ndarray | None = None,
    type_dict: dict[int, str] | None = None,
) -> None:
    """Write atomic configuration to an XYZ file.

    Args:
        filename: Output XYZ file name.
        coords: Atomic coordinates.
        types: Atomic types as integers.
        box_size: Simulation box size in x, y, z.
        type_dict: Dictionary mapping atomic type integers to element symbols.

    Example:
        >>> write_xyz("output.xyz", coords, types, box, {14: "Si", 8: "O"})

    """
    if type_dict is None:
        msg = "type_dict must be provided"
        raise ValueError(msg)

    n_atoms = coords.shape[0]
    path = Path(filename)
    with path.open("w") as f:
        f.write(f"{n_atoms}\n")
        if box_size is not None:
            f.write(f"CUB {box_size[0]:.8f} {box_size[1]:.8f} {box_size[2]:.8f}\n")
        else:
            f.write("\n")
        for t, (x, y, z) in zip(types, coords, strict=False):
            symbol = type_dict.get(t)
            if symbol is None:
                msg = f"Unknown atomic type: {t}"
                raise ValueError(msg)
            f.write(f"{symbol} {x:.8f} {y:.8f} {z:.8f}\n")