crystod.salc

Contents

crystod.salc#

Crystal-orbital SALC analysis: the Python face of the crystod command.

Everything the main command does with a structure file is available here with a phonopy.structure.atoms.PhonopyAtoms cell in place of the -c POSCAR argument: the irreducible representations of the crystal orbitals – the symmetry-adapted linear combinations (SALCs) of one atomic shell’s Bloch sums – at any k point, the SALC coefficient bases behind the interactive 3D viewer, the crystal-orbital diagrams built from extended-Hueckel or periodic PySCF overlaps, the star of a k point, and the band irreps of a finished VASP run read from its WAVECAR. The classes take the same inputs as the command-line flags they mirror and return the numbers the command prints.

SALC irreps at a k point (crystod -c POSCAR --element EL --orbital ORB)
CrystalOrbital

Irrep decomposition of one element’s shell at a k point, or at every special point, with ISO-IR labels; --spinor is the spinor flag of the constructor (double-valued irreps with names such as -GM8+(4), numbered as in Bradley & Cracknell (1972) Table 6.5 with the exceptions of the manual; the old spelling spior is still accepted, with a DeprecationWarning). The shell "axial" of irreducible_decomposition(k, element, "axial") is one axial vector (Rx, Ry, Rz) per site: the irreps of the element’s spin configurations (crystod --element EL --axial, which prints a complex irrep and its conjugate at a time-reversal-invariant point once, under the pair label; this method returns them unmerged).

Crystal-orbital diagrams (crystod --diagram)
CrystalOrbitalDiagram

The symmetry + extended-Hueckel engine: fragment sublattices from --co-left/--co-right, full core + valence basis, one solve_at per special k point.

PySCFCrystalOrbitalDiagram

The quantitative engine of --pyscf: three periodic PySCF calculations sharing one AO space, deep-level column alignment (needs pip install "CrystOD[quantum]").

assign_bond_characters()

The COOP bonding/antibonding/nonbonding classification both engines apply to their levels.

dipole_selection_rules()

dipole_selection_rules(diagram): the band-edge electric-dipole selection rules of every k point of a diagram object of any engine (Gamma_f x Gamma_V x Gamma_i per polarization, in the Cartesian axes of the input cell), the blocks the engines print; band_edge_selection_rules() does one k point from its solved levels, little_group_dipole_table() gives the rule for every irrep pair of the little group, and format_dipole_selection_rules() the report block.

Symmetry-adapted orbital bases (crystod --visualize)
SymmetryAdaptedOrbitalBasis

Explicit SALC coefficient vectors of one shell at a k point, from the projected representation matrices; the data of the SALC viewer.

Star of k (crystod --star-of-k)
compute_star()

The arms of the star of a k point and the operations reaching each.

format_star_lines()

The report lines of those arms.

resolve_kpoint_input()

A --kpoint argument (label or coordinates) as label plus coordinates.

Band irreps of a VASP run (crystod --extract-irrep)
extract_band_irreps()

extract_band_irreps(path, kpoints=None, zero="vbm", window=None, spin="both", symprec=1e-5, degeneracy_tol=None): the irreps of the electronic bands of one finished VASP run, straight from its WAVECAR (every special k point of the space group the file holds, or the given labels/coordinates, or kpoints="all"), returned as a BandIrreps (levels with band indices, energies, degeneracy, ISO-IR label, Mulliken symbol at Gamma and the engine’s notes; band edges and gap); format_band_irreps() gives the report lines and write_band_irreps_yaml() the -o YAML file.

unfold_bands()

unfold_bands(child, parent=None, *, child_cell=None, parent_cell=None, trans_mat=None, zero="vbm", separate_zero=False, spin="both", degeneracy_tol=1e-3, all_kpoints=False, weight_min=0.02, symprec=1e-5, window=None, tolerance=0.01): the electronic bands of a low-symmetry VASP run unfolded onto the zone of its high-symmetry parent run, from the two WAVECARs (crystod --unfold), returned as a BandUnfolding with to_dict(), write_dat(path), write_yaml(path) and plot(path); format_band_unfolding() gives the report lines and unfold_kpoints() writes a child KPOINTS covering the parent path (crystod --unfold-kpoints).

Attributes resolve lazily (PEP 562): import crystod.salc is instant; the implementation modules, and with them phonopy and spgrep (and pyscf for the PySCF diagram), are imported the first time an attribute is used. Bad input that the command line reports as ERROR: ... and exits on is raised as ValueError from the functions of this namespace; the classes raise SystemExit from their constructors and methods, as the implementation modules do.

class crystod.salc.BandIrreps(directory, wavecar, structure, formula, n_atoms, nbands, nkpts, ispin, spinor, encut, precision, efermi, efermi_source, vbm, vbm_at, vbm_kpoint, vbm_label, cbm, cbm_at, cbm_kpoint, cbm_label, metallic, zero, zero_energy, space_group, space_group_number, symprec, degeneracy_tol, window, selection, kpoints, missing, edges)[source]#

Bases: object

Everything crystod --extract-irrep prints and writes.

Variables:
  • directory (str) – The run directory.

  • wavecar (str) – The WAVECAR file.

  • structure (str) – The structure file the labels refer to.

  • formula (str) – Chemical formula of the cell (a Va point-charge species of a sublattice run in parentheses: SrTi(Va2-)3).

  • n_atoms (int) – Atoms in the cell (Va point charges included).

  • nbands (int) – Bands per k point.

  • nkpts (int) – k points in the file.

  • ispin (int) – 1 or 2.

  • spinor (bool) – Spin-orbit (vasp_ncl) run.

  • encut (float) – Plane-wave cutoff in eV (WAVECAR header).

  • precision (str) – complex64 or complex128 coefficients.

  • efermi (float) – Fermi level in eV.

  • efermi_source (str) – Where it was read (OUTCAR, vasprun.xml, DOSCAR or WAVECAR header).

  • vbm (float | None) – Valence-band maximum in eV (raw), highest occupied eigenvalue over every k point and spin channel of the file.

  • vbm_at (tuple | None) – (k index, band, spin) of the VBM (1-based index and band, spin channel 0 or 1).

  • vbm_kpoint (list | None) – Fractional k point of the VBM.

  • vbm_label (str) – Its special-point name, or "".

  • cbm (float | None) – Lowest empty eigenvalue in eV (raw), same range.

  • cbm_at (tuple | None) – (k index, band, spin) of the CBM.

  • cbm_kpoint (list | None) – Fractional k point of the CBM.

  • cbm_label (str) – Its special-point name, or "".

  • metallic (bool) – Partially occupied bands exist (no gap is quoted).

  • zero (str) – "vbm", "efermi" or "raw".

  • zero_energy (float) – The eV subtracted from the raw eigenvalues.

  • space_group (str) – Hermann-Mauguin symbol.

  • space_group_number (int) – International number.

  • symprec (float) – Symmetry tolerance.

  • degeneracy_tol (float) – Seed window of the level clustering in eV.

  • window (tuple | None) – (emin, emax) eV relative to the zero, or None.

  • selection (str) – "special", "requested" or "all".

  • kpoints (list) – The KPointIrreps list (k outer, spin inner).

  • missing (list) – Special points (name, k) absent from the file (default selection only).

  • edges (list) – The BandEdges of every analysed k point and spin.

kpoint(label, spin=None)[source]#

The analysed k point named label (first match).

Raises:

KeyError – No such k point.

Return type:

KPointIrreps

to_dict()[source]#

The content of the YAML file (-o) as plain Python data.

Floats are rounded to six decimals, so that yaml.safe_load of the written file equals this dictionary.

Return type:

dict

cbm: float | None#
cbm_at: tuple | None#
cbm_kpoint: list | None#
cbm_label: str#
degeneracy_tol: float#
directory: str#
edges: list#
efermi: float#
efermi_source: str#
encut: float#
formula: str#
property gap: float | None#

CBM - VBM over the whole file in eV (None for a metal).

ispin: int#
kpoints: list#
metallic: bool#
missing: list#
n_atoms: int#
nbands: int#
nkpts: int#
precision: str#
selection: str#
space_group: str#
space_group_number: int#
spinor: bool#
structure: str#
symprec: float#
vbm: float | None#
vbm_at: tuple | None#
vbm_kpoint: list | None#
vbm_label: str#
wavecar: str#
window: tuple | None#
zero: str#
zero_energy: float#
class crystod.salc.BandUnfolding(child, parent, mapping, M, N, offsets, image_names, zero, zero_energy, parent_zero_energy, separate_zero, spins, degeneracy_tol, weight_min, window, all_kpoints, unfolded, child_matches, parent_view, coverage, alignment, checks, top_complete, notes=<factory>, timings=<factory>, files=<factory>, command='', parent_poscar='', alignment_all=<factory>, symmetry_notes=<factory>, child_ops=None, setting_coverage=None, figure_error=None)[source]#

Bases: object

The result of unfold_bands() (crystod --unfold).

