Source code for crystod.correlation

"""Correlation of irreps (crystod-group --correlate).

Four kinds of restriction of a representation to a subgroup are computed:

- Point-group correlation tables (``--correlate --pg G --subgroup H``):
  every irrep of the point group G restricted to each inequivalent
  orientation of a subgroup type H (m-3m -> 4/mmm: T2g -> B2g + Eg).
- The correlation of a group-subgroup pair of structures (``--correlate
  --supergroup-poscar P --subgroup-poscar C``): for every special k point
  of the space group G of P, the small irreps of the space group H of C
  that every irrep of G becomes, at every k point of H its star reaches
  (the offline counterpart of DCORREL of the Bilbao Crystallographic
  Server).  This is how a zone-boundary soft mode of the parent turns into
  Raman-active modes of the low-symmetry phase: R4+ of Pm-3m (SrTiO3)
  becomes GM1+ [A1g] + GM5+ [Eg] of I4/mcm.
- Compatibility relations along a symmetry line (``--correlate-kpath --sg SG
  --kpoint K0 K1 [--line L]``): how the small irreps at two special points
  split or join on the line between them (GM4- -> DT1 + DT5 in Pm-3m),
  the offline counterpart of COMPATIBILITY RELATIONS of the Bilbao
  Crystallographic Server.
- Spin-orbit compatibility (``--correlate-double-group --sg SG [--kpoint
  K]``): the double-valued (spinor) small irreps that a single-valued small
  irrep at k becomes when spin-orbit coupling is switched on,
  Gamma x D(1/2) = sum_j m_j Delta_j (R4- -> -R6- + -R8- in Pm-3m, the
  j = 1/2 and j = 3/2 levels of the Pb 6p band of CsPbI3).

How the group-subgroup correlation works (``subgroup_correlation``):

- ``SymmetryModeAnalysis`` maps the subgroup structure onto the supergroup
  structure: the sublattice basis ``B`` of H (rows, parent primitive units)
  and the operations of H as parent operations; re-expressed in the basis B
  (``W = B^-T R B^T``, ``v = B^-T (tau + t)``) they are identified by spglib
  through a generic orbit and must form the space group of the file.
- The labels of H refer to the ISO-IR frame of the subgroup structure file
  (``crystod.isoir.canonical_iso_frame``, the frame in which every other
  command names the irreps of that structure, and the one the printed
  transformation (P, p) describes), carried onto the basis B.
- Arm a of a parent irrep (q_a, units 1/DEN) carries the wave vector k'_a =
  B q_a of H.  The arms with equal k' modulo the reciprocal lattice of H
  form a sector, the sectors are grouped into stars of H, and the trace of
  the sector block of the full induced matrices (complex, before
  realification; the conjugate traces for the D* half of a doubled irrep)
  on the little group of k' in H, evaluated at the parent operation whose
  translation is exactly the one handed to the labeler, is decomposed into
  the small irreps of H (``IsoIRLabeler.decompose_characters``).  Small
  irreps that time reversal pairs (conj(chi(g0^-1 h g0)) with g0 taking k'
  to -k') are merged under the pair label (``P1P3``).
- The special points of H that no special point of G reaches (N and P of
  I4/mcm under Pm-3m) come from parent symmetry lines; their preimages
  k = B^-1 (k' + m) are classified and the parent line irreps there
  (``ComputedInducedRepresentation``) are decomposed the same way.
- Checks: the character at the identity is the dimension of the sector,
  the dimensions add up per sector and over all stars of H to that of the
  parent irrep, every label carries the k name of its sector, and all
  sectors (arms) of one star of H give the same decomposition.
- With ``--spinor`` (``subgroup_correlation(..., spinor=True)``) the
  double-valued small irreps of G at the tabulated arm (``crystod.
  wavecar_irreps.little_group_data`` on the cell of ``--correlate-double-
  group``) give the characters chi(g^-1 h g) on every arm (with the SU(2)
  sign of the conjugation, as ``transport_double_valued_names``); their sum
  over a sector is decomposed into the double-valued small irreps of H,
  computed on a generic orbit of H on the lattice B L_G (the Cartesian frame
  of G, so that every operation has the same SU(2) matrix in both groups;
  checked) and named with the single-valued labels of H's frame.  Time
  reversal (Wigner's test, ``crystod.extract_irrep._time_reversal``) merges
  pairs as ``A/B`` and doubles as ``A/A``.  Every run also checks
  Res_H(Gamma x D(1/2)) = Res_H(Gamma) x D(1/2) for every single-valued
  irrep Gamma of G on every arm of H.

How the compatibility relations work:

- The line joining the two points is the segment from the tabulated k0 to
  the nearest arm of the star of k1 (the one with the largest little
  group first); ``kdelta`` is the first point of the 1/24 grid on the
  segment whose little group is the little group of the line.
- The small characters at both end points (spgrep phase convention,
  ``SpaceGroupIrrepAlgebra.induced_characters``) are restricted to that
  little group and multiplied by ``exp(SIGMA 2 pi i (kdelta - k_end).v)``
  for the translation ``v`` of every coset representative, which turns
  them into characters with the factor system of kdelta; the result is
  decomposed into the small irreps at kdelta with the ISO-IR labeler of
  the space group (``IsoIRLabeler.decompose_characters``).
- Check: the dimensions of the line irreps add up to the dimension of the
  small irrep at the end point.

How the spin-orbit compatibility works:

- The bare space group is realised by the generic two-orbit structure of
  the ISO-IR labeler (``SpaceGroupIrrepAlgebra._isoir_labeler_inputs``),
  reduced to the primitive basis of the algebra, so k needs no conversion
  and the labels refer to the frame of every other ``crystod-group`` mode.
- ``crystod.wavecar_irreps.spin_orbit_compatibility`` decomposes the
  characters chi_Gamma(g) tr U_g on the double-group coset representatives
  (spgrep's SU(2) matrices U_g) into the double-valued small irreps, named
  as ``crystod --spinor`` names them (``-R6+``: Bradley & Cracknell's
  numbering with the exceptions of ``double_valued_names``, the same name
  on every arm of the star).
- Checks: every single-valued label carries the k name asked for and, at
  a special point, the labels are those of the ISO-IR table at k (else the
  frame is wrong and the command stops; off the special points only the
  one k name is checked); the multiplicities are non-negative integers with
  sum_j m_j dim Delta_j = 2 dim Gamma for every row, and, D(1/2) being
  self-conjugate, sum_i m_ij dim Gamma_i = 2 dim Delta_j for every
  double-valued irrep (each occurs at least once).

How the correlation tables work:

- The subgroups of G are generated from phonopy's table of G (setting 0)
  by adjoining one element at a time to the cyclic subgroups, identified
  with ``spglib.get_pointgroup`` and grouped into conjugacy classes under
  G: one column per class (m-3m has three classes of mm2: the twofold axis
  along z with the axial or the diagonal mirrors, and along [110]).
- The elements of a representative are carried onto the elements of
  phonopy's table of H: unchanged when they match one of its settings (the
  two settings of -42m, 3m, -3m and -6m2 are both tried, and the header
  names the setting), else with spglib's transformation to the standard
  orientation or a conjugation solved for the generators, whichever puts
  the principal axis of the table first (z before x before diagonals).
  The classes of H that fix the
  orientation (``C2' = 2_x, 2_y``) are printed, since B1/B2/B3 depend on
  them.
- The restricted characters are reduced with the norm of each row of the
  table of H (a complex-conjugate pair merged into one real E counts
  once); the multiplicities must be integers and the dimensions must add
  up to that of the irrep of G (checked for every row).

Example:
    >>> from crystod import group
    >>> group.correlation_table("m-3m", "4/mmm").rows["Eg"]
    [[('A1g', 1), ('B1g', 1)]]
    >>> result = group.subgroup_correlation("POSCAR_AlF3_Pm-3m", "POSCAR_AlF3_R-3c")
    >>> [(r.parent_irrep, r.child_irreps) for b in result.blocks for r in b.rows
    ...  if b.parent_k_name == "R" and r.parent_irrep == "R4+"]
    [('R4+', [('GM1+', 1, 1), ('GM3+', 1, 2)])]
    >>> [(r.irrep, r.double_irreps) for r in group.spin_orbit_relations(
    ...     "Pm-3m", "R") if r.irrep == "R4-"]
    [('R4-', [('-R6-', 1), ('-R8-', 1)])]
"""

from __future__ import annotations

import argparse
import functools
import textwrap
from collections import Counter
from dataclasses import dataclass, field
from fractions import Fraction

import numpy as np

# the generic points of the orbit structure of a subgroup (the ones of
# IsotropyAnalyzer._identify_type, so that spglib sees the same structure)
_GENERIC_POINTS = (
    np.array([0.1234, 0.2345, 0.3178]),
    np.array([0.4321, 0.0567, 0.1873]),
)


