crystod.phonon

Contents

crystod.phonon#

Phonon analyses of CrystOD: the crystod-phonon command as a library.

This domain covers what crystod-phonon does from phonopy force data (a unit cell with FORCE_SETS or FORCE_CONSTANTS, or a phonopy_params.yaml): labeling phonon modes with ISO-IR space-group irreps, following imaginary modes to the isotropy subgroups they can condense into, exporting eigenvectors for VESTA, resolving the longitudinal/transverse character of bands, freezing modes into modulated structures, and showing every mode of the k path in an interactive viewer. The symmetry-only vibration bases need no force data at all. Where the command takes files, the functions take a live phonopy.Phonopy object; build it with primitive_matrix="auto", so that a zone-boundary instability appears at its own q point instead of being folded onto the supercell Gamma point.

Irrep labeling (crystod-phonon --irreps):

  • get_irrep_labels() – irrep labels, band indices and frequencies of the modes at a tabulated q point, from phonopy characters and the ISO-IR tables;

  • get_irt_special_points() – the special q points of the ISO-IR tables in the primitive basis;

  • find_star_representative() – map any arm of a star onto its tabulated arm;

  • read_phonon_irreps() – read the phonon_irreps.yaml (or phonon_irreps_all.yaml) the command writes into a plain dictionary.

Spectroscopic activity at Gamma (--irreps and --vibration --qpoint GM):

Mode labeling and isotropy subgroups (crystod-phonon --subgroup; the structure-search API):

Eigenvectors and VESTA export (crystod-phonon --vector):

Longitudinal/transverse character (crystod-phonon --lt):

  • get_longitudinal_ratio() – the longitudinal character of every (q point, band) pair: 1 = longitudinal, 0 = transverse.

Modulated structures (crystod-phonon --modulation):

  • SymmetryAdaptedModulation – the symmetry-adapted modes at one q point and the structures obtained by freezing them in (harmonic eigen-displacements on phonopy’s primitive cell as it is; the amplitude is the displacement norm of one primitive cell where 2q is a reciprocal lattice vector);

  • ModulationTerm – the modes and amplitudes of one q point in a combined modulation.

Symmetry-only vibration bases (crystod-phonon --vibration):

Band unfolding (crystod-phonon --unfold):

Phonon mode viewer (crystod-phonon --visualize):

Mode-resolved force constants (crystod-phonon --mode-resolved-fc):

Displacement patterns of isotropy subgroups (crystod-phonon -c POSCAR --element EL --irrep IR [IR2 ...], no force data):

  • displacement_irrep_arrangements() – for every row of the table of crystod-group --parent SG --irrep ... (several irreps: the coupled rows) the symmetry-adapted displacement pattern of the atoms of the chosen elements that lowers the symmetry to the row’s subgroup, with the space group spglib finds on the displaced structure, as DisplacementIrrepAnalysis of DisplacementArrangement rows (symmetry-adapted patterns, not eigenvectors of a dynamical matrix).

  • displacement_irrep_survey() – the irreps of the displacement (polar-vector) representation of the atoms of the elements at every special k point (crystod-phonon -c POSCAR --element EL, the survey), as DisplacementSurvey.

Attributes resolve lazily (PEP 562): importing this module is instant and pulls in phonopy/spgrep only on first use. The implementation lives in crystod.phonon_irreps, crystod.phonon_activity, crystod.phonon_subgroups, crystod.phonon_vector, crystod.phonon_lt, crystod.modulation, crystod.vibration_modes, crystod.phonon_unfold, crystod.phonon_visualize, crystod.phonon_mode_fc and crystod.displacement_arrangements, whose import paths keep working. Bad input raises ValueError from the functions of this namespace, where the implementation modules exit the process (SystemExit) as a command line wants it.

Example:

import phonopy
from crystod import phonon
from crystod.examples import example_path

ph = phonopy.load(
    unitcell_filename=example_path("221_PPOSCAR_SrTiO3"),
    force_sets_filename=example_path("FORCE_SETS_SrTiO3"),
    supercell_matrix=[4, 4, 4], primitive_matrix="auto")

modes = phonon.label_phonon_modes(ph, [0.5, 0.5, 0.5])   # R point
results = phonon.imaginary_mode_subgroups(ph, [0.5, 0.5, 0.5])
for result in results:
    print(result.mode)                                    # R5- soft mode
    for sub in result.subgroups:
        print("   ", sub.label, "->", sub.symbol)         # I4/mcm, R-3c, ...
class crystod.phonon.Activity(n_ir, n_raman, dimension=0, acoustic=False, labels=(), band_indices=(), frequency=None, parts=())[source]#

Bases: object

Spectroscopic activity of one irrep block at Gamma.

One record per degenerate phonon set (force-constant route) or per mode space (structure-only route). classify_gamma_irreps() fills the multiplicities; the caller adds the acoustic flag and the identification (labels, bands, frequency) with dataclasses.replace().

Variables:
  • n_ir (int) – Multiplicity of the block in the vector representation (> 0: IR active); -1 when the characters of the block are not those of a representation (a degenerate set split by too tight a tolerance), so that nothing can be said.

  • n_raman (int) – Multiplicity in the symmetric square of the vector representation (> 0: Raman active); -1 as for n_ir.

  • dimension (int) – Dimension of the block (its character at the identity).

  • acoustic (bool) – True when every band of the block is a rigid translation of the crystal.

  • labels (tuple[str, ...]) – ISO-IR label(s) of the block without the dimension suffix ("GM4-"); more than one when the set holds several irreps (the acoustic set of a polar crystal, where the three translations span two irreps at 0 THz by translation invariance, or an accidental degeneracy).

  • band_indices (tuple[int, ...]) – 1-based band indices of the block (force-constant route only).

  • frequency (float | None) – Frequency in THz of the first band (force-constant route only).

  • parts (tuple[tuple[str, int, str], ...]) – The block split per irrep (force-constant route): (label, copies, kind) triples, kind one of "IR", "Raman", "IR+Raman", "silent" or "acoustic". The acoustic bands of a set are the copies of the irreps of the vector representation they span; the rest is optical. Empty when the set could not be decomposed.

Example

>>> from crystod.phonon_activity import Activity
>>> Activity(n_ir=1, n_raman=0, dimension=3).activity
('IR',)
>>> Activity(n_ir=1, n_raman=0, dimension=3, acoustic=True).activity
('acoustic',)
acoustic: bool = False#
property activity: tuple[str, ...]#

('IR',), ('Raman',), ('IR', 'Raman'), ('silent',), ('acoustic',), or ('unknown',) for a block that is not a representation; a block holding several irreps lists every kind that occurs in it (('IR', 'silent', 'acoustic')).

band_indices: tuple[int, ...] = ()#
dimension: int = 0#
frequency: float | None = None#
property ir_active: bool#

True for an optical block that occurs in the vector representation.

labels: tuple[str, ...] = ()#
n_ir: int#
n_raman: int#
parts: tuple[tuple[str, int, str], ...] = ()#
property raman_active: bool#

True for an optical block that occurs in the symmetric square.

class crystod.phonon.DielectricResponse(eps_inf, eps_static, sets, volume, born_sum, lst=None, imaginary_bands=())[source]#

Bases: object

Static dielectric response of the Gamma phonons from Born charges.

Variables:
  • eps_inf (numpy.ndarray) – Electronic dielectric tensor (BORN), 3x3.

  • eps_static (numpy.ndarray) – eps_inf + sum of the set contributions, 3x3.

  • sets (tuple) – One DielectricSet per degenerate set, in band order.

  • volume (float) – Primitive-cell volume in Angstrom^3.

  • born_sum (numpy.ndarray) – sum_kappa Z*_kappa (zero by the acoustic sum rule), 3x3.

  • lst (tuple | None) – (direction, product, ratio) of the Lyddane-Sachs-Teller check, or None: product is prod (nu_LO / nu_TO)^2 over the optical bands with the non-analytical term for q -> 0 along direction (reduced reciprocal coordinates), ratio is q.eps_0.q / q.eps_inf.q.

  • imaginary_bands (tuple[int, ...]) – 1-based bands of the optical modes with an imaginary frequency and a nonzero mode effective charge: they enter eps_static with a negative sign (nu^2 < 0), so that eps_static is then not the static dielectric tensor of a stable structure.

born_sum: ndarray#
property born_sum_deviation: float#

Largest absolute element of sum_kappa Z*_kappa.

eps_inf: ndarray#
eps_static: ndarray#
imaginary_bands: tuple[int, ...] = ()#
lst: tuple | None = None#
sets: tuple#
volume: float#
class crystod.phonon.DielectricSet(activity, charges, oscillator_strength, contribution)[source]#

Bases: object

The dielectric quantities of one degenerate set at Gamma.

Variables:
  • activity (crystod.phonon_activity.Activity) – The Activity of the set.

  • charges (numpy.ndarray) – Mode effective charges (e/sqrt(amu)) of its bands, shape (n_bands, 3), from the real eigenvectors of mode_effective_charges().

  • oscillator_strength (numpy.ndarray) – S = sum_m Re(Z~_m Z~_m^*) over the optical bands of the set, 3x3 in e^2/amu (basis independent).

  • contribution (numpy.ndarray) – Delta eps = DIELECTRIC_FACTOR * S / (Omega nu^2), 3x3 (zero for an acoustic set).

activity: Activity#
property charge_norm: float#

sqrt(sum_m |Z~_m|^2) over all bands of the set (independent of the eigenvector basis inside a degenerate subspace).

charges: ndarray#
contribution: ndarray#
oscillator_strength: ndarray#
class crystod.phonon.DisplacementArrangement(number, row, copies, tag, order_parameter, letters=<factory>, coefficients=(), field=None, displacements=None, displaced_positions=None, group_number=None, group_symbol=None, point_group=None, found_size=None, found_index=None, check='', note=None, n_fixing_field=0, n_fixing_order_parameter=0, displacement_text='', polar_axes=None, vesta_name='', poscar_name='', weight_reason=None, reproduce=None, fixing_translations=<factory>)[source]#

Bases: object

The displacement pattern of one table row (one choice of copies).

Variables:
  • number (int) – The row number of the table, from 1.

  • row (crystod.displacement_arrangements.DisplacementRow) – The DisplacementRow.

  • copies (tuple) – One DisplacementCopy per irrep.

  • tag (str) – "" when every irrep has one copy, else the copy numbers ("c1-2").

  • order_parameter (numpy.ndarray) – The order parameter used (the irreps’ parts concatenated).

  • letters (dict) – {letter: value} of the free parameters.

  • coefficients (tuple) – The weight of every irrep’s part.

  • field (numpy.ndarray) – The displacements on the chosen atoms of the diagonal cell, (n_cells, n_sites, 3), Cartesian, largest 1 (not rounded).

  • displacements (numpy.ndarray) – The displacement of every atom of the written cell (Angstrom, Cartesian, largest amplitude), POSCAR order of the written supercell.

  • displaced_positions (numpy.ndarray) – The fractional positions of the displaced structure (written cell).

  • group_symbol (group_number,) – The space group spglib finds on the displaced structure as written (None when not identified).

  • point_group (str | None) – Its point group (spglib’s symbol).

  • found_index (found_size,) – Size and index found on the structure.

  • check (str) – "same", "enantiomorph", "different" or "not identified".

  • note (str | None) – A NOTE for the row, or None.

  • n_fixing_order_parameter (n_fixing_field,) – Elements of G/T_S that fix the displacements and the order parameter (equal by construction).

  • displacement_text (str) – The line on the sizes of the displacements.

  • polar_axes (numpy.ndarray) – An orthonormal basis (rows, Cartesian) of the vectors fixed by the operations of G/T_S that fix the pattern (the directions a polarization may take).

  • poscar_name (vesta_name,) – The file names.

check: str = ''#
property check_text: str#

The check column ("63 Cmcm same").

coefficients: tuple = ()#
copies: tuple#
displaced_positions: ndarray = None#
displacement_text: str = ''#
displacements: ndarray = None#
field: ndarray = None#
fixing_translations: list#
found_index: int | None = None#
found_size: int | None = None#
group_number: int | None = None#
group_symbol: str | None = None#
letters: dict#
n_fixing_field: int = 0#
n_fixing_order_parameter: int = 0#
note: str | None = None#
number: int#
order_parameter: ndarray#
point_group: str | None = None#
polar_axes: ndarray = None#
poscar_name: str = ''#
reproduce: ndarray = None#
row: DisplacementRow#
tag: str#
vesta_name: str = ''#
weight_reason: str | None = None#
class crystod.phonon.DisplacementIrrepAnalysis(formula, elements, space_group, space_group_number, irreps, dimensions, kpoints, decompositions, multiplicities, copies, singles, rows, arrangements, coefficients, amplitude, check_symprec, cell_matrix, supercell_sizes, cell_translations, supercell_lattice, supercell_symbols, supercell_positions, supercell_site_of_atom, supercell_cell_of_atom, site_indices, site_elements, residuals=<factory>, order_parameter_input=None, stratum=None, copy_note=None, unlabelled_kpoints=<factory>, parts=<factory>, conventional_centring=None, conventional_multiples=None, internal_cell_translations=<factory>, conventional_note=None, symbol='', poscar_basename='POSCAR')[source]#

Bases: object

The displacement patterns of given irreps on a crystal (crystod-phonon -c POSCAR --element EL --irrep IR [IR2 ...]).

The attributes parallel crystod.magnetic_arrangements.MagneticIrrepAnalysis (kpoints, decompositions, multiplicities, copies, singles, rows, arrangements, the written cell and the diagonal cell); amplitude is the largest displacement in Angstrom, check_symprec the spglib tolerance of the check, singles maps the label of every irrep of a coupled run to the rows of its own table (as crystod-group --parent prints them).

amplitude: float#
arrangements: list#
cell_matrix: ndarray#
cell_translations: list#
check_symprec: float#
coefficients: tuple#
conventional_centring: str | None = None#
conventional_multiples: ndarray | None = None#
conventional_note: str | None = None#
copies: dict#
copy_note: str | None = None#
decompositions: dict#
dimensions: list#
elements: list#
formula: str#
internal_cell_translations: list#
irreps: list#
kpoints: dict#
multiplicities: dict#
property n_cells: int#

Number of primitive cells of the written cell.

order_parameter_input: list | None = None#
parts: list#
poscar_basename: str = 'POSCAR'#
residuals: dict#
rows: list#
singles: dict#
site_elements: list#
site_indices: list#
space_group: str#
space_group_number: int#
stratum: int | None = None#
supercell_cell_of_atom: list#
supercell_lattice: ndarray#
supercell_positions: ndarray#
supercell_site_of_atom: list#
supercell_sizes: ndarray#
supercell_symbols: list#
symbol: str = ''#
unlabelled_kpoints: list#
class crystod.phonon.DisplacementSurvey(formula, elements, space_group, space_group_number, site_indices, site_elements, positions, kpoints, unlabelled_kpoints=<factory>)[source]#

Bases: object

The irreps of the displacement (polar-vector) representation of the atoms of given elements at every special k point (crystod-phonon -c POSCAR --element EL [EL2 ...], no --irrep or --qpoint).

kpoints lists (name, q, lines) per special point, in the order of the tables: q in the primitive reciprocal basis of the POSCAR, lines the (element, text) decompositions, one per element and, for several elements, ("total", text) (the text of the header of the --irrep/--qpoint forms, complex pairs under their pair label). unlabelled_kpoints names the points whose irreps could not be labelled at the tolerance (irrep_N in the text).

elements: list#
formula: str#
kpoints: list#
positions: ndarray#
property report_name: str#

saad_<formula>_<El>[-<El2>...]_survey.

site_elements: list#
site_indices: list#
space_group: str#
space_group_number: int#
unlabelled_kpoints: list#
class crystod.phonon.DomainAverage(path_index, k_parent, multiplicity, n_arms, frequencies, weights_canonical, weights, n_domains, sum_rule_max_deviation, orbit_spectral_max_deviation, n_arms_unfolded)[source]#

Bases: object

The unfolded spectrum averaged over the orientation domains (domain_average()).

Variables:
  • path_index (numpy.ndarray) – (n_rows,) path k of each class row.

  • k_parent (numpy.ndarray) – (n_rows, 3) representative arm (the first arm of the class).

  • multiplicity (numpy.ndarray) – (n_rows,) m, arms in the class.

  • n_arms (numpy.ndarray) – (n_k,) n, arms of the star of each path k.

  • frequencies (numpy.ndarray) – (n_rows, n_band).

  • weights_canonical (numpy.ndarray) – (n_rows, n_band) of the representative.

  • weights (numpy.ndarray) – (n_rows, n_band) weights_canonical * m / n.

  • n_domains (int) – |parent point group| / |child point group|.

  • sum_rule_max_deviation (float) – max over the path k of |sum of its rows - 3 n_parent|.

  • orbit_spectral_max_deviation (tuple) – (THz, weight), largest difference between the arms of one class (all arms are unfolded).

  • n_arms_unfolded (int) – Arms unfolded in all.

frequencies: ndarray#
k_parent: ndarray#
multiplicity: ndarray#
n_arms: ndarray#
n_arms_unfolded: int#
n_domains: int#
orbit_spectral_max_deviation: tuple#
path_index: ndarray#
sum_rule_max_deviation: float#
weights: ndarray#
weights_canonical: ndarray#
class crystod.phonon.GammaOrigin(k_fold, k_names, on_path, frequencies, groups, weights, group_labels, group_fractions, group_members, child_irreps, child_short, origin, soft_levels, checks, notes=<factory>)[source]#

