Source code for multipie.util.util_model_analyzer

# 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 for ModelAnalyzer class.
"""

import os
import numpy as np
import sympy as sp
from collections import defaultdict
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import Normalize, LinearSegmentedColormap
from matplotlib.backends.backend_pdf import PdfPages
from multipie import Group
from multipie.util.util import str_to_sympy, simplify
from multipie.util.util_constant import M_ZERO, k_B_SI, elem_charge_SI


# ==================================================
[docs] def grid_path(pts, gpath, N1=100, A=None): """ Create grid points along path. Args: pts (dict): definitions of points, e.g., {"A":[1,2,3],"B":[3,4,5]}. gpath (str): path, e.g., "A-B|C-D-E". N1 (int, optional): number of divisions. A (ndarray, optional): conversion matrix. Returns: - (ndarray) -- grid points. - (ndarray) -- linear positions. - (dict) -- dict[disconnected linear position, label]. """ if A is None: d = np.array(list(pts.values())[0]).shape[0] A = np.eye(d) gpath = gpath.replace(" ", "").replace("\t", "").replace("\n", "") glabel = gpath.split("-") gpath = gpath.split("|") gpath = [i.split("-") for i in gpath] gpath = [[(i1, i2) for i1, i2 in zip(i[:-1], i[1:])] for i in gpath] gpath = sum(gpath, []) grid = [] glin = [] gdis = [0] x = 0 for s, e in gpath: s = np.array(pts[s]) e = np.array(pts[e]) dv = (e - s) / N1 d = np.linalg.norm(dv @ A.T) for j in range(N1): glin.append(x) grid.append(s + j * dv) x += d grid.append(s + N1 * dv) glin.append(x) gdis.append(x) grid = np.asarray(grid) glin = np.asarray(glin) gdis = dict(zip(gdis, glabel)) return grid, glin, gdis
# ==================================================
[docs] def grid_all(N1, N2, N3): """ Create N1 x N2 x N3 grid points. Args: N1 (int): number of divisions for a1. N2 (int): number of divisions for a2. N3 (int): number of divisions for a3. Returns: - (ndarray) -- grid points. """ kpoints = np.array([[i / float(N1), j / float(N2), k / float(N3)] for i in range(N1) for j in range(N2) for k in range(N3)]) return kpoints
# ==================================================
[docs] def fourier_r_to_k(OR, atom, kv, s=True): """ Fourier transformation from R to k. Args: OR (dict): matrix dict, dict[(n1,n2,n3,m,n): value]. atom (ndarray): atomic positions. kv (ndarray): list of k vector. s (bool, optional): include phase of atomic position ? Returns: - (ndarray) -- O(k) = sum_s Omn exp( 2pi i k*Rs ), Rs = (n1,n2,n3)-s(R[m]-R[n]). """ Nk = len(kv) d = len(atom) # O_R as d x d matrix for each R, so that exp(2pi i k*R) is computed once for each R. OR_mat = {} for (R, m, n), value in OR.items(): OR_mat.setdefault(tuple(R), np.zeros((d, d), dtype=complex))[m, n] += value if not OR_mat: return np.zeros((Nk, d, d), dtype=complex) R = np.asarray(list(OR_mat.keys()), dtype=float) eR = np.exp(1j * (2 * np.pi * kv @ R.T)) # (Nk, number of R). S = np.tensordot(eR, np.asarray(list(OR_mat.values())), axes=(1, 0)) if s: eRa = np.exp(1j * (2 * np.pi * kv @ atom.T)) S *= np.conj(eRa)[:, :, None] * eRa[:, None, :] return S
# ==================================================
[docs] def fourier_k_to_r(Ok, atom, kv, irvec, s=True): """ Fourier transformation from k to R (inverse of fourier_r_to_k). Args: Ok (ndarray): O(k) matrix, shape (Nk, d, d). atom (ndarray): atomic positions. kv (ndarray): list of k vector. irvec (iterable): list/array of R = (n1, n2, n3) lattice vectors to evaluate O_R at. s (bool, optional): include phase of atomic position ? (must match the value used to generate `Ok`). Returns: dict: dict[(n1,n2,n3,m,n): value], O_R = (1/Nk) sum_k O(k) exp(-2pi i k*Rs), Rs = (n1,n2,n3)-s(R[m]-R[n]), i.e. the inverse of `fourier_r_to_k`. """ eRa = np.exp(1j * (2 * np.pi * kv @ atom.T)) Nk = len(kv) d = len(atom) OR = {} for R in irvec: R = tuple(int(v) for v in R) eR = np.exp(-1j * (2 * np.pi * kv @ np.asarray(R, dtype=float))) if s: phase = eR[:, None, None] * eRa[:, :, None] * np.conj(eRa)[:, None, :] else: phase = eR[:, None, None] * np.ones((Nk, d, d), dtype=complex) value = np.sum(Ok * phase, axis=0) / Nk for m in range(d): for n in range(d): OR[(R, m, n)] = value[m, n] return OR
# ==================================================
[docs] def output_dispersion(filename, k, ef, e, o=None, olist=None): """ Output band dispersion along high-symmetry lines. Args: filename (str): file name. k (ndarray): k points along high-symmetry lines. ef (float): fermi energy. e (ndarray): eigen values. o (list, optional): expectation value of any operator for each band, [[num_k, num_band]]. olist (list, optional): list of local operator. """ emax = np.nanmax(np.where(np.isfinite(e), e, np.nan)) emin = np.nanmin(np.where(np.isfinite(e), e, np.nan)) fs = open(filename, "w") if olist: ke_ol = "# k Energy " + " ".join(olist) + "\n" else: ke_ol = "# k Energy\n" fs.write(ke_ol) fs.write(f"# Emax = {emax}\n") fs.write(f"# Emin = {emin}\n") fs.write(f"# shifted by fermi energy = {ef}\n\n") num_k, Nm = e.shape e = e.T kv = np.append(k, -1.0) # add dummy for last one. for n in range(Nm): en = e[n] - ef s = "" for i in range(num_k): # skip values that cannot be computed (Ek = 0 with negative power), and break the line there. if not np.isfinite(en[i]): if s != "" and not s.endswith("\n\n"): s += "\n" continue s += "{k: .15f} {e: .15f}".format(k=kv[i], e=en[i]) if o is None: s += "\n" else: for oi in o: s += " {o: .15f}".format(o=oi[i, n]) s += "\n" if np.abs(kv[i] - kv[i + 1]) < 1e-5 and not s.endswith("\n\n"): s += "\n" s += "\n" fs.write(s) fs.close()
# ==================================================
[docs] def k_label(label, style="latex"): """ Convert k-point label for plot. Args: label (str): k-point label, e.g., "Γ", "GAMMA", "G", "X|M". style (str, optional): "latex" (matplotlib) or "gnuplot" (enhanced text). Returns: - (str) -- converted label. """ gamma = r"$\Gamma$" if style == "latex" else "{/Symbol G}" lst = [gamma if v in ["Γ", "GAMMA", "G"] else v for v in label.split("|")] return ":".join(lst)
# ==================================================
[docs] def create_gnuplot_cmd(filename, k_dis_pos, kmax, emax, emin, ef, colormap=False, lwidth=2, lc="salmon"): """ Create gnuplot file. Args: filename (str): file name. k_dis_pos (dict): info. of high-symmetry point in linear k, dict[disconnected position, label]. kmax (float): maximum value in kpoints. emax (float): maximum value of eigen values. emin (float): minimum value of eigen values. ef (float): fermi energy. colormap (bool, optional): with colormap of first expectation value of operator. lwidth (int, optional): line width. lc (str, optional): line color. Notes: - values that cannot be computed are not written in data file, so that they are skipped in the plot. """ offset = (emax - emin) * 0.1 gnufile = os.path.dirname(filename) + "/plot_band.gnu" fs = open(gnufile, "w") fs.write(f"Ef = {ef} # fermi energy (data are already shifted by Ef).\n") fs.write("Ef_line = 0.0 # position of fermi level in plot.\n") fs.write("xmin = 0.0\n") fs.write(f"xmax = {kmax}\n") fs.write(f"ymin = {emin-ef-offset}\n") fs.write(f"ymax = {emax-ef+offset}\n") fs.write(f"lwidth = {lwidth}\n\n") fs.write("unset key\n") fs.write("unset grid\n") fs.write("set xrange [xmin:xmax]\n") fs.write("set yrange [ymin:ymax]\n") fs.write("set tics font 'Times New Roman, 14'\n\n") fs.write("set size ratio 0.7\n\n") fs.write('set palette defined ( -1.0 "royalblue", 0 "gray90", 1.0 "salmon")\n') fs.write("set cbrange [-1.0:1.0]\n\n") if k_dis_pos is not None: for pos in k_dis_pos.keys(): fs.write(f"set arrow from {pos}, ymin to {pos}, ymax nohead\n") fs.write( "set xtics (" + ", ".join([f'"{k_label(label, "gnuplot")}" {pos}' for pos, label in k_dis_pos.items()]) + ")\n\n" ) filename = os.path.basename(filename) basename = os.path.splitext(filename)[0] if colormap: plot_cmd = f"plot '{filename}' u 1:2:3 w l lw lwidth lc palette, Ef_line lw 0.5 lc 'black'\n\n" else: plot_cmd = f"plot '{filename}' u 1:2 w l lw lwidth lc '{lc}', Ef_line lw 0.5 lc 'black'\n\n" fs.write("set terminal postscript eps color enhanced\n") fs.write(f"set output '{basename}.eps'\n") fs.write(plot_cmd) fs.write("set terminal pdf enhanced\n") fs.write(f"set output '{basename}.pdf'\n") fs.write(plot_cmd) fs.close()
# ==================================================
[docs] def plot_save_dispersion(filename, k_dis_pos, ef=None, colormap=False, lwidth=1, lc="salmon"): """ Generate plot window for band dispersion (matplotlib). Args: filename (str): file name. k_dis_pos (dict): info. of high-symmetry point in linear k, dict[disconnected position, label]. ef (float, optional): not used, kept for compatibility. colormap (bool, optional): with colormap of first expectation value of operator. lwidth (int, optional): line width. lc (str, optional): line color. Notes: - energies in data file are already shifted by fermi energy. """ # read file. bands = read_text_data(filename) emax = max(a[:, 1].max() for a in bands) emin = min(a[:, 1].min() for a in bands) kmax = max(a[:, 0].max() for a in bands) offset = (emax - emin) * 0.1 fig, ax = plt.subplots(figsize=(6, 3.5)) # aspect ratio 0.7 fig.subplots_adjust(right=0.84) ax.set_xlim(0, kmax) ax.set_ylim(emin - offset, emax + offset) ax.axhline(0, color="black", lw=0.5) ax.tick_params(axis="x", which="both", bottom=False, top=False, labelbottom=True) ax.tick_params(axis="y", which="both", left=True, right=True, direction="in") # vertical lines. positions = list(k_dis_pos.keys()) labels = [k_label(v, "latex") for v in k_dis_pos.values()] for x in positions: ax.axvline(x, color="black", lw=0.5) ax.set_xticks(positions) ax.set_xticklabels(labels) if colormap: all_segments = [] all_colors = [] for band in bands: x = band[:, 0] y = band[:, 1] c = band[:, 2] points = np.column_stack((x, y)).reshape(-1, 1, 2) seg = np.concatenate([points[:-1], points[1:]], axis=1) all_segments.extend(seg) all_colors.extend(c[:-1]) lcobj = LineCollection(all_segments, cmap="coolwarm", norm=Normalize(-1.0, 1.0), linewidth=lwidth) lcobj.set_array(np.asarray(all_colors)) ax.add_collection(lcobj) cbar = fig.colorbar(lcobj, ax=ax, ticks=[-1.0, -0.5, 0.0, 0.5, 1.0], fraction=0.035, pad=0.02) cbar.ax.tick_params(which="both", length=0) cbar.set_ticklabels(["-1", "-0.5", "0", "0.5", "1"]) else: for band in bands: ax.plot(band[:, 0], band[:, 1], color=lc, lw=lwidth) fn_pdf = os.path.splitext(filename)[0] + ".pdf" fn_eps = os.path.splitext(filename)[0] + ".eps" fig.savefig(fn_pdf) fig.savefig(fn_eps) plt.close("all")
# ==================================================
[docs] def plot_save_weight(filename, k_dis_pos, labels, lwidth=1.5): """ Plot band dispersion colored by orbital weight (fat band), one page for each weight (matplotlib). Args: filename (str): file name of data, columns (k, E, weight1, weight2, ...). k_dis_pos (dict): info. of high-symmetry point in linear k, dict[disconnected position, label]. labels (list): label of weights. lwidth (float, optional): line width. Notes: - energies in data file are already shifted by fermi energy. - the plots are saved in one PDF file (filename with .pdf). """ bands = read_text_data(filename) emax = max(a[:, 1].max() for a in bands) emin = min(a[:, 1].min() for a in bands) kmax = max(a[:, 0].max() for a in bands) offset = (emax - emin) * 0.1 positions = list(k_dis_pos.keys()) xlabels = [k_label(v, "latex") for v in k_dis_pos.values()] cmap = LinearSegmentedColormap.from_list("weight", ["0.9", "red"]) # as palette of gnuplot. fn_pdf = os.path.splitext(filename)[0] + ".pdf" with PdfPages(fn_pdf) as pdf: for no, label in enumerate(labels): fig, ax = plt.subplots(figsize=(6, 3.5)) fig.subplots_adjust(right=0.84) ax.set_xlim(0, kmax) ax.set_ylim(emin - offset, emax + offset) ax.set_title(label) ax.axhline(0, color="black", lw=0.5) ax.tick_params(axis="x", which="both", bottom=False, top=False, labelbottom=True) ax.tick_params(axis="y", which="both", left=True, right=True, direction="in") for x in positions: ax.axvline(x, color="black", lw=0.5) ax.set_xticks(positions) ax.set_xticklabels(xlabels) segments, colors = [], [] for band in bands: points = band[:, :2].reshape(-1, 1, 2) segments.extend(np.concatenate([points[:-1], points[1:]], axis=1)) colors.extend(band[:-1, 2 + no]) lcobj = LineCollection(segments, cmap=cmap, norm=Normalize(0.0, 1.0), linewidth=lwidth) lcobj.set_array(np.asarray(colors)) ax.add_collection(lcobj) fig.colorbar(lcobj, ax=ax, ticks=[0.0, 0.5, 1.0], fraction=0.035, pad=0.02) pdf.savefig(fig) plt.close(fig)
# ==================================================
[docs] def create_gnuplot_weight(filename, k_dis_pos, kmax, emax, emin, ef, labels, lwidth=2): """ Create gnuplot file for band dispersion colored by orbital weight (fat band), one page for each weight. Args: filename (str): file name of data, columns (k, E, weight1, weight2, ...). k_dis_pos (dict): info. of high-symmetry point in linear k, dict[disconnected position, label]. kmax (float): maximum value in kpoints. emax (float): maximum value of eigen values. emin (float): minimum value of eigen values. ef (float): fermi energy. labels (list): label of weights (without spaces). lwidth (int, optional): line width. """ offset = (emax - emin) * 0.1 gnufile = os.path.join(os.path.dirname(filename), "plot_weight.gnu") basename = os.path.splitext(os.path.basename(filename))[0] with open(gnufile, "w", encoding="utf-8") as fs: fs.write(f"Ef = {ef} # fermi energy (data are already shifted by Ef).\n") fs.write("Ef_line = 0.0 # position of fermi level in plot.\n") fs.write("xmin = 0.0\n") fs.write(f"xmax = {kmax}\n") fs.write(f"ymin = {emin-ef-offset}\n") fs.write(f"ymax = {emax-ef+offset}\n") fs.write(f"lwidth = {lwidth}\n") fs.write(f'labels = "{" ".join(labels)}" # weight of column 3, 4, ...\n\n') fs.write("unset key\n") fs.write("unset grid\n") fs.write("set xrange [xmin:xmax]\n") fs.write("set yrange [ymin:ymax]\n") fs.write("set tics font 'Times New Roman, 14'\n\n") fs.write("set size ratio 0.7\n\n") fs.write('set palette defined ( 0 "gray90", 1.0 "red")\n') fs.write("set cbrange [0.0:1.0]\n\n") if k_dis_pos is not None: for pos in k_dis_pos.keys(): fs.write(f"set arrow from {pos}, ymin to {pos}, ymax nohead\n") fs.write( "set xtics (" + ", ".join([f'"{k_label(label, "gnuplot")}" {pos}' for pos, label in k_dis_pos.items()]) + ")\n\n" ) fs.write("set terminal pdf enhanced\n") fs.write(f"set output '{basename}.pdf'\n") fs.write("do for [i=1:words(labels)] {\n") fs.write(" set title word(labels, i) noenhanced\n") fs.write(f" plot '{basename}.txt' u 1:2:(column(2+i)) w l lw lwidth lc palette, Ef_line lw 0.5 lc 'black'\n") fs.write("}\n")
# ==================================================
[docs] def output_dos(filename, energy, ef, dos, labels, comment): """ Output DOS. Args: filename (str): file name. energy (ndarray): energy grid (not shifted). ef (float): fermi energy. dos (ndarray): DOS, [energy, column], columns (total, integrated total, partial, ...). labels (list): label of partial DOS. comment (list): comment lines (without "#"). """ with open(filename, mode="w", encoding="utf-8") as f: for line in comment: print(f"# {line}", file=f) print("#", file=f) print("# E total N(E) " + " ".join(labels), file=f) for e, row in zip(energy - ef, dos): print(f"{e: .15e} " + " ".join(f"{v: .15e}" for v in row), file=f)
# ==================================================
[docs] def plot_save_dos(filename, labels, lwidth=1): """ Plot DOS (matplotlib). Args: filename (str): file name of data, columns (E, total, N(E), partial, ...). labels (list): label of partial DOS. lwidth (float, optional): line width. Notes: - energies in data file are already shifted by fermi energy. """ data = np.loadtxt(filename, ndmin=2) e = data[:, 0] fig, ax = plt.subplots(figsize=(6, 3.5)) ax.set_xlim(e[0], e[-1]) ax.set_ylim(0, 1.1 * data[:, 1].max()) ax.axvline(0, color="black", lw=0.5) ax.tick_params(axis="both", which="both", direction="in", top=True, right=True) ax.set_xlabel("Energy") ax.set_ylabel("DOS") ax.plot(e, data[:, 1], color="black", lw=lwidth, label="total") for no, label in enumerate(labels): ax.plot(e, data[:, 3 + no], lw=lwidth, label=label) ax.legend(fontsize="small", frameon=False) fig.savefig(os.path.splitext(filename)[0] + ".pdf") fig.savefig(os.path.splitext(filename)[0] + ".eps") plt.close(fig)
# ==================================================
[docs] def create_gnuplot_dos(filename, emin, emax, dmax, ef, labels, lwidth=2): """ Create gnuplot file for DOS. Args: filename (str): file name of data, columns (E, total, N(E), partial, ...). emin (float): minimum of energy grid (not shifted). emax (float): maximum of energy grid (not shifted). dmax (float): maximum of total DOS. ef (float): fermi energy. labels (list): label of partial DOS. lwidth (int, optional): line width. """ gnufile = os.path.join(os.path.dirname(filename), "plot_dos.gnu") basename = os.path.splitext(os.path.basename(filename))[0] with open(gnufile, "w", encoding="utf-8") as fs: fs.write(f"Ef = {ef} # fermi energy (data are already shifted by Ef).\n") fs.write("Ef_line = 0.0 # position of fermi level in plot.\n") fs.write(f"xmin = {emin-ef}\n") fs.write(f"xmax = {emax-ef}\n") fs.write("ymin = 0.0\n") fs.write(f"ymax = {1.1*dmax}\n") fs.write(f"lwidth = {lwidth}\n\n") fs.write("set key top right noenhanced\n") fs.write("unset grid\n") fs.write("set xrange [xmin:xmax]\n") fs.write("set yrange [ymin:ymax]\n") fs.write("set xlabel 'Energy'\n") fs.write("set ylabel 'DOS'\n") fs.write("set tics font 'Times New Roman, 14'\n\n") fs.write("set size ratio 0.7\n\n") fs.write("set arrow from Ef_line, ymin to Ef_line, ymax nohead lw 0.5 lc 'black'\n\n") plot = [f"'{basename}.txt' u 1:2 w l lw lwidth lc 'black' title 'total'"] plot += [f"'' u 1:{4 + no} w l lw lwidth title '{label}'" for no, label in enumerate(labels)] plot_cmd = "plot " + ", \\\n ".join(plot) + "\n\n" fs.write("set terminal postscript eps color enhanced\n") fs.write(f"set output '{basename}.eps'\n") fs.write(plot_cmd) fs.write("set terminal pdf enhanced\n") fs.write(f"set output '{basename}.pdf'\n") fs.write(plot_cmd)
# ==================================================
[docs] def parse_orbital(orbital_str): """ Parse orbital string. Args: orbital_str (str): orbital string, (orbital, spin). Returns: - (tuple or str) -- orbital, spin or orbital. """ if orbital_str.count("("): return orbital_str.strip("()").split(",") else: return orbital_str, "u"
# ==================================================
[docs] def create_operator_index(ket, mode=None): """ Create operator index. Args: ket (list): ket list. mode (str, optional): "orbital" or "spin". Returns: - (list) -- index pair list. Note: - atom, sublattice, rank is the same in pair. - spin is the same for "orbital" mode. - orbital is the same for "spin" mode. """ results = [] for i, (atom_i, sub_i, rank_i, idx_i, orb_i) in enumerate(ket): o_i, s_i = parse_orbital(orb_i) for j, (atom_j, sub_j, rank_j, idx_j, orb_j) in enumerate(ket): o_j, s_j = parse_orbital(orb_j) if atom_i != atom_j or sub_i != sub_j or rank_i != rank_j: # same atom, sub, rank. continue if mode == "spin" and o_i != o_j: # same orbital. continue if mode == "orbital" and s_i != s_j: # same spin. continue results.append((i, j, rank_i, idx_i, idx_j)) return results
# ==================================================
[docs] def create_local_operator(ket, op_name, op_dict, spinful): """ Create local operator. Args: ket (list): ket set. op_name (str): operator name. op_dict (dict): operator dict. spinful (bool): lgs basis ? Returns: - (ndarray) -- matrix for given operator. """ if op_name[0] == "S": mode = "spin" if not spinful: raise ValueError(f"spin operator '{op_name}' requires a spinful model.") else: mode = "orbital" dim = len(ket) mat = np.zeros((dim, dim), dtype=complex) lst = create_operator_index(ket, mode) if mode == "spin": for m, n, rank, b_idx, k_idx in lst: # kets of an orbital are in the order of (u, d), so that the odd index is d. mat[m, n] += complex(op_dict["s"][op_name][b_idx % 2, k_idx % 2]) else: for m, n, rank, b_idx, k_idx in lst: if spinful: b_idx = b_idx // 2 k_idx = k_idx // 2 mat[m, n] += complex(op_dict[rank][op_name][b_idx, k_idx]) return mat
# ==================================================
[docs] def local_expectation(Uk, op): """ Expectation value of local operator for each eigen state. Args: Uk (ndarray): eigen vectors, Uk[k,:,n]. op (ndarray): operator matrix (dim x dim). Returns: - (ndarray) -- expectation values, [k,n]. """ return np.sum(Uk.conj() * (op @ Uk), axis=1).real
# ==================================================
[docs] def samb_matrix_value(matrix): """ SAMB matrix (real-space) with numerical values. Args: matrix (dict): SAMB matrix, dict[(n1,n2,n3,m,n), (value, bond_no)] (value may be sympy). Returns: - (dict) -- dict[((n1,n2,n3),m,n), complex value], the form of fourier_r_to_k. """ return {((int(n1), int(n2), int(n3)), int(m), int(n)): complex(v) for (n1, n2, n3, m, n), (v, _) in matrix.items()}
# ==================================================
[docs] def operator_expectation(Uk, Ok): """ Expectation value of k-dependent operator for each eigen state. Args: Uk (ndarray): eigen vectors, Uk[k,:,n]. Ok (ndarray): operator matrix at each k, Ok[k,:,:]. Returns: - (ndarray) -- expectation values (real part), [k,n]. """ return np.einsum("kmi,kmn,kni->ki", Uk.conj(), Ok, Uk, optimize=True).real
# ==================================================
[docs] def density_matrix_r(Uk, occupation, atom, kv, R, s=True): """ Sum over k points of the density matrix, as the counterpart of a real-space matrix O(R). Args: Uk (ndarray): eigen vectors, Uk[k,:,n]. occupation (ndarray): occupation of each eigen state, [k,n]. atom (ndarray): atomic positions. kv (ndarray): k points (fractional). R (ndarray): lattice vectors, [number of R, 3]. s (bool, optional): include phase of atomic position ? Returns: - (ndarray) -- A[R,m,n] = sum_k P(k)_nm exp(2pi i k*R) (with the phase of atomic position, as fourier_r_to_k). Notes: - P(k) = U(k) f U(k)^dagger, and sum_k Tr[P(k) O(k)] = sum_(R,m,n) O(R)_mn A[R,m,n] for O(k) by fourier_r_to_k. """ PT = np.einsum("kni,ki,kmi->kmn", Uk, occupation, Uk.conj(), optimize=True) # P(k)_nm as [k,m,n]. if s: eRa = np.exp(1j * (2 * np.pi * kv @ atom.T)) PT *= np.conj(eRa)[:, :, None] * eRa[:, None, :] eR = np.exp(1j * (2 * np.pi * kv @ np.asarray(R, dtype=float).T)) # (Nk, number of R). return np.tensordot(eR, PT, axes=(0, 0))
# ==================================================
[docs] def power_energy(Ek, power): """ Raise energy to the power. Args: Ek (ndarray): energy eigen values. power (float): power (positive). Returns: - (ndarray) -- Ek^power, or -|Ek|^power where Ek^power is not a real number (negative Ek with non-integer power). """ with np.errstate(invalid="ignore"): value = np.power(Ek, power) return np.where(np.isnan(value), -np.power(np.abs(Ek), power), value)
# ==================================================
[docs] def create_all_local_operator(): """ Create local operators. Returns: - (dict) -- local operators, dict[rank, dict[name, matrix]]. Note: - atomic basis is tesseral harmonics, s, px, py, pz, dv, dxy, dxz, dyz, du, fc, fs, fbz, f3, fx, fy, faz. - operator names are Lx, Ly, Lz, Qu, Qv, Qyz, Qxz, Qxy, and spin Sx, Sy, Sz (in d["s"]). - they are not normalized as SAMB (Tr X^2 = 1), but are the physical operators: the normalized atomic SAMB is multiplied by the factor in op_factor. - Lx, Ly, Lz: orbital angular momentum (in units of hbar), [Lx, Ly] = i Lz, L^2 = l(l+1). - Qu, Qv, Qyz, Qxz, Qxy: matrix elements <l m|Q(r)|l m'> of the angular functions, Qu = (3z^2-r^2)/(2r^2), Qv = sqrt(3)(x^2-y^2)/(2r^2), Qyz = sqrt(3)yz/r^2, Qxz = sqrt(3)zx/r^2, Qxy = sqrt(3)xy/r^2, e.g., <pz|Qu|pz> = 2/5, <du|Qu|du> = 2/7, <faz|Qu|faz> = 4/15. - Sx, Sy, Sz: sigma/2 in the order of (u, d). - L and Q are zero for rank 0 (s orbital). - it is used for basis, lg and lgs, not for jml. """ op_key = [("M", 1, "T1g", -1, -1, 0, 0, "q"), ("Q", 2, "Eg", -1, -1, 0, 0, "q"), ("Q", 2, "T2g", -1, -1, 0, 0, "q")] op_factor = { 1: ["sqrt(2)", "sqrt(6)/5", "sqrt(6)/5"], 2: ["sqrt(10)", "sqrt(14)/7", "sqrt(14)/7"], 3: ["14/sqrt(7)", "sqrt(21)*2/15", "sqrt(21)*2/15"], } group = Group("Oh") lst = ["Lx", "Ly", "Lz", "Qu", "Qv", "Qyz", "Qxz", "Qxy"] d = {0: {name: str_to_sympy("[[0]]") for name in lst}} for rank in [1, 2, 3]: no = 0 am = group.atomic_samb("lg", (rank, rank)) dd = {} for l, f in zip(op_key, op_factor[rank]): f = str_to_sympy(f) v, ex = am[l] for e, m in zip(ex, v): name = lst[no] no = no + 1 dd[name] = m * f d[rank] = dd spin = {"Sx": "[[0,1/2],[1/2,0]]", "Sy": "[[0,-I/2],[I/2,0]]", "Sz": "[[1/2,0],[0,-1/2]]"} d["s"] = {name: str_to_sympy(s) for name, s in spin.items()} return d
# ==================================================
[docs] def create_k_multipole(cluster_samb, cluster_vector): """ Create momentum multipole. Args: cluster_samb (dict): cluster SAMB. cluster_vector (dict): cluster vector. Returns: - (dict) -- momentum multipole in terms of k.b_n, dict[wyckoff, dict[idx, (k_multipole, symmetry)] ]. - (dict) -- cluster vector, dict[site/bond name, dict[kb, expression] ]. """ k_multipole = {} for k, v in cluster_samb.items(): if "@" in k: # bond. d = len(next(iter(v.values()))[0][0]) kb = np.array([sp.Symbol(f"p_{i+1}", real=True) for i in range(d)], dtype=object) c = list(map(sp.cos, kb)) s = list(map(sp.sin, kb)) d_wp = {} for idx, (samb, sym) in v.items(): if idx[0] == "Q": d_wp[idx] = (sp.sqrt(2) * np.vectorize(sp.re)(samb) @ c, sym) else: d_wp[idx] = (sp.sqrt(2) * np.vectorize(sp.im)(samb) @ s, sym) k_multipole[k] = d_wp else: # site. k_multipole[k] = v kb_dic = {} kv = np.array([sp.Symbol(f"k_{i}", real=True) for i in range(1, 4)], dtype=object) for sb, lst in cluster_vector.items(): if ";" in sb: d = len(lst) kb = np.array([sp.Symbol(f"p_{i+1}", real=True) for i in range(d)], dtype=object) kb_dic[sb] = {i: j @ kv for i, j in zip(kb, lst)} else: kb_dic[sb] = {} return k_multipole, kb_dic
# ==================================================
[docs] def create_k_matrix(matrix, cluster_dict, vector_dict): """ Create momentum matrix. Args: matrix (dict): O(R) matrix dict. cluster_dict (dict): cluster dict. vector_dict (dict): vector dict. Returns: - (dict) -- momentum matrix, dict[tag, dict[(m,n), value] ]. Notes: - only tight-binding gauge is supported. """ k_matrix = {} for tag in matrix.keys(): cluster = cluster_dict[tag] OR = matrix[tag] if ";" in cluster: vec = vector_dict[cluster] mat = defaultdict(lambda: sp.S(0)) kb = np.array([sp.Symbol(f"p_{i+1}", real=True) for i in range(len(vec))], dtype=object) for (n1, n2, n3, m, n), (value, b_no) in OR.items(): k = kb[b_no - 1] if b_no > 0 else -kb[-b_no - 1] mat[(m, n)] += value * (sp.cos(k) + sp.I * sp.sin(k)) mat = {Rmn: simplify(v) for Rmn, v in mat.items() if not v.is_zero} k_matrix[tag] = mat else: k_matrix[tag] = {(m, n): v for (n1, n2, n3, m, n), (v, b) in OR.items()} return k_matrix
# ==================================================
[docs] def check_same_orbital_block(ket): """ Check same orbital block for all atoms. Args: ket (list): ket list. Returns: - (bool) -- same block ? - (int) -- block size. """ d = {} for atom, sl, rank, comp, orb in ket: d[atom] = d.get(atom, []) + [orb] d = {atom: tuple(sorted(list(set(lst)))) for atom, lst in d.items()} orb_set = list(set(d.values())) same = len(orb_set) == 1 orb_dim = len(orb_set[0]) return same, orb_dim
# ==================================================
[docs] def add_local_parameter(matrix_info, parameter, ket): """ Add local parameter for given nonlocal parameter. Args: matrix_info (dict): matrix info. parameter (dict): parameter dict without site cluster. ket (list): ket list. Returns: - (dict) -- parameter dict with adding local one. """ same, d = check_same_orbital_block(ket) if not same: return dim = matrix_info["dimension"] nn = dim // d local = {} local_z = {} for tag, mat in matrix_info["matrix"].items(): v = np.full((dim, dim), 0.0, dtype=complex) for (n1, n2, n3, m, n), (val, no) in mat.items(): v[m, n] += complex(val) if ";" in matrix_info["cluster"][tag]: # nonlocal SAMB with parameter key. if tag not in parameter.keys(): continue vd = v.reshape(nn, d, nn, d).sum(axis=0).transpose(1, 0, 2) s = np.full((dim, dim), 0.0, dtype=complex) for i in range(nn): s[i * d : (i + 1) * d, i * d : (i + 1) * d] = vd[i] local[tag] = s else: # local SAMB. local_z[tag] = v coeff = {tag: np.array([np.real(np.einsum("ij,ji->", z, s)) for z in local_z.values()]) for tag, s in local.items()} zt = np.full(len(local_z.keys()), 0.0) for zj, val in parameter.items(): if zj not in local_z.keys(): zt -= val * coeff[zj] for zk, val in zip(local_z.keys(), zt): if abs(val) > 1e-8: parameter[zk] = float(val) parameter = dict(sorted(parameter.items(), key=lambda x: int(x[0][1:]))) return parameter
# ==================================================
[docs] def add_local_parameter_sym(matrix_info, ket): """ Add local parameter for given nonlocal parameter. Args: matrix_info (dict): matrix info. ket (list): ket list. Returns: - (dict) -- parameter dict with adding local one. """ same, d = check_same_orbital_block(ket) if not same: return dim = matrix_info["dimension"] nn = dim // d local = {} nonlocal_z = [] local_z = {} for tag, mat in matrix_info["matrix"].items(): v = np.full((dim, dim), sp.S(0)) for (n1, n2, n3, m, n), (val, no) in mat.items(): v[m, n] += val if ";" in matrix_info["cluster"][tag]: # nonlocal SAMB with parameter key. vd = v.reshape(nn, d, nn, d).sum(axis=0).transpose(1, 0, 2) s = np.full((dim, dim), sp.S(0)) for i in range(nn): s[i * d : (i + 1) * d, i * d : (i + 1) * d] = vd[i] local[tag] = s nonlocal_z.append(tag) else: # local SAMB. local_z[tag] = v coeff = {tag: np.array([np.einsum("ij,ji->", z, s) for z in local_z.values()]) for tag, s in local.items()} zt = np.full(len(local_z.keys()), sp.S(0)) for zj in nonlocal_z: zjv = sp.Symbol(zj, real=True) zt -= zjv * coeff[zj] parameter = {} for zk, val in zip(local_z.keys(), zt): if not val.is_zero: parameter[zk] = str(val).replace(" ", "") parameter = dict(sorted(parameter.items(), key=lambda x: int(x[0][1:]))) return parameter
# ==================================================
[docs] def solve_z(Z_dict, names, simplify=True): """ Solve z parameter in terms of atomic parameters on bond 1. Args: Z_dict (dict): bond-1 basis, dict[(m,n), val]. names (list): name of each ket, used for the atomic variables g_{m,n} and h_{m,n}. simplify (bool, optional): simplify result ? Returns: - (dict) -- z parameter. """ j_names = list(Z_dict.keys()) mn_keys = sorted({mn for d in Z_dict.values() for mn in d}) N, M = len(j_names), len(mn_keys) Z = sp.Matrix(M, N, lambda r, c: Z_dict[j_names[c]].get(mn_keys[r], 0)) g = [sp.Symbol(f"g_{{{names[m]},{names[n]}}}", real=True) for m, n in mn_keys] h = [sp.Symbol(f"h_{{{names[m]},{names[n]}}}", real=True) for m, n in mn_keys] gg = sp.Matrix([gi + sp.I * hi for gi, hi in zip(g, h)]) normal_mat = sp.re(Z.H * Z) # N x N real symmetric. rhs = sp.re(Z.H * gg) # N x 1 (including re(g_mn), im(g_mn)) z_vec = normal_mat.pinv(method="RD") * rhs # 'RD' is robust for analytic matrix. if simplify: z_vec = sp.simplify(z_vec) return {j_names[i]: z_vec[i] for i in range(N)}
# ==================================================
[docs] def short_orbital_name(orbital, rank, basis_type): """ Short orbital name for the atomic variables (ASCII). Args: orbital (str): orbital of the ket, e.g., "pz", "(px,u)", "(3/2,1/2)". rank (int): orbital rank. basis_type (str): basis type, "lg/lgs/jml". Returns: - (str) -- short name, e.g., "pz", "pxu" (lgs), "p(3/2,1/2)" (jml). """ if basis_type == "lgs": # (px,u) -> pxu. o, s = orbital.strip("()").split(",") return o + s if basis_type == "jml": # (3/2,1/2) of p -> p(3/2,1/2), as p and d have the same (j,m). return "spdf"[rank] + orbital return orbital
# ==================================================
[docs] def convert_zj_atomic_var(matrix_info, combined_cluster, combined_id, IR, full_ket, basis_type): """ Convert from zj to atomic variable. Args: matrix_info (dict): matrix info. combined_cluster (dict): combined cluster. combined_id (dict): combined id. IR (str): identity irrep. full_ket (list): kets of the full matrix, [(atom, sublattice, rank, basis_idx, orbital)]. basis_type (str): basis type, "lg/lgs/jml". Returns: - (dict) -- zj to var for each cluster, dict[bond name, dict["bond" or zj, (head site, tail site) or var] ]. Note: - "bond" is (head site, tail site) of bond 1, e.g., ("C(2)", "C(1)"). - the atomic variables are g_{head orbital,tail orbital} and h_{...}, H_{head,tail} = g + i h at bond 1, with the short orbital names (short_orbital_name). """ ket = [short_orbital_name(orbital, rank, basis_type) for atom, sl, rank, idx, orbital in full_ket] site = [f"{atom}({sl})" for atom, sl, rank, idx, orbital in full_ket] # classify zj for each cluster (only the selected SAMBs, which are in the matrix). cluster = {} for tag, name in combined_cluster.items(): if tag not in matrix_info["matrix"]: continue X = combined_id[tag][2][0] Gamma = combined_id[tag][2][2] if ";" in name and X in ["Q", "G"] and Gamma == IR: cluster.setdefault(name, []).append(tag) # construct bond1-projected matrix. dic = {} for name, tags in cluster.items(): d = {} for zj in tags: # only representative bond 1. d[zj] = {(m, n): val for (n1, n2, n3, m, n), (val, no) in matrix_info["matrix"][zj].items() if no == 1} dic[name] = d # solve zj for each cluster. result = {} for name, d in dic.items(): mn = {mn for v in d.values() for mn in v} head = {site[m] for m, n in mn} tail = {site[n] for m, n in mn} if len(head) != 1 or len(tail) != 1: raise ValueError(f"bond 1 of {name} connects more than one pair of sites: {sorted(head)}, {sorted(tail)}.") result[name] = {"bond": (head.pop(), tail.pop())} | solve_z(d, ket) return result
# ==================================================
[docs] def read_text_data(filename): """ Read text data. Args: filename (str): file name. Returns: - (list) -- block of data (ndarray) separated by empty line, [block][x, y]. """ bands = [] band = [] with open(filename, "r") as f: for line in f: line = line.strip() # skip comment. if line.startswith("#"): continue # each block ends with empty line. if line == "": if band: bands.append(np.array(band)) band = [] continue band.append([float(x) for x in line.split()]) # last block. if band: bands.append(np.array(band)) return bands
# ==================================================
[docs] def is_almost_zero(x): """ Check if x is numerically zero (within a tolerance). """ return np.abs(x) < M_ZERO * 100
# ==================================================
[docs] def kelvin_to_ev(T_kelvin): """ Convert temperature from Kelvin to eV (k_B * T). """ return T_kelvin * k_B_SI / elem_charge_SI
# ==================================================
[docs] def fermi_dirac(x, T=0.0, unit="Kelvin"): """ Fermi-Dirac distribution function, f(x) = 1 / (1 + exp(x/T)). Args: x (ndarray): energy relative to the chemical potential (E - mu), in eV. T (float, optional): temperature (Kelvin or eV, see `unit`). unit (str, optional): unit of T, "Kelvin" or "eV". Returns: - (ndarray) -- Fermi-Dirac occupation, 0 <= f(x) <= 1. """ if T == 0.0: return np.where(x < 0.0, 1.0, np.where(x > 0.0, 0.0, 0.5)) T_eV = kelvin_to_ev(T) if unit == "Kelvin" else T return 0.5 * (1.0 - np.tanh(0.5 * x / T_eV))
# ==================================================
[docs] def fermi_dirac_deriv(x, T=0.01, unit="Kelvin"): """ Minus the derivative of the Fermi-Dirac distribution w.r.t. x, -df/dx = f(x)*f(-x)/T. A positive, bell-shaped function peaked at x=0 (used e.g. for smearing/DOS broadening). Args: x (ndarray): energy relative to the chemical potential (E - mu), in eV. T (float, optional): temperature (Kelvin or eV, see `unit`). Must be nonzero. unit (str, optional): unit of T, "Kelvin" or "eV". Returns: - (ndarray) -- -df/dx. """ T_eV = kelvin_to_ev(T) if unit == "Kelvin" else T return fermi_dirac(x, T, unit) * fermi_dirac(-x, T, unit) / T_eV
# ==================================================
[docs] def fermi_dirac_deriv2(x, T=0.01, unit="Kelvin"): """ Second derivative of the Fermi-Dirac distribution w.r.t. x, -d^2f/dx^2 (i.e. the derivative of `fermi_dirac_deriv`). Args: x (ndarray): energy relative to the chemical potential (E - mu), in eV. T (float, optional): temperature (Kelvin or eV, see `unit`). Must be nonzero. unit (str, optional): unit of T, "Kelvin" or "eV". Returns: - (ndarray) -- -d^2f/dx^2. """ T_eV = kelvin_to_ev(T) if unit == "Kelvin" else T return (1 - 2 * fermi_dirac(-x, T, unit)) * fermi_dirac(x, T, unit) * fermi_dirac(-x, T, unit) / T_eV / T_eV
# ==================================================
[docs] def convert_orbital_to_detail(tag): """ Convert orbital name to (rank, comp). Args: tag (str): "name" or "(name,u/d)". name = wannier90 or multipie. Returns: - (tuple) -- orbital (rank, comp, tag). """ rank_d = {"s": 0, "p": 1, "d": 2, "f": 3} wannier = Group.global_info()["harmonics"]["wannier90"] tesseral = Group.global_info()["harmonics"]["tesseral"] if tag.count(","): name, spin = tag.strip("()").split(",") basis = Group.global_info()["harmonics"]["atomic_basis"]["spinful"]["lgs"] else: name = tag basis = Group.global_info()["harmonics"]["atomic_basis"]["spinless"]["lg"] if name not in tesseral.keys(): name = wannier[name] rank = rank_d[name[0]] basis = basis[rank] comp = basis.index(tag) return (rank, comp, tag)