Variables:
  • parent (child,) – VaspBandRun (parent without WAVECAR when only parent_cell was given).

  • mapping (object) – crystod.phonon_unfold.ParentMapping.

  • N (M,) – A_child = M A_parent, N = det M.

  • offsets (numpy.ndarray) – (N, 3) coset offsets g_i (parent fractional, Gamma first).

  • image_names (list) – ISO-IR names of the g_i in the parent.

  • parent_zero_energy (zero, zero_energy,) – Energy reference (mode, the value subtracted from child and parent eigenvalues).

  • spins (list) – Spin channels analysed.

  • unfolded (dict) – {(spin, index): KUnfolded}.

  • child_matches (dict) – {(index, i): parent k index} parent k points (any arm, time reversal) equal to image i of child k index.

  • parent_view (dict) – per spin: [(path position, parent index, child index, image i, R), ...] for the covered parent path points.

  • coverage (list) – [(leg text, covered, total, positions), ...] per parent leg; positions are the covered points as 0-based offsets along the leg.

  • alignment (dict) – Statistics of E_child - E_parent over pure matched levels (each distinct child K once).

  • checks (dict) – The numerical checks of the summary.

  • notes (list) – NOTE lines (setup block).

  • symmetry_notes (list) – NOTE lines of the Parent path coverage block.

  • child_ops (numpy.ndarray | None) – Reciprocal child operations used to relate child k points (point group and time reversal; only E and -E for an ISPIN = 2 child).

  • setting_coverage (dict | None) – The best-covering equivalent setting when it covers more parent path points than this one ({'M', 'coverage', 'covered', 'total'}), else None.

default_window()[source]#

The default energy ranges (eV relative to the zero) of the figure and the tables.

The child path levels are sorted; from the highest level at or below the zero the walk goes down while consecutive levels are closer than 2 eV: that is the valence block containing the zero. Figure: from its bottom - 1 eV to min(completeness limit + 1 eV, child maximum + 0.3 eV); tables: from its bottom - 0.5 eV to 6 eV (not above the figure’s top); all rounded outward to 0.5 eV.

Returns:

{'figure': (lo, hi), 'table': (lo, hi), 'block_bottom': E, 'whole': (lo, hi)} (whole: integer limits that hold the whole child spectrum).

Return type:

dict

distinct_path_entries(spin)[source]#

path_entries() with every child K once (modulo the child reciprocal lattice): a K repeated on the path (the child Gamma at three vertices) counts once.

Return type:

list

nearest_parent(ik, image, energy, spin)[source]#

(parent index, parent energy) of the parent level nearest to energy (relative) at the parent k equal to image image of child k ik; (None, None) without.

parent_energies(index, spin)[source]#

Parent eigenvalues (relative to the parent zero) at parent k index.

Return type:

ndarray

path_entries(spin)[source]#

The KUnfolded of the child path points in path order.

Return type:

list

plot(path)[source]#
Return type:

int

to_dict()[source]#
Return type:

dict

write_dat(path)[source]#
Return type:

str

write_yaml(path)[source]#
Return type:

str

M: ndarray#
N: int#
alignment: dict#
alignment_all: dict#
all_kpoints: bool#
checks: dict#
child: VaspBandRun#
child_matches: dict#
child_ops: ndarray | None = None#
command: str = ''#
coverage: list#
degeneracy_tol: float#
figure_error: str | None = None#
property figure_window: tuple#

--window, else the default figure range (both pages).

files: dict#
image_names: list#
mapping: object#
notes: list#
offsets: ndarray#
parent: VaspBandRun | None#
parent_poscar: str = ''#
parent_view: dict#
parent_zero_energy: float | None#
separate_zero: bool#
setting_coverage: dict | None = None#
spins: list#
symmetry_notes: list#
property table_window: tuple#

--window, else the default range of the vertex tables.

timings: dict#
top_complete: float#
unfolded: dict#
weight_min: float#
window: tuple | None#
zero: str#
zero_energy: float#
property zero_text: str#
class crystod.salc.CrystalOrbital(cell, symprec=1e-05, spinor=None, *, spior=None)[source]#

Bases: object

Irreps of the crystal orbitals built from one atomic shell (crystod).

The Bloch sums of one element’s s, p, d, f, g, h or i shell at a k point span a (reducible) representation of the little group of k – the site-symmetry induced representation, or band representation, of that shell. Its character is the product of the permutation character of the element’s sites (with the Bloch phases of k) and the rotation character of the shell, and its decomposition into the irreps of the little group is what crystod -c POSCAR --element EL --orbital ORB [--kpoint K] prints: with --spinor the double-valued (spin-orbit) irreps, without --kpoint every special point of the space group. The shell "axial" (AXIAL_ORBITAL) is one axial vector (Rx, Ry, Rz) per site, the magnetic representation of crystod --element EL --axial: the irreps of the spin configurations of the element’s sites. The spgrep irreps are labelled with the ISO-IR (Miller-Love) names, GM3+(2), X5-(2) and so on, the number in parentheses being the dimension. The ISO-IR tables hold single-valued irreps only; the double-valued irreps of --spinor are named -GM7+(2), -R8-(4) (crystod.wavecar_irreps.double_valued_names(), built on the ISO-IR labels of the single-valued irreps at the same k, numbered as in Bradley & Cracknell (1972) Table 6.5 except in 32, 3m, -3m and the cyclic co-groups, and the same on every arm of a star), the names of crystod --extract-irrep, not the Bilbao numbering.

The input cell is reduced to the spglib primitive cell, and the symmetry operations are reordered to match the ISO-IR tables (a ValueError is raised when that fails).

Parameters:
  • cell (PhonopyAtoms) – The crystal structure as phonopy.structure.atoms.PhonopyAtoms (any setting; it is converted to the primitive cell).

  • symprec (float) – Symmetry tolerance handed to spglib.

  • spinor (Optional[bool]) – True for the double-valued (spinor) irreps (default: single-valued).

  • spior (Optional[bool]) – Deprecated misspelling of spinor, still accepted (with a DeprecationWarning); it applies only when spinor is not given.

Variables:
  • primitive_cell – The standardized primitive PhonopyAtoms cell that every k point and atom index refers to.

  • spglib_dataset – The spglib symmetry dataset of the primitive cell ("international", "number", "wyckoffs", "site_symmetry_symbols", …).

  • transformation_matrix – The spglib transformation matrix of the primitive cell; it carries the ISO-IR k vectors and rotations, tabulated in the conventional setting, onto the primitive basis.

  • rotations – Integer rotation matrices in the primitive basis, in the ISO-IR table order.

  • translations – The matching fractional translations.

  • seitz_symbols – The Seitz symbol of every operation, same order.

  • spinor – Whether double-valued irreps are used.

  • symprec – The symmetry tolerance in use.

  • irt_character_table – The ISO-IR table of the space group (empty with spinor: the bundled ISO-IR data hold single-valued irreps only).

  • irt_kpoint_table – The single-valued ISO-IR table the special k points are enumerated from.

  • labels_from_isoir – Set by get_irrep_labels() at a k point the table does not list: whether the labels came from the full ISO-IR k-vector data.

  • spinor_label_note – Set by get_irrep_labels() with spinor: the NOTE lines of the last k point, joined by newlines – why some double-valued irreps kept their generic irrep_i(dim) keys, or else where the names differ from Bradley & Cracknell (1972) (spinor_numbering_notes()) – or None.

Example

>>> from phonopy.interface.calculator import read_crystal_structure
>>> from crystod import salc
>>> from crystod.examples import example_path
>>> cell, _ = read_crystal_structure(
...     str(example_path("221_PPOSCAR_ScF3")), interface_mode="vasp")
>>> co = salc.CrystalOrbital(cell)
>>> co.get_irt_special_points()[0]
['GM', 'R', 'X', 'M']
>>> _, _, counts, labels = co.irreducible_decomposition(
...     [0, 0, 0], "Sc", "d")
>>> {labels[key]: int(n) for key, n in counts.items() if n > 0}
{'GM3+(2)': 1, 'GM5+(3)': 1}
calc_reducible_characters(k, element, orbital, mapping_little_group, spin_traces=None)[source]#

Characters of the crystal-orbital representation at k.

Parameters:
  • k (list[float]) – Three primitive reciprocal coordinates.

  • element (str) – Chemical symbol.

  • orbital (str) – Shell letter ("s" to "i"), or "axial" (AXIAL_ORBITAL).

  • mapping_little_group (ndarray[tuple[Any, ...], dtype[int64]]) – Indices into rotations of the little-group operations.

  • spin_traces – With spinor, tr U_g of those operations (see get_atomic_orbital_characters()).

Returns:

the product of the permutation character of the element’s atoms (get_permutation_characters()) and the rotation character of the shell (get_atomic_orbital_characters()).

Return type:

Complex array, one entry per little-group operation

get_atomic_orbital_characters(rotations, orbital, spin_traces=None)[source]#

Rotation characters of one atomic shell.

The character of a proper rotation by alpha on the 2l+1 orbitals of shell l is sin((l + 1/2) alpha) / sin(alpha / 2) (2l+1 for the identity); an improper operation multiplies it by (-1)^l. With spinor the spin factor tr U_g is included, U_g being the SU(2) matrix spgrep assigns to the operation (angle in [0, pi], U(-R) = U(R); tr U_g = 2 cos(alpha / 2)), so that the reducible character and spgrep’s double-valued irreps share one lift.

Parameters:
  • rotations (ndarray[tuple[Any, ...], dtype[int64]]) – Integer rotation matrices, shape (n, 3, 3).

  • orbital (str) – Shell letter "s", "p", "d", "f", "g", "h" or "i", or AXIAL_ORBITAL ("axial"): one axial vector (Rx, Ry, Rz), the character det(R) chi_p(R) – the p-shell value with no sign change on improper operations.

  • spin_traces – With spinor, tr U_g of the n operations as the double-valued irreps were built with (the traces of spgrep’s little_unitary_rotations); computed with spgrep’s own map from the rotation to U_g when omitted.