Bases: object

The child modes at K = 0 unfolded onto the parent k folding onto it (gamma_origin()).

Variables:
  • k_fold (numpy.ndarray) – (N, 3) = mapping.folding_kpoints; k_names their names.

  • on_path (numpy.ndarray) – (N,) bool, the folding k is a point of the band path.

  • frequencies (numpy.ndarray) – (n_band,) child frequencies at K = 0 (THz).

  • groups (list) – Degenerate groups (index arrays) of the child Gamma modes.

  • weights (numpy.ndarray) – (N, n_band) P_J(k) at each folding k, canonical at each k (the modes of a degenerate level rotated as for weights_canonical of the path, independently at each k): per level, sum_k P_g(k) is the number of modes of the level; per mode, only the weights at one k are basis independent.

  • group_members (group_labels, group_fractions,) – [N][n_groups] label (U1 rule), its share and its irrep names at each folding k; None without irreps.

  • child_irreps (list) – Per group, '<labels> [<Mulliken>] <activity>' of label_phonon_modes on the child; child_short the Mulliken symbols (or labels) alone.

  • origin (list) – Per group, (k name, label or '', P_g) of the k with the largest P_g.

  • soft_levels (list) – With parent phonons, every parent level below -0.1 THz at a folding k: dicts with k_name, k, unit, frequency, n, contents ([(group index, c_g, child irrep)], c_g >= 0.02, descending) and mean_frequency (content-weighted).

  • checks (dict) – 'sum_over_k' (max of |sum_k P_J(k) - 1| per mode before the rotation and |sum_k P_g(k) - n_g| per level), 'sum_rule_k' (|sum_J P_J(k) - 3 n_parent|).

  • notes (list) – NOTE lines (child labels or Mulliken symbols missing).

checks: dict#
child_irreps: list#
child_short: list#
frequencies: ndarray#
group_fractions: list | None#
group_labels: list | None#
group_members: list | None#
groups: list#
k_fold: ndarray#
k_names: list#
notes: list#
on_path: ndarray#
origin: list#
soft_levels: list#
weights: ndarray#
class crystod.phonon.ImaginaryModeResult(mode, space_group, space_group_number, subgroups, errors=<factory>)[source]#

Bases: object

Isotropy subgroups reachable from one imaginary phonon level.

One block of the crystod-phonon --subgroup report, as returned by imaginary_mode_subgroups() and scan_imaginary_modes().

Variables:
  • mode (crystod.phonon_subgroups.PhononMode) – The imaginary level, a PhononMode.

  • space_group (str) – International short symbol of the parent space group.

  • space_group_number (int) – Its number.

  • subgroups (tuple[crystod.phonon_subgroups.IsotropySubgroup, ...]) – The IsotropySubgroup records of every irrep label of the level, in table order; empty when no label has tabulated subgroups.

  • errors (dict) – Maps an irrep label to the reason its subgroup enumeration failed (e.g. the label of a symmetry line or plane, which has no isotropy subgroups in the tables; "?" when the level carries no label at all). Empty on success.

errors: dict#
mode: PhononMode#
space_group: str#
space_group_number: int#
subgroups: tuple[IsotropySubgroup, ...]#
class crystod.phonon.IrrepHessianBlock(irrep, dim, eigenvalues, trace, translations_removed=None)[source]#

Bases: object

The force-constant matrix restricted to one irrep subspace at q.

Variables:
  • irrep (str) – The irrep label without its dimension suffix ("GM4-"); for a set that cannot be split, its labels joined as "GM3- + GM5-".

  • dim (int) – Dimension of the subspace (multiplicity times irrep dimension).

  • eigenvalues (list[float]) – Eigenvalues of S+ Phi(q) S in eV/A^2, ascending.

  • trace (float) – Their sum in eV/A^2.

  • translations_removed (crystod.phonon_mode_fc.IrrepHessianBlock | None) – At Gamma, for a block that contains uniform translations, the same block with them projected out first; else None.

dim: int#
eigenvalues: list[float]#
irrep: str#
trace: float#
translations_removed: IrrepHessianBlock | None = None#
class crystod.phonon.ModeForceConstantSet(band_indices, irrep_labels, frequency, effective_mass, force_constant, force_constant_per_fu, force_constant_translations_removed=None, acoustic=False, n_vectors=0, components=<factory>)[source]#

Bases: object

The force constant of one degenerate set of phonon modes at q.

Variables:
  • band_indices (list[int]) – 0-based band indices of the set (ascending frequency).

  • irrep_labels (list[str]) – 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 (float) – Mean frequency of the set in THz (negative: imaginary).

  • effective_mass (float | None) – 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 (float | None) – 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 (float | None) – k / Z in eV/A^2 per formula unit, or None.

  • force_constant_translations_removed (float | None) – 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 (bool) – 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 (int) – Number of patterns behind the values (the set size, or the dimension of the irrep subspace of a component).

  • components (list[crystod.phonon_mode_fc.ModeForceConstantSet]) – For a set that carries several labels and was split by the character projector: one ModeForceConstantSet per label (same band_indices, one label each); else empty.

acoustic: bool = False#
band_indices: list[int]#
components: list[ModeForceConstantSet]#
effective_mass: float | None#
force_constant: float | None#
force_constant_per_fu: float | None#
force_constant_translations_removed: float | None = None#
frequency: float#
irrep_labels: list[str]#
n_vectors: int = 0#
class crystod.phonon.ModeForceConstants(q, q_label, band_sets, irrep_blocks, n_atoms, formula_units, notes=<factory>)[source]#

Bases: object

Mode- and irrep-resolved force constants at one q point.

Variables:
  • q (list[float]) – Fractional coordinates of q in the primitive reciprocal basis.

  • q_label (str | None) – Name of q ("GM", "R"), or None.

  • band_sets (list[crystod.phonon_mode_fc.ModeForceConstantSet]) – One ModeForceConstantSet per degenerate set.

  • irrep_blocks (list[crystod.phonon_mode_fc.IrrepHessianBlock]) – One IrrepHessianBlock per irrep present at q, in the order of first appearance.

  • n_atoms (int) – Atoms in the primitive cell.

  • formula_units (int) – Formula units Z of the primitive cell.

  • notes (list[str]) – 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).

band_sets: list[ModeForceConstantSet]#
formula_units: int#
irrep_blocks: list[IrrepHessianBlock]#
n_atoms: int#
notes: list[str]#
q: list[float]#
q_label: str | None#
class crystod.phonon.ModulationTerm(qpoint, mode_indices, amplitudes)[source]#

Bases: object

One modulation term: modes of one q point with their amplitudes.

crystod-phonon --modulation builds one term from --qpoint, --mode and --amplitude, or one per numbered set (--qpoint1, --mode1, --amplitude1, --qpoint2, …); a combined structure sums the terms on their common supercell.

Variables:
  • qpoint (list[float]) – Fractional coordinates of q in the primitive reciprocal basis.

  • mode_indices (list[int]) – 0-based indices into the mode table of SymmetryAdaptedModulation at that q (the printed table is 1-based).

  • amplitudes (list[float]) – Amplitude in Angstroms of each mode, same length as mode_indices: the norm of the mode’s displacement of one primitive cell at a time-reversal-invariant q (see SymmetryAdaptedModulation.get_modulated_structure()).

amplitudes: list[float]#
mode_indices: list[int]#
qpoint: list[float]#
class crystod.phonon.ParentMapping(M, origin_shift, N, kappa, ideal_frac_child, displacement_cart, max_displacement, max_displacement_species, rms_displacement, max_displacement_parent_lattice, A_child, A_parent, A_pp, strain, frame_rotation, child_cell, parent_cell, child_unitcell, parent_unitcell, child_space_group, parent_space_group, child_symbol, child_number, parent_symbol, parent_number, folding_kpoints, folding_names, setting_P=None, setting_p=None, crystod_group_P=None, crystod_group_p=None, equivalent_settings=<factory>, parent_operation=None, source='given', sma_modes=<factory>, sma_max_displacement=None, sma_child_space_group=None, notes=<factory>)[source]#

Bases: object

The child -> parent setting and atom map of the unfolding.

Variables:
  • M (numpy.ndarray) – (3, 3) int64, A_child = M @ A_parent (unfolding cells).

  • origin_shift (numpy.ndarray) – (3,) p in [0, 1), parent primitive fractional (x_parent = M.T x_child + p).

  • N (int) – det M.

  • kappa (numpy.ndarray) – (n_child,) parent primitive atom of every child atom.

  • ideal_frac_child (numpy.ndarray) – (n_child, 3) ideal site next to each atom (child fractional).

  • displacement_cart (numpy.ndarray) – (n_child, 3) Angstrom, child Cartesian frame.

  • rms_displacement (max_displacement, max_displacement_species,) – In the child lattice (Angstrom).

  • max_displacement_parent_lattice (float) – The same fractional displacements in the strain-free parent lattice (the measure of crystod-group).

  • A_pp (A_child, A_parent,) – Lattices (rows); A_pp = inv(M) @ A_child.

  • strain (dict) – Lengths, angles, strains, volume strain and rotation angle of the pseudo-parent cell against the parent cell.

  • frame_rotation (numpy.ndarray) – (3, 3) proper rotation, v_parent = R @ v_child.

  • parent_cell (child_cell,) – The unfolding cells (PhonopyAtoms).

  • parent_unitcell (child_unitcell,) – The cells of the files (frames of the ISO-IR names).

  • parent_space_group (child_space_group,) – 'Pnma (No. 62)' (spglib at 1e-5 on the unfolding cells); child_symbol, child_number, parent_symbol, parent_number the parts.

  • folding_kpoints (numpy.ndarray) – (N, 3) parent k with M k integer, in (-1/2, 1/2]; GM first.

  • folding_names (list) – Their ISO-IR names in the parent (GM, X, …).

  • setting_p (setting_P,) – The setting used, as crystod-group prints it for the input files (columns of P: the child basis in parent units).

  • crystod_group_p (crystod_group_P,) – The setting crystod-group finds.

  • equivalent_settings (list) – Every M valid for --trans-mat (M0 @ W.T over the proper rotations W of the parent), the crystod-group setting M0 first.

  • parent_operation (tuple | None) – (W, w) relating a --trans-mat setting to the crystod-group one, else None.

  • source (str) – 'crystod-group', '--trans-mat' or 'given'.

  • sma_modes (list) – [(k name, irrep, amplitude in Angstrom), ...] of crystod-group’s decomposition of the distortion.

  • sma_max_displacement (float | None) – crystod-group’s largest atomic displacement.

  • sma_child_space_group (str | None) – The child space group at the mapping tolerance.

  • notes (list) – NOTE lines about the mapping (printed under the setup block).

A_child: ndarray#
A_parent: ndarray#
A_pp: ndarray#
M: ndarray#
N: int#
child_cell: object#
child_number: int#
child_space_group: str#
child_symbol: str#
child_unitcell: object#
crystod_group_P: ndarray | None = None#
crystod_group_p: ndarray | None = None#
displacement_cart: ndarray#
equivalent_settings: list#
folding_kpoints: ndarray#
folding_names: list#
frame_rotation: ndarray#
ideal_frac_child: ndarray#
kappa: ndarray#
max_displacement: float#
max_displacement_parent_lattice: float#
max_displacement_species: str#
notes: list#
origin_shift: ndarray#
parent_cell: object#
parent_number: int#
parent_operation: tuple | None = None#
parent_space_group: str#
parent_symbol: str#
parent_unitcell: object#
rms_displacement: float#
setting_P: ndarray | None = None#
setting_p: ndarray | None = None#
sma_child_space_group: str | None = None#
sma_max_displacement: float | None = None#
sma_modes: list#
source: str = 'given'#
strain: dict#
class crystod.phonon.ParentPath(kpoints, segment_index, distances, legs, leg_labels, connections, tick_positions, tick_labels, vertices, path_text, source, npoints, note=None)[source]#

Bases: object

A band path of the parent zone, as make_parent_path() builds it.

Variables:
  • kpoints (numpy.ndarray) – (n_k, 3) parent primitive fractional k.

  • segment_index (numpy.ndarray) – (n_k,) leg of every point.

  • distances (numpy.ndarray) – (n_k,) cumulative path length, 1/Angstrom without 2 pi, in the reciprocal metric of A_pp; no jump at a break (phonopy).

  • legs (list) – [(k_start, k_end), ...]; leg_labels their labels.

  • connections (list) – phonopy path_connections (leg i continues into leg i + 1).

  • tick_labels (tick_positions,) – One tick per vertex; 'X|R' at a break.

  • vertices (list) – [(label, k, K = M k, child point name), ...], one per leg end point in path order (both sides of a break appear).

  • path_text (str) – 'GM-X-M-GM-R-X|R-M'.

  • source (str) – 'seekpath' or '--band'.

  • npoints (int) – Points per leg (inclusive end points).

  • note (str | None) – The NOTE about a basis conversion of the seekpath path, or None.

connections: list#
distances: ndarray#
kpoints: ndarray#
leg_labels: list#
legs: list#
note: str | None = None#
npoints: int#
path_text: str#
segment_index: ndarray#
source: str#
tick_labels: list#
tick_positions: ndarray#
vertices: list#
class crystod.phonon.PhononMode(band_indices, frequency, labels, qpoint, qpoint_label, representative_q, activity=())[source]#

Bases: object

One degenerate phonon level at a q point.

Returned by label_phonon_modes(); crystod-phonon --subgroup prints one such level per imaginary mode. str(mode) gives the one-line form "modes 1,2,3: -1.0867 THz  R5-".

Variables:
  • band_indices (tuple[int, ...]) – 1-based band indices of the level (CrystOD convention).

  • frequency (float) – Frequency in THz; negative means imaginary.

  • labels (tuple[str, ...]) – ISO-IR irrep label(s) of the level, without the dimension suffix that phonon_irreps.yaml appends ("R4+", not "R4+(3)"); empty when the level could not be labeled.

  • qpoint (tuple[float, float, float]) – The q point that was asked for, in fractional coordinates of the primitive reciprocal basis.

  • qpoint_label (str | None) – Tabulated name of its star (e.g. "R") in the frame of the labels, or None for a q point outside every tabulated star.

  • representative_q (tuple[float, float, float]) – The tabulated arm of the star at which the labels were read (equal to qpoint when that is the tabulated arm).

  • activity (tuple[str, ...]) – At Gamma, the spectroscopic activity of the level: ("IR",), ("Raman",), ("IR", "Raman"), ("silent",) or ("acoustic",) (see crystod.phonon_activity); a level that holds several irreps (more than one label) lists every kind that occurs in it, e.g. ("IR", "silent", "acoustic"); ("unknown",) when the characters of the level are not those of a representation (a degenerate level split by too small a degeneracy tolerance). Empty at any other q.

activity: tuple[str, ...] = ()#
band_indices: tuple[int, ...]#
property degeneracy: int#

Number of bands in the level.

frequency: float#
property is_imaginary: bool#

True when the frequency is negative (no threshold applied).

labels: tuple[str, ...]#
qpoint: tuple[float, float, float]#
qpoint_label: str | None#
representative_q: tuple[float, float, float]#
class crystod.phonon.PhononViewer(formula, space_group, number, supercell, force_data, nac, path_source, dispersion, points, threshold, bonds, primitive_lattice, conventional_lattice, amplitude=0.5, notes=<factory>, all_irreps=False)[source]#

Bases: object

Everything the phonon mode viewer page shows.

Variables:
  • formula (str) – Reduced formula (ScF3).

  • space_group (str) – Hermann-Mauguin symbol; number its number.

  • supercell (str) – The force-calculation supercell (4 x 4 x 4).

  • force_data (str | None) – FORCE_SETS or FORCE_CONSTANTS (or None).

  • nac (bool) – Whether the NAC correction is applied.

  • path_source (str) – seekpath or --band.

  • dispersion (object) – The crystod.phonon_irreps_plot.Dispersion of the path.

  • points (list) – The ViewerPoint list, in the order of the selector.

  • threshold (float) – Frequency (THz) below which a level counts as imaginary.

  • bonds (list) – The (el1, el2, max_length) bond specifications.

  • primitive_lattice (numpy.ndarray[tuple[Any, ...], numpy.dtype[numpy.float64]]) – Rows, Angstrom; conventional_lattice the conventional cell with --conventional (else None).

  • amplitude (float) – Default largest displacement on the page (Angstrom, default_amplitude()).

  • notes (list) – Notes of the run (path, NAC, segment midpoints not drawn).

  • all_irreps (bool) – Whether the segment midpoints are shown too (--all-irreps; they follow the special points in points).

all_irreps: bool = False#
amplitude: float = 0.5#
bonds: list#
conventional_lattice: ndarray[tuple[Any, ...], dtype[float64]] | None#
dispersion: object#
force_data: str | None#
formula: str#
nac: bool#
notes: list#
number: int#
path_source: str#
points: list#
primitive_lattice: ndarray[tuple[Any, ...], dtype[float64]]#
space_group: str#
supercell: str#
threshold: float#
class crystod.phonon.RamanTensors(label, dimension, multiplicity, tensors, partners=())[source]#

Bases: object

The symmetry-allowed Raman tensors of one Raman-active irrep.