[docs] @dataclass class Compatibility: """A small irrep at a special point restricted to a symmetry line. Attributes: k0_label: Name of the special point (``GM``, ``X``, ...). k0_irrep: ISO-IR label of the small irrep at that point. line_label: ISO-IR name of the line (``DT``, ``SM``, ...). line_irreps: The small irreps on the line, as ``(ISO-IR label, multiplicity)`` pairs. dimension: Dimension of the small irrep at the point. k_point: The arm of the point the line starts from, primitive basis, as ``Fraction`` values. k_delta: The point of the line at which the line irreps are labeled, primitive basis, as ``Fraction`` values. fixed_dimension: Dimension of the k subspace fixed by the little co-group of ``k_delta``: 1 for a symmetry line, 2 for a symmetry plane, 3 for a general point (possible only when two points are given that no line joins). """ k0_label: str k0_irrep: str line_label: str line_irreps: list dimension: int = 0 k_point: tuple = () k_delta: tuple = () fixed_dimension: int = 1
[docs] @dataclass class SpinOrbitRelation: """A single-valued small irrep and the double-valued ones it becomes. One line of ``crystod-group --correlate-double-group``: when spin-orbit coupling is switched on, a level of the single-valued (spinless) small irrep Gamma at k becomes the double-valued (spinor) small irreps of Gamma x D(1/2) = sum_j m_j Delta_j. Attributes: k_label: ISO-IR name of the k point (``GM``, ``R``, ...); for coordinates off the special points, the ISO-IR name of the line, plane or general point they lie on (``DT``, ``GP``). k_kind: ``"point"`` for a tabulated special point, otherwise ``"line"``, ``"plane"`` or ``"general point"`` (the dimension of the k subspace fixed by the little co-group). k_point: k in the primitive basis, as ``Fraction`` values: the tabulated arm of a special point (whatever arm was given); otherwise the coordinates given, reduced into (-1, 1) by an integer and snapped onto fractions with denominators up to 48 within 1e-6, as the little group is computed (the header prints any other coordinate with three decimals). irrep: ISO-IR label of the single-valued small irrep (``R4+``). dimension: Its dimension. double_irreps: The double-valued small irreps of irrep x D(1/2), as ``(name, multiplicity)`` pairs in natural order (``-R6+``, ``-R8+``: the names of ``crystod --spinor``, ``crystod.wavecar_irreps.double_valued_names``). double_dimensions: ``{name: dimension}`` of every double-valued small irrep at k. notes: The NOTE lines of the k point (without the ``NOTE:`` prefix), the same in every record of one k point: where the names differ from Bradley & Cracknell (1972), or why they are generic. """ k_label: str k_kind: str k_point: tuple irrep: str dimension: int double_irreps: list double_dimensions: dict = field(default_factory=dict) notes: list = field(default_factory=list)
@dataclass class _Segment: """A symmetry line between two special points.""" name0: str name1: str k0: np.ndarray k1: np.ndarray kdelta: np.ndarray ops: list line: str length: float fixed_dimension: int = 1 # ------------------------------------------------------------------ helpers def _orbit_cell(rotations, translations, lattice): """Generic-orbit structure of a subgroup in its sublattice basis (the structure ``IsotropyAnalyzer._identify_type`` identifies).""" positions, numbers = [], [] for species, x0 in enumerate(_GENERIC_POINTS): orbit = [] for W, v in zip(rotations, translations): x = np.mod(np.asarray(W) @ x0 + np.asarray(v), 1.0) if not any(np.allclose(x, p, atol=1e-6) for p in orbit): orbit.append(x) positions.extend(orbit) numbers.extend([species + 1] * len(orbit)) return np.asarray(lattice, dtype=float), np.array(positions), numbers def _frame_setting(labeler, lattice, B, primitive_matrix): """Basis rows and origin (parent conventional units) of the ISO-IR frame ``x_iso = P x + origin_shift`` of the subgroup, as ``IsotropyAnalyzer.conventional_setting`` computes it for spglib's.""" P = np.asarray(labeler.P, dtype=float) shift = np.asarray(labeler.origin_shift, dtype=float) lattice = np.asarray(lattice, dtype=float) L_parent_prim = np.linalg.inv(np.asarray(B, dtype=float)) @ lattice L_parent_conv = np.linalg.inv(np.asarray(primitive_matrix, dtype=float)).T @ L_parent_prim L_child = np.linalg.inv(P).T @ lattice basis = L_child @ np.linalg.inv(L_parent_conv) # reduce modulo the translations of H (cell coordinates of H), not modulo # the parent lattice: a parent translation outside T_H need not normalize # H, and would describe the frame of a conjugate subgroup (another domain) origin_cell = -np.linalg.inv(P) @ shift origin_cell = origin_cell - np.floor(origin_cell + 1e-9) origin = origin_cell @ lattice @ np.linalg.inv(L_parent_conv) return np.round(basis, 6) + 0.0, np.round(origin, 6) + 0.0 def _gamma_family(labeler, rotations, translations): """ISO-IR labels and characters of the Gamma irreps of the subgroup on its operations, or ``None``. Coupled to private parts of ``crystod.isoir.IsoIRLabeler`` (``conventional_k``, ``conventional_operations``, ``_matched_families``, ``_family_characters_checked``); the section 02-09 tests guard the result. """ k_conv = labeler.conventional_k([0.0, 0.0, 0.0]) conv_ops = labeler.conventional_operations(rotations, translations) for _, family in labeler._matched_families(k_conv): chars = labeler._family_characters_checked(family, conv_ops) if chars is not None: return tuple(ir.label for ir, _, _ in family), np.asarray(chars, dtype=complex) return None def _complex_partners(family) -> dict: """``{label: partner}`` for every complex-type Gamma irrep of the family and its complex-conjugate partner (empty for ``None``).""" if family is None: return {} labels, chars = family partners = {} for a, chi in enumerate(chars): if np.abs(chi.imag).max() <= 1e-6: continue for b, other in enumerate(chars): if b != a and np.allclose(other, chi.conj(), atol=1e-6): partners[labels[a]] = labels[b] break return partners def _pair_label(name: str, partner: str) -> str: """The ISOTROPY pair label of a complex irrep and its conjugate (``GM2+GM3+``), as ``InducedRepresentation.label`` and ``crystod.phonon_activity`` write it.""" from .phonon_activity import _natural_key return "".join(sorted((name, partner), key=_natural_key)) def _merge_pairs(gamma_part, partners) -> list: """Join each complex-conjugate pair of equal multiplicity into one pair term (the physically irreducible representation), in place of its first member.""" counts = dict(gamma_part) merged, used = [], set() for name, n in gamma_part: if name in used: continue partner = partners.get(name) if partner is not None and counts.get(partner) == n: merged.append((_pair_label(name, partner), n)) used |= {name, partner} else: merged.append((name, n)) used.add(name) return merged def _gamma_mulliken(family, cell, rotations) -> dict: """Mulliken symbols of the Gamma irreps of the subgroup, keyed by ISO-IR label and by pair label of complex pairs (phonopy's tables, as ``crystod.phonon.mulliken_symbols``); an empty dict when they cannot be assigned. Coupled to the private ``crystod.phonon_activity._mulliken_of_table`` (fed a duck-typed table); the section 02-09 tests assert bracketed symbols. """ import types import warnings import spglib from .phonon_activity import _mulliken_of_table if family is None: return {} try: labels, chars = family dataset = spglib.get_symmetry_dataset(cell, symprec=1e-4) if dataset is None: return {} def item(name): return dataset[name] if isinstance(dataset, dict) else getattr(dataset, name) table = types.SimpleNamespace( vibrations=types.SimpleNamespace(spglib_dataset={ "pointgroup": item("pointgroup"), "transformation_matrix": item("transformation_matrix"), }), rotations=np.asarray(rotations), labels=labels, characters=np.array([np.conj(chi) for chi in chars]), ) with warnings.catch_warnings(): warnings.simplefilter("ignore") return _mulliken_of_table(table) except Exception: return {} def _format_vector(values) -> str: from .isotropy_subgroup import _format_setting_value return "(" + ",".join(_format_setting_value(x) for x in values) + ")" def _k_fractions(k_int) -> tuple: from .spacegroup_product import DEN return tuple(Fraction(int(v), DEN) for v in np.asarray(k_int)) def _k_text(values) -> str: return "(" + ", ".join(str(v) for v in values) + ")" # ---------------------------------------- (c) correlation of a group-subgroup pair
[docs] @dataclass class IrrepCorrelation: """One irrep of the supergroup G and the irreps of the subgroup H it becomes. One row of ``crystod-group --correlate --supergroup-poscar P --subgroup-poscar C``: the components of the parent irrep that belong to one arm of a k star of H, decomposed into the small irreps of H there. Attributes: parent_irrep: ISO-IR label of the parent irrep (``R4+``; the pair label of a complex-type irrep, ``GM2+GM3+``; on a symmetry line the ISO-IR line label, ``LD1``). parent_dim: Dimension of the parent small irrep (doubled for a complex- or pseudoreal-type pair), i.e. the components of one parent arm. arms_merged: Number of parent arms that fall onto one arm of H (the ``m x`` prefix of the printed row; 1 when nothing merges). child_irreps: The small irreps of H at that arm, as ``(ISO-IR label, multiplicity, dimension)``; a complex-conjugate pair of equal multiplicity is one term with the pair label and the dimension of the pair. mulliken: ``{label: Mulliken symbol}`` of the Gamma irreps of H among ``child_irreps`` (empty away from Gamma). parent_mulliken: Mulliken symbol of the parent irrep at Gamma, or None. double_valued: ``True`` for a row of double-valued (spinor) irreps (``--spinor``): the names of ``crystod --spinor`` on both sides (``-R8+``), a time-reversal pair as ``A/B`` and an irrep doubled by time reversal as ``A/A``, with the dimension of the pair. """ parent_irrep: str parent_dim: int arms_merged: int child_irreps: list mulliken: dict = field(default_factory=dict) parent_mulliken: str | None = None double_valued: bool = False
[docs] @dataclass class KpointCorrelation: """The rows of one parent k star and one k star of the subgroup. Attributes: parent_k_name: ISO-IR name of the parent k point (``X``; ``LD`` for a point of a symmetry line). parent_k: The parent arm shown, primitive basis of G, as ``Fraction`` values in (-1/2, 1/2]. parent_kind: ``"point"`` for a tabulated special point of G, ``"line"``, ``"plane"`` or ``"general point"`` otherwise. parent_arms: Number of arms of the parent star. parent_arms_in_block: How many of them fall onto this star of H. child_k_name: ISO-IR name of the k point of H (``M``). child_k: Its arm shown, primitive basis of H as ``crystod-bz --show-kpoint`` prints it (the tabulated arm for a special point), as ``Fraction`` values. child_k_conventional: The same in the conventional basis of H, or None for a primitive lattice. child_arms: Number of arms of the star of H. arms_merged: Parent arms per arm of H. rows: One ``IrrepCorrelation`` per parent irrep of the star. """ parent_k_name: str parent_k: tuple parent_kind: str parent_arms: int parent_arms_in_block: int child_k_name: str child_k: tuple child_k_conventional: tuple | None child_arms: int arms_merged: int rows: list = field(default_factory=list)
[docs] @dataclass class SubgroupCorrelation: """The correlation of the irreps of a group-subgroup pair of structures. Returned by ``subgroup_correlation`` (``crystod-group --correlate --supergroup-poscar P --subgroup-poscar C``). Attributes: parent_symbol: International symbol of the supergroup G (``parent_number`` its number); ``child_symbol`` and ``child_number`` likewise for the subgroup H, the space group of the child structure. parent_file: The supergroup structure file as given; ``child_file`` the subgroup one. size: Primitive-cell multiplication of H relative to G. index: Index of H in G. basis: Rows of the primitive basis of H in parent primitive units (the sublattice basis of ``SymmetryModeAnalysis.mapping.S``). frame_basis: Rows of the conventional basis of the ISO-IR frame of H the labels of H refer to, in parent conventional units. frame_origin: Its origin in parent conventional units. frame_source: ``"structure"`` when that frame is the ISO-IR frame of the subgroup structure file (the one every other command uses for that file), ``"orbit"`` when it is the frame of a generic orbit of H (fallback). transformation: The ``SettingTransformation`` (P, p) printed in the ``* Transformation matrix (parent -> child) *`` block. blocks: One ``KpointCorrelation`` per (parent star, star of H): the special points of G in the order of the ISO-IR tables, then the parent line or plane points that are the only source of a special point of H. unreached: The special points of H that no parent special point reaches, as ``(name, k of H, parent k, parent k name, kind)`` with k as ``Fraction`` tuples (empty when every one is reached). notes: The NOTE lines of the command (without ``NOTE:``). spinor: Whether the double-valued rows were computed (``--spinor``). spinor_notes: The NOTE lines of ``spinor_numbering_notes`` of the k points of G and H (where the double-valued names differ from Bradley & Cracknell), without ``NOTE:``. parent_formula: Reduced chemical formula of the supergroup structure (``SymmetryModeAnalysis.parent_formula``, the name of ``sym_mode_<formula>``), e.g. ``"YMnO3"``; the command names its report file ``CORREL_<formula>_<G>_<H>`` after it. """ parent_symbol: str parent_number: int child_symbol: str child_number: int parent_file: str child_file: str size: int index: int basis: np.ndarray frame_basis: np.ndarray frame_origin: np.ndarray frame_source: str transformation: object blocks: list = field(default_factory=list) unreached: list = field(default_factory=list) notes: list = field(default_factory=list) spinor: bool = False spinor_notes: list = field(default_factory=list) parent_formula: str = ""
def _file_name_symbol(symbol: str) -> str: """A space-group symbol made file-name safe (``P6_3/mmc`` -> ``P63mmc``); see :func:`crystod.cli.common.file_name_tag`.""" from .cli.common import file_name_tag return file_name_tag(symbol) def subgroup_correlation_file_name(result: SubgroupCorrelation) -> str: """The file ``crystod-group --correlate --supergroup-poscar P --subgroup-poscar C`` saves its printed report in. ``CORREL_<formula>_<G>_<H>``: the reduced formula of the supergroup structure (as in ``sym_mode_<formula>``) and the short international symbols of G and H without ``_`` and ``/``; ``_spinor`` is appended for a ``--spinor`` run, so the two reports do not overwrite each other. Only the command writes the file; ``subgroup_correlation`` writes nothing. Args: result: The :class:`SubgroupCorrelation` of the run. Returns: The file name, e.g. ``"CORREL_YMnO3_P63mmc_P63cm"``, ``"CORREL_SrTiO3_Pm-3m_I4mcm_spinor"``. """ name = (f"CORREL_{result.parent_formula or 'structure'}_" f"{_file_name_symbol(result.parent_symbol)}_" f"{_file_name_symbol(result.child_symbol)}") return name + "_spinor" if result.spinor else name @dataclass class _SubgroupContext: """The subgroup H of a structure pair, as the sector engine uses it.""" algebra: object B: np.ndarray indices: list parent_translations: list rotations: list inverse_rotations: list translations: list labeler: object child_algebra: object cell: tuple frame_source: str def _structure_frame(analysis, child_file, rotations, translations): """The ISO-IR frame ``(P, origin_shift)`` of the subgroup structure file carried onto the primitive basis of H with the parent origin, or None. The frame of the file is ``crystod.isoir.canonical_iso_frame`` of the file (the frame every command names the irreps of that structure in); the file is related to spglib's primitive cell of the analysis by ``_affine_map_between_cells`` (x_file = A x_c + b), and that cell to the working basis by x_w = x_c + S^-T p (x_parent = S^T x_c + p). The frame is accepted only when it carries the operations of H onto the tabulated ISO-IR operations. """ from .isoir import ( _affine_map_between_cells, _frame_is_valid, _iso_table_entry, canonical_iso_frame, ) from .symmetry_mode import read_structure_cell number = int(analysis.child_number) tolerance = float(analysis.tolerance) try: file_cell = read_structure_cell(child_file) frame = canonical_iso_frame(number, file_cell, tolerance) relation = _affine_map_between_cells(file_cell, analysis.child_prim, tolerance) except Exception: return None if frame is None or relation is None: return None P_file, origin_file = (np.asarray(x, dtype=float) for x in frame) A, b = (np.asarray(x, dtype=float) for x in relation) S = np.asarray(analysis.mapping.S, dtype=float) p = np.asarray(analysis.mapping.p, dtype=float) P = P_file @ A origin = P_file @ (b - A @ np.linalg.inv(S.T) @ p) + origin_file if not _frame_is_valid(_iso_table_entry(number), rotations, translations, P, origin, 1e-4): return None return P, origin - np.floor(origin + 1e-9) def _subgroup_context(analysis, child_file) -> _SubgroupContext: """H as parent operations, its operations in its primitive basis and the ISO-IR labeler of its irreps.""" import spglib from .isoir import IsoIRLabeler, get_cached_labeler from .isotropy_subgroup import invariant_parent_lattice, sublattice_operations from .spacegroup_product import SpaceGroupIrrepAlgebra from .symmetry_mode import _conjugated_child_operations algebra = analysis.algebra S = np.asarray(analysis.mapping.S, dtype=np.int64) conjugated = _conjugated_child_operations(algebra, S, analysis._child_ops) own = None if conjugated is None else analysis._child_operation_members( conjugated, analysis.mapping) if own is None: raise RuntimeError("the operations of the subgroup structure are not parent " "operations in the cell relation found.") rotations, translations, parent_translations = sublattice_operations(algebra, S, own) lattice = S @ invariant_parent_lattice(algebra) cell = _orbit_cell(rotations, translations, lattice) dataset = spglib.get_symmetry_dataset(cell, symprec=1e-4) number = None if dataset is None else int( dataset["number"] if isinstance(dataset, dict) else dataset.number) if number != int(analysis.child_number): raise SystemExit( f"ERROR: the operations of {analysis.child_symbol} (No. " f"{analysis.child_number}) carried into the parent form the space group " f"No. {number}, not that of the subgroup structure.") frame = _structure_frame(analysis, child_file, rotations, translations) if frame is not None: labeler = IsoIRLabeler(number, transformation_matrix=frame[0], origin_shift=frame[1]) source = "structure" else: labeler = get_cached_labeler(number, cell) source = "orbit" if labeler is None: raise SystemExit(f"ERROR: no ISO-IR frame for {analysis.child_symbol} (No. " f"{number}); its irreps cannot be labeled.") inverse = [np.rint(np.linalg.inv(W)).astype(np.int64) for W in rotations] return _SubgroupContext( algebra=algebra, B=S, indices=[int(i) for i, _ in own], parent_translations=parent_translations, rotations=rotations, inverse_rotations=inverse, translations=translations, labeler=labeler, child_algebra=SpaceGroupIrrepAlgebra(str(number)), cell=cell, frame_source=source, ) def _family_at(labeler, k, rotations, translations): """ISO-IR labels and characters of the small irreps of H at k (primitive basis of H) on the given little-group operations, or None (the generalization of ``_gamma_family``; the -k branches are not tried).""" k_conv = labeler.conventional_k(k) conv_ops = labeler.conventional_operations(rotations, translations) for _, family in labeler._matched_families(k_conv): chars = labeler._family_characters_checked(family, conv_ops) if chars is not None: return tuple(ir.label for ir, _, _ in family), np.asarray(chars, dtype=complex) return None def _label_k(label: str) -> str: """The k-point name of an ISO-IR label (``GM`` of ``GM5+``, ``LD`` of ``LD1``, ``P`` of ``P1P2``).""" import re match = re.match(r"[A-Z]+", label) return match.group(0) if match else label def _sectors(rep, B) -> dict: """The arms of an induced irrep grouped by the k vector of H they carry. Arm a of the parent irrep (vector q_a, parent primitive reciprocal basis, units 1/DEN) is the vector k'_a = B q_a of H (k'_j = q . b_j); the complex conjugate of a doubled irrep (D + D*) carries -q_a. Returns ``{k' mod DEN: [(a, sign), ...]}`` in arm order.""" from .spacegroup_product import DEN arms = np.asarray(rep.arms, dtype=np.int64) k_child = arms @ np.asarray(B, dtype=np.int64).T signed = [(a, 1) for a in range(len(arms))] if rep.doubled: signed += [(a, -1) for a in range(len(arms))] sectors: dict[tuple, list] = {} for a, sign in signed: key = tuple(int(x) for x in (sign * k_child[a]) % DEN) sectors.setdefault(key, []).append((a, sign)) return sectors def _sector_characters(rep, ctx, key, members): """Little group of k' = key/DEN in H and the characters of the sector on it: tr(P_sector D(g)) at the parent operation whose translation is exactly the one handed to the labeler (``sublattice_operations``); the conjugate traces for the D* part of a doubled irrep.""" from .spacegroup_product import DEN k = np.asarray(key, dtype=np.int64) little = [j for j, W_inv in enumerate(ctx.inverse_rotations) if np.all((k @ W_inv - k) % DEN == 0)] d = int(rep.dim_small) characters = [] for j in little: block = rep.blocks[ctx.indices[j]] phases = rep.translation_phases(ctx.parent_translations[j]) total = 0j for a, sign in members: trace = phases[a * d] * np.trace(block[a * d:(a + 1) * d, a * d:(a + 1) * d]) total += trace if sign > 0 else np.conj(trace) characters.append(total) return little, np.array(characters, dtype=complex) def _decompose_sector(rep, ctx, key, members): """``[(label, multiplicity, dim)]`` (complex pairs merged) and the k type of one sector, checked.""" from .spacegroup_product import DEN little, characters = _sector_characters(rep, ctx, key, members) dimension = len(members) * int(rep.dim_small) rotations = [ctx.rotations[j] for j in little] translations = [ctx.translations[j] for j in little] identity = [n for n, j in enumerate(little) if np.array_equal(ctx.rotations[j], np.eye(3, dtype=np.int64))] if not identity or abs(characters[identity[0]] - dimension) > 1e-6: raise RuntimeError(f"internal error: the sector of {rep.label} at k' = {key}/{DEN} " f"has the character {characters[identity[0]] if identity else '?'} " f"at the identity, not its dimension {dimension}.") k = np.asarray(key, dtype=float) / DEN result = ctx.labeler.decompose_characters(k, rotations, translations, characters) if result is None: raise RuntimeError(f"internal error: the components of {rep.label} at k' = " f"{_k_text(_k_fractions(key))} of H do not decompose into its " "small irreps.") terms, ktype = result total = sum(n * dim for _, n, dim in terms) if total != dimension: raise RuntimeError(f"internal error: the irreps of H in {rep.label} add up to " f"{total} dimensions, its sector has {dimension}.") if any(_label_k(label) != ktype for label, _, _ in terms): raise RuntimeError(f"internal error: the irreps of H in {rep.label} at {ktype} " f"carry other k names: {', '.join(t[0] for t in terms)}.") try: family = _family_at(ctx.labeler, k, rotations, translations) except Exception: family = None partners = _time_reversal_partners(ctx, key, little, family) dims = {label: dim for label, _, dim in terms} pair_dims = {_pair_label(name, partner): dims.get(name, 0) + dims.get(partner, 0) for name, partner in partners.items()} merged = [(label, n, dims[label] if label in dims else pair_dims[label]) for label, n in _merge_pairs([(label, n) for label, n, _ in terms], partners)] return merged, ktype def _time_reversal_partners(ctx, key, little, family) -> dict: """``{label: partner}`` of the small irreps of H at k' that time reversal pairs into one physically irreducible representation (the pair labels of DCORREL, ``P1P3``). The partner of an irrep with characters chi is the irrep with conj(chi(g0^-1 h g0)) on the little group, g0 an operation of H taking k' to -k' (the identity when k' = -k'; none exists when -k' lies in another star of H, and nothing is paired). g0^-1 h g0 is a little-group operation j plus a lattice translation n of H, and the ISO-IR characters of the family (phase convention exp(+2 pi i k.t)) give chi(j + n) = exp(2 pi i k'.n) chi(j). """ from .spacegroup_product import DEN if family is None: return {} labels, chars = family k = np.asarray(key, dtype=np.int64) g0 = next((j for j, W_inv in enumerate(ctx.inverse_rotations) if np.all((k @ W_inv + k) % DEN == 0)), None) if g0 is None: return {} W0 = np.asarray(ctx.rotations[g0], dtype=float) v0 = np.asarray(ctx.translations[g0], dtype=float) W0_inv = np.linalg.inv(W0) position = {} for n, j in enumerate(little): position[np.asarray(ctx.rotations[j], dtype=np.int64).tobytes()] = n images, phases = [], [] for j in little: W = np.asarray(ctx.rotations[j], dtype=float) v = np.asarray(ctx.translations[j], dtype=float) W_c = np.rint(W0_inv @ W @ W0).astype(np.int64) v_c = W0_inv @ (W @ v0 + v - v0) m = position.get(W_c.tobytes()) if m is None: return {} shift = v_c - np.asarray(ctx.translations[little[m]], dtype=float) if not np.allclose(shift, np.rint(shift), atol=1e-6): return {} images.append(m) phases.append(np.exp(2j * np.pi * float(k @ np.rint(shift)) / DEN)) partners = {} for a, chi in enumerate(chars): reversed_chi = np.conj(np.asarray(chi)[images] * np.array(phases)) if np.allclose(reversed_chi, chi, atol=1e-6): continue for b, other in enumerate(chars): if b != a and np.allclose(other, reversed_chi, atol=1e-6): partners[labels[a]] = labels[b] break return partners def _h_stars(ctx, keys) -> list[list[tuple]]: """The sectors grouped into stars of H (an operation of H maps the k' of one onto that of another), in the order of their first sector.""" from .spacegroup_product import DEN remaining = list(keys) stars = [] while remaining: k = np.asarray(remaining[0], dtype=np.int64) orbit = {tuple(int(x) for x in (k @ W_inv) % DEN) for W_inv in ctx.inverse_rotations} star = [key for key in remaining if key in orbit] stars.append(star) remaining = [key for key in remaining if key not in orbit] return stars def _centered(fractions) -> tuple: """k coordinates reduced into (-1/2, 1/2].""" reduced = [] for value in fractions: value = value - (value.numerator // value.denominator) if value > Fraction(1, 2): value -= 1 reduced.append(value) return tuple(reduced) def _child_coordinates(ctx, key): """k' (units 1/DEN, primitive basis of H used by the labeler) in the standard primitive basis of H (that of ``crystod-bz --show-kpoint``) and in its conventional basis, as ``Fraction`` tuples.""" from .spacegroup_product import DEN M = np.asarray(ctx.child_algebra.primitive_matrix, dtype=float) k_conv = ctx.labeler.conventional_k(np.asarray(key, dtype=float) / DEN) k_prim = k_conv @ M return (tuple(Fraction(float(v)).limit_denominator(DEN * 4) for v in k_prim), tuple(Fraction(float(v)).limit_denominator(DEN * 4) for v in k_conv)) def _display_sector(ctx, star, ktype): """The sector of an H star shown in the header: the one at the arm the ISO-IR table of H lists (``crystod-bz --show-kpoint``), else the first; with its coordinates (primitive, conventional or None).""" from .spacegroup_product import DEN child = ctx.child_algebra M = np.asarray(child.primitive_matrix, dtype=float) centred = not np.allclose(M, np.eye(3)) tabulated = child.k_by_kname.get(ktype) chosen = None if tabulated is not None: target = tuple(Fraction(int(v), DEN) for v in np.asarray(tabulated)) for key in star: prim, _ = _child_coordinates(ctx, key) if all((a - b).denominator == 1 for a, b in zip(prim, target)): chosen = key break if chosen is None: chosen = star[0] prim, _ = _child_coordinates(ctx, chosen) prim = _centered(prim) else: prim = target inverse = np.linalg.inv(M) conv = None if centred: conv = tuple(Fraction(float(v)).limit_denominator(DEN * 4) for v in np.array([float(x) for x in prim]) @ inverse) return chosen, prim, conv def _parent_mulliken(algebra) -> dict: """Mulliken symbols of the Gamma irreps of the parent (empty on failure).""" try: labeler, conv_R, conv_t = _labeler_context(algebra) family = _gamma_family(labeler, conv_R, conv_t) return _gamma_mulliken(family, algebra._isoir_labeler_inputs()[0], conv_R) except (Exception, SystemExit): return {} def _correlate_star(ctx, reps, parent_name, parent_kind, parent_mulliken, child_mulliken, spinor=None, k_int=None): """The ``KpointCorrelation`` blocks of one parent star (every irrep in ``reps``), keyed by star of H, checked; with ``spinor`` (a ``_SpinorContext``) the double-valued rows of the star of ``k_int`` follow the single-valued ones.""" from .spacegroup_product import DEN blocks: dict[tuple, KpointCorrelation] = {} for rep in reps: sectors = _sectors(rep, ctx.B) per_component = int(rep.dim_small) full_dimension = len(rep.arms) * per_component * (2 if rep.doubled else 1) covered = 0 for star in _h_stars(ctx, list(sectors)): results = [_decompose_sector(rep, ctx, key, sectors[key]) for key in star] first, ktype = results[0] for (terms, other), key in zip(results[1:], star[1:]): if other != ktype or sorted(terms) != sorted(first): raise RuntimeError( f"internal error: {rep.label} decomposes differently on two arms of " f"{ktype} of H ({first} and {terms} at {_k_text(_k_fractions(key))}).") counts = {len(sectors[key]) for key in star} if len(counts) != 1: raise RuntimeError(f"internal error: the arms of {ktype} of H carry " f"different numbers of parent arms of {rep.label}.") members_per_sector = counts.pop() covered += members_per_sector * per_component * len(star) # parent k vectors per arm of H (a doubled irrep carries q and -q) vectors = {tuple(int(x) for x in (sign * np.asarray(rep.arms[a])) % DEN) for a, sign in sectors[star[0]]} merged = len(vectors) identity = tuple(sorted(star)) if identity not in blocks: shown, child_k, child_conv = _display_sector(ctx, star, ktype) # the parent arm of that sector with the fewest negative # coordinates (in (-1/2, 1/2]) parent_k = min( (_centered(_k_fractions(sign * np.asarray(rep.arms[a]))) for a, sign in sectors[shown]), key=lambda k: (sum(1 for v in k if v < 0), [-v for v in k])) arms_in_block = len({tuple(int(x) for x in (s * np.asarray(rep.arms[b])) % DEN) for key in star for b, s in sectors[key]}) blocks[identity] = KpointCorrelation( parent_k_name=parent_name, parent_k=parent_k, parent_kind=parent_kind, parent_arms=len(rep.arms), parent_arms_in_block=arms_in_block, child_k_name=ktype, child_k=child_k, child_k_conventional=child_conv, child_arms=len(star), arms_merged=merged, ) block = blocks[identity] mulliken = child_mulliken if ktype == "GM" else {} block.rows.append(IrrepCorrelation( parent_irrep=rep.label, parent_dim=members_per_sector * per_component // merged, arms_merged=merged, child_irreps=first, mulliken={label: mulliken[label] for label, _, _ in first if label in mulliken}, parent_mulliken=parent_mulliken.get(rep.label), )) if covered != full_dimension: raise RuntimeError(f"internal error: the stars of H carry {covered} components " f"of {rep.label}, which has {full_dimension}.") if spinor is not None: _spinor_blocks(ctx, spinor, k_int, blocks) return list(blocks.values()) def _special_point_reps(algebra, kname): """The induced irreps of a tabulated parent star, one per physically irreducible representation (a complex pair once, under its pair label).""" from .isotropy_subgroup import InducedRepresentation reps, skipped = [], set() for irrep in algebra.irreps_by_kname[kname]: if irrep.name in skipped: continue rep = InducedRepresentation(algebra, irrep.name) if rep.doubled and rep.fs_type == "complex": partner = rep.conjugate_partner() if partner is not None: skipped.add(partner) reps.append(rep) return reps def _line_point_reps(algebra, k_int): """The induced irreps of the parent star of an off-special k (units 1/DEN) with their ISO-IR line labels: ``(k-type name, kind, reps)``.""" from .isotropy_subgroup import ComputedInducedRepresentation from .spacegroup_product import DEN k_int = np.mod(np.asarray(k_int, dtype=np.int64), DEN) smalls = algebra.computed_irreps_at(k_int) labels = algebra._isoir_line_labels(k_int) if labels is None or labels[1] is None: raise RuntimeError("no ISO-IR labels for the parent line irreps") ktype, names = labels reps, skipped = [], set() for index, small in enumerate(smalls): partner = None for other, candidate in enumerate(smalls): if other != index and set(candidate["chi"]) == set(small["chi"]) and all( abs(candidate["chi"][op] - np.conj(small["chi"][op])) < 1e-6 for op in small["chi"]): partner = names[other] break if names[index] in skipped: continue rep = ComputedInducedRepresentation(algebra, k_int, small, names[index], ktype, partner) if rep.doubled and rep.fs_type == "complex" and partner is not None: skipped.add(partner) reps.append(rep) from .phonon_activity import _natural_key reps.sort(key=lambda rep: _natural_key(rep.label)) return ktype, _k_kind(algebra, k_int / DEN), reps def _unreached_points(ctx, blocks): """The special points of H that no block reaches: ``(name, k' key in the labeler basis, preimages)`` with the parent preimages (units 1/DEN, parent primitive basis) of the tabulated arm, one per coset of the reciprocal lattice of G in that of H.""" from .spacegroup_product import DEN reached = {block.child_k_name for block in blocks} child = ctx.child_algebra M = np.asarray(child.primitive_matrix, dtype=float) B = np.asarray(ctx.B, dtype=np.int64) B_inv = np.linalg.inv(B.astype(float)) size = abs(int(round(np.linalg.det(B)))) unreached = [] for name, k_std in child.k_by_kname.items(): if name in reached: continue # standard primitive -> conventional -> labeler basis (k_conv = k' P^-1) k_conv = (np.asarray(k_std, dtype=float) / DEN) @ np.linalg.inv(M) k_child = k_conv @ np.asarray(ctx.labeler.P, dtype=float) key = np.rint(k_child * DEN).astype(np.int64) if not np.allclose(k_child * DEN, key, atol=1e-6): continue preimages = [] for m in np.ndindex(size, size, size): q = B_inv @ (key + DEN * np.asarray(m)) q_int = np.rint(q).astype(np.int64) if not np.allclose(q, q_int, atol=1e-6): continue q_int = q_int % DEN if not any(np.array_equal(q_int, other) for other in preimages): preimages.append(q_int) unreached.append((name, tuple(int(x) for x in key % DEN), preimages)) return unreached def _line_blocks(ctx, blocks, parent_mulliken, spinor=None): """Blocks of the parent line/plane stars whose only image is a special point of H that no parent special point reaches; and the points left unreached (with the most specific parent preimage).""" from .spacegroup_product import DEN algebra = ctx.algebra labeler, _, _ = _labeler_context(algebra) M_inv = np.linalg.inv(np.asarray(algebra.primitive_matrix, dtype=float)) extra, left = [], [] computed: dict = {} # parent star -> its blocks (every star of H) for name, key, preimages in _unreached_points(ctx, blocks): # the parent stars of the preimages, most specific k type first candidates = [] for q in preimages: arms, _ = algebra._star_of_vector(q) star = tuple(sorted(tuple(int(x) for x in arm) for arm in arms)) kind = _k_kind(algebra, q / DEN) pname = labeler.kpoint_name((q / DEN) @ M_inv) or "?" rank = {"point": 0, "line": 1, "plane": 2}.get(kind, 3) candidates.append((rank, -len(algebra.little_group(q)), star, q, pname, kind)) candidates.sort(key=lambda item: (item[0], item[1], item[2])) if not candidates: continue best, _, star, q, pname, kind = candidates[0] new = [] used: set = set() for rank, little, star_c, q_c, _, _ in candidates: if (rank, little) != (best, candidates[0][1]) or star_c in used: continue used.add(star_c) if star_c not in computed: try: ktype, kind_c, reps = _line_point_reps(algebra, q_c) computed[star_c] = _correlate_star(ctx, reps, ktype, kind_c, parent_mulliken, {}, spinor, q_c) except (RuntimeError, SystemExit, LookupError, ValueError): computed[star_c] = [] new.extend(b for b in computed[star_c] if b.child_k_name == name) if new: extra.extend(new) else: child_k, _ = _child_coordinates(ctx, key) left.append((name, _centered(child_k), _centered(_k_fractions(q)), pname, kind)) return extra, left
[docs] def subgroup_correlation(supergroup_file, subgroup_file, tolerance=0.01, spinor=False) -> SubgroupCorrelation: """Correlation of the irreps of a supergroup and a subgroup structure. The computation behind ``crystod-group --correlate --supergroup-poscar P --subgroup-poscar C`` (the offline counterpart of DCORREL of the Bilbao Crystallographic Server): for every special k point of the supergroup G (the points of ``crystod-bz --show-kpoint``), the small irreps of the subgroup H, the space group of the subgroup structure, that every irrep of G becomes. How it works: - ``SymmetryModeAnalysis`` maps the subgroup structure onto the supergroup structure (sublattice basis B, origin, the operations of H as parent operations); H is re-expressed in the basis B (``isotropy_subgroup.sublattice_operations``) and identified by spglib through a generic orbit (it must be the space group of the file). - The labels of H refer to the ISO-IR frame of the subgroup structure file (``crystod.isoir.canonical_iso_frame``, the frame of every other command on that file), carried onto the basis B; when the frame cannot be carried over, that of a generic orbit of H. - Arm a of a parent irrep (the full induced irrep of ``InducedRepresentation``, complex matrices before realification) carries k'_a = B q_a of H; the arms with equal k' modulo the reciprocal lattice of H form a sector, the sectors are grouped into stars of H, and the character tr(P_sector D(g)) on the little group of k' in H (evaluated at the parent operation whose translation is the one given to the labeler) is decomposed into the small irreps of H with ``IsoIRLabeler.decompose_characters``. - Checks: the character at the identity is the sector dimension, the dimensions add up per sector and over all stars of H to that of the parent irrep, every label carries the k name of its sector, and all sectors of one star of H give the same decomposition. Args: supergroup_file: The high-symmetry structure (POSCAR or CIF). subgroup_file: The low-symmetry structure of the same compound (POSCAR or CIF), whose space group is H. tolerance: Symmetry tolerance (symprec, Angstrom) for both files. spinor: Also correlate the double-valued (spinor) irreps (``--spinor``): after the single-valued rows of every block, one ``IrrepCorrelation`` with ``double_valued=True`` per double-valued irrep of G (a time-reversal pair once, as ``A/B``), named as ``crystod --spinor`` and ``--correlate-double-group`` name them (G in the frame of that command, H in the frame of the single-valued labels of H). Characters only: the arm characters chi(g^-1 h g) of the double-valued small irreps of G (spgrep, with the SU(2) sign of the conjugation) summed over a sector are decomposed into the double-valued small irreps of H, whose SU(2) matrices are those of G (one Cartesian frame, checked per operation). Checks as for the single-valued rows, and Res_H(Gamma x D(1/2)) = Res_H(Gamma) x D(1/2) for every single-valued irrep Gamma of G on every arm of H. Returns: A ``SubgroupCorrelation``. Raises: SystemExit: A file is missing or unreadable, or the subgroup structure cannot be mapped onto the supergroup structure (``ValueError`` through ``crystod.group``). RuntimeError: An internal consistency check failed. Example: >>> from crystod import group >>> result = group.subgroup_correlation("POSCAR_SrTiO3_Pm-3m", ... "POSCAR_SrTiO3_I4mcm") >>> rows = {(b.parent_k_name, b.child_k_name, r.parent_irrep): r.child_irreps ... for b in result.blocks for r in b.rows} >>> rows["R", "GM", "R4+"] [('GM1+', 1, 1), ('GM5+', 1, 2)] >>> rows["X", "M", "X1+"] [('M3+', 1, 1)] """ from .symmetry_mode import SymmetryModeAnalysis analysis = SymmetryModeAnalysis(str(supergroup_file), str(subgroup_file), float(tolerance)) ctx = _subgroup_context(analysis, str(subgroup_file)) algebra = ctx.algebra notes = [] if len(analysis.subgroup_members) > len(ctx.indices): notes.append( f"the displacement field keeps {len(analysis.subgroup_members)} parent " f"operations (per lattice translation of {analysis.child_symbol}), more than the " f"{len(ctx.indices)} of the subgroup structure, whose lattice breaks the others; " f"the space group of the subgroup structure, {analysis.child_symbol}, is used.") try: gamma = _family_at(ctx.labeler, np.zeros(3), ctx.rotations, ctx.translations) except Exception: gamma = None child_mulliken = _gamma_mulliken(gamma, ctx.cell, ctx.rotations) parent_mulliken = _parent_mulliken(algebra) sctx = _spinor_context(ctx) if spinor else None blocks = [] for kname in algebra.k_by_kname: blocks.extend(_correlate_star(ctx, _special_point_reps(algebra, kname), kname, "point", parent_mulliken, child_mulliken, sctx, algebra.k_by_kname[kname])) order = {name: n for n, name in enumerate(ctx.child_algebra.k_by_kname)} parent_order = {name: n for n, name in enumerate(algebra.k_by_kname)} blocks.sort(key=lambda b: (parent_order[b.parent_k_name], order.get(b.child_k_name, len(order)))) extra, left = _line_blocks(ctx, blocks, parent_mulliken, sctx) blocks.extend(extra) size = abs(int(round(np.linalg.det(ctx.B)))) n_point = len(ctx.rotations) frame_basis, frame_origin = _frame_setting( ctx.labeler, ctx.cell[0], ctx.B, algebra.primitive_matrix) return SubgroupCorrelation( parent_symbol=algebra.sg_type.international_short, parent_number=int(algebra.sg_type.number), child_symbol=ctx.child_algebra.sg_type.international_short, child_number=int(ctx.child_algebra.sg_type.number), parent_file=str(supergroup_file), child_file=str(subgroup_file), size=size, index=algebra.n_ops * size // n_point, basis=np.asarray(ctx.B), frame_basis=frame_basis, frame_origin=frame_origin, frame_source=ctx.frame_source, transformation=analysis.setting_transformation(), blocks=blocks, unreached=left, notes=notes, spinor=bool(spinor), spinor_notes=list(sctx.notes) if sctx is not None else [], parent_formula=str(getattr(analysis, "parent_formula", "") or ""), )
# ------------------- (c, --spinor) double-valued irreps of a group-subgroup pair @dataclass class _SpinorContext: """The double groups of G and H in one Cartesian frame. ``cell_g`` is the cell of ``--correlate-double-group`` (the generic structure of the ISO-IR labeler of G in the primitive basis of the algebra), so the names of G are those of that command; ``cell_h`` is a generic orbit of H in the basis B on the lattice B L_G, the same Cartesian frame, so spgrep lifts every operation of H to the SU(2) matrix it has in G. """ cell_g: tuple cell_h: tuple whole_g: object g_index: dict groups: dict = field(default_factory=dict) lifts: Counter = field(default_factory=Counter) notes: list = field(default_factory=list) def _spinor_context(ctx) -> _SpinorContext: """Build the double groups of G and H; raise when the frames disagree.""" import spglib from .spacegroup_product import DEN from .wavecar_irreps import little_group_data algebra = ctx.algebra cell_g = _spin_orbit_cell(algebra) whole = little_group_data(*cell_g, np.zeros(3), spinor=True) g_index = {} for i in range(algebra.n_ops): hits = [w for w, R in enumerate(whole.rotations) if np.array_equal(np.asarray(R, dtype=np.int64), algebra.rotations[i])] if len(hits) != 1: raise RuntimeError("internal error: the double group of the parent does not " "list every rotation once.") shift = np.array(algebra.translations[i], dtype=float) / DEN - whole.translations[hits[0]] if not np.allclose(shift, np.rint(shift), atol=1e-6): raise RuntimeError("internal error: the cell of the double group of the parent " "has another origin than the ISO-IR tables.") g_index[i] = hits[0] lattice_h = np.asarray(ctx.B, dtype=float) @ np.asarray(cell_g[0], dtype=float) cell_h = _orbit_cell(ctx.rotations, ctx.translations, lattice_h) dataset = spglib.get_symmetry_dataset(cell_h, symprec=1e-5) number = None if dataset is None else int( dataset["number"] if isinstance(dataset, dict) else dataset.number) if number != int(ctx.child_algebra.sg_type.number): raise RuntimeError("internal error: the orbit of the subgroup in the frame of the " "parent has another space group.") return _SpinorContext(cell_g=cell_g, cell_h=cell_h, whole_g=whole, g_index=g_index) def _h_direct_group(ctx, sctx, key): """``(single, double)`` little groups of H at k' = key/DEN, the double-valued names taken at k' (``double_valued_names``) with the single-valued labels of ``ctx.labeler`` (the frame of the single-valued rows).""" import dataclasses from .spacegroup_product import DEN from .wavecar_irreps import _little_group_data, double_valued_names, little_group_data key = tuple(int(x) % DEN for x in key) cached = sctx.groups.get(("direct", key)) if cached is not None: return cached k = np.asarray(key, dtype=float) / DEN single = little_group_data(*sctx.cell_h, k, spinor=False) double = _little_group_data(*sctx.cell_h, k, spinor=True, symprec=1e-5, symmetry_cell=None, transport=False) labelled = ctx.labeler.label_characters(k, list(single.rotations), list(single.translations), list(single.characters)) if labelled is None: raise RuntimeError(f"internal error: no ISO-IR labels of H at {_k_text(_k_fractions(key))}.") label_map, ktype = labelled labels = [label_map[m] for m in range(len(single.characters))] order = _operation_order(single, double) names, prints = double_valued_names( double.characters, double.spin_rotations, k, single.characters[:, order], labels, ktype, rotations=double.rotations, translations=double.translations, lattice=sctx.cell_h[0], frame=ctx.labeler, dims=double.dims) single = dataclasses.replace(single, names=labels, k_label=ktype, from_isoir=True) double = dataclasses.replace(double, names=names, fingerprints=prints, k_label=ktype, from_isoir=True, names_transported=False) sctx.groups[("direct", key)] = (single, double) return single, double def _h_groups(ctx, sctx, key): """:func:`_h_direct_group` with the double-valued names of the representative arm of the star of H carried to k' (the names every command prints on every arm).""" import dataclasses from .spacegroup_product import DEN from .wavecar_irreps import _names_from_representative_arm key = tuple(int(x) % DEN for x in key) cached = sctx.groups.get(("named", key)) if cached is not None: return cached single, double = _h_direct_group(ctx, sctx, key) def direct(k): return _h_direct_group(ctx, sctx, np.rint(np.asarray(k, dtype=float) * DEN))[1] carried = _names_from_representative_arm(double, ctx.labeler, single.rotations, single.translations, single.characters, direct) if carried is not None: double = dataclasses.replace(double, names=carried, names_transported=True) sctx.groups[("named", key)] = (single, double) return single, double def _operation_order(single, double) -> list: """For every operation of ``double``, its index in ``single``.""" def key(rotation, translation): return (np.asarray(rotation, dtype=np.int64).tobytes(), tuple(np.round(np.asarray(translation, dtype=float) % 1.0, 6) % 1.0)) position = {key(R, t): i for i, (R, t) in enumerate(zip(single.rotations, single.translations))} try: return [position[key(R, t)] for R, t in zip(double.rotations, double.translations)] except KeyError: raise RuntimeError("internal error: single- and double-valued little groups of H " "differ.") from None def _conjugated_character(base, k0, whole, g, rotation, translation, unitary, spinor): """The character vector (one entry per irrep of ``base``, the little group of k0) at the element {rotation|translation} (SU(2) matrix ``unitary``) of the little group of the arm k0 R_g^-1: chi(g^-1 h g), as ``transport_double_valued_names`` evaluates it.""" R_g = np.asarray(whole.rotations[g], dtype=np.int64) t_g = np.asarray(whole.translations[g], dtype=float) R_inv = np.rint(np.linalg.inv(R_g)).astype(np.int64) W1 = R_inv @ np.asarray(rotation, dtype=np.int64) @ R_g t1 = R_inv @ (np.asarray(rotation, dtype=float) @ t_g + translation - t_g) hits = [j for j, W in enumerate(base.rotations) if np.array_equal(np.asarray(W, dtype=np.int64), W1)] if len(hits) != 1: raise RuntimeError("internal error: a conjugated operation is not in the little " "group of the parent.") j = hits[0] n = t1 - np.asarray(base.translations[j], dtype=float) if not np.allclose(n, np.rint(n), atol=1e-6): raise RuntimeError("internal error: a conjugated translation is not a lattice " "vector of the parent.") sign = 1.0 if spinor: U_g = np.asarray(whole.spin_rotations[g], dtype=complex) U1 = U_g.conj().T @ unitary @ U_g if np.allclose(U1, -base.spin_rotations[j], atol=1e-6): sign = -1.0 elif not np.allclose(U1, base.spin_rotations[j], atol=1e-6): raise RuntimeError("internal error: the SU(2) matrices of the parent do not " "close under conjugation.") phase = np.exp(-2j * np.pi * float(np.asarray(k0, dtype=float) @ np.rint(n))) return sign * phase * np.asarray(base.characters[:, j], dtype=complex) def _arm_operation(whole, k0, arm): """An operation g of the parent (index into ``whole``) with k0 R_g^-1 = arm.""" for g, R in enumerate(whole.rotations): image = np.asarray(k0, dtype=float) @ np.linalg.inv(np.asarray(R, dtype=float)) d = image - np.asarray(arm, dtype=float) if np.allclose(d, np.rint(d), atol=1e-6): return g raise RuntimeError("internal error: an arm is not in the star of the parent k point.") def _sector_double_characters(ctx, sctx, base_single, base_double, k0, arms, key, members): """Characters of the parent irreps (single- and double-valued, all of them) on the sector of arms ``members`` at k' = key/DEN, on the operations of the little groups of H at k' as spgrep lists them (H's lift and translations): ``(single, double, chi_single, chi_double)``.""" from .spacegroup_product import DEN algebra = ctx.algebra single_h, double_h = _h_groups(ctx, sctx, key) whole = sctx.whole_g k_child = np.asarray(key, dtype=float) / DEN g_of = {a: _arm_operation(whole, k0, np.asarray(arms[a], dtype=float) / DEN) for a in members} def characters(group_h, base, spinor): out = np.zeros((len(base.characters), len(group_h.rotations)), dtype=complex) for column, (W, t_h) in enumerate(zip(group_h.rotations, group_h.translations)): js = [j for j, R in enumerate(ctx.rotations) if np.array_equal(np.asarray(R, dtype=np.int64), np.asarray(W, dtype=np.int64))] if len(js) != 1: raise RuntimeError("internal error: an operation of H is missing.") j = js[0] n = np.asarray(ctx.translations[j], dtype=float) - np.asarray(t_h, dtype=float) if not np.allclose(n, np.rint(n), atol=1e-6): raise RuntimeError("internal error: the translations of H differ.") i = ctx.indices[j] rotation = algebra.rotations[i] translation = (np.array(algebra.translations[i], dtype=float) / DEN + ctx.parent_translations[j]) unitary = np.asarray(whole.spin_rotations[sctx.g_index[i]], dtype=complex) lift = 1.0 if spinor: U_h = np.asarray(group_h.spin_rotations[column], dtype=complex) if np.allclose(U_h, unitary, atol=1e-6): sctx.lifts["same"] += 1 elif np.allclose(U_h, -unitary, atol=1e-6): sctx.lifts["opposite"] += 1 lift = -1.0 else: raise RuntimeError("internal error: H and G lift an operation to " "different SU(2) matrices.") # the element of H at the translation spgrep lists: exp(-2 pi i k'.n) less phase = np.exp(2j * np.pi * float(k_child @ np.rint(n))) for a in members: q = np.asarray(arms[a], dtype=np.int64) if np.any((q @ algebra.inverse_rotations[i] - q) % DEN): continue # h moves this arm: no diagonal block out[:, column] += lift * phase * _conjugated_character( base, k0, whole, g_of[a], rotation, translation, unitary, spinor) return out return (single_h, double_h, characters(single_h, base_single, False), characters(double_h, base_double, True)) def _decompose_counts(group, chi, what) -> np.ndarray: """Multiplicities of the irreps of ``group`` in the character rows ``chi`` (one row per source), checked to be non-negative integers.""" m = (chi @ np.conj(np.asarray(group.characters, dtype=complex)).T) / group.order counts = np.rint(m.real).astype(int) if np.max(np.abs(m - counts), initial=0.0) > 1e-6 or np.any(counts < 0): raise RuntimeError(f"internal error: the {what} do not decompose into the small " "irreps of H.") return counts def _pair_terms(counter, names, dims, reversal) -> list: """``[(label, n, dim)]`` with the irreps that time reversal pairs merged (``A/B`` for Wigner's case c, ``A/A`` for case b), in natural order.""" from .wavecar_irreps import _label_key left = dict(counter) dim_of = dict(zip(names, dims)) terms = [] for name in sorted(left, key=_label_key): n = left.get(name, 0) if not n: continue case, partner = (reversal or {}).get(name, ("a", name)) if case == "c" and left.get(partner) == n: first, second = sorted((name, partner), key=_label_key) terms.append((f"{first}/{second}", n, dim_of[name] + dim_of[partner])) left[partner] = 0 elif case == "b" and n % 2 == 0: terms.append((f"{name}/{name}", n // 2, 2 * dim_of[name])) else: terms.append((name, n, dim_of[name])) left[name] = 0 return terms def _spinor_blocks(ctx, sctx, k_int, blocks: dict) -> None: """Append the double-valued rows of the parent star of k_int (units 1/DEN) to its ``blocks`` (keyed by the sorted sector keys of the star of H), with the check Res_H(Gamma_i x D(1/2)) = Res_H(Gamma_i) x D(1/2).""" from .extract_irrep import _time_reversal from .spacegroup_product import DEN from .wavecar_irreps import little_group_data, spin_orbit_compatibility algebra = ctx.algebra k_int = np.mod(np.asarray(k_int, dtype=np.int64), DEN) k0 = k_int / DEN arms, _ = algebra._star_of_vector(k_int) base_single = little_group_data(*sctx.cell_g, k0, spinor=False) base_double = little_group_data(*sctx.cell_g, k0, spinor=True) product = spin_orbit_compatibility(*sctx.cell_g, k0) reversal_g = _time_reversal(base_double, *sctx.cell_g, 1e-5) or {} k_child = np.asarray(arms, dtype=np.int64) @ np.asarray(ctx.B, dtype=np.int64).T sectors: dict[tuple, list] = {} for a in range(len(arms)): sectors.setdefault(tuple(int(x) for x in k_child[a] % DEN), []).append(a) index_g = {name: m for m, name in enumerate(base_double.names)} for star in _h_stars(ctx, list(sectors)): owners = [identity for identity in blocks if set(star) <= set(identity)] if len(owners) != 1: raise RuntimeError("internal error: a star of H of the double-valued irreps has " "no single-valued block.") block = blocks[owners[0]] found = None for key in star: single_h, double_h, chi_s, chi_d = _sector_double_characters( ctx, sctx, base_single, base_double, k0, arms, key, sectors[key]) n_single = _decompose_counts(single_h, chi_s, "single-valued irreps of G") n_double = _decompose_counts(double_h, chi_d, "double-valued irreps of G") dims = np.asarray(double_h.dims) size = len(sectors[key]) if not np.array_equal(n_double @ dims, size * np.asarray(base_double.dims)): raise RuntimeError("internal error: the double-valued irreps of H do not add " "up to the dimensions of those of G.") # Res_H(Gamma_i x D(1/2)) = Res_H(Gamma_i) x D(1/2) order = _operation_order(single_h, double_h) traces = np.real(np.trace(double_h.spin_rotations, axis1=1, axis2=2)) spin_h = _decompose_counts( double_h, np.asarray(single_h.characters)[:, order] * traces[None, :], "products with D(1/2) of H") for i, label in enumerate(base_single.names): left = np.zeros(len(double_h.names), dtype=int) for name in product[str(label)]: left += n_double[index_g[name]] right = n_single[i] @ spin_h if not np.array_equal(left, right): raise RuntimeError( f"internal error: Res({label} x D(1/2)) and Res({label}) x D(1/2) " f"differ at {double_h.k_label} of H.") names = [str(name) for name in double_h.names] if found is None: found = (n_double, names, dims, double_h) elif sorted(zip(names, map(tuple, n_double.T))) != sorted( zip(found[1], map(tuple, found[0].T))): raise RuntimeError("internal error: the double-valued irreps of G decompose " "differently on two arms of a star of H.") n_double, names, dims, double_h = found reversal_h = _time_reversal(double_h, *sctx.cell_h, 1e-5) or {} merged = block.arms_merged rows, done = [], set() for d, name in enumerate(base_double.names): if name in done: continue case, partner = reversal_g.get(name, ("a", name)) counts = Counter({names[c]: int(n_double[d, c]) for c in range(len(names)) if n_double[d, c]}) label, dim = str(name), int(base_double.dims[d]) if case == "c" and partner in index_g and partner != name: other = index_g[partner] for c in range(len(names)): counts[names[c]] += int(n_double[other, c]) first, second = sorted((str(name), str(partner)), key=_label_key_) label, dim = f"{first}/{second}", dim + int(base_double.dims[other]) done.add(partner) elif case == "b": counts = Counter({n: 2 * v for n, v in counts.items()}) label, dim = f"{name}/{name}", 2 * dim done.add(name) rows.append(IrrepCorrelation( parent_irrep=label, parent_dim=dim, arms_merged=merged, child_irreps=_pair_terms(counts, names, [int(x) for x in dims], reversal_h), double_valued=True)) rows.sort(key=lambda row: _label_key_(row.parent_irrep.split("/")[0])) block.rows.extend(rows) _spinor_notes(sctx, block.child_k_name, ctx.child_algebra, double_h) _spinor_notes(sctx, base_double.k_label or "?", algebra, base_double) def _label_key_(label: str): from .wavecar_irreps import _label_key return _label_key(label) def _spinor_notes(sctx, k_name, algebra, group) -> None: """The ``spinor_numbering_notes`` of one k point of G or H, once each.""" from .crystal_orbital_spgrep import spinor_numbering_notes try: lines = spinor_numbering_notes(group.names, group.dims, group.rotations, group.characters) except Exception: # the notes are a remark: never stop the command lines = [] for line in lines: text = f"{k_name} of {algebra.sg_type.international_short}: {line}" if text not in sctx.notes: sctx.notes.append(text) def _arm_text(count: int) -> str: return f"{count} arm" + ("s" if count != 1 else "") def _block_header(result: SubgroupCorrelation, block: KpointCorrelation) -> list[str]: kinds = {"line": "symmetry line", "plane": "symmetry plane", "general point": "general point"} parent = f"{block.parent_k_name} {_k_text(block.parent_k)} of {result.parent_symbol}" if block.parent_kind in kinds: parent += f" ({kinds[block.parent_kind]})" child = f"{block.child_k_name} {_k_text(block.child_k)}" if block.child_k_conventional is not None and any(block.child_k_conventional): child += f" [conventional {_k_text(block.child_k_conventional)}]" child += f" of {result.child_symbol}" if block.parent_arms > 1 or block.child_arms > 1: if block.parent_arms_in_block < block.parent_arms: parent += f", {block.parent_arms_in_block} of {block.parent_arms} arms" else: parent += f", {_arm_text(block.parent_arms)}" child += f", {_arm_text(block.child_arms)}" pieces = [child] if block.arms_merged > 1: pieces.append(f"({block.arms_merged} arms of {result.parent_symbol} per arm of " f"{result.child_symbol})") lines = [f"{parent} ->"] for piece in pieces: if len(lines[-1]) + 1 + len(piece) <= 100: lines[-1] += " " + piece else: lines.append(" " + piece) return lines def _child_term(label: str, n: int, dim: int, mulliken: dict) -> str: text = f"{label}({dim})" if n > 1: text = f"{n} {text}" if label in mulliken: text += f" [{mulliken[label]}]" return text
[docs] def format_subgroup_correlation(result: SubgroupCorrelation) -> str: """The ``* Correlation of the irreps at the special k points *`` block. Args: result: The ``SubgroupCorrelation`` of ``subgroup_correlation``. Returns: The text (no trailing newline) the command prints after the transformation block: per parent star and star of H a header (the parent k, its arms, the k of H, its arms), one row per parent irrep with the dimension after every label, ``R4+(3) [T1g] -> GM1+(1) [A1g] + GM5+(2) [Eg]`` (``2 x LD1(1) -> N1(2)`` when two parent arms fall onto one arm of H), then the NOTE and note lines. """ lines = ["* Correlation of the irreps at the special k points *"] for number, block in enumerate(result.blocks): if number: lines.append("") lines.extend(_block_header(result, block)) # the single-valued rows, then the double-valued ones (--spinor), each # aligned on its own, so that the first are those of a run without it for rows in ([row for row in block.rows if not row.double_valued], [row for row in block.rows if row.double_valued]): if not rows: continue sources = [] for row in rows: source = f"{row.parent_irrep}({row.parent_dim})" if row.arms_merged > 1: source = f"{row.arms_merged} x {source}" if row.parent_mulliken: source += f" [{row.parent_mulliken}]" sources.append(source) width = max(len(source) for source in sources) for source, row in zip(sources, rows): terms = " + ".join(_child_term(label, n, dim, row.mulliken) for label, n, dim in row.child_irreps) lines.append(f" {source:<{width}} -> {terms}") notes = list(result.notes) + list(result.spinor_notes) if result.unreached: parts = [f"{name} {_k_text(k)}" for name, k, _, _, _ in result.unreached] sources = [f"{name} of {_k_text(q)} ({kind} {pname} of {result.parent_symbol})" for name, _, q, pname, kind in result.unreached] notes.append(f"{_and_join(parts)} of {result.child_symbol} " f"{'is the image' if len(parts) == 1 else 'are images'} of no special " f"point of {result.parent_symbol}: {', '.join(sources)}.") lines.append("") for note in notes: lines += textwrap.wrap(f"NOTE: {note}", width=100, subsequent_indent=" ", break_on_hyphens=False, break_long_words=False) merged = any(block.arms_merged > 1 for block in result.blocks) text = (f"note: the labels of {result.child_symbol} refer to its ISO-IR frame printed " "under * Subgroup *; [..] is the Mulliken symbol of an irrep at GM" + (f"; m x: m arms of {result.parent_symbol} fall onto one arm of " f"{result.child_symbol}" if merged else "") + ".") lines += textwrap.wrap(text, width=100, subsequent_indent=" ", break_on_hyphens=False, break_long_words=False) if result.spinor: from .crystal_orbital_spgrep import SPINOR_NAME_NOTE lines += [("note: double-valued rows (--spinor): A/B is a pair of irreps that time " "reversal makes"), " degenerate, A/A an irrep doubled by it.", SPINOR_NAME_NOTE] return "\n".join(lines)
def _and_join(items: list[str]) -> str: if len(items) <= 1: return "".join(items) return ", ".join(items[:-1]) + " and " + items[-1] def format_subgroup_header(result: SubgroupCorrelation) -> str: """The ``* Supergroup *``, ``* Subgroup *`` and ``* Transformation matrix (parent -> child) *`` blocks of the command.""" lines = [ "* Supergroup *", f"{result.parent_symbol} (No. {result.parent_number}): {result.parent_file}", "", "* Subgroup *", f"{result.child_symbol} (No. {result.child_number}): {result.child_file}", f"cell size {result.size}, index {result.index}", "sublattice basis (parent primitive units): " + ", ".join("(" + ",".join(str(int(x)) for x in row) + ")" for row in result.basis), f"labels of {result.child_symbol} in its ISO-IR frame (" + ("that of the subgroup structure file" if result.frame_source == "structure" else "that of a generic orbit of the subgroup") + "):", "basis (parent conventional units): " + ", ".join(_format_vector(row) for row in result.frame_basis), f"origin: {_format_vector(result.frame_origin)}", "", ] lines += result.transformation.lines( f"{result.parent_symbol} (No. {result.parent_number})", f"{result.child_symbol} (No. {result.child_number})") return "\n".join(lines) # ------------------------------------------- (b) compatibility along a line def _reciprocal_metric(algebra) -> np.ndarray: """Metric of the reciprocal lattice of a lattice with the full point symmetry (the invariant lattice of the isotropy machinery).""" g0 = np.diag([1.0, 1.07, 1.13]) g = sum(W.T @ g0 @ W for W in np.asarray(algebra.rotations, dtype=float)) return np.linalg.inv(g / algebra.n_ops) def _labeler_context(algebra): from .isoir import get_cached_labeler inputs = algebra._isoir_labeler_inputs() if inputs is None: raise SystemExit("ERROR: the ISO-IR labeler is not available for space group " f"{algebra.sg_type.number}.") cell, rotations, translations = inputs labeler = get_cached_labeler(algebra.sg_type.number, cell, 1e-5) if labeler is None: raise SystemExit("ERROR: the ISO-IR labeler is not available for space group " f"{algebra.sg_type.number}.") return labeler, rotations, translations def _segments(algebra, labeler, name0: str, name1: str) -> list[_Segment]: """Every symmetry line from the tabulated k0 to an arm (+ G) of the star of k1, with its first interior grid point and little group.""" from .spacegroup_product import DEN metric = _reciprocal_metric(algebra) M_inv = np.linalg.inv(algebra.primitive_matrix) tabulated = set() for kname in algebra.k_by_kname: arms, _ = algebra.star(kname) tabulated |= {tuple(int(x) for x in np.asarray(arm) % DEN) for arm in arms} k0 = np.asarray(algebra.k_by_kname[name0], dtype=np.int64) little0 = set(algebra.little_group(k0)) arms1, _ = algebra.star(name1) found: dict[tuple, _Segment] = {} names: dict[tuple, str | None] = {} # one k-type lookup per star (slow) for arm in arms1: for shift in np.ndindex(3, 3, 3): k1 = np.asarray(arm, dtype=np.int64) + DEN * (np.asarray(shift) - 1) d = k1 - k0 if not d.any(): continue ops = [ i for i in sorted(little0) if np.array_equal(d @ algebra.inverse_rotations[i], d) ] steps = int(np.gcd.reduce(np.abs(d))) unit = d // steps for j in range(1, steps): kdelta = k0 + unit * j if tuple(int(x) for x in kdelta % DEN) in tabulated: continue if sorted(algebra.little_group(kdelta)) != ops: continue star_arms, _ = algebra._star_of_vector(kdelta % DEN) star = min(tuple(int(x) for x in arm) for arm in star_arms) if star not in names: names[star] = labeler.kpoint_name((kdelta / DEN) @ M_inv) name = names[star] key = (name, tuple(int(x) for x in k1)) # dimension of the k subspace fixed by the little co-group: # 1 for a symmetry line, 2 for a plane, 3 for a general point Q = np.mean([np.asarray(algebra.inverse_rotations[i], dtype=float) for i in ops], axis=0) found[key] = _Segment( name0, name1, k0, k1, kdelta, ops, name or "?", float(np.sqrt(d @ metric @ d)) / DEN, int(np.linalg.matrix_rank(Q, tol=1e-6)), ) break return list(found.values()) def _segment_rank(segment: _Segment, tabulated_k1) -> tuple: k1 = segment.k1 return ( -len(segment.ops), round(segment.length, 6), 0 if np.array_equal(k1, tabulated_k1) else 1, int(np.sum(k1 < 0)), tuple(int(-x) for x in k1), ) def _choose_segments(algebra, labeler, name0, names1, line, strict): chosen = [] available = {} for name1 in names1: segments = _segments(algebra, labeler, name0, name1) available[name1] = sorted({s.line for s in segments}) if line is not None: segments = [s for s in segments if s.line.upper() == line.upper()] elif not strict: segments = [s for s in segments if s.fixed_dimension == 1] if not segments: continue tabulated = np.asarray(algebra.k_by_kname[name1], dtype=np.int64) chosen.append(min(segments, key=lambda s: _segment_rank(s, tabulated))) return chosen, available def _relations_of_segment(algebra, labeler, conv_R, conv_t, segment) -> list[Compatibility]: from .spacegroup_product import DEN, SIGMA k_conv = (segment.kdelta / DEN) @ np.linalg.inv(algebra.primitive_matrix) little_R = [conv_R[i] for i in segment.ops] little_t = [conv_t[i] for i in segment.ops] records = [] for name, k_end in ((segment.name0, segment.k0), (segment.name1, segment.k1)): delta = segment.kdelta - k_end phases = np.array([ np.exp(SIGMA * 2j * np.pi * float(delta @ algebra.translations[i]) / DEN**2) for i in segment.ops ]) for irrep in algebra.irreps_by_kname[name]: try: arms, C = algebra.induced_characters(irrep) except SystemExit as exc: raise SystemExit( f"ERROR: the small characters of {irrep.name} are not available " f"({str(exc).removeprefix('ERROR: ')})" ) from None matches = [a for a, arm in enumerate(arms) if np.all((np.asarray(arm) - k_end) % DEN == 0)] if not matches: raise RuntimeError(f"internal error: {segment.name1} arm not in the star.") a = matches[0] identity = algebra._rotation_index[algebra._key(np.eye(3))] dimension = int(round(C[identity, a].real)) characters = np.array([C[i, a] for i in segment.ops]) * phases result = labeler.decompose_characters(k_conv, little_R, little_t, characters) if result is None: raise RuntimeError( f"internal error: {irrep.name} does not decompose into small " f"irreps of the line {segment.line}." ) total = sum(n * dim for _, n, dim in result[0]) if total != dimension: raise RuntimeError( f"internal error: the line irreps of {irrep.name} add up to " f"{total} dimensions, the irrep has {dimension}." ) records.append(Compatibility( k0_label=name, k0_irrep=irrep.name, line_label=result[1], line_irreps=[(label, int(n)) for label, n, _ in result[0]], dimension=dimension, k_point=_k_fractions(k_end), k_delta=_k_fractions(segment.kdelta), fixed_dimension=segment.fixed_dimension, )) return records
[docs] def compatibility_relations(sg, k0, k1=None, line=None) -> list[Compatibility]: """Compatibility relations between special points along symmetry lines. The computation behind ``crystod-group --correlate-kpath --sg SG --kpoint K0 K1 [--line L]``. Args: sg: Space-group number or international symbol. k0: The first special point: ISO-IR name (``"GM"``, ``"X"``; ``G`` and ``GAMMA`` mean ``GM``) or three primitive coordinates. k1: The second special point, in the same forms; ``None`` takes every other tabulated special point joined to k0 by a symmetry line. line: ISO-IR name of the line (``"DT"``) when several lines join the two points; ``None`` takes the line with the largest little group (then the shortest). Returns: ``Compatibility`` records: for every line, the small irreps at k0 and then those at the other end, in table order. Raises: SystemExit: Unknown space group or k point, the same point twice, or no symmetry line (of the requested name) between the points (``ValueError`` through ``crystod.group``). RuntimeError: An internal consistency check failed (a restriction that does not decompose, or dimensions that do not add up). Example: >>> from crystod import group >>> rows = group.compatibility_relations("Pm-3m", "GM", "X") >>> [(r.k0_irrep, r.line_irreps) for r in rows if r.k0_irrep == "GM4-"] [('GM4-', [('DT1', 1), ('DT5', 1)])] """ from .isotropy_subgroup import resolve_special_kpoint from .spacegroup_product import SpaceGroupIrrepAlgebra algebra = SpaceGroupIrrepAlgebra(str(sg)) name0 = resolve_special_kpoint(algebra, k0) labeler, conv_R, conv_t = _labeler_context(algebra) group_text = (f"{algebra.sg_type.international_short} " f"(No. {algebra.sg_type.number})") if k1 is not None: name1 = resolve_special_kpoint(algebra, k1) if name1 == name0: raise SystemExit(f"ERROR: give two different special points (both are {name0}).") names1 = [name1] else: names1 = [name for name in algebra.k_by_kname if name != name0] segments, available = _choose_segments( algebra, labeler, name0, names1, line, strict=k1 is not None ) if not segments: if k1 is not None: lines = ", ".join(available[names1[0]]) or "none" wanted = f"line named {line}" if line is not None else "symmetry line" raise SystemExit( f"ERROR: no {wanted} joins {name0} and {names1[0]} in {group_text}; " f"the segments between them lie on: {lines}." ) wanted = f" named {line}" if line is not None else "" raise SystemExit(f"ERROR: no symmetry line{wanted} starts at {name0} in {group_text}.") records = [] for segment in segments: records.extend(_relations_of_segment(algebra, labeler, conv_R, conv_t, segment)) return records
[docs] def format_compatibility(records: list[Compatibility]) -> str: """The ``* Compatibility relations *`` block as text. Args: records: The records returned by ``compatibility_relations``. Returns: The text block (no trailing newline): per line a header naming the line, its end points and kdelta, then one line per small irrep of each end point, e.g. ``GM4- -> DT1 + DT5``. """ lines = ["* Compatibility relations *"] groups: dict[tuple, list[Compatibility]] = {} for record in records: groups.setdefault( (record.line_label, record.k_delta, record.fixed_dimension), [] ).append(record) kinds = {1: "line", 2: "plane", 3: "general segment"} for (line_label, k_delta, fixed), group in groups.items(): ends: dict[str, tuple] = {} for record in group: ends.setdefault(record.k0_label, record.k_point) between = " and ".join(f"{name} {_k_text(k)}" for name, k in ends.items()) lines.append(f"{kinds.get(fixed, 'line')} {line_label} between {between}, labeled at " f"kdelta = {_k_text(k_delta)} (primitive basis)") width = max(len(record.k0_irrep) for record in group) for record in group: terms = " + ".join( f"{n} {label}" if n > 1 else label for label, n in record.line_irreps ) lines.append(f" {record.k0_irrep:<{width}} (dim {record.dimension}) -> {terms}") return "\n".join(lines)
# ------------------------- (d) spin-orbit coupling: single -> double-valued _SPIN_ORBIT_KINDS = {0: "point", 1: "line", 2: "plane", 3: "general point"} def _spin_orbit_cell(algebra): """A primitive cell whose space group is exactly the group of ``algebra``. The generic two-orbit structure of the ISO-IR labeler (conventional setting of the ISO-IR table operations) reduced with ``algebra.primitive_matrix``: its basis is the primitive basis of the algebra, so the tabulated k vectors need no conversion, and spglib carries it into the same ISO-IR frame as the labeler of every other mode. Returns: ``(lattice, positions, numbers)``: lattice vectors as rows (Angstrom), fractional positions and species ids. Raises: SystemExit: The ISO-IR labeler is not available for the group. RuntimeError: The reduction did not give a primitive cell. """ inputs = algebra._isoir_labeler_inputs() if inputs is None: raise SystemExit("ERROR: the ISO-IR labeler is not available for space group " f"{algebra.sg_type.number}.") (lattice, positions, numbers), _, _ = inputs M = np.asarray(algebra.primitive_matrix, dtype=float) primitive_lattice = M.T @ np.asarray(lattice, dtype=float) fractional = (np.asarray(positions, dtype=float) @ np.linalg.inv(M).T) % 1.0 seen: set = set() kept_positions, kept_numbers = [], [] for position, number in zip(fractional, numbers): key = (int(number),) + tuple(int(v) % 1_000_000 for v in np.rint(position * 1e6)) if key in seen: continue seen.add(key) kept_positions.append(position) kept_numbers.append(int(number)) if len(kept_positions) * int(round(1.0 / abs(np.linalg.det(M)))) != len(positions): raise RuntimeError("internal error: the generic structure of space group " f"{algebra.sg_type.number} does not reduce to a primitive cell.") return primitive_lattice, np.array(kept_positions), np.array(kept_numbers, dtype=int) def _k_kind(algebra, k) -> str: """``line``, ``plane`` or ``general point`` for k off the special points: the dimension of the k subspace fixed by its little co-group.""" k = np.asarray(k, dtype=float) ops = [] for W in algebra.inverse_rotations: shift = k @ W - k if np.allclose(shift, np.rint(shift), atol=1e-8): ops.append(np.asarray(W, dtype=float)) rank = int(np.linalg.matrix_rank(np.mean(ops, axis=0), tol=1e-6)) return _SPIN_ORBIT_KINDS.get(rank, "point") def _off_special_kpoint(coordinates) -> tuple[np.ndarray, tuple]: """k off the special points, as it is computed, classified and printed. Each coordinate is reduced into (-1, 1) by an integer (k + G has the same relations) and snapped as ``crystod.wavecar_irreps.little_group_data`` snaps it (onto a fraction with a denominator up to 48 when within 1e-6), so that ``0.1 0.1000001 0.3`` is the point (1/10, 1/10, 3/10) of the mirror plane throughout. Args: coordinates: Three ``Fraction`` values (primitive basis). Returns: ``(k, k_point)``: k as floats and the coordinates as ``Fraction`` values (a snapped coordinate as its fraction, any other as given). """ from .wavecar_irreps import _K_DENOMINATOR, _snap_kpoint reduced = [value - int(value) for value in coordinates] vector = _snap_kpoint([float(value) for value in reduced]) vector = vector - np.trunc(vector) + 0.0 # 0.9999999 snaps onto 1, i.e. 0 k_point = [] for value, snapped in zip(reduced, vector): fraction = Fraction(float(snapped)).limit_denominator(_K_DENOMINATOR) k_point.append(fraction if float(fraction) == float(snapped) else value) return vector, tuple(k_point) def _k_header_text(values) -> str: """The coordinates of a header: fractions with denominators up to 48 as fractions, any other coordinate with three decimals (so that a header stays within 100 columns whatever the input).""" from .wavecar_irreps import _K_DENOMINATOR return "(" + ", ".join( str(value) if isinstance(value, Fraction) and value.denominator <= _K_DENOMINATOR else f"{float(value):.3f}" for value in values) + ")" def _spin_orbit_targets(algebra, k) -> list[tuple]: """The k points of ``spin_orbit_relations``: ``(name, k, k as Fractions, kind)``, name None off the special points.""" from .isotropy_subgroup import resolve_special_kpoint from .spacegroup_product import DEN if k is None: return [(name, np.asarray(k_int, dtype=float) / DEN, _k_fractions(k_int), "point") for name, k_int in algebra.k_by_kname.items()] if isinstance(k, str): tokens = k.replace(",", " ").split() else: try: values = list(k) except TypeError: values = [k] tokens = [piece for value in values for piece in ( value.replace(",", " ").split() if isinstance(value, str) else [value])] coordinates = None if len(tokens) == 3: try: coordinates = [Fraction(token) if isinstance(token, str) else Fraction(float(token)).limit_denominator(10**6) for token in tokens] except (TypeError, ValueError, ZeroDivisionError): coordinates = None if len(tokens) == 1 and isinstance(tokens[0], str): # an irrep label is answered with its k point (the message of # resolve_special_kpoint points to --irrep, which this mode lacks) for irreps in algebra.irreps_by_kname.values(): for irrep in irreps: if irrep.name.upper() == tokens[0].upper(): raise SystemExit( f'ERROR: "{tokens[0]}" is an irrep label of ' f"{algebra.sg_type.international_short} (No. " f"{algebra.sg_type.number}), not a k point; its k point is " f"{irrep.kpname} (--kpoint {irrep.kpname})." ) try: name = resolve_special_kpoint(algebra, tokens) except SystemExit as exc: if coordinates is None: if len(tokens) == 1 and isinstance(tokens[0], str): raise SystemExit( f"{exc}\nA point on a symmetry line or plane is given by its three " "coordinates, e.g. --kpoint 0 1/4 0." ) from None raise # a symmetry line or plane, or a general point: classified, printed # and labelled at one and the same k, the one little_group_data uses vector, k_point = _off_special_kpoint(coordinates) return [(None, vector, k_point, _k_kind(algebra, vector))] k_int = algebra.k_by_kname[name] return [(name, np.asarray(k_int, dtype=float) / DEN, _k_fractions(k_int), "point")] def _spin_orbit_block(algebra, cell, name, k, k_point, kind) -> list[SpinOrbitRelation]: """The ``SpinOrbitRelation`` records of one k point, checked.""" from .crystal_orbital_spgrep import spinor_numbering_notes from .wavecar_irreps import ( _LABEL_RE, _label_key, little_group_data, spin_orbit_compatibility, ) where = name if name is not None else _k_text(k_point) try: table = spin_orbit_compatibility(*cell, k) single = little_group_data(*cell, k, spinor=False) double = little_group_data(*cell, k, spinor=True) except ValueError as exc: raise RuntimeError(f"the small irreps at {where} could not be built ({exc})") from None labels = [str(label) for label in single.names] if sorted(table) != sorted(labels): raise RuntimeError(f"internal error: the relations at {where} do not cover the " "single-valued small irreps.") notes: list[str] = [] if single.from_isoir: expected = name if name is not None else str(single.k_label) letters = {match["k"] if match is not None else None for match in map(_LABEL_RE.match, labels)} if letters != {expected}: raise RuntimeError( f"internal error: the single-valued small irreps at {where} were labeled " f"{', '.join(labels)}, not {expected}: the frame of the cell does not " "match the ISO-IR tables." ) if name is not None: order = [irrep.name for irrep in algebra.irreps_by_kname[name]] if sorted(order) != sorted(labels): raise RuntimeError( f"internal error: the single-valued small irreps at {name} were labeled " f"{', '.join(labels)}; the ISO-IR table has {', '.join(order)}." ) else: order = sorted(labels, key=_label_key) k_label = expected try: notes = spinor_numbering_notes(double.names, double.dims, double.rotations, double.characters) except Exception: # the notes are a remark: never stop the command notes = [] else: order = labels k_label = name if name is not None else "?" notes = ["all double-valued irreps keep generic names: no ISO-IR labels for the " "single-valued irreps"] double_names = [str(n) for n in double.names] if len(set(double_names)) != len(double_names): notes.append("the double-valued names are not unique here; read the multiplicities " "by name with care") double_dimensions = {n: int(d) for n, d in zip(double_names, double.dims)} single_dimensions = {str(n): int(d) for n, d in zip(single.names, single.dims)} records = [] column = Counter() for label in order: counts = Counter(table[label]) pairs = [(str(n), int(counts[n])) for n in dict.fromkeys(table[label])] total = sum(m * double_dimensions[n] for n, m in pairs) if total != 2 * single_dimensions[label]: raise RuntimeError(f"internal error: {label} x D(1/2) has {total} dimensions, " f"not {2 * single_dimensions[label]}.") for n, m in pairs: column[n] += m * single_dimensions[label] records.append(SpinOrbitRelation( k_label=k_label, k_kind=kind, k_point=tuple(k_point), irrep=label, dimension=single_dimensions[label], double_irreps=pairs, double_dimensions=dict(double_dimensions), notes=list(notes), )) # D(1/2) is self-conjugate, so sum_i m_ij dim Gamma_i = dim(Delta_j x D(1/2)) for n, dimension in double_dimensions.items(): if column[n] != 2 * dimension: raise RuntimeError(f"internal error: the double-valued irrep {n} at {where} " f"occurs with {column[n]} dimensions of single-valued " f"irreps, not {2 * dimension}.") return records
[docs] def spin_orbit_relations(sg, k=None) -> list[SpinOrbitRelation]: """Single-valued small irreps and the double-valued ones they become. The computation behind ``crystod-group --correlate-double-group --sg SG [--kpoint K]``: for every single-valued (spinless) small irrep Gamma at k, the double-valued (spinor) small irreps of Gamma x D(1/2), i.e. what a level of a scalar-relativistic band structure becomes when spin-orbit coupling is switched on. The single-valued labels are the ISO-IR labels of every other ``crystod-group`` mode and the double-valued names those of ``crystod --spinor`` (``-R6+``; Bradley & Cracknell's numbering with the exceptions of ``crystod.wavecar_irreps.double_valued_names``). Args: sg: Space-group number or international symbol. k: The ISO-IR name of a special point (``"R"``; ``G`` and ``GAMMA`` mean ``GM``), three primitive coordinates (numbers, or strings such as ``"1/2"``; any arm of a star, any k + G), or ``None`` for every tabulated special point of the group. Coordinates off the special points give the relations on that symmetry line or plane or at that general point, at the coordinates given, reduced into (-1, 1) by an integer and snapped onto fractions with denominators up to 48 within 1e-6 (``0.1000001`` is 1/10). Returns: ``SpinOrbitRelation`` records, one per single-valued small irrep: k point by k point in the order of the ISO-IR tables, and in table order at each special point (natural order off them). Raises: SystemExit: Unknown space group or k-point name, or a malformed k point (``ValueError`` through ``crystod.group``). RuntimeError: An internal consistency check failed (labels of another k point or another frame, multiplicities that violate the dimension or reciprocity checks). Example: >>> from crystod import group >>> rows = group.spin_orbit_relations("Pm-3m", "R") >>> [(r.irrep, r.dimension, r.double_irreps) for r in rows][3] ('R4+', 3, [('-R6+', 1), ('-R8+', 1)]) """ from .spacegroup_product import SpaceGroupIrrepAlgebra algebra = SpaceGroupIrrepAlgebra(str(sg)) targets = _spin_orbit_targets(algebra, k) cell = _spin_orbit_cell(algebra) records: list[SpinOrbitRelation] = [] for name, vector, k_point, kind in targets: records.extend(_spin_orbit_block(algebra, cell, name, vector, k_point, kind)) return records
[docs] def format_spin_orbit_relations(records: list[SpinOrbitRelation]) -> str: """The ``* Compatibility relations *`` blocks of the spin-orbit relations. Args: records: The records returned by ``spin_orbit_relations``. Returns: The text (no trailing newline): one block per k point, separated by a blank line, each with a header naming the k point and its coordinates (primitive basis), one line per single-valued small irrep with the dimension after every label, e.g. ``R4+(3) -> -R6+(2) + -R8+(4)`` (a multiplicity in front, as ``GM1(1) -> 2 -GM2(1)``), and the NOTE lines of the k point. """ groups: dict[tuple, list[SpinOrbitRelation]] = {} for record in records: groups.setdefault((record.k_label, tuple(record.k_point)), []).append(record) blocks = [] for (k_label, k_point), group in groups.items(): kind = "k point" if group[0].k_kind == "point" else group[0].k_kind lines = ["* Compatibility relations *", f"{kind} {k_label} {_k_header_text(k_point)} (primitive basis): " "irrep x D(1/2) -> double-valued irreps"] sources = [f"{record.irrep}({record.dimension})" for record in group] width = max(len(source) for source in sources) for source, record in zip(sources, group): terms = " + ".join( f"{n} {name}({record.double_dimensions[name]})" if n > 1 else f"{name}({record.double_dimensions[name]})" for name, n in record.double_irreps ) lines.append(f" {source:<{width}} -> {terms}") for note in group[0].notes: lines += textwrap.wrap(f"NOTE: {note}", width=78, subsequent_indent=" ", break_on_hyphens=False, break_long_words=False) blocks.append("\n".join(lines)) return "\n\n".join(blocks)
# ------------------------------------- (a) point-group correlation tables # the two settings phonopy tabulates for these point groups, by the full # symbol of the setting (character_table[pg][0] and [1]) _SETTING_NAMES = { "-42m": ("-42m", "-4m2"), "3m": ("3m1", "31m"), "-3m": ("-3m1", "-31m"), "-6m2": ("-6m2", "-62m"), } # the class of phonopy's table of H whose axis is printed as the axis of an # orientation (the z axis of the table); None for 1, -1 and the cubic groups _PRINCIPAL_CLASS = { "2": "C2", "m": "sgh", "2/m": "C2", "222": "C2", "mm2": "C2", "mmm": "C2", "4": "C4", "-4": "S4", "4/m": "C4", "422": "C4", "4mm": "C4", "-42m": "S4", "4/mmm": "C4", "3": "C3", "-3": "S6", "32": "C3", "3m": "C3", "-3m": "S6", "6": "C6", "-6": "S3", "6/m": "C6", "622": "C6", "6mm": "C6", "-6m2": "S3", "6/mmm": "C6", }
[docs] @dataclass class CorrelationTable: """The correlation table of a point group G and one subgroup type H. Attributes: parent: The point group G (phonopy's symbol, e.g. ``"m-3m"``). subgroup: The subgroup type H (``"4/mmm"``). orientations: One ``(description, rotations)`` pair per conjugacy class of subgroups of type H in G (the inequivalent orientations): the column header (``"4/mmm (4 || z)"``) and the rotation matrices of the representative subgroup, in the axes of the table of G, as an ``(|H|, 3, 3)`` integer array. rows: ``{irrep of G: decompositions}`` in the order of the table of G, with one decomposition per orientation: a list of ``(Mulliken symbol of H, multiplicity)`` pairs in the order of the table of H. A complex-conjugate pair that phonopy's table merges into one real ``E`` keeps that symbol. conjugates: Number of subgroups conjugate to each representative. settings: The setting of phonopy's table of H each orientation is labeled with (``"-4m2"``; ``""`` for the groups with one setting). axes: Per orientation, the classes of H that fix its orientation about the principal axis, with their elements in the axes of G (``"C2' = 2_x, 2_y; C2'' = 2_[110], 2_[1-10]"``); the symbols B1/B2/B3 refer to them. parent_order: Order of G. subgroup_order: Order of H. hexagonal_axes: ``True`` when the table of G uses hexagonal axes (trigonal and hexagonal G): directions are then ``[uvw]`` in those axes, otherwise ``x``/``y``/``z`` along the cell axes. """ parent: str subgroup: str orientations: list rows: dict conjugates: list = field(default_factory=list) settings: list = field(default_factory=list) axes: list = field(default_factory=list) parent_order: int = 0 subgroup_order: int = 0 hexagonal_axes: bool = False
def _point_group_table(pg: str, setting: int = 0) -> dict: """phonopy's character table of a point group (one setting).""" from phonopy.phonon.character_table import character_table if pg not in character_table: available = ", ".join(character_table) raise SystemExit(f'ERROR: "{pg}" is not in the point groups.\nChoose from: {available}') return character_table[pg][setting] def _table_classes(table: dict) -> list[str]: names = table["rotation_list"] return [names] if isinstance(names, str) else list(names) def _table_operations(table: dict) -> list[tuple[np.ndarray, str]]: """``(rotation, class name)`` for every element of a table, class by class.""" return [ (np.array(rotation, dtype=int), name) for name in _table_classes(table) for rotation in table["mapping_table"][name] ] def _table_characters(table: dict) -> dict: """``{irrep: {class: character}}`` of a table (scalars of point group 1 made vectors).""" classes = _table_classes(table) return { irrep: dict(zip(classes, np.atleast_1d(np.asarray(values, dtype=complex)))) for irrep, values in table["character_table"].items() } def _closure(seed, table_product, identity: int) -> frozenset: group = set(seed) | {identity} while True: grown = group | {int(table_product[a, b]) for a in group for b in group} if grown == group: return frozenset(group) group = grown def _all_subgroups(table_product, identity: int) -> set: """Every subgroup of a finite group given by its multiplication table, grown from the cyclic subgroups by adjoining one element at a time.""" n = len(table_product) layer = {_closure([a], table_product, identity) for a in range(n)} found = set(layer) while layer: larger = set() for group in layer: for a in range(n): if a not in group: joined = _closure(group | {a}, table_product, identity) if joined not in found: found.add(joined) larger.add(joined) layer = larger return found def _integer_direction(vector) -> np.ndarray: """The shortest integer vector along ``vector``, first nonzero entry > 0.""" v = np.asarray(vector, dtype=float) v = v / np.abs(v).max() for scale in range(1, 13): w = v * scale if np.allclose(w, np.rint(w), atol=1e-6): w = np.rint(w).astype(int) break else: # pragma: no cover - lattice directions of point-group axes are short raise RuntimeError("internal error: an axis is not a lattice direction.") w = w // np.gcd.reduce(np.abs(w)) if w[np.flatnonzero(w)[0]] < 0: w = -w return w def _element_kind(R) -> tuple[str, np.ndarray | None]: """Hermann-Mauguin symbol (``4``, ``-4``, ``m``, ...) and axis of a rotation in lattice axes (for a mirror the normal: the direction it reverses); the axis is ``None`` for 1 and -1.""" R = np.asarray(R, dtype=float) det = int(round(np.linalg.det(R))) proper = R * det order = {3: 1, -1: 2, 0: 3, 1: 4, 2: 6}[int(round(np.trace(proper)))] if det > 0: symbol = str(order) else: symbol = {1: "-1", 2: "m", 3: "-3", 4: "-4", 6: "-6"}[order] if order == 1: return symbol, None w, v = np.linalg.eig(proper) axis = v[:, int(np.argmin(np.abs(w - 1.0)))].real return symbol, _integer_direction(axis) def _direction_text(axis, orthogonal: bool) -> str: """``x``/``y``/``z`` for the axes of an orthogonal table, else ``[uvw]``.""" if orthogonal and np.count_nonzero(axis) == 1: return "xyz"[int(np.flatnonzero(axis)[0])] return "[" + "".join(str(int(x)) for x in axis) + "]" def _element_text(R, orthogonal: bool) -> str: symbol, axis = _element_kind(R) if axis is None: return symbol direction = _direction_text(axis, orthogonal) return f"{symbol}_{direction}" def _axis_key(axis) -> tuple: """Order of preference of axes: z, x, y, then face and body diagonals.""" if axis is None: return (0,) a = np.abs(axis) nonzero = int(np.count_nonzero(axis)) return ( nonzero, -int(a[2]) if nonzero == 1 else 0, int(a[2] != 0) if nonzero == 2 else 0, tuple(-int(x) for x in a), tuple(-int(x) for x in axis), ) def _generators(rotations: list[np.ndarray]) -> list[np.ndarray]: """A small generating set of a matrix group (greedy, in list order).""" keys = {R.tobytes() for R in rotations} span = {np.eye(3, dtype=int).tobytes()} generators: list[np.ndarray] = [] for R in rotations: if R.tobytes() in span: continue generators.append(R) members = [np.frombuffer(k, dtype=int).reshape(3, 3) for k in span] + [R] while True: grown = {(A @ B).tobytes() for A in members for B in members} | { M.tobytes() for M in members } if len(grown) == len(members): break members = [np.frombuffer(k, dtype=int).reshape(3, 3) for k in grown] span = {M.tobytes() for M in members} if span == keys: break return generators def _conjugated_classes(rotations, X, table_ops) -> list[str] | None: """Class names of ``X^-1 R X`` in a table, or ``None`` when some image is not an element of it.""" lookup = {R.tobytes(): name for R, name in table_ops} X_inv = np.linalg.inv(X) classes = [] for R in rotations: image = X_inv @ R @ X if not np.allclose(image, np.rint(image), atol=1e-6): return None name = lookup.get(np.rint(image).astype(int).tobytes()) if name is None: return None classes.append(name) if len(set(lookup)) != len(rotations): return None return classes def _solve_conjugation(rotations, table_ops) -> list[list[str]]: """Class names of the elements of a matrix group under every isomorphism ``R -> X^-1 R X`` onto the elements of a table (generators mapped to elements of the same kind, ``R X = X T`` solved for X), one list per distinct assignment.""" import itertools generators = _generators(rotations) def kind(R): return (round(float(np.linalg.det(R))), int(round(float(np.trace(R))))) candidates = [[T for T, _ in table_ops if kind(T) == kind(g)] for g in generators] eye = np.eye(3) weights = np.array([1.0, 0.37, 0.61, 0.83, 0.29, 0.47, 0.71, 0.19, 0.53]) found: list[list[str]] = [] for images in itertools.product(*candidates): system = np.vstack([ np.kron(eye, g) - np.kron(np.asarray(t, dtype=float).T, eye) for g, t in zip(generators, images) ]) _, s, vh = np.linalg.svd(system) null = vh[np.sum(s > 1e-8):] if not len(null): continue X = (weights[: len(null)] @ null).reshape(3, 3, order="F") if abs(np.linalg.det(X)) < 1e-8: continue classes = _conjugated_classes(rotations, X, table_ops) if classes is not None and classes not in found: found.append(classes) return found def _assignment_key(rotations, classes, subgroup: str, setting: int) -> tuple: """Preference among class assignments: the principal axis first (z before x before diagonals), then the axes of the other classes in the order of the table.""" members: dict[str, list] = {} for R, name in zip(rotations, classes): members.setdefault(name, []).append(_axis_key(_element_kind(R)[1])) principal = _PRINCIPAL_CLASS.get(subgroup) head = min(members[principal]) if principal in members else (0,) names = _table_classes(_point_group_table(subgroup, setting)) return (head, tuple(min(members.get(name, [(0,)])) for name in names)) def _embedding(rotations, subgroup: str) -> tuple[int, list[str]] | None: """The setting of phonopy's table of H and the class of every element of a subgroup of type H given in the axes of G: the axes of G as they are; otherwise spglib's transformation to the standard orientation and the conjugations found for the generators (needed for a subgroup that spglib leaves in a non-standard orientation, such as mm2 with the twofold axis along x), of which the one whose principal axis comes first (z before x before diagonals, ``_assignment_key``) is kept, a tie going to spglib's (so the diagonal mmm of 4/mmm keeps C2z = 2_z).""" import spglib settings = range(len(_all_tables(subgroup))) tables = [_table_operations(_point_group_table(subgroup, s)) for s in settings] for s in settings: classes = _conjugated_classes(rotations, np.eye(3), tables[s]) if classes is not None: return s, classes # candidates: spglib's transformation first, then the solver's # assignments in order of preference; the principal axis decides (z # before x before diagonals) and a tie keeps the earlier candidate candidates: list[tuple[int, list[str]]] = [] _, _, P = spglib.get_pointgroup(np.asarray(rotations, dtype="intc")) P = np.asarray(P, dtype=float) if abs(np.linalg.det(P)) > 1e-8: for s in settings: classes = _conjugated_classes(rotations, P, tables[s]) if classes is not None: candidates.append((s, classes)) break for s in settings: found = _solve_conjugation(rotations, tables[s]) if found: found.sort(key=lambda c: _assignment_key(rotations, c, subgroup, s)) candidates += [(s, c) for c in found] break if not candidates: return None return min(candidates, key=lambda sc: _assignment_key(rotations, sc[1], subgroup, sc[0])[0]) def _all_tables(pg: str) -> list: from phonopy.phonon.character_table import character_table _point_group_table(pg) return character_table[pg] @dataclass class _Census: """The subgroups of a point group, by type and conjugacy class.""" ops: list orthogonal: bool by_type: dict @functools.lru_cache(maxsize=None) def _subgroup_census(pg: str) -> _Census: """Every subgroup of the point group (phonopy's table, setting 0), identified with ``spglib.get_pointgroup`` and grouped into conjugacy classes under the group: ``{type: [[subgroup, ...] per class]}`` with the types in the order of phonopy's tables, each subgroup a frozenset of indices into ``ops``.""" import spglib from phonopy.phonon.character_table import character_table ops = _table_operations(_point_group_table(pg)) n = len(ops) index = {R.tobytes(): i for i, (R, _) in enumerate(ops)} product = np.array([[index[(ops[a][0] @ ops[b][0]).tobytes()] for b in range(n)] for a in range(n)]) identity = index[np.eye(3, dtype=int).tobytes()] inverse = [int(np.flatnonzero(product[a] == identity)[0]) for a in range(n)] found: dict[str, dict[tuple, list]] = {} for group in sorted(_all_subgroups(product, identity), key=sorted): rotations = np.asarray([ops[i][0] for i in sorted(group)], dtype="intc") kind = spglib.get_pointgroup(rotations)[0].strip() canonical = min( tuple(sorted(int(product[product[g, i], inverse[g]]) for i in group)) for g in range(n) ) found.setdefault(kind, {}).setdefault(canonical, []).append(group) by_type = {kind: list(found[kind].values()) for kind in character_table if kind in found} orthogonal = all(np.array_equal(R.T @ R, np.eye(3, dtype=int)) for R, _ in ops) return _Census(ops, orthogonal, by_type) @dataclass class _Orientation: rotations: list setting: int classes: list conjugates: int principal: tuple identity_axes: bool def _orientation_of(group, ops, subgroup) -> _Orientation | None: rotations = [ops[i][0] for i in sorted(group)] found = _embedding(rotations, subgroup) if found is None: return None setting, classes = found principal_class = _PRINCIPAL_CLASS.get(subgroup) principal = (None, None) if principal_class is not None: R = next(R for R, name in zip(rotations, classes) if name == principal_class) principal = _element_kind(R) table = _table_operations(_point_group_table(subgroup, setting)) identity_axes = _conjugated_classes(rotations, np.eye(3), table) is not None return _Orientation(rotations, setting, classes, 0, principal, identity_axes) def _secondary_classes(orientation: _Orientation, subgroup: str, orthogonal: bool) -> list[tuple[str, list[str]]]: """The classes of H that fix its orientation about the principal axis, as ``(class name, element symbols)``: those of twofold rotations off the principal axis, else those of mirrors whose normal is off it (``("C2'", ["2_x", "2_y"])``).""" if subgroup not in _PRINCIPAL_CLASS: return [] axis = orientation.principal[1] groups: dict[str, list] = {} for R, name in zip(orientation.rotations, orientation.classes): groups.setdefault(name, []).append(R) table = _point_group_table(subgroup, orientation.setting) def pick(symbol): chosen = [] for name in _table_classes(table): members = groups.get(name, []) kinds = [_element_kind(R) for R in members] if members and all(k[0] == symbol for k in kinds) and not any( axis is not None and np.array_equal(k[1], axis) for k in kinds ): ordered = sorted(members, key=lambda R: _axis_key(_element_kind(R)[1])) chosen.append((name, [_element_text(R, orthogonal) for R in ordered])) return chosen return pick("2") or pick("m")
[docs] def correlation_table(pg: str, subgroup: str) -> CorrelationTable: """The correlation table of a point group and a subgroup type. The computation behind ``crystod-group --correlate --pg G --subgroup H``: every subgroup of G (from phonopy's table, order at most 48) is generated, the ones of type H (``spglib.get_pointgroup``) are grouped into conjugacy classes under G, and the irreps of G are restricted to one representative of each class. The restricted characters are reduced with phonopy's table of H after the elements are carried onto the elements of that table (in the axes of G when they match one of its settings, else with spglib's transformation to the standard orientation, else by a conjugation found for the generators). Args: pg: The point group G, as phonopy names it (``"m-3m"``, ``"6/mmm"``). subgroup: The subgroup type H (``"4/mmm"``, ``"3m"``). Returns: A ``CorrelationTable`` with one orientation per conjugacy class of subgroups of type H, ordered by the principal axis (z first). Raises: SystemExit: Unknown point group, or H not a subgroup of G (``ValueError`` through ``crystod.group``). RuntimeError: A restriction does not decompose into the irreps of H or the dimensions do not add up (internal check). Example: >>> from crystod import group >>> table = group.correlation_table("m-3m", "4/mmm") >>> [header for header, _ in table.orientations] ['4/mmm (4 || z)'] >>> table.rows["T2g"] [[('B2g', 1), ('Eg', 1)]] """ parent_table = _point_group_table(pg) _point_group_table(subgroup) census = _subgroup_census(pg) ops, n, orthogonal = census.ops, len(census.ops), census.orthogonal classes = census.by_type.get(subgroup) if not classes: raise SystemExit(f"ERROR: {subgroup} is not a subgroup of {pg} (its subgroup " f"types: {', '.join(census.by_type)}).") orientations: list[_Orientation] = [] for members in classes: candidates = [o for o in (_orientation_of(g, ops, subgroup) for g in members) if o] if not candidates: raise RuntimeError(f"internal error: a subgroup of type {subgroup} of {pg} " "does not match phonopy's table of it.") best = min(candidates, key=lambda o: ( _axis_key(o.principal[1]), 0 if o.identity_axes else 1, _assignment_key(o.rotations, o.classes, subgroup, o.setting))) best.conjugates = len(members) orientations.append(best) orientations.sort(key=lambda o: ( _axis_key(o.principal[1]), 0 if o.identity_axes else 1, o.setting, _assignment_key(o.rotations, o.classes, subgroup, o.setting))) parent_chars = _table_characters(parent_table) parent_class = {R.tobytes(): name for R, name in ops} results: dict[str, list] = {irrep: [] for irrep in parent_chars} for orientation in orientations: sub_chars = _table_characters(_point_group_table(subgroup, orientation.setting)) dims = {irrep: int(round(chars[_table_classes( _point_group_table(subgroup, orientation.setting))[0]].real)) for irrep, chars in sub_chars.items()} for irrep, chars in parent_chars.items(): restricted = np.array([chars[parent_class[R.tobytes()]] for R in orientation.rotations]) terms = [] total = 0 for name, sub in sub_chars.items(): chi = np.array([sub[c] for c in orientation.classes]) value = complex(np.vdot(chi, restricted) / np.vdot(chi, chi)) count = int(round(value.real)) if abs(value - count) > 1e-6: raise RuntimeError(f"internal error: {irrep} of {pg} restricted to " f"{subgroup} gives a non-integral multiplicity.") if count: terms.append((name, count)) total += count * dims[name] dimension = int(round(chars[_table_classes(parent_table)[0]].real)) if total != dimension: raise RuntimeError(f"internal error: {irrep} of {pg} (dim {dimension}) " f"restricted to {subgroup} adds up to {total}.") results[irrep].append(terms) headers = [] for orientation in orientations: symbol, axis = orientation.principal parts = [] if axis is not None: direction = _direction_text(axis, orthogonal) parts.append(f"{symbol} || {direction}" if symbol != "m" else f"m_{direction}") headers.append(parts) # the setting describes the orientation only in the axes of G (a # transformed table is just phonopy's index): name it there, or when # two columns differ by nothing else for j, orientation in enumerate(orientations): if subgroup in _SETTING_NAMES and (orientation.identity_axes or any( headers[k][:1] == headers[j][:1] and o.setting != orientation.setting for k, o in enumerate(orientations))): headers[j] = headers[j] + [ f"{_SETTING_NAMES[subgroup][orientation.setting]} setting"] secondary = [_secondary_classes(o, subgroup, orthogonal) for o in orientations] axes = ["; ".join(f"{name} = {', '.join(elements)}" for name, elements in found) for found in secondary] texts = [f"{subgroup} ({', '.join(parts)})" if parts else subgroup for parts in headers] for j, text in enumerate(texts): # columns with the same principal axis: name the first element of # the first class that fixes the orientation if texts.count(text) > 1 and secondary[j]: headers[j] = headers[j][:1] + [secondary[j][0][1][0]] + headers[j][1:] texts = [f"{subgroup} ({', '.join(parts)})" if parts else subgroup for parts in headers] return CorrelationTable( parent=pg, subgroup=subgroup, orientations=[(text, np.asarray(o.rotations, dtype=int)) for text, o in zip(texts, orientations)], rows=results, conjugates=[o.conjugates for o in orientations], settings=[_SETTING_NAMES[subgroup][o.setting] if subgroup in _SETTING_NAMES else "" for o in orientations], axes=axes, parent_order=n, subgroup_order=len(orientations[0].rotations), hexagonal_axes=not orthogonal, )
def _decomposition_text(terms) -> str: return " + ".join(f"{n} {name}" if n > 1 else name for name, n in terms)
[docs] def format_correlation_table(table: CorrelationTable) -> str: """The ``* Point group *``, ``* Subgroup *`` and ``* Correlation table *`` blocks of ``--correlate --pg G --subgroup H`` as text. Args: table: The record returned by ``correlation_table``. Returns: The text (no leading blank line, no trailing newline): G and its order, H with its orientations (number of conjugate subgroups and the classes that fix the orientation), the table with one row per irrep of G and one column per orientation, and a note on the axes. """ count = len(table.orientations) index = table.parent_order // table.subgroup_order lines = [ "* Point group *", f"{table.parent} (order {table.parent_order})", "", "* Subgroup *", f"{table.subgroup} (order {table.subgroup_order}, index {index}): {count} " f"inequivalent orientation{'s' if count > 1 else ''}", ] for (header, _), conjugates, axes in zip(table.orientations, table.conjugates, table.axes): text = f" {header}: {conjugates} conjugate subgroup{'s' if conjugates > 1 else ''}" if axes: text += f"; {axes}" lines.append(text) grid = [["irrep"] + [header for header, _ in table.orientations]] for irrep, decompositions in table.rows.items(): grid.append([irrep] + [_decomposition_text(terms) for terms in decompositions]) widths = [max(len(row[j]) for row in grid) for j in range(len(grid[0]))] lines += ["", "* Correlation table *"] for row in grid: lines.append(" ".join(cell.ljust(width) for cell, width in zip(row, widths)).rstrip()) import textwrap frame = (f"directions [uvw] are in the hexagonal axes a, b, c of the table of " f"{table.parent}" if table.hexagonal_axes else f"x, y, z are the axes [100], [010], [001] of the table of {table.parent}") note = (f"note: {frame}; 2_d is the twofold rotation about d, m_d the mirror " "normal to d; the symbols of H are those of phonopy's table of H") if any(table.axes): note += (" with its classes as listed under *\x00Subgroup\x00* (B1/B2/B3 " "follow them)") note += "." lines += [""] + [line.replace("\x00", " ") for line in textwrap.wrap(note, width=78, subsequent_indent=" ")] return "\n".join(lines)
# ------------------------------------------------------------------ command def _print_subgroup_report(args) -> SubgroupCorrelation: """Print the report of ``--correlate --supergroup-poscar`` (header and correlation blocks) and return its result.""" result = subgroup_correlation(args.supergroup_poscar, args.subgroup_poscar, args.tolerance, spinor=args.spinor) print() print(format_subgroup_header(result)) print() print(format_subgroup_correlation(result)) return result def main(argv: list[str] | None = None) -> None: """Command-line entry behind ``crystod-group --correlate``, ``--correlate-kpath`` and ``--correlate-double-group``.""" from .isotropy_subgroup import _protect_component_values parser = argparse.ArgumentParser( description="Correlation of irreps: point-group correlation tables, the " "correlation of a group-subgroup pair of structures, compatibility relations " "along a line." ) target = parser.add_mutually_exclusive_group(required=True) target.add_argument("--pg", help="point group (correlation table).") target.add_argument("--supergroup-poscar", dest="supergroup_poscar", help="supergroup structure (group-subgroup correlation).") target.add_argument("--sg", help="space group (compatibility relations).") parser.add_argument("--subgroup", default=None) parser.add_argument("--subgroup-poscar", dest="subgroup_poscar", default=None) parser.add_argument("--tolerance", type=float, default=0.01) parser.add_argument("--spinor", action="store_true", help="with --supergroup-poscar: also the double-valued irreps.") parser.add_argument("--output-dir", dest="output_dir", default=None, help="with --supergroup-poscar: directory of the " "CORREL_<formula>_<G>_<H> report (default: the current one).") parser.add_argument("--no-files", dest="no_files", action="store_true", help="with --supergroup-poscar: print the report only.") parser.add_argument("--kpoint", nargs="+", default=None) parser.add_argument("--line", default=None) parser.add_argument("--double-group", action="store_true", help="with --sg: single-valued -> double-valued small irreps.") if argv is None: import sys argv = sys.argv[1:] args = parser.parse_args(_protect_component_values(list(argv))) if args.spinor and not args.supergroup_poscar: parser.error("--spinor needs --supergroup-poscar.") if (args.output_dir is not None or args.no_files) and not args.supergroup_poscar: parser.error("--output-dir/--no-files need --supergroup-poscar.") if args.double_group and not args.sg: parser.error("--double-group needs --sg (a space group).") try: if args.pg: if not args.subgroup: parser.error("--pg needs --subgroup.") table = correlation_table(args.pg, args.subgroup) print() print(format_correlation_table(table)) return if args.supergroup_poscar: if not args.subgroup_poscar: parser.error("--supergroup-poscar needs --subgroup-poscar.") # the report goes to the terminal and, word for word (the # * Output files * block included), to CORREL_<formula>_<G>_<H> # (an ERROR exit writes no file) from .cli.common import SavedReport with SavedReport(enabled=not args.no_files, output_dir=args.output_dir) as report: result = _print_subgroup_report(args) report.name = subgroup_correlation_file_name(result) return if args.double_group: tokens = " ".join(args.kpoint or []).replace(",", " ").split() k = None if not tokens else tokens[0] if len(tokens) == 1 else tokens records = spin_orbit_relations(args.sg, k) elif not args.kpoint or len(args.kpoint) > 2: parser.error("--sg needs --kpoint with one or two k-point names.") else: k1 = args.kpoint[1] if len(args.kpoint) == 2 else None records = compatibility_relations(args.sg, args.kpoint[0], k1, args.line) except RuntimeError as exc: raise SystemExit(f"ERROR: {exc}") from None from .spacegroup_product import SpaceGroupIrrepAlgebra algebra = SpaceGroupIrrepAlgebra(args.sg) print() print("* Space group *") print(f"{algebra.sg_type.international_short} (No. {algebra.sg_type.number})") print() if args.double_group: print(format_spin_orbit_relations(records)) return print(format_compatibility(records)) if __name__ == "__main__": main()