Returns:

Real array of the n characters.

Raises:

ValueError – An unknown shell letter, or the axial basis with spinor (a magnetic moment is single-valued).

Return type:

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

get_irrep_labels(k, irreps, mapping_little_group, spin_rotations=None)[source]#

Map spgrep irreps at k to ISO-IR labels.

The ISO-IR labeller (crystod.isoir) names the irreps at any k, in the ISO-IR frame of the input cell; a k point tabulated only through its -k partner gets the ‘A’ names (PA1). The direct comparison of characters with the special-point table is the fallback where the labeller gives nothing. With spinor the double-valued irreps are named by label_spinor_irreps() (-GM8+(4), from the ISO-IR labels of the single-valued irreps at k in the same frame, fixed at the representative arm of the star of k).

Parameters:
  • k (list[float]) – Three primitive reciprocal coordinates.

  • irreps – The spgrep irreps at k (arrays of shape (little_group_order, dim, dim)), as returned by irreducible_decomposition().

  • mapping_little_group (ndarray[tuple[Any, ...], dtype[int64]]) – Indices into rotations of the little-group operations, in the order of the irrep matrices.

  • spin_rotations – With spinor, the SU(2) matrices U_g the double-valued irreps were built with (spgrep’s little_unitary_rotations), same order; recomputed with spgrep when omitted.

Returns:

{generic: label} with the generic key "irrep_i(dim)" of every irrep and its ISO-IR label such as "GM3+(2)" (with spinor: "-GM8+(4)"). In the fallback, a k point the table does not list is first mapped onto the tabulated arm of its star (characters transported by conjugation); an irrep that finds no match on either route keeps its generic key as the label, and so does a double-valued irrep that cannot be named (the reason is left in spinor_label_note).

Return type:

dict[str, str]

get_irt_irreps_at_k(k)[source]#

Tabulated ISO-IR irreps at a k point.

Parameters:

k (list[float]) – Three primitive reciprocal coordinates.

Returns:

The ISO-IR irrep records whose k vector equals k – each with kpname, k and its characters – or an empty list when the point is not tabulated as given (a non-tabulated arm of a star, or no special point at all).

Return type:

list[IsoTableIrrep]

get_irt_special_points()[source]#

Special k points of the space group from the ISO-IR tables.

Returns:

the tabulated names (GM, R, X, M for Pm-3m) and their primitive reciprocal coordinates, one entry per distinct point, in table order. The coordinates are the table’s own, carried by spglib’s transformation matrix, as the direct character comparison needs them; the points crystod analyzes and prints are get_special_points().

Return type:

(names, kpoints)

get_kpoint_name(k)[source]#

Name of a k point (GM, X, M, …), or None.

The ISO-IR k-vector type of k in the frame of the labels (the ISO-IR frame of the input cell): any arm of a special-point star gets the star’s name, a line, plane or generic k its type letters (DT, GP, …), and the partner of a star tabulated only through -k the ‘A’ name (PA of I-4). The special-point table is the fallback where the ISO-IR data give nothing.

Parameters:

k (list[float]) – Three primitive reciprocal coordinates.

Returns:

The name, or None when nothing matches.

Return type:

str | None

get_little_group(k)[source]#

Little group of k: the operations that leave k invariant.

Parameters:

k (list[float]) – Three primitive reciprocal coordinates.

Returns:

(little_rotations, little_translations) in the ISO-IR operation order (spgrep’s get_little_group without the index mapping, which irreducible_decomposition() returns).

get_little_group_symbol(k)[source]#

Space-group-type symbol of the little group of k.

Parameters:

k (list[float]) – Three primitive reciprocal coordinates.

Returns:

The short Hermann-Mauguin symbol and number spglib assigns to the little-group operations, e.g. "Pm-3m (221)" at Gamma or "P4/mmm (123)" at X of a cubic perovskite.

Return type:

str

get_modified_permutation_rep(r, t, k)[source]#

Bloch-phased permutation matrix of one operation at k.

Parameters:
  • r (ndarray[tuple[Any, ...], dtype[int64]]) – Integer rotation matrix in the primitive basis.

  • t (ndarray[tuple[Any, ...], dtype[float64]]) – Its fractional translation.

  • k (list[float, float, float]) – Three primitive reciprocal coordinates.

Returns:

Complex array of shape (n_atoms, n_atoms) whose entry [j, i] is the Bloch phase exp(2 pi i k . (R^-1 (x_j - t) - x_j)) when the operation sends atom i onto atom j (modulo lattice translations), and 0 elsewhere.

Return type:

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

get_permutation_characters(element, permutation_matrices)[source]#

Permutation characters restricted to the atoms of one element.

Parameters:
  • element (str) – Chemical symbol.

  • permutation_matrices (ndarray[tuple[Any, ...], dtype[complex128]]) – Output of get_permutation_reps_at_k().

Returns:

Complex array with the trace of every matrix over the rows and columns of the element’s atoms (the index list of get_target_element_positions(), contiguous or not).

Return type:

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

get_permutation_reps_at_k(little_rotations, little_translations, k)[source]#

Permutation matrices of the little-group operations at k.

Parameters:
  • little_rotations – Rotations of the little group of k, shape (order, 3, 3).

  • little_translations – Their fractional translations, shape (order, 3).

  • k (list[float]) – Three primitive reciprocal coordinates.

Returns:

one get_modified_permutation_rep() matrix per operation.

Return type:

Complex array of shape (order, n_atoms, n_atoms)

get_special_points()[source]#

Special k points named in the frame of the labels.

The points of get_irt_special_points() passed through crystod.isoir.special_points_in_frame: every point is named by the ISO-IR labeller of the input cell, and a point that is the -k partner of a tabulated type is replaced by -k, so that each name is the letters of the labels printed at its point. The two lists differ only when the frame of the labels is not spglib’s (an input outside the ISO-IR setting). These are the points crystod analyzes when --kpoint is omitted, and the names --kpoint accepts.

Returns:

(names, kpoints), one entry per distinct point, in table order.

Return type:

tuple[list[str], list[list[float]]]

get_target_element_positions(element)[source]#

Indices of the atoms of element in the primitive cell.

Parameters:

element (str) – Chemical symbol, e.g. "Sc".

Returns:

spglib keeps the atom order of the input, so a POSCAR whose species line repeats an element (O Ti O Sr O) gives [0, 2, 4] for O. Index with this list, never with the range from its first to its last entry.

Return type:

The atom indices in cell order. They need not be contiguous

Raises:

ValueError – The element is not in the cell.

irreducible_decomposition(k, element, orbital)[source]#

Decompose the crystal orbitals of one shell at k into irreps.

The calculation behind every line crystod prints: the irreps of the little group of k from spgrep (double-valued with spinor, with the SU(2) matrices U_g spgrep built them with also giving the spin factor tr U_g of the reducible characters), the reducible characters from calc_reducible_characters(), and the multiplicities from the character inner product.

Parameters:
  • k (list[float, float, float]) – Three primitive reciprocal coordinates.

  • element (str) – Chemical symbol, e.g. "Sc".

  • orbital (str) – Shell letter "s" to "i", e.g. "d", or "axial" (AXIAL_ORBITAL) for one axial vector (Rx, Ry, Rz) per site – the magnetic representation of crystod --element EL --axial, whose irreps classify the spin configurations of the element’s sites.

Returns:

mapping_little_group are the indices into rotations of the little-group operations, irreps the spgrep irrep matrices, counts maps the generic key "irrep_i(dim)" of every irrep to its multiplicity (rounded to two decimals), and labels maps the same keys to the ISO-IR labels, or to CrystOD’s double-valued names with spinor (get_irrep_labels()).

Return type:

(mapping_little_group, irreps, counts, labels)

Raises:

ValueError – An element that is not in the cell, an unknown shell letter, or "axial" with spinor.

class crystod.salc.CrystalOrbitalDiagram(cell, left_tokens, right_tokens, symprec=1e-05, electrons=None, sketch_tokens=None, oxidation=None, conventional=False)[source]#

Bases: object

Crystal-orbital diagram engine: symmetry + extended-Hueckel overlaps.

The engine behind crystod --diagram -c POSCAR --co-left A --co-right B. The two fragment sublattices are given as element formulas (every atom of the primitive cell must belong to exactly one of them), each atom carries its full core + valence shell basis, and at every high-symmetry k point the fragment Bloch orbitals are symmetry-adapted, the Bloch overlap lattice sums are evaluated, and the Wolfsberg-Helmholz eigenproblem is solved for the two fragment columns and the crystal column of the diagram (the module docstring describes the physics and the caveats). The CLI sequence, report_and_write(), is special_kpoints(), then solve_at() per k point, then the HTML writer, which draws the hover wave-function sketches with supercell_for() and sketch_partners().