Variables:
  • label (str) – ISO-IR label of the irrep; a complex irrep is listed together with its conjugate ("GM2GM3").

  • dimension (int) – Dimension of the (physically irreducible) irrep.

  • multiplicity (int) – Its multiplicity in the symmetric square of the vector representation.

  • tensors (tuple) – dimension * multiplicity basis tensors (3x3 arrays) in the Cartesian axes of the input cell, a basis of the isotypic subspace of the irrep.

  • partners (tuple) – For an irrep of dimension >= 2 that occurs more than once (E of 3m, -3m, 32, 3, -3), the Raman tensor of each partner with constants shared across the partners: one array of shape (n_constants, 3, 3) per partner, the coefficient tensor of each constant (Loudon’s form, e.g. [[c, 0, 0], [0, -c, d], [0, d, 0]] and [[0, -c, -d], [-c, 0, 0], [-d, 0, 0]] for Eg of -3m). Empty otherwise, where tensors are the partners (multiplicity 1) or the irrep is one-dimensional.

dimension: int#
label: str#
multiplicity: int#
partners: tuple = ()#
tensors: tuple#
class crystod.phonon.SymmetryAdaptedModulation(yaml_path=None, qpoint=None, symprec=1e-05, keep_q_coords=False, phonon=None)[source]#

Bases: object

Symmetry-adapted phonon modes at one q point and their frozen-in structures.

The engine of crystod-phonon --modulation. On construction the dynamical matrix of phonon at qpoint is block-diagonalized in the spgrep irrep-projected basis of phonon.primitive as it is (its atom order, positions, lattice and Cartesian frame; no re-standardization), so that the partners of a degenerate level transform with the irrep matrices instead of coming out as arbitrary combinations – the solver shared with crystod-phonon --vector (crystod.symmetry_adapted_modes.solve_symmetry_adapted_modes()); the result is verified against the plain phonopy spectrum. get_modulated_structure() then freezes selected modes into the smallest commensurate supercell of that same cell, and analyze_symmetry() reports the space group of the result.

The frozen-in displacements are true harmonic eigen-displacements (phonopy’s eigenvector divided by the square root of the atomic mass, as phonopy’s own modulation does). At a time-reversal-invariant q (2q a reciprocal lattice vector) every mode vector is real, the partners of a degenerate level are orthonormal real patterns along directions that symmetry operations fix up to sign, chosen and ordered by the isotropy subgroups they freeze into (independent of the origin, orientation and lattice basis of the input; which of several equivalent domains comes first, and the signs, are conventions – the signs of the partners of one level relative to each other do not depend on the origin either, the overall sign at q != 0 only picks one of two copies translated by a lattice vector, and nothing ties the signs of different q points), and the amplitude is the norm of the displacement of one primitive cell. At any other q the vector is a complex Bloch wave whose global phase (a shift of the modulation along the lattice) is fixed by a convention only, not controlled physically, and a single partner of a degenerate level freezes into a structure that depends on that phase.

Parameters:
  • yaml_path (str | None) – A phonopy_params.yaml (.xz accepted) to load the phonopy object from, without the non-analytical term correction (neither the yaml’s NAC parameters nor a BORN file are read; pass a phonon loaded with is_nac=True for NAC); ignored when phonon is given.

  • qpoint (list[float] | None) – Fractional coordinates of q in the reciprocal basis of phonon.primitive (required).

  • symprec (float) – Symmetry tolerance of the spglib/spgrep analysis.

  • keep_q_coords (bool) – Name a non-special q by its coordinates (q_<coords>) in get_q_label() instead of its ISO-IR k-vector type.

  • phonon – A prebuilt phonopy.Phonopy object with force constants, e.g. from phonopy.load of a unit cell with FORCE_SETS; lets one set of force data drive several q points without reloading it. Build it with primitive_matrix="auto": its primitive cell must be primitive.

Variables:
  • qpoint – The q point as a float array of shape (3,).

  • phonon – The phonopy object.

  • vibrations – The symmetry analysis of phonon.primitive (vibrations.primitive_cell – the cell the structures are built on –, vibrations.rotations, vibrations.translations).

  • irreps – The spgrep irreps of the little group of q.

  • vibration_basis – The irrep-projected basis of the vibration space, one (dim, 3 * n_atoms) array per projected space (rows are kets in phonopy’s phase convention).

  • n_atoms – Number of atoms in the primitive cell.

  • mode_info – One {"frequency_THz": ..., "degeneracy": ...} dict per mode, sorted by frequency (mode i is band i of the phonopy spectrum).

  • mode_vectors – The corresponding freezing vectors, 3 * n_atoms complex components each, v_j = e_j exp(2 pi i q . x_j) / sqrt(m_j) normalized over the primitive cell (e the phonopy eigenvector, x_j the scaled position of atom j in vibrations.primitive_cell); the displacement of atom j in the cell at lattice translation R is amplitude * Re(v_j * exp(2 pi i q . R)). Real at a time-reversal-invariant q.

  • eigenvectors – The same modes as unit eigenvectors of phonopy’s dynamical matrix, in phonopy’s convention (mass-weighted, atom-position phase).

Raises:
  • ValueError – If qpoint is missing, neither yaml_path nor phonon is given, the phonopy object carries no force constants, or its primitive cell is not primitive (crystod.symmetry_adapted_modes.NonPrimitiveCellError).

  • RuntimeError – If the symmetry-adapted construction does not reproduce the phonopy spectrum.

Example

Freeze one component of the R-point soft mode of cubic SrTiO3 (ph as in crystod.phonon.label_phonon_modes()):

from crystod import phonon

modulation = phonon.SymmetryAdaptedModulation(
    phonon=ph, qpoint=[0.5, 0.5, 0.5])
modulation.print_mode_info()            # 15 modes, R5-(3) first
atoms = modulation.get_modulated_structure([0], [0.3])
modulation.analyze_symmetry(atoms)      # I4/mcm (No. 140)
static analyze_symmetry(atoms, symprec=0.1)[source]#

Space group of a structure, printed and returned.

crystod-phonon --modulation reports the space group of the generated structure with this; the default 0.1 is the tolerance the command uses for that report (--tolerance overrides it).

Parameters:
  • atoms (Atoms) – The structure as an ase.Atoms object.

  • symprec (float) – spglib symmetry tolerance.

Returns:

Dict with "international" (short symbol), "number" and "hall" (Hall symbol).

Return type:

dict[str, str | int]

static get_commensurate_supercell_sizes(qpoint)[source]#

Supercell multiplicities along a, b, c commensurate with q.

The smallest diagonal supercell on which the modulation at q is periodic (not always the smallest supercell of all: q = (1/2, 1/2, 0) gives 2 x 2 x 1).

Parameters:

qpoint (list[float] | ndarray[tuple[Any, ...], dtype[float64]]) – Fractional coordinates of q in the primitive reciprocal basis.

Returns:

1 for an integer component, else the denominator of the component.

Return type:

Integer array (n1, n2, n3)

Raises:

ValueError – If a component is not a fraction with a denominator of at most 12 (e.g. 0.15): no such supercell holds the modulation, and freezing it into one would build a structure that is not periodic. The message names the smallest commensurate supercell (20 x 1 x 1 for 0.15).

format_mode_table()[source]#

The lines print_mode_info() prints: the title "Phonon modes at q = ...", the column header, a rule and one row per mode (1-based mode number, frequency in THz, irrep, degeneracy).

Returns:

The lines, without trailing newlines.

Return type:

list[str]

get_mode_labels()[source]#

Per-mode irrep labels, e.g. 'X3-(1)'; '-' when unavailable.

Uses the ISO-IR-table-based labeling of crystod-phonon --vector and --irreps. The label of band i applies to mode i because the symmetry-adapted frequencies are verified to match the plain phonopy spectrum. Computed once and cached.

Returns:

List of n_modes label strings in mode order.

Return type:

list[str]

get_modulated_structure(mode_indices, amplitudes)[source]#

Freeze selected modes into the smallest commensurate supercell.

The supercell is n1 x n2 x n3 copies of vibrations.primitive_cell (phonopy’s primitive cell as it is) with n_i the denominator of the i-th component of q (get_commensurate_supercell_sizes()). Atom j in the cell at lattice translation R is displaced by the sum over the selected modes of amplitude * Re(vector_j * exp(2 pi i q . R)) with vector the mode’s entry of mode_vectors – the harmonic eigen-displacement of the mode; at a time-reversal-invariant q the displacement of every primitive cell has the norm amplitude. The atoms are ordered by species, as a POSCAR wants them.

Parameters:
  • mode_indices (list[int]) – 0-based indices into mode_vectors (the printed mode table is 1-based).

  • amplitudes (list[float]) – Amplitude in Angstroms of each selected mode, same length as mode_indices.

Returns:

The modulated structure as an ase.Atoms object with periodic boundary conditions.

Raises:
  • SystemExit – If a mode index is out of range (the command-line convention; not translated to ValueError for methods).

  • ValueError – If q is not commensurate with a supercell of at most 12 cells per axis.

Return type:

Atoms

get_q_label()[source]#

Short q label for file names.

The ISO-IR k-vector type of q in the frame of the labels: the name of its star at a special point (e.g. 'X'), else the type of q (e.g. 'DT'); else 'q_<coordinates>'. With keep_q_coords only a point in the star of a tabulated special point keeps its name, any other q gets 'q_<coordinates>'. Computed once and cached.

Returns:

The label string.

Return type:

str

print_mode_info()[source]#

Print the mode table: number, frequency (THz), irrep, degeneracy.

Mode numbers are 1-based, as --mode of crystod-phonon --modulation expects them.

eigenvectors: list[ndarray[tuple[Any, ...], dtype[complex128]]]#
mode_info: list[dict[str, float | int]]#
mode_vectors: list[ndarray[tuple[Any, ...], dtype[complex128]]]#
property n_modes: int#

Number of modes at q (3 * n_atoms).

class crystod.phonon.SymmetryOnlyVibrations(cell, symprec=1e-05, standardize=True, input_cell=None, quiet=False)[source]#

Bases: _CoreRepresentation

Symmetry-allowed vibration bases of a crystal, without force data.

The engine of crystod-phonon --vibration: at a q point, the displacement representation of the little group of q (the permutation representation of the atoms times the Cartesian rotation, with Bloch phases) is projected onto the spgrep irreps, giving one basis of symmetry-adapted displacement patterns per irrep occurrence. The spaces are labeled with ISO-IR irrep names, and any component can be written out as a displaced structure on the commensurate supercell: the partner of get_symmetry_adapted_spaces() – fixed by the conventions of --modulation, real with the Bloch phase of every atom at a time-reversal-invariant q, so that it freezes into an isotropy subgroup of its irrep – a unit-norm symmetry-adapted displacement pattern, not a normal mode. crystod.symmetry_adapted_modes.solve_symmetry_adapted_modes() (behind crystod-phonon --modulation and --vector) uses the same basis, on phonopy’s primitive cell as it is (standardize=False), to block-diagonalize a dynamical matrix.

Parameters:
  • cell (PhonopyAtoms) – The crystal structure as a phonopy.structure.atoms.PhonopyAtoms object, e.g. from phonopy.interface.calculator.read_crystal_structure.

  • symprec (float) – Symmetry tolerance of the spglib analysis.

  • standardize (bool) – Reduce cell to the spglib primitive cell first (the default; a note is printed on stdout unless quiet). False keeps the input cell as it is, which must then already be primitive; this preserves the caller’s atom positions so that phase conventions stay consistent with an externally built dynamical matrix. Either way the analysis, the Bloch phases and the written supercells all use primitive_cell.

  • input_cell (PhonopyAtoms | None) – The cell whose ISO-IR frame names the irreps, when it is not cell itself (e.g. the unit cell a phonopy primitive cell was built from); default cell.

  • quiet (bool) – Do not print the note ### Inputed cell was converted into primitive cell. ### that standardize prints on stdout (the commands keep it); for library use and the MCP server, whose stdout is the protocol stream.

Variables:
  • primitive_cell – The primitive cell the analysis runs on.

  • spglib_dataset – Its spglib symmetry dataset (["number"], ["international"], …).

  • rotations – Rotation parts of the space-group operations in the primitive basis, shape (n_ops, 3, 3).

  • translations – The corresponding translation parts, shape (n_ops, 3).

  • rotations_cartesian – The rotations in Cartesian coordinates.

  • symprec – The symmetry tolerance.

  • labels_from_isoir – True when the last get_irrep_labels() call took its labels from the general ISO-IR k-vector lookup rather than from the special-point table.

Example

List the vibration spaces of cubic ScF3 at the R point:

from phonopy.interface.calculator import read_crystal_structure
from crystod import phonon
from crystod.examples import example_path

cell, _ = read_crystal_structure(
    example_path("221_PPOSCAR_ScF3"), interface_mode="vasp")
vibrations = phonon.SymmetryOnlyVibrations(cell)
label, qpoint = vibrations.resolve_qpoint(["R"])
irreps, spaces, labels = vibrations.describe_mode_spaces(qpoint)
labels                      # ['R1+(1)', 'R3+(2)', 'R4+(3)', ...]
[space.shape for space in spaces]   # [(1, 12), (2, 12), (3, 12), ...]
describe_mode_spaces(qpoint)[source]#

Irreps, projected vibration spaces and their labels at q.

The one-call form of get_vibration_rep(), get_irrep_labels() and get_vibration_basis(), as crystod-phonon --vibration prints them (one “Mode Space” line per irrep occurrence, with its label and dimension).

Parameters:

qpoint (list[float]) – Fractional coordinates of q in the primitive reciprocal basis.

Returns:

the spgrep irreps, one (dim, 3 * n_atoms) array per irrep occurrence, and the ISO-IR label of each space. The mode-space numbers of the command are 1-based positions in basis_spaces. These are spgrep’s raw projected spaces; the partners the command writes out are those of get_symmetry_adapted_spaces().

Return type:

(irreps, basis_spaces, basis_space_labels)

get_high_symmetry_qpoints()[source]#

High-symmetry q points of the primitive cell, from seekpath.

crystod-phonon --vibration --list-qpoints prints this map. The coordinates are expressed in the reciprocal basis of this object’s (spglib) primitive cell: seekpath’s own primitive cell can differ from it by an integer change of basis (base-centred monoclinic cells, for instance), and the tabulated coordinates are transformed accordingly. A warning is issued only when the two cells are not related by such a change of basis, in which case the coordinates are returned as seekpath gives them.

seekpath names its points in spglib’s standardized frame, while the irrep labels refer to the ISO-IR frame of the input cell; for an input outside the ISO-IR setting the two differ by an element of the normalizer, which can turn seekpath’s P into the PA of the labels. A point whose ISO-IR type differs between the two frames is therefore moved to the point that carries its type in the frame of the labels (-k for the -k partner of a tabulated type, else its image under the change of frame), so that --qpoint P is the point the labels call P. The names stay seekpath’s: for a triclinic cell seekpath’s letters X, Y, Z, R, T, U, V denote other points than the ISO-IR names of the labels (seekpath’s Z of 1_PPOSCAR_RbBe2F5 carries X1).

Returns:

Dict mapping seekpath labels ("GAMMA", "R", "X", …) to fractional coordinates in the primitive reciprocal basis.

Return type:

dict[str, list[float]]

get_irrep_labels(qpoint, irreps, mapping_little_group)[source]#

ISO-IR labels of the spgrep irreps at q.

The ISO-IR labeller (crystod.isoir) names the spgrep irreps at any q – a special point, any arm of its star or copy q + G, a symmetry line, plane or generic q (Miller-Love labels) – in the ISO-IR frame of the input cell; a q point tabulated only through its -k partner gets the ‘A’ names of the conjugate irreps (PA1). Only where the labeller gives nothing are the characters compared directly with the special-point table (at a tabulated point, or by conjugation onto the tabulated arm for another arm of its star). An irrep neither route names keeps its generic irrep_N(dim) label.

Parameters:
  • qpoint (list[float]) – Fractional coordinates of q in the primitive reciprocal basis.

  • irreps – The spgrep irreps from get_vibration_rep().

  • mapping_little_group (ndarray[tuple[Any, ...], dtype[int64]]) – The little-group indices from get_vibration_rep().

Returns:

One label per irrep, e.g. "R4+(3)" (the irrep name with its dimension).

Return type:

list[str]

get_special_qpoints()[source]#

The ISO-IR special q points of the space group, in the frame of the labels.

crystod-phonon --vibration lists these points (--list-qpoints) and resolves --qpoint NAME through them: one entry per special point of the ISO-IR tables, named as the irrep labels at it are named (the frame of the labels, crystod.isoir.special_points_in_frame; a point tabulated only through its -k partner is listed at the tabulated point), the set of points crystod-phonon --irreps writes under special_points: for the same structure. The -k partners (PA) and seekpath’s extra points (H_2) are not listed. The command prints them in the order of seekpath’s path (GM, A, K, H, M, L for P6_3mc); this method keeps the table order.

Returns:

Dict mapping ISO-IR names ("GM", "A", "K", …), in the order of the tables, to fractional coordinates in the reciprocal basis of primitive_cell; empty when the tables do not cover the space group.

Return type:

dict[str, list[float]]

get_supercell_displacements(qpoint, mode_vector, supercell_size)[source]#

Displacement pattern of one basis vector on a supercell.

Atom j of the primitive cell at lattice translation R is displaced by Re(mode_j * exp(2 pi i q . (R + x_j))) (unit amplitude), with x_j the scaled position of atom j in primitive_cell, the cell the supercell is built from: the Bloch wave the ket mode describes in the atom-position phase convention. For a row of get_symmetry_adapted_spaces() at a time-reversal-invariant q the displacement of every primitive cell has unit norm.

