diff --git a/.basedpyright/baseline.json b/.basedpyright/baseline.json index e9c01352..61d96c7b 100644 --- a/.basedpyright/baseline.json +++ b/.basedpyright/baseline.json @@ -779,22 +779,6 @@ "lineCount": 1 } }, - { - "code": "reportUnnecessaryComparison", - "range": { - "startColumn": 50, - "endColumn": 71, - "lineCount": 1 - } - }, - { - "code": "reportUnnecessaryComparison", - "range": { - "startColumn": 47, - "endColumn": 71, - "lineCount": 1 - } - }, { "code": "reportUnreachable", "range": { diff --git a/.claude/skills/verify-pyprocar/features/parsers.md b/.claude/skills/verify-pyprocar/features/parsers.md index 18b40502..e6cc1b60 100644 --- a/.claude/skills/verify-pyprocar/features/parsers.md +++ b/.claude/skills/verify-pyprocar/features/parsers.md @@ -24,6 +24,7 @@ The proven end state (1f36aae1; `vasp` and `qe` re-driven at d6d4aaa7): - That 4.9992 is the nscf vasprun value. It is not the SCF value 5.3017 that the examples pass as `fermi=`, so object-API plots are shifted by 4.9992. - `qe` (`data/codes/qe/7.2/SrVO3/non-spin-polarized/bands`): `bands_shape` is `[155, 25, 1]`, ticks are `Γ X M Γ R X`, and `ebs_fermi` is 12.5491. - The cell is cubic, so a private copy with `K_POINTS crystal_b` changed to `tpiba_b` must give the same 155 k-points and ticks (proven at #262). `tpiba_c` and `crystal_c` give `kpath` `None`; only the synthetic tests in `tests/pyprocar/io/qe/test_qe_parser.py` cover them. +- `qe` non-collinear (`data/codes/qe/7.2/SrVO3/non-colinear/bands`, #293): `projected` is `[155, 50, 4, 5, 16]` (total, Sx, Sy, Sz on projwfc.x's real (l, m) orbitals `s pz px py dz2 dxz dyz dx2-y2 dxy ...`), and `bands` keeps 1 channel. At Gamma, band 41 has V t2g 0.984 and eg 0.000, and band 47 has t2g 0.000 and eg 0.833, matching the j-state weights in `kpdos.out`. A wrong spinor transform moves weight between dxy and dx2-y2. Every parser passes orbital names; a PROCAR that `pyprocar.filter` rewrote keeps its `o0` header name and label (`Bi-(o0)` on `data/examples/bands/auto`). - `elk` structure: all four `data/codes/elk/6.3/SrVO3/*` dirs give a 3.841244 Angstrom cubic lattice, through `GEOMETRY.OUT` or, in `non-spin-polarized/bands`, the `elk.in` fallback. Their `structure.pkl` files hold the pre-#242 Bohr lattice (7.2589), so do not compare against them. - `get_parser` writes nothing into the dir. - `abinit` (`data/codes/abinit/9.6/Fe/*/bands`, #255): `kpath` ticks are `Γ(0) H(50) N(100) Γ(150) P(200) H|P(250) N(300)`, and `ebs` is an `ElectronicBandStructurePath`. Abinit writes each segment boundary once, so a wrong segmentation shows as 3 ticks `Γ(0) H|H(250) N(300)`. With Cartesian x-distances, Γ–H is `1/a` = 0.3521 Å⁻¹ (a = 2.84 Å). diff --git a/.claude/skills/verify-pyprocar/features/utilities.md b/.claude/skills/verify-pyprocar/features/utilities.md index 6f5bc47e..cb21c56d 100644 --- a/.claude/skills/verify-pyprocar/features/utilities.md +++ b/.claude/skills/verify-pyprocar/features/utilities.md @@ -31,6 +31,7 @@ The proven end state (SrVO3, non-spin-polarized, d6d4aaa7, driven 2026-10-04): - `repair`: 2,363,890 bytes, with a valid `PROCAR lm decomposed` header. - `cat` of the PROCAR with itself: one header with `# of k-points: 400`. - `generate2dkmesh(-0.5,-0.5,0.5,0.5,0,5,4)`: shape `[20, 3]`, and `Kgrid.dat` starts `Generated by PyProcar / 20 / Reciprocal`. +- A filtered PROCAR plots (#293, `tests/pyprocar/scripts/test_filtered_procar.py`). With `atoms=[[0],[1],[2,3,4]]` the PROCAR has 3 rows next to the 5-atom POSCAR. The parser warns and sets `ebs.atom_groups = 3`. `bandsplot(mode='parametric', atoms=[2])` draws the same colours as `atoms=[2,3,4]` on the unfiltered PROCAR. Species selections (`atoms=['O']`, `overlay_species`, `items`) raise `Cannot select species 'O'`. With `orbitals=[[0],[1,2,3]]` the columns are labelled `o0` and `o1`, and `orbitals=['p']` raises `hold no whole p shell`. On the irreducible k-points of `data/examples/fermi2d/non-spin-polarized`, `fermi2D` of an atom-filtered PROCAR raises `filtered by atoms cannot be unfolded`, because ibz2fbz (#299) permutes atoms between rows the file no longer names. A structure-less DOS (every Lobster DOS) sums every atom row when a selection names no atoms: `dosplot(code='lobster', mode='parametric', orbitals=[1,2,3])` colours by the p weight of all atoms. - `side_effects.txt`: `KPOINTS_pyprocar`, `PROCAR_bands_1_5`, `PROCAR_repaired`, `PROCAR_merged`, `Kgrid.dat`. `bandgap` writes nothing. ## Gotchas diff --git a/CLAUDE.md b/CLAUDE.md index 174b6aec..0126a41a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,7 +12,7 @@ When a reviewer corrects a mistake, fix it and add its rule here. If the rule is | Code runs on the declared floor, Python 3.12. | ruff `target-version` and basedpyright `pythonVersion`; `tests/test_python_floor.py` keeps those, `pyproject.toml` and `pixi.toml` equal | | Physical constants come from `pyprocar/utils/units.py`. | `tests/test_unit_constants.py` | | `pixi.toml` tasks name only defined tasks, environments and files. | `tests/test_pixi_manifest.py` | -| Parsers hand the core projections as `(k, band, spin, atom, orbital)` for bands and `(energy, spin, atom, orbital)` for DOS, with one orbital name per orbital. | `check_projected_layout` in the `ElectronicBandStructure` and `DensityOfStates` constructors | +| Parsers hand the core projections as `(k, band, spin, atom, orbital)` for bands and `(energy, spin, atom, orbital)` for DOS. The leading axes match the bands or total DOS, the atom axis matches the structure (or the `atom_groups` count of a PROCAR filtered by atoms), and there are 1, 2 or 4 spin channels (non-collinear is total, Sx, Sy, Sz, with 1 or 4 band channels). Every parser passes one name per orbital it projects. | `check_projected_layout` in the `ElectronicBandStructure` and `DensityOfStates` constructors; `tests/pyprocar/io/test_orbital_names.py` | | Scripts, notebooks and docs call `pyprocar.*` with its current signature, and every `ebs.` they name exists. | `tests/test_documented_calls.py` | | Tests never write `data/`; a test that reads it is marked `data`. | audit hook in `tests/conftest.py` | | A message the user must see or act on is a `UserWarning` from `warn_user` (`pyprocar/utils/log_utils.py`), which names the user's line; the `user` logger carries only info and debug progress. Tests assert a warning with `tests/utils/user_warning.py`, which also checks the line it names. | `tests/test_user_warnings.py`. In `pyprocar/` it fails on `.warning`, `.error`, `.critical`, `.exception`, `.fatal`, `.warn`, or `.log` with a constant or named level of WARNING or above, called on `getLogger("user")`, on a name bound to it in the same function or module, on a `self.` attribute bound to it in the same class, or on a name imported from another module that binds it; and on `warn` or `warn_explicit` from the `warnings` module outside `log_utils.py`. In `tests/` it fails on `caplog.at_level` or `set_level` with logger `"user"`, on `setLevel` on the user logger, and on `pytest.warns(UserWarning, ...)` outside the helper. | diff --git a/docs/source/user-guide/filter.rst b/docs/source/user-guide/filter.rst index 3bcc1194..b2c48163 100644 --- a/docs/source/user-guide/filter.rst +++ b/docs/source/user-guide/filter.rst @@ -22,6 +22,10 @@ If you want to select only :math:`p_x` orbitals, just use ``orbitals=[[3]]``. In the same way to plot the projection of total :math:`p`-orbitals use ``orbitals=[[1,2,3]]`` (i.e. :math:`px+py+pz`). Same goes for other orbitals. +Each new column is named by ``orbital_names``, which defaults to ``o0``, ``o1``, and so on. PyProcar reads these names from the header of the new file, so plots label the columns ``o0`` and ``o1``. In the new file, orbital index ``i`` selects the ``i``-th column, so ``orbitals=[1]`` selects the :math:`p` sum of the example above. Pass ``orbital_names=['s','p']`` to label the columns ``s`` and ``p``. + +A shell name such as ``orbitals=['p']`` selects the column named ``p``, or the columns whose names make up the whole :math:`p` shell, for example ``py``, ``pz`` and ``px``. Columns named ``o0`` and ``o1`` make up no shell, so select them by index. + =================================== To filter selected :math:`k`-points =================================== @@ -57,5 +61,18 @@ Usage:: PyProcar counts each row of ions in PROCAR file starting from 0. Keep in mind: ``atoms=0`` does not define the atom_type, rather it defines only the first ion in the POSCAR. So if you have more than one ion of the same element, use ``atoms = [[0,1,2,3,...]]``. +Each group in ``atoms`` becomes one row of the new PROCAR, the sum of the rows of its atoms. For a SrVO3 calculation with the POSCAR order Sr, V, O, O, O:: + + pyprocar.filter('PROCAR','PROCAR-filtered_atoms', atoms=[[0],[1],[2,3,4]]) + +writes 3 rows: Sr, V, and the sum of the three O atoms. To plot the new file, rename it to ``PROCAR`` in the calculation directory. When the PROCAR has fewer or more rows than the POSCAR has atoms, PyProcar warns that the PROCAR was filtered by atoms and treats each row as a group: + +- Atom index ``i`` selects the ``i``-th group, so ``atoms=[2]`` selects the three O atoms. Plots label a selection by its group indices, not by a species. +- A plot with no ``atoms`` sums every group. +- A selection by species raises an error, because a group can hold atoms of several species. This includes ``atoms=['O']`` and the ``overlay_species`` mode. Select groups by index instead. +- A Fermi surface or other k-point mesh needs the full k grid. Unfolding the irreducible k-points moves atoms between rows, and the filtered file does not say which atoms a row holds, so PyProcar raises an error. Filter the PROCAR of a calculation on the full k grid (``ISYM = -1``), or plot the unfiltered PROCAR and select atoms there. + +PyProcar cannot detect a filtered PROCAR that has exactly as many rows as the POSCAR has atoms. It then labels each row with the species of the POSCAR atom at the same index. + .. automodule:: pyprocar.scripts.scriptFilter :members: diff --git a/pyprocar/core/atomic_orbital_index.py b/pyprocar/core/atomic_orbital_index.py index 9fa84596..e487da91 100644 --- a/pyprocar/core/atomic_orbital_index.py +++ b/pyprocar/core/atomic_orbital_index.py @@ -151,6 +151,43 @@ } +_SHELL_LETTERS = "spdf" +_LETTER_ORBITAL_NAME = re.compile(r"\d*([spdf])[_xyz0-9^()\- ]*") +_ELK_ORBITAL_NAME = re.compile(r"Y(\d)-?\d+") + + +def _angular_momentum(orbital_name: str) -> int | None: + """The l of an orbital name a parser writes (``px``, ``d_z^2``, ``x2-y2``, Elk's ``Y1-1``).""" + if orbital_name == "x2-y2": + return 2 + if elk := _ELK_ORBITAL_NAME.fullmatch(orbital_name): + return int(elk[1]) + if letter := _LETTER_ORBITAL_NAME.fullmatch(orbital_name): + return _SHELL_LETTERS.index(letter[1]) + return None + + +def orbital_shells(orbital_names: Sequence[str] | None) -> tuple[tuple[str, tuple[int, ...]], ...]: + """The whole s, p, d and f shells among the orbitals, as (letter, orbital indices). + + Without names the slots of the conventional table stand. With names, shell l is + the 2l+1 orbitals whose names have angular momentum l, so a filtered PROCAR's + ``o0`` or a spin-orbit ``l1_j1.5_m0.5`` state is in no shell. + """ + if not orbital_names: + return PRIMARY_ORBITAL_GROUPS + by_l: dict[int, list[int]] = {} + for index, name in enumerate(orbital_names): + ang = _angular_momentum(name) + if ang is not None: + by_l.setdefault(ang, []).append(index) + return tuple( + (letter, tuple(by_l[ang])) + for ang, letter in enumerate(_SHELL_LETTERS) + if len(by_l.get(ang, ())) == 2 * ang + 1 + ) + + def _normalize_indices(indices: Iterable[int] | None) -> list[int]: if indices is None: return [] @@ -304,12 +341,12 @@ def _build_label_tokens( return [] if is_non_colinear and (orbital_names is None or len(orbital_names) == 0): - return [self._format_soc_label(idx) for idx in normalized] + return [self.soc_label(idx) for idx in normalized] remaining = set(normalized) tokens: list[str] = [] if prefer_groups: - for group_name, group_indices in PRIMARY_ORBITAL_GROUPS: + for group_name, group_indices in orbital_shells(orbital_names): group_set = set(group_indices) if group_set and group_set <= remaining: tokens.append(group_name) @@ -406,7 +443,7 @@ def _build_index_map(self, list_a: Sequence[str], list_b: Sequence[str]) -> dict mapping[i] = list_b.index(orb) return mapping - def _format_soc_label(self, index: int) -> str: + def soc_label(self, index: int) -> str: if 0 <= index < len(self.flat_soc_order): entry = self.flat_soc_order[index] l = entry.get("l") @@ -838,11 +875,13 @@ def __init__( self, *, label_builder: ProjectionLabelBuilder, + n_atom_rows: int, orbital_names: Sequence[str] | None = None, is_non_colinear: bool = False, ) -> None: self.label_builder = label_builder self.atom_indexer = label_builder.atom_indexer + self.n_atom_rows: int = n_atom_rows self.orbital_names = orbital_names self.is_non_colinear = is_non_colinear @@ -910,18 +949,18 @@ def resolve( atoms_set = set() for specie in species_list: atoms_set.update(self._atoms_for_species(specie)) - elif atoms_set is None: - if self.atom_indexer is None: - raise ValueError( - "Atom indexer is required when atoms and species selections are omitted" - ) - species_map = self.atom_indexer.species_atom_map() - species_list = list(species_map.keys()) - atoms_set = {idx for indices in species_map.values() for idx in indices} - else: + elif atoms_set is not None: species_list = self._species_from_atoms(sorted(atoms_set)) + elif self.atom_indexer is not None: + species_list = list(self.atom_indexer.species_atom_map().keys()) - atoms_tuple = tuple(sorted(atoms_set)) if atoms_set is not None else tuple() + atoms_tuple = ( + tuple(sorted(atoms_set)) if atoms_set is not None else tuple(range(self.n_atom_rows)) + ) + if not atoms_tuple: + raise ValueError("The selection names no atoms; select at least one atom or species") + if spins_set is not None and not spins_set: + raise ValueError("The selection names no spins; omit spins to select every channel") orbitals_tuple = ( tuple(sorted(orbitals_set)) if orbitals_set is not None and len(orbitals_set) > 0 @@ -931,7 +970,7 @@ def resolve( species_tuple = tuple(species_list) if species_list is not None else tuple() labels = self.label_builder.build_components( - atoms=atoms_tuple if atoms_tuple else None, + atoms=atoms_tuple, orbitals=orbitals_tuple, spins=spins_tuple, species=species_tuple, @@ -990,7 +1029,11 @@ def _ensure_mapping(mapping: Mapping) -> Mapping: def _atoms_for_species(self, specie: str) -> tuple[int, ...]: if self.atom_indexer is None: - raise ValueError("Species selections require atom indexing information") + raise ValueError( + f"Cannot select species {specie!r}: the projections name no species per atom row," + + " because there is no structure or because each row is a group of atoms" + + " (a PROCAR filtered by atoms). Select rows by index with atoms=[...]." + ) mapping = self.atom_indexer.species_atom_map([specie]) if specie not in mapping: raise ValueError(f"Species '{specie}' not found in atom index") diff --git a/pyprocar/core/dos.py b/pyprocar/core/dos.py index b9e79742..8c71a967 100755 --- a/pyprocar/core/dos.py +++ b/pyprocar/core/dos.py @@ -17,6 +17,7 @@ from pyprocar.core.atomic_orbital_index import ProjectionSelectionResolver from pyprocar.core.projection import ( + DOS_PROJECTIONS, NormMode, build_property, check_projected_layout, @@ -201,6 +202,8 @@ def _units_divide(u_input: str, u_norm: str | None) -> str: class DensityOfStates(PointSet): """Data-centric representation of a density of states calculation.""" + atom_groups: int | None = None + def __init__( self, energies: npt.ArrayLike, @@ -245,7 +248,7 @@ def __init__( if projected is not None: projected_array = self._validate_projected(projected) check_projected_layout( - projected_array, orbital_names, ("n_energies", "n_spins", "n_atoms", "n_orbitals") + projected_array, orbital_names, DOS_PROJECTIONS, total_array, structure ) self.add_property( name="projected", @@ -1584,14 +1587,6 @@ def _validate_projected(self, projected: npt.ArrayLike) -> npt.NDArray[np.float6 if projected_array.ndim == 3: projected_array = projected_array[:, np.newaxis, :, :] - if projected_array.ndim != 4: - raise ValueError( - "Projected DOS must have shape (n_energies, n_spins, n_atoms, n_orbitals)" - ) - - if projected_array.shape[0] != self.n_energies: - raise ValueError("Projected DOS must align with the energy grid") - return projected_array @cached_property diff --git a/pyprocar/core/ebs.py b/pyprocar/core/ebs.py index fd200708..c3199f27 100755 --- a/pyprocar/core/ebs.py +++ b/pyprocar/core/ebs.py @@ -30,6 +30,7 @@ ) from pyprocar.core.brillouin_zone import BrillouinZone from pyprocar.core.projection import ( + BAND_PROJECTIONS, NormMode, build_property, check_projected_layout, @@ -82,6 +83,7 @@ def get_ebs_from_data( structure: Structure | None = None, kpath: kpoints.KPath = None, kgrid_info: kpoints.KGridInfo | None = None, + atom_groups: int | None = None, **kwargs, ): ebs_args = { @@ -94,6 +96,7 @@ def get_ebs_from_data( "reciprocal_lattice": reciprocal_lattice, "orbital_names": orbital_names, "structure": structure, + "atom_groups": atom_groups, } # grid_dims = mathematics.get_grid_dims(kpoints) @@ -188,9 +191,14 @@ class ElectronicBandStructure(PointSet): factor (a_i . b_j = delta_ij). Defaults to None shifted_to_fermi : bool, optional Boolean to determine if the fermi energy is shifted, defaults to False + atom_groups : int, optional + The number of rows of the atom axis of ``projected`` when each row is a group of + the structure's atoms, as in a PROCAR filtered by atoms. Atom indices then select + groups, and species selections raise. Defaults to None, one row per atom """ _mesh: pv.PolyData | pv.StructuredGrid | pv.PointSet | None = None + _atom_groups: int | None = None def __init__( self, @@ -204,12 +212,13 @@ def __init__( reciprocal_lattice: kpoints.RECIPROCAL_LATTICE_DTYPE | None = None, shifted_to_fermi: bool = False, structure: Structure | None = None, + atom_groups: int | None = None, ): super().__init__(kpoints) logger.info("Initializing ElectronicBandStructure") check_projected_layout( - projected, orbital_names, ("n_kpoints", "n_bands", "n_spins", "n_atoms", "n_orbitals") + projected, orbital_names, BAND_PROJECTIONS, bands, structure, atom_groups ) if bands is not None: @@ -226,6 +235,7 @@ def __init__( self._reciprocal_lattice = reciprocal_lattice self._shifted_to_fermi = shifted_to_fermi self._structure = structure + self._atom_groups = atom_groups logger.info("___ElectronicBandStructure initialization complete___") @@ -324,6 +334,10 @@ def fermi(self): def structure(self): return self._structure + @property + def atom_groups(self) -> int | None: + return self._atom_groups + @property def n_kpoints(self): """The number of k points @@ -800,7 +814,7 @@ def compute_projected_sum( species_orbital_map=species_orbital_map, atoms_orbital_map=atoms_orbital_map, ) - atoms_list = list(selection.atoms) if selection.atoms else None + atoms_list = list(selection.atoms) orbitals_list = list(selection.orbitals) if selection.orbitals else None spins_list = list(selection.spins) if selection.spins else None @@ -921,7 +935,7 @@ def compute_projected_sum_spin_texture( spins=None, # All spin components needed for texture species=species, ) - atom_list = list(selection.atoms) if selection.atoms else None + atom_list = list(selection.atoms) orbital_list = list(selection.orbitals) if selection.orbitals else None # Use all atoms/orbitals if none specified @@ -2259,6 +2273,18 @@ def ibz2fbz(ebs, rotations=None, kgrid_info=None, inplace=True, time_reversals=N f"{filled} k-points were filled by time reversal combined with a listed operation, " + "which this magnetic group does not contain; their values may be wrong" ) + if ebs.atom_groups is not None and structure is not None: + unmoved = np.arange(len(structure.atoms)) + if any( + np.any(atom_permutation(structure, rotations[index]) != unmoved) + for index in np.unique(operation[operation != IDENTITY]) + ): + raise ValueError( + "A PROCAR filtered by atoms cannot be unfolded from the irreducible k-points: " + + "symmetry operations move atoms between its rows, and the file does not say " + + "which atoms each row holds. Filter the PROCAR of a full k-grid calculation " + + "(ISYM = -1), or select atoms in the plot of the unfiltered PROCAR." + ) for prop_name, calc_name, gradient_order, value_array in ebs.iter_properties(): ebs.get_property(prop_name)[calc_name, gradient_order] = value_array[source] diff --git a/pyprocar/core/fermisurface.py b/pyprocar/core/fermisurface.py index a9ae33ac..5ab3d8ff 100644 --- a/pyprocar/core/fermisurface.py +++ b/pyprocar/core/fermisurface.py @@ -317,7 +317,7 @@ def compute_projected_sum( species_orbital_map=species_orbital_map, atoms_orbital_map=atoms_orbital_map, ) - atoms_list = list(selection.atoms) if selection.atoms else None + atoms_list = list(selection.atoms) orbitals_list = list(selection.orbitals) if selection.orbitals else None spins_list = list(selection.spins) if selection.spins else None else: diff --git a/pyprocar/core/projection.py b/pyprocar/core/projection.py index 5493a36b..3293f745 100644 --- a/pyprocar/core/projection.py +++ b/pyprocar/core/projection.py @@ -1,6 +1,7 @@ from __future__ import annotations -from collections.abc import Callable, Mapping +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass from enum import Enum from typing import Any, Protocol @@ -50,16 +51,98 @@ def normed_name(self, name: str) -> str: } +@dataclass(frozen=True, slots=True) +class ProjectedLayout: + """The axes of a projection array and the array its leading axes repeat. + + The leading axes run up to and including ``n_spins``. A non-collinear + calculation has 4 projection channels (total, Sx, Sy, Sz) and either 4 or 1 + channels in the leading array: the VASP and Abinit parsers repeat each + eigenvalue 4 times, the QE parser keeps one. + """ + + axes: tuple[str, ...] + leading: str + + @property + def n_leading(self) -> int: + return self.axes.index("n_spins") + 1 + + def __str__(self) -> str: + return f"({', '.join(self.axes)})" + + +BAND_PROJECTIONS = ProjectedLayout( + ("n_kpoints", "n_bands", "n_spins", "n_atoms", "n_orbitals"), "bands" +) +DOS_PROJECTIONS = ProjectedLayout(("n_energies", "n_spins", "n_atoms", "n_orbitals"), "total") +SPIN_CHANNELS = (1, 2, 4) + + +class HasAtoms(Protocol): + @property + def natoms(self) -> int: ... + + def check_projected_layout( - projected: npt.ArrayLike | None, orbital_names: list[str] | None, axes: tuple[str, ...] + projected: npt.ArrayLike | None, + orbital_names: Sequence[str] | None, + layout: ProjectedLayout, + leading: npt.ArrayLike | None = None, + structure: HasAtoms | None = None, + atom_groups: int | None = None, ) -> None: - """Raise unless ``projected`` has ``axes`` and ``orbital_names`` names its last axis.""" + """Raise unless ``projected`` is in ``layout`` and agrees with the data it belongs to. + + Its leading axes must equal the shape of ``leading`` (the bands or the total + DOS), its atom axis must equal ``atom_groups`` when the rows are groups of + atoms and ``structure.natoms`` otherwise, it must have 1, 2 or 4 spin + channels, and ``orbital_names`` must name its last axis. + """ if projected is None: return shape = np.shape(projected) - if len(shape) != len(axes): + if len(shape) != len(layout.axes): + raise ValueError( + f"projected has shape {shape}; it must have the {len(layout.axes)} axes {layout}." + ) + leading_shape = None if leading is None else np.shape(leading) + if leading_shape is not None and len(leading_shape) != layout.n_leading: + raise ValueError( + f"{layout.leading} has shape {leading_shape}; it must have the axes" + + f" ({', '.join(layout.axes[: layout.n_leading])})." + ) + spin_axis = layout.n_leading - 1 + n_spins = (shape if leading_shape is None else leading_shape)[spin_axis] + if n_spins not in SPIN_CHANNELS: + raise ValueError( + f"{'projected' if leading_shape is None else layout.leading} has {n_spins} spin" + + f" channels; a calculation has 1, 2 or 4 spin channels, not {n_spins}" + + " (non-polarized, collinear up and down, or non-collinear total, Sx, Sy, Sz)." + ) + expected: list[tuple[int, ...] | None] = [None] * len(layout.axes) + if leading_shape is not None: + expected[: layout.n_leading] = [(size,) for size in leading_shape] + expected[spin_axis] = (1, 4) if n_spins == 1 else (n_spins,) + if atom_groups is not None: + expected[layout.n_leading] = (atom_groups,) + elif structure is not None: + expected[layout.n_leading] = (structure.natoms,) + if any( + sizes is not None and actual not in sizes + for sizes, actual in zip(expected, shape, strict=True) + ): + described = ", ".join("*" if s is None else "|".join(map(str, s)) for s in expected) + sources = [] if leading_shape is None else [f"{layout.leading} of shape {leading_shape}"] + if atom_groups is not None: + sources.append(f"{atom_groups} atom groups") + elif structure is not None: + sources.append(f"a {structure.natoms}-atom structure") raise ValueError( - f"projected has shape {shape}; it must have the {len(axes)} axes ({', '.join(axes)})." + f"projected has shape {shape}; the layout {layout} expects ({described}) from" + + f" {' and '.join(sources)}. Its spin channels match those of {layout.leading}," + + " except that non-collinear projections (total, Sx, Sy, Sz) may go with one" + + f" {layout.leading} channel." ) n_orbitals = shape[-1] if orbital_names is not None and len(orbital_names) != n_orbitals: @@ -101,11 +184,17 @@ def spin_projection_names(self) -> list[str]: ... def orbital_names(self) -> list[str] | None: ... @property def is_non_collinear(self) -> bool: ... + @property + def atom_groups(self) -> int | None: ... + @property + def n_atoms(self) -> int: ... def selection_resolver(source: ProjectionSource) -> ProjectionSelectionResolver: atom_indexer = ( - None if source.structure is None else AtomIndexer.from_structure(source.structure) + None + if source.structure is None or source.atom_groups is not None + else AtomIndexer.from_structure(source.structure) ) label_builder = ProjectionLabelBuilder( atom_indexer=atom_indexer, @@ -114,6 +203,7 @@ def selection_resolver(source: ProjectionSource) -> ProjectionSelectionResolver: ) return ProjectionSelectionResolver( label_builder=label_builder, + n_atom_rows=source.n_atoms, orbital_names=source.orbital_names, is_non_colinear=source.is_non_collinear, ) @@ -219,7 +309,7 @@ def _selection_metadata( label_latex.append(f"${body_latex}{suffix_latex}$") return { - "atoms": list(selection.atoms) if len(selection.atoms) > 0 else None, + "atoms": list(selection.atoms), "orbitals": list(selection.orbitals) if selection.orbitals is not None else None, "spins": list(selection.spins) if selection.spins is not None else None, "species": list(selection.species) if len(selection.species) > 0 else None, diff --git a/pyprocar/io/abinit/dos.py b/pyprocar/io/abinit/dos.py index e59b3f68..3bea576a 100644 --- a/pyprocar/io/abinit/dos.py +++ b/pyprocar/io/abinit/dos.py @@ -13,6 +13,9 @@ # DOS_AT columns: energy, l=0..4 DOS, l=0..4 integrated DOS, then lm-resolved DOS from lm=0 0. _LM_COLUMNS = slice(11, 20) +# Those columns are lm = 0 0, 1 -1, ..., 2 2 in Abinit's real spherical harmonics, named +# as Abinit's own PROCAR header names them. +_LM_NAMES = ["s", "py", "pz", "px", "dxy", "dyz", "dz2", "dxz", "dx2"] def _read_dos_file(text: str) -> tuple[np.ndarray, float]: @@ -86,6 +89,11 @@ def fermi(self) -> float: """Fermi energy in eV.""" return self._total_dos_data[1] + @cached_property + def orbital_names(self) -> list[str] | None: + """Names of the lm columns that ``projected`` keeps.""" + return list(_LM_NAMES) if self.projected_dos_filepaths else None + @cached_property def projected(self) -> np.ndarray | None: """Projected DOS in electrons/eV with shape (n_energies, n_spins, n_atoms, n_orbitals).""" diff --git a/pyprocar/io/abinit/output.py b/pyprocar/io/abinit/output.py index cf91e81e..6ee543de 100644 --- a/pyprocar/io/abinit/output.py +++ b/pyprocar/io/abinit/output.py @@ -87,6 +87,18 @@ def nspin(self) -> int: match = re.findall(r"nsppol\s*=\s*([1-9]*)", self.file_str) return int(match[0]) + @cached_property + def nspinor(self) -> int: + """Spinor components per wavefunction: 2 for a non-collinear run.""" + match = re.search(r"nspinor\s*=\s*(\d)", self.file_str) + return int(match.group(1)) if match else 1 + + @cached_property + def nspden(self) -> int: + """Density components: 4 when a non-collinear run carries a magnetization.""" + match = re.search(r"nspden\s*=\s*(\d)", self.file_str) + return int(match.group(1)) if match else 1 + @cached_property def reclat(self) -> np.ndarray: """Reciprocal lattice vectors in 1/Angstrom, without the 2*pi (Abinit prints Bohr^-1).""" diff --git a/pyprocar/io/abinit/parser.py b/pyprocar/io/abinit/parser.py index 133d8f9e..c54dd0bf 100644 --- a/pyprocar/io/abinit/parser.py +++ b/pyprocar/io/abinit/parser.py @@ -223,7 +223,7 @@ def ebs(self) -> ElectronicBandStructure | None: projected=procar._spd2projected(procar.spd), fermi=self.abinit_output.fermi, projected_phase=projected_phase, - orbital_names=procar.orbital_names_old[:-1], + orbital_names=procar.orbital_names, reciprocal_lattice=self.abinit_output.reclat, structure=self.structure, kpath=self.kpath, # pyright: ignore[reportArgumentType] @@ -237,9 +237,31 @@ def dos(self) -> DensityOfStates | None: energies=self.abinit_dos.energies, total=self.abinit_dos.dos_total, fermi=self.abinit_dos.fermi, - projected=self.abinit_dos.projected, + projected=self._projected_dos, + orbital_names=self.abinit_dos.orbital_names, + structure=self.structure, ) + @property + def _projected_dos(self) -> np.ndarray | None: + """The DOS_AT projections, as total, Sx, Sy, Sz for a non-magnetic spinor run. + + Abinit's DOS_AT files hold no magnetization components. With nspden = 1 the + density carries no magnetization, time reversal pairs every state with one of + opposite spin, and the spin-resolved DOS is zero. + """ + assert self.abinit_dos is not None + projected = self.abinit_dos.projected + if projected is None or self.abinit_output is None or self.abinit_output.nspinor != 2: + return projected + if self.abinit_output.nspden != 1: + warn_user( + "Abinit's DOS_AT files hold no magnetization components, so the projected DOS" + + f" of this nspden = {self.abinit_output.nspden} spinor run is the total only." + ) + return projected + return np.pad(projected, ((0, 0), (0, 3), (0, 0), (0, 0))) + @property def structure(self) -> Structure | None: if self.abinit_output is None: diff --git a/pyprocar/io/elk/dos.py b/pyprocar/io/elk/dos.py index 461bef08..9afb933b 100644 --- a/pyprocar/io/elk/dos.py +++ b/pyprocar/io/elk/dos.py @@ -8,6 +8,7 @@ import numpy as np import numpy.typing as npt +from pyprocar.io.elk.projections import lm_names from pyprocar.utils.units import HARTREE_TO_EV @@ -159,6 +160,11 @@ def _pdos_parsed(self) -> dict[tuple[str, str], dict[int, npt.NDArray[np.float64 return result + @cached_property + def orbital_names(self) -> list[str]: + """Each PDOS block's (l, m) slot, in the basis Elk writes to ELMIREP.OUT.""" + return lm_names(self.N_ORBITALS) + @cached_property def natoms(self) -> int: """Number of atoms with PDOS data.""" diff --git a/pyprocar/io/elk/parser.py b/pyprocar/io/elk/parser.py index 4aeb9648..fdd3c026 100644 --- a/pyprocar/io/elk/parser.py +++ b/pyprocar/io/elk/parser.py @@ -378,6 +378,8 @@ def _dos(self) -> DensityOfStates | None: total=total, fermi=self.fermi, projected=self._dos_parser.projected, + orbital_names=self._dos_parser.orbital_names, + structure=self.structure, ) @property diff --git a/pyprocar/io/elk/projections.py b/pyprocar/io/elk/projections.py index 346ae609..59ce0552 100644 --- a/pyprocar/io/elk/projections.py +++ b/pyprocar/io/elk/projections.py @@ -11,14 +11,14 @@ _L_NAMES = ["s", "p", "d", "f", "g", "h"] -def _lm_names(n_columns: int) -> list[str]: +def lm_names(n_columns: int) -> list[str]: lmax = round(n_columns**0.5) - 1 return [f"Y{ang}{m}" for ang in range(lmax + 1) for m in range(-ang, ang + 1)] _LAYOUTS: dict[int, tuple[slice, Callable[[int], list[str]]]] = { 21: (slice(1, None), lambda n: _L_NAMES[:n]), - 22: (slice(None), _lm_names), + 22: (slice(None), lm_names), 23: (slice(None), lambda _: ["spin"]), 24: (slice(-1, None), lambda _: ["moment"]), } diff --git a/pyprocar/io/lobster/parser.py b/pyprocar/io/lobster/parser.py index f9e39369..1bedc490 100644 --- a/pyprocar/io/lobster/parser.py +++ b/pyprocar/io/lobster/parser.py @@ -320,6 +320,7 @@ def dos(self) -> DensityOfStates | None: energies=self._doscar.energies + fermi, total=self._doscar.total_dos, projected=self._doscar.projected_dos, + orbital_names=self._doscar.orbital_labels, fermi=fermi, ) diff --git a/pyprocar/io/qe/parser.py b/pyprocar/io/qe/parser.py index 09abf454..b02a03fb 100644 --- a/pyprocar/io/qe/parser.py +++ b/pyprocar/io/qe/parser.py @@ -23,6 +23,7 @@ from pyprocar.core import kpoints as k_utils from pyprocar.io.base import BaseParser from pyprocar.io.qe.projwfc import AtomicProjXML, ProjwfcDOS, ProjwfcIn, ProjwfcOut +from pyprocar.io.qe.projwfc.spinor import spinor_projections from pyprocar.io.qe.pw import PwIn, PwOut, PwXML from pyprocar.utils.log_utils import warn_user from pyprocar.utils.units import AU_TO_ANG, HARTREE_TO_EV @@ -640,7 +641,12 @@ def bands(self) -> np.ndarray | None: @cached_property def spd_phase(self) -> np.ndarray | None: - if self.atomic_proj_xml is None or self.projwfc_out is None: + """Complex projections of a collinear run; a spinor run has no single phase per orbital.""" + if ( + self.atomic_proj_xml is None + or self.projwfc_out is None + or self.projwfc_out.is_non_colinear + ): return None logger.info("Parsing spd phase from atomic_proj.xml and projwfc.out") @@ -667,18 +673,7 @@ def spd_phase(self) -> np.ndarray | None: for state_num, wfc_info in wfc_mapping.items(): atm_num = wfc_info["atm_num"] - orbital_l = wfc_info["l"] - j = wfc_info["j"] - m_j = wfc_info["m_j"] - m = wfc_info["m"] - - orbital_dict = ( - {"l": orbital_l, "j": j, "m_j": m_j} - if m_j is not None - else {"l": orbital_l, "m": m} - ) - - i_orbital = orbitals.index(orbital_dict) + i_orbital = orbitals.index({"l": wfc_info["l"], "m": wfc_info["m"]}) i_atom = atm_num - 1 i_state = state_num - 1 pyprocar_projections_phase[..., i_atom, i_orbital] += projections[..., i_state] @@ -707,6 +702,8 @@ def position_gauge_phase(self) -> np.ndarray | None: @cached_property def spd(self) -> np.ndarray | None: + if self.projwfc_out is not None and self.projwfc_out.is_non_colinear: + return self._spinor_spd if self.spd_phase is None: return None logger.info("Parsing spd from spd phase") @@ -718,6 +715,25 @@ def spd(self) -> np.ndarray | None: logger.debug(f"Spd: {spd.shape}") return spd + @cached_property + def _spinor_spd(self) -> np.ndarray | None: + """Total, Sx, Sy and Sz per (l, m) orbital from the spinor projections.""" + if self.atomic_proj_xml is None or self.atomic_proj_xml.projections is None: + return None + assert self.projwfc_out is not None and self.projwfc_out.n_atoms is not None + spd = spinor_projections( + self.atomic_proj_xml.projections[:, :, 0, :], + self.projwfc_out.atm_wfcs, + self.projwfc_out.n_atoms, + ) + if self.kpath is not None: + spd = k_utils.insert_continuous_points(spd, self.kticks) + return spd + + @cached_property + def orbital_names(self) -> list[str] | None: + return None if self.projwfc_out is None else self.projwfc_out.orbital_names + @cached_property def orbitals(self) -> list[dict[str, int | float]] | None: if self.projwfc_out is not None: @@ -734,10 +750,6 @@ def ebs(self) -> ElectronicBandStructure | None: warn_user("Cannot create EBS without fermi energy") return None - # TODO: orbitals is list[dict] but get_ebs_from_data expects list[str] - # Need to convert quantum numbers to orbital names - orbital_names: list[str] | None = None - return get_ebs_from_data( kpoints=self.kpoints, bands=self.bands, @@ -745,7 +757,7 @@ def ebs(self) -> ElectronicBandStructure | None: projected_phase=self.position_gauge_phase, fermi=self.fermi, reciprocal_lattice=self.reciprocal_lattice, - orbital_names=orbital_names, + orbital_names=self.orbital_names, structure=self.structure, kpath=self.kpath, # pyright: ignore[reportArgumentType] kgrid_info=self.kgrid_info, @@ -778,6 +790,8 @@ def dos(self) -> DensityOfStates | None: total=total_dos, fermi=self.fermi, projected=self.projwfc_dos.projected_dos, + orbital_names=self.projwfc_dos.orbital_names, + structure=self.structure, ) @cached_property diff --git a/pyprocar/io/qe/projwfc/projwfc_dos.py b/pyprocar/io/qe/projwfc/projwfc_dos.py index ef2bc9a8..69442c0c 100644 --- a/pyprocar/io/qe/projwfc/projwfc_dos.py +++ b/pyprocar/io/qe/projwfc/projwfc_dos.py @@ -14,6 +14,7 @@ import pandas as pd # pyright: ignore[reportMissingTypeStubs] from pyprocar.core.atomic_orbital_index import OrbitalIndexer +from pyprocar.io.qe.projwfc.projwfc_out import ORBITAL_NAMES logger = logging.getLogger(__name__) user_logger = logging.getLogger("user") @@ -433,3 +434,10 @@ def orbitals(self): @cached_property def n_orbitals(self) -> int: return len(self.orbitals) + + @cached_property + def orbital_names(self) -> list[str]: + """projwfc.x's (l, m) labels, or l, j and m_j for the spin-orbit states.""" + if not self.is_non_colinear: + return list(ORBITAL_NAMES) + return [ORBITAL_ORDERING.soc_label(index) for index in range(self.n_orbitals)] diff --git a/pyprocar/io/qe/projwfc/projwfc_out.py b/pyprocar/io/qe/projwfc/projwfc_out.py index 1efc6e15..ba8ae45f 100644 --- a/pyprocar/io/qe/projwfc/projwfc_out.py +++ b/pyprocar/io/qe/projwfc/projwfc_out.py @@ -23,6 +23,14 @@ ORBITAL_ORDERING = OrbitalIndexer() +# The l and m labels projwfc.x prints (print_lowdin), in its real-harmonic order m = 1..2l+1. +ORBITAL_NAMES = [ + "s", + *("pz", "px", "py"), + *("dz2", "dxz", "dyz", "dx2-y2", "dxy"), + *("fz3", "fxz2", "fyz2", "fzx2-zy2", "fxyz", "fx3-3xy2", "f3yx2-y3"), +] + def convert_lorbnum_to_letter(lorbnum): """A helper method to convert the lorb number to the letter format @@ -104,9 +112,10 @@ def version(self) -> str | None: @cached_property def is_non_colinear(self) -> bool: + """Whether the states are spinors: |l j m_j> with spin-orbit, |l m s_z> without.""" if self.atm_wfcs: atm_wfc = self.atm_wfcs[0] - return atm_wfc["j"] is not None + return atm_wfc["j"] is not None or atm_wfc["s_z"] is not None return False @cached_property @@ -145,13 +154,14 @@ def n_atm_wfcs(self) -> int: def atm_wfcs(self): state_pattern = re.compile( r"""^\s*state\s+\#\s*(?P\d+):\s* - atom\s+(?P\d+)\s*\((?P[A-Za-z]+)\s*\),\s* + atom\s+(?P\d+)\s*\((?P[^\s)]+)\s*\),\s* wfc\s+(?P\d+)\s* \( l\s*=\s*(?P\d+) (?:\s+j\s*=\s*(?P[-+]?\d+(?:\.\d+)?))? (?:\s+m_j\s*=\s*(?P[-+]?\d+(?:\.\d+)?))? (?:\s+m\s*=\s*(?P[-+]?\d+(?:\.\d+)?))? + (?:\s+s_z\s*=\s*(?P[-+]?\d+(?:\.\d+)?))? \) """, re.VERBOSE | re.MULTILINE, @@ -169,6 +179,7 @@ def atm_wfcs(self): "j": float(match.group("j")) if match.group("j") else None, "m_j": float(match.group("mj")) if match.group("mj") else None, "m": int(match.group("m")) if match.group("m") else None, + "s_z": float(match.group("s_z")) if match.group("s_z") else None, } ) @@ -235,19 +246,13 @@ def n_atoms(self) -> int | None: return n_atoms @cached_property - def non_colinear_orbitals(self): - return ORBITAL_ORDERING.flat_soc_order - - @cached_property - def colinear_orbitals(self): + def orbitals(self): + """The (l, m) orbitals pyprocar projects onto; spinor states map onto them too.""" return ORBITAL_ORDERING.az_to_lm_records @cached_property - def orbitals(self): - if self.is_non_colinear: - return self.non_colinear_orbitals - else: - return self.colinear_orbitals + def orbital_names(self) -> list[str]: + return list(ORBITAL_NAMES) @cached_property def n_orbitals(self) -> int: diff --git a/pyprocar/io/qe/projwfc/spinor.py b/pyprocar/io/qe/projwfc/spinor.py new file mode 100644 index 00000000..185aea65 --- /dev/null +++ b/pyprocar/io/qe/projwfc/spinor.py @@ -0,0 +1,157 @@ +"""Turn projwfc.x spinor projections into total, Sx, Sy and Sz per real (l, m) orbital. + +In a non-collinear run projwfc.x projects each band onto spinor atomic states: +``|l m s_z>`` without spin-orbit coupling and ``|l j m_j>`` with it. The +coefficients come from QE 7.2: ``spinor`` and ``sph_ind`` (upflib) build each +``|l j m_j>`` from complex spherical harmonics, and ``rot_ylm`` (upflib +init_us_1.f90) writes those in the real harmonics that ``ylmr2`` defines, whose +order m = 1..2l+1 projwfc.x prints as z, x, y for p and z2, xz, yz, x2-y2, xy for d. +""" + +from collections import defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from itertools import zip_longest +from typing import Self + +import numpy as np +import numpy.typing as npt + +from pyprocar.io.qe.projwfc.projwfc_out import ORBITAL_NAMES + + +@dataclass(frozen=True, slots=True) +class SpinorState: + """One projwfc.x atomic state: |l j m_j> with spin-orbit, |l m s_z> without.""" + + atom: int + wfc: int + ang: int + j: float | None + m_j: float | None + m: int | None + s_z: float | None + + @classmethod + def from_record(cls, record: Mapping[str, int | float | None]) -> Self: + def optional(key: str) -> float | None: + value = record[key] + return None if value is None else float(value) + + m = record["m"] + return cls( + atom=int(record["atom_num"] or 0), + wfc=int(record["wfc_num"] or 0), + ang=int(record["l"] or 0), + j=optional("j"), + m_j=optional("m_j"), + m=None if m is None else int(m), + s_z=optional("s_z"), + ) + + @property + def is_upper(self) -> bool: + return self.j is not None and abs(self.j - self.ang - 0.5) < 1e-8 + + def in_real_harmonics(self) -> npt.NDArray[np.complex128]: + """The state's components on (real m, spin up/down), shape (2l+1, 2).""" + ang = self.ang + components = np.zeros((2 * ang + 1, 2), dtype=np.complex128) + if self.s_z is not None and self.m is not None: + components[self.m - 1, 0 if self.s_z > 0 else 1] = 1.0 + return components + assert self.j is not None and self.m_j is not None + m = round(self.m_j - 0.5 if self.is_upper else self.m_j + 0.5) + for spin in (1, 2): + k = _sph_ind(self.is_upper, m, spin) + if abs(k) <= ang: + components[:, spin - 1] = _spinor(ang, self.is_upper, m, spin) * _complex_to_real( + ang, k + ) + return components + + +def _spinor(ang: int, upper: bool, m: int, spin: int) -> float: + if upper: + return np.sqrt((ang + m + 1 if spin == 1 else ang - m) / (2 * ang + 1)) + if m < -ang + 1: + return 0.0 + return ( + np.sqrt((ang - m + 1) / (2 * ang + 1)) if spin == 1 else -np.sqrt((ang + m) / (2 * ang + 1)) + ) + + +def _sph_ind(upper: bool, m: int, spin: int) -> int: + if upper: + return m if spin == 1 else m + 1 + return m - 1 if spin == 1 else m + + +def _complex_to_real(ang: int, k: int) -> npt.NDArray[np.complex128]: + """Coefficients of the complex harmonic m = k on the 2l+1 real harmonics (rot_ylm).""" + row = np.zeros(2 * ang + 1, dtype=np.complex128) + if k == 0: + row[0] = 1.0 + return row + mm = abs(k) + sign = (-1.0) ** mm if k < 0 else 1.0 + row[2 * mm - 1] = sign / np.sqrt(2.0) + row[2 * mm] = (-1j if k < 0 else 1j) * sign / np.sqrt(2.0) + return row + + +def _shells(states: Sequence[SpinorState]) -> list[list[int]]: + """Group state indices into shells that span all real m and both spins of one l. + + projwfc.x lists the j = l - 1/2 and j = l + 1/2 states of a fully relativistic + pseudopotential as separate wavefunctions; the n-th of each pair up per atom and l. + """ + by_wfc: dict[tuple[int, int], list[int]] = defaultdict(list) + for index, state in enumerate(states): + by_wfc[(state.atom, state.wfc)].append(index) + halves: dict[tuple[int, int, bool], list[list[int]]] = defaultdict(list) + shells: list[list[int]] = [] + for (atom, _), indices in by_wfc.items(): + first = states[indices[0]] + if first.j is None or first.ang == 0 or len({states[i].j for i in indices}) == 2: + shells.append(indices) + else: + halves[(atom, first.ang, first.is_upper)].append(indices) + for atom, ang in dict.fromkeys((atom, ang) for atom, ang, _ in halves): + for lower, upper in zip_longest( + halves[(atom, ang, False)], halves[(atom, ang, True)], fillvalue=[] + ): + shells.append(lower + upper) + return shells + + +def spinor_projections( + amplitudes: npt.NDArray[np.complexfloating], + records: Sequence[Mapping[str, int | float | None]], + n_atoms: int, +) -> npt.NDArray[np.float64]: + """Total, Sx, Sy and Sz of each band on each atom's real (l, m) orbitals. + + ``amplitudes`` holds with shape (n_kpoints, n_bands, n_states), and + ``records`` describes each state as ProjwfcOut.atm_wfcs does. Returns shape + (n_kpoints, n_bands, 4, n_atoms, 16), orbitals in projwfc.x's real-harmonic + order. Shells with different radial functions add incoherently. + """ + states = [SpinorState.from_record(record) for record in records] + n_kpoints, n_bands, _ = amplitudes.shape + projected = np.zeros((n_kpoints, n_bands, 4, n_atoms, len(ORBITAL_NAMES))) + for shell in _shells(states): + ang, atom = states[shell[0]].ang, states[shell[0]].atom - 1 + basis = np.array([states[i].in_real_harmonics() for i in shell]) + components = (amplitudes[..., shell] @ basis.reshape(len(shell), -1)).reshape( + n_kpoints, n_bands, 2 * ang + 1, 2 + ) + up, down = components[..., 0], components[..., 1] + up2, down2 = up.real**2 + up.imag**2, down.real**2 + down.imag**2 + up_down = np.conj(up) * down + out = projected[:, :, :, atom, ang * ang : (ang + 1) ** 2] + out[:, :, 0] += up2 + down2 + out[:, :, 1] += 2 * up_down.real + out[:, :, 2] += 2 * up_down.imag + out[:, :, 3] += up2 - down2 + return projected diff --git a/pyprocar/io/vasp/parser.py b/pyprocar/io/vasp/parser.py index 6ab4da5b..8fef789a 100644 --- a/pyprocar/io/vasp/parser.py +++ b/pyprocar/io/vasp/parser.py @@ -15,6 +15,7 @@ from pyprocar.io.vasp.poscar import Poscar from pyprocar.io.vasp.procar import Procar from pyprocar.io.vasp.vasprun import VaspXML +from pyprocar.utils.log_utils import warn_user logger = logging.getLogger(__name__) @@ -244,6 +245,16 @@ def ebs(self) -> ElectronicBandStructure | None: ) return None + structure = self.structure + atom_groups = None + if structure is not None and self.procar.n_atoms != structure.natoms: + atom_groups = self.procar.n_atoms + warn_user( + f"The PROCAR has {atom_groups} ion rows and the structure {structure.natoms}" + + " atoms, so each row is a group of atoms written by pyprocar.filter. Atom" + + " index i selects the i-th group, and species selections raise." + ) + return get_ebs_from_data( kpoints=self.procar.kpoints, bands=self.procar.bands, @@ -251,10 +262,11 @@ def ebs(self) -> ElectronicBandStructure | None: projected_phase=self.procar.projected_phase, fermi=self.outcar.fermi, reciprocal_lattice=self.outcar.reciprocal_lattice, - orbital_names=self._orbital_names(self.procar.projected), - structure=self.structure, + orbital_names=self.procar.orbital_names, + structure=structure, kpath=self.kpath, kgrid_info=self.kgrid_info, + atom_groups=atom_groups, ) @cached_property diff --git a/pyprocar/io/vasp/procar.py b/pyprocar/io/vasp/procar.py index 09614bf4..9aa12301 100644 --- a/pyprocar/io/vasp/procar.py +++ b/pyprocar/io/vasp/procar.py @@ -69,39 +69,16 @@ def filename(self) -> str: return "" return self.filepath.name - @property + @cached_property def orbital_names(self) -> list[str]: - return [ - "s", - "py", - "pz", - "px", - "dxy", - "dyz", - "dz2", - "dxz", - "x2-y2", - "fy3x2", - "fxyz", - "fyz2", - "fz3", - "fxz2", - "fzx2", - "fx3", - "tot", - ] + """The orbital columns the PROCAR header names, between "ion" and "tot". - @property - def orbital_names_old(self) -> list[str]: - return ["s", "py", "pz", "px", "dxy", "dyz", "dz2", "dxz", "dx2", "tot"] - - @property - def orbital_names_short(self) -> list[str]: - return ["s", "p", "d", "f", "tot"] - - @property - def labels(self) -> list[str]: - return self.orbital_names_old[:-1] + A PROCAR that pyprocar.filter rewrote names its summed columns o0, o1, ... + """ + header = re.search(r"^ion(.+)tot\s*$", self.file_str, re.MULTILINE) + if header is None: + raise ValueError("No 'ion ... tot' orbital header found in the PROCAR file") + return header.group(1).split() @cached_property def n_kpoints(self) -> int: @@ -223,22 +200,7 @@ def has_phase(self) -> bool: @cached_property def n_orbitals(self) -> int: - """Get the number of orbitals from the first orbital header""" - orbital_headers = re.findall(r"ion(.+)", self.file_str) - if len(orbital_headers) == 0: - raise ValueError("No orbital headers found in PROCAR file") - - # Look for a header with "tot" in it (the regular projection header) - # Phase headers don't have "tot" - for header in orbital_headers: - found_orbs = header.split() - if "tot" in found_orbs: - # Subtract 1 for "tot" column - return len(found_orbs) - 1 - - # If no header with "tot" found, use the first header - found_orbs = orbital_headers[0].split() - return len(found_orbs) + return len(self.orbital_names) @cached_property def spd(self) -> np.ndarray | None: @@ -280,30 +242,7 @@ def _read_projections(self) -> np.ndarray | None: """ - # finding all orbital headers - header_lines = re.findall(r"(ion.+tot)", self.file_str) - - # testing if the orbital names are known (the standard ones) - orbital_in_procar = header_lines[0].split() - n_spd_columns = len(orbital_in_procar) - - # only the first 'size' orbital - standard_orbitals = self.orbital_names[: n_spd_columns - 1] + self.orbital_names[-1:] - standard_orbitals_short = ( - self.orbital_names_short[: n_spd_columns - 1] + self.orbital_names_short[-1:] - ) - standard_orbitals_old = self.orbital_names_old[: n_spd_columns - 1] + [ - self.orbital_names_old[-1:] - ] - if ( - orbital_in_procar != standard_orbitals - and orbital_in_procar != standard_orbitals_short - and orbital_in_procar != standard_orbitals_old - ): - logger.warning( - f"{n_spd_columns} orbitals. (Some of) " - + "They are unknow (if you did 'filter' them it is OK)." - ) + n_spd_columns = self.n_orbitals + 2 # VASP writes no "tot" row for a single ion; Abinit writes one anyway has_tot_row = self.n_atoms > 1 or re.search(r"^\s*tot\s", self.file_str, re.M) is not None @@ -377,31 +316,6 @@ def _read_phases(self) -> np.ndarray | None: """ Helped method to parse the projection phases """ - # finding all orbital headers - header_lines = re.findall(r"(ion.+tot)", self.file_str) - - # testing if the orbital names are known (the standard ones) - orbital_in_procar = header_lines[0].split() - n_spd_columns = len(orbital_in_procar) - - # only the first 'size' orbital - standard_orbitals = self.orbital_names[: n_spd_columns - 1] + self.orbital_names[-1:] - standard_orbitals_short = ( - self.orbital_names_short[: n_spd_columns - 1] + self.orbital_names_short[-1:] - ) - standard_orbitals_old = self.orbital_names_old[: n_spd_columns - 1] + [ - self.orbital_names_old[-1:] - ] - if ( - orbital_in_procar != standard_orbitals - and orbital_in_procar != standard_orbitals_short - and orbital_in_procar != standard_orbitals_old - ): - logger.warning( - f"{n_spd_columns} orbitals. (Some of) " - + "They are unknow (if you did 'filter' them it is OK)." - ) - # Vasp format different for 1 atom n_spd_rows = self.n_atoms + 1 # n_projection_rows = self.n_atoms + 1 diff --git a/pyprocar/scripts/_selection.py b/pyprocar/scripts/_selection.py index c9f57e95..de5f5fac 100644 --- a/pyprocar/scripts/_selection.py +++ b/pyprocar/scripts/_selection.py @@ -4,17 +4,52 @@ import numpy as np -from pyprocar.core.atomic_orbital_index import PRIMARY_ORBITAL_GROUPS +from pyprocar.core.atomic_orbital_index import orbital_shells from pyprocar.core.property_store import Property -ORBITAL_GROUPS = {name: list(indices) for name, indices in PRIMARY_ORBITAL_GROUPS} +SHELL_LETTERS = ("s", "p", "d", "f") -def orbital_indices(orbitals): - """Resolve orbital group names ("s", "p", "d", "f") to indices; indices pass through.""" - if orbitals is None or len(orbitals) == 0 or not isinstance(orbitals[0], str): +def present_shells(source) -> dict[str, list[int]]: + """The s, p, d and f shells among ``source``'s orbitals, by the names it carries. + + A shell is either its 2l+1 orbitals or one column named by its letter, the sum + that Elk's task 21 and ``pyprocar.filter(orbital_names=[...])`` write. + """ + shells = { + letter: list(indices) + for letter, indices in orbital_shells(source.orbital_names) + if max(indices) < source.n_orbitals + } + for index, name in enumerate(source.orbital_names or ()): + if name in SHELL_LETTERS: + shells.setdefault(name, [index]) + return {letter: shells[letter] for letter in SHELL_LETTERS if letter in shells} + + +def orbital_indices(orbitals, source): + """Resolve shell names (s, p, d, f) to the orbitals of ``source``; indices pass through.""" + if orbitals is None or len(orbitals) == 0: return orbitals - return [i for name in orbitals for i in ORBITAL_GROUPS[name]] + shells = present_shells(source) + indices = [] + for orbital in orbitals: + if not isinstance(orbital, str): + indices.append(orbital) + elif orbital in shells: + indices.extend(shells[orbital]) + elif orbital in SHELL_LETTERS: + raise ValueError( + f"orbitals names the {orbital} shell, but the orbitals {source.orbital_names}" + + f" hold no whole {orbital} shell. Select orbitals by index." + ) + else: + raise ValueError( + f"orbitals takes orbital indices or the shell names {', '.join(SHELL_LETTERS)}," + + f" not {orbital!r}. Select one orbital by its index, its position in the" + + " orbital names, for example 8 for d x2-y2 in VASP's order." + ) + return indices class SpinSelection(NamedTuple): @@ -61,12 +96,16 @@ def projection_components(source, kind: str, atoms=None, orbitals=None, items=No if kind == "species": selections = [(s, {"species": [s], "orbitals": orbitals}) for s in source.structure.species] elif kind == "orbitals": - groups = ["s", "p", "d", "f"] if source.n_orbitals > 9 else ["s", "p", "d"] - selections = [(g, {"atoms": atoms, "orbitals": ORBITAL_GROUPS[g]}) for g in groups] + shells = present_shells(source) + if not shells: + raise ValueError( + f"The orbitals {source.orbital_names} hold no whole s, p, d or f shell to overlay." + ) + selections = [(g, {"atoms": atoms, "orbitals": shells[g]}) for g in shells] else: mappings = [items] if isinstance(items, dict) else list(items or []) selections = [ - (s, {"species": [s], "orbitals": orbital_indices(orbs)}) + (s, {"species": [s], "orbitals": orbital_indices(orbs, source)}) for mapping in mappings for s, orbs in mapping.items() ] diff --git a/pyprocar/scripts/scriptBandsplot.py b/pyprocar/scripts/scriptBandsplot.py index 41d97e81..07d2b7a3 100644 --- a/pyprocar/scripts/scriptBandsplot.py +++ b/pyprocar/scripts/scriptBandsplot.py @@ -13,7 +13,8 @@ from pyprocar.cfg import ConfigFactory, ConfigManager from pyprocar.cfg.band_structure import BandStructureConfig from pyprocar.cfg.base import PlotType -from pyprocar.core import ElectronicBandStructureMesh, ElectronicBandStructurePath, Structure +from pyprocar.core import ElectronicBandStructureMesh, ElectronicBandStructurePath +from pyprocar.core.projection import selection_resolver from pyprocar.core.property_store import Property from pyprocar.plotter.bs_plot import BandStructurePlotter from pyprocar.scripts._selection import ( @@ -228,10 +229,9 @@ def bandsplot( channels = projection_spins = [0] if atoms is not None and isinstance(atoms[0], str): - species = set(atoms) - names = np.asarray(cast(Structure, ebs.structure).atoms) - atoms = [i for i, name in enumerate(names) if name in species] - orbitals = orbital_indices(orbitals) + species = [str(name) for name in atoms] + atoms = list(selection_resolver(ebs).resolve(species=species).atoms) + orbitals = orbital_indices(orbitals, ebs) user_clim = config.clim if "clim" in kwargs else None diff --git a/pyprocar/scripts/scriptDosplot.py b/pyprocar/scripts/scriptDosplot.py index 4a880fe5..b94952c1 100644 --- a/pyprocar/scripts/scriptDosplot.py +++ b/pyprocar/scripts/scriptDosplot.py @@ -299,13 +299,13 @@ def dosplot( user_logger.info(f"{key} : {value}") user_logger.info("_" * 100) - orbitals = orbital_indices(orbitals) if mode not in DOS_MODES: raise ValueError(f"The mode needs to be one of {DOS_MODES}, got {mode!r}") if dirname is None: raise ValueError("dirname is required") dos = DensityOfStates.from_code(code, dirname, use_cache=use_cache) + orbitals = orbital_indices(orbitals, dos) codes_with_scf_fermi = ["qe", "elk", "abinit"] if code in codes_with_scf_fermi and fermi is None: diff --git a/pyprocar/scripts/scriptUnfold.py b/pyprocar/scripts/scriptUnfold.py index bfca82c0..24efc910 100644 --- a/pyprocar/scripts/scriptUnfold.py +++ b/pyprocar/scripts/scriptUnfold.py @@ -7,6 +7,7 @@ from pyprocar.cfg import ConfigFactory, ConfigManager, PlotType from pyprocar.cfg.unfold import UnfoldingConfig, UnfoldMode, UnfoldPlotMode from pyprocar.core import ElectronicBandStructurePath, Structure +from pyprocar.core.projection import selection_resolver from pyprocar.core.property_store import Property from pyprocar.plotter.bs_plot import BandStructurePlotter from pyprocar.scripts._selection import ( @@ -182,9 +183,9 @@ def unfold( weights = take_channels(cast(Property, ebs.weights), channels) if atoms is not None and isinstance(atoms[0], str): - species = set(atoms) - atoms = [i for i, name in enumerate(np.asarray(structure.atoms)) if name in species] - orbitals = orbital_indices(orbitals) + species = [str(name) for name in atoms] + atoms = list(selection_resolver(ebs).resolve(species=species).atoms) + orbitals = orbital_indices(orbitals, ebs) plotter = BandStructurePlotter(ax=ax) linestyle = per_channel(config.linestyle, n_channels) diff --git a/tests/pyprocar/core/test_atomic_orbital_index.py b/tests/pyprocar/core/test_atomic_orbital_index.py index 6a22246c..d578314c 100644 --- a/tests/pyprocar/core/test_atomic_orbital_index.py +++ b/tests/pyprocar/core/test_atomic_orbital_index.py @@ -92,6 +92,7 @@ def test_projection_selection_resolver_resolves_species_selection(): ) resolver = ProjectionSelectionResolver( label_builder=builder, + n_atom_rows=10, orbital_names=["s", "p_y", "p_z", "p_x", "d_{xy}", "d_{yz}", "d_{z^2}", "d_{xz}"], is_non_colinear=False, ) @@ -119,6 +120,7 @@ def test_projection_selection_resolver_species_orbital_map(): ) resolver = ProjectionSelectionResolver( label_builder=builder, + n_atom_rows=5, orbital_names=None, is_non_colinear=False, ) @@ -141,6 +143,7 @@ def test_projection_selection_resolver_defaults_to_all_atoms(): ) resolver = ProjectionSelectionResolver( label_builder=builder, + n_atom_rows=5, orbital_names=None, is_non_colinear=False, ) diff --git a/tests/pyprocar/core/test_dos.py b/tests/pyprocar/core/test_dos.py index 3ca88910..380e12db 100644 --- a/tests/pyprocar/core/test_dos.py +++ b/tests/pyprocar/core/test_dos.py @@ -4,6 +4,7 @@ from pyprocar.core.dos import DensityOfStates from pyprocar.core.property_store import Property from pyprocar.core.structure import Structure +from tests.pyprocar.core.test_ibz2fbz import VASP_ORBITALS from tests.utils import DATA_DIR @@ -632,3 +633,44 @@ def test_dos_rejects_orbital_names_that_do_not_match_the_projected_orbitals(): projected=np.ones((5, 1, 2, 9)), orbital_names=[f"o{i}" for i in range(16)], ) + + +def _structureless_dos(n_spins: int) -> DensityOfStates: + """Weight (atom + 1) * (orbital + 1) on two atoms, halved in the spin-down channel.""" + energies = np.linspace(-1.0, 1.0, 3) + spin_scale = np.array([1.0, 0.5])[:n_spins] + projected = np.einsum("s,a,o->sao", spin_scale, np.arange(1.0, 3.0), np.arange(1.0, 10.0)) + return DensityOfStates( + energies=energies, + total=np.ones((3, n_spins)), + projected=np.broadcast_to(projected, (3, *projected.shape)).copy(), + orbital_names=VASP_ORBITALS, + ) + + +def test_projected_sum_without_structure_or_atoms_sums_every_atom_row() -> None: + d_shell = [4, 5, 6, 7, 8] + + prop = _structureless_dos(n_spins=1).compute_projected_sum(orbitals=d_shell) + + assert isinstance(prop, Property) + # (1 + 2) * (5 + 6 + 7 + 8 + 9) on each energy + np.testing.assert_allclose(np.asarray(prop.value).ravel(), [105.0, 105.0, 105.0]) + + +def test_magnetization_without_structure_or_atoms_sums_every_atom_row() -> None: + prop = _structureless_dos(n_spins=2).compute_magnetization(orbitals=[1, 2, 3]) + + assert isinstance(prop, Property) + # (1 - 0.5) * (1 + 2) * (2 + 3 + 4) on each energy + np.testing.assert_allclose(np.asarray(prop.value).ravel(), [13.5, 13.5, 13.5]) + + +def test_an_empty_atom_selection_raises_instead_of_summing_nothing() -> None: + with pytest.raises(ValueError, match="names no atoms"): + _structureless_dos(n_spins=1).compute_projected_sum(atoms=[], orbitals=[0]) + + +def test_an_empty_spin_selection_raises_instead_of_summing_nothing() -> None: + with pytest.raises(ValueError, match="names no spins"): + _structureless_dos(n_spins=2).compute_projected_sum(atoms=[0], spins=[]) diff --git a/tests/pyprocar/core/test_orbital_labels.py b/tests/pyprocar/core/test_orbital_labels.py new file mode 100644 index 00000000..2e386a58 --- /dev/null +++ b/tests/pyprocar/core/test_orbital_labels.py @@ -0,0 +1,75 @@ +"""Selection labels name orbitals the way the parser named them. + +A shell letter (s, p, d, f) stands for a selection only when the parser's names +say those columns are that whole shell. The names below are the ones each code +prints: a filtered PROCAR header, projwfc.x's Lowdin labels, Elk's ELMIREP.OUT +and projwfc.x's spin-orbit pdos file names. +""" + +from typing import cast + +import numpy as np +import pytest + +from pyprocar.core import ElectronicBandStructure, Structure, kpoints +from pyprocar.core.ebs import PROJECTED_DTYPE + +QE_NAMES = ["s", "pz", "px", "py", "dz2", "dxz", "dyz", "dx2-y2", "dxy"] +ELK_NAMES = ["Y00", "Y1-1", "Y10", "Y11", "Y2-2", "Y2-1", "Y20", "Y21", "Y22"] +QE_SPIN_ORBIT_NAMES = [ + "l0_j0.5_m-0.5", + "l0_j0.5_m0.5", + "l1_j0.5_m-0.5", + "l1_j0.5_m0.5", + "l1_j1.5_m-1.5", +] + + +def orbital_label(orbital_names: list[str], orbitals: list[int]) -> str: + ebs = ElectronicBandStructure( + kpoints=cast(kpoints.KPOINTS_DTYPE, np.zeros((1, 3))), + bands=np.zeros((1, 1, 1)), + projected=cast(PROJECTED_DTYPE, np.ones((1, 1, 1, 1, len(orbital_names)))), + orbital_names=orbital_names, + structure=Structure( + atoms=["V"], fractional_coordinates=np.zeros((1, 3)), lattice=np.eye(3) + ), + ) + return ebs.compute_projected_sum(orbitals=orbitals).metadata["orbital_label"] + + +@pytest.mark.parametrize( + ("orbital_names", "orbitals", "expected"), + [ + pytest.param(["o0", "o1"], [0], "o0", id="filtered-procar"), + pytest.param(QE_SPIN_ORBIT_NAMES, [0, 1], "l0_j0.5_m-0.5,l0_j0.5_m0.5", id="qe-j-basis"), + ], +) +def test_label_uses_the_parser_names_when_they_are_not_a_whole_shell( + orbital_names, orbitals, expected +) -> None: + assert orbital_label(orbital_names, orbitals) == expected + + +@pytest.mark.guards_existing_behaviour( + reason="shell letters already label whole shells; the fix must keep them" +) +@pytest.mark.parametrize( + ("orbital_names", "orbitals", "expected"), + [ + pytest.param(QE_NAMES, [1, 2, 3], "p", id="qe-p"), + pytest.param(QE_NAMES, [0, 4, 5, 6, 7, 8], "s,d", id="qe-s-d"), + pytest.param(ELK_NAMES, [1, 2, 3], "p", id="elk-p"), + pytest.param(QE_NAMES, [1, 2], "pz,px", id="qe-part-of-p"), + pytest.param(["s", "p", "d"], [1], "p", id="filtered-procar-named-shells"), + ], +) +def test_label_uses_the_shell_letter_for_a_whole_shell(orbital_names, orbitals, expected) -> None: + assert orbital_label(orbital_names, orbitals) == expected + + +@pytest.mark.guards_existing_behaviour( + reason="the fixed table never called py and pz a p shell; orbital_shells must not either" +) +def test_two_of_three_p_orbitals_are_not_labelled_p() -> None: + assert orbital_label(["s", "py", "pz"], [1, 2]) == "py,pz" diff --git a/tests/pyprocar/core/test_projected_layout.py b/tests/pyprocar/core/test_projected_layout.py new file mode 100644 index 00000000..bd509e06 --- /dev/null +++ b/tests/pyprocar/core/test_projected_layout.py @@ -0,0 +1,144 @@ +import re +from typing import cast + +import numpy as np +import pytest + +from pyprocar.core import DensityOfStates, ElectronicBandStructure, Structure, kpoints +from pyprocar.core.ebs import PROJECTED_DTYPE + +N_K, N_BANDS, N_ATOMS, N_ORBITALS = 2, 3, 5, 9 +BAND_LAYOUT = "(n_kpoints, n_bands, n_spins, n_atoms, n_orbitals)" +DOS_LAYOUT = "(n_energies, n_spins, n_atoms, n_orbitals)" + + +def five_atoms() -> Structure: + return Structure( + atoms=["Sr", "V", "O", "O", "O"], + fractional_coordinates=np.zeros((N_ATOMS, 3)), + lattice=np.eye(3) * 3.9, + ) + + +def band_structure( + projected_shape: tuple[int, ...], n_band_spins: int = 1, structure: Structure | None = None +) -> ElectronicBandStructure: + return ElectronicBandStructure( + kpoints=cast(kpoints.KPOINTS_DTYPE, np.zeros((N_K, 3))), + bands=np.zeros((N_K, N_BANDS, n_band_spins)), + projected=cast(PROJECTED_DTYPE, np.zeros(projected_shape)), + orbital_names=[f"o{i}" for i in range(projected_shape[-1])], + structure=structure, + ) + + +@pytest.mark.parametrize( + ("projected_shape", "n_band_spins", "with_structure", "expected"), + [ + pytest.param( + (N_K, N_BANDS, N_ATOMS, 1, N_ORBITALS), + 1, + False, + "(2, 3, 1|4, *, *)", + id="spin-atom-swap", + ), + pytest.param( + (N_BANDS, N_K, 1, N_ATOMS, N_ORBITALS), 1, False, "(2, 3, 1|4, *, *)", id="k-band-swap" + ), + pytest.param( + (N_K, N_BANDS, 1, 4, N_ORBITALS), 1, True, "(2, 3, 1|4, 5, *)", id="atoms-not-structure" + ), + pytest.param( + (N_K, N_BANDS, 4, N_ATOMS, N_ORBITALS), 2, False, "(2, 3, 2, *, *)", id="collinear-4" + ), + pytest.param( + (N_K, N_BANDS, 1, N_ATOMS, N_ORBITALS), 4, False, "(2, 3, 4, *, *)", id="ncl-bands-1" + ), + ], +) +def test_band_structure_names_the_expected_layout_for_misordered_projections( + projected_shape, n_band_spins, with_structure, expected +): + structure = five_atoms() if with_structure else None + + with pytest.raises(ValueError) as error: + band_structure(projected_shape, n_band_spins, structure) + + assert BAND_LAYOUT in str(error.value) + assert expected in str(error.value) + + +def test_band_structure_rejects_a_spin_count_that_is_not_1_2_or_4(): + with pytest.raises(ValueError, match=re.escape("1, 2 or 4 spin channels, not 3")): + band_structure((N_K, N_BANDS, 3, N_ATOMS, N_ORBITALS), n_band_spins=3) + + +@pytest.mark.guards_existing_behaviour( + reason="every valid spin layout loads on the base; the stronger check must keep accepting them" +) +@pytest.mark.parametrize( + ("n_band_spins", "n_spins"), [(1, 1), (2, 2), (4, 4), (1, 4)], ids=["1", "2", "4", "1-4"] +) +def test_band_structure_accepts_each_spin_layout_with_a_matching_structure(n_band_spins, n_spins): + ebs = band_structure((N_K, N_BANDS, n_spins, N_ATOMS, N_ORBITALS), n_band_spins, five_atoms()) + + assert ebs.projected is not None + assert ebs.projected.to_array().shape == (N_K, N_BANDS, n_spins, N_ATOMS, N_ORBITALS) + + +@pytest.mark.parametrize( + ("total_shape", "projected_shape", "with_structure", "expected"), + [ + pytest.param( + (7, 1), (7, N_ATOMS, 1, N_ORBITALS), False, "(7, 1|4, *, *)", id="spin-atom-swap" + ), + pytest.param( + (7, 2), (7, 1, N_ATOMS, N_ORBITALS), False, "(7, 2, *, *)", id="spins-not-total" + ), + pytest.param((7, 1), (6, 1, N_ATOMS, N_ORBITALS), False, "(7, 1|4, *, *)", id="energies"), + pytest.param((7, 4), (7, 4, 2, N_ORBITALS), True, "(7, 4, 5, *)", id="atoms-not-structure"), + ], +) +def test_dos_names_the_expected_layout_for_misordered_projections( + total_shape, projected_shape, with_structure, expected +): + with pytest.raises(ValueError) as error: + DensityOfStates( + energies=np.linspace(-1.0, 1.0, total_shape[0]), + total=np.ones(total_shape), + projected=np.ones(projected_shape), + orbital_names=[f"o{i}" for i in range(projected_shape[-1])], + structure=five_atoms() if with_structure else None, + ) + + assert DOS_LAYOUT in str(error.value) + assert expected in str(error.value) + + +def grouped_band_structure(projected: np.ndarray, atom_groups: int) -> ElectronicBandStructure: + return ElectronicBandStructure( + kpoints=cast(kpoints.KPOINTS_DTYPE, np.zeros((N_K, 3))), + bands=np.zeros((N_K, N_BANDS, 1)), + projected=cast(PROJECTED_DTYPE, projected), + orbital_names=[f"o{i}" for i in range(projected.shape[-1])], + structure=five_atoms(), + atom_groups=atom_groups, + ) + + +def test_band_structure_of_atom_groups_selects_each_group_row(): + rows = np.arange(3.0).reshape(1, 1, 1, 3, 1) * np.ones((N_K, N_BANDS, 1, 3, N_ORBITALS)) + + ebs = grouped_band_structure(rows, atom_groups=3) + + np.testing.assert_allclose(ebs.compute_projected_sum(atoms=[2]).value, 2.0 * N_ORBITALS) + np.testing.assert_allclose(ebs.compute_projected_sum(orbitals=[0]).value, 0.0 + 1.0 + 2.0) + + +def test_band_structure_of_atom_groups_checks_the_atom_axis_against_the_group_count(): + with pytest.raises(ValueError) as error: + grouped_band_structure(np.zeros((N_K, N_BANDS, 1, N_ORBITALS, 3)), atom_groups=3) + + assert BAND_LAYOUT in str(error.value) + assert "(2, 3, 1|4, 3, *)" in str(error.value) + assert "3 atom groups" in str(error.value) diff --git a/tests/pyprocar/core/test_projection.py b/tests/pyprocar/core/test_projection.py index 9a04bc2c..5082d5d1 100644 --- a/tests/pyprocar/core/test_projection.py +++ b/tests/pyprocar/core/test_projection.py @@ -88,6 +88,9 @@ def test_build_property_rejects_disallowed_mode(): ) +@pytest.mark.guards_existing_behaviour( + reason="the labels are unchanged; the source only gains atom_groups and n_atoms" +) def test_build_property_selection_labels(): structure = Structure( atoms=["Sr", "V"], fractional_coordinates=[[0, 0, 0], [0.5, 0.5, 0.5]], lattice=np.eye(3) @@ -97,6 +100,8 @@ def test_build_property_selection_labels(): spin_projection_names=["Spin-up", "Spin-down"], orbital_names=["s", "p"], is_non_collinear=False, + atom_groups=None, + n_atoms=2, ) selection = selection_resolver(source).resolve(atoms=[1], orbitals=[0], spins=[1]) owner = _Owner(points=np.zeros((1, 3))) diff --git a/tests/pyprocar/io/abinit/test_dos.py b/tests/pyprocar/io/abinit/test_dos.py index 0100e264..8cad5fc0 100644 --- a/tests/pyprocar/io/abinit/test_dos.py +++ b/tests/pyprocar/io/abinit/test_dos.py @@ -5,6 +5,7 @@ from tests.pyprocar.io.abinit import ABINIT_DATA_DIR, CALC_TYPES from tests.utils import BaseTest +from tests.utils.user_warning import user_warning pytestmark = pytest.mark.data @@ -141,3 +142,41 @@ def test_dosplot_puts_abinit_fermi_at_zero(): plt.close(fig) assert energies.min() == pytest.approx(-88.9908960598) assert energies.max() == pytest.approx(90.6042531638) + + +NCL_DOS = ABINIT_DATA_DIR / "non-colinear" / "dos" +NCL_DOS_FILES = ("abinit.out", "abinito_DOS_TOTAL", "abinito_DOS_AT0001") + + +def test_non_magnetic_spinor_dos_has_total_and_zero_spin_channels(): + """abinit.in sets nspinor 2 and nspden 1, so the run carries no magnetization. + + The l = 0, 1, 2 columns (2 to 4) of abinito_DOS_AT0001 integrate to 21.833 + electrons by the trapezoid rule on the file's own energy grid. + """ + from pyprocar.io import get_parser + + dos = get_parser("abinit", NCL_DOS).dos + + assert dos is not None and dos.projected is not None + projected = dos.projected.to_array() + assert projected.shape == (9401, 4, 1, 9) + assert dos.is_non_collinear + assert np.trapezoid(projected[:, 0].sum(axis=(1, 2)), dos.energies) == pytest.approx( + 21.833, abs=0.005 + ) + assert np.all(projected[:, 1:] == 0.0) + + +def test_magnetic_spinor_dos_keeps_only_the_total_and_says_why(tmp_path): + for name in NCL_DOS_FILES: + (tmp_path / name).write_bytes((NCL_DOS / name).read_bytes()) + out = tmp_path / "abinit.out" + out.write_text(out.read_text().replace("nspden = 1", "nspden = 4")) + from pyprocar.io import get_parser + + with user_warning(__file__, match="hold no magnetization components"): + dos = get_parser("abinit", tmp_path).dos + + assert dos is not None and dos.projected is not None + assert dos.projected.to_array().shape == (9401, 1, 1, 9) diff --git a/tests/pyprocar/io/lobster/test_parser.py b/tests/pyprocar/io/lobster/test_parser.py index 6162e2a4..8561a852 100644 --- a/tests/pyprocar/io/lobster/test_parser.py +++ b/tests/pyprocar/io/lobster/test_parser.py @@ -27,3 +27,38 @@ def test_fatband_weights_land_on_their_spin_ion_and_orbital(tmp_path): assert projected[:, :, 0, fe, s] == pytest.approx(expected) projected[:, :, 0, fe, s] = 0.0 assert np.all(projected == 0.0) + + +PDOS_HEADER = " 10.0000 -10.0000 5 0.0000 1.0000" +PDOS_ENERGIES = (-10.0, -5.0, 0.0, 5.0, 10.0) +# s, p_y, p_z and p_x weights of each atom's block, the same on every energy +PDOS_WEIGHTS = {26: (0.1, 0.2, 0.3, 0.4), 8: (0.01, 0.02, 0.03, 0.04)} + + +def _write_projected_doscar(dirpath) -> None: + lines = DOSCAR_CONTENT.splitlines()[:6] + lines += [f" {e:9.4f} 1.0000 0.5000" for e in PDOS_ENERGIES] + for z, weights in PDOS_WEIGHTS.items(): + lines.append(f"{PDOS_HEADER}; Z= {z}; s p_y p_z p_x") + lines += [f" {e:9.4f} " + " ".join(f"{w:.4f}" for w in weights) for e in PDOS_ENERGIES] + (dirpath / "DOSCAR.lobster").write_text("\n".join(lines) + "\n") + + +def test_dosplot_parametric_colours_a_lobster_dos_by_every_atom(tmp_path): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + import pyprocar + + _write_projected_doscar(tmp_path) + + fig, ax = pyprocar.dosplot( + code="lobster", dirname=str(tmp_path), mode="parametric", orbitals=[1, 2, 3], show=False + ) + colours = np.asarray(ax.images[0].get_array()).ravel() + plt.close(fig) + + # p of both atoms over every projection: (0.9 + 0.09) / (1.0 + 0.1) + np.testing.assert_allclose(colours, [0.9] * 5) diff --git a/tests/pyprocar/io/qe/test_noncollinear_projections.py b/tests/pyprocar/io/qe/test_noncollinear_projections.py new file mode 100644 index 00000000..2bf07875 --- /dev/null +++ b/tests/pyprocar/io/qe/test_noncollinear_projections.py @@ -0,0 +1,185 @@ +"""QE non-collinear band structures come out as total, Sx, Sy and Sz per real (l, m) orbital. + +The atomic_proj.xml amplitudes below are written by hand from QE 7.2's own +definitions of the spinor states (upflib spinor.f90, sph_ind.f90 and the rot_ylm +matrix in init_us_1.f90), for four bands with a known spinor on one p shell: + + band 1: pz with spin along +x band 2: pz with spin along +y + band 3: px with spin down band 4: py with spin up + +Without spin-orbit coupling projwfc.x projects on |l m s_z> directly. +""" + +import math +from pathlib import Path + +import numpy as np +import pytest + +from pyprocar.io import get_parser +from tests.utils import DATA_DIR + +R6, R3, R2 = 1 / math.sqrt(6), 1 / math.sqrt(3), 1 / math.sqrt(2) + +# for the states j=1/2 (m_j=-1/2, 1/2) then j=3/2 (m_j=-3/2..3/2). +SOC_STATES = [ + "l=1 j=0.5 m_j=-0.5", + "l=1 j=0.5 m_j= 0.5", + "l=1 j=1.5 m_j=-1.5", + "l=1 j=1.5 m_j=-0.5", + "l=1 j=1.5 m_j= 0.5", + "l=1 j=1.5 m_j= 1.5", +] +SOC_WFC = [1, 1, 2, 2, 2, 2] +SOC_AMPLITUDES = [ + [-R6, R6, 0, R3, R3, 0], + [-1j * R6, R6, 0, 1j * R3, R3, 0], + [0, -R3, -R2, 0, R6, 0], + [-1j * R3, 0, 0, -1j * R6, 0, -1j * R2], +] + +# for (m=1 pz, m=2 px, m=3 py) spin up, then the same spin down. +NOSOC_STATES = [f"l=1 m= {m} s_z= {s_z}" for s_z in ("0.5", "-0.5") for m in (1, 2, 3)] +NOSOC_WFC = [1] * 6 +NOSOC_AMPLITUDES = [ + [R2, 0, 0, R2, 0, 0], + [R2, 0, 0, 1j * R2, 0, 0], + [0, 0, 0, 0, 1, 0], + [0, 0, 1, 0, 0, 0], +] + +# (band, orbital index in projwfc.x order s, pz, px, py) -> (total, Sx, Sy, Sz) +EXPECTED = { + (0, 1): [1.0, 1.0, 0.0, 0.0], + (1, 1): [1.0, 0.0, 1.0, 0.0], + (2, 2): [1.0, 0.0, 0.0, -1.0], + (3, 3): [1.0, 0.0, 0.0, 1.0], +} + +PW_XML = """ + + + + 55.8Fe.upf + + + + 0.0 0.0 0.0 + + + 5.0 0.0 0.0 + 0.0 5.0 0.0 + 0.0 0.0 5.0 + + + + + 1.0 0.0 0.0 + 0.0 1.0 0.0 + 0.0 0.0 1.0 + + + + true + 4 + 0.0 + 1 + + 0.0 0.0 0.0 + 100 + -0.2 -0.1 0.1 0.2 + 1.0 1.0 0.0 0.0 + + + + +""" + + +def projwfc_out(states: list[str], wfcs: list[int]) -> str: + lines = [ + f" state #{i:4d}: atom 1 (Fe ), wfc {wfc:2d} ({state})" + for i, (state, wfc) in enumerate(zip(states, wfcs, strict=True), start=1) + ] + return ( + "\n Program PROJWFC v.7.2 starts on 1Jan2026 at 12: 0: 0\n\n" + + " Atomic states used for projection\n\n" + + "\n".join(lines) + + "\n\n natomwfc = 6\n nbnd = 4\n nkstot = 1\n" + ) + + +def atomic_proj_xml(amplitudes: list[list[complex]]) -> str: + wfcs = "".join( + f' \n' + + "".join( + f" {complex(band[i]).real:.15f} {complex(band[i]).imag:.15f}\n" for band in amplitudes + ) + + " \n" + for i in range(6) + ) + return ( + "\n" + + '
\n' + + " \n" + + ' 0.0 0.0 0.0\n' + + " -0.2 -0.1 0.1 0.2\n" + + f" \n{wfcs} \n" + + " \n\n" + ) + + +@pytest.mark.parametrize( + ("states", "wfcs", "amplitudes"), + [ + pytest.param(SOC_STATES, SOC_WFC, SOC_AMPLITUDES, id="spin-orbit-j-basis"), + pytest.param(NOSOC_STATES, NOSOC_WFC, NOSOC_AMPLITUDES, id="no-spin-orbit-s_z-basis"), + ], +) +def test_spinor_projections_give_total_and_spin_per_real_orbital( + tmp_path: Path, states, wfcs, amplitudes +) -> None: + (tmp_path / "pw.xml").write_text(PW_XML) + (tmp_path / "kpdos.out").write_text(projwfc_out(states, wfcs)) + (tmp_path / "out" / "fe.save").mkdir(parents=True) + (tmp_path / "out" / "fe.save" / "atomic_proj.xml").write_text(atomic_proj_xml(amplitudes)) + + ebs = get_parser("qe", tmp_path).ebs + + assert ebs is not None and ebs.projected is not None + projected = ebs.projected.to_array() + assert projected.shape == (1, 4, 4, 1, 16) + expected = np.zeros((4, 4, 16)) + for (band, orbital), spin in EXPECTED.items(): + expected[band, :, orbital] = spin + np.testing.assert_allclose(projected[0, :, :, 0, :], expected, atol=1e-12) + assert ebs.orbital_names is not None and ebs.orbital_names[:4] == ["s", "pz", "px", "py"] + + +QE_NONCOLLINEAR_BANDS = DATA_DIR / "codes/qe/7.2/SrVO3/non-colinear/bands" +D_ORBITALS = ["dz2", "dxz", "dyz", "dx2-y2", "dxy"] + + +@pytest.mark.data +def test_qe_spin_orbit_band_structure_matches_projwfc_weights_at_gamma() -> None: + """kpdos.out of the same run prints each band's weights on the j states at Gamma. + + Band 41 (11.583 eV) is V 0.377 [#28] + 0.285 [#35] + 0.251 [#33] + 0.071 [#30], + all V d states, 0.984 in all. Band 47 (13.817 eV) is V 0.500 [#34] + 0.333 [#29] + and O s 0.079 [#54] (atom 5) + 0.020 [#38] + 0.020 [#46], |psi|^2 = 0.951. + Cubic SrVO3 puts the first in V t2g (dxz, dyz, dxy) and the second in V eg. + """ + ebs = get_parser("qe", QE_NONCOLLINEAR_BANDS).ebs + + assert ebs is not None and ebs.projected is not None + projected = ebs.projected.to_array() + assert projected.shape == (155, 50, 4, 5, 16) + assert ebs.orbital_names is not None and ebs.orbital_names[4:9] == D_ORBITALS + v_d = dict(zip(D_ORBITALS, projected[0, :, 0, 1, 4:9].T, strict=True)) + t2g = v_d["dxz"] + v_d["dyz"] + v_d["dxy"] + eg = v_d["dz2"] + v_d["dx2-y2"] + assert (t2g[40], eg[40]) == pytest.approx((0.984, 0.0), abs=2e-3) + assert (t2g[46], eg[46]) == pytest.approx((0.0, 0.833), abs=2e-3) + assert projected[0, 46, 0, 4, 0] == pytest.approx(0.079, abs=1e-3) + assert projected[0, 46, 0].sum() == pytest.approx(0.951, abs=2e-3) diff --git a/tests/pyprocar/io/test_orbital_names.py b/tests/pyprocar/io/test_orbital_names.py new file mode 100644 index 00000000..91af04ed --- /dev/null +++ b/tests/pyprocar/io/test_orbital_names.py @@ -0,0 +1,125 @@ +"""Every parser names the orbitals it projects, so check_projected_layout compares them. + +The expected names come from each code's own output for the same run: projwfc.x's +Lowdin charge labels, Abinit's PROCAR header and Elk's ELMIREP.OUT. +""" + +import re +from pathlib import Path + +import numpy as np +import pytest + +from pyprocar.io import get_parser +from pyprocar.io.vasp import Procar +from tests.pyprocar.io.lobster.test_doscar_lobster import DOSCAR_CONTENT +from tests.pyprocar.io.lobster.test_lobsterout import LOBSTEROUT_CONTENT +from tests.utils import DATA_DIR + +CODES = DATA_DIR / "codes" + +FILTERED_PROCAR = """PROCAR lm decomposed +# of k-points: 1 # of bands: 2 # of ions: 2 + + k-point 1 : 0.00000000 0.00000000 0.00000000 weight = 1.00000000 + +band 1 # energy -1.00000000 # occ. 1.00000000 + +ion o0 tot + 1 0.100 0.100 + 2 0.200 0.200 +tot 0.300 0.300 + +band 2 # energy 1.00000000 # occ. 0.00000000 + +ion o0 tot + 1 0.400 0.400 + 2 0.500 0.500 +tot 0.900 0.900 + +""" + + +def test_filtered_procar_keeps_the_column_name_its_header_gives() -> None: + procar = Procar.from_str(FILTERED_PROCAR) + + assert procar.orbital_names == ["o0"] + assert procar.projected is not None + assert procar.projected[0, :, 0, :, 0].tolist() == [[0.1, 0.2], [0.4, 0.5]] + + +@pytest.mark.data +def test_vasp_band_structure_of_a_filtered_procar_is_named_o0() -> None: + ebs = get_parser("vasp", DATA_DIR / "examples/bands/auto").ebs + + assert ebs is not None + assert ebs.orbital_names == ["o0"] + + +def lowdin_labels(projwfc_output: Path) -> list[str]: + """The s, then (l, m) labels projwfc.x prints for atom 1's Lowdin charges.""" + lines = [line for line in projwfc_output.read_text().splitlines() if "Atom # 1:" in line] + labels = [label for line in lines for label in re.findall(r"(\w[\w-]*)\s*=", line)] + return [label for label in labels if label not in {"charge", "p", "d", "f"}] + + +@pytest.mark.data +@pytest.mark.parametrize( + ("relpath", "member", "projwfc_output"), + [ + ("non-spin-polarized/bands", "ebs", "kpdos.out"), + ("non-spin-polarized/dos", "dos", "pdos.out"), + ], +) +def test_qe_names_its_orbitals_as_projwfc_labels_them(relpath, member, projwfc_output) -> None: + calc = CODES / "qe/7.2/SrVO3" / relpath + expected = lowdin_labels(calc / projwfc_output) + + names = getattr(get_parser("qe", calc), member).orbital_names + + assert expected == ["s", "pz", "px", "py", "dz2", "dxz", "dyz", "dx2-y2", "dxy"] + assert names[:9] == expected + + +@pytest.mark.data +def test_abinit_dos_names_its_orbitals_as_the_same_runs_procar_does() -> None: + calc = CODES / "abinit/9.6/Fe/non-spin-polarized/dos" + header = next(line for line in (calc / "PROCAR").open() if line.startswith("ion")) + + dos = get_parser("abinit", calc).dos + + assert dos is not None + assert dos.orbital_names == header.split()[1:-1] + + +@pytest.mark.data +def test_elk_dos_names_its_orbitals_by_the_l_m_slots_of_elmirep() -> None: + calc = CODES / "elk/6.3/SrVO3/non-spin-polarized/dos" + first_atom = (calc / "ELMIREP.OUT").read_text().split("\n \n")[0] + expected = [f"Y{ang}{m}" for ang, m in re.findall(r"l =\s*(\d+), m =\s*(-?\d+)", first_atom)] + + dos = get_parser("elk", calc).dos + + assert dos is not None + assert len(expected) == 16 + assert dos.orbital_names == expected + + +LOBSTER_PDOS_BLOCK = """ -10.0000 10.0000 5 0.0000 1.0000 ; Z= 26 ; s p_y p_z p_x + -10.0000 0.0100 0.0200 0.0300 0.0400 + -5.0000 0.0500 0.0600 0.0700 0.0800 + 0.0000 0.0900 0.1000 0.1100 0.1200 + 5.0000 0.1300 0.1400 0.1500 0.1600 + 10.0000 0.1700 0.1800 0.1900 0.2000 +""" + + +def test_lobster_dos_names_the_slot_each_orbital_column_fills(tmp_path: Path) -> None: + (tmp_path / "lobsterout").write_text(LOBSTEROUT_CONTENT) + (tmp_path / "DOSCAR.lobster").write_text(DOSCAR_CONTENT + LOBSTER_PDOS_BLOCK) + + dos = get_parser("lobster", tmp_path).dos + + assert dos is not None and dos.projected is not None and dos.orbital_names is not None + p_z = dos.projected.to_array()[:, 0, 0, dos.orbital_names.index("p_z")] + np.testing.assert_allclose(p_z, [0.03, 0.07, 0.11, 0.15, 0.19]) diff --git a/tests/pyprocar/scripts/test_filtered_procar.py b/tests/pyprocar/scripts/test_filtered_procar.py new file mode 100644 index 00000000..c7001b19 --- /dev/null +++ b/tests/pyprocar/scripts/test_filtered_procar.py @@ -0,0 +1,235 @@ +"""PROCARs written by pyprocar.filter load and plot through the one-call functions. + +Expected values come from the unfiltered PROCAR of the same run: a row of an +atom-filtered PROCAR is the sum of the rows of its group of atoms, and a column +of an orbital-filtered PROCAR is the sum of its group of orbital columns. +""" + +import shutil +from pathlib import Path +from typing import Any + +import matplotlib + +matplotlib.use("Agg") + +import matplotlib.pyplot as plt +import numpy as np +import pytest +from matplotlib.collections import LineCollection + +import pyprocar +from pyprocar.core import ElectronicBandStructure +from pyprocar.io import get_parser +from tests.utils import DATA_DIR + +pytestmark = pytest.mark.data + +CALC = DATA_DIR / "examples/bands/non-spin-polarized" +FERMI2D_CALC = DATA_DIR / "examples/fermi2d/non-spin-polarized" +FERMI = 5.3017 + + +@pytest.fixture(autouse=True) +def close_figures(): + yield + plt.close("all") + + +def _copy_calc(tmp_path: Path, src: Path = CALC, extra: tuple[str, ...] = ()) -> Path: + dst = tmp_path / "calc" + dst.mkdir() + for name in ("PROCAR", "OUTCAR", "POSCAR", "KPOINTS", *extra): + shutil.copy(src / name, dst / name) + return dst + + +def _filtered_calc( + tmp_path: Path, src: Path = CALC, extra: tuple[str, ...] = (), **selection +) -> Path: + calc = _copy_calc(tmp_path, src, extra) + pyprocar.filter(str(calc / "PROCAR"), str(calc / "PROCAR-filtered"), **selection) + (calc / "PROCAR-filtered").replace(calc / "PROCAR") + return calc + + +def _ebs(calc: Path) -> ElectronicBandStructure: + ebs = get_parser("vasp", calc).ebs + assert ebs is not None + return ebs + + +@pytest.fixture(scope="module") +def unfiltered() -> np.ndarray: + projected = _ebs(CALC).projected + assert projected is not None + return np.asarray(projected.value) + + +def _sum(ebs: ElectronicBandStructure, **selection) -> np.ndarray: + prop = ebs.compute_projected_sum(**selection) + return np.asarray(prop.value) + + +def test_atom_filtered_procar_plots_each_group_of_atoms( + tmp_path: Path, unfiltered: np.ndarray +) -> None: + calc = _filtered_calc(tmp_path, atoms=[[0], [1], [2, 3, 4]]) + + _, ax = pyprocar.bandsplot( + code="vasp", dirname=str(calc), mode="plain", fermi=FERMI, show=False + ) + assert len([line for line in ax.lines if len(line.get_xdata()) == 200]) == 20 + + _, ax = pyprocar.bandsplot( + code="vasp", dirname=str(calc), mode="parametric", fermi=FERMI, atoms=[2], show=False + ) + assert len([c for c in ax.collections if isinstance(c, LineCollection)]) == 20 + + ebs = _ebs(calc) + np.testing.assert_allclose( + _sum(ebs, atoms=[2])[..., 0], unfiltered[..., 0, 2:5, :].sum(axis=(-1, -2)), atol=1e-9 + ) + np.testing.assert_allclose( + _sum(ebs, orbitals=[4, 5, 6, 7, 8])[..., 0], + unfiltered[..., 0, :, 4:9].sum(axis=(-1, -2)), + atol=1e-9, + ) + + +def test_atom_filtered_procar_labels_a_group_by_its_row_not_a_poscar_species( + tmp_path: Path, +) -> None: + ebs = _ebs(_filtered_calc(tmp_path, atoms=[[0, 1], [2, 3, 4]])) + + prop = ebs.compute_projected_sum(atoms=[0], orbitals=[0]) + + assert prop.metadata["atom_label"] == "0" + assert prop.metadata["label_plain"] == ["0-(s)"] + + +def test_atom_filtered_procar_refuses_species_selections(tmp_path: Path) -> None: + calc = _filtered_calc(tmp_path, atoms=[[0, 1], [2, 3, 4]]) + + with pytest.raises(ValueError, match="filtered by atoms"): + pyprocar.bandsplot(code="vasp", dirname=str(calc), mode="overlay_species", show=False) + oxygen: Any = ["O"] + with pytest.raises(ValueError, match="filtered by atoms"): + pyprocar.bandsplot( + code="vasp", dirname=str(calc), mode="parametric", atoms=oxygen, show=False + ) + + +def test_orbital_filtered_procar_labels_each_column_by_its_header_name( + tmp_path: Path, unfiltered: np.ndarray +) -> None: + calc = _filtered_calc(tmp_path, orbitals=[[0], [1, 2, 3]]) + + _, ax = pyprocar.bandsplot( + code="vasp", dirname=str(calc), mode="parametric", atoms=[1], orbitals=[1], show=False + ) + assert len([c for c in ax.collections if isinstance(c, LineCollection)]) == 20 + + ebs = _ebs(calc) + s_column = ebs.compute_projected_sum(atoms=[1], orbitals=[0]) + p_column = ebs.compute_projected_sum(atoms=[1], orbitals=[1]) + + assert s_column.metadata["orbital_label"] == "o0" + assert p_column.metadata["orbital_label"] == "o1" + np.testing.assert_allclose( + np.asarray(p_column.value)[..., 0], unfiltered[..., 0, 1, 1:4].sum(axis=-1), atol=1e-9 + ) + + +@pytest.mark.parametrize("header_name", ["x2-y2", "dx2"]) +@pytest.mark.parametrize("selected", ["x2-y2", "dx2"]) +def test_selecting_one_orbital_by_name_raises_whichever_name_the_header_uses( + tmp_path: Path, header_name: str, selected: str +) -> None: + calc = _copy_calc(tmp_path) + procar = calc / "PROCAR" + procar.write_text(procar.read_text().replace("x2-y2", header_name)) + by_name: Any = [selected] + + with pytest.raises(ValueError, match=r"orbitals takes orbital indices or the shell names"): + pyprocar.bandsplot( + code="vasp", dirname=str(calc), mode="parametric", orbitals=by_name, show=False + ) + + +def test_a_shell_name_selects_the_columns_its_header_names(tmp_path: Path) -> None: + calc = _filtered_calc(tmp_path, orbitals=[[1], [2], [3]], orbital_names=["py", "pz", "px"]) + p_shell: Any = ["p"] + + def colors(orbitals) -> np.ndarray: + _, ax = pyprocar.bandsplot( + code="vasp", + dirname=str(calc), + mode="parametric", + atoms=[1], + orbitals=orbitals, + show=False, + ) + return np.concatenate( + [np.asarray(c.get_array()) for c in ax.collections if isinstance(c, LineCollection)] + ) + + np.testing.assert_array_equal(colors(p_shell), colors([0, 1, 2])) + + +def test_a_shell_name_selects_the_column_named_by_its_letter(tmp_path: Path) -> None: + calc = _filtered_calc( + tmp_path, orbitals=[[0], [1, 2, 3], [4, 5, 6, 7, 8]], orbital_names=["s", "p", "d"] + ) + d_shell: Any = ["d"] + + def colors(orbitals) -> np.ndarray: + _, ax = pyprocar.bandsplot( + code="vasp", + dirname=str(calc), + mode="parametric", + atoms=[1], + orbitals=orbitals, + show=False, + ) + return np.concatenate( + [np.asarray(c.get_array()) for c in ax.collections if isinstance(c, LineCollection)] + ) + + np.testing.assert_array_equal(colors(d_shell), colors([2])) + _, ax = pyprocar.bandsplot( + code="vasp", dirname=str(calc), mode="overlay_orbitals", atoms=[1], show=False + ) + legend = ax.get_legend() + assert legend is not None + assert [t.get_text() for t in legend.get_texts()] == ["s", "p", "d"] + + +def test_a_shell_name_raises_when_the_header_names_no_such_shell(tmp_path: Path) -> None: + calc = _filtered_calc(tmp_path, orbitals=[[0], [1, 2, 3]]) + p_shell: Any = ["p"] + + with pytest.raises(ValueError, match="hold no whole p shell"): + pyprocar.bandsplot( + code="vasp", dirname=str(calc), mode="parametric", orbitals=p_shell, show=False + ) + + +def test_part_of_a_shell_is_not_that_shell(tmp_path: Path) -> None: + calc = _filtered_calc(tmp_path, orbitals=[[0], [1], [2]], orbital_names=["s", "py", "pz"]) + p_shell: Any = ["p"] + + with pytest.raises(ValueError, match="hold no whole p shell"): + pyprocar.bandsplot( + code="vasp", dirname=str(calc), mode="parametric", orbitals=p_shell, show=False + ) + + +def test_fermi2d_refuses_to_unfold_an_atom_filtered_irreducible_procar(tmp_path: Path) -> None: + """A symmetry operation moves O atoms between rows the filtered file no longer names.""" + calc = _filtered_calc(tmp_path, FERMI2D_CALC, ("vasprun.xml", "IBZKPT"), atoms=[[2], [3, 4]]) + + with pytest.raises(ValueError, match="filtered by atoms"): + pyprocar.fermi2D( + code="vasp", dirname=str(calc), mode="plain", fermi=FERMI, k_z_plane=0.0, show=False + )