Parameters:
  • cell – The crystal structure as phonopy.structure.atoms.PhonopyAtoms (converted to the spglib primitive cell).

  • left_tokens (list[str]) – --co-left formula tokens, e.g. ["SrTi"] or ["Sr", "Ti"]; a count such as O3 is optional and, when given, checked against the primitive cell.

  • right_tokens (list[str]) – --co-right formula tokens, e.g. ["O3"].

  • symprec (float) – Symmetry tolerance handed to spglib.

  • electrons (float | None) – Electrons per primitive cell for the aufbau filling of the crystal column (default: all electrons of the neutral atoms).

  • sketch_tokens (list[str] | None) – El-shell tokens ("Ti-3d", "O_2p") that restrict the drawn sketch components; None draws every component (what the CLI does).

  • oxidation (dict[str, float] | None) – {element: formal charge} for the point-charge lattice of the removed sublattice; must be charge-neutral over the cell. Default: pymatgen’s oxidation-state guess.

  • conventional (bool) – Draw the hover sketches in the conventional cell instead of the k-commensurate primitive supercell (display only).

Variables:
  • builder – The SymmetryAdaptedOrbitalBasis of the cell (symmetry operations, irrep labels, spglib_dataset).

  • symbols – Chemical symbols of the primitive-cell atoms.

  • positions – Their fractional coordinates, shape (n_atoms, 3).

  • lattice – Primitive lattice vectors as rows, in Angstrom.

  • formula – {"left": ..., "right": ...}, the fragment formulas.

  • oxidation – The formal charges in use.

  • specs – One SublatticeSpec per (element, shell) block of the AO basis, fragment-major; side_specs[column] lists those of one fragment.

  • n_ao – Size of the AO basis; side_slice[column] is the slice of a fragment’s contiguous block.

  • orbitals – One AtomicOrbital per basis function, in the representation order (spec-major, site-major, then m).

  • electrons – Electrons per cell in the crystal column; side_electrons[column] those of the fragment columns.

  • h_raw – Bare atomic on-site energies (eV) of every basis function; h_bar the same after the shell-averaged point-charge shift, v_onsite the full on-site ligand-field matrix, and site_potential the Ewald monopole potential at every atom.

  • sketch_specs – Indices into specs of the drawn shells, or None for all.

  • last_estimated – Set by solve_at(): the number of near-dependent Bloch combinations whose energies are first-order Loewdin estimates (marked ~ in the report), and last_dependent the number of linearly dependent combinations removed.

Raises:

SystemExit – A fragment formula that does not match the cell, an element without extended-Hueckel parameters or archived atomic levels, or oxidation states that are not charge-neutral.

Example

>>> from phonopy.interface.calculator import read_crystal_structure
>>> from crystod import salc
>>> from crystod.examples import example_path
>>> cell, _ = read_crystal_structure(
...     str(example_path("221_PPOSCAR_ScF3")), interface_mode="vasp")
>>> diagram = salc.CrystalOrbitalDiagram(cell, ["Sc"], ["F3"])
>>> diagram.formula, diagram.oxidation
({'left': 'Sc', 'right': 'F3'}, {'Sc': 3.0, 'F': -1.0})
>>> levels, labels = diagram.solve_at([0, 0, 0])
>>> occupied = [lv for lv in levels["mo"] if lv.electrons]
>>> homo = max(occupied, key=lambda lv: lv.energy)
>>> homo.label, round(homo.energy, 2), homo.bond_character
('GM5- #1', -17.4, 'nonbonding')
bloch_overlap(kpoint)[source]#

Bloch overlap matrix S(k) of the full AO basis, atom gauge.

S_k(i, j) = sum_n exp(2 pi i k . (n + x_j - x_i)) s(i at 0, j at n) over the lattice translations n within the pair cutoffs; the on-site term of an orbital with itself is 1. Every shell, the valence f shells included, takes its inter-site overlaps from the shared two-centre STO routine (pair_overlap).

Parameters:

kpoint – Three primitive reciprocal coordinates.

Returns:

Hermitian complex array of shape (n_ao, n_ao).

Return type:

ndarray

hamiltonian(S)[source]#

Wolfsberg-Helmholz Hamiltonian over the Bloch overlaps.

H_ij = K S_ij (h_i + h_j) / 2 with the shell-averaged shifted energies h_bar (rotation-invariant, so the symmetry of H stays exact); the on-site blocks carry the bare atomic energies plus the full anisotropic point-charge ligand-field matrices (v_onsite). The diagonal of S_k is 1 plus the same-orbital neighbour-cell Bloch sum, so only the on-site R = 0 term is the bare atomic energy: the diagonal correction (1 - K) restores h + K h_bar (S_kk - 1) + V_ii.

Parameters:

S (ndarray) – The Bloch overlap matrix from bloch_overlap().

Returns:

Hermitian complex array of shape (n_ao, n_ao), in eV.

Return type:

ndarray

little_group_data(kpoint)[source]#

Irreps, labels and the AO representation of the little group at k.

Parameters:

kpoint – Three primitive reciprocal coordinates.

Returns:

the spgrep irreps, the indices of the little-group operations into builder.rotations, their ISO-IR labels, and one complex (n_ao, n_ao) matrix per operation – block-diagonal over the (element, shell) specs, each block the Kronecker product of the Bloch-phased site permutation with the real-orbital Wigner matrix of the shell.

Return type:

(irreps, mapping, labels, representation)

sketch_partners(level, kpoint, sites)[source]#

Real wave-function amplitudes of a level on the supercell atoms.

The hover sketch of one level, one entry per degenerate partner. Only the sketch_specs components are drawn (all shells unless sketch_tokens restricted them). The amplitudes are Re[psi] (or Im[psi] when Re vanishes) of the Bloch crystal orbital, so the sign alternation between the cells of the k-commensurate supercell is displayed faithfully; degenerate partners are realified and RREF-canonicalized like the molecular sketch.

Same-l shells of one atom (e.g. Sc 2p/3p/4p) share their slots and accumulate, each weighted by its STO radial amplitude at a probe radius, so the drawn lobe signs are the signs of the real wave function there. (A bare coefficient of one shell is wrong: a semicore level like Sc 3p would be drawn from the tiny orthogonalization tail of the 4p shell, whose sign is inverted – the crystal analogue of the contracted-GTO compression in the molecular PySCF sketch.)

In the full-basis –diagram mode the lobe SIZE of each (atom, l) channel is additionally calibrated to its Loewdin population (level.channel_pop, attached by solve_at), and the probe radius is chosen per channel as the one (1.5/2.0/2.5/3.0 bohr) where the accumulated amplitude is largest – the visualize_eht/PySCF-viewer recipe. Raw amplitude x coefficient lobes misstate the mix badly: the 89.9%-Ti-4s GM1+ level of rutile TiO2 was DRAWN as d lobes (drawn d:s = 2.7:1), because the compact 3d weighs ~4x the diffuse 4s at a fixed 2-bohr radius while the semicore 3s orthogonality tail cancels most of the s channel. A level without channel_pop (or a sketch_specs-filtered sketch, an API-only mode – the CLI rejects –atomic-orbital with –diagram) keeps the legacy fixed-radius raw amplitudes.

Parameters:
  • level (DiagramLevel) – A DiagramLevel from solve_at() (its vectors are used).

  • kpoint – The k point the level was solved at.

  • sites – The (atom index, translation) list of supercell_for() at that k point.

Returns:

One list per partner; each holds one sketch entry [atom, s, px, py, pz, dxy, dyz, dz2, dxz, dx2-y2] per supercell atom (index into sites, then the real amplitudes of the nine s/p/d components).

solve_at(kpoint)[source]#

Solve the fragment and crystal eigenproblems at one k point.

The fragment columns are the generalized eigenproblems of the two sublattice blocks, the crystal column that of the full basis. Every level is labelled by projecting its degenerate space onto the irreps, filled by aufbau, and given its Loewdin fragment composition and its COOP bond character (assign_bond_characters()); the outermost columns list the isolated on-site shell levels. Sets last_estimated and last_dependent.

Parameters:

kpoint – Three primitive reciprocal coordinates, for the diagram one of special_kpoints().

Returns:

levels maps the columns "left", "mo" (the crystal), "right", "left-ao" and "right-ao" (the outermost isolated-shell columns) to lists of DiagramLevel records – label, irrep, energy (eV), degeneracy, electrons, vectors (shape (n_ao, degeneracy), S-orthonormal), composition, bond_character, overlap_population, estimated and detail – and labels are the ISO-IR irrep labels at kpoint.

Return type:

(levels, labels)

Raises:

SystemExit – The representation does not leave S or H invariant (a gauge or real-harmonics inconsistency; please report the case).

special_kpoints()[source]#

Tabulated special k points of the space group.

Returns:

[(name, kpoint), ...] with the ISO-IR names (GM, R, X, M for Pm-3m) and primitive reciprocal coordinates, in table order: the k points crystod --diagram draws (--kpoint NAME restricts the run to one of them). The points are named in the frame of the labels (crystod.isoir.special_points_in_frame).

supercell_for(kpoint)[source]#

Display supercell of the hover sketch at k.

Default: the k-commensurate diagonal supercell of the primitive cell. With conventional the display cell is the conventional cell of the detected centring (times the diagonal multiples that make exp(2 pi i k . T) = 1 for its edge vectors, as in the SALC viewer), and each atom is wrapped into it with its own primitive-lattice translation – the Bloch phases stay exact because every conventional-cell position is a primitive-lattice translate of a basis atom.

Parameters:

kpoint – Three primitive reciprocal coordinates.

Returns:

