Source code for crystod.phonon_mode_fc

"""
Mode-resolved force constants: ``crystod-phonon --mode-resolved-fc``.

From POSCAR + FORCE_SETS (or FORCE_CONSTANTS) of a supercell calculation,
at the special q points of the space group (the list ``crystod-phonon
--irreps`` surveys, or one ``--qpoint``), this gives the harmonic stiffness
of every phonon level and of every irrep subspace, written to
``mode-resolved-fc.yaml``.

Method.  With n atoms in phonopy's primitive cell (``primitive_matrix=
"auto"``), M = diag(m_i) the masses (amu) and D(q) the phonopy dynamical
matrix (eV/A^2/amu), the Fourier-transformed force-constant matrix is
Phi(q) = M^1/2 D(q) M^1/2 (3n x 3n, Hermitian, eV/A^2), taken from the same
phonopy object so that the phase convention is the one of the eigenvectors.
D(q) has the eigenvalues w (frequency sign(w) sqrt|w| in THz units of
phonopy) and the orthonormal eigenvectors e; the displacement pattern of a
mode is u = M^-1/2 e, normalized to 1 A (the Euclidean norm of u^ over the
3n components of the primitive cell is 1).  A q point with integer
coordinates (a reciprocal lattice vector, e.g. ``--qpoint 1 0 0``) is
reduced to Gamma first: phonopy's eigenvectors there carry the phases
exp(2 pi i G.r_j), which the uniform translations below do not.

(A) Per degenerate set, ``force_constant`` k = u^+ Phi(q) u^ = mu w, with the
    ``effective_mass`` mu = 1 / sum_i ``|e_i|^2 / m_i`` (amu); the sign of k is
    the sign of w (an imaginary mode has k < 0).  Degenerate partners of one
    irrep have the same k (Schur's lemma), so one value per set is given.
    ``force_constant_per_fu`` is k / Z, Z the formula units of the primitive
    cell (the gcd of the species counts).  At Gamma only,
    ``force_constant_translations_removed`` is k of u^ after its uniform
    translation (the mean displacement over the atoms, per Cartesian
    direction) is projected out and the rest renormalized to 1 A: a polar
    mode fixes the centre of mass, not the mean position, so its u^ carries
    a translation part.  It equals k for a mode without one and is not given
    for the acoustic set.  A Gamma set is acoustic when its translational
    weight, the mean over its orthonormal eigenvectors e of the squared norm
    of the projection of e on the three rigid translations (mass-weighted,
    sqrt(m_i) per atom), exceeds 1/2: about 1 for the acoustic set and about
    0 for an optical one, also with force constants that keep the acoustic
    sum rule only approximately (a frequency criterion would fail there).
(B) Per irrep present at q, the ``irrep_hessian`` block: the patterns u of all
    modes carrying that label (every copy, every partner) are
    orthonormalized (QR) into S (3n x d) and S+ Phi(q) S is diagonalized;
    the eigenvalues (eV/A^2), their trace and d are given.  The isotypic
    subspace is invariant under Phi(q), so the block does not depend on the
    basis; it is the Hessian of the energy restricted to the
    symmetry-adapted subspace.  At Gamma a block that contains uniform
    translations is also given with the three translations projected out
    first (``translations_removed``; d drops by their number).
    A degenerate set that carries two labels (an accidental degeneracy, such
    as the acoustic GM1 + GM5 set of P4mm) is split by the character
    projector P_X = (d_X / N_q) sum_g chi_X(g)* Gamma(g) (N_q the order of
    the group of q) built from the
    mode representation matrices of phonopy (``Irreps.ground_matrices``)
    and the character of a set at the same q that carries the single label
    X.  When every label of the set but one has such a reference, the
    remaining label gets the rest of the set (the complement of the known
    projections).  A set that still cannot be split (two or more labels
    without a reference, or one irrep twice) gets no k and mu, as they
    depend on the basis there: its labels are kept, its block is given under
    the combined name ``A + B`` and a NOTE says why.

Conventions.  k is the curvature per primitive cell with the pattern
normalized to 1 A over the primitive cell; it does not change when the
cell is enlarged, whereas k per formula unit does (it refers to the Z of the
primitive cell).  Units: eV/A^2 (1 eV/A^2 = 1000 meV/A^2), amu, THz.
With the amplitude A of an AMPLIMODES-type decomposition (``crystod-group
--supergroup-cif``) measured over the same cell, the harmonic energy of the
pattern is E_cell = k A^2 / 2.

Checks on every call: the eigenvalues w of D(q) equal those behind the
frequencies of :func:`crystod.phonon_irreps.get_irrep_labels` to 1e-6 of
max |w| (compared as w, not as frequencies, which amplify rounding near
zero) and the irrep blocks together span 3n (both raise ``RuntimeError``); the spread of k
within a degenerate set is below 1e-9 eV/A^2 and the number of negative
block eigenvalues equals the number of imaginary modes of that irrep
(Sylvester's law of inertia) (both add a NOTE otherwise).  NOTEs also mark
a q that is not a q point of the supercell (its dynamical matrix is
Fourier-interpolated) and, with NAC, a q so close to Gamma that phonopy adds
no non-analytical term.
"""

from __future__ import annotations

import math
import os
import re
import textwrap
import warnings
from argparse import ArgumentParser, RawTextHelpFormatter
from dataclasses import dataclass, field
from functools import reduce

import numpy as np

from .spglib_compat import ensure_spglib_compat

ensure_spglib_compat()

#: Default name of the written file.
DEFAULT_OUTPUT = "mode-resolved-fc.yaml"

