Source code for multipie.util.util_wannier

# SPDX-License-Identifier: MPL-2.0
# Copyright (C) 2021- The MultiPie developers
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

"""
Utility functions for reading Wannier90 files used by ModelAnalyzer.
"""

import numpy as np
from contextlib import contextmanager
from io import TextIOWrapper
from pathlib import Path
import gzip
import re
import warnings
import tarfile
import spglib
from multipie import Group
from multipie.util.util_crystal import convert_to_primitive_vector

BOHR2ANG = 0.529177249


# ==================================================
@contextmanager
def _open_text(path):
    """
    Open a plain, ``.gz``, or ``.tar.gz`` text file.
    """
    path = Path(path)

    if path.exists():
        with path.open("r", encoding="utf-8") as f:
            yield f
        return

    gz_path = Path(str(path) + ".gz")
    if gz_path.exists():
        with gzip.open(gz_path, "rt", encoding="utf-8") as f:
            yield f
        return

    tar_path = Path(str(path) + ".tar.gz")
    if tar_path.exists():
        with tarfile.open(tar_path, "r:gz") as tf:
            files = [member for member in tf.getmembers() if member.isfile()]
            exact = [member for member in files if Path(member.name).name == path.name]

            if exact:
                member = exact[0]
            elif len(files) == 1:
                member = files[0]
            else:
                raise FileNotFoundError(f"{path.name} is not found in {tar_path}")

            raw = tf.extractfile(member)
            if raw is None:
                raise FileNotFoundError(f"failed to read {member.name} in {tar_path}")

            with TextIOWrapper(raw, encoding="utf-8") as f:
                yield f
        return

    raise FileNotFoundError(f"failed to read file: {path}")


# ==================================================
def _read_lines(path):
    """
    Read a plain, ``.gz``, or ``.tar.gz`` text file as a list of lines.
    """
    with _open_text(path) as f:
        return f.read().splitlines()


# ==================================================
def _blocks(lines):
    """
    Return ``{block_name: lines_between_begin_and_end}``.
    """
    blocks = {}
    i = 0

    while i < len(lines):
        line = lines[i].strip().lower()
        if not line.startswith("begin "):
            i += 1
            continue

        name = line[6:].strip()
        end = f"end {name}"

        if name in blocks:
            raise ValueError(f"block '{name}' is defined more than once")

        for j in range(i + 1, len(lines)):
            if lines[j].strip().lower() == end:
                blocks[name] = lines[i + 1 : j]
                i = j + 1
                break
        else:
            raise ValueError(f"missing '{end}'")

    return blocks


# ==================================================
def _array(lines, dtype=float):
    """
    Read numerical rows and always return a two-dimensional array.
    """
    return np.atleast_2d(np.loadtxt(lines, dtype=dtype))


# ==================================================
def _convert_w90_orbital(l, m, r, s):
    """
    Convert a Wannier90 projection label to a MultiPie orbital label.

    Args:
        l (int): Angular-momentum index.
        m (int): Wannier90 angular-function index.
        r (int): Wannier90 radial-function index.
        s (int): Spin component: ``1`` for up, ``-1`` for down, and ``0``
                 for a non-spinor projection.

    Returns:
        - (str) -- MultiPie orbital label, such as ``s``, ``px``, ``du``, ``(px,u)``, or ``(px,d)``.

    Notes:
        - The radial index ``r`` is currently not encoded in the returned MultiPie orbital label, but it is retained in the argument list for consistency with the Wannier90 projection format.
    """
    orbitals = {
        0: {1: (0, "s")},
        1: {1: (2, "pz"), 2: (0, "px"), 3: (1, "py")},
        2: {1: (4, "du"), 2: (2, "dxz"), 3: (3, "dyz"), 4: (0, "dv"), 5: (1, "dxy")},
        3: {
            1: (6, "faz"),
            2: (4, "fx"),
            3: (5, "fy"),
            4: (2, "fbz"),
            5: (3, "f3"),
            6: (0, "fc"),
            7: (1, "fs"),
        },
    }

    try:
        orbital = orbitals[l][m]
    except KeyError as exc:
        raise ValueError(f"invalid orbital projection: l={l}, m={m}, r={r}, s={s}") from exc

    if s == 1:
        return orbital[0], f"({orbital[1]},u)"
    if s == -1:
        return orbital[0], f"({orbital[1]},d)"
    if s == 0:
        return orbital

    raise ValueError(f"invalid spin component: s={s}")


# ==================================================
def _projection_data(rows, spinors):
    """
    Read Wannier projection metadata from an ``nnkp`` projection block.
    """
    num_wann = int(rows[0])
    step = 3 if spinors else 2

    if len(rows) < 1 + step * num_wann:
        raise ValueError("incomplete projection block")

    projections = [rows[1 + step * iw] for iw in range(num_wann)]
    orbital = np.zeros((num_wann, 3), dtype=int)
    spin = np.zeros(num_wann, dtype=int)
    spin_axis = np.zeros((num_wann, 3), dtype=float)

    for iw, row in enumerate(projections):
        values = row.split()
        if len(values) < 6:
            raise ValueError(f"invalid projection entry: {row}")

        # Columns 4--6 contain l, m, and the radial-function index.
        orbital[iw] = values[3:6]

        if spinors:
            values = rows[1 + step * iw + 2].split()
            if len(values) < 4:
                raise ValueError("invalid spinor projection entry")
            spin[iw] = int(values[0])
            spin_axis[iw] = values[1:4]

    # Wannier90 uses fixed-width projection strings.  These slices retain the
    # original convention for identifying orbital specifications and centers.
    orb_key = [row[:40] for row in projections]
    pos_key = [row[:35] for row in projections]
    orb_unique = list(dict.fromkeys(orb_key))
    pos_unique = list(dict.fromkeys(pos_key))

    atom_orb = [[iw for iw, value in enumerate(orb_key) if value == key] for key in orb_unique]
    atom_pos = [[iorb for iorb, value in enumerate(orb_unique) if key in value] for key in pos_unique]
    atom_pos_r = [[float(x) for x in key.split()[:3]] for key in pos_unique]

    # Map each Wannier function to its zero-based projection-center index.
    nw2n = np.zeros(num_wann, dtype=int)
    for ia, positions in enumerate(atom_pos):
        for ipos in positions:
            nw2n[atom_orb[ipos]] = ia

    return {
        "num_wann": num_wann,
        "num_atom": len(atom_pos_r),
        "nw2n": nw2n.tolist(),
        "nw2l": orbital[:, 0].tolist(),
        "nw2m": orbital[:, 1].tolist(),
        "nw2r": orbital[:, 2].tolist(),
        "nw2s": spin.tolist(),
        "nw2saxis": spin_axis.tolist(),
        "atom_orb": atom_orb,
        "atom_pos": atom_pos,
        "atom_pos_r": atom_pos_r,
    }