Parameters:
  • qpoint (list[float]) – Fractional coordinates of q in the primitive reciprocal basis.

  • mode_vector (ndarray[tuple[Any, ...], dtype[complex128]]) – One row of get_symmetry_adapted_spaces() (what --vibration writes) or of a projected space of describe_mode_spaces() (whose global phase, and at a time-reversal-invariant q its partner basis, spgrep leaves arbitrary), 3 * n_atoms complex components.

  • supercell_size (tuple[int, int, int]) – (n1, n2, n3) multiplicities, e.g. from get_supercell_size().

Returns:

Cartesian positions and displacements of the supercell atoms, shape (n1 * n2 * n3 * n_atoms, 3), their chemical symbols, and the supercell lattice vectors as rows.

Return type:

(positions, displacements, symbols, supercell_lattice)

get_supercell_size(qpoint)[source]#

Supercell multiplicities along a, b, c commensurate with q.

Parameters:

qpoint (list[float]) – Fractional coordinates of q in the primitive reciprocal basis.

Returns:

1 for an integer component, else the denominator of the component (commensurate_supercell_sizes(), the check --modulation makes).

Return type:

(n1, n2, n3)

Raises:

ValueError – If a component is not a fraction with a denominator of at most 12 (e.g. 0.15 = 3/20): no such supercell holds the modulation; the message names the smallest one that does.

get_symmetry_adapted_spaces(qpoint)[source]#

Symmetry-adapted partners of every mode space, as --vibration freezes them.

The spaces of describe_mode_spaces() (same order, same dimensions) with their partners fixed by the conventions of crystod-phonon --modulation (crystod.symmetry_adapted_modes.solve_symmetry_adapted_spaces(), the mode solver with no dynamical matrix): the spaces of a repeated irrep are an orthonormal basis of its isotypic space fixed by the displacements (the atom orbit each lives on, then how the atoms move along the crystal axes, then the products of the displacements of neighbouring atoms), not the copies spgrep’s projection happens to return; at a time-reversal-invariant q (2q a reciprocal lattice vector) every partner is, with the Bloch factor exp(2 pi i q . x_j) of each atom, a real displacement pattern along a direction symmetry operations fix up to sign – a single partner freezes into an isotropy subgroup of its irrep, whatever the origin; at any other q each space is a complex Bloch wave whose global phase is a convention. A complex irrep and its conjugate, which time reversal joins into one real space at such a q, share its real partners: the first half belongs to the irrep whose label sorts first. At a time-reversal-invariant q the k-th space of a given label thus holds the same partners however q is written (q, q + G or -q); the position of a label in the list follows spgrep’s irrep order at the q given and can differ between those spellings. (At any other q the relative phases of the partners of a larger irrep follow the irrep matrices spgrep builds at the q given.) The rows are unit-norm symmetry-adapted displacement patterns, not normal modes: there are no force constants to select a combination of the spaces of a repeated irrep, and no masses.

Parameters:

qpoint (list[float]) – Fractional coordinates of q in the primitive reciprocal basis.

Returns:

One (dim, 3 * n_atoms) array per mode space, rows in the atom-position phase convention of get_vibration_basis() (the Bloch factor of each atom not included), ready for get_supercell_displacements().

Return type:

list[ndarray[tuple[Any, …], dtype[complex128]]]

get_vibration_basis(irreps, vibration_rep, irrep_labels=None)[source]#

Project the displacement representation onto each irrep.

Parameters:
Returns:

one (dim, 3 * n_atoms) array per occurrence of an irrep in the displacement representation, and the label of each space. The rows are the symmetry-adapted displacement patterns as kets: for one array B and the irrep matrices d, vibration_rep[g] @ B.T == B.T @ d[g]. They are in the atom-position phase convention of phonopy’s eigenvectors (Bloch factor exp(2 pi i q . x_j) of each atom not included). Repeated occurrences of one irrep transform with the same matrices but are not orthogonal to each other.

Return type:

(basis_vectors, basis_labels)

get_vibration_rep(kpoint)[source]#

Displacement representation of the little group of q.

Parameters:

kpoint (list[float]) – Fractional coordinates of q in the primitive reciprocal basis.

Returns:

the spgrep irreps of the little group of q; the representation matrices of the little-group operations on the 3 * n_atoms displacement space, shape (n_little, 3 * n_atoms, 3 * n_atoms); and the indices of the little-group operations within rotations.

Return type:

(irreps, vibration_rep, mapping_little_group)

name_qpoint(qpoint)[source]#

The name crystod-phonon --vibration gives to q point coordinates.

The ISO-IR name of a point of get_special_qpoints(); for another arm of its star (or q + G) the name of the arm the space-group rotations map q onto; else the ISO-IR k-vector type of q in the frame of the labels (T for a symmetry line, PA for the -k partner of a tabulated point, GP for a general point); else "custom".

Parameters:

qpoint – Fractional coordinates in the primitive reciprocal basis.

Returns:

The name.

Return type:

str

resolve_qpoint(raw_qpoint)[source]#

Resolve --qpoint tokens into a label and coordinates.

One token is a seekpath label (GM, G and the Greek capital gamma are accepted for GAMMA) of get_high_symmetry_qpoints(); three tokens are coordinates in the primitive reciprocal basis, fractions such as 1/3 allowed. Coordinates of a point of get_high_symmetry_qpoints() are labeled with its name there. Other coordinates get, where the frame of the labels names q differently from spglib’s frame (an input outside the ISO-IR setting), the ISO-IR name in the frame of the labels (PA above PA labels); else the name of the star arm the space-group rotations map them onto, else the ISO-IR k-vector type of q, else "custom".

Parameters:

raw_qpoint (list[str]) – The tokens, one label or three coordinate strings.

Returns:

(label, qpoint) with qpoint a list of three floats.

Raises:

ValueError – For an unknown label, or a token count other than one or three.

Return type:

tuple[str, list[float]]

resolve_special_qpoint(raw_qpoint)[source]#

Resolve --qpoint tokens of crystod-phonon --vibration.

One token is an ISO-IR name of get_special_qpoints() (any case); GAMMA, G and the Greek capital gamma stand for GM, and a seekpath name of get_high_symmetry_qpoints() that is not an ISO-IR name of the list (H_2) is accepted as an alias of its point. Three tokens are coordinates in the primitive reciprocal basis (fractions such as 1/3 allowed), named by name_qpoint(). resolve_qpoint() keeps the seekpath names for the other commands.

Parameters:

raw_qpoint (list[str]) – The tokens, one name or three coordinate strings.

Returns:

(name, qpoint) with qpoint a list of three floats.

Raises:

ValueError – For an unknown name, or a token count other than one or three.

Return type:

tuple[str, list[float]]

write_displaced_structure(positions, displacements, symbols, supercell_lattice, amplitude, output_path)[source]#

Write positions + amplitude * displacements as a POSCAR.

The atoms are grouped by species, in the order the species first appear in symbols (one block per element, Sc F / 8 24, as --modulation writes them); within a species they keep their order.

Parameters:
  • positions (ndarray[tuple[Any, ...], dtype[float64]]) – Cartesian positions from get_supercell_displacements().

  • displacements (ndarray[tuple[Any, ...], dtype[float64]]) – The unit-amplitude displacements from the same call.

  • symbols (list[str]) – Chemical symbols of the atoms.

  • supercell_lattice (ndarray[tuple[Any, ...], dtype[float64]]) – Supercell lattice vectors as rows.

  • amplitude (float) – Displacement amplitude in Angstroms.

  • output_path (str) – Output file path (VASP format, direct coordinates).

class crystod.phonon.UnfoldInputs(child_poscar, parent_poscar, child_force_file, parent_force_file, child_dim, parent_dim, child_readfc, parent_readfc, child_unitcell, parent_unitcell, child_primitive_matrix, parent_primitive_matrix, child_cell, parent_cell, child_phonon, parent_phonon)[source]#

Bases: object

The child and the parent as load_unfold_inputs() reads them.

Variables:
  • parent_poscar (child_poscar,) – The structure files as given.

  • child_force_file (str) – Absolute path of the child’s FORCE_SETS (or FORCE_CONSTANTS) that was read.

  • parent_force_file (str | None) – The same for the parent; None without parent_dim.

  • parent_dim (child_dim,) – Diagonal supercells of the force calculations (parent_dim None without parent force data).

  • parent_readfc (child_readfc,) – FORCE_CONSTANTS instead of FORCE_SETS.

  • parent_unitcell (child_unitcell,) – The cells of the files (PhonopyAtoms, read with crystod.vasp_io.read_poscar_cell()).

  • parent_primitive_matrix (child_primitive_matrix,) – phonopy primitive matrices (A_prim = P.T @ A_unit); the identity when a cell is used as given.

  • child_cell (object) – The child unfolding cell (child_phonon.primitive).

  • parent_cell (object) – The parent primitive cell of the unfolding.

  • child_phonon (object) – phonopy.Phonopy with the child force constants.

  • parent_phonon (object | None) – The same for the parent, or None without parent_dim.

child_cell: object#
child_dim: tuple#
child_force_file: str#
child_phonon: object#
child_poscar: str#
child_primitive_matrix: ndarray#
child_readfc: bool#
child_unitcell: object#
parent_cell: object#
parent_dim: tuple | None#
parent_force_file: str | None#
parent_phonon: object | None#
parent_poscar: str#
parent_primitive_matrix: ndarray#
parent_readfc: bool#
parent_unitcell: object#
class crystod.phonon.UnfoldedBands(k_parent, K_child, frequencies, weights, weights_canonical, vectors, degenerate_group, group_weight, sum_rule_max_deviation, timings)[source]#

Bases: object

Child phonons unfolded onto parent k points (unfold()).

Variables:
  • k_parent (numpy.ndarray) – (n_k, 3) parent fractional k.

  • K_child (numpy.ndarray) – (n_k, 3) k_parent @ M.T (what phonopy was given; unwrapped).

  • frequencies (numpy.ndarray) – (n_k, n_band) THz, ascending, n_band = 3 n_child.

  • weights (numpy.ndarray) – (n_k, n_band) P_J(k) in phonopy’s eigenvector basis.

  • weights_canonical (numpy.ndarray) – (n_k, n_band) after the canonical rotation of degenerate sets (basis independent).

  • vectors (numpy.ndarray) – (n_k, n_band, 3 n_parent) complex canonical u_J(k), child Cartesian frame, parent origin, index 3 kappa + alpha.

  • degenerate_group (numpy.ndarray) – (n_k, n_band) group index (0, 1, … ascending) at each k.

  • group_weight (numpy.ndarray) – (n_k, n_band) P_g of the mode’s degenerate group.

  • sum_rule_max_deviation (float) – max over k of |sum_J P_J(k) - 3 n_parent|.

  • timings (dict) – {'eigen_s', 'unfold_s', 'canonical_s'} (CPU wall time).

K_child: ndarray#
degenerate_group: ndarray#
frequencies: ndarray#
group_weight: ndarray#
k_parent: ndarray#
sum_rule_max_deviation: float#
timings: dict#
vectors: ndarray#
weights: ndarray#
weights_canonical: ndarray#
class crystod.phonon.UnfoldedIrreps(units, kname, weights, group_label, group_members, group_fraction, inseparable, tr_units, parent_labels, parent_frequencies, mulliken, checks, cache, basis, notes=<factory>, timings=<factory>)[source]#

Bases: object

Parent-irrep resolution of unfolded bands (irrep_resolve()).

Variables:
  • units (list) – Every irrep unit met along the k points ('GM4-', 'S1+S2', …), grouped by k type, natural order inside a type.

  • kname (list) – ISO-IR k type of every k ('GM', 'DT', 'X', …).

  • weights (numpy.ndarray) – (n_k, n_band, n_units) P_J^(u)(k) per mode (canonical basis); 0 where a unit does not occur.

  • group_label (numpy.ndarray) – (n_k, n_band) str, the label of the mode’s degenerate group ('R4+', 'Z1/Z3', 'S1+S2', 'mixed', '-').

  • group_members (list) – [k][mode] -> tuple of the irrep names of the label (('U2+', 'U3+'), ('Z1', 'Z3'); () for mixed and -).

  • group_fraction (numpy.ndarray) – (n_k, n_band) summed share of P_g held by the label’s units (0 for mixed and -).

  • inseparable (list) – [k] -> tuples of units the child symmetry cannot separate.

  • tr_units (list) – [k] -> the time-reversal pairs present at k.

  • parent_labels (numpy.ndarray | None) – (n_k, 3 n_parent) str, unit of every parent band (with parent phonons), else None; parent_frequencies likewise (THz).

  • mulliken (dict) – {parent GM unit: Mulliken symbol}.

  • checks (dict) – Largest deviations: projector identities (‘completeness’, ‘idempotency’, ‘hermiticity’, ‘orthogonality’, ‘mass_commutator’), ‘sum_over_irreps’ (sum_u P_J^(u) - P_J), ‘per_irrep_sum_rule’ (sum_J P_J^(u) - trace), ‘parent_purity’ (distance of the unit weights of every parent level from whole numbers of bands), ‘forbidden_weight’ (largest share of a degenerate group in parent irreps its irreps of H(k) forbid), ‘selection_residual’ (largest residual of the H(k)-invariance of the groups’ subspaces), ‘selection_groups’ (groups checked), ‘class_multiplicity’ (distance from integers of the multiplicities behind the inseparable sets), ‘translation_mismatch’.

  • cache (dict) – {'runs', 'labeled_directly', 'copied', 'mismatches'} of the line-label cache.

  • basis (object) – The ParentIrrepBasis (reused by crystod.phonon_unfold.gamma_origin()).

  • notes (list) – NOTE lines (time-reversal test failed, Mulliken symbols, checks above 1e-6).

  • timings (dict) – CPU wall times of the steps.

basis: object#
cache: dict#
checks: dict#
group_fraction: ndarray#
group_label: ndarray#
group_members: list#
inseparable: list#
kname: list#
mulliken: dict#
notes: list#
parent_frequencies: ndarray | None#
parent_labels: ndarray | None#
timings: dict#
tr_units: list#
units: list#
weights: ndarray#
class crystod.phonon.ViewerMode(band, frequency, irrep, component, dimension, set_index, mulliken, activity, u, scale, vector)[source]#

Bases: object

One phonon mode (band) at a q point of the viewer.

Variables:
  • band (int) – 1-based band index (frequency order).

  • frequency (float) – Frequency in THz (negative: imaginary).

  • irrep (str) – Text of the degenerate set the band belongs to, as phonon_irreps.yaml labels it (GM4-(3); X3- for a one-dimensional irrep; GM1 + GM5(2) for a set holding several irreps; ? when unlabeled).

  • component (int) – 1..dimension inside the degenerate set.

  • dimension (int) – Number of bands of the set.

  • set_index (int) – 0-based index of the set at this q point.

  • mulliken (str | None) – Mulliken symbol of the set at Gamma (T1u), else None.

  • activity (str | None) – Activity of the set at Gamma (IR, Raman, IR+Raman, silent, acoustic), else None.

  • u (numpy.ndarray[tuple[Any, ...], numpy.dtype[numpy.complex128]]) – Atomic-gauge complex displacement vectors, shape (n_primitive_atoms, 3), normalized so that the largest displacement of the display cell at phase 0 is 1.

  • scale (float) – The factor removed by that normalization (the largest real displacement of the field of crystod.phonon_vector.get_supercell_displacement_field()).

  • vector (numpy.ndarray[tuple[Any, ...], numpy.dtype[numpy.complex128]]) – The mass-weighted mode vector the pattern comes from (phonopy convention, 3 * n_atoms complex components).

activity: str | None#
band: int#
component: int#
dimension: int#
frequency: float#
irrep: str#
mulliken: str | None#
scale: float#
set_index: int#
u: ndarray[tuple[Any, ...], dtype[complex128]]#
vector: ndarray[tuple[Any, ...], dtype[complex128]]#
class crystod.phonon.ViewerPoint(name, q, x, cell_matrix, cell_description, lattice, symbols, positions, atom_index, translations, bonds, polyhedra, modes, notes=<factory>, segment=None)[source]#

Bases: object

One q point of the viewer: its display cell, atoms, bonds and modes.

Variables:
  • name (str) – ISO-IR name of the point (GM, X; U|K for the two sides of a break that carry the same levels; DT for a segment midpoint, its ISO-IR k-vector type).

  • q (list) – Fractional coordinates, primitive reciprocal basis.

  • x (float | None) – Position on the dispersion (path distance; the middle of its leg for a segment midpoint), or None when the point is not on the path (--qpoint elsewhere).

  • cell_matrix (numpy.ndarray[tuple[Any, ...], numpy.dtype[numpy.int64]]) – Rows are the display-cell vectors in the primitive basis (commensurate with q: each axis times the denominator of q, _display_cell_matrix()).

  • cell_description (str) – primitive, 2 x 2 x 2 cells (as the SALC viewer).

  • lattice (numpy.ndarray[tuple[Any, ...], numpy.dtype[numpy.float64]]) – The display-cell lattice vectors as rows (Angstrom).

  • translations (symbols, positions, atom_index,) – The drawn atoms (boundary completion and bonded images included): element, Cartesian position (A), primitive atom index a and primitive-basis lattice translation T (ints).

  • bonds (list) – [(name, [(slot_i, slot_j), ...]), ...] per --bond.

  • polyhedra (list) – [(element, center_slot, [(slot_i, slot_j, slot_k), ...]), ...]: the triangles of the convex hull of each coordination polyhedron at equilibrium (kept while the atoms move).

  • modes (list) – The ViewerMode list, in band order.

  • notes (list) – Notes of this point (fallbacks).

  • segment (str | None) – The segment of the path whose midpoint this point is (GM-X; --all-irreps), None at a special point.