one (primitive atom index, integer lattice translation) pair per drawn atom, the chemical symbols, the Cartesian positions in Angstrom (shape (n, 3)), the display lattice vectors as rows, and a text such as "primitive cell, 2 x 2 x 2".

Return type:

(sites, symbols, cartesian, display_lattice, description)

class crystod.salc.PySCFCrystalOrbitalDiagram(cell, left_tokens, right_tokens, *, symprec=1e-05, basis='gth-dzvp-molopt-sr', pseudo='gth-pbe', xc='pbe', kmesh=None, ke_cutoff=200.0, oxidation=None, electrons=None, sigma=0.0, degeneracy_tol=None, no_ghost=False, symmetrize=True, max_l=None, projection='lowdin', chk=None, onsite=False, conventional=False, conv_tol=1e-08, max_cycle=100, max_memory=4000.0, verbose=0)[source]#

Bases: CrystalOrbitalDiagram

Crystal-orbital diagram from three periodic PySCF calculations.

The engine behind crystod --diagram --pyscf. It subclasses the extended-Hueckel engine only to reuse its k-point list, degenerate-group clustering, irrep projection, level filling and supercell helper; the Hamiltonian, the overlap and the orbitals all come from PySCF (the module docstring describes the construction). The CLI sequence, report_and_write(), is run() (the SCFs, or a chk restart), prepare_bands() for all special_kpoints(), solve_at() and site_symmetry_irreps() per k point, align_fragment_columns(), atomic_ion_levels() with attach_atomic_columns(), then the shared HTML writer. PySCF is an optional dependency (pip install "CrystOD[quantum]").

Parameters:
  • cell – The crystal structure as phonopy.structure.atoms.PhonopyAtoms (converted to the spglib primitive cell).

  • left_tokens – --co-left formula tokens, e.g. ["Sc"].

  • right_tokens – --co-right formula tokens, e.g. ["F3"].

  • symprec – Symmetry tolerance handed to spglib.

  • basis – GTH basis set name (--basis); GTH_BASIS_SETS lists what PySCF ships, and the coverage of every element is checked.

  • pseudo – GTH pseudopotential family (--pseudo).

  • xc – Exchange-correlation functional (--xc; "hf" for Hartree-Fock).

  • kmesh – SCF k mesh [n1, n2, n3] (--kmesh); default default_kmesh(), round(8 Angstrom / |a_i|) per axis.

  • ke_cutoff – FFT density-grid cutoff in Hartree (--ke-cutoff); below about 80 the GTH Gaussians are not resolved.

  • oxidation – {element: formal charge} (--oxidation); default pymatgen’s guess. Sets both the fragment ion charges and the point charges of the removed sublattice.

  • electrons – Electrons per cell filled into the crystal column (default: the crystal cell’s own count).

  • sigma – Fermi smearing width in eV (--sigma; 0 = integer occupations; an odd-electron cell always smears).

  • degeneracy_tol – Seed window in eV for clustering degenerate levels (--degeneracy-tol; default DEGENERACY_SEED_EV).

  • no_ghost – Exclude the removed sublattice’s basis functions from the fragment calculations (--no-ghost).

  • symmetrize – Re-diagonalize the group-averaged Fock so grid-broken degeneracies come out exact (--no-symmetrize turns it off).

  • max_l – Drop basis shells with l above this from every element (--max-l); None keeps all.

  • projection – "lowdin" or "mulliken", the population measure of the compositions and sketch lobe sizes (--projection).

  • chk – Restart file path (--chk): written after the SCFs when missing, read (skipping them) when present. report_and_write() defaults to CHK_{formula}.chk.

  • onsite – Single-Hamiltonian mode (--onsite): only the crystal SCF runs, and the fragment columns are the per-shell on-site multiplets of the crystal Fock operator.

  • conventional – Draw the hover sketches in the conventional cell (display only).

  • conv_tol – SCF convergence threshold in Hartree.

  • max_cycle – SCF iteration limit.

  • max_memory – PySCF memory limit in MB.

  • verbose – PySCF verbosity level (--verbose).

Variables:
  • builder – The SymmetryAdaptedOrbitalBasis of the cell.

  • symbols – Chemical symbols of the primitive-cell atoms; positions their fractional and cartesian their Cartesian coordinates, lattice the lattice vectors as rows (Angstrom).

  • cells – {"mo": crystal, "left": ..., "right": ...} PySCF pbc.gto.Cell objects that share one AO space of n_ao functions.

  • formula – {"left": ..., "right": ...}, the fragment formulas.

  • side_atoms – Atom indices of each fragment; side_charge their formal charges, side_electrons their electron counts, and crystal_electrons that of the crystal.

  • oxidation – The formal charges in use.

  • specs – One AOBlock per (element, shell) of the AO space; side_specs[column] those of one fragment, ao_blocks the unmerged per-atom blocks.

  • kmesh – The SCF mesh in use.

  • mean_field – After run(): {column: converged KRKS/KRHF}; density_matrix and scf_energy (Hartree) likewise.

  • smeared – The columns whose occupations ended up Fermi-smeared.

  • last_coupling – Set by solve_at(): (left level, right level, |H~|, gap, minority weight, |S|, |H|) tuples of the same-irrep fragment pairs, strongest mixing first; last_gauge_residual the D+ S D - S residual of the representation check.

  • atomic_ions – After atomic_ion_levels(): {element: {"charge", "nelec", "method", "shells", "caveats"}}.

  • chk_path – The restart file in use, if any.

Raises:
  • ImportError – PySCF is not installed.

  • SystemExit – A fragment formula that does not match the cell, a basis or functional PySCF does not ship for these elements, a projection other than lowdin/mulliken, a kmesh entry below 1, or oxidation states that are not charge-neutral.

Example

The diagram of ScF3, three SCFs on a 2x2x2 mesh (minutes, not seconds):

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

cell, _ = read_crystal_structure(
    str(example_path("221_PPOSCAR_ScF3")), interface_mode="vasp")
diagram = salc.PySCFCrystalOrbitalDiagram(cell, ["Sc"], ["F3"])
diagram.run()
kpoints = diagram.special_kpoints()
diagram.prepare_bands([k for _, k in kpoints])
levels, labels = diagram.solve_at(kpoints[0][1])   # GM
align_fragment_columns(records)[source]#

Deep-level (XPS-style) alignment of the three energy columns.

Each calculation carries its own G = 0 average-potential reference, so the raw columns are offset by one rigid constant each. For every fragment column the deepest chemically inert level is located – the deepest fragment level some crystal level consists of to at least ALIGNMENT_PURITY, the two paired one-to-one in energy order at each k point (_alignment_counterparts()) – and its fragment -> crystal energy difference, averaged over the k points where the pair exists, is that column’s offset. The zero is then put at the deeper of the two anchors in its PRE-BONDING (fragment) value: that fragment column stays, the crystal column moves by -delta_ref, the other fragment column by delta_other - delta_ref.

Parameters:

records – The per-k-point list built by report_and_write(): dicts with "name", "kpoint" and "levels" (the solve_at() result), one per diagram k point. The level energies are shifted in place.

Returns:

shifts maps "left", "mo" and "right" to the applied energy shifts in eV and "reference" to the anchoring column; anchors[column] describes each fragment’s anchor level ("label", "fragment_energy", "purity", "spread", "n_k", "fallback") or is None. (None, anchors) when no chemically inert fragment level exists; nothing is shifted then.

Return type:

(shifts, anchors)

atomic_ion_levels()[source]#

Levels of one isolated ion per element, at its formal charge.

The atomic stage before the sublattice forms (the crystal analogue of MolOD’s ligand-ao column), computed with PySCF as the three-stage story charged atom -> charged sublattice -> crystal.

Same basis / pseudopotential / functional as the periodic calculations (GTH pseudopotentials work in PySCF’s molecular code). A cation whose formal charge removes every pseudo-valence electron (Al^3+ with GTH-q3) has nothing to converge: its levels are the bare-ion one-electron spectrum (hcore eigenvalues – for Al^3+ the 3s eigenvalue, -27.9 eV, reproduces the third ionization potential of Al, 28.4 eV). Anions are vacuum-unbound (positive eigenvalues); that raw offset is absorbed by the per-element deep-shell anchoring in attach_atomic_columns, which also bridges the molecular (vacuum) and periodic (G = 0) energy references.

Returns:

{"charge", "nelec", "method", "shells": [(shell_name, l, energy_eV), ...], "caveats"}, one shell per (element, shell) spec of the AO basis.

Return type:

None. Fills atomic_ions with one entry per element

attach_atomic_columns(records)[source]#

Outermost isolated-ion columns + splitting connector links.

Call AFTER align_fragment_columns: the molecular (vacuum) and periodic (G = 0) references share no common zero, so each element’s ion levels are shifted rigidly so that its DEEPEST shell matches the (degeneracy-weighted, all-k) mean energy of the fragment levels that shell dominates – the band’s center of gravity, which in an orthogonal-basis tight-binding picture IS the on-site energy. The anchor shell’s connector fan then shows pure intra-sublattice splitting; the other shells additionally carry the ion’s own level spacing against the environment’s.

Parameters:

records – The per-k-point list of align_fragment_columns(); the "left-ao" and "right-ao" columns are added to every record’s "levels" in place.

Returns:

{element: (anchor shell, shift)} for the report, the shift in eV; ("none", 0.0) for an element none of whose shells dominates a fragment level.