# ==================================================
[docs] def read_win(seedname, topdir=None): """ Read ``seedname.win``. Args: seedname (str): Wannier90 seedname. topdir (str, optional): directory containing ``seedname.win``. Returns: - (dict) -- info. dict. - num_k : Number of k points inferred from ``mp_grid`` (int). - num_bands : Number of Bloch bands passed to Wannier90 (int). - num_wann : Number of Wannier functions (int). - spinors : Whether the Wannier functions are spinors (bool). - fermi_energy: Fermi energy in eV (float). - A : Real lattice vectors ``[a1,a2,a3]`` in angstrom, shape ``[3][3]`` (list). - atoms_frac : Atomic positions in fractional coordinates, ``{(symbol, occurrence): [r1,r2,r3]}`` (dict). - atoms_cart : Atomic positions in Cartesian coordinates in angstrom, ``{(symbol, occurrence): [x,y,z]}`` (dict). - mp_grid : Monkhorst-Pack grid ``[nk1,nk2,nk3]`` (list). - kpoints : Explicit k points in crystal coordinates, reduced to ``0 <= k_i < 1``, shape ``[num_k][3]`` (list). Notes: - If only one of ``atoms_frac`` and ``atoms_cart`` is present, the other is calculated using ``A``. - Cartesian lengths are returned in angstrom. """ if topdir is None: topdir = "." lines = _read_lines(Path(topdir) / f"{seedname}.win") blocks = _blocks(lines) def param(name, default, cast): """Read a scalar ``name = value`` or ``name : value`` parameter.""" pattern = re.compile(rf"^\s*{re.escape(name)}\s*[=:]\s*([^!]*)", re.IGNORECASE) values = [match.group(1).strip() for line in lines if (match := pattern.match(line))] if len(values) > 1: raise ValueError(f"{name} is defined more than once") if not values: return default value = values[0] if cast is bool: value = value.lower() if value in ("true", ".true."): return True if value in ("false", ".false."): return False raise ValueError(f"invalid boolean value for {name}: {values[0]}") return cast(value) def vectors(name): """Read a three-vector block and convert bohr to angstrom.""" rows = blocks.get(name) if not rows: return None unit = rows[0].strip().lower() start = int(unit in ("ang", "bohr")) scale = BOHR2ANG if unit == "bohr" else 1.0 data = _array([row for row in rows[start:] if row.strip()]) * scale if data.shape != (3, 3): raise ValueError(f"{name} must contain three three-dimensional vectors") return data def atoms(name): """Read an atoms block as ``{(symbol, occurrence): position}``.""" rows = blocks.get(name) if not rows: return None unit = rows[0].strip().lower() start = int(unit in ("ang", "bohr")) scale = BOHR2ANG if unit == "bohr" else 1.0 count, out = {}, {} for row in rows[start:]: if not row.strip(): continue values = row.split() if len(values) != 4: raise ValueError(f"invalid entry in {name}: {row}") symbol, *xyz = values count[symbol] = count.get(symbol, 0) + 1 out[symbol, count[symbol]] = (np.asarray(xyz, dtype=float) * scale).tolist() return out # --- scalar parameters --- mp_grid = [int(x) for x in param("mp_grid", "1 1 1", str).split()] if len(mp_grid) != 3: raise ValueError("mp_grid must contain three integers") # --- lattice vectors and atomic positions --- A = vectors("unit_cell_cart") atoms_frac = atoms("atoms_frac") atoms_cart = atoms("atoms_cart") if A is not None: if atoms_cart is not None and atoms_frac is None: atoms_frac = {key: (np.asarray(pos) @ np.linalg.inv(A)).tolist() for key, pos in atoms_cart.items()} elif atoms_frac is not None and atoms_cart is None: atoms_cart = {key: (np.asarray(pos) @ A).tolist() for key, pos in atoms_frac.items()} d = { "num_k": int(np.prod(mp_grid)), "num_bands": param("num_bands", 0, int), "num_wann": param("num_wann", 0, int), "spinors": param("spinors", False, bool), "fermi_energy": param("fermi_energy", 0.0, float), "A": None if A is None else A.tolist(), "atoms_frac": atoms_frac, "atoms_cart": atoms_cart, "mp_grid": mp_grid, "kpoints": [[0.0, 0.0, 0.0]], } # --- explicit k points --- if rows := blocks.get("kpoints"): kpoints = np.mod(_array([row for row in rows if row.strip()])[:, :3], 1) if len(kpoints) != d["num_k"]: raise ValueError( f"inconsistent number of k points in {seedname}.win: " f"mp_grid gives {d['num_k']}, but the kpoints block contains {len(kpoints)}" ) d["kpoints"] = kpoints.tolist() return d
# ==================================================
[docs] def read_nnkp(seedname, topdir=None): """ Read ``seedname.nnkp`` generated by Wannier90. Args: seedname (str): Wannier90 seedname. topdir (str, optional): directory containing ``seedname.nnkp``. Returns: - (dict) -- info. dict. - A : Real lattice vectors ``[a1,a2,a3]`` in Cartesian coordinates, shape ``[3][3]`` (list). - B : Reciprocal lattice vectors ``[b1,b2,b3]`` in Cartesian coordinates, shape ``[3][3]`` (list). - num_k : Number of k points (int). - num_wann : Number of Wannier projections (int). - num_atom : Number of distinct projection centers (int). - num_b : Number of b-vectors per k point (int). - kpoints : k points in crystal coordinates, reduced to ``0 <= k_i < 1``, shape ``[num_k][3]`` (list). - nnkpts : Nearest-neighbour table ``[ik,ikb,G1,G2,G3]``, shape ``[num_k][num_b][5]`` (list). - nw2n : Zero-based projection-center index of each Wannier function, shape ``[num_wann]`` (list). - nw2l, nw2m : Angular indices ``l`` and ``m`` of each projection, shape ``[num_wann]`` (list). - nw2r : Radial-function index of each projection, shape ``[num_wann]`` (list). - nw2s : Spin component of each projection; zero for non-spinor projections (list). - nw2saxis : Spin-quantization axis of each projection, shape ``[num_wann][3]`` (list). - atom_orb : Wannier-function indices grouped by orbital projection (list). - atom_pos : Orbital-projection indices grouped by projection center (list). - atom_pos_r : Projection-center positions in fractional coordinates, shape ``[num_atom][3]`` (list). - bvec_cart : b-vectors at Gamma in Cartesian reciprocal coordinates, shape ``[num_b][3]`` (list). - bvec_crys : The same b-vectors in crystal coordinates, shape ``[num_b][3]`` (list). - wb : Finite-difference weights of ``bvec_cart``, shape ``[num_b]`` (list). - bveck : Cartesian b-vector for each ``(k,b)`` pair, shape ``[num_k][num_b][3]`` (list). - wk : Finite-difference weight for each ``(k,b)`` pair, shape ``[num_k][num_b]`` (list). - kb2k : Zero-based index of ``k+b`` for each pair, shape ``[num_k][num_b]`` (list). Notes: - ``num_atom`` and ``atom_pos_r`` describe Wannier projection centers, which need not coincide with the physical atoms in ``seedname.win``. - For ``auto_projections``, only ``num_wann`` is available; the detailed projection entries are returned as ``None``. """ if topdir is None: topdir = "." blocks = _blocks(_read_lines(Path(topdir) / f"{seedname}.nnkp")) required = ("real_lattice", "recip_lattice", "kpoints", "nnkpts") missing = [name for name in required if name not in blocks] if missing: raise ValueError(f"missing blocks in {seedname}.nnkp: {', '.join(missing)}") # --- lattice vectors --- A = _array(blocks["real_lattice"]) B = _array(blocks["recip_lattice"]) if A.shape != (3, 3) or B.shape != (3, 3): raise ValueError("real_lattice and recip_lattice must have shape [3][3]") # --- k points --- rows = blocks["kpoints"] num_k = int(rows[0]) kpoints_wo_shift = _array(rows[1 : 1 + num_k]) if len(kpoints_wo_shift) != num_k: raise ValueError("invalid number of k points") kpoints = np.mod(kpoints_wo_shift, 1) # --- nearest-neighbour k points --- rows = blocks["nnkpts"] num_b = int(rows[0]) nnkpts = _array(rows[1 : 1 + num_k * num_b], dtype=int) if len(nnkpts) != num_k * num_b: raise ValueError("invalid number of nearest-neighbour k-point entries") nnkpts = nnkpts.reshape(num_k, num_b, 5) d = { "A": A.tolist(), "B": B.tolist(), "num_k": num_k, "num_wann": 0, "num_atom": 0, "num_b": num_b, "kpoints": kpoints.tolist(), "nnkpts": nnkpts.tolist(), "nw2n": None, "nw2l": None, "nw2m": None, "nw2r": None, "nw2s": None, "nw2saxis": None, "atom_orb": None, "atom_pos": None, "atom_pos_r": None, "bvec_cart": None, "bvec_crys": None, "wb": None, "bveck": None, "wk": None, "kb2k": None, } # --- projection information --- projection_block = "spinor_projections" if "spinor_projections" in blocks else "projections" projection_rows = blocks.get(projection_block) if projection_rows and int(projection_rows[0]) > 0: d.update( _projection_data( projection_rows, spinors=projection_block.startswith("spinor"), ) ) elif "auto_projections" in blocks: # With automatic projections, nnkp stores num_wann but does not store # the per-Wannier projection metadata listed above. d["num_wann"] = int(blocks["auto_projections"][0]) else: raise ValueError(f"projection information is missing in {seedname}.nnkp") # b = k_ikb + G - k_ik in crystal coordinates, followed by conversion to # Cartesian reciprocal coordinates using the row-vector convention. b_crys = kpoints_wo_shift[nnkpts[..., 1] - 1] + nnkpts[..., 2:5] - kpoints_wo_shift[nnkpts[..., 0] - 1] bveck = b_crys @ B # Wannier90 finite-difference shells are identified using the Gamma point. gamma = np.flatnonzero(np.all(np.isclose(kpoints_wo_shift, 0), axis=1)) if not len(gamma): raise ValueError("Gamma point must be included") bvec_cart = bveck[gamma[0]] bvec_crys = bvec_cart @ A.T / (2 * np.pi) # Solve sum_b w_b b_a b_c = delta_ac using the pseudoinverse. bbmat = np.einsum("bi,bj->bij", bvec_cart, bvec_cart).reshape(num_b, 9) wb = np.eye(3).ravel() @ np.linalg.pinv(bbmat) # Assign the corresponding Gamma-shell weight to every (k,b) pair. match = np.isclose( bveck[..., None, :], bvec_cart[None, None, ...], rtol=1e-5, atol=1e-5, ).all(axis=-1) if not match.any(axis=-1).all(): raise ValueError("unknown b-vector") d.update( bvec_cart=bvec_cart.tolist(), bvec_crys=bvec_crys.tolist(), wb=wb.tolist(), bveck=bveck.tolist(), wk=wb[match.argmax(axis=-1)].tolist(), kb2k=(nnkpts[..., 1] - 1).tolist(), ) return d
# ==================================================
[docs] def merge_wannier_info(win, nnkp, seedname): """ Check duplicated entries in ``win`` and ``nnkp``, then merge them. Args: win (dict): Information returned by :func:`read_win`. nnkp (dict): Information returned by :func:`read_nnkp`. seedname (str): Wannier90 seedname used in error messages. Returns: - (dict) -- Merged Wannier90 information. Every key present in both input dictionaries is checked for consistency, and the value from ``win`` is retained for the duplicated key. With the current readers, the duplicated entries are ``A``, ``num_k``, ``num_wann``, and ``kpoints``. """ common_keys = win.keys() & nnkp.keys() for key in sorted(common_keys): value_win = win[key] value_nnkp = nnkp[key] if isinstance(value_win, (list, tuple, np.ndarray)) or isinstance(value_nnkp, (list, tuple, np.ndarray)): a = np.asarray(value_win) b = np.asarray(value_nnkp) if a.shape != b.shape: raise ValueError( f"inconsistent {key} between {seedname}.win and " f"{seedname}.nnkp: shape {a.shape} != {b.shape}" ) if np.issubdtype(a.dtype, np.number) and np.issubdtype(b.dtype, np.number): same = np.allclose(a, b, rtol=1e-7, atol=1e-8) detail = f"maximum difference = {np.max(np.abs(a - b)):.3e}" else: same = np.array_equal(a, b) detail = "values differ" else: same = value_win == value_nnkp detail = f"win={value_win!r}, nnkp={value_nnkp!r}" if not same: raise ValueError(f"inconsistent {key} between {seedname}.win and " f"{seedname}.nnkp: {detail}") # Duplicated entries have already been checked; retain the win values. return win | {key: value for key, value in nnkp.items() if key not in common_keys}
# ==================================================
[docs] def matrix_dict_r(Or, rpoints, diagonal=False): """ dictionary form of an arbitrary operator matrix in real-space representation. Args: Or (ndarray): real-space representation of the given operator, O_{ab}(R) = <φ_{a}(0)|O|φ_{b}(R)>. rpoints (ndarray): lattice points (crystal coordinate, [[n1,n2,n3]], nj: integer). diagonal (bool, optional): diagonal matrix ? Returns: - (dict) -- real-space representation of the given operator, {(n2,n2,n3,a,b) = O_{ab}(R)}. """ # number of pseudo atomic orbitals dim_r = len(Or[0]) if not diagonal: dim_c = len(Or[0][0]) Or_dict = {} r_list = [[r, round(n1), round(n2), round(n3)] for r, (n1, n2, n3) in enumerate(rpoints)] if diagonal: Or_dict = {(n1, n2, n3, a, a): Or[r][a] for r, n1, n2, n3 in r_list for a in range(dim_r)} else: Or_dict = {(n1, n2, n3, a, b): Or[r][a][b] for r, n1, n2, n3 in r_list for a in range(dim_r) for b in range(dim_c)} return Or_dict
# ==================================================
[docs] def read_hr(hr_file, topdir=None): """ Read ``seedname_hr.dat`` generated by Wannier90. Args: hr_file (str): Wannier90 Hamiltonian file. topdir (str, optional): directory containing ``seedname_hr.dat``. Returns: - (dict) -- info. dict. - HH_R : Real-space Hamiltonian matrices ``H_mn(R)`` in eV, shape ``[num_R][num_wann][num_wann]`` (ndarray). - irvec : Lattice vectors ``R = n1*a1 + n2*a2 + n3*a3`` in crystal coordinates, shape ``[num_R][3]`` (ndarray). - ndegen : Wigner-Seitz degeneracy of each ``R`` vector, shape ``[num_R]`` (ndarray). Notes: - Wannier indices in the file are one-based and are converted to zero-based array indices. ``ndegen`` is the denominator used in the Wannier90 Fourier interpolation over ``R`` vectors. The file is read sequentially to avoid storing the full text representation in memory. """ if topdir is None: topdir = "." def next_nonempty(f): """Return the next non-empty line or raise a format error.""" for line in f: if line.strip(): return line raise ValueError(f"unexpected end of {hr_file}") with _open_text(Path(topdir) / f"{hr_file}") as f: # The first line is a comment written by Wannier90. try: next(f) except StopIteration as exc: raise ValueError(f"invalid hr file: {hr_file}") from exc num_wann = int(next_nonempty(f)) num_R = int(next_nonempty(f)) if num_wann <= 0 or num_R <= 0: raise ValueError("num_wann and num_R must be positive") # Degeneracies are normally written with at most 15 integers per line. ndegen = [] while len(ndegen) < num_R: ndegen.extend(map(int, next_nonempty(f).split())) if len(ndegen) != num_R or any(value <= 0 for value in ndegen): raise ValueError(f"invalid degeneracies in {hr_file}") ndegen = np.asarray(ndegen, dtype=int) irvec = np.empty((num_R, 3), dtype=int) HH_R = np.zeros((num_R, num_wann, num_wann), dtype=complex) r_index = {} # Each R block contains num_wann**2 Hamiltonian matrix elements. for iR in range(num_R): R_block = None assigned = np.zeros((num_wann, num_wann), dtype=bool) for _ in range(num_wann * num_wann): values = next_nonempty(f).split() if len(values) != 7: raise ValueError(f"invalid Hamiltonian entry: {' '.join(values)}") n1, n2, n3, m, n = map(int, values[:5]) R = (n1, n2, n3) if R_block is None: R_block = R elif R != R_block: raise ValueError(f"inconsistent R vectors within block {iR}") if not (1 <= m <= num_wann and 1 <= n <= num_wann): raise ValueError(f"invalid Wannier indices m={m}, n={n}") if assigned[m - 1, n - 1]: raise ValueError(f"duplicated Hamiltonian entry for R={R}, m={m}, n={n}") assigned[m - 1, n - 1] = True HH_R[iR, m - 1, n - 1] = float(values[5]) + 1j * float(values[6]) if not assigned.all(): raise ValueError(f"incomplete Hamiltonian block for R={R_block}") if R_block in r_index: raise ValueError(f"duplicated R vector: {R_block}") irvec[iR] = R_block r_index[R_block] = iR # No additional non-empty Hamiltonian rows should remain. if any(line.strip() for line in f): raise ValueError(f"too many Hamiltonian entries in {hr_file}") # Check H(R) = H(-R)^dagger. for iR, R in enumerate(map(tuple, irvec)): minus_R = tuple(-np.asarray(R)) if minus_R not in r_index: raise ValueError(f"missing -R vector for R={R}") jR = r_index[minus_R] if not np.allclose(HH_R[iR], HH_R[jR].conj().T, rtol=1e-8, atol=1e-8): diff = np.max(np.abs(HH_R[iR] - HH_R[jR].conj().T)) raise ValueError(f"Hermiticity is violated for R={R}: maximum difference = {diff:.3e}") hr_dict = matrix_dict_r(HH_R, irvec) return hr_dict, irvec, ndegen
# ==================================================
[docs] def read_wsvec(seedname, topdir=None): """ Read ``seedname_wsvec.dat`` generated by Wannier90. Args: seedname (str): seedname. topdir (str, optional): directory containing ``seedname_wsvec.dat``. Returns: - (dict) -- lattice translations T of the shortest images of each element, dict[(n1,n2,n3,a,b), [(T1,T2,T3)]], or None if the file does not exist. Notes: - Wannier indices in the file are one-based and are converted to zero-based indices. - H_ab(R) contributes to H_ab(k) as sum_T H_ab(R) exp(ik.(R+T)) / (ndegen(R) nT). """ if topdir is None: topdir = "." path = Path(topdir) / f"{seedname}_wsvec.dat" if not any(Path(str(path) + ext).exists() for ext in ["", ".gz", ".tar.gz"]): return None wsvec = {} with _open_text(path) as f: # read entries one by one from the stream (the file has an entry for each R and pair of Wannier functions). rows = (line.split() for line in f if line.strip() and not line.lstrip().startswith("#")) try: for row in rows: n1, n2, n3, a, b = map(int, row) nT = int(next(rows)[0]) if nT <= 0: raise ValueError T = [] for _ in range(nT): t1, t2, t3 = map(int, next(rows)) T.append((t1, t2, t3)) key = (n1, n2, n3, a - 1, b - 1) if key in wsvec: raise ValueError wsvec[key] = T except (ValueError, IndexError, StopIteration): raise ValueError(f"invalid format in {seedname}_wsvec.dat (near entry {len(wsvec) + 1}).") from None return wsvec
# ==================================================
[docs] def apply_ws_degeneracy(hr_dict, irvec, ndegen, wsvec=None): """ Convert H(R) in "hr.dat" into real-space hoppings, using the Wigner-Seitz degeneracies. Args: hr_dict (dict): H(R) read by :func:`read_hr`, dict[(n1,n2,n3,a,b), value]. irvec (ndarray): R vectors, [num_R][3]. ndegen (ndarray): Wigner-Seitz degeneracy of each R, [num_R]. wsvec (dict, optional): shortest image translations read by :func:`read_wsvec`. Returns: - (dict) -- real-space hoppings, dict[(n1,n2,n3,a,b), value]. Note: - Wannier90 gives H(k) = sum_R H(R) exp(ik.R) / ndegen(R), where H(R) of the equivalent images on the boundary of the Wigner-Seitz supercell is written with the full value. The hopping at each image is H(R)/ndegen(R). - with use_ws_distance (wsvec), H_ab(R) is further distributed over R+T with the weight 1/nT. """ degen = {tuple(int(i) for i in R): int(n) for R, n in zip(irvec, ndegen)} HR = {} for (n1, n2, n3, a, b), v in hr_dict.items(): v = v / degen[(n1, n2, n3)] if wsvec is None: T = [(0, 0, 0)] else: T = wsvec.get((n1, n2, n3, a, b)) if T is None: raise ValueError(f"no entry for R=({n1},{n2},{n3}), a={a+1}, b={b+1} in wsvec.") for t1, t2, t3 in T: key = (n1 + t1, n2 + t2, n3 + t3, a, b) HR[key] = HR.get(key, 0) + v / len(T) # check H_ab(R) = H_ba(-R)^*. for (n1, n2, n3, a, b), v in HR.items(): diff = abs(v - np.conj(HR.get((-n1, -n2, -n3, b, a), 0))) if diff > 1e-8 + 1e-8 * abs(v): raise ValueError( f"Hermiticity is violated for R=({n1},{n2},{n3}), a={a+1}, b={b+1} after applying ndegen/wsvec: difference = {diff:.3e}" ) return HR
# ==================================================
[docs] def build_ket_wannier(nnkp, site_dict, rtol=1e-4, atol=1e-4): """ Construct the MultiPie ket basis from Wannier90 projection information. Args: nnkp (dict): Information returned by :func:`read_nnkp`. site_dict (dict): MultiPie sites in the form ``{(name, sublattice): fractional_position}``. rtol (float, optional): Relative tolerance for comparing fractional positions. atol (float, optional): Absolute tolerance for comparing fractional positions. Returns: - (list) -- Wannier ket basis with one entry per Wannier function. Each entry has the form ``[name, sublattice, l, orbital]``. Notes: - Fractional positions are compared modulo lattice translations, so coordinates differing by an integer lattice vector are treated as the same site. """ keys = ("nw2n", "nw2l", "nw2m", "nw2r", "nw2s", "atom_pos_r") missing = [key for key in keys if nnkp.get(key) is None] if missing: raise ValueError( "ket_wannier cannot be constructed because detailed projection " f"information is unavailable: {', '.join(missing)}" ) arrays = [nnkp[key] for key in ("nw2n", "nw2l", "nw2m", "nw2r", "nw2s")] lengths = {len(values) for values in arrays} if lengths != {nnkp["num_wann"]}: raise ValueError("inconsistent number of Wannier projection entries") site_items = [((name, sublattice), np.asarray(position, dtype=float)) for (name, sublattice), position in site_dict.items()] ket_wannier = [] for iw, (pos_idx, l, m, r, s) in enumerate(zip(*arrays)): if not 0 <= pos_idx < len(nnkp["atom_pos_r"]): raise ValueError(f"invalid projection-center index for Wannier function {iw}: {pos_idx}") position = np.asarray(nnkp["atom_pos_r"][pos_idx], dtype=float) matches = [] for site, site_position in site_items: delta = position - site_position delta -= np.rint(delta) if np.allclose(delta, 0.0, rtol=rtol, atol=atol): matches.append(site) if len(matches) == 0: raise ValueError(f"no MultiPie site matches Wannier projection center {position.tolist()}") if len(matches) > 1: raise ValueError(f"multiple MultiPie sites match Wannier projection center " f"{position.tolist()}: {matches}") name, sublattice = matches[0] comp, orbital = _convert_w90_orbital(l, m, r, s) ket_wannier.append([name, sublattice, l, comp, orbital]) return ket_wannier
# ==================================================
[docs] def sort_ket_matrix(Ok, ket1, ket2): """ Sort ket to align with the MultiPie definition (ket2). Args: Ok (ndarray): arbitrary operator in k-space representation, O_{ab}(k) = <φ_{a}(k)|H|φ_{b}(k)>. ket1 (list): ket basis list, [[atom name, sublattice, rank, orbital]] ket2 (list): ket basis list, orbital@site. Returns: - (ndarray) -- operator. """ idx_list = [ket1.index(o) for o in ket2] Ok = Ok[:, idx_list, :] Ok = Ok[:, :, idx_list] return Ok
# ==================================================
[docs] def sort_ket_matrix_dict(Or_dict, ket1, ket2): """ Sort ket to align with the MultiPie definition (ket2). Args: Or_dict (dict): dictionary form of an arbitrary operator matrix in reak-space/k-space representation. ket1 (list): ket basis list, [[atom name, sublattice, rank, orbital]] ket2 (list): ket basis list, orbital@site. Returns: - (dict) -- dictionary form of an arbitrary operator matrix. """ idx_list = [ket2.index(o) for o in ket1] Or_dict = {(n1, n2, n3, idx_list[a], idx_list[b]): complex(v) for (n1, n2, n3, a, b), v in Or_dict.items()} return Or_dict
# ==================================================
[docs] def sort_ket_list(lst, ket1, ket2): """ Sort ket to align with the MultiPie definition (ket2). Args: lst (list): arbitrary list that has the same dimensions as the ket. ket1 (list): ket basis list, [[atom name, sublattice, rank, orbital]] ket2 (list): ket basis list, orbital@site. Returns: - (list) -- arbitrary list that has the same dimensions as the ket. """ idx_list = [ket1.index(o) for o in ket2] lst = np.array(lst) if lst.ndim == 1: lst = list(np.array(lst)[idx_list]) elif lst.ndim == 2: lst = list(np.array(lst)[idx_list, :]) elif lst.ndim == 3: lst = list(np.array(lst)[idx_list, :, :]) else: raise ValueError(f"invalid dimension of lst = {lst.ndim} was given.") return list(lst)
# ==================================================
[docs] def decompose_operator_by_SAMB(Or_dict, Zr_dict, digit=15): """ Decompose arbitrary operator into linear combination of SAMBs. Args: Or_dict (dict): dictionary form of an arbitrary operator matrix in real-space/k-space representation. Zr_dict (dict): dictionary form of SAMBs. digit (int, optional): round digit for Zr_dict. Returns: - (dict) -- parameter set, dict[zj, coeff]. """ def _round(v): c_val = complex(v) return round(c_val.real, digit) + round(c_val.imag, digit) * 1j z = { zj: float( np.real( np.sum([_round(v) * Or_dict.get((-k[0], -k[1], -k[2], k[4], k[3]), (0, None))[0] for k, (v, b_no) in d.items()]) ) ) for zj, d in Zr_dict.items() } return z
# ==================================================
[docs] def read_umat(seedname, topdir=None): """ Read ``seedname_u.mat``, ``seedname_u_dis.mat``. Not implemented yet. """ pass
# ==================================================
[docs] def read_eig(seedname, topdir=None): """ Read ``seedname.eig``. Not implemented yet. """ pass
# ==================================================
[docs] def read_mmn(seedname, topdir=None): """ Read ``seedname.mmn``. Not implemented yet. """ pass
# ==================================================
[docs] def read_spn(seedname, topdir=None): """ Read ``seedname.spn``. Not implemented yet. """ pass
# ==================================================
[docs] def read_uHu(seedname, topdir=None): """ Read ``seedname.uHu``. Not implemented yet. """ pass
# ==================================================
[docs] def read_uIu(seedname, topdir=None): """ Read ``seedname.uIu``. Not implemented yet. """ pass
# ================================================== # ================================================== SYMPREC = 1e-4 # ==================================================
[docs] def find_sg(A, atoms_frac, symprec=SYMPREC): """ Find space group via spglib. Args: A (ndarray): lattice vector, [a1,a2,a3]. (conventional, standard setting). atoms_frac (dict): atoms_frac in "win". symprec (float, optional): precision for spglib. Returns: - (int) -- space group no. """ dataset = _symmetry_dataset(A, atoms_frac, symprec) if dataset: return dataset.number else: return None
# ================================================== def _symmetry_dataset(A, atoms_frac, symprec=SYMPREC): """ Get spglib symmetry dataset of the structure in "win". """ positions = list(atoms_frac.values()) elements = list(set([i[0] for i in atoms_frac.keys()])) elements = {i: no for no, i in enumerate(elements)} numbers = [elements[i[0]] for i in atoms_frac.keys()] cell = (A, positions, numbers) return spglib.get_symmetry_dataset(cell, symprec=symprec) # ==================================================
[docs] def convert_to_conventional_frac(A, atoms_frac, symprec=SYMPREC): """ Convert atomic positions in "win" to fractional coordinates of the conventional cell. Args: A (ndarray): lattice vector in "win", [a1,a2,a3]. atoms_frac (dict): atoms_frac in "win". symprec (float, optional): precision for spglib. Returns: - (int) -- space group no. - (dict) -- atoms_frac in conventional cell. Note: - for a centred lattice, the positions are transformed into the standard conventional cell of spglib, x' = P x + p. - for a primitive lattice, the positions are returned as they are. """ dataset = _symmetry_dataset(A, atoms_frac, symprec) if not dataset: raise ValueError("space group cannot be determined from the structure in 'win'.") if dataset.international[0] == "P": return dataset.number, atoms_frac P = np.asarray(dataset.transformation_matrix, dtype=float) p = np.asarray(dataset.origin_shift, dtype=float) atoms_frac = {k: (P @ np.asarray(v, dtype=float) + p).tolist() for k, v in atoms_frac.items()} return dataset.number, atoms_frac
# ==================================================
[docs] def find_vector_index(vector_list, vector, symprec=SYMPREC): """ Find vector index. Args: vector_list (list): vector list. vector (ndarray): vector to find. symprec (float, optional): precision. Returns: - (int) -- index (None if not found). Note: - vectors differing by a lattice translation are regarded as the same. """ vector = np.asarray(vector, dtype=float) for idx, v in enumerate(vector_list): # compare modulo lattice translations. delta = np.asarray(v, dtype=float) - vector if np.allclose(delta - np.rint(delta), 0.0, rtol=0, atol=symprec): return idx return None
# ==================================================
[docs] def get_or_add_vector(existing_list, target_vector, symprec=SYMPREC): """ Get and add vector. Args: existing_list (list): vector list previously appeared. target_vector (ndarray): vector. symprec (float, optional): precision. Returns: - (int) -- index. """ target_arr = np.asarray(target_vector).reshape(-1) for idx, v in enumerate(existing_list): # Wyckoff orbits with different multiplicities have different lengths. if v.shape == target_arr.shape and np.allclose(v, target_arr, rtol=0, atol=symprec): return idx existing_list.append(target_arr) return len(existing_list) - 1
# ==================================================
[docs] def create_ket_wannier_multipie(wannier_info, tol=1e-4): """ Create wannier and MultiPie ket, and conversion index. Args: wannier_info (dict): wannier_info dict. A, atoms_frac, atomc_cart, nw2n, nw2l, nw2m, nw2r, nw2s, atom_pos_r. tol (float, optional): tolerance to match projection centres with atoms (fractional). Returns: - (list) -- idx for converting from wannier to multipie. <m|w> = delta(m.w2m(w)). - (list) -- idx for converting from multipie to wannier. <m|w> = delta(w,m2w(m)). - (list) -- ket_multipie name. |m>. - (list) -- projection centre in fractional coordinate (in multipie order). |m>(pos). - (list) -- projection centre in cartesian coordinate (in multipie order). |m>(pos). Note: - each projection centre (nw2n is its index in "nnkp") is matched with an atom in "win" modulo lattice translations. a centre which is not on an atom (e.g., bond centre) is named X1, X2, ... in order of appearance. if atom_pos_r is not given, the n-th projection centre is the n-th atom in "win". - the positions are those of the projection centres, to which R of H(R) refers. """ # create orbital list. orbital_info = [wannier_info[key] for key in ("nw2n", "nw2l", "nw2m", "nw2r", "nw2s")] orbital_list = [] for n, l, m, r, s in zip(*orbital_info): comp, orbital = _convert_w90_orbital(l, m, r, s) orbital_list.append((n, l, comp, orbital)) # determine space group by spglib, and convert positions into conventional cell. space_group_no, atoms_conv = convert_to_conventional_frac(wannier_info["A"], wannier_info["atoms_frac"]) group = Group(space_group_no) # match projection centres with atoms in "win" (if atom_pos_r is not given, centre n is atom n). # a centre which is not on an atom (e.g., bond centre) is None. atoms = [np.asarray(p, dtype=float) for p in wannier_info["atoms_frac"].values()] centres = np.asarray(wannier_info.get("atom_pos_r", atoms), dtype=float) c2a = [] for c in centres: d = [float(np.max(np.abs((c - p) - np.rint(c - p)))) for p in atoms] i = int(np.argmin(d)) c2a.append(i if d[i] <= tol else None) off_atom = [n for n, i in enumerate(c2a) if i is None] # create atom site-cluster info. existing_list = [] site_cluster = {} atom_info = [] for (atom, _), pos in atoms_conv.items(): wp, sites = group.find_wyckoff_site(pos) # an atom in an orbit found before belongs to the same site cluster. key = next((k for k, v in site_cluster.items() if k[:2] == (atom, wp) and find_vector_index(v, pos) is not None), None) if key is None: key = (atom, wp, get_or_add_vector(existing_list, sites) + 1) site_cluster[key] = sites atom_info.append((*key, pos)) # sublattice number of each atom: as in a model (in a plus set) for a primitive cell. if the cell is not primitive, # e.g., the conventional cell of a centred lattice, the atoms in each site cluster are numbered in order of appearance. plus_set = group.symmetry_operation.get("plus_set", None) npset = 1 if plus_set is None else len(plus_set) cluster = [(atom, wp, idx) for atom, wp, idx, _ in atom_info] sublattice = [ find_vector_index(site_cluster[c], pos) % (len(site_cluster[c]) // npset) + 1 for c, (*_, pos) in zip(cluster, atom_info) ] if len(set(zip(cluster, sublattice))) != len(atom_info): sublattice = [cluster[: i + 1].count(c) for i, c in enumerate(cluster)] # label of atom: element, or element with the number of its site cluster if it has several site clusters. clusters = list(dict.fromkeys(cluster)) label = {} for c in clusters: same = [k for k in clusters if k[0] == c[0]] label[c] = c[0] if len(same) == 1 else f"{c[0]}{same.index(c) + 1}" # label of projection centre not on an atom: X1, X2, ... not used by atoms. free = (f"X{k}" for k in range(1, len(label) + len(off_atom) + 2) if f"X{k}" not in label.values()) off_label = {n: next(free) for n in off_atom} # create ket info. name, (atom, sublattice, rank, component, orbital), frac_position, (wycokff, multiplicity). w_ket = [] for n, l, comp, orbital in orbital_list: if c2a[n] is None: # projection centre not on an atom, X1, X2, ... atom, sl, pos, wp, idx = off_label[n], 1, centres[n].tolist(), None, None else: atom, wp, idx, pos = atom_info[c2a[n]] sl = sublattice[c2a[n]] atom = label[(atom, wp, idx)] name = f"{orbital}@{atom}({sl})" w_ket.append((name, (atom, sl, l, comp, orbital), pos, (wp, idx))) m2w = sorted(range(len(w_ket)), key=lambda i: w_ket[i][1][:4]) w2m = [no for no, i in sorted(enumerate(m2w), key=lambda x: x[1])] ket_wannier = [w[0] for w in w_ket] ket_multipie = [w_ket[w][0] for w in m2w] nw2n = wannier_info["nw2n"] atoms_frac = [centres[nw2n[w]].tolist() for w in m2w] atoms_cart = (np.asarray(atoms_frac) @ np.asarray(wannier_info["A"], dtype=float)).tolist() # for debug. # return space_group_no, str(group), site_cluster, w_ket, m2w, ket_wannier, ket_multipie return w2m, m2w, ket_multipie, atoms_frac, atoms_cart
# ==================================================
[docs] def find_lattice_transformation(A_wannier, A_model, tol=0.1): """ Find integer unimodular matrix U such that A_wannier = U A_model. Args: A_wannier (ndarray): primitive lattice vectors in "win", [a1,a2,a3] (Cartesian). A_model (ndarray): primitive lattice vectors of the model, [a1,a2,a3] (Cartesian). tol (float, optional): tolerance for the deviation of U from integers. Returns: - (ndarray) -- U (int), or None if not found. - (float) -- maximum deviation of U from integers. Note: - both lattices must be given in the same Cartesian frame (no rotation). - fractional coordinates are converted as x_model = x_wannier U. """ U = np.asarray(A_wannier, dtype=float) @ np.linalg.inv(np.asarray(A_model, dtype=float)) Ui = np.rint(U) residual = float(np.max(np.abs(U - Ui))) if residual > tol or round(abs(np.linalg.det(Ui))) != 1: return None, residual return Ui.astype(int), residual
# ==================================================
[docs] def model_primitive_vector(model): """ Get primitive lattice vectors of a MultiPie model. Args: model (MaterialModel): loaded MultiPie model. Returns: - (ndarray) -- primitive lattice vectors, [a1,a2,a3] (Cartesian), consistent with the primitive fractional coordinates of the model. """ return convert_to_primitive_vector(model.group.info.lattice, model["unit_vector"])
# ================================================== def _parse_ket_name(ket): """ Parse MultiPie ket name, "orbital@site(sublattice)" or [site, sublattice, orbital]. """ if isinstance(ket, str): m = re.fullmatch(r"\s*(.+)@(.+)\((\d+)\)\s*", ket) if m is None: raise ValueError(f"invalid ket name '{ket}', use 'orbital@site(sublattice)'.") orbital, site, sl = m.groups() else: site, sl, orbital = ket return site, int(sl), str(orbital).replace(" ", "") # ==================================================
[docs] def map_wannier_to_model(nnkp, A_wannier, model, ket_wannier=None, tol=SYMPREC, lattice_tol=0.1): """ Map Wannier functions onto the kets of a MultiPie model. Args: nnkp (dict): information returned by :func:`read_nnkp`. A_wannier (ndarray): lattice vectors in "win", [a1,a2,a3] (Cartesian). model (MaterialModel): loaded MultiPie model. ket_wannier (list, optional): MultiPie ket for each Wannier function, ["orbital@site(sublattice)"] or [[site, sublattice, orbital]]. If empty, it is determined from the projection centres. tol (float, optional): tolerance for fractional positions. lattice_tol (float, optional): tolerance for the lattice transformation. Returns: - (dict) -- mapping information. - w2m: MultiPie ket index of each Wannier function (list). - U: lattice transformation, x_model = x_wannier U + t (ndarray). - t: origin shift (ndarray). - offset: lattice offset L of each Wannier function, c U + t = r + L, where c and r are the projection centre and the position of MultiPie ket (int ndarray). Note: - the lattice of "win" must be related to the primitive lattice of the model by an integer unimodular matrix in the same Cartesian frame. Otherwise, the lattice vectors of "win" are assumed to be those of the model (with warning). - the origin shift t is chosen so that all the projection centres coincide with the sites of the model. When several shifts are possible, the smallest one is used (with warning if the mapping depends on the choice). """ keys = ("nw2n", "nw2l", "nw2m", "nw2r", "nw2s", "atom_pos_r") missing = [key for key in keys if nnkp.get(key) is None] if missing: raise ValueError(f"projection information is unavailable in nnkp: {', '.join(missing)}") model_ket = [tuple(k) for k in model["full_matrix"]["ket"]] ket_pos = np.asarray(list(model.get_ket_site().values()), dtype=float) num_wann = len(nnkp["nw2n"]) if num_wann != len(model_ket): raise ValueError(f"number of Wannier functions ({num_wann}) differs from the dimension of the model ({len(model_ket)}).") # lattice transformation. Ap = model_primitive_vector(model) U, residual = find_lattice_transformation(A_wannier, Ap, lattice_tol) if U is None: warnings.warn( "lattice vectors in 'win' do not match the primitive lattice of the model " f"(maximum deviation from integer transformation = {residual:.3e}). " "The fractional coordinates in 'win' are used as those of the model primitive cell.", stacklevel=2, ) U = np.eye(3, dtype=int) center = np.asarray(nnkp["atom_pos_r"], dtype=float) center_m = center @ U # projection centres in nnkp are rounded to 5 decimals, which is amplified by U. # a residual contains the rounding errors of two centres (the one checked and the one fixing t). tol = tol + 1e-5 * float(np.max(np.abs(U).sum(axis=0))) orbitals = [ (l, *_convert_w90_orbital(l, m, r, s)) for l, m, r, s in zip(*[nnkp[k] for k in ("nw2l", "nw2m", "nw2r", "nw2s")]) ] def same(x, y): d = np.asarray(x) - np.asarray(y) return np.allclose(d - np.rint(d), 0.0, rtol=0, atol=tol) def assign_ket(site_of_center): w2m = [] for iw, (l, _, orbital) in enumerate(orbitals): site, sl = site_of_center[nnkp["nw2n"][iw]] idx = [i for i, k in enumerate(model_ket) if k[0] == site and k[1] == sl and k[2] == l and k[4] == orbital] if len(idx) != 1: return None w2m.append(idx[0]) if sorted(w2m) != list(range(len(model_ket))): return None return w2m if ket_wannier: # user-given correspondence. if len(ket_wannier) != num_wann: raise ValueError(f"ket_wannier must have {num_wann} entries.") w2m = [] for ket in ket_wannier: site, sl, orbital = _parse_ket_name(ket) idx = [i for i, k in enumerate(model_ket) if k[0] == site and k[1] == sl and k[4] == orbital] if len(idx) != 1: raise ValueError(f"ket '{ket}' is not found in the model.") w2m.append(idx[0]) if sorted(w2m) != list(range(len(model_ket))): raise ValueError("ket_wannier must contain every ket of the model exactly once.") t = ket_pos[w2m[0]] - center_m[nnkp["nw2n"][0]] t -= np.rint(t) else: # determine origin shift and site of each projection centre. sites = {} for k, p in zip(model_ket, ket_pos): sites.setdefault((k[0], k[1]), p) site_list = list(sites.items()) candidates = [] for _, p in site_list: t = p - center_m[0] t -= np.rint(t) site_of_center = [] for c in center_m: match = [s for s, q in site_list if same(c + t, q)] if len(match) != 1: break site_of_center.append(match[0]) else: # several centres may be periodic images of the same site (with different orbitals). w2m = assign_ket(site_of_center) if w2m is not None: candidates.append((round(float(np.linalg.norm(t)), 6), t, w2m)) if not candidates: raise ValueError( "Wannier projection centres cannot be mapped onto the sites and orbitals of the model. " "Check that the lattice vectors and positions in 'win' agree with the model (cell, site and orbital), " "or give 'ket_wannier' in the control." ) _, t, w2m = min(candidates, key=lambda c: c[0]) if len({tuple(c[2]) for c in candidates}) > 1: warnings.warn( "Wannier functions can be mapped onto the model in several ways. " f"The origin shift {np.round(t, 6).tolist()} is used. Give 'ket_wannier' in the control to specify the mapping.", stacklevel=2, ) # check consistency of positions, and get lattice offset of each Wannier function, x_win U + t = x_model + offset. offset = [] for iw in range(num_wann): d = center_m[nnkp["nw2n"][iw]] + t - ket_pos[w2m[iw]] if not same(d, 0.0): raise ValueError(f"position of Wannier function {iw+1} does not coincide with that of ket {model_ket[w2m[iw]]}.") offset.append(np.rint(d).astype(int)) return {"w2m": w2m, "U": U, "t": t, "offset": np.asarray(offset, dtype=int)}
# ==================================================
[docs] def convert_hr_to_model(hr_dict, mapping): """ Convert H(R) in "hr.dat" into the ket and lattice of a MultiPie model. Args: hr_dict (dict): H(R) in Wannier index, dict[(n1,n2,n3,a,b), value]. mapping (dict): mapping information returned by :func:`map_wannier_to_model`. Returns: - (dict) -- H(R) in MultiPie index and primitive lattice of the model, dict[(n1,n2,n3,m,n), (value, None)]. Note: - H_ab(R) = <0,a|H|R,b> is re-indexed through the bond vector, (c_b + R - c_a) U = r_n + (R U + L_b - L_a) - r_m, where c and r are the projection centre and the position of MultiPie ket, and L is the lattice offset. """ w2m, U, offset = mapping["w2m"], mapping["U"], mapping["offset"] HR = {} for (n1, n2, n3, a, b), v in hr_dict.items(): R = np.array([n1, n2, n3], dtype=int) @ U + offset[b] - offset[a] key = (int(R[0]), int(R[1]), int(R[2]), w2m[a], w2m[b]) HR[key] = HR.get(key, 0.0) + complex(v) return {k: (v, None) for k, v in HR.items()}