atom_index: list#
bonds: list#
cell_description: str#
cell_matrix: ndarray[tuple[Any, ...], dtype[int64]]#
property is_gamma: bool#
property is_midpoint: bool#

Whether the point is a segment midpoint of --all-irreps.

lattice: ndarray[tuple[Any, ...], dtype[float64]]#
modes: list#
name: str#
notes: list#
polyhedra: list#
positions: ndarray[tuple[Any, ...], dtype[float64]]#
q: list#
segment: str | None = None#
symbols: list#
translations: ndarray[tuple[Any, ...], dtype[int64]]#
x: float | None#
class crystod.phonon.WyckoffOrbit(element, wyckoff, multiplicity, atoms, irreps)[source]#

Bases: object

The Gamma irreps carried by one orbit of equivalent atoms.

Variables:
  • element (str) – Chemical symbol of the orbit.

  • wyckoff (str) – Wyckoff letter (spglib, standard setting).

  • multiplicity (int) – Multiplicity of the Wyckoff position (in the conventional cell).

  • atoms (tuple[int, ...]) – 1-based indices of the orbit’s atoms in the primitive cell of the analysis.

  • irreps (tuple[tuple[str, int], ...]) – (label, copies) pairs: the decomposition of the displacement representation of the orbit at Gamma.

atoms: tuple[int, ...]#
element: str#
irreps: tuple[tuple[str, int], ...]#
multiplicity: int#
wyckoff: str#
crystod.phonon.build_symmetry_adapted_modes(phonon, qpoint, symprec=1e-05)[source]#

Symmetry-adapted eigenvectors of the dynamical matrix at q.

The dynamical matrix is block-diagonalized in the spgrep irrep-projected basis of the primitive cell, so that the partners of a degenerate level transform with the irrep matrices instead of coming out as the arbitrary linear combinations a plain eigensolver returns – the solver shared with crystod-phonon --modulation (crystod.symmetry_adapted_modes.solve_symmetry_adapted_modes()). crystod-phonon --vector exports these vectors as VESTA arrows. The result is verified against the plain phonopy solution: the frequencies must match, every vector must be an eigenvector of the dynamical matrix, and the vectors must be orthonormal. At a time-reversal-invariant q (2q a reciprocal lattice vector) the partners of a degenerate level are real displacement patterns (e_j exp(2 pi i q.x_j) real).

Parameters:
  • phonon – A phonopy.Phonopy object with force constants, built with primitive_matrix="auto"; its primitive cell is used as-is (no standardization), so that the projected basis and the dynamical matrix share one phase convention.

  • qpoint (list[float]) – Fractional coordinates of q in the primitive reciprocal basis.

  • symprec (float) – Symmetry tolerance of the spglib/spgrep analysis.

Returns:

List of (frequency_THz, mode_vector) sorted by frequency (negative for imaginary modes); mode_vector has 3 * n_atoms complex components in the mass-weighted phonopy convention (atom-position phase), as phonopy’s own eigenvectors.

Raises:
  • ValueError – If the primitive cell of phonon is not primitive (crystod.symmetry_adapted_modes.NonPrimitiveCellError).

  • RuntimeError – If the construction cannot reproduce the phonopy spectrum (the projection does not span the vibration space, or the symmetry analysis does not match the dynamical matrix).

Return type:

list[tuple[float, ndarray[tuple[Any, …], dtype[complex128]]]]

Example

>>> from crystod import phonon
>>> # ph: the SrTiO3 object of the label_phonon_modes example
>>> modes = phonon.build_symmetry_adapted_modes(ph, [0.5, 0.5, 0.5])
>>> [round(frequency, 4) for frequency, _ in modes[:4]]
[-1.0867, -1.0867, -1.0867, 3.9891]
>>> modes[0][1].shape
(15,)
crystod.phonon.classify_gamma_irreps(rotations, characters)[source]#

IR and Raman multiplicities of irrep blocks at Gamma, from characters.

Parameters:
  • rotations – The point-group rotations at Gamma, shape (n_ops, 3, 3), integer matrices in any lattice basis (only tr R and tr R^2 are used, which do not depend on the basis); the rotation parts of the space-group operations of a primitive cell.

  • characters – The characters of the blocks over the same ordered list of rotations: one vector of length n_ops (a single block) or an array of shape (n_blocks, n_ops); complex values allowed.

Returns:

One Activity per block with n_ir, n_raman and dimension filled (acoustic is False; the caller decides it, since the acoustic modes share their irreps with IR-active ones).

Raises:

ValueError – If the shapes do not match, or a multiplicity is not a non-negative integer (the characters are not those of a representation of these rotations).

Return type:

list[Activity]

Example

>>> import numpy as np
>>> from crystod.phonon_activity import classify_gamma_irreps
>>> rotations = [np.eye(3, dtype=int), -np.eye(3, dtype=int)]   # -1
>>> [a.activity for a in classify_gamma_irreps(rotations, [[1, 1], [1, -1]])]
[('Raman',), ('IR',)]
crystod.phonon.commensurate_qpoints(phonon)[source]#

q points of the primitive cell commensurate with the phonon supercell.

These are exactly the q points a supercell calculation resolves (the ones that fold onto Gamma of the supercell): for a supercell matrix S in the primitive basis, the det(S) distinct vectors m @ inv(S).T modulo reciprocal-lattice translations. crystod-phonon --subgroup without --qpoint scans this set.

Parameters:

phonon – A phonopy.Phonopy object; only its primitive cell and supercell are read.

Returns:

List of (q1, q2, q3) tuples in fractional coordinates of the primitive reciprocal basis, snapped to exact fractions and sorted by length, so that Gamma comes first.

Raises:

ValueError – If the supercell is not an integer multiple of the primitive cell.

Example

>>> from crystod import phonon
>>> qpoints = phonon.commensurate_qpoints(ph)   # ph: 4x4x4 supercell
>>> len(qpoints), qpoints[0], qpoints[1]
(64, (0.0, 0.0, 0.0), (0.0, 0.0, 0.25))
crystod.phonon.dielectric_response(phonon, activities=None, *, lst_direction=(1, 0, 0))[source]#

Mode effective charges and the static dielectric tensor at Gamma.

For every degenerate set the oscillator strength S_{alpha beta} = sum_m Z~_{m,alpha} Z~_{m,beta} and its contribution Delta eps = C S / (Omega nu^2) to the static dielectric tensor, with Omega the primitive-cell volume (Angstrom^3), nu the frequency (THz) and C = e^2 / (eps_vac amu) / (Angstrom^3 (2 pi THz)^2) = 4.4225e4 (DIELECTRIC_FACTOR, for S in e^2/amu); eps_0 = eps_inf + sum over the optical bands. The acoustic bands of a set (the n largest rigid-translation weights, n their rounded sum) are left out. Also the acoustic sum rule of the Born charges and the Lyddane-Sachs-Teller check (DielectricResponse).

Parameters:
  • phonon – A phonopy.Phonopy object with force constants, loaded with the NAC parameters (is_nac=True and a BORN file).

  • activities – The Activity records of the Gamma sets from the same irreps run (phonon.irreps still at Gamma); computed with gamma_mode_activities() when omitted.

  • lst_direction – Direction of q -> 0 (reduced reciprocal coordinates) for the Lyddane-Sachs-Teller check; None skips it.

Returns:

A DielectricResponse.

Raises:

ValueError – If phonon carries no Born effective charges.

Return type:

DielectricResponse

Example

>>> import phonopy
>>> from crystod import phonon
>>> ph = phonopy.load(unitcell_filename="221_PPOSCAR_ScF3",
...     force_sets_filename="FORCE_SETS", born_filename="BORN",
...     supercell_matrix=[4, 4, 4], primitive_matrix="auto", is_nac=True)
>>> response = phonon.dielectric_response(ph)
>>> round(float(response.eps_static[0, 0]), 3), round(response.lst[1], 3)
(7.592, 3.324)
crystod.phonon.displacement_irrep_arrangements(cell=None, elements=(), irreps=(), *, symprec=1e-05, coefficients=None, classify=True, vibrations=None, order_parameter=None, copies=None, conventional=False, amplitude=0.1, poscar_name='POSCAR')[source]#

The displacement patterns of given irreps on a crystal.

The computation behind crystod-phonon -c POSCAR --element EL [EL2 ...] --irrep IR [IR2 ...]: for every row of the table of crystod-group --parent SG --irrep IR [IR2 ...] (one irrep: its table; several: the coupled table, every irrep condensed) the displacement pattern of the atoms of the chosen elements that the row’s order parameter describes (see the module docstring), with the space group of the displaced structure identified again with spglib. The patterns are symmetry adapted, not eigenvectors of a dynamical matrix.

Parameters:
  • cell – The crystal (phonopy PhonopyAtoms, a primitive cell); not needed when vibrations is given.

  • elements – The elements whose atoms move (["O"], ["La", "O"]).

  • irreps – ISO-IR labels (["X3-"], ["X3-", "X2+"]; pair labels such as GM2+GM3+ accepted, as with --parent).

  • symprec (float) – Symmetry tolerance (spglib, Angstrom); also the tolerance of the check on the displaced structure.

  • coefficients – The weight of every irrep’s part (each part has its largest displacement 1 before weighting); default per row 1 each, or the first of 1 : 0.5, 1 : 0.75, … under which no displacement cancels between the parts.

  • classify (bool) – Identify the space group of every displaced structure.

  • vibrations – A prebuilt SymmetryOnlyVibrations(cell, standardize=False).

  • order_parameter – --order-parameter tokens (irrep after irrep); one pattern, of that vector, instead of one per row.

  • copies – One copy number (from 1) per irrep (--copies).

  • conventional (bool) – Write the patterns in the conventional cell (the cell of crystod-mag --irrep --conventional).

  • amplitude (float) – The largest displacement of the written structures (Angstrom).

  • poscar_name (str) – The name of the input POSCAR (the base of the file names M<name>_... and S<name>_...).

Returns:

A DisplacementIrrepAnalysis.

Raises:

ValueError – An element not in the cell, an unknown or repeated irrep, an irrep the displacement representation of the elements does not contain (the message lists the decomposition at its k point), a supercell larger than the limits of the magnetic mode, a cell that is not primitive, a wrong --order-parameter, a zero, nan or too small weight, a non-positive amplitude.

Return type:

DisplacementIrrepAnalysis

crystod.phonon.displacement_irrep_survey(cell=None, elements=(), *, symprec=1e-05, vibrations=None)[source]#

The irreps of the atomic displacements at every special k point.

The computation behind crystod-phonon -c POSCAR --element EL [EL2 ...] (no --irrep, no --qpoint): the decomposition of the displacement (polar-vector) representation of the atoms of the elements at every special k point of the irrep tables (the points the crystod-mag survey and crystod --orbital p list), by the function the headers of the --irrep and --qpoint forms use. p orbitals transform as polar vectors, so every line equals crystod -c POSCAR --element EL --orbital p up to the order of the terms, except that a complex irrep and its conjugate at a time-reversal-invariant point are one term under their pair label (A1A3(2) for A1(1) + A3(1), as in the headers and the crystod-mag survey), where crystod lists both.

Parameters:
  • cell – The crystal (phonopy PhonopyAtoms, a primitive cell); not needed when vibrations is given.

  • elements – The elements whose atoms move.

  • symprec (float) – Symmetry tolerance (spglib, Angstrom).

  • vibrations – A prebuilt SymmetryOnlyVibrations(cell, standardize=False).

Returns:

A DisplacementSurvey.

Raises:

ValueError – No element, an element given twice or not in the cell, a cell that is not primitive.

Return type:

DisplacementSurvey

Example

>>> from phonopy.interface.vasp import read_vasp
>>> from crystod import phonon
>>> cell = read_vasp("example/04-01_phonon_irrep/La3Ni2O7/PPOSCAR_La3Ni2O7_I4mmm")
>>> survey = phonon.displacement_irrep_survey(cell, ["O"])
>>> [name for name, _, _ in survey.kpoints]
['GM', 'X', 'M', 'N', 'P']
crystod.phonon.domain_average(child_phonon, mapping, kpoints, *, parent_rotations=None, child_rotations_parent=None, degeneracy_tolerance=0.0001)[source]#

Average the unfolded spectrum over every arm of the star of each k.

The average over the |G_parent| / |G_child| orientation domains of the child (a twinned crystal): all arms of the star of each k are unfolded; arms related by a child operation or by time reversal form a class (arm_orbits()) and the first arm of each class carries the weight m / n of its m arms out of n. The arms of one class are all unfolded and compared (orbit_spectral_max_deviation).

Return type:

DomainAverage

crystod.phonon.find_parent_mapping(child_poscar, parent_poscar, *, child_cell=None, parent_cell=None, trans_mat=None, tolerance=0.01, max_displacement=1.8)[source]#

The setting of crystod-group, converted to the unfolding cells, with the atom map.

crystod.symmetry_mode.SymmetryModeAnalysis(parent, child, tolerance) (the analysis of crystod-group --supergroup-cif PARENT --subgroup-cif CHILD) gives the transformation (P, p) between the two input files; with the phonopy primitive matrices Pc, Pp of the unfolding cells (A_prim = P.T @ A_file) it becomes M0 = Pc.T @ P.T @ inv(Pp.T) and p0 = inv(Pp) @ p. trans_mat chooses another of the equivalent settings: it must be M0 @ W.T for a rotation W of an operation (W, w) of the parent, and the origin becomes W @ p0 + w.

Parameters:
  • child_poscar (str) – The two structure files.

  • parent_poscar (str) – The two structure files.

  • child_cell – The unfolding cells (default: the cells of the files reduced as load_unfold_inputs() does).

  • parent_cell – The unfolding cells (default: the cells of the files reduced as load_unfold_inputs() does).

  • trans_mat – None, or nine integers row-wise, A_child = T @ A_parent (the crystod-bz --trans-mat convention) relative to the unfolding cells.

  • tolerance (float) – Symmetry tolerance of the analysis (crystod-group’s 0.01), in (0, 0.5] Angstrom.

  • max_displacement (float) – Largest accepted displacement (Angstrom).

Returns:

ParentMapping.

Raises:

SystemExit – crystod-group cannot relate the structures, spglib fails at tolerance (far below the round-off of the cells, e.g. 1e-16), or trans_mat is not an equivalent setting (ValueError through crystod.phonon).

Return type:

ParentMapping

crystod.phonon.find_star_representative(qpoint, rotations, q_names, q_list)[source]#

Map a q point onto the tabulated arm of its star.

The ISO-IR tables list only one representative arm per special point (e.g. only (1/2, 1/2, 0) for the three M arms of Pm-3m), so a direct coordinate lookup fails for the other arms. Some space-group rotation R sends q onto a tabulated point when q @ R equals it modulo reciprocal-lattice translations; the spectra of star arms coincide band by band, so the labels read at the representative apply to the modes at q. This is how crystod-phonon --irreps/--vector and label_phonon_modes() label a non-representative arm.

Parameters:
  • qpoint (list[float] | ndarray[tuple[Any, ...], dtype[float64]]) – Fractional coordinates of q in the primitive reciprocal basis.

  • rotations (ndarray[tuple[Any, ...], dtype[int64]]) – Rotation parts of the space-group operations, shape (n_ops, 3, 3), in the same (primitive) basis as qpoint and the tabulated points.

  • q_names (list[str]) – Labels of the tabulated special points.

  • q_list (list[list[float]]) – Their coordinates, as returned by get_irt_special_points().

Returns:

(label, representative_q) for the first tabulated point some rotation maps q onto, or None when q lies in no tabulated star.

Return type:

tuple[str, list[float]] | None

Example

>>> from crystod import phonon
>>> from crystod.runtime_compat import get_symmetry_dataset
>>> names = ["GM", "R", "X", "M"]
>>> points = [[0, 0, 0], [0.5, 0.5, 0.5], [0, 0.5, 0], [0.5, 0.5, 0]]
>>> # ph: a phonopy.Phonopy object of cubic SrTiO3 (Pm-3m)
>>> rotations = get_symmetry_dataset(ph.primitive_symmetry)["rotations"]
>>> phonon.find_star_representative([0.5, 0, 0], rotations, names, points)
('X', [0, 0.5, 0])
crystod.phonon.format_activity_summary(activities, *, symmetry_only=False, mulliken=None)[source]#

One-line summary of the Gamma activities, counted per irrep label.

"GM4- x4 (3 IR, 1 acoustic), GM5- x1 (silent)": each label with the number of times it occurs, then how many of those are acoustic and what the optical ones are (IR, Raman, IR+Raman, silent). A set holding several irreps counts per irrep through its Activity.parts (each copy with its own kind); without parts it counts once under each of its labels with the set’s activity. An unlabeled set appears as ?. The labels appear in the order of their first appearance (band order of the sets; inside a set holding several irreps, the labeler’s order).

