crystod.md#
Public MD-trajectory API of CrystOD (the crystod-md domain).
This module mirrors crystod-md --adp and crystod-md --project. For
--adp it holds the building blocks that turn a
molecular-dynamics XDATCAR trajectory into a time-averaged structure with
symmetry-constrained anisotropic displacement parameters (ADPs, the U_ij
tensors of the _atom_site_aniso_U_* loop of a CIF file). The command
itself (crystod.xdatcar_adp.main) chains these functions with the folding
of the MD supercell onto one unit cell, the spglib symmetry search of the
averaged structure and the CIF writer; the API exposes the reusable pieces,
so the same site-symmetry constraints can be applied to displacement
statistics obtained elsewhere.
Trajectory input:
read_xdatcar– read anXDATCAR(fixed-cell, or NpT with repeated headers) into the element list, the per-frame lattices and the fractional coordinates of every frame.
Site-symmetry constraints on U_ij (crystod-md --adp):
get_site_symmetry_operations– the space-group rotations that leave a site fixed;build_symmetry_projector– the 6x6 projector onto theUtensors invariant under those rotations;apply_symmetry_constraints– symmetrize a 3x3Utensor with such a projector;get_constraint_description– spell a projector out asU11=U22, U12=0, ...for reports.
Mode projection (crystod-md --project):
project_trajectory– match the trajectory atoms to the ideal supercell of the parent primitive cell and project the displacements of every frame onto its symmetry-adapted patterns (the bases ofcrystod-phonon --vibration):Q(t)per irrep, mode space, component and q point, the statistics of each series and the sum rule; returns aTrajectoryProjection. Withphonon=(a phonopy object with force constants,crystod-md --project --yaml) the basis is the phonon eigenvectors at each q instead: one mass-weighted normal coordinatea(t)per mode (the modes ofcrystod-phonon --modulation), with the effective frequencysqrt(k_B T/<a^2>)/(2 pi)whentemperature=is given;star=Trueprojects every arm of the star of each requested q;format_projection– the terminal report of--projectfor such a result;commensurate_qpoints– the q points a diagonal supercell resolves.
Q is the displacement norm per parent primitive cell carried by a
pattern (at a time-reversal invariant q, the amplitude of crystod-phonon
--modulation; the mass-weighted centre-of-mass drift of every frame is
removed first):
symbols, lattices, frames = md.read_xdatcar("XDATCAR")
result = md.project_trajectory("221_PPOSCAR_ScF3", (4, 4, 4), symbols,
lattices[1000:], frames[1000:],
qpoints=["R", "M"], irreps=["R4+", "M3+"])
print(md.format_projection(result))
import phonopy
phonon = phonopy.load("phonopy_params.yaml", is_nac=False)
modes = md.project_trajectory(None, (4, 4, 4), symbols, lattices[1000:],
frames[1000:], qpoints=["R", "M", "GM"],
phonon=phonon, temperature=300)
print(modes.projections[0].columns[0], # "1_R4+"
modes.projections[0].effective_frequencies[0])
The functions chain in that order:
import spglib
from crystod import md
symbols, lattices, frames = md.read_xdatcar("XDATCAR")
symmetry = spglib.get_symmetry(cell) # the time-averaged unit cell
site_ops = md.get_site_symmetry_operations( # tolerance in Angstrom
site, symmetry["rotations"], symmetry["translations"], lattice=cell[0])
projector = md.build_symmetry_projector(site_ops, lattice=cell[0])
u_ij = md.apply_symmetry_constraints(u_raw, projector) # CIF U^ij
Attributes resolve lazily (PEP 562): importing this module is instant, and the
implementation modules crystod.xdatcar_adp (numpy and spglib) and
crystod.md_projection are loaded on first use. Functions reached through this namespace report bad input as
ValueError instead of the SystemExit the implementation raises for the
command line.
- class crystod.md.TrajectoryProjection(formula, space_group, space_group_number, dim, n_atoms, steps, lattice_mode, matching, projections, skipped=<factory>, irrep_filter=None, projected_msd=0.0, total_msd=0.0, drift_rms=0.0, n_q_covered=0, n_q_commensurate=0, basis='symmetry', temperature=None, star=False)[source]#
Bases:
objectResult of
project_trajectory().- Variables:
formula (str) – Reduced formula of the parent (
"ScF3").space_group (str) – International symbol of the parent.
space_group_number (int) – Its number.
dim (tuple[int, int, int]) – Supercell multiplicities
(n1, n2, n3).n_atoms (int) – Atoms in the supercell.
steps (numpy.ndarray[tuple[Any, ...], numpy.dtype[numpy.int64]]) – The step number of every frame used.
lattice_mode (str) –
"fixed"(one cell),"frame"(each frame’s own cell) or"mean"(the time-averaged cell,mean_lattice).matching (crystod.md_projection.SiteMatching) – The
SiteMatching.projections (list[crystod.md_projection.QProjection]) – One
QProjectionper projected q.skipped (list[str]) – Notes on requested q points that were not projected (the -q partner of a projected q, or no irrep left by the filter) and on filter names that match no irrep at the projected q.
irrep_filter (list[str] | None) – The irrep names of the filter, or
None.projected_msd (float) –
sum_c <Q_c^2>over the projected columns (A^2); in the phonon-eigenvector basissum <a^2>(amu A^2).total_msd (float) –
<|u|^2> / Nafter drift removal (A^2); in the phonon-eigenvector basis<sum_jR m_j |u_j(R)|^2>over the supercell (amu A^2).drift_rms (float) – Root mean square over the frames of the removed centre-of-mass displacement (Angstrom; it includes a static uniform offset of the structure from the ideal sites).
n_q_covered (int) – Commensurate q covered by the projection (a -q partner counts with its q).
n_q_commensurate (int) – All commensurate q of the supercell.
basis (str) –
"symmetry"(the patterns ofcrystod-phonon --vibration) or"eigenvector"(phonon eigenvectors of a phonopy object).temperature (float | None) – The temperature of the effective frequencies (K), or
None.star (bool) – Every arm of the star of each requested q was projected.
- basis: str = 'symmetry'#
- property complete: bool#
Every commensurate q and every irrep was projected.
- dim: tuple[int, int, int]#
- drift_rms: float = 0.0#
- formula: str#
- irrep_filter: list[str] | None = None#
- lattice_mode: str#
- matching: SiteMatching#
- n_atoms: int#
- n_q_commensurate: int = 0#
- n_q_covered: int = 0#
- projected_msd: float = 0.0#
- projections: list[QProjection]#
- skipped: list[str]#
- space_group: str#
- space_group_number: int#
- star: bool = False#
- steps: ndarray[tuple[Any, ...], dtype[int64]]#
- temperature: float | None = None#
- total_msd: float = 0.0#
- crystod.md.apply_symmetry_constraints(u_cryst, projector)[source]#
Symmetrize a
Utensor with a site-symmetry projector.This is the step of
crystod-md --adpthat turns the raw displacement covariance of a Wyckoff position into theU_ijwritten to the CIF file: the six independent components ofu_cryst(upper triangle, order[U11, U22, U33, U12, U13, U23]) are multiplied byprojectorand reassembled into a symmetric matrix.- Parameters:
u_cryst (ndarray[tuple[Any, ...], dtype[float64]]) – Symmetric
(3, 3)tensor of CIF componentsU^{ij}(the basisbuild_symmetry_projectorworks in). Only the upper triangle is read.projector (ndarray[tuple[Any, ...], dtype[float64]]) – The
(6, 6)matrix frombuild_symmetry_projector.
- Returns:
The constrained
(3, 3)tensor, symmetric by construction.- Return type:
ndarray[tuple[Any, …], dtype[float64]]
Example
>>> import numpy as np >>> from crystod import md >>> projector = md.build_symmetry_projector( # two-fold along c ... [np.eye(3, dtype=int), np.diag([-1, -1, 1])]) >>> u = np.array([[0.010, 0.001, 0.002], ... [0.001, 0.012, 0.003], ... [0.002, 0.003, 0.015]]) >>> md.apply_symmetry_constraints(u, projector) array([[0.01 , 0.001, 0. ], [0.001, 0.012, 0. ], [0. , 0. , 0.015]])
- crystod.md.build_symmetry_projector(rotations, lattice=None)[source]#
Build the 6x6 projector onto
Utensors with a given site symmetry.crystod-md --adpcalls this once per Wyckoff position with the rotations found byget_site_symmetry_operations. A symmetric tensor is handled as the component vector[U11, U22, U33, U12, U13, U23]of the CIFU^{ij}(U^{ij} = <dx_i dx_j> / (|a*_i| |a*_j|)withdxthe fractional displacement; Trueblood et al. 1996). A fractional rotationRmapsdx -> R dx, henceU -> M @ U @ M.TwithM = N*^-1 @ R @ N*andN* = diag(|a*_1|, |a*_2|, |a*_3|); the projector is the average of those 6x6 maps over the group. Multiplying a component vector by it leaves the closest tensor that has the full site symmetry, which is whatapply_symmetry_constraintsdoes.MequalsRwhen every rotation only mixes axes of equal reciprocal length, which holds for the conventional cells of the standard settings and for the F-, C-centred, rhombohedral and body-centred cubic primitive cells, but not for body-centred tetragonal or orthorhombic primitive cells (or a general basis).latticemust be given for those.- Parameters:
rotations (Sequence[numpy.ndarray]) – The rotation matrices of the site-symmetry group, each of shape
(3, 3)and acting on fractional coordinates (the spglib convention). The sequence must be a complete group;[identity]gives the identity projector.lattice (array-like, optional) – The
(3, 3)lattice matrix of the cell (rows = lattice vectors, Angstrom), from whichN*is taken; its metric is averaged overrotationsfirst, so an approximately symmetric (instantaneous MD) cell gives exact constraints.None(default) usesRitself, i.e. assumesM == Ras described above.
- Returns:
The
(6, 6)projectorP(idempotent,P @ P == P).- Return type:
ndarray[tuple[Any, …], dtype[float64]]
Example
A two-fold axis along
cforbidsU13andU23:>>> import numpy as np >>> from crystod import md >>> projector = md.build_symmetry_projector( ... [np.eye(3, dtype=int), np.diag([-1, -1, 1])]) >>> md.get_constraint_description(projector) 'U13=0, U23=0'
- crystod.md.commensurate_qpoints(parent_lattice, dim)[source]#
All q of the parent cell commensurate with a diagonal supercell.
The enumeration of
crystod.phonon_subgroups.commensurate_qpoints()(crystod-phonon --subgroup) applied to the supercelldiag(dim)of the parent.- Parameters:
parent_lattice – Parent lattice vectors as rows, shape
(3, 3).dim –
(n1, n2, n3).
- Returns:
n1 n2 n3q points (fractional, parent reciprocal basis), Gamma first, sorted by length.- Return type:
list[tuple[float, float, float]]
- crystod.md.format_projection(result, source=None, files=())[source]#
The terminal report of
crystod-md --project.- Parameters:
result (TrajectoryProjection) – The
TrajectoryProjection.source (dict | None) – Optional input description for the
* Input *block, keysparent,trajectory,frames(a text line).files – Paths of the files written (listed in
* Output files *).
- Returns:
The report,
* ... *blocks separated by blank lines.- Return type:
str
- crystod.md.get_constraint_description(projector, tol=1e-06)[source]#
Spell out the relations a site-symmetry projector imposes on
U.crystod-md --adpprints the result next to every Wyckoff position and in itsSite / Ueq / Constrainttable, for exampleU11=U33, U12=0, U13=0, U23=0for the F site of cubic ScF3. Every symmetric tensor isP @ vfor somev, so its componentiis rowiof the projectorPapplied tov: a component whose row vanishes is reported asUij=0, and two components with equal (opposite) rows asUij=Ukl(Uij=-Ukl). This reading holds for oblique projectors too, such as those of body-centred tetragonal primitive cells. Other linear relations, such asU12 = U11/2on a three-fold axis of a hexagonal cell, are enforced by the projector but not spelled out.- Parameters:
projector (ndarray[tuple[Any, ...], dtype[float64]]) – The
(6, 6)matrix frombuild_symmetry_projector.tol (float) – Absolute tolerance below which a coefficient counts as zero and within which two coefficients count as equal.
- Returns:
The relations joined by
", ";"no constraint"when the projector is the identity (site symmetry 1 or -1), and"general linear constraints only"when it constrainsUonly through relations of the other kind (a two-fold axis alongaof a hexagonal cell:U12 = U22/2,U13 = U23/2).- Return type:
str
Example
>>> import numpy as np >>> from crystod import md >>> three_fold = np.array([[0, -1, 0], [1, -1, 0], [0, 0, 1]]) >>> group = [np.eye(3, dtype=int), three_fold, three_fold @ three_fold] >>> md.get_constraint_description(md.build_symmetry_projector(group)) 'U11=U22, U13=0, U23=0'
- crystod.md.get_site_symmetry_operations(coords, rotations, translations, symprec=0.1, lattice=None)[source]#
Select the space-group operations that leave a site fixed.
This is where the ADP constraints of
crystod-md --adpstart: the site-symmetry group of a Wyckoff position is the subset of the space-group operations(R, t)for whichR @ x + tequalsxup to a lattice translation. Only the rotation parts are returned, which is allbuild_symmetry_projectorneeds.- Parameters:
coords (array-like) – Fractional coordinates
(x, y, z)of the site.rotations (array-like) – Rotation parts of the space-group operations, shape
(n_ops, 3, 3), as inspglib.get_symmetry(cell).translations (array-like) – The matching translation parts, shape
(n_ops, 3).symprec (float) – Tolerance on the distance between
R @ x + tandx. Withlatticeit is the Cartesian minimum-image distance in Angstrom, the unit of spglib’ssymprec(crystod-md --adppasses its--tolerancehere and to spglib). Withoutlatticeit is the Euclidean norm of the wrapped fractional difference (unitless; kept for backward compatibility).lattice (array-like, optional) – The
(3, 3)lattice matrix (rows = lattice vectors, Angstrom) that makessympreca Cartesian distance.None(default) compares fractional coordinates.
- Returns:
The rotation matrices of the site-symmetry group, a list of
(3, 3)arrays in the order ofrotations.
Example
The F site of cubic ScF3 (Pm-3m) has site symmetry 4/mmm, order 16:
>>> import numpy as np, spglib >>> from crystod import md >>> cell = (4.0 * np.eye(3), ... [[0, 0, 0], [0.5, 0, 0], [0, 0.5, 0], [0, 0, 0.5]], ... [21, 9, 9, 9]) >>> symmetry = spglib.get_symmetry(cell) >>> site_ops = md.get_site_symmetry_operations( ... [0.5, 0, 0], symmetry["rotations"], symmetry["translations"]) >>> len(site_ops) 16 >>> md.get_constraint_description(md.build_symmetry_projector(site_ops)) 'U22=U33, U12=0, U13=0, U23=0'
- crystod.md.project_trajectory(parent_cell, dim, symbols, lattices, frames, qpoints=None, irreps=None, mean_lattice=False, steps=None, symprec=1e-05, phonon=None, temperature=None, star=False)[source]#
Project the displacements of an MD trajectory onto parent modes.
The engine of
crystod-md --project. The trajectory atoms are matched to the ideal supercell of the parent (site(j, R)at(x_j + R) / dim) by element and the nearest periodic image of their time-averaged positions, so the atom order of the trajectory does not matter. The displacement of every atom in every frame is taken relative to its ideal site (wrapped to the nearest image, converted to Cartesian with the frame’s own cell or, withmean_lattice, the time-averaged cell), and the mass-weighted centre-of-mass displacement of the frame is removed (drift). Each frame is then projected onto the unit-norm real patterns of the symmetry-adapted spaces ofSymmetryOnlyVibrations.get_symmetry_adapted_spacesat every q:Q = p_hat . u / sqrt(N), the displacement norm per parent primitive cell (at a time-reversal invariant q, the amplitude ofcrystod-phonon --modulation).With
phononthe basis is the phonon eigenvectors instead (see the module docstring): the parent cell isphonon.primitive, the trajectory is taken in mass-weighted coordinates and every column is the normal coordinatea(t)of one mode (and, withtemperature, its effective frequency).- Parameters:
parent_cell – The parent primitive cell, a
PhonopyAtomsor the path of a POSCAR file. Its Cartesian axes are those of the patterns; the trajectory cell must have the same orientation. May beNonewithphonon; if both are given, the cell must bephonon.primitive(lattice vectors and positions within the larger ofsymprecand 1e-4 A, atoms in any order).dim – Diagonal supercell multiplicities
(n1, n2, n3).symbols – Element of every trajectory atom (
read_xdatcar).lattices – One
(3, 3)supercell lattice per frame (rows).frames – Fractional coordinates, shape
(n_frames, n_atoms, 3).qpoints –
Nonefor every tabulated special point commensurate withdim(in the ordercrystod-phonon --vibrationlists them),"all"for every commensurate q, or a list of labels ("R") and coordinate triples ([0.5, 0.5, 0], strings such as"1/2"allowed);"all"may also be an item of the list.irreps – ISO-IR irrep names to keep (
["R4+", "M3+"]; the dimension suffix is optional);Nonekeeps all.mean_lattice (bool) – Use the time-averaged cell for every frame.
steps – Step number of every frame (default
0 .. n_frames - 1).symprec (float) – Symmetry tolerance of the parent.
phonon – A
phonopy.Phonopyobject with force constants (e.g.phonopy.load("phonopy_params.yaml", is_nac=False)): project on its symmetry-adapted eigenvectors at every q (the modes ofcrystod-phonon --modulation).temperature (float | None) – Temperature of the run in K (
phonononly): adds the effective frequency of every mode.star (bool) – Replace every requested q (labels, coordinates, or the default special points) by all arms of its star.
- Returns:
- Raises:
ValueError – The composition is not
n1 n2 n3times the parent’s, the cells disagree, an atom matches no site or two atoms one site, the parent is not primitive, a q is unknown or not commensurate, the irrep filter keeps nothing,parent_cellis not the primitive cell ofphonon, the phonopy object has no force constants, ortemperatureis given withoutphononor is not positive.- Return type:
Example
>>> from crystod import md >>> symbols, lattices, frames = md.read_xdatcar("XDATCAR") >>> result = md.project_trajectory( ... "221_PPOSCAR_ScF3", (4, 4, 4), symbols, lattices, frames[1000:], ... qpoints=["R", "M"], irreps=["R4+", "M3+"]) >>> [p.columns for p in result.projections] [['R4+(3)_3_1', 'R4+(3)_3_2', 'R4+(3)_3_3'], ['M3+(1)_2_1']]
- crystod.md.read_xdatcar(path)[source]#
Read a VASP
XDATCARtrajectory into arrays.This is the input step of
crystod-md --adp. Both layouts written by VASP are handled: the fixed-cell one, a single header followed byDirect configuration=blocks, and the variable-cell (NpT) one, in which every configuration repeats the header. The scaling factor of the header is folded into the lattice. A truncated trailing frame (a run that is still writing) is dropped silently.- Parameters:
path (str) – Path of the
XDATCARfile.- Returns:
symbols: the element symbol of every atom, in file order (one entry per atom, solen(symbols) == n_atoms);lattices: one(3, 3)lattice matrix per frame, rows being the lattice vectors in Angstrom; all identical for a fixed-cell run;frames: the fractional coordinates as written by VASP (wrapped into the cell, not unwrapped), shape(n_frames, n_atoms, 3).
- Return type:
A tuple
(symbols, lattices, frames)- Raises:
FileNotFoundError –
pathdoes not exist.ValueError – The file holds no complete configuration.
Example
>>> from crystod import md >>> symbols, lattices, frames = md.read_xdatcar("XDATCAR") >>> frames.shape # example/06-01_xdatcar2adp: ScF3, 4x4x4 cell, NpT (4001, 256, 3) >>> symbols[0], symbols[-1], lattices[0].shape ('Sc', 'F', (3, 3))