compound_formula()[source]#

Reduced formula in conventional chemical order (rutile: TiO2).

The same helper the symmetry-mode tables are named after: cations before anions, the cation on the most special Wyckoff site first. Falls back to a plain alphabetical composition if pymatgen’s oxidation-state guesser has nothing to say about the elements. report_and_write() names the default restart file CHK_{formula}.chk after it.

Returns:

The formula string.

Return type:

str

little_group_data(kpoint)[source]#

Irreps, labels and the AO representation of the little group at k.

Same construction as the extended-Hueckel engine, but written directly in PySCF’s AO ordering: D[(a', shell, m'), (a, shell, m)] = P[a', a] W^l[m', m].

Parameters:

kpoint – Three primitive reciprocal coordinates.

Returns:

(irreps, mapping, labels, representation) as in CrystalOrbitalDiagram.little_group_data().

overlap_at(kpoint)[source]#

PySCF AO overlap matrix S(k) of the crystal cell.

Parameters:

kpoint – Three primitive reciprocal coordinates.

Returns:

Hermitian complex array of shape (n_ao, n_ao).

Return type:

ndarray

prepare_bands(kpoints)[source]#

Diagonalize every calculation at every diagram k point in one call.

get_bands rebuilds the density on the FFT grid each time it is called, so asking for all the special points at once instead of one per k point removes that cost from all but the first. Call after run(); solve_at() then reads the cache.

Parameters:

kpoints – List of three-component primitive reciprocal coordinates.

Returns:

None.

Return type:

None

run(report=<built-in function print>, defer_notice=False)[source]#

Run the periodic SCF calculations, or restore them from chk.

The crystal is solved first; its converged density restricted to one sublattice’s AO block is the initial guess of that fragment. A calculation that does not converge is retried up a ladder of Fermi smearing widths, cycle counts and virtual-level shifts, each rung reported. The converged results land in mean_field, density_matrix and scf_energy, and are written to chk_path when it is set. With onsite only the crystal calculation runs.

Parameters:
  • report – Callable that receives the progress lines (default print).

  • defer_notice (bool) – Do not report the “SCF saved to …” line; the caller prints the returned text where it lists its output files.

Returns:

The “SCF saved to FILE (…)” notice (without indentation) when a checkpoint was written, else None.

Raises:

SystemExit – An SCF that does not converge even with smearing, or an explicit chk file whose parameters do not match.

Return type:

str | None

site_symmetry_irreps(kpoint, representation, irreps, labels)[source]#

Irrep content of every (element, shell) block at k.

The site-symmetry induced representation that crystod --element EL --orbital ORB reports, recomputed here from the very representation used for the labelling.

Parameters:
  • kpoint – Three primitive reciprocal coordinates (not used by the computation; kept for symmetry with little_group_data()).

  • representation – The AO representation matrices from little_group_data().

  • irreps – The spgrep irreps from the same call.

  • labels – Their ISO-IR labels.

Returns:

the irreps the shell’s Bloch orbitals span, multiplicities as prefixes.

Return type:

{(element, shell): ["GM1+", "2GM4-", ...]}

sketch_partners(level, kpoint, sites)[source]#

Real wave-function amplitudes of a level on the supercell atoms.

The hover sketch of one level from the PySCF AO coefficients, in the entry format of the extended-Hueckel sketch (CrystalOrbitalDiagram.sketch_partners()).

The PySCF eigenvectors are in the atomic Bloch gauge, so the cell-to-cell phase is exp(2 pi i k . T) without the site offset. Same-l shells of one atom accumulate with their contracted-GTO radial amplitude at r0 = 2 bohr (see _build_ao_blocks), which fixes the lobe signs and orientation; the lobe SIZE is then rescaled to the Loewdin population of that (atom, l) channel. Raw r0 amplitudes would misstate the sizes: a diffuse gth-dzvp Sc 4p is ~5x an F 2p at r0, so a 7%-population Sc admixture used to draw at 83% of the largest F lobe. f shells and higher are omitted from the drawing.

Parameters:
  • level – A DiagramLevel from solve_at().

  • kpoint – The k point the level was solved at.

  • sites – The (atom index, translation) list of supercell_for() at that k point.

Returns:

One list per partner; each holds one sketch entry [atom, s, px, py, pz, dxy, dyz, dz2, dxz, dx2-y2] per supercell atom (index into sites, then the real amplitudes of the nine s/p/d components).

solve_at(kpoint)[source]#

Solve the fragment and crystal levels at one k point from the SCFs.

Reads the band energies and coefficients cached by prepare_bands() (or computes them), clusters degenerate levels until their irrep multiplicities are integral, labels them, drops ghost-dominated fragment states, fills them by aufbau, attaches the population rows and the COOP bond characters, and records the same-irrep fragment couplings in last_coupling.

Parameters:

kpoint – Three primitive reciprocal coordinates.

Returns:

(levels, labels) with the columns "left", "mo" and "right" as in CrystalOrbitalDiagram.solve_at() (the -ao columns are added later by attach_atomic_columns()); energies in eV on the raw per-calculation references until align_fragment_columns() shifts them.

Raises:

SystemExit – The AO representation does not leave the PySCF overlap invariant (please report the case).

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

Bases: SymmetryOnlyVibrations

SALC bases of one element’s shell at a k point (crystod --visualize).

Where CrystalOrbital counts irreps from characters, this class builds the representation matrices themselves – for every little-group operation the Kronecker product of the Bloch-phased site permutation with the real-orbital Wigner matrix of the shell – and projects them onto the irreps with spgrep, which gives the symmetry-adapted linear combinations (SALCs) as explicit coefficient vectors over the (atom, m) orbital components. The command crystod --visualize -c POSCAR --element EL --orbital ORB --kpoint K prints those coefficients and writes the interactive 3D HTML viewer from them (s, p, d and f shells; without --kpoint one page per special k point of the space group).

The symmetry machinery is inherited from SymmetryOnlyVibrations (the crystod-phonon engine): the cell is reduced to the spglib primitive cell, get_irrep_labels() supplies the ISO-IR labels of the spgrep irreps, and resolve_qpoint the seekpath k-point labels that resolve_kpoint_input() relies on.

Parameters:
  • cell (PhonopyAtoms) – The crystal structure as phonopy.structure.atoms.PhonopyAtoms.

  • symprec (float) – Symmetry tolerance handed to spglib.

  • standardize (bool) – Convert cell to the spglib primitive cell (the default); False keeps it as given, which must then already be a primitive cell.

Variables:
  • primitive_cell – The PhonopyAtoms cell all atom indices refer to.

  • spglib_dataset – The spglib symmetry dataset of that cell ("international", "number", "wyckoffs", …).

  • rotations – Integer rotation matrices in the primitive basis, shape (n_ops, 3, 3), in spglib order.

  • translations – The matching fractional translations, (n_ops, 3).

  • rotations_cartesian – The same rotations as Cartesian matrices, the input of the Wigner matrices.

  • symprec – The symmetry tolerance in use.

Example

>>> from phonopy.interface.calculator import read_crystal_structure
>>> from crystod import salc
>>> from crystod.examples import example_path
>>> cell, _ = read_crystal_structure(
...     str(example_path("221_PPOSCAR_ScF3")), interface_mode="vasp")
>>> basis = salc.SymmetryAdaptedOrbitalBasis(cell=cell)
>>> k = [0, 0, 0]
>>> irreps, rep, mapping, atoms = basis.get_orbital_rep(k, "F", l=1)
>>> labels = basis.get_irrep_labels(k, irreps, mapping)
>>> counts = basis.decompose_orbital_rep(irreps, rep, labels)
>>> {label: n for label, n in counts.items() if n > 0}
{'GM4-(3)': 2.0, 'GM5-(3)': 1.0}
>>> spaces, space_labels = basis.get_orbital_basis(irreps, rep, labels)
>>> [space.shape for space in spaces], space_labels
([(3, 9), (3, 9), (3, 9)], ['GM4-(3)', 'GM4-(3)', 'GM5-(3)'])
decompose_orbital_rep(irreps, orbital_rep, irrep_labels)[source]#

Multiplicity of every irrep in the orbital representation.

Parameters:
  • irreps – The spgrep irreps from get_orbital_rep().

  • orbital_rep – The representation matrices from the same call.

  • irrep_labels (list[str]) – One label per irrep (get_irrep_labels()).

Returns:

{label: multiplicity} for every irrep, the multiplicities rounded to two decimals (zero entries included). The printed * Irreducible Decomposition * of the CLI lists the non-zero ones.

Return type:

dict[str, float]

get_element_indices(element)[source]#

Indices of the atoms whose orbitals enter the basis.

Parameters:

element (str) – Chemical symbol, or "all" for every atom of the cell.

Returns:

The atom indices in primitive-cell order.

Raises:

ValueError – The element is not in the cell.

Return type:

list[int]

get_orbital_basis(irreps, orbital_rep, irrep_labels)[source]#

Project the orbital representation onto its irreps: the SALCs.

Parameters:
  • irreps – The spgrep irreps from get_orbital_rep().

  • orbital_rep – The representation matrices from the same call.

  • irrep_labels (list[str]) – One label per irrep (get_irrep_labels()).

Returns:

one complex array of shape (dim, n_atoms (2l+1)) per occurrence of an irrep – its dim rows are the partner SALCs, the columns the (atom, m) coefficients in the order of get_orbital_rep() – and the irrep label of every space (repeated when an irrep occurs more than once). --mode-index N of the CLI selects the N-th space, 1-based.

The coefficients are in the site gauge, that of the permutation matrices of get_orbital_rep(): they multiply the Bloch sums with phase exp(2 pi i k.(T + x_a)) (x_a the atom’s fractional position). Multiplying the block of atom a by exp(2 pi i k.x_a) gives the atomic-gauge coefficients (phase exp(2 pi i k.T)), the ones the viewer draws.

Return type:

(basis_spaces, basis_labels)

get_orbital_rep(kpoint, element, l)[source]#

Representation of the little group on the shell’s Bloch orbitals.

Parameters:
  • kpoint (list[float]) – Three primitive reciprocal coordinates.

  • element (str) – Chemical symbol, or "all".

  • l (int) – Azimuthal quantum number of the shell (0 to 3).

Returns:

the spgrep irreps at kpoint; the representation matrices, a complex array of shape (order, n_atoms (2l+1), n_atoms (2l+1)) whose rows and columns run atom-major over the (atom, m) components, m in the real-orbital order of ORBITAL_COMPONENT_NAMES; the indices into rotations of the little-group operations; and the atom indices of the element.

Return type:

(irreps, orbital_rep, mapping_little_group, element_indices)

get_supercell_size(kpoint)[source]#

Multiplicities of the viewer’s display cell along a, b, c.

The denominator of each component of k, limited to 6 (1 for a zero component); never an error, so that a k point no small cell holds periodically is still drawn. (crystod-phonon --vibration writes structures, and its SymmetryOnlyVibrations.get_supercell_size() refuses such a q.)

Return type:

tuple[int, int, int]

crystod.salc.assign_bond_characters(levels, overlap, rows_left, rows_right, spec_ranges, sqrt_overlap=None, hamiltonian=None)[source]#

COOP bonding character of every crystal (or molecular) orbital level.

P = 2 Re[c_L+ S_LR c_R] / degeneracy is the electron weight accumulated between the two fragments: P > 0 in-phase (bonding, drawn blue), P < 0 out-of-phase with an internuclear node (antibonding, red), P ~ 0 nonbonding (black; exactly 0 when the irrep has no partner on the other fragment). This is the classification that colors the level connectors of crystod --diagram and crystod-mol --diagram; the diagram engines call it from their solve_at after the aufbau filling. An (F - E S) energy partition was rejected: Mulliken-like cross terms of the diffuse shells give nonsense signs in a non-orthogonal basis.

Semicore handling. A filled semicore shell contributes to P in two distinct ways: resonant filled-filled pairing (Sc 3p with F 2s of ScF3, 6 eV apart – the He2-like closed-shell repulsion whose occupied upper partner is genuinely antibonding) and far off-resonant orthogonality tails (the same Sc 3p inside the F 2p band 23 eV above, or Sc 3s against everything), which are not bonding physics and would flip the sign of an otherwise donation-bonding state. With hamiltonian given (the crystal Fock/EHT operator), semicore shells are flagged against the crystal valence-band maximum – occupied fragment levels whose expectation <phi|H|phi> (reference-consistent with the crystal energies) tops out SEMICORE_DEPTH_EV below the VBM – and a flagged shell is excluded from a level’s P only when the level is more than SEMICORE_DEPTH_EV away from that shell’s band top (the semicore band and its resonant partners keep it). Without hamiltonian the legacy rule applies: flag against each fragment column’s own HOMO and keep the shell where it holds at least 40% of the level’s weight – fine for molecules, but blind to a semicore that is the fragment HOMO (Sc 3p of Sc3+).

Parameters:
  • levels – {"left": [...], "mo": [...], "right": [...]} level records (DiagramLevel or the molecular equivalent) with vectors, energy, degeneracy, electrons and label ("El shell irrep") filled in.

  • overlap – The overlap matrix S of the full basis at this k point.

  • rows_left – AO indices of the left fragment’s basis functions.

  • rows_right – AO indices of the right fragment’s basis functions.

  • spec_ranges – {(element, shell): AO indices} of every shell block.

  • sqrt_overlap – S^(1/2) for Loewdin weights in the legacy semicore rule; None uses Mulliken gross populations there.

  • hamiltonian – The crystal one-electron operator (Fock or EHT H) at this k point; enables the VBM-referenced semicore rule.

Returns:

None. Every levels["mo"] record receives bond_character ("bonding", "antibonding" or "nonbonding", threshold BOND_CHARACTER_TOL) and overlap_population (P), and a line stating them is appended to its detail.

Return type:

None

crystod.salc.band_edge_selection_rules(builder, name, kpoint, crystal_levels, spinor=False, axes='input')[source]#

Band-edge dipole selection rules of one k point, from its levels.

The VBM is the highest crystal level holding electrons, the CBM the lowest empty one (the HOMO/LUMO markers of the page); degenerate levels within 1 meV form one edge. When the band edge is forbidden, the allowed occupied -> empty pair of smallest energy difference is reported as well. dipole_selection_rules() is the same for the k points of a diagram object.

Parameters:
  • builder – The diagram’s SymmetryAdaptedOrbitalBasis (diagram.builder of every engine).

  • name (str) – The k-point label.

  • kpoint – Its primitive reciprocal coordinates in builder’s cell.

  • crystal_levels – The crystal-column levels (levels["mo"]), records with label, irrep, energy and electrons.

  • spinor (bool) – Spinor (double-group) levels: the rules are not evaluated.

  • axes (str) – Frame of the polarizations, as in little_group_dipole_table() (default: the input cell).

Returns:

A DipoleSelectionRules.

Return type:

DipoleSelectionRules

Example

>>> from phonopy.interface.calculator import read_crystal_structure
>>> from crystod import salc
>>> from crystod.examples import example_path
>>> cell, _ = read_crystal_structure(
...     str(example_path("221_PPOSCAR_SrTiO3")), interface_mode="vasp")
>>> diagram = salc.CrystalOrbitalDiagram(cell, ["SrTi"], ["O3"])
>>> levels, _ = diagram.solve_at([0, 0, 0])
>>> rules = salc.band_edge_selection_rules(
...     diagram.builder, "GM", [0, 0, 0], levels["mo"])
>>> rules.band_edge.initial, rules.band_edge.final, rules.band_edge.verdict
(['GM5- #1'], ['GM5+ #1'], 'allowed (x, y, z)')
crystod.salc.compute_star(rotations, translations, kpoint)[source]#

Compute the star of k: the orbit of a k point under the rotations.

Every rotation R of the space group sends k to k' = k R; the distinct images modulo reciprocal-lattice vectors are the arms of the star, and the rotations sending k to one arm form a coset of the little group of k. This is the computation behind crystod --star-of-k; crystod-phonon --modulation uses it to combine the arms of a multi-q modulation.

Parameters:
  • rotations (ndarray[tuple[Any, ...], dtype[int64]]) – Integer rotation matrices of the space group in the primitive basis, shape (n_ops, 3, 3) – for example SymmetryAdaptedOrbitalBasis.rotations.

  • translations (ndarray[tuple[Any, ...], dtype[float64]]) – The matching fractional translations, shape (n_ops, 3). Accepted for a uniform call signature; the star depends on the rotations only.

  • kpoint (list[float]) – Three primitive reciprocal coordinates of k.

Returns:

"kpoint" (the arm wrapped into (-0.5, 0.5]), "representative_index" (index of the first rotation reaching the arm, the coset representative) and "operation_indices" (indices of every rotation reaching the arm). With the identity listed first, as spglib does, the first arm is k itself and its "operation_indices" are the little group of k.

Return type:

One dict per arm, in order of first appearance along rotations

Example

>>> from phonopy.interface.calculator import read_crystal_structure
>>> from crystod import salc
>>> from crystod.examples import example_path
>>> cell, _ = read_crystal_structure(
...     str(example_path("221_PPOSCAR_ScF3")), interface_mode="vasp")
>>> basis = salc.SymmetryAdaptedOrbitalBasis(cell=cell)
>>> arms = salc.compute_star(basis.rotations, basis.translations,
...                          [0.5, 0.5, 0])
>>> [arm["kpoint"].tolist() for arm in arms]
[[0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.0, 0.5, 0.5]]
>>> len(arms[0]["operation_indices"])
16
crystod.salc.dipole_selection_rules(diagram, kpoint=None)[source]#

Band-edge dipole selection rules of a crystal-orbital diagram.

The rules of the * Dipole selection rules at <k> * blocks of crystod --diagram, for the k points of a CrystalOrbitalDiagram, PySCFCrystalOrbitalDiagram or VASPCrystalOrbitalDiagram: each k point is solved with diagram.solve_at unless the engine report already did (the rules are cached on the diagram). An object without special_kpoints and solve_at (the page object of the VASP overlap engine) gives the rules its report cached. Polarizations refer to the Cartesian axes of the input cell; the k coordinates are those of the builder’s (standardized) primitive reciprocal basis, as in the * k point * blocks of the report.

Parameters:
  • diagram – The diagram object.

  • kpoint – None (default) for every special k point of the diagram (diagram.special_kpoints()), a special-point name such as "GM", or three primitive reciprocal coordinates.

Returns:

One DipoleSelectionRules per k point, in the order of diagram.special_kpoints().