Parameters:
  • activities – Activity records, e.g. from gamma_mode_activities().

  • symmetry_only (bool) – The records are mode spaces without force constants (--vibration): the acoustic sets are not identified among them, and the count of each label in the vector representation (n_ir) is reported as acoustic.

  • mulliken – Optional {label: Mulliken symbol} map (mulliken_symbols()); each label found in it is followed by its symbol in square brackets ("GM4- [T1u] x4 (...)").

Returns:

The summary string.

Return type:

str

Example

>>> from crystod.phonon_activity import Activity, format_activity_summary
>>> t1u = Activity(n_ir=1, n_raman=0, dimension=3, labels=("GM4-",))
>>> t2u = Activity(n_ir=0, n_raman=0, dimension=3, labels=("GM5-",))
>>> format_activity_summary([t1u] * 4 + [t2u], symmetry_only=True)
'GM4- x4 (3 IR, 1 acoustic), GM5- x1 (silent)'
crystod.phonon.format_dielectric_table(response)[source]#

The lines crystod-phonon --irreps --nac prints after the activity summary: one row per Gamma set (irrep, frequency, activity, |Z~|, the diagonal of Delta eps), the diagonals of eps_inf, of the sum of the contributions and of eps_0, a note when imaginary optical modes with a dipole contribute (with a negative sign), the acoustic sum rule of the Born charges and the Lyddane-Sachs-Teller check.

Parameters:

response (DielectricResponse) – The DielectricResponse.

Returns:

The lines.

Return type:

list[str]

crystod.phonon.format_mode_resolved_fc(results)[source]#

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.

Parameters:

results (list[ModeForceConstants]) – The q points, as survey_mode_resolved_fc() returns.

Returns:

The lines (blank lines and the * Title * lines included).

Return type:

list[str]

crystod.phonon.format_raman_tensors(records, *, mulliken=None)[source]#

The lines --raman-tensor prints.

Parameters:
Returns:

A header line and one line per irrep, or the line saying that no Gamma phonon is Raman active. An irrep with RamanTensors.partners gets one tensor per partner with the constants a, b, ... shared across them; any other irrep its basis tensors side by side, each with its own free constant a.

Return type:

list[str]

crystod.phonon.format_wyckoff_orbits(orbits, mode_space_labels, *, mulliken=None)[source]#

The lines of the Wyckoff-orbit breakdown of --vibration --qpoint GM.

Parameters:
  • orbits – WyckoffOrbit records.

  • mode_space_labels – The labels of the mode spaces ("GM4-(3)" or without the suffix), one per space.

  • mulliken – Optional {label: Mulliken symbol} map (mulliken_symbols()); in the orbit lines each label found in it is followed by its symbol in square brackets ("GM1 [A1]").

Returns:

One line per orbit and a check line comparing the summed decomposition with the mode-space list.

Return type:

list[str]

crystod.phonon.gamma_mode_activities(phonon_or_cell, *, degeneracy_tolerance=0.001, symprec=1e-05)[source]#

IR / Raman / silent / acoustic activity of the Gamma-point phonons.

The library form of the activity lines of crystod-phonon --irreps (from force constants) and crystod-phonon --vibration --qpoint GM (from the structure alone).

Parameters:
  • phonon_or_cell – A phonopy.Phonopy object with force constants (one record per degenerate set, acoustic sets flagged), or a crystal structure – a phonopy.structure.atoms.PhonopyAtoms or a POSCAR path – (one record per mode space of --vibration). A primitive structure is analysed on its own axes; any other is first reduced to the spglib primitive cell (the activities do not depend on the axes).

  • degeneracy_tolerance (float) – Frequency tolerance (THz) of the degenerate sets (force-constant route; --tolerance of --irreps).

  • symprec (float) – Symmetry tolerance of the structure-only route.

Returns:

A list of Activity; format_activity_summary() turns it into the one-line summary the commands print.

Raises:
  • RuntimeError – If the modes at Gamma cannot be labeled (force-constant route).

  • ValueError – If the structure cannot be read.

Return type:

list[Activity]

Example

>>> import phonopy
>>> from crystod import phonon
>>> from crystod.examples import example_path
>>> ph = phonopy.load(
...     unitcell_filename=example_path("221_PPOSCAR_SrTiO3"),
...     force_sets_filename=example_path("FORCE_SETS_SrTiO3"),
...     supercell_matrix=[4, 4, 4], primitive_matrix="auto", is_nac=False)
>>> activities = phonon.gamma_mode_activities(ph)
>>> [(a.labels, a.activity) for a in activities][:2]
[(('GM4-',), ('acoustic',)), (('GM4-',), ('IR',))]
>>> phonon.format_activity_summary(activities)
'GM4- x4 (3 IR, 1 acoustic), GM5- x1 (silent)'
crystod.phonon.gamma_origin(child_phonon, mapping, *, irreps=None, parent_phonon=None, path=None, weight_min=0.02, degeneracy_tolerance=0.0001)[source]#

Where the child Gamma modes come from: their weights at the parent k folding onto K = 0.

The child eigenvectors are computed once at K = 0 and unfolded onto each of the N parent k with M k integer (explicit G phase), so mode J is the same vector at every k and sum_k P_J(k) = 1; then, at each k, the modes of a degenerate level are rotated canonically (as along the path), which keeps the level sums sum_k P_g(k) = n_g and makes the weights basis independent. With irreps (from irrep_resolve()) every child level gets its parent label at each k; with parent_phonon the unstable parent levels are followed into the child: c_g(S) = sum_{J in g} sum_{s in S} |<e_s(k)|u_J(k)>|^2.

Parameters:
  • child_phonon – As for unfold().

  • mapping (ParentMapping) – As for unfold().

  • irreps – UnfoldedIrreps (its basis is reused), or None.

  • parent_phonon – phonopy.Phonopy of the parent, or None.

  • path – The ParentPath (marks the folding k on the path), or None.

  • weight_min (float) – Labels below it are '-'.

  • degeneracy_tolerance (float) – THz, degenerate child levels.

Returns:

GammaOrigin.

Return type:

GammaOrigin

crystod.phonon.gamma_raman_tensors(phonon_or_cell, *, symprec=1e-05)[source]#

Raman tensors of the Raman-active Gamma phonon irreps.

For every irrep that occurs among the Gamma phonons and in the symmetric square of the vector representation, the basis of the symmetric second-rank tensors that transform as that irrep, in the Cartesian axes of the input cell (the polarizability derivative of a mode of the irrep is a combination of them); for an irrep of dimension >= 2 that occurs more than once (E of the trigonal point groups) also the tensor of each partner with constants shared across the partners (RamanTensors.partners). The irreps and their ISO-IR labels are those of --irreps / --vibration; the rotations are the point-group operations of a primitive cell with the axes of the input cell, R = L^T W (L^T)^-1 with L the lattice vectors as rows.

Parameters:
  • phonon_or_cell – A phonopy.Phonopy object (its primitive cell keeps the axes of the input unit cell), or a crystal structure – a phonopy.structure.atoms.PhonopyAtoms or a POSCAR path.

  • symprec (float) – Symmetry tolerance of the structure route.

Returns:

One RamanTensors per Raman-active irrep, in label order; empty when no Gamma phonon is Raman active (cubic perovskites).

Return type:

list[RamanTensors]

Example

>>> from crystod import phonon
>>> records = phonon.gamma_raman_tensors("227_PPOSCAR_Si")   # diamond Si
>>> [(record.label, len(record.tensors)) for record in records]
[('GM5+', 3)]
>>> print(phonon.format_raman_tensors(records)[1])
  GM5+ (3 tensors):  [[0, 0, 0], [0, 0, a], [0, a, 0]]   [[0, 0, a], [0, 0, 0], [a, 0, 0]]   [[0, a, 0], [a, 0, 0], [0, 0, 0]]
crystod.phonon.get_commensurate_supercell_matrix(qpoint, base_matrix)[source]#

Smallest diagonal multiple of base_matrix commensurate with q.

crystod-phonon --vector draws a mode on the smallest supercell over which its Bloch phase is periodic: each base-cell axis is multiplied by the denominator of the corresponding component of q in the base reciprocal basis (denominators up to 12).

Parameters:
  • qpoint (list[float]) – Fractional coordinates of q in the primitive reciprocal basis.

  • base_matrix (ndarray[tuple[Any, ...], dtype[int64]]) – Rows are the base-cell (primitive or conventional) lattice vectors in the primitive basis: the identity for the primitive cell, or the matrix of get_conventional_matrix for the conventional cell.

Returns:

Integer matrix S whose rows are the supercell lattice vectors in the primitive basis (L_super = S @ L_primitive), satisfying q . S_row in Z for every row.

Return type:

ndarray[tuple[Any, …], dtype[int64]]

Example

>>> import numpy as np
>>> from crystod import phonon
>>> base = np.eye(3, dtype=int)
>>> phonon.get_commensurate_supercell_matrix([0.0, 0.5, 0.0], base)
array([[1, 0, 0],
       [0, 2, 0],
       [0, 0, 1]])
crystod.phonon.get_irrep_labels(q, phonon, irt_table, prim_mat, degeneracy_tolerance)[source]#

Irrep labels, band indices, and frequencies of the phonon modes at q.

The labeling step of crystod-phonon --irreps: phonopy’s character analysis (Phonopy.set_irreps) groups the bands at q into degenerate sets and computes their characters, and each set is decomposed against the ISO-IR (ISOTROPY) small irreps of q by the ISO-IR labeller, with Miller-Love labels, at a special point as on a symmetry line or plane or at a generic q, in the ISO-IR frame of the input cell; a q point tabulated only through its -k partner gets the ‘A’ names (PA1). Only at a tabulated special point, a set the labeller cannot decompose falls back on the direct character overlap with the special-point table (a set is labeled when the overlap exceeds 0.9). For a non-representative arm of a star, map q onto the tabulated arm with find_star_representative() first; label_phonon_modes() does both steps in one call.

Parameters:
  • q (list[float]) – Fractional coordinates of q in the primitive reciprocal basis, as tabulated (the representative arm of its star).

  • phonon – A phonopy.Phonopy object with force constants, built with primitive_matrix="auto".

  • irt_table – ISO-IR irrep table of the space group (see get_irt_special_points()).

  • prim_mat – Conventional-to-primitive matrix of the centring.

  • degeneracy_tolerance (float) – Frequency tolerance (THz) within which bands count as degenerate; --tolerance of crystod-phonon --irreps (default 1e-3).

Returns:

one entry of labels per degenerate set, each a list of "R4+(3)"-style labels (the irrep name with its dimension) or None when no tabulated irrep matched; band_indices the 0-based band indices of each set; and frequencies the THz frequencies of all bands at q.

Return type:

(labels, band_indices, frequencies)

Raises:

ValueError – If the q point can be labeled from neither table.

Example

>>> from phonopy.structure.cells import get_primitive_matrix_by_centring
>>> from crystod import phonon
>>> from crystod.irreptables_compat import load_irreptables
>>> IrrepTable, _ = load_irreptables()
>>> table = IrrepTable(221, spinor=False)          # ph: cubic SrTiO3
>>> prim_mat = get_primitive_matrix_by_centring("P")
>>> labels, bands, freqs = phonon.get_irrep_labels(
...     [0.5, 0.5, 0.5], ph, table, prim_mat, 1e-3)
>>> labels[0], bands[0], round(float(freqs[0]), 4)
(['R5-(3)'], [0, 1, 2], -1.0867)
crystod.phonon.get_irt_special_points(irt_table, prim_mat)[source]#

Unique special q points of the ISO-IR tables, in the primitive basis.

The ISO-IR tables list their irreps per special k point in the conventional reciprocal basis; this collects the distinct points, converts them to the primitive basis of the phonopy object, and returns them in table order. crystod-phonon --irreps surveys exactly these points. Coordinates are snapped to exact fractions (1/3 stays 1/3, not 0.333333): decimal-rounded values break the little-group detection and the ISO-IR table lookups downstream.

Parameters:
  • irt_table – ISO-IR irrep table of the space group, i.e. IrrepTable(number, spinor=False) with IrrepTable from crystod.irreptables_compat.load_irreptables().

  • prim_mat – Conventional-to-primitive matrix of the centring, e.g. phonopy.structure.cells.get_primitive_matrix_by_centring("P").

Returns:

the k-point labels ("GM", "R", …) and their fractional coordinates in the primitive reciprocal basis, in the order of the tables (Gamma first).

Return type:

(q_names, q_list)

Example

>>> from phonopy.structure.cells import get_primitive_matrix_by_centring
>>> from crystod import phonon
>>> from crystod.irreptables_compat import load_irreptables
>>> IrrepTable, _ = load_irreptables()
>>> table = IrrepTable(221, spinor=False)          # Pm-3m
>>> prim_mat = get_primitive_matrix_by_centring("P")
>>> names, points = phonon.get_irt_special_points(table, prim_mat)
>>> names
['GM', 'R', 'X', 'M']
>>> points[1]
[0.5, 0.5, 0.5]
crystod.phonon.get_longitudinal_ratio(qpoints, eigenvectors, reciprocal_lattice)[source]#

Longitudinal character of every (q point, band) pair.

The character is sqrt(sum over atoms of |q_hat . e_atom|^2), with q_hat the unit propagation vector and e_atom the three components of the normalized eigenvector on that atom: 1 for a purely longitudinal mode, 0 for a purely transverse one. At the Gamma point no propagation direction exists and the neutral value 0.5 is returned. crystod-phonon --lt colors each band of the band structure by this quantity (red = longitudinal, blue = transverse).

Parameters:
  • qpoints (ndarray[tuple[Any, ...], dtype[float64]]) – Fractional q coordinates along the path, shape (n_q, 3).

  • eigenvectors (ndarray[tuple[Any, ...], dtype[complex128]]) – Eigenvectors of the dynamical matrix, shape (n_q, 3 * n_atoms, n_bands) with the bands in columns, as phonopy returns them (run_qpoints(..., with_eigenvectors=True) or a band structure computed with eigenvectors).

  • reciprocal_lattice (ndarray[tuple[Any, ...], dtype[float64]]) – Reciprocal lattice vectors as rows, used only for the direction of q (with or without the 2 pi factor).

Returns:

Array of shape (n_q, n_bands) with the longitudinal character in [0, 1].

Return type:

ndarray[tuple[Any, …], dtype[float64]]

Example

>>> import numpy as np
>>> from crystod import phonon
>>> from crystod.runtime_compat import get_qpoints_result
>>> qpoints = np.array([[0.0, 0.0, 0.0], [0.25, 0.0, 0.0], [0.5, 0.0, 0.0]])
>>> ph.run_qpoints(qpoints, with_eigenvectors=True)   # ph: cubic SrTiO3
>>> eigenvectors = np.array(get_qpoints_result(ph).eigenvectors)
>>> reciprocal = np.linalg.inv(np.array(ph.primitive.cell)).T
>>> ratio = phonon.get_longitudinal_ratio(qpoints, eigenvectors, reciprocal)
>>> ratio.shape                                       # 15 bands
(3, 15)
crystod.phonon.imaginary_mode_subgroups(phonon, qpoint=(0.0, 0.0, 0.0), *, threshold=-0.1, degeneracy_tolerance=0.0001, with_settings=True)[source]#

Isotropy subgroups of every imaginary phonon level at qpoint.

The symmetry-lowering step of a structure search, and the API form of crystod-phonon --subgroup --qpoint: every degenerate level with frequency below threshold is labeled with label_phonon_modes(), and the isotropy subgroups of its irrep are enumerated with isotropy_subgroups(), covering all order-parameter directions, including the ones a single frozen-in modulation would miss. The acoustic modes at Gamma (uniform translations, at zero frequency) are skipped whatever the threshold: freezing them in moves the crystal and lowers no symmetry.

Parameters:
  • phonon – A live phonopy.Phonopy object with force constants, built with primitive_matrix="auto" (see label_phonon_modes()).

  • qpoint – Fractional coordinates of q in the primitive reciprocal basis.

  • threshold (float) – Frequency (THz) below which a level counts as imaginary; the -0.1 default matches the instability criterion of structure-search workflows.

  • degeneracy_tolerance (float) – Frequency tolerance (THz) within which bands count as degenerate.

  • with_settings (bool) – Also compute the conventional basis/origin of every subgroup (see isotropy_subgroups()).

Returns:

List of ImaginaryModeResult, one per imaginary level in band order. A level that could not be labeled, or whose irrep has no tabulated subgroups, yields a result with empty subgroups and the reason in errors; an empty list means no level lies below threshold.

Raises:

RuntimeError – If the q point cannot be labeled at all (from label_phonon_modes()).

Example

>>> from crystod import phonon
>>> # ph: the SrTiO3 object of the label_phonon_modes example
>>> for result in phonon.imaginary_mode_subgroups(ph, [0.5, 0.5, 0.5]):
...     print(result.mode)
...     for sub in result.subgroups:
...         print("   ", sub.label, "->", sub.symbol)
modes 1,2,3: -1.0867 THz  R5-
    R5-(0,0,a) -> I4/mcm
    R5-(a,a,a) -> R-3c
    R5-(0,a,a) -> Imma
    R5-(0,a,b) -> C2/m
    R5-(a,a,b) -> C2/c
    R5-(a,b,c) -> P-1
crystod.phonon.irrep_resolve(bands, mapping, *, path=None, parent_phonon=None, weight_min=0.02, degeneracy_tolerance=0.0001, symprec=1e-05)[source]#

Resolve unfolded bands by the irreps of the parent; label every degenerate group.