_ZERO_K = 1e-7  # eV/A^2: |k| or |kappa| below this counts as zero ...
_ZERO_K_REL = 1e-6  # ... or below this fraction of the largest |eigenvalue| of Phi(q)
_ACOUSTIC_WEIGHT = 0.5  # translational weight above which a Gamma set is acoustic
_EIG_TOL = 1e-6  # eig(D) against get_irrep_labels, relative to max |w|
_COMMENSURATE_TOL = 1e-6  # q . (supercell vector) this close to an integer: a supercell q
_SCHUR_TOL = 1e-9  # eV/A^2, spread of k within one degenerate set


[docs] @dataclass class ModeForceConstantSet: """The force constant of one degenerate set of phonon modes at q. Attributes: band_indices: 0-based band indices of the set (ascending frequency). irrep_labels: ISO-IR labels with their dimension (``"GM4-(3)"``); a set of an accidental degeneracy lists all its labels, a set with no label carries a generic ``"irrep_N(d)"``. frequency: Mean frequency of the set in THz (negative: imaginary). effective_mass: mu = 1 / (sum over i of ``|e_i|^2 / m_i``) in amu, or ``None`` for a set split into ``components`` and for a set that cannot be split (its value would depend on the basis). force_constant: k = u^+ Phi u^ = mu w in eV/A^2 per primitive cell (the pattern u^ normalized to 1 A over the primitive cell), or ``None`` as ``effective_mass``. force_constant_per_fu: k / Z in eV/A^2 per formula unit, or ``None``. force_constant_translations_removed: At Gamma, k of the pattern with its uniform translation removed and renormalized (eV/A^2); ``None`` away from Gamma, for the acoustic set and for a split or unsplittable set. acoustic: The set is the acoustic set at Gamma: its translational weight, the mean squared projection of its orthonormal eigenvectors e on the three rigid translations (sqrt(m_i) on every atom), exceeds 1/2. n_vectors: Number of patterns behind the values (the set size, or the dimension of the irrep subspace of a component). components: For a set that carries several labels and was split by the character projector: one :class:`ModeForceConstantSet` per label (same ``band_indices``, one label each); else empty. """ band_indices: list[int] irrep_labels: list[str] frequency: float effective_mass: float | None force_constant: float | None force_constant_per_fu: float | None force_constant_translations_removed: float | None = None acoustic: bool = False n_vectors: int = 0 components: list[ModeForceConstantSet] = field(default_factory=list)
[docs] @dataclass class IrrepHessianBlock: """The force-constant matrix restricted to one irrep subspace at q. Attributes: irrep: The irrep label without its dimension suffix (``"GM4-"``); for a set that cannot be split, its labels joined as ``"GM3- + GM5-"``. dim: Dimension of the subspace (multiplicity times irrep dimension). eigenvalues: Eigenvalues of S+ Phi(q) S in eV/A^2, ascending. trace: Their sum in eV/A^2. translations_removed: At Gamma, for a block that contains uniform translations, the same block with them projected out first; else ``None``. """ irrep: str dim: int eigenvalues: list[float] trace: float translations_removed: IrrepHessianBlock | None = None
[docs] @dataclass class ModeForceConstants: """Mode- and irrep-resolved force constants at one q point. Attributes: q: Fractional coordinates of q in the primitive reciprocal basis. q_label: Name of q (``"GM"``, ``"R"``), or ``None``. band_sets: One :class:`ModeForceConstantSet` per degenerate set. irrep_blocks: One :class:`IrrepHessianBlock` per irrep present at q, in the order of first appearance. n_atoms: Atoms in the primitive cell. formula_units: Formula units Z of the primitive cell. notes: Remarks on this q point (q reduced to Gamma, NAC at or near Gamma, a q interpolated from the supercell, unlabeled or unsplittable sets, failed checks). """ q: list[float] q_label: str | None band_sets: list[ModeForceConstantSet] irrep_blocks: list[IrrepHessianBlock] n_atoms: int formula_units: int notes: list[str] = field(default_factory=list)
def _irrep_name(label: str) -> str: return re.sub(r"\(\d+\)$", "", label) def _irrep_dim(label: str) -> int: match = re.search(r"\((\d+)\)$", label) return int(match.group(1)) if match else 1 def _orthonormal_columns(vectors, tol: float = 1e-6): """Orthonormal basis of the column span of ``vectors`` (SVD, rank cut).""" if vectors.shape[1] == 0: return vectors left, singular, _ = np.linalg.svd(vectors, full_matrices=False) return left[:, singular > tol * max(1.0, singular[0])] def _supercell_text(phonon) -> str: """``"2 x 2 x 2"`` for a diagonal supercell matrix, else its nine entries.""" matrix = np.rint(np.array(phonon.supercell_matrix)).astype(int) if np.count_nonzero(matrix - np.diag(np.diag(matrix))) == 0: return " x ".join(str(value) for value in np.diag(matrix)) return "[" + " ".join(str(value) for value in matrix.ravel()) + "]" def formula_units_of(phonon) -> int: """Formula units Z of phonopy's primitive cell (gcd of the species counts).""" numbers = list(phonon.primitive.numbers) counts = [numbers.count(z) for z in sorted(set(numbers))] return int(reduce(math.gcd, counts)) def _label_context(phonon, irt_table=None, prim_mat=None): """``(dataset, irt_table, prim_mat)`` of the labels of ``phonon``.""" from phonopy.structure.cells import get_primitive_matrix_by_centring from .irreptables_compat import load_irreptables from .runtime_compat import get_symmetry_dataset dataset = get_symmetry_dataset(phonon.symmetry) if irt_table is None: irrep_table_class, _ = load_irreptables() irt_table = irrep_table_class(dataset["number"], spinor=False) if prim_mat is None: prim_mat = get_primitive_matrix_by_centring(dataset["international"][0]) return dataset, irt_table, prim_mat
[docs] def mode_resolved_force_constants( phonon, q, *, irt_table=None, prim_mat=None, degeneracy_tolerance: float = 1e-3, q_label: str | None = None, ) -> ModeForceConstants: """Mode- and irrep-resolved force constants at one q point. Args: phonon: A ``phonopy.Phonopy`` object with force constants, built with ``primitive_matrix="auto"``. q: Fractional coordinates of q in the primitive reciprocal basis; a q with integer coordinates is computed at [0, 0, 0] (with a NOTE, and ``q_label`` ``"GM"`` when it is ``None``). irt_table: ISO-IR irrep table of the space group; built from the symmetry of ``phonon`` when ``None``. prim_mat: Conventional-to-primitive matrix of the centring; from the symmetry of ``phonon`` when ``None``. degeneracy_tolerance: Frequency tolerance (THz) of the degenerate sets (``--tolerance``, default 1e-3). q_label: Name of q for the result (``"GM"``, ``"R"``). Returns: :class:`ModeForceConstants` with one :class:`ModeForceConstantSet` per degenerate set and one :class:`IrrepHessianBlock` per irrep. Raises: RuntimeError: The eigenvalues of D(q) differ from those of the irrep labeling by more than 1e-6 of the largest, or the irrep blocks do not span the 3n mode space (an internal inconsistency). ValueError: The q point cannot be labeled (from :func:`crystod.phonon_irreps.get_irrep_labels`). Example:: import phonopy from crystod import phonon ph = phonopy.load(unitcell_filename="221_PPOSCAR_SrTiO3", force_sets_filename="FORCE_SETS", supercell_matrix=[4, 4, 4], primitive_matrix="auto") result = phonon.mode_resolved_force_constants(ph, [0.5, 0.5, 0.5], q_label="R") first = result.band_sets[0] print(first.irrep_labels, first.frequency, first.force_constant) # ['R5-(3)'] -1.0867... -0.077309... (eV/A^2: the unstable octahedral rotation) """ from phonopy.physical_units import get_physical_units from .phonon_irreps import get_irrep_labels _, irt_table, prim_mat = _label_context(phonon, irt_table, prim_mat) q = [float(value) for value in q] to_thz = get_physical_units().DefaultToTHz notes: list[str] = [] is_gamma = bool(np.allclose(q, np.rint(q), atol=1e-8)) if is_gamma and any(abs(value) > 0.5 for value in q): # a reciprocal lattice vector G: phonopy's eigenvectors there carry the # phases exp(2 pi i G.r_j), the uniform translations below do not original = "[" + ", ".join(str(int(round(value))) for value in q) + "]" notes.append(f"q = {original} is equivalent to GM; computed at GM") q = [0.0, 0.0, 0.0] if q_label is None: q_label = "GM" labels, band_sets, freqs = get_irrep_labels( q=q, phonon=phonon, irt_table=irt_table, prim_mat=prim_mat, degeneracy_tolerance=degeneracy_tolerance, ) freqs = np.asarray(freqs, dtype=float) irreps = phonon.irreps ground = np.array(irreps.ground_matrices) characters = np.array(irreps.characters) n_sym = len(ground) n = len(phonon.primitive) masses = np.array(phonon.primitive.masses, dtype=float) sqm3 = np.repeat(np.sqrt(masses), 3) minv3 = 1.0 / np.repeat(masses, 3) z_fu = formula_units_of(phonon) dynmat = phonon.dynamical_matrix dynmat.run(np.array(q, dtype=float)) dmat = np.array(dynmat.dynamical_matrix) dmat = 0.5 * (dmat + dmat.conj().T) phi = dmat * np.outer(sqm3, sqm3) w, evecs = np.linalg.eigh(dmat) # compare the eigenvalues, not sign(w) sqrt|w|: the square root amplifies # the rounding of w near zero (acoustic modes, light atoms) w_labels = np.sign(freqs) * (freqs / to_thz) ** 2 scale_w = max(float(np.max(np.abs(w))), 1e-12) deviation = float(np.max(np.abs(w - w_labels))) if deviation > _EIG_TOL * scale_w: raise RuntimeError( f"internal inconsistency at q = {q}: eig(D) and the irrep labeling differ " f"by {deviation / scale_w:.2e} of max |w|" ) nac = getattr(phonon, "nac_params", None) is not None if is_gamma and nac: notes.append( "--nac: phonopy adds no non-analytical term at exactly Gamma (it needs a " "q direction), so the Gamma values are the analytic (TO) ones" ) elif nac: q_norm = float(np.linalg.norm(np.linalg.inv(phonon.primitive.cell) @ np.array(q))) threshold = float(getattr(dynmat, "Q_DIRECTION_TOLERANCE", 1e-5)) if q_norm < threshold: notes.append( f"--nac: |q| = {q_norm:.1e} 1/A (2 pi omitted) is below phonopy's " f"q-direction threshold {threshold:g} 1/A, so no non-analytical term is " "added at this q; the values are the analytic ones" ) if not is_gamma: to_supercell = phonon.supercell.cell @ np.linalg.inv(phonon.primitive.cell) q_super = to_supercell @ np.array(q) if not np.allclose(q_super, np.rint(q_super), atol=_COMMENSURATE_TOL): where = f"{q_label} = {_q_short(q)}" if q_label else _q_short(q) notes.append( f"q = {where} is not commensurate with the {_supercell_text(phonon)} " "supercell of the force calculation (--dim): the dynamical matrix at this " "q is Fourier-interpolated from the supercell force constants" ) # the three rigid translations: uniform in the patterns u, sqrt(m_i) in the # mass-weighted eigenvectors e (where they are exact eigenvectors of D(0) # under the acoustic sum rule) translations = np.zeros((3 * n, 3)) translations_e = np.zeros((3 * n, 3)) for axis in range(3): translations[axis::3, axis] = 1.0 / np.sqrt(n) translations_e[axis::3, axis] = np.sqrt(masses / masses.sum()) eig_phi = np.linalg.eigvalsh(phi) zero_k = max(_ZERO_K, _ZERO_K_REL * float(np.max(np.abs(eig_phi)))) def translational_weight(vectors) -> float: """Mean squared projection of orthonormal vectors e on the translations.""" overlap = translations_e.T @ vectors return float(np.real(np.vdot(overlap, overlap))) / vectors.shape[1] def mode_values(vector, acoustic): """``(mu, k, k_tr)`` of one mass-weighted vector (k in eV/A^2).""" mu = 1.0 / float(np.real(np.vdot(vector, minv3 * vector))) pattern = vector / sqm3 pattern = pattern / np.linalg.norm(pattern) k = float(np.real(np.vdot(pattern, phi @ pattern))) k_tr = None if is_gamma and not acoustic: rest = pattern - translations @ (translations.T @ pattern) norm = np.linalg.norm(rest) if norm > 1e-8: rest = rest / norm k_tr = float(np.real(np.vdot(rest, phi @ rest))) return mu, k, k_tr # characters of the sets with a single label: the projectors of a split reference: dict[str, tuple] = {} for index, label in enumerate(labels): if label is not None and len(label) == 1 and _irrep_name(label[0]) not in reference: reference[_irrep_name(label[0])] = (characters[index], _irrep_dim(label[0])) result_sets: list[ModeForceConstantSet] = [] block_vectors: dict[str, list] = {} block_modes: dict[str, list] = {} unlabeled = 0 def add_to_block(key, vectors, w_mean): block_vectors.setdefault(key, []).extend(vectors[:, c] for c in range(vectors.shape[1])) block_modes.setdefault(key, []).extend([w_mean] * vectors.shape[1]) def component(label, vectors, bands, frequency, w_mean): acoustic = is_gamma and translational_weight(vectors) > _ACOUSTIC_WEIGHT values = [mode_values(vectors[:, c], acoustic) for c in range(vectors.shape[1])] ks = [value[1] for value in values] spread = max(ks) - min(ks) if spread > _SCHUR_TOL: notes.append( f"k spread {spread:.2e} eV/A^2 within the set of bands " f"{_band_text([b + 1 for b in bands])} ({label})" ) k_tr_values = [value[2] for value in values] k_tr = None if is_gamma and not acoustic and not any(value is None for value in k_tr_values): k_tr = float(np.mean(k_tr_values)) k = float(np.mean(ks)) add_to_block(_irrep_name(label), vectors, w_mean) return ModeForceConstantSet( band_indices=[int(b) for b in bands], irrep_labels=[label], frequency=frequency, effective_mass=float(np.mean([value[0] for value in values])), force_constant=k, force_constant_per_fu=k / z_fu, force_constant_translations_removed=k_tr, acoustic=acoustic, n_vectors=int(vectors.shape[1]), ) def projector_of(name): chi, dim_x = reference[name] return np.tensordot(chi.conj(), ground, axes=(0, 0)) * dim_x / n_sym for index, (label, bands) in enumerate(zip(labels, band_sets)): bands = [int(b) for b in bands] vectors = evecs[:, bands] w_mean = float(np.mean(w[bands])) frequency = float(np.mean(freqs[bands])) if label is None: unlabeled += 1 generic = f"irrep_{unlabeled}({len(bands)})" notes.append( f"bands {_band_text([b + 1 for b in bands])} carry no ISO-IR label; " f"reported as {generic}" ) result_sets.append(component(generic, vectors, bands, frequency, w_mean)) continue if len(label) == 1: result_sets.append(component(label[0], vectors, bands, frequency, w_mean)) continue # an accidental degeneracy: split by the character projectors; a label # without a reference set gets the complement when it is the only one names = [_irrep_name(item) for item in label] unknown = [name_x for name_x in names if name_x not in reference] parts = [] if len(set(names)) == len(names) and len(unknown) <= 1: known_sum = np.zeros_like(vectors) for item, name_x in zip(label, names): if name_x in reference: projected = projector_of(name_x) @ vectors known_sum = known_sum + projected parts.append((item, _orthonormal_columns(projected, tol=1e-3))) else: parts.append((item, None)) parts = [ (item, _orthonormal_columns(vectors - known_sum, tol=1e-3) if cols is None else cols) for item, cols in parts ] if sum(cols.shape[1] for _, cols in parts) != len(bands) or any( cols.shape[1] == 0 or cols.shape[1] % _irrep_dim(item) for item, cols in parts ): parts = [] if not parts: combined = " + ".join(names) if len(set(names)) < len(names): why = "it holds one irrep more than once" else: why = (f"no set at this q carries {' or '.join(unknown)} alone, so the " "character projector cannot separate them") notes.append( f"bands {_band_text([b + 1 for b in bands])} ({', '.join(label)}) are not " f"split: {why}; their k and mu depend on the basis and are not given, and the " f"{combined} block holds them" ) add_to_block(combined, vectors, w_mean) result_sets.append( ModeForceConstantSet( band_indices=bands, irrep_labels=list(label), frequency=frequency, effective_mass=None, force_constant=None, force_constant_per_fu=None, acoustic=is_gamma and translational_weight(vectors) > _ACOUSTIC_WEIGHT, n_vectors=len(bands), ) ) continue comps = [component(item, part, bands, frequency, w_mean) for item, part in parts] result_sets.append( ModeForceConstantSet( band_indices=bands, irrep_labels=list(label), frequency=frequency, effective_mass=None, force_constant=None, force_constant_per_fu=None, acoustic=all(item.acoustic for item in comps), n_vectors=len(bands), components=comps, ) ) blocks: list[IrrepHessianBlock] = [] for key, vectors in block_vectors.items(): patterns = np.array(vectors).T / sqm3[:, None] basis, _ = np.linalg.qr(patterns) hessian = basis.conj().T @ phi @ basis kappa = np.sort(np.linalg.eigvalsh(0.5 * (hessian + hessian.conj().T))) block = IrrepHessianBlock( irrep=key, dim=int(basis.shape[1]), eigenvalues=[float(v) for v in kappa], trace=float(np.sum(kappa)), ) # Sylvester: the signs of kappa are those of the mode k (= mu w) mode_k = np.array([ w_value / float(np.real(np.vdot(v, minv3 * v))) for v, w_value in zip(vectors, block_modes[key]) ]) inertia_modes = (int(np.sum(mode_k < -zero_k)), int(np.sum(np.abs(mode_k) <= zero_k))) inertia_kappa = (int(np.sum(kappa < -zero_k)), int(np.sum(np.abs(kappa) <= zero_k))) if inertia_modes != inertia_kappa: notes.append( f"{key}: negative/zero eigenvalues {inertia_kappa[0]}/{inertia_kappa[1]} but " f"imaginary/zero modes {inertia_modes[0]}/{inertia_modes[1]} (Sylvester)" ) if is_gamma: # the translations inside the block (singular values of basis+ T near 1; # exactly 1 under the acoustic sum rule, as T lies in the vector-irrep # subspaces), then the rest of the block orthogonal to all of them n_tr = int(np.sum(np.linalg.svd(basis.conj().T @ translations, compute_uv=False) > np.sqrt(0.5))) if n_tr: left, _, _ = np.linalg.svd( basis - translations @ (translations.T @ basis), full_matrices=False ) reduced = left[:, : basis.shape[1] - n_tr] hessian_r = reduced.conj().T @ phi @ reduced kappa_r = np.sort( np.linalg.eigvalsh(0.5 * (hessian_r + hessian_r.conj().T)) ) block.translations_removed = IrrepHessianBlock( irrep=key, dim=int(reduced.shape[1]), eigenvalues=[float(v) for v in kappa_r], trace=float(np.sum(kappa_r)), ) zeros = int(np.sum(np.abs(kappa_r) <= zero_k)) if zeros: notes.append( f"{key}: {zeros} zero eigenvalue(s) left after the translations " "were removed" ) blocks.append(block) total = sum(block.dim for block in blocks) if total != 3 * n: raise RuntimeError( f"internal inconsistency at q = {q}: the irrep blocks span {total} of {3 * n} " "dimensions" ) return ModeForceConstants( q=q, q_label=q_label, band_sets=result_sets, irrep_blocks=blocks, n_atoms=n, formula_units=z_fu, notes=notes, )
def _special_points(phonon, irt_table, prim_mat) -> tuple[list[str], list[list[float]]]: """The special q points of ``crystod-phonon --irreps``, Gamma first.""" from .phonon_irreps import _is_gamma_point, _special_points_in_label_frame names, points = _special_points_in_label_frame(phonon, irt_table, prim_mat) order = sorted(range(len(names)), key=lambda i: 0 if _is_gamma_point(points[i]) else 1) return [names[i] for i in order], [[float(v) for v in points[i]] for i in order]
[docs] def survey_mode_resolved_fc( phonon, *, degeneracy_tolerance: float = 1e-3 ) -> list[ModeForceConstants]: """Mode- and irrep-resolved force constants at every special q point. The points are those ``crystod-phonon --irreps`` surveys (the ISO-IR special points, named in the frame of the labels), Gamma first. Args: phonon: A ``phonopy.Phonopy`` object with force constants, built with ``primitive_matrix="auto"``. degeneracy_tolerance: Frequency tolerance (THz) of the degenerate sets (default 1e-3). Returns: One :class:`ModeForceConstants` per special point. """ _, irt_table, prim_mat = _label_context(phonon) names, points = _special_points(phonon, irt_table, prim_mat) return [ mode_resolved_force_constants( phonon, q, irt_table=irt_table, prim_mat=prim_mat, degeneracy_tolerance=degeneracy_tolerance, q_label=name, ) for name, q in zip(names, points) ]
def _num(value: float, decimals: int) -> str: # + 0.0 turns a rounded -0.0 into 0.0 return f"{round(float(value), decimals) + 0.0:.{decimals}f}" def _num_list(values, decimals: int = 6) -> str: return "[" + ", ".join(_num(value, decimals) for value in values) + "]" def _band_text(bands: list[int]) -> str: """``"4-6"`` for consecutive 1-based bands, ``"5"`` for one.""" if len(bands) == 1: return str(bands[0]) if bands == list(range(bands[0], bands[-1] + 1)): return f"{bands[0]}-{bands[-1]}" return ",".join(str(b) for b in bands) def _write_values(fp, item: ModeForceConstantSet, indent: str) -> None: # a set that cannot be split has no values (they would depend on the basis) if item.force_constant is not None: fp.write(f"{indent}effective_mass: {_num(item.effective_mass, 6)}\n") fp.write(f"{indent}force_constant: {_num(item.force_constant, 6)}\n") fp.write(f"{indent}force_constant_per_fu: {_num(item.force_constant_per_fu, 6)}\n") if item.force_constant_translations_removed is not None: fp.write( f"{indent}force_constant_translations_removed: " f"{_num(item.force_constant_translations_removed, 6)}\n" ) if item.acoustic: fp.write(f"{indent}acoustic: true\n")
[docs] def write_mode_resolved_fc_yaml( results: list[ModeForceConstants], path: str = DEFAULT_OUTPUT, *, space_group: str, nac: bool, formula_units: int, special_points: list[tuple[str, list[float]]] | None = None, notes: list[str] | None = None, ) -> None: """Write ``mode-resolved-fc.yaml``. Args: results: The q points to write (:func:`survey_mode_resolved_fc` or :func:`mode_resolved_force_constants`). path: File path (default ``mode-resolved-fc.yaml``). space_group: Hermann-Mauguin symbol for the header. nac: Whether the NAC correction was applied. formula_units: Formula units Z of the primitive cell. special_points: ``[(label, q), ...]`` of the ``special_points`` list (default: the q points of ``results``). notes: Remarks on the whole run (the force-constant consistency NOTE), written as a top-level ``notes`` list; none by default. """ from .phonon_irreps import _yaml_flow_texts, _yaml_qpoint, _yaml_text if special_points is None: special_points = [(r.q_label or "", r.q) for r in results] with open(path, "w", encoding="utf-8") as fp: fp.write(f"space_group: {_yaml_text(space_group)}\n") fp.write(f"nac: {'true' if nac else 'false'}\n") fp.write(f"formula_units_per_primitive_cell: {formula_units}\n") if notes: fp.write("notes:\n") for note in notes: fp.write(f"- {_yaml_text(note)}\n") fp.write("units:\n") fp.write( " force_constant: eV/A^2 per primitive cell, pattern normalized to |u| = 1 A " "over the primitive cell\n" ) fp.write( " force_constant_per_fu: eV/A^2 per formula unit (force_constant / " "formula_units_per_primitive_cell)\n" ) fp.write(" effective_mass: amu\n") fp.write(" frequency: THz\n") fp.write("special_points:\n" if special_points else "special_points: []\n") for name, q in special_points: fp.write(f"- q_label: {_yaml_text(name)}\n") fp.write(f" q_position: {_yaml_qpoint(q)}\n") fp.write("\n") fp.write("mode_resolved_fc:\n" if results else "mode_resolved_fc: []\n") for result in results: fp.write(f"- q_label: {_yaml_text(result.q_label or '')}\n") fp.write(f" q_position: {_yaml_qpoint(result.q)}\n") fp.write(" band_sets:\n") for item in result.band_sets: bands = ", ".join(str(b + 1) for b in item.band_indices) fp.write(f" - band_indices: [{bands}]\n") fp.write(f" irrep_label: {_yaml_flow_texts(item.irrep_labels, quote=True)}\n") fp.write(" frequency: %14.10f\n" % item.frequency) if not item.components: _write_values(fp, item, " ") continue if item.acoustic: fp.write(" acoustic: true\n") fp.write(" components: # accidental degeneracy split by character projection\n") for comp in item.components: fp.write(f" - irrep: {_yaml_text(comp.irrep_labels[0])}\n") fp.write(f" n_vectors: {comp.n_vectors}\n") _write_values(fp, comp, " ") fp.write(" irrep_hessian:\n") for block in result.irrep_blocks: fp.write(f" - irrep: {_yaml_text(block.irrep)}\n") fp.write(f" dim: {block.dim}\n") fp.write(f" eigenvalues: {_num_list(block.eigenvalues)}\n") fp.write(f" trace: {_num(block.trace, 6)}\n") reduced = block.translations_removed if reduced is not None: fp.write(" translations_removed:\n") fp.write(f" dim: {reduced.dim}\n") fp.write(f" eigenvalues: {_num_list(reduced.eigenvalues)}\n") fp.write(f" trace: {_num(reduced.trace, 6)}\n") if result.notes: fp.write(" notes:\n") for note in result.notes: fp.write(f" - {_yaml_text(note)}\n") fp.write("\n")
[docs] def read_mode_resolved_fc(path) -> dict: """Read a ``mode-resolved-fc.yaml`` file. The file is the one ``crystod-phonon --mode-resolved-fc`` writes; this is ``yaml.safe_load`` of it, checked for the ``mode_resolved_fc`` list. Args: path: Path of the file. Returns: dict: The file as a plain dictionary: ``space_group`` (str), ``nac`` (bool), ``formula_units_per_primitive_cell`` (int), ``notes`` (list of str, only when the force constants fail the consistency check of :func:`crystod.phonon_irreps.check_force_constants_consistency`), ``units`` (dict of str), ``special_points`` (list of ``{"q_label", "q_position"}``) and ``mode_resolved_fc``, one entry per q point with ``q_label``, ``q_position``, ``band_sets`` (``band_indices`` 1-based, ``irrep_label``, ``frequency``, ``effective_mass``, ``force_constant``, ``force_constant_per_fu``, at Gamma ``force_constant_translations_removed`` or ``acoustic``; a split set has ``components`` with ``irrep`` and ``n_vectors`` instead of the values, a set that cannot be split has no values at all), ``irrep_hessian`` (``irrep``, ``dim``, ``eigenvalues``, ``trace``, at Gamma possibly ``translations_removed``) and, when there are remarks, ``notes`` (list of str, the NOTE lines of the terminal). Raises: FileNotFoundError: The file does not exist. ValueError: The file is not YAML or has no ``mode_resolved_fc`` list whose entries hold ``band_sets`` and ``irrep_hessian`` lists. """ import yaml with open(path, encoding="utf-8") as handle: text = handle.read() try: data = yaml.safe_load(text) except yaml.YAMLError as exc: raise ValueError(f"{path} is not a YAML file ({str(exc).splitlines()[0]})") from None if not isinstance(data, dict) or not isinstance(data.get("mode_resolved_fc"), list): raise ValueError(f"{path} has no 'mode_resolved_fc' list; it is not a mode-resolved-fc.yaml") for point in data["mode_resolved_fc"]: if not ( isinstance(point, dict) and isinstance(point.get("band_sets"), list) and isinstance(point.get("irrep_hessian"), list) ): raise ValueError( f"{path}: a 'mode_resolved_fc' entry lacks the 'band_sets' or " "'irrep_hessian' list" ) return data
def _q_text(q) -> str: return "[" + ", ".join(_num(value, 4) for value in q) + "]" def _q_short(q) -> str: """``[0.25, 0.25, 0.25]``, ``[1e-06, 0, 0]``: q with up to six significant digits.""" return "[" + ", ".join(f"{float(value) + 0.0:.6g}" for value in q) + "]" def _wrap_values(prefix: str, values, width: int = 100, decimals: int = 6) -> list[str]: """``prefix`` followed by the values, wrapped under the first value.""" texts = [_num(value, decimals) for value in values] if not texts: return [prefix.rstrip()] lines, current = [], prefix + texts[0] for text in texts[1:]: if len(current) + 1 + len(text) > width: lines.append(current) current = " " * len(prefix) + text else: current += " " + text lines.append(current) return lines
[docs] def format_mode_resolved_fc(results: list[ModeForceConstants]) -> list[str]: """The terminal blocks of the q points: per q a ``* Mode-resolved force constants at Q *`` table and an ``* Irrep-resolved Hessian at Q *`` table, NOTE lines after them. Args: results: The q points, as :func:`survey_mode_resolved_fc` returns. Returns: The lines (blank lines and the ``* Title *`` lines included). """ lines: list[str] = [] for result in results: name = result.q_label or _q_text(result.q) is_gamma = bool(np.allclose(result.q, np.rint(result.q), atol=1e-8)) rows = [] for item in result.band_sets: band = _band_text([b + 1 for b in item.band_indices]) parts = item.components or [item] for index, part in enumerate(parts): label = part.irrep_labels[0] if item.components else ", ".join(item.irrep_labels) rows.append((band if index == 0 else "", label, item.frequency if index == 0 else None, part)) width_band = max([4] + [len(row[0]) for row in rows]) width_label = max([5] + [len(row[1]) for row in rows]) lines.append("") lines.append(f"* Mode-resolved force constants at {name} *") lines.append(f" q = {_q_text(result.q)}") header = ( f" {'band':>{width_band}s} {'irrep':<{width_label}s} {'freq (THz)':>10s} " f"{'mu (amu)':>9s} {'k (eV/A^2)':>12s} {'k/fu':>11s}" ) if is_gamma: header += f" {'k(-transl.)':>11s}" lines.append(header) for band, label, frequency, part in rows: freq_text = f"{_num(frequency, 4):>10s}" if frequency is not None else " " * 10 if part.force_constant is None: # a set that cannot be split values = f"{'-':>9s} {'-':>12s} {'-':>11s}" else: values = ( f"{part.effective_mass:9.4f} {_num(part.force_constant, 6):>12s} " f"{_num(part.force_constant_per_fu, 6):>11s}" ) line = f" {band:>{width_band}s} {label:<{width_label}s} {freq_text} {values}" if is_gamma: if part.force_constant_translations_removed is not None: line += f" {_num(part.force_constant_translations_removed, 6):>11s}" else: line += f" {'acoustic' if part.acoustic else '-':>11s}" lines.append(line) lines.append("") lines.append(f"* Irrep-resolved Hessian at {name} *") width_irrep = max([10] + [len(block.irrep) for block in result.irrep_blocks]) lines.append( f" {'irrep':<{width_irrep}s} {'dim':>3s} {'trace':>12s} eigenvalues (eV/A^2)" ) for block in result.irrep_blocks: prefix = f" {block.irrep:<{width_irrep}s} {block.dim:3d} {_num(block.trace, 6):>12s} " lines.extend(_wrap_values(prefix, block.eigenvalues)) reduced = block.translations_removed if reduced is not None: prefix = ( f" {' -transl.':<{width_irrep}s} {reduced.dim:3d} " f"{_num(reduced.trace, 6):>12s} " ) lines.extend(_wrap_values(prefix, reduced.eigenvalues)) for note in result.notes: lines.extend( textwrap.wrap(note, width=100, initial_indent=" NOTE: ", subsequent_indent=" ", break_on_hyphens=False) ) return lines
desc = """\ Mode-resolved force constants k = u^+ Phi(q) u^ = mu w (eV/A^2 per primitive cell, |u^| = 1 A over the primitive cell) of every degenerate set, and the force-constant matrix restricted to every irrep subspace, at the special q points of the space group (or one --qpoint). Reads POSCAR + FORCE_SETS (or FORCE_CONSTANTS with --readfc) from the working directory. # Command Example: python3 -m crystod.phonon_mode_fc --dim "4 4 4" --poscar 221_PPOSCAR_SrTiO3 """ def build_parser() -> ArgumentParser: parser = ArgumentParser(description=desc, formatter_class=RawTextHelpFormatter) parser.add_argument( "--dim", required=True, type=str, help="Supercell dimension of the force calculation." ) parser.add_argument("--poscar", type=str, default="POSCAR", help="POSCAR path.") parser.add_argument( "--readfc", action="store_true", help="Read FORCE_CONSTANTS instead of FORCE_SETS." ) parser.add_argument( "--nac", dest="nac", action="store_true", help="Apply the non-analytical term correction with ./BORN (without it\n" "a BORN file is not read).", ) parser.add_argument( "--tolerance", "-tol", dest="tol", type=float, default=1e-3, help="Degeneracy tolerance (THz) of the irrep labels (default 1e-3).", ) parser.add_argument( "--qpoint", nargs="+", default=None, help="Compute one q point only: a special-point label such as R or three\n" "primitive reciprocal coordinates (default: every special point).", ) parser.add_argument( "--output", "-o", default=None, help=f"Path of the YAML file (default {DEFAULT_OUTPUT}).", ) return parser def _resolve_requested(phonon, dataset, names, points, tokens) -> tuple[str, list[float]]: """``--qpoint`` tokens to ``(label, q)``, as ``--vector`` resolves them.""" from .phonon_vector import resolve_qpoint from .runtime_compat import get_symmetry_dataset rotations = get_symmetry_dataset(phonon.primitive_symmetry)["rotations"] primitive, unitcell = phonon.primitive, phonon.unitcell isoir_context = ( dataset["number"], (primitive.cell, primitive.scaled_positions, primitive.numbers), phonon.primitive_symmetry.tolerance, (unitcell.cell, unitcell.scaled_positions, unitcell.numbers), ) try: name, q = resolve_qpoint( [str(token) for token in tokens], names, points, rotations=rotations, isoir_context=isoir_context, ) except ValueError as exc: raise SystemExit(f"ERROR: {exc}") from None return name, [float(value) for value in q] def _force_file_atoms(path: str) -> int | None: """Supercell atoms named in the first line of FORCE_SETS or FORCE_CONSTANTS. FORCE_SETS (type 1) starts with the number of atoms, FORCE_CONSTANTS with ``n_rows n_atoms`` (or ``n_atoms``); ``None`` when the first line is not of that form (a type-2 FORCE_SETS, an hdf5 file), and phonopy is left to judge. """ try: with open(path, encoding="utf-8", errors="replace") as handle: tokens = handle.readline().split() except OSError: return None if not 1 <= len(tokens) <= 2 or not all(token.isdigit() for token in tokens): return None return int(tokens[-1]) def main(argv: list[str] | None = None) -> None: from phonopy import load from .phonon_irreps import ( check_force_constants_consistency, check_nac_loaded, format_note_lines, nac_load_options, ) from .phonon_vector import reduced_formula from .vasp_io import read_poscar_cell args = build_parser().parse_args(argv) output = args.output or DEFAULT_OUTPUT supercell_matrix = [float(value) for value in args.dim.split()] if args.readfc: force_sets, force_constants, force_data = None, "./FORCE_CONSTANTS", "FORCE_CONSTANTS" else: force_sets, force_constants, force_data = "./FORCE_SETS", None, "FORCE_SETS" # the cheap refusals first, before the force data are read directory = os.path.dirname(os.path.abspath(output)) if not os.path.isdir(directory): raise SystemExit(f"ERROR: cannot write {output}: the directory {directory} does not exist.") if not os.access(directory, os.W_OK): raise SystemExit(f"ERROR: cannot write {output}: the directory {directory} is not writable.") if not os.path.isfile(args.poscar): raise SystemExit(f"ERROR: the cell file '{args.poscar}' was not found (-c).") unitcell = read_poscar_cell(args.poscar) expected = len(unitcell.numbers) * int(round(abs(np.prod(supercell_matrix)))) found = _force_file_atoms(force_constants or force_sets) if found is not None and found != expected: raise SystemExit( f"ERROR: --dim {args.dim} makes a supercell of {expected} atoms from " f"{len(unitcell.numbers)} in '{args.poscar}', but {force_data} holds {found}; give " "the --dim of the force calculation." ) with warnings.catch_warnings(): # a conventional or supercell POSCAR: phonopy says that "auto" found a # smaller primitive cell, which is what this mode asks for warnings.filterwarnings("ignore", message="primitive_matrix defaulted to 'auto'") try: phonon = load( supercell_matrix=supercell_matrix, primitive_matrix="auto", unitcell=unitcell, force_sets_filename=force_sets, force_constants_filename=force_constants, **nac_load_options(args.nac), ) except (IndexError, ValueError, RuntimeError) as exc: raise SystemExit( f"ERROR: phonopy could not read {force_data} with --dim {args.dim} and " f"'{args.poscar}' ({type(exc).__name__}: {exc})." ) from None nac_note = check_nac_loaded(phonon, args.nac, "BORN") fc_note = check_force_constants_consistency( phonon, force_sets_filename=force_sets, force_constants_filename=force_constants, unitcell=unitcell, ) dataset, irt_table, prim_mat = _label_context(phonon) names, points = _special_points(phonon, irt_table, prim_mat) if args.qpoint: selected = [_resolve_requested(phonon, dataset, names, points, args.qpoint)] else: selected = list(zip(names, points)) results = [] for name, q in selected: try: results.append( mode_resolved_force_constants( phonon, q, irt_table=irt_table, prim_mat=prim_mat, degeneracy_tolerance=args.tol, q_label=name, ) ) except ValueError as exc: raise SystemExit(f"ERROR: q = {name} {q}: {exc}") from None z_fu = formula_units_of(phonon) write_mode_resolved_fc_yaml( results, output, space_group=dataset["international"], nac=args.nac, formula_units=z_fu, special_points=list(zip(names, points)), notes=[fc_note] if fc_note else None, ) dims = " x ".join(str(int(value)) for value in supercell_matrix) print("\n* Structure *") print(f" Space group: {dataset['international']} (#{dataset['number']})") print(f" Formula: {reduced_formula(list(phonon.primitive.symbols))}") print(f" Primitive cell: {len(phonon.primitive)} atoms, Z = {z_fu} formula unit(s)") print(f" Supercell: {dims} ({force_data})") if nac_note: print(f" {nac_note}") if fc_note: print("\n".join(format_note_lines(fc_note))) print("\n* Conventions *") print(" k = u^+ Phi(q) u^ = mu w in eV/A^2 per primitive cell, the pattern u^ normalized") print(" to |u^| = 1 A over the primitive cell; k/fu = k / Z; mu = 1 / sum_i |e_i|^2/m_i (amu)") print(" k(-transl.) (GM only): k of u^ with its uniform translation removed, renormalized") print(" Irrep blocks: eigenvalues of Phi(q) on the irrep subspace (eV/A^2); k < 0: unstable") print(" 1 eV/A^2 = 1000 meV/A^2, the unit many stability analyses quote per formula unit") for line in format_mode_resolved_fc(results): print(line) print("\n* Output files *") print(f" Mode-resolved force constants written to: {output}") if __name__ == "__main__": main()