Raises:

ValueError – kpoint names no special point of the space group (or, for a page object, no k point its report evaluated).

Return type:

list[DipoleSelectionRules]

Example

>>> from phonopy.interface.calculator import read_crystal_structure
>>> from crystod import salc
>>> from crystod.examples import example_path
>>> cell, _ = read_crystal_structure(
...     str(example_path("221_PPOSCAR_SrTiO3")), interface_mode="vasp")
>>> diagram = salc.CrystalOrbitalDiagram(cell, ["SrTi"], ["O3"])
>>> rules = salc.dipole_selection_rules(diagram, "GM")[0]
>>> rules.band_edge.verdict
'allowed (x, y, z)'
crystod.salc.extract_band_irreps(path='.', kpoints=None, zero='vbm', window=None, spin='both', symprec=1e-05, degeneracy_tol=None, *, cell=None)[source]#

Irreps of the bands of one VASP run, from its WAVECAR.

The Python form of crystod --extract-irrep [PATH].

Parameters:
  • path (str) – The WAVECAR file or the run directory that holds it.

  • kpoints – None (every special point of the space group the file holds), "all" (every k point of the file), or a list of special-point labels ("GM", "X") and fractional coordinates ([0, 0.5, 0] or "0 1/2 0") in the run’s reciprocal basis.

  • zero (str) – Energy zero: "vbm", "efermi" or "raw".

  • window – (emin, emax) in eV relative to the zero: only the levels inside are kept (the level numbers stay those of the full list).

  • spin (str) – "up", "down" or "both" (ISPIN = 2 runs).

  • symprec (float) – Symmetry tolerance of spglib.

  • degeneracy_tol (float | None) – Seed window of the level clustering in eV (default DEFAULT_DEGENERACY_TOL, 1 meV).

  • cell (str | None) – Structure file in place of the run’s POSCAR (the same cell and origin).

Returns:

A BandIrreps.

Raises:

SystemExit – Every user error, as one ERROR: line (the crystod.salc namespace raises ValueError instead).

Return type:

BandIrreps

crystod.salc.format_band_irreps(result)[source]#

The terminal report of extract_band_irreps(), line by line.

The * Title * blocks VASP run, Space group, Special k points in the WAVECAR (k points in the WAVECAR with --all-kpoints), one Band irreps at ... table per k point (and spin channel), and Band edges.

Return type:

list

crystod.salc.format_band_unfolding(result, pages=None)[source]#

The terminal report of crystod --unfold (lines of at most 100 ASCII columns).

Return type:

list

crystod.salc.format_dipole_selection_rules(rules, k_text='', nested=False)[source]#

Report block of dipole_selection_rules().

Parameters:
  • rules (DipoleSelectionRules) – The rules of one k point.

  • k_text (str) – The k coordinates as printed next to the label, e.g. "(1/2,1/2,1/2)".

  • nested (bool) – Indent the content as a part of an engine report (three-space content, as the * k point <k> * blocks of crystod --diagram); the default is a standalone block (two-space content). The "* ... *" title is at column 0 in both cases.

Returns:

The lines of the * Dipole selection rules at ... * block, the leading blank line included.

Return type:

list[str]

crystod.salc.format_star_lines(arms, seitz_symbols=None, indent=' ')[source]#

Format the arms of a star as the report lines of crystod --star-of-k.

Parameters:
  • arms (list[dict]) – The list returned by compute_star().

  • seitz_symbols (list[str] | None) – Seitz symbols of all rotations, indexed like the rotations given to compute_star(); when present, each line names the coset-representative operation.

  • indent (str) – Text put in front of every line.

Returns:

One string per arm, "arm 1: k = [+0.5, +0.5, +0]" and so on, with "(representative: 2_001)" appended when symbols are given.

Return type:

list[str]

Example

>>> for line in salc.format_star_lines(arms):   # arms of compute_star
...     print(line)
 arm 1: k = [+0.5, +0.5, +0]
 arm 2: k = [+0.5, +0, +0.5]
 arm 3: k = [+0, +0.5, +0.5]
crystod.salc.little_group_dipole_table(builder, kpoint, axes='input')[source]#

Dipole selection rules of every irrep pair of the little group at k.

Parameters:
  • builder – A SymmetryAdaptedOrbitalBasis (or any SymmetryOnlyVibrations): its rotations, translations, rotations_cartesian and get_irrep_labels define the operations and the ISO-IR labels.

  • kpoint – Three primitive reciprocal coordinates of builder’s cell.

  • axes (str) – "input" (default): polarizations in the Cartesian axes of the builder’s input cell (input_frame_rotation()); "standardized": in those of the standardized primitive cell.

Returns:

The LittleGroupDipoleTable of that k point.

Raises:

ValueError – axes is neither "input" nor "standardized".

Return type:

LittleGroupDipoleTable

crystod.salc.resolve_kpoint_input(structure, raw_kpoint)[source]#

Resolve a --kpoint argument into a label and primitive coordinates.

The two command-line spellings of a k point – one high-symmetry label such as GM/X/M/R, or three primitive reciprocal coordinates (fractions such as 1/2 allowed) – become (label, coordinates) with the seekpath labels of the structure: coordinates that hit a special point (or an arm of its star) receive that point’s name, any other point the ISO-IR k-vector type letters (GP for a general point). This is what crystod --star-of-k and crystod --visualize do with --kpoint. When the label lookup itself fails (seekpath unavailable), three coordinates are still accepted and labelled custom.

Parameters:
Returns:

the k-point name and its three primitive reciprocal coordinates as floats.

Return type:

(label, kpoint)

Raises:

ValueError – An unknown label, or a token count that is neither one nor three (a ValueError from the implementation module as well as through crystod.salc).

Example

>>> from phonopy.interface.calculator import read_crystal_structure
>>> from crystod import salc
>>> from crystod.examples import example_path
>>> cell, _ = read_crystal_structure(
...     str(example_path("221_PPOSCAR_ScF3")), interface_mode="vasp")
>>> basis = salc.SymmetryAdaptedOrbitalBasis(cell=cell)
>>> salc.resolve_kpoint_input(basis, ["M"])
('M', [0.5, 0.5, 0.0])
>>> salc.resolve_kpoint_input(basis, ["1/2", "1/2", "0"])
('M', [0.5, 0.5, 0.0])
crystod.salc.unfold_bands(child, parent=None, *, child_cell=None, parent_cell=None, trans_mat=None, zero='vbm', separate_zero=False, spin='both', degeneracy_tol=0.001, all_kpoints=False, weight_min=0.02, symprec=1e-05, window=None, tolerance=0.01)[source]#

Unfold the bands of a child VASP run onto the zone of its parent.

The Python form of crystod --unfold --child-wavecar C --parent-wavecar P.

Parameters:
  • child – Child WAVECAR or run directory (with its POSCAR and KPOINTS).

  • parent – Parent WAVECAR or run directory; None with parent_cell (no parent eigenvalues: no overlay, no parent-path view).

  • child_cell (str | None) – Structure files in place of the runs’ POSCARs (the same cells as the WAVECARs).

  • parent_cell (str | None) – Structure files in place of the runs’ POSCARs (the same cells as the WAVECARs).

  • trans_mat – Nine integers, A_child = T A_parent: one of the equivalent settings (default: crystod-group’s).

  • zero – 'vbm', 'efermi' ('fermi'), 'raw' ('none') or an energy in eV, taken from the child and applied to both runs.

  • separate_zero (bool) – Each run at its own reference (vbm or efermi).

  • spin (str) – 'up', 'down' or 'both' (ISPIN = 2 runs).

  • degeneracy_tol (float) – Bands closer than this (eV, single linkage) form a level.

  • all_kpoints (bool) – Unfold the weighted (mesh) k points too.

  • weight_min (float) – Level shares below this are not drawn.

  • symprec (float) – spglib tolerance on the run cells.

  • window – (emin, emax) eV relative to the zero for the figure and tables (default: BandUnfolding.default_window()).

  • tolerance (float) – Tolerance of the setting search (Angstrom, crystod-group’s 0.01).

Returns:

BandUnfolding.

Raises:

SystemExit – Every user error as one ERROR: line (ValueError through crystod.salc).

Return type:

BandUnfolding

crystod.salc.unfold_kpoints(child, parent, *, child_cell=None, parent_cell=None, trans_mat=None, npoints=51, output='KPOINTS_unfold', tolerance=0.01, symprec=1e-05, write=True)[source]#

A child KPOINTS with the parent path mapped to K = M k_p.

The child’s weighted SCF points are copied verbatim (from its KPOINTS, else its IBZKPT), then the parent path (the zero-weight labelled points of the parent KPOINTS; without them seekpath’s path with npoints points per leg) follows as zero-weight points with ! K.n LABEL SEP comments carrying the parent labels.

Raises:

SystemExit – Every user error as one ERROR: line.

Return type:

KpointsUnfold

crystod.salc.write_band_irreps_yaml(result, path)[source]#

Write the YAML file of -o FILE (the layout of BandIrreps.to_dict()).

The layout follows phonon_irreps.yaml: run metadata first, then the analysed k points, then per k point (and spin channel) the list of levels with bands (1-based), energy (eV relative to the zero), degeneracy, irrep (null when unassigned), mulliken (Gamma), occupation and note, then the band edges.

Returns:

path.

Return type:

str