Parameters:
  • bands – crystod.phonon_unfold.UnfoldedBands.

  • mapping – The crystod.phonon_unfold.ParentMapping.

  • path – The crystod.phonon_unfold.ParentPath of bands (its straight runs reuse the ISO-IR names); None labels every k directly.

  • parent_phonon – phonopy.Phonopy of the parent (primitive cell = mapping.parent_cell) for the parent levels, or None.

  • weight_min (float) – Groups with P_g below it get the label '-'.

  • degeneracy_tolerance (float) – THz, degenerate groups of child (and parent) modes.

  • symprec (float) – spglib tolerance of the symmetry analysis.

Returns:

UnfoldedIrreps.

Raises:

SystemExit – A projector identity fails (an internal error).

Return type:

UnfoldedIrreps

crystod.phonon.isotropy_subgroups(space_group, irrep, order_parameter=None, *, with_settings=True)[source]#

Isotropy subgroups of a space-group irrep, as data.

Programmatic counterpart of crystod-group --parent: the order-parameter directions of the irrep (or of the coupled order parameter of several irreps) are enumerated with crystod.group.IsotropyAnalyzer, and each direction is returned with the space group it condenses into. No phonopy object is needed; the function is also exported as crystod.group.isotropy_subgroups.

Parameters:
  • space_group (str | int) – International short symbol (e.g. "Pm-3m") or number (e.g. 221) of the parent.

  • irrep (str | list[str]) – ISO-IR irrep label (e.g. "R4+"); a list of labels enumerates the subgroups of the coupled order parameter.

  • order_parameter (list[str] | None) – If given (e.g. ["a", "0", "0"]), resolve only this direction and return a single-element list. Components are plain numbers or parameter names; composite entries of the enumerated table such as "0.282a" are rejected.

  • with_settings (bool) – Also compute the conventional basis/origin of each subgroup in the parent convention (slightly slower; on by default).

Returns:

List of IsotropySubgroup, sorted like the --parent table (free components, index, subgroup number).

Raises:

ValueError – For an unknown space group, an irrep that is not tabulated for it (the labels of symmetry lines and planes, e.g. DT5, have no isotropy subgroups in the tables), or an invalid order parameter.

Example

>>> from crystod import phonon
>>> for sub in phonon.isotropy_subgroups("Pm-3m", "R4+"):
...     print(sub)
R4+(0,0,a) -> I4/mcm (No. 140), size 2, index 6
R4+(a,a,a) -> R-3c (No. 167), size 2, index 8
R4+(0,a,a) -> Imma (No. 74), size 2, index 12
R4+(0,a,b) -> C2/m (No. 12), size 2, index 24
R4+(a,a,b) -> C2/c (No. 15), size 2, index 24
R4+(a,b,c) -> P-1 (No. 2), size 2, index 48
>>> sub = phonon.isotropy_subgroups(221, "R4+", ["0", "0", "a"])[0]
>>> sub.symbol, sub.basis.tolist()
('I4/mcm', [[-1.0, 0.0, 1.0], [1.0, 0.0, 1.0], [0.0, 2.0, 0.0]])
crystod.phonon.isotropy_subgroups_at_kpoint(space_group, kpoint, *, with_settings=True)[source]#

Isotropy subgroups of every irrep of one special k point, as data.

Programmatic counterpart of crystod-group --parent SG --kpoint K: isotropy_subgroups() run over all irreps of the k point, in the order of the ISO-IR tables. No phonopy object is needed; the function is also exported as crystod.group.isotropy_subgroups_at_kpoint.

Parameters:
  • space_group (str | int) – International short symbol (e.g. "Pm-3m") or number (e.g. 221) of the parent.

  • kpoint (str | sequence) – The ISO-IR name of a special k point ("GM", "R", "X", …; the case is ignored and "G"/"GAMMA" mean "GM"), or its three coordinates in the primitive reciprocal basis (numbers, or strings such as "1/2"; a decimal within 0.0005 of a special point is taken for it). Coordinates may be those of any arm of the star and may differ from it by a reciprocal lattice vector. The names of a space group are the keys of crystod.group.SpaceGroupIrrepAlgebra(space_group).k_by_kname.

  • with_settings (bool) – Also compute the conventional basis/origin of each subgroup in the parent convention (slightly slower; on by default).

Returns:

a dict mapping every irrep label to its list of IsotropySubgroup records (each sorted like the --parent table), with the k-point name, its coordinates and the failed irreps as attributes. An irrep whose enumeration fails is reported in errors and does not stop the others.

Return type:

A crystod.group.KpointIsotropySubgroups

Raises:

ValueError – For an unknown space group, an unknown k-point name, or coordinates that are not a tabulated special point (symmetry lines and planes and general points have no isotropy subgroups in the tables); the message lists the k points of the space group.

Example

>>> from crystod import group
>>> table = group.isotropy_subgroups_at_kpoint("Pm-3m", "GM")
>>> list(table)
['GM1+', 'GM2+', 'GM3+', 'GM4+', 'GM5+', 'GM1-', 'GM2-', 'GM3-', 'GM4-', 'GM5-']
>>> for sub in table["GM3+"]:
...     print(sub)
GM3+(a,0) -> P4/mmm (No. 123), size 1, index 3
GM3+(a,b) -> Pmmm (No. 47), size 1, index 6
>>> table.kpoint, table.coordinates, table.n_arms, table.errors
('GM', [0.0, 0.0, 0.0], 1, {})
>>> group.isotropy_subgroups_at_kpoint(221, [0, 0.5, 0.5]).kpoint
'M'
crystod.phonon.label_phonon_modes(phonon, qpoint=(0.0, 0.0, 0.0), *, degeneracy_tolerance=0.0001)[source]#

ISO-IR irrep labels of the phonon modes of phonon at qpoint.

The API form of crystod-phonon --irreps for one q point: the ISO-IR table of the space group is loaded, q is mapped onto the tabulated arm of its star with find_star_representative() (the spectra of star arms coincide band by band), and the degenerate levels are labeled with get_irrep_labels(). The levels come back as PhononMode records with 1-based band indices.

Parameters:
  • phonon – A live phonopy.Phonopy object with force constants available (e.g. from phonopy.load), built with primitive_matrix="auto" so that a zone-boundary instability appears at its own q point instead of being folded onto the supercell Gamma point, where it cannot be labeled.

  • qpoint – Fractional coordinates of q in the primitive reciprocal basis; any arm of a star is accepted.

  • degeneracy_tolerance (float) – Frequency tolerance (THz) within which bands count as degenerate.

Returns:

List of PhononMode, one per degenerate level, ordered by band index; at Gamma each level carries its IR / Raman / silent / acoustic activity.

Raises:

RuntimeError – If the space-group tables cannot label this q point at all.

Example

>>> import phonopy
>>> from crystod import phonon
>>> from crystod.examples import example_path
>>> ph = phonopy.load(
...     unitcell_filename=example_path("221_PPOSCAR_SrTiO3"),
...     force_sets_filename=example_path("FORCE_SETS_SrTiO3"),
...     supercell_matrix=[4, 4, 4], primitive_matrix="auto")
>>> for mode in phonon.label_phonon_modes(ph, [0.5, 0.5, 0.5]):
...     print(mode)
modes 1,2,3: -1.0867 THz  R5-
modes 4,5,6: 3.9891 THz  R4-
modes 7,8,9: 11.6887 THz  R5+
modes 10,11,12: 12.6621 THz  R4-
modes 13,14: 14.8133 THz  R3-
modes 15: 23.2302 THz  R2-
crystod.phonon.load_unfold_inputs(child_poscar, child_dim, parent_poscar, parent_dim=None, *, child_readfc=False, parent_readfc=False)[source]#

Read the child and the parent: structures, primitive cells and force constants.

The child’s force file (FORCE_SETS, or FORCE_CONSTANTS with child_readfc) is looked up next to child_poscar, then in the working directory; the parent’s (only with parent_dim) next to parent_poscar only. In each place the per-structure name FORCE_SETS_<POSCAR file name> (macer’s name, e.g. FORCE_SETS_POSCAR_child) comes before FORCE_SETS, so that the two POSCARs can share one directory. Every phonopy.load runs inside an empty temporary working directory with absolute paths (phonopy would otherwise read a stray ./FORCE_CONSTANTS instead of the FORCE_SETS it is given).

Parameters:
  • child_poscar (str) – The child (low-symmetry) structure.

  • child_dim – Diagonal supercell of the child force calculation.

  • parent_poscar (str) – The parent (high-symmetry) structure.

  • parent_dim – Diagonal supercell of the parent force calculation, or None (no parent force data: no parent bands).

  • child_readfc (bool) – Read FORCE_CONSTANTS instead of FORCE_SETS.

  • parent_readfc (bool) – Read FORCE_CONSTANTS instead of FORCE_SETS.

Returns:

UnfoldInputs.

Raises:

SystemExit – A file is missing or unreadable, or child and parent would read the same force file (ValueError through crystod.phonon).

Return type:

UnfoldInputs

crystod.phonon.make_parent_path(mapping, *, band=None, band_labels=None, npoints=51, symprec=1e-05)[source]#

The band path of the parent zone along which the child phonons are unfolded.

Default: seekpath’s path of the parent primitive cell (the --fatband path), in the parent primitive basis (converted when seekpath’s standardized primitive cell is another basis). band: a manual path in the --band format, parent primitive fractional coordinates. The vertex labels are the ISO-IR names of the vertices in the parent unless band_labels gives one label per vertex.

Parameters:
  • mapping (ParentMapping) – The ParentMapping (parent cell, M, A_pp).

  • band (str | None) – Manual path, e.g. "0 0 0  0 1/2 0  1/2 1/2 0, 1/2 1/2 0  1/2 1/2 1/2".

  • band_labels (str | None) – Labels of every vertex of band, e.g. "GM X M M R".

  • npoints (int) – Points per leg (inclusive end points).

  • symprec (float) – seekpath tolerance.

Returns:

ParentPath.

Return type:

ParentPath

crystod.phonon.mode_effective_charges(phonon, eigenvectors=None, frequencies=None)[source]#

Mode effective charges of the Gamma phonons.

Z~_{m,alpha} = sum_{kappa beta} Z*_{kappa, alpha beta} e_m(kappa beta) / sqrt(M_kappa) with e_m the eigenvector of the dynamical matrix (the displacement is e / sqrt(M)), M in amu and Z* the Born effective charges of phonon.nac_params (phonopy’s convention: Z*[kappa, alpha, beta] with alpha the field and beta the displacement direction, atoms in the order of the primitive cell). The eigenvectors are made real first: the global phase of every eigenvector is fixed so that its largest component is real, and, when the frequencies are known, every degenerate subspace gets a real orthonormal basis (the dynamical matrix at Gamma is real), so that the charges are real and sum_m |Z~_m|^2 over a degenerate set does not depend on the eigenvectors phonopy chose inside it.

Parameters:
  • phonon – A phonopy.Phonopy object with force constants and NAC parameters (loaded with a BORN file).

  • eigenvectors – The Gamma eigenvectors as columns, shape (3 n_atoms, 3 n_atoms); phonon.irreps.eigenvectors when the irreps are set at Gamma, else computed (without the non-analytical term).

  • frequencies – The frequencies (THz) of eigenvectors, used to find the degenerate subspaces; taken with the eigenvectors when those are not given.

Returns:

The charges in e/sqrt(amu), shape (3 n_atoms, 3), in band order.

Raises:

ValueError – If phonon carries no Born effective charges.

Return type:

ndarray

crystod.phonon.mode_resolved_force_constants(phonon, q, *, irt_table=None, prim_mat=None, degeneracy_tolerance=0.001, q_label=None)[source]#

Mode- and irrep-resolved force constants at one q point.

Parameters:
  • 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 (float) – Frequency tolerance (THz) of the degenerate sets (--tolerance, default 1e-3).

  • q_label (str | None) – Name of q for the result ("GM", "R").

Returns:

ModeForceConstants with one ModeForceConstantSet per degenerate set and one 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 crystod.phonon_irreps.get_irrep_labels()).

Return type:

ModeForceConstants

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)
crystod.phonon.mulliken_symbols(source, *, symprec=1e-05)[source]#

Mulliken symbols of the Gamma irreps, keyed by their ISO-IR labels.

The point-group character tables of phonopy (phonopy.phonon.character_table, the ones phonopy’s own IrReps labels its Gamma modes with) name the ISO-IR Gamma irreps of the structure: the point-group rotations are carried to the conventional standard setting of spglib exactly as phonopy does it, each is assigned to its class through the mapping_table of the table, and the character of every irrep, averaged over each class, is compared with the rows of the table (tolerance 1e-3). The symbols therefore follow phonopy’s axis convention, the one of its own ir_label output: B1/B2 (and B1/B2/B3) refer to the axes of the conventional standard setting. A complex irrep and its conjugate, which together form one physically irreducible representation, both get the symbol of that representation (E of the point group 3, Eg of -3), and so does their combined label ("GM2GM3", the label of the Raman tensors of such a pair). An irrep no row matches is left out and a warning is issued; the function never raises for that reason.

Parameters:
  • source – A crystod.vibration_modes.SymmetryOnlyVibrations, a phonopy.Phonopy object (the irreps and labels of --irreps), or a crystal structure – a phonopy.structure.atoms.PhonopyAtoms or a POSCAR path.

  • symprec (float) – Symmetry tolerance of the structure route.

Returns:

{label: symbol} with the labels without the dimension suffix, e.g. {"GM1": "A1", "GM4": "B1", "GM5": "E2", "GM6": "E1", ...} for wurtzite ZnO; every Gamma irrep of the point group is a key, not only those that occur among the phonons.

Return type:

dict[str, str]

Example

>>> from crystod import phonon
>>> from crystod.examples import example_path
>>> symbols = phonon.mulliken_symbols(example_path("221_PPOSCAR_SrTiO3"))
>>> symbols["GM4-"], symbols["GM5-"]
('T1u', 'T2u')
crystod.phonon.parent_mapping_from_setting(child_cell, parent_cell, M, origin_shift, *, child_unitcell=None, parent_unitcell=None, max_displacement=1.8)[source]#

The atom map of the child onto the parent for a given setting (M, p).

No symmetry-mode analysis: the setting is taken as given. The ideal sites are the N copies of the parent atoms inside the child cell, inv(M.T) @ (x_parent[kappa] + t - p); the child atoms of each species are paired with them by the minimum total squared displacement (Hungarian algorithm, minimum image in the child lattice); the pairing is validated (every parent atom owns N child atoms of its species in N distinct cosets, one common origin shift, every parent translation permutes the ideal sites).

Parameters:
  • child_cell – The child unfolding cell (PhonopyAtoms).

  • parent_cell – The parent primitive cell (PhonopyAtoms).

  • M – A_child = M @ A_parent (integer, det > 0).

  • origin_shift – p of x_parent = M.T x_child + p.

  • child_unitcell – Cells whose frames name the k points (default: the unfolding cells).

  • parent_unitcell – Cells whose frames name the k points (default: the unfolding cells).

  • max_displacement (float) – Largest accepted displacement (Angstrom).

Returns:

ParentMapping with source = 'given'.

Raises:

SystemExit – Atom counts that do not fit, or a displacement above max_displacement (ValueError through crystod.phonon).

Return type:

ParentMapping

crystod.phonon.phonon_viewer_data(phonon, *, irt_table=None, prim_mat=None, degeneracy_tolerance=0.001, band=None, band_labels=None, npoints=None, qpoint=None, conventional=False, bonds=None, threshold=-0.1, force_data=None, tolerance=1e-05, all_irreps=False)[source]#

Compute everything the phonon mode viewer shows.

Parameters:
  • phonon – phonopy.Phonopy object with force constants, built with primitive_matrix="auto" (as crystod-phonon --irreps).

  • irt_table – ISO-IR table of the space group and centring matrix (default: from the symmetry of phonon).

  • prim_mat – ISO-IR table of the space group and centring matrix (default: from the symmetry of phonon).

  • degeneracy_tolerance (float) – THz within which bands form one set.

  • band (str | None) – The path (--band, --band-labels, --npoints; default the seekpath path).

  • band_labels (str | None) – The path (--band, --band-labels, --npoints; default the seekpath path).

  • npoints (int | None) – The path (--band, --band-labels, --npoints; default the seekpath path).

  • tolerance (float) – The path (--band, --band-labels, --npoints; default the seekpath path).

  • qpoint (list[str] | None) – --qpoint tokens (one label or three coordinates) to show that point only; default every labeled special point of the path.

  • conventional (bool) – Display the conventional cell (times the multiples commensurate with q) instead of the primitive cell.

  • bonds (list[tuple[str, str, float]] | None) – [(el1, el2, max_length_A), ...]: bonds and the VESTA-style coordination polyhedra around el1.

  • threshold (float) – Frequency (THz) below which a level is drawn as imaginary.

  • force_data (str | None) – Name of the force data shown on the page.

  • all_irreps (bool) – Also show the midpoint of every segment of the path, as crystod-phonon --irreps --all-irreps labels it (the symmetry lines DT, Z, SM, …; --band: the midpoints of its legs), after the special points; the points get segment set. A midpoint equal to a special point or to an earlier midpoint is left out, and so is one whose display cell would hold more than LARGE_CELL_ATOMS atoms (with a note; qpoint draws it).

Returns:

The PhononViewer; write_phonon_viewer_html() writes it.

Raises:

ValueError – all_irreps together with qpoint, or an unknown qpoint label.

Return type:

PhononViewer

crystod.phonon.raman_tensor_basis(rotations_cartesian, character)[source]#

Basis of the symmetric second-rank tensors that transform as an irrep.

The character projector (d/|G|) sum_g conj(chi(g)) (R_g x R_g) on the six-dimensional space of symmetric tensors (T -> R T R^T) gives the isotypic subspace of the irrep, of dimension d * n_Raman; it is returned in the canonical basis of the sparsest tensors (see crystod-phonon --raman-tensor). A complex character is combined with its conjugate (the physically irreducible pair), which gives a real subspace.

Parameters:
  • rotations_cartesian – The point-group rotations in Cartesian coordinates, shape (n_ops, 3, 3) (orthogonal matrices).

  • character – The character of the irrep over the same rotations.

Returns:

The basis tensors as 3x3 arrays, each scaled so that its first nonzero component (in the order xx, yy, zz, yz, xz, xy) is 1; empty for a Raman-inactive irrep.

Raises:

ValueError – If a rotation is not orthogonal.

Return type:

list[ndarray]

Example

>>> import numpy as np
>>> from crystod.phonon_activity import raman_tensor_basis
>>> ops = [np.eye(3), np.diag([-1.0, -1.0, 1.0])]    # point group 2 (z)
>>> [t.tolist() for t in raman_tensor_basis(ops, [1, -1])]
[[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]], [[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]]
crystod.phonon.read_mode_resolved_fc(path)[source]#

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.

Parameters:

path – Path of the file.

Returns:

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 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).

Return type:

dict

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.

crystod.phonon.read_phonon_irreps(path)[source]#

Read a phonon_irreps.yaml or phonon_irreps_all.yaml file.

The file is the one crystod-phonon --irreps (--all-irreps) writes; this is yaml.safe_load of it, checked for the irreps list, so any YAML library reads the same data.

Parameters:

path – Path of the file.

Returns:

The file as a plain dictionary, with these keys:

  • space_group (str): Hermann-Mauguin symbol of the space group.

  • nac (bool): whether the NAC correction (--nac) was applied.

  • dielectric_electronic, dielectric_static (3x3 nested lists; only with --nac): eps_inf and eps_0.

  • special_points: list of {"q_label": str, "q_position": [float, float, float]} (primitive reciprocal basis).

  • k_path (str) and path_midpoints (list of {"q_label", "segment", "q_position"}; only in phonon_irreps_all.yaml): the seekpath k-path and the midpoints of its segments.

  • irreps: list with one entry per q point, {"q_label", "q_position", "band_sets"} plus "segment" at a k-path midpoint and "activity_summary" (str) at Gamma. band_sets lists the degenerate sets, each a dictionary with band_indices (1-based ints), irrep_label (list of ISO-IR labels with their dimension, "GM4-(3)"; a set holding several irreps lists them all), frequency (THz, negative for an imaginary mode) and, at Gamma, mulliken (str, "A1 + E" for a set holding several irreps), activity (list of "IR", "Raman", "silent", "acoustic") and, with --nac, mode_effective_charge (3x3) and dielectric_contribution (diagonal, 3 floats). band_sets is empty at a k-path midpoint whose labeling failed.

  • raman_tensors (only with --raman-tensor): list with one entry per Raman-active Gamma irrep, {"irrep_label", "mulliken" (if known), "dimension", "multiplicity", "partners" (bool), "constants" (list of names), "tensors" (the tensors as printed, strings), "coefficients"}; coefficients holds one 3x3 matrix per tensor (constant a) or, with partners, one n_constants x 3 x 3 array per partner. Empty list when no Gamma phonon is Raman active.

Return type:

dict

Raises:
  • FileNotFoundError – The file does not exist.

  • ValueError – The file is not YAML, has no irreps list, or has an irreps entry without a band_sets list; a file whose band sets sit directly under q_label is not YAML and is rejected here (write it again with crystod-phonon --irreps).

Example:

from crystod import phonon

data = phonon.read_phonon_irreps("phonon_irreps.yaml")
for point in data["irreps"]:
    for band_set in point["band_sets"]:
        print(point["q_label"], band_set["band_indices"],
              band_set["irrep_label"], band_set["frequency"])
crystod.phonon.resolve_qpoint(raw_qpoint, q_names, q_list, rotations=None, isoir_context=None)[source]#

Resolve --qpoint tokens into a label and primitive-basis coordinates.

This is how crystod-phonon --vector, --subgroup and --modulation (--qpoint and --qpointN; it keeps only the coordinates) read their --qpoint argument: a single token is the label of a tabulated special point (GM, G, GAMMA and the Greek capital gamma all mean Gamma); three tokens are coordinates in the primitive reciprocal basis, fractions such as 1/3 allowed. With isoir_context, coordinates are labeled with their ISO-IR k-vector type in the frame of the labels (the star’s name at a special point, PA at the -k partner of P, U, B, DT on a line or plane). Otherwise, or when the ISO-IR data give nothing, they are labeled with the name of the special point they coincide with; with rotations, any arm of a tabulated star is labeled with the star’s name, not only the tabulated arm; anything else is q_<coords>. The commands pass the list in the frame of the labels (phonon_irreps._special_points_in_label_frame), so a label given on the command line names the point the labels call by it.

Parameters:
  • raw_qpoint (list[str]) – The tokens, one label or three coordinate strings.

  • q_names (list[str]) – Labels of the tabulated special points.

  • q_list (list[list[float]]) – Their coordinates, as returned by crystod.phonon.get_irt_special_points().

  • rotations (ndarray[tuple[Any, ...], dtype[int64]] | None) – Space-group rotations in the primitive basis, shape (n_ops, 3, 3), or None to label exact matches only.

  • isoir_context (tuple | None) – (space-group number, primitive cell tuple, symprec) for the ISO-IR fallback label, optionally followed by the input cell tuple whose ISO-IR frame the label refers to, or None for q_<coords>.

Returns:

(label, qpoint) with qpoint a list of three floats. The coordinates are the ones that were given (not the tabulated arm), so the label names the star while the modes are computed at the requested q.

Raises:

ValueError – For an unknown label, or a token count other than one or three.

Return type:

tuple[str, list[float]]

Example

>>> from crystod import phonon
>>> names = ["GM", "R", "X", "M"]
>>> points = [[0, 0, 0], [0.5, 0.5, 0.5], [0, 0.5, 0], [0.5, 0.5, 0]]
>>> phonon.resolve_qpoint(["R"], names, points)
('R', [0.5, 0.5, 0.5])
>>> # rotations: the primitive-cell rotations of the space group
>>> phonon.resolve_qpoint(["1/2", "0", "0"], names, points, rotations)
('X', [0.5, 0.0, 0.0])
crystod.phonon.scan_imaginary_modes(phonon, qpoints=None, *, threshold=-0.1, degeneracy_tolerance=0.0001, with_settings=True)[source]#

Isotropy subgroups of all imaginary modes at the resolvable q points.

Runs imaginary_mode_subgroups() over qpoints and merges the results; the API form of crystod-phonon --subgroup without --qpoint. Star arms are deduplicated (all arms of a star carry the same levels), and a q point whose modes cannot be labeled is skipped with a warning rather than aborting the scan.

Parameters:
  • phonon – A live phonopy.Phonopy object with force constants, built with primitive_matrix="auto" (see label_phonon_modes()).

  • qpoints – q points to scan, in fractional coordinates of the primitive reciprocal basis; None means commensurate_qpoints() of the phonon supercell.

  • threshold (float) – Frequency (THz) below which a level counts as imaginary.

  • degeneracy_tolerance (float) – Frequency tolerance (THz) within which bands count as degenerate.

  • with_settings (bool) – Also compute the conventional basis/origin of every subgroup (see isotropy_subgroups()).

Returns:

List of ImaginaryModeResult sorted most unstable first (ascending frequency); empty when no level lies below threshold.

Example

>>> from crystod import phonon
>>> results = phonon.scan_imaginary_modes(ph)   # ph: SrTiO3, 4x4x4
>>> [(r.mode.qpoint_label, round(r.mode.frequency, 4)) for r in results]
[('R', -1.0867)]
crystod.phonon.star_arms(k_parent, rotations, tol=1e-08)[source]#

Arms of the star of a parent k point.

Parameters:
  • k_parent – (3,) parent fractional k.

  • rotations – (n_g, 3, 3) integer point-group rotations of the parent (fractional, acting on positions); fractional k transforms with W.T over the whole group.

  • tol (float) – Tolerance of the comparison modulo reciprocal lattice vectors.

Returns:

arms (n_arm, 3) reduced into (-1/2, 1/2], k itself first, the others in lexicographically descending order (X: (0,1/2,0), (1/2,0,0), (0,0,1/2)).

Return type:

(arms, order of the little co-group)

crystod.phonon.survey_mode_resolved_fc(phonon, *, degeneracy_tolerance=0.001)[source]#

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.

Parameters:
  • phonon – A phonopy.Phonopy object with force constants, built with primitive_matrix="auto".

  • degeneracy_tolerance (float) – Frequency tolerance (THz) of the degenerate sets (default 1e-3).

Returns:

One ModeForceConstants per special point.

Return type:

list[ModeForceConstants]

crystod.phonon.unfold(child_phonon, mapping, kpoints, *, degeneracy_tolerance=0.0001, gauge='ideal', method='unwrapped')[source]#

Unfold the child phonons onto parent k points.

Parameters:
  • child_phonon – phonopy.Phonopy whose primitive cell is mapping.child_cell (e.g. load_unfold_inputs(...).child_phonon).

  • mapping (ParentMapping) – The ParentMapping.

  • kpoints – (n_k, 3) parent primitive fractional k.

  • degeneracy_tolerance (float) – THz, degenerate child modes (canonical rotation, groups).

  • gauge (str) – "ideal" (default) or "actual" (diagnostic, without the ideal-site phase factor).

  • method (str) – "unwrapped" (K = M k, default) or "wrapped" (K reduced into [-1/2, 1/2] with the explicit G phase; identical results).

Returns:

UnfoldedBands.

Raises:

SystemExit – The sum rule is violated (an internal error).

Return type:

UnfoldedBands

crystod.phonon.write_band_vector_yaml(phonon, *, band=None, band_labels=None, npoints=None, tolerance=1e-05, filename='band_vector.yaml')[source]#

Write phonopy’s band.yaml with eigenvectors along the viewer’s path.

The path and the q points are those of the irreps figure and the viewer (crystod.phonon_irreps_plot.compute_dispersion()); the vertices are labeled with their ISO-IR names (GM, X) in phonopy’s labels list. The file is phonopy’s own format (nqpoint, npath, segment_nqpoint, labels, reciprocal_lattice, the primitive cell, then phonon: with one entry per q point: q-position, distance and band:, each band with its frequency (THz) and eigenvector: one list per atom of three [re, im] pairs, the mass-weighted eigenvector in phonopy’s atom-position phase convention), so phonopy’s and other band.yaml readers read it.

Parameters:
  • phonon – phonopy.Phonopy object with force constants.

  • band (str | None) – The path, as for crystod.phonon_irreps_plot.compute_dispersion().

  • band_labels (str | None) – The path, as for crystod.phonon_irreps_plot.compute_dispersion().

  • npoints (int | None) – The path, as for crystod.phonon_irreps_plot.compute_dispersion().

  • tolerance (float) – The path, as for crystod.phonon_irreps_plot.compute_dispersion().

  • filename (str) – Output path.

Returns:

The number of q points written (nqpoint).

Return type:

int

crystod.phonon.write_mode_resolved_fc_yaml(results, path='mode-resolved-fc.yaml', *, space_group, nac, formula_units, special_points=None, notes=None)[source]#

Write mode-resolved-fc.yaml.

Parameters:
  • results (list[ModeForceConstants]) – The q points to write (survey_mode_resolved_fc() or mode_resolved_force_constants()).

  • path (str) – File path (default mode-resolved-fc.yaml).

  • space_group (str) – Hermann-Mauguin symbol for the header.

  • nac (bool) – Whether the NAC correction was applied.

  • formula_units (int) – Formula units Z of the primitive cell.

  • special_points (list[tuple[str, list[float]]] | None) – [(label, q), ...] of the special_points list (default: the q points of results).

  • notes (list[str] | None) – Remarks on the whole run (the force-constant consistency NOTE), written as a top-level notes list; none by default.

crystod.phonon.write_phonon_viewer_html(data, output=None)[source]#

Write the standalone phonon mode viewer page.

The page ships, per q point, the drawn atoms (element, Cartesian position, primitive atom index a, lattice translation T), the bonds and polyhedra as atom pairs and vertex lists, and per mode the atomic-gauge vectors u_a (ViewerMode); the script rebuilds the displacement of atom (a, T) as Re[u_a exp(i(2 pi q.T - phi))] times the amplitude (Angstrom), phi the animation phase. The dispersion ships the bands per leg, the ticks and, per labeled level, the mode it selects.

The page opens on the first q point and its first mode; the URL hash #q=R&mode=4&view=a selects the first q point named R (G, GM or GAMMA for Gamma), the mode of band 4 and the orthographic view down the a axis of the display cell (b, c); #q=DT(GM-X) selects the midpoint of the segment GM-X and #q=7 the seventh q button. The arrow keys step through the modes.

Parameters:
crystod.phonon.write_vesta_with_arrows(filepath, lattice, scaled_positions, symbols, arrows_cartesian, title, arrow_rgb=(255, 0, 0), arrow_radius=0.5)[source]#

Write a complete VESTA file with per-atom displacement arrows.

The output of crystod-phonon --vector: the structure is written as a P1 cell with one VECTR/VECTT arrow per atom, following the Phonopy_VESTA approach (A. P. Roy et al., Phys. Rev. Lett. 132, 026701 (2024)): a complete file including VESTA’s style sections, since VESTA ignores vectors in files that lack them. Arrow components are written in the VESTA vector convention: values along the a/b/c axis directions with the modulus in Angstroms (equal to Cartesian components for cubic cells).

Parameters:
  • filepath (str) – Output path (.vesta).

  • lattice (ndarray[tuple[Any, ...], dtype[float64]]) – Lattice vectors as rows, in Angstroms, shape (3, 3).

  • scaled_positions (ndarray[tuple[Any, ...], dtype[float64]]) – Fractional atomic coordinates, shape (n_atoms, 3).

  • symbols (list[str]) – Chemical symbols of the atoms (radius and color are taken from VESTA’s element defaults).

  • arrows_cartesian (ndarray[tuple[Any, ...], dtype[float64]]) – Cartesian arrow vectors in Angstroms, shape (n_atoms, 3).

  • title (str) – The VESTA title line.

  • arrow_rgb (tuple[int, int, int]) – Arrow color as an RGB triple (default red).

  • arrow_radius (float) – Arrow radius in VESTA units.

Returns:

None. The file is written to filepath.

Return type:

None

Example

Draw the first R-point mode of SrTiO3 on its 2x2x2 supercell (ph as in crystod.phonon.label_phonon_modes()):

import numpy as np
from crystod import phonon
from crystod.phonon_vector import get_supercell_displacement_field

q = [0.5, 0.5, 0.5]
modes = phonon.build_symmetry_adapted_modes(ph, q)
supercell_matrix = phonon.get_commensurate_supercell_matrix(
    q, np.eye(3, dtype=int))
supercell, field = get_supercell_displacement_field(
    ph, q, supercell_matrix, modes[0][1])
arrows = field.real * (1.5 / np.linalg.norm(field.real, axis=1).max())
phonon.write_vesta_with_arrows(
    "SrTiO3_R_mode1.vesta", np.array(supercell.cell),
    np.array(supercell.scaled_positions), list(supercell.symbols),
    arrows, title="SrTiO3 R mode 1")
crystod.phonon.wyckoff_orbit_decomposition(vibrations)[source]#

The Gamma phonon irreps per orbit of equivalent atoms (Bilbao SAM).

The displacement representation restricted to one orbit has the character chi(g) = (atoms of the orbit that g maps onto themselves, modulo lattice translations) * tr R_g at Gamma; it is decomposed into the labeled Gamma irreps of the mode spaces of --vibration. The sum over the orbits is the full mode-space list.

Parameters:

vibrations – A crystod.vibration_modes.SymmetryOnlyVibrations (any primitive cell; the orbits are spglib’s equivalent_atoms of it).

Returns:

One WyckoffOrbit per orbit, in atom order; the irreps of an orbit in natural label order (GM1, GM2, ..., GM10), as in the sum line of format_wyckoff_orbits().

Raises:

ValueError – If the cell of vibrations is not a primitive cell (e.g. a supercell analysed with standardize=False).

Return type:

list[WyckoffOrbit]

Example

>>> from crystod import phonon
>>> from crystod.examples import example_path
>>> from crystod.vasp_io import read_poscar_cell
>>> vib = phonon.SymmetryOnlyVibrations(
...     read_poscar_cell(example_path("221_PPOSCAR_SrTiO3")), standardize=False)
>>> for orbit in phonon.wyckoff_orbit_decomposition(vib):
...     print(orbit)
Wyckoff orbit Sr (1a): GM4-
Wyckoff orbit Ti (1b): GM4-
Wyckoff orbit O (3c): 2 GM4- + GM5-
class crystod.phonon.IsotropySubgroup[source]#

Alias of crystod.group.IsotropySubgroup, the record type of the subgroups of an ImaginaryModeResult (the same class object, exported from both namespaces; it is documented once, under crystod.group).