# 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/.
"""
Material model construction class.
This module provides material model construction.
"""
import os
import re
import inspect
import logging
import numpy as np
import sympy as sp
from itertools import product
from collections import defaultdict
from multipie import __version__, SAMBType, UniqueSAMBType
from multipie.core.group import Group
from multipie.util.util_binary import BinaryManager
from multipie.util.util import deep_update, time_stamp, check_latex, check_qtdraw, read_dict
from multipie.util.util_pdf_latex import PDFviaLaTeX, LaTeXError, tex_text
from multipie.util.util_crystal import get_cell_info, create_igrid, convert_to_primitive_vector
from multipie.util.util_material_model import (
get_basis_type,
get_bond,
get_tail_head,
get_neighbor_info,
create_site_grid,
create_site_so,
create_wyckoff_dict,
create_braket_dict,
create_full_matrix_info,
create_combined_cluster_info,
parse_representative_site,
parse_representative_bond,
write_site_dict,
write_bond_dict,
write_site_grid,
create_qtdraw,
parse_samb_select,
parse_combined_select,
SEARCH_CELL_RANGE,
REMOVED_MODEL_KEY,
)
from multipie.util.util_material_model_pdf import ModelPDF
from multipie.util.util_coset import coset_analysis, inversion_model, check_inversion_model
from multipie.util import util_coset
from multipie.core.default_model import default_model
from multipie.util.util import check_dict_keys
from multipie.util.util_plot import plot_site, plot_bond, plot_site_samb, plot_bond_samb, plot_harmonics
from multipie.util.util_samb_figure import draw_samb_figure, select_samb_figure, save_samb_png
logger = logging.getLogger(__name__)
# ==================================================
[docs]
class MaterialModel(BinaryManager):
# ==================================================
def __init__(self, topdir=None, verbose=False):
"""
Material model construction.
Args:
topdir (str, optional): top directory. [default: cwd]
verbose (bool, optional): verbose comment ?
"""
if topdir is None:
topdir = os.getcwd()
super().__init__(topdir=topdir, verbose=verbose)
# ==================================================
@property
def group(self):
"""
Group class.
Returns:
- (Group) -- group class.
"""
return self._group
# ==================================================
[docs]
def load(self, name):
"""
Load model.
Args:
name (str): model name.
"""
self.set_subdir(name)
self.load_binary(name + ".pkl")
version = str(self.get("version", "0"))
m = re.match(r"(\d+)", version)
if m is None or int(m[1]) < 3: # the group database (SAMB) of Ver.3 differs from that of Ver.2.
raise ValueError(
f"model '{name}' was created by MultiPie {version}, whose SAMB differ from those of MultiPie {__version__}. "
"Create the model again (e.g., mp_create), or convert a model of Ver.2 with mp_convert."
)
self._group = Group(self["group"])
self.__dict__.pop("_coset_cache", None)
# ==================================================
[docs]
def save(self):
"""
Save model data in subdir.
"""
self.set_subdir(self["model"])
self.save_binary(self["model"], detail=False)
# ==================================================
[docs]
def save_view(self):
"""
Save model view QtDraw file.
"""
if self["qtdraw_prop"]["create"] and not check_qtdraw():
if self.verbose:
print("QtDraw not found; skipping .qtdw output.")
return
if self["qtdraw_prop"]["create"]:
from qtdraw import create_qtdraw_file
cwd = os.getcwd()
path = self.get_cwd()
filename = self["model"]
os.chdir(path)
try:
create_qtdraw_file(
filename=f"{filename}.qtdw",
callback=lambda qtdraw: create_qtdraw(
qtdraw, self.group, filename, self["cell_info"], self["site"], self["bond"], self["qtdraw_prop"]
),
)
finally:
os.chdir(cwd)
if self.verbose:
print(f"save qtdraw to '{path}/{filename}.qtdw'.")
# ==================================================
[docs]
def save_pdf(self, verbose=None):
"""
Save model as PDF file.
"""
if verbose is None:
verbose = self.verbose
if self["pdf_ctrl"]["create"] and not check_latex():
if verbose:
print("LaTeX not found; skipping PDF output.")
return
if self["pdf_ctrl"]["create"]:
cwd = os.getcwd()
path = os.path.abspath(self.get_cwd())
os.chdir(path)
filename = self["model"]
try:
pdf = PDFviaLaTeX(filename, landscape=True, english=True, dir=path)
ModelPDF(self, pdf)
except LaTeXError as e:
logger.warning(f"skip PDF creation: {e}")
return
finally:
os.chdir(cwd)
if verbose:
print(f"save PDF to '{path}/{filename}.pdf'.")
# ==================================================
def save_samb_figure(self, tag, png=False):
"""
Save QtDraw file of an atomic (x), cluster (y) or combined (z) SAMB, "<model>_<tag>.qtdw" (and ".png").
Args:
tag (str or list): (list of) SAMB tag, e.g. "x1", "y2", "z3".
png (bool, optional): save also PNG ?
Note:
- the SAMBs are drawn one after another in one off-screen widget (creating and closing a widget for each
file takes much longer than drawing).
:meta private:
"""
if check_qtdraw() and self["qtdraw_prop"]["create"]:
from qtdraw import create_qtdraw_file
tags = [tag] if isinstance(tag, str) else list(tag)
if not tags:
return
names = [os.path.abspath(f"{self['model']}_{t}") for t in tags]
# QtDraw 3.4.2 or later: skip the formatting of each file by black (a subprocess).
fmt = {"formatted": False} if "formatted" in inspect.signature(create_qtdraw_file).parameters else {}
def draw(qtdraw):
for t, name in zip(tags, names):
draw_samb_figure(qtdraw, self, t)
if png:
try:
save_samb_png(qtdraw, f"{name}.png", self["qtdraw_prop"]["view"])
except Exception as e: # e.g. no OpenGL for off-screen rendering.
logger.warning(f"skip PNG of {t}: {e}")
if t != tags[-1]:
qtdraw.save(f"{name}.qtdw", **fmt)
create_qtdraw_file(filename=f"{names[-1]}.qtdw", callback=draw, **fmt) # the last one is saved here.
# ==================================================
[docs]
def save_samb_qtdraw(self, samb_figure=True, png=False, verbose=None):
"""
Save SAMB QtDraw files in "<model>/samb/".
Args:
samb_figure (bool or list, optional): True for all the atomic SAMBs, and the cluster and combined SAMBs of the
sites and of the bonds with neighbor < qtdraw/max_neighbor, or list of SAMB tags (x: atomic, y: cluster,
z: combined), e.g. ["x1", "y2", "z3"].
png (bool, optional): save also PNG files "<model>_<tag>.png" ?
verbose (bool, optional): verbose ?
Notes:
- The file of each SAMB is "<model>_<tag>.qtdw".
- The polar (Q, T) and the axial (G, M) parts of the atomic SAMB are drawn separately: lobes colored by
sign for polar parts, and translucent lobes with axial-vector arrows for axial parts (see
util_samb_figure). A cluster SAMB is drawn as a combined SAMB with the atomic SAMB Q0.
"""
if verbose is None:
verbose = self.verbose
if samb_figure is False:
return
tags = select_samb_figure(self, samb_figure) # check before the other conditions.
if not check_qtdraw():
logger.warning("QtDraw not found; skipping SAMB .qtdw output.")
return
if not self["qtdraw_prop"]["create"]:
logger.warning("'qtdraw/create' of the model is False; skipping SAMB .qtdw output.")
return
cwd = os.getcwd()
path = self.get_cwd()
os.makedirs(os.path.join(path, "samb"), exist_ok=True)
os.chdir(os.path.join(path, "samb"))
try:
self.save_samb_figure(tags, png)
finally:
os.chdir(cwd)
if verbose:
print(f"save SAMB QtDraw files in '{self.get_cwd()}/samb/'.")
# ==================================================
[docs]
def get_samb_matrix(self, select):
"""
Get SAMB matrix.
Args:
select (dict): select dict (see, select_combined_samb).
Returns:
- (dict) -- matrix info.
"""
_, samb_select, _select = self.select_combined_samb(select)
regularized_select = samb_select | _select
matrix = self.get_combined_samb_matrix(select)
ket_site = self.get_ket_site()
matrix_info = {
"model": self["model"],
"source": f"{self['model']}.pkl",
"created": f"{self['created']}",
"select": regularized_select,
"dimension": len(ket_site),
"ket": list(ket_site.keys()),
"ket_pos": list(ket_site.values()),
"index": self["full_matrix"]["index"],
"vector": self["cluster_vector"],
"cluster": self["combined_cluster"],
"matrix": matrix,
}
return matrix_info
# ==================================================
[docs]
def analyze(self, model_in):
"""
Set model.
Args:
model_in (dict or str): model input dict or file name.
"""
if isinstance(model_in, str):
if self.verbose:
print(f"read '{model_in}'.")
model_in = read_dict(model_in, self.topdir)
self.clear()
# keys removed in Ver.3: the bond search range and the max. neighbor are set from "bond".
for key in REMOVED_MODEL_KEY:
if key in model_in:
raise ValueError(
f"'{key}' is removed in MultiPie Ver.3: the neighbors are given by 'bond' only, "
"and the bond search range is set automatically. Delete it from the model input."
)
# check unknown keys, e.g., typo.
select_key = ["X", "l", "Gamma", "s"]
check_dict_keys(
model_in,
default_model,
name=f"model '{model_in.get('model', default_model['model'])}'",
allowed={
"cell": ["a", "b", "c", "alpha", "beta", "gamma"],
"SAMB_select": select_key,
"atomic_select": select_key,
"site_select": select_key,
"bond_select": select_key,
},
free=["site"],
)
# set model based on default model.
model = {}
deep_update(model, default_model)
deep_update(model, model_in)
# get basic data.
cell = model["cell"]
site_data = model["site"]
if not isinstance(site_data, dict) or not site_data:
raise ValueError(f"model '{model['model']}': no site is given in 'site'.")
# '_' and ';' are used in the names of site and bond clusters.
bond_sites = {tag for b in model["bond"] if isinstance(b, (tuple, list)) for tag in b[:2]}
for name, value in site_data.items():
if not isinstance(name, str) or not name or ";" in name:
raise ValueError(f"model '{model['model']}': site name {name!r} must be a non-empty string without ';'.")
if "_" in name and name in bond_sites:
raise ValueError(f"model '{model['model']}': site name {name!r} used in bond must not contain '_'.")
if not isinstance(value, (tuple, list)) or len(value) != 2:
raise ValueError(f"model '{model['model']}': site '{name}' must be (position, orbital), but {value!r} is given.")
bond_data = model["bond"]
spinful = model["spinful"]
toroidal_priority = model["toroidal_priority"]
samb_select = model["SAMB_select"]
atomic_select = model["atomic_select"]
site_select = model["site_select"]
bond_select = model["bond_select"]
# set group data.
group = Group(model["group"])
if group.group_type not in ["PG", "SG"]: # cluster and combined SAMB are for PG/SG only.
raise ValueError(
f"model '{model['model']}': 'group' must be a point group (PG) or space group (SG), "
f"but {model['group']!r} is a magnetic group ({group.group_type})."
)
crystal = group.info.crystal
irrep = list(group.character["table"].keys())
samb_select = parse_samb_select(samb_select, irrep)
atomic_select = parse_samb_select(atomic_select, irrep)
site_select = parse_samb_select(site_select, irrep)
bond_select = parse_samb_select(bond_select, irrep)
basis_type = get_basis_type(site_data, spinful)
basis_list = ["jml", "lgs", "lg"]
basis_info = {k: group.atomic_basis(k) for k in basis_list}
basis_info_type = group.atomic_basis(basis_type)
# set cell data.
cell_info = get_cell_info(crystal, cell)
G = cell_info["G"][0:3, 0:3]
# set grid data.
if group.is_point_group:
igrid = None
else:
igrid = create_igrid(SEARCH_CELL_RANGE) # initial range, enlarged per bond if needed.
# set site and bond.
site_dict = parse_representative_site(group, site_data, basis_type, basis_info)
site_grid = create_site_grid(site_dict, igrid)
site_so = create_site_so(group, site_dict)
bond_dict = parse_representative_bond(group, G, site_grid, site_so, site_dict, bond_data, self.verbose)
# inversion model: the image of the model under the first coset (inversion) of a chiral group.
inversion_info = None
if model["create_inversion_model"]:
first = group.coset
if first is None or first["kind"] != "inversion":
print(
f"model '{model['model']}': 'create_inversion_model' is ignored, "
f"as the first coset of {group} is not the inversion (the group is not chiral or has no parent)."
)
else:
image_group, site_data, rep_bond_given, inversion_info = inversion_model(group, site_data, site_dict, bond_dict)
group = Group(image_group)
irrep = list(group.character["table"].keys())
samb_select = parse_samb_select(model["SAMB_select"], irrep)
atomic_select = parse_samb_select(model["atomic_select"], irrep)
site_select = parse_samb_select(model["site_select"], irrep)
bond_select = parse_samb_select(model["bond_select"], irrep)
basis_info = {k: group.atomic_basis(k) for k in basis_list}
basis_info_type = group.atomic_basis(basis_type)
site_dict = parse_representative_site(group, site_data, basis_type, basis_info)
site_grid = create_site_grid(site_dict, igrid)
site_so = create_site_so(group, site_dict)
bond_dict = parse_representative_bond(
group, G, site_grid, site_so, site_dict, bond_data, self.verbose, rep_bond_given=rep_bond_given
)
check_inversion_model(inversion_info, site_dict, bond_dict, not group.is_point_group)
inversion_info["model"] = model["model"]
model["model"] = model["model"] + "_inv"
A = cell_info["A"][0:3, 0:3].T
lattice = group.info.lattice
Ap = convert_to_primitive_vector(lattice, A)
# site_bond => wyckoff, braket.
wyckoff_dict = create_wyckoff_dict(site_dict["representative"], bond_dict["representative"])
braket_dict = create_braket_dict(site_dict["representative"], bond_dict["representative"], basis_info_type)
# information for full matrix.
full_mat_info = create_full_matrix_info(site_dict, basis_info_type)
# save information.
name = model["model"]
self._group = group
self["model"] = name
self["group"] = str(group)
self["crystal"] = crystal
self["unit_vector"] = A.tolist()
self["unit_vector_primitive"] = Ap.tolist()
self["basis_type"] = basis_type
self["cell_info"] = cell_info
self["toroidal_priority"] = toroidal_priority
self["SAMB_select"] = samb_select
self["atomic_select"] = atomic_select
self["site_select"] = site_select
self["bond_select"] = bond_select
self["site"] = site_dict
self["site_grid"] = site_grid
self["bond"] = bond_dict
self["wyckoff"] = wyckoff_dict
self["braket"] = braket_dict
self["full_matrix"] = full_mat_info
self["qtdraw_prop"] = model["qtdraw"]
self["pdf_ctrl"] = model["pdf"]
self["inversion_model"] = inversion_info
# SAMB.
atomic_samb, atomic_id = self.get_atomic_samb(atomic_select)
cluster_samb, cluster_id = self.get_cluster_samb(site_select, bond_select)
combined_samb, combined_id, combined_min_num, combined_num, common_id, cluster_info = self.get_combined_samb(
atomic_samb, cluster_samb, samb_select, toroidal_priority
)
zj_site_bond, site_bond_vector = create_combined_cluster_info(combined_id, bond_dict["cell"])
# save samb.
self["atomic_samb"] = atomic_samb
self["atomic_id"] = atomic_id
self["cluster_samb"] = cluster_samb
self["cluster_id"] = cluster_id
self["cluster_vector"] = site_bond_vector
self["combined_samb"] = combined_samb
self["combined_id"] = combined_id
self["combined_cluster"] = zj_site_bond
self["common_id"] = common_id
self["cluster_info"] = cluster_info
self["SAMB_number_min"] = combined_min_num
self["SAMB_number"] = combined_num
irrep_id = {
irrep: self.select_combined_samb(select={"Gamma": irrep})[0] for irrep in self.group.character["table"].keys()
}
self["irrep_id"] = irrep_id
# coset.
self["coset"] = coset_analysis(self, model["coset"], model["coset_weight"])
self["version"] = __version__
self["created"] = time_stamp()
comment = f"Model: {self['model']}\n"
comment += f"* Group: " + self.group.name() + "\n"
comment += f"* SAMB selection: {self['SAMB_select']}\n"
comment += f"* atomic selection: {self['atomic_select']}\n"
comment += f"* site-cluster selection: {self['site_select']}\n"
comment += f"* bond-cluster selection: {self['bond_select']}\n"
comment += f" {combined_min_num} (all {combined_num}) basis set"
self.add_comment(comment)
if self.verbose:
print(f"{combined_min_num} (all {combined_num}) SAMBs are created.")
# ==================================================
[docs]
def clear(self):
"""
Clear all data.
"""
super().clear()
self._group = None
self.__dict__.pop("_coset_cache", None)
# ==================================================
[docs]
def get_atomic_samb(self, select):
"""
Get all atomic SAMB.
Args:
select (dict): select dict.
Returns:
- (dict) -- atomic SAMB, dict[BraketInfoType, SAMB Dict].
- (dict) -- atomic id, dict["x#", (SAMB index, comp)].
"""
basis_type = self["basis_type"]
samb = {}
for lst in self["braket"].values():
for braket_info in lst:
if braket_info not in samb:
samb[braket_info] = self.group.atomic_samb(
basis_type, (braket_info.bh_rank, braket_info.kt_rank), (braket_info.bh_idx, braket_info.kt_idx)
).select(**select)
no = 1
atomic_id = {}
for bk_info, i in samb.items():
if bk_info.bh_rank > bk_info.kt_rank:
continue
for idx, (mat, ex) in i.items():
for c in range(len(ex)):
atomic_id[f"x{no}"] = (bk_info, idx, c)
no += 1
return samb, atomic_id
# ==================================================
[docs]
def get_cluster_samb(self, site_select, bond_select):
"""
Get all cluster SAMB.
Args:
site_select (dict): site select dict.
bond_select (dict): bond select dict.
Returns:
- (dict) -- cluster SAMB, dict[wyckoff, SAMB Dict].
- (dict) -- cluster id, dict["y#", (wyckoff, SAMB index, comp)].
"""
irreps = list(self.group.character["table"].keys())
# sort by multiplicity, and by name for the same multiplicity (the order of set changes from run to run).
wp_lst = sorted(
list(set([lst.wyckoff for lst in self["site"]["representative"].values()])), key=lambda i: (int(i[:-1]), i)
)
site_samb = {
wp: self.group.cluster_samb(wp)
.select(**site_select)
.sort(("Gamma", irreps), "l", "k", ("X", ["Q", "G", "T", "M"]), "n")
for wp in wp_lst
}
wp_lst = sorted(
list(set([lst.wyckoff for lst in self["bond"]["representative"].values()])),
key=lambda i: (int(i.split("@")[0][:-1]), i),
)
bond_samb = {
wp: self.group.cluster_samb(wp, "bond")
.select(**bond_select)
.sort(("Gamma", irreps), "l", "k", ("X", ["Q", "G", "T", "M"]), "n")
for wp in wp_lst
}
samb = site_samb | bond_samb
no = 1
cluster_id = {}
for wp, i in samb.items():
for idx, (mat, ex) in i.items():
for c in range(len(ex)):
cluster_id[f"y{no}"] = (wp, idx, c)
no += 1
return samb, cluster_id
# ==================================================
[docs]
def get_combined_samb(self, atomic_samb, cluster_samb, select, toroidal_priority=False):
"""
Get all combined SAMB.
Args:
atomic_samb (dict): all atomic SAMB, Dict[braket_info, SAMB].
cluster_samb (dict): alll cluster SAMB, Dict["site/bond", SAMB].
select (dict): SAMB select.
toroidal_priority (bool, optional): use (G,T) prior to (Q,M) in creation ?
Returns:
- (dict) -- combined SAMB (minimal), dict[SAMBType, SAMB].
- (dict) -- id to SAMB info, dict[str, (tag, UniqueSAMBType, component)].
- (int) -- no. of minimal SAMBs.
- (int) -- no. of all SAMBs.
- (dict) -- comomon id, dict[SAMBType, [id]].
- (dict) -- cluster info, dict[site/bond_name, dict[(bra_rank,ket_rank), (wyckoff,z_list)] ].
"""
# grouping and sorting site/bond relations.
samb_groups = {}
for sb, wp in self["wyckoff"].items():
tail, head = get_tail_head(sb)
neighbor, n = get_neighbor_info(sb)
for bk in self["braket"][sb]:
comb = SAMBType(head, tail, wp, bk)
samb_groups.setdefault(comb, []).append((neighbor, n))
# ensure deterministic order within groups.
samb_groups = {k: sorted(v) for k, v in samb_groups.items()}
# combined SAMB calculation.
combined_results = {}
for comb in samb_groups:
bra_orb = self["site"]["representative"][comb.head].orbital[comb.bk_info.bh_rank]
ket_orb = self["site"]["representative"][comb.tail].orbital[comb.bk_info.kt_rank]
# filtering cluster SAMB if orbitals differ.
c_s = cluster_samb[comb.wyckoff]
if comb.head != comb.tail and bra_orb != ket_orb:
c_s = c_s.select(X=["Q"])
combined_results[comb] = self.group.combined_samb(
atomic_samb[comb.bk_info].named_keys(), c_s.named_keys(), toroidal_priority, **select
)
# flatten and sort items (priority: Site(0) -> Bond(1)).
items = sorted(
[
(0 if nb == 0 else 1, c.tail, c.head, nb, n, c, i)
for c, nn_lst in samb_groups.items()
for i, (nb, n) in enumerate(nn_lst)
]
)
# global z-indexing.
combined_id, common_id_map = {}, {c: [[] for _ in v] for c, v in samb_groups.items()}
z_count = 0
for Gamma in self["SAMB_select"]["Gamma"]:
for _, tail, head, nb, n, comb, i in items:
sb_tag = tail if nb == 0 else get_bond(tail, head, nb, n)
res = combined_results[comb].select(Gamma=Gamma)
for idx in res.keys():
for comp, tag in enumerate(self.group.tag_multipole(idx, latex=True, superscript="c")):
z_count += 1
z_id = f"z{z_count}"
combined_id[z_id] = (tag, UniqueSAMBType(comb, nb, n), idx, comp)
common_id_map[comb][i].append((z_id, sb_tag))
# output formatting (common_id and cluster_info).
common_id = {
c: ([[z for z, _ in d] for d in data if d], [d[0][1] for d in data if d])
for c, data in common_id_map.items()
if any(data)
}
cluster_info = {}
for c, (z_lists, sb_list) in common_id.items():
for sb, z_list in zip(sb_list, z_lists):
cluster_info.setdefault(sb, {})[(c.bk_info.bh_rank, c.bk_info.kt_rank)] = (c.wyckoff, z_list)
min_no = sum(sum(len(v[0]) for v in res.values()) for res in combined_results.values())
return combined_results, combined_id, min_no, z_count, common_id, cluster_info
# ==================================================
def select_combined_samb(self, select):
"""
Select combined SAMB.
Args:
select (dict): select conditions for multipoles with keywords, "site/bond/X/l/Gamma/s".
Returns:
- (dict) -- selected combined IDs.
- (dict) -- SAMB select dict.
- (dict) -- other select dict.
Note:
- site = [(site, *[orbital_rank])]. (* omittable).
- bond = [(site1;site2, *rank1;rank2, *[neighbor])] or [(*site1;site2, *rank1;rank2, [neighbor])].
- X = Q/G/T/M, []=all.
- l = [0,1,2,3,4,5,6,7,8,9,10,11], []=all.
- Gamma = [irreps.], "IR"=identity, []=all.
- s = [0,1], []=all.
:meta private:
"""
irrep = list(self.group.character["table"].keys())
samb_select = self["SAMB_select"]
site_rep = self["site"]["representative"]
bond_rep = self["bond"]["representative"]
samb_select, select = parse_combined_select(select, irrep, samb_select, site_rep, bond_rep)
combined_id = {}
for zi, (tag, samb_info, idx, comp) in self["combined_id"].items():
st = samb_info.samb_type
bk = st.bk_info
is_site = "@" not in st.wyckoff
is_match = False
if is_site:
is_match = any(st.head == s and bk.bh_rank in r for s, r in select["site"])
else:
for h, t, nr, hr, tr in select["bond"]:
if samb_info.neighbor != nr:
continue
if (st.head == h and st.tail == t and bk.bh_rank in hr and bk.kt_rank in tr) or (
st.head == t and st.tail == h and bk.bh_rank in tr and bk.kt_rank in hr
):
is_match = True
break
if is_match:
if idx in self["combined_samb"][st].select(**samb_select).keys():
if tag in self.group.tag_multipole(idx, latex=True, superscript="c"):
combined_id[zi] = (tag, samb_info, idx, comp)
return combined_id, samb_select, select
# ==================================================
[docs]
def get_combined_samb_matrix(self, select=None, fmt="sympy", digit=14, bond=True):
"""
Get combined SAMBs in matrix form (real-space).
Args:
select (dict, optional): select conditions for multipoles with keywords (see, select_combined_samb).
fmt (str, optional): sympy/value.
digit (int, optional): digit for value output.
bond (bool, optional): include bond_d ?
Returns:
- (dict) -- combined SAMB in matrix form, dict[zj, dict[ (n1, n2, n3, m, n), (matrix element, bond_no)] ].
Note:
- R = (n1,n2,n3) and m and n are lattice indices (corresponding to bond_no), bra and ket indexes, respectively.
"""
if fmt not in ["sympy", "value"]:
raise KeyError(f"Unknown format: {fmt}")
combined_id, _, _ = self.select_combined_samb(select)
return self._combined_samb_matrix(combined_id, fmt, digit, bond)
# ==================================================
def _combined_samb_matrix(self, combined_id, fmt="sympy", digit=14, bond=True):
"""
Get the given combined SAMBs in matrix form (real-space).
Args:
combined_id (dict): combined IDs, dict[zj, (symbol, UniqueSAMBType, index, comp)], e.g., a part of self["combined_id"].
fmt (str, optional): sympy/value.
digit (int, optional): digit for value output.
bond (bool, optional): include bond_d ?
Returns:
- (dict) -- combined SAMB in matrix form (see, get_combined_samb_matrix).
Note:
- only the data of the model is used (not the group), so that the SAMB of a model of Ver.2 can be built.
:meta private:
"""
def _format_val(v):
expanded_v = sp.expand(v)
if fmt == "value":
c_val = complex(expanded_v)
return round(c_val.real, digit) + round(c_val.imag, digit) * 1j
return expanded_v
if fmt not in ["sympy", "value"]:
raise KeyError(f"Unknown format: {fmt}")
full_matrix_idx = self["full_matrix"]["index"]
atomic_samb_data = self["atomic_samb"]
cluster_samb_data = self["cluster_samb"]
# kets of plus_set-1 sites for each site name.
ket_list = {}
for o in self["full_matrix"]["ket"]:
if o[1] == 1:
ket_list.setdefault(o[0], []).append(o)
matrix = {}
for zi, (s_symbol, u_samb_type, index, comp) in combined_id.items():
st = u_samb_type.samb_type
wp = st.wyckoff
tail, head = st.tail, st.head
bk = st.bk_info
b_rank, k_rank = bk.bh_rank, bk.kt_rank
b_idx, k_idx = bk.bh_idx, bk.kt_idx
is_site = "@" not in wp
if is_site:
c_info = self["site"]["cell"][tail]
else:
bond_name = get_bond(tail, head, u_samb_type.neighbor, u_samb_type.n)
c_info = self["bond"]["cell"][bond_name]
# Retrieve linear combination (lc) and symmetry (sym) info
lc_list, sym_list = self["combined_samb"][st][index]
lc = lc_list[comp]
a_samb = atomic_samb_data[bk]
c_samb = cluster_samb_data[wp]
# collect the terms of each matrix element, and sum them at once (adding sympy terms one by one is slow).
terms = defaultdict(list)
bond_d = {}
for cg, t1, c1, t2, c2 in lc:
atomic_matrix = a_samb[t1][0][c1] # X matrix
cluster_coeffs = c_samb[t2][0][c2] # Y coefficients
for yi, bi in zip(cluster_coeffs, c_info):
if is_site:
h_sl = t_sl = bi.sublattice
n1 = n2 = n3 = 0
else:
h_sl, t_sl = bi.h_idx[0], bi.t_idx[0]
n1, n2, n3 = bi.R_primitive
b_top, b_dim = full_matrix_idx[(head, h_sl, b_rank)]
k_top, k_dim = full_matrix_idx[(tail, t_sl, k_rank)]
# pre-calculate the scalar multiplier for this sub-block.
scale = cg * yi
for r in range(b_dim):
row_idx = b_top + r
for c in range(k_dim):
val = scale * atomic_matrix[r, c]
if val != 0:
terms[(n1, n2, n3, row_idx, k_top + c)].append(val)
bond_d[(n1, n2, n3, row_idx, k_top + c)] = 0 if is_site else bi.no
if not is_site:
if head == tail and (b_rank, b_idx) != (k_rank, k_idx):
if h_sl == t_sl:
b2_top, k2_top = k_top, b_top
else:
bra_orb = [o for o in ket_list[head] if o[2] == b_rank][0]
ket_orb = [o for o in ket_list[head] if o[2] == k_rank][0]
delta = ket_list[head].index(ket_orb) - ket_list[head].index(bra_orb)
b2_top = b_top + delta
k2_top = k_top - delta
for r, c in product(range(k_dim), range(b_dim)):
terms[(n1, n2, n3, b2_top + r, k2_top + c)].append(cg * yi * atomic_matrix[c, r].conjugate())
bond_d[(n1, n2, n3, b2_top + r, k2_top + c)] = 0 if is_site else bi.no
d = {Rmn: sp.Add(*t) for Rmn, t in terms.items()}
# add hermite conjugate elements.
hc = defaultdict(list)
for (n1, n2, n3, m, n), val in d.items():
hc[(-n1, -n2, -n3, n, m)].append(sp.conjugate(val))
bond_d[(-n1, -n2, -n3, n, m)] = -bond_d[(n1, n2, n3, m, n)]
for Rmn, t in hc.items():
d[Rmn] = sp.Add(d.get(Rmn, sp.S(0)), *t)
norm_sq = sp.Add(*[v * sp.conjugate(v) for v in d.values()])
norm = sp.sqrt(sp.expand(norm_sq))
matrix[zi] = {
Rmn: (_format_val(v / norm), bond_d[Rmn]) if bond else _format_val(v / norm)
for Rmn, v in d.items()
if not v.is_zero
}
matrix = dict(sorted(matrix.items(), key=lambda x: int(x[0][1:])))
return matrix
# ==================================================
def _coset_space(self, op=None, parent=None, embedding=None):
"""the parent, embedding, g, parent structure (util_coset.resolve_coset) and the image space, cached."""
key = (parent, op if op is None or isinstance(op, str) else repr(np.asarray(op).tolist()), repr(embedding))
cache = self.__dict__.setdefault("_coset_cache", {})
if key not in cache:
rc = util_coset.resolve_coset(self, parent, op, embedding)
cache[key] = (rc, util_coset.image_space(self, rc))
return cache[key]
# ==================================================
# ==================================================
[docs]
def image_overlap(self, op=None, parent=None, embedding=None):
"""
Get S_kj = <Z_k, g Z_j>, its eigenvalues and eigenvectors.
Args:
op (str or array, optional): g (see transform_samb).
parent (str, optional): supergroup P (see transform_samb).
embedding (None, int, dict or array, optional): embedding (see transform_samb).
Returns:
- (dict) -- "parent", "rep", "order" n, "embedding" (None for the parents of the binaries), "samb" ([z]),
"S" (ndarray, S[k, j]), "eigenvalue", "eigenvector" (columns), "projection" ([n Pi^(m)] for m = 0..n-1,
see parent_forbidden_part), "complete" (every g^t Z_j lies on the bonds of the model), "shell"
(parent_shells), "parent_structure".
Note:
- S is a constant matrix of the model and g; its diagonal is w(+) - w(-) of "weight" (order 2).
- S gives <g Z_j> = sum_k S_kj <Z_k> for a state invariant under H only if the model contains the whole
neighbor shells of the parent structure ("complete").
"""
rc, sp_ = self._coset_space(op, parent, embedding)
S, _ = util_coset.overlap_matrix(sp_)
Pm, complete = util_coset.projected_matrix(sp_, rc["order"])
if rc["order"] == 2 and np.allclose(S, np.conj(S.T), atol=1e-8):
w, v = np.linalg.eigh((S + np.conj(S.T)) / 2)
else:
w, v = np.linalg.eig(S)
return {
"parent": rc["parent"],
"rep": rc["rep"],
"order": rc["order"],
"embedding": rc["embedding"],
"samb": list(sp_["zs"]),
"S": S,
"eigenvalue": np.where(np.abs(w) < 1e-12, 0, w) + 0,
"eigenvector": v,
"projection": Pm,
"complete": complete,
"shell": util_coset.parent_shells(self, rc),
"parent_structure": rc["parent_structure"],
}
# ==================================================
[docs]
def parent_forbidden_part(self, expectation, op=None, parent=None, embedding=None, by_eigenvalue=False):
"""
Get F_j, the part of Z_j forbidden by the parent, from the expectation values <Z_k>.
Args:
expectation (dict or array): <Z_k>, {z: value} or in the order of the SAMB of the model.
op (str or array, optional): g (see transform_samb).
parent (str, optional): supergroup P (see transform_samb).
embedding (None, int, dict or array, optional): embedding (see transform_samb).
by_eigenvalue (bool, optional): give F_j^(m) for each eigenvalue w^m of g instead of F_j ?
Returns:
- (dict) -- {z: F_j}, or {z: [F_j^(m) for m = 0..n-1]} (by_eigenvalue).
Note:
- with the projections Pi_m = (1/n) sum_t w^(-m t) g^t (w = exp(2 pi i/n), n: order of g) on the parent
structure, F_j^(m) = n <Pi_m Z_j> = sum_k sum_t w^(-m t) S^(t)_kj <Z_k> (S^(t)_kj = <Z_k, g^t Z_j>) for a
state invariant under H, and F_j = sum_{m>0} F_j^(m) = n <Z_j> - sum_t <g^t Z_j> (real). F_j^(0) is the
part allowed by the parent, sum_m F_j^(m) = n <Z_j>.
- n = 2 (e.g., the inversion): F_j = <Z_j> - <g Z_j> = sum_k (delta_kj - S_kj) <Z_k>; 0 on the parent
structure, eps_j F_j in the inversion model, -F_j for the image state with the same matrix.
- a warning is given if the model does not contain the whole neighbor shells of the parent structure.
"""
rc, sp_ = self._coset_space(op, parent, embedding)
n = rc["order"]
Pm, complete = util_coset.projected_matrix(sp_, n)
zs = sp_["zs"]
if isinstance(expectation, dict):
e = np.array([expectation.get(z, 0) for z in zs])
else:
e = np.asarray(expectation)
if len(e) != len(zs):
raise ValueError(f"expectation must have {len(zs)} values, but {len(e)} are given.")
if not complete:
logger.warning(
"the model does not contain the whole neighbor shells of the parent structure: F_j differs from "
"n <Z_j> - sum_t <g^t Z_j> (see image_overlap()['shell'])."
)
Fm = [M.T @ e for M in Pm]
clean = lambda v: (np.real(v) if np.allclose(np.imag(v), 0, atol=1e-12) else v).tolist()
if by_eigenvalue:
Fm = [clean(f) for f in Fm]
return {z: [Fm[m][j] for m in range(n)] for j, z in enumerate(zs)}
F = clean(sum(Fm[1:]))
return dict(zip(zs, F))
# ==================================================
[docs]
def parent_shells(self, parent=None, embedding=None):
"""
Get the neighbor shells of the parent structure and the neighbors of the model structure in each.
Args:
parent (str, optional): supergroup P (see transform_samb).
embedding (None, int, dict or array, optional): embedding (see transform_samb).
Returns:
- (dict) -- {(tail, head): [{"shell", "distance" (parent structure), "neighbor" ([n] of the model
structure), "model" ([n] in the bonds of the model), "complete"}]}.
"""
rc, _ = self._coset_space(None, parent, embedding)
return util_coset.parent_shells(self, rc)
# ==================================================
[docs]
def map_bond(self, op=None, parent=None, embedding=None):
"""
Get the bonds of the model moved by g on the parent structure.
Args:
op (str or array, optional): g (see transform_samb).
parent (str, optional): supergroup P (see transform_samb).
embedding (None, int, dict or array, optional): embedding (see transform_samb).
Returns:
- (dict) -- {bond: [{"bond": (tail atom, head atom, n), "image": (tail atom, head atom, n), "neighbor" (of the
image in the model structure), "distance"}]}, atoms: (site, sublattice), n: lattice vector
(conventional), for the bonds from the first tail atom.
"""
rc, _ = self._coset_space(op, parent, embedding)
return util_coset.map_bond(self, rc)
# ==================================================
[docs]
def X(self, tag, hc=False):
"""
Get atomic SAMB.
Args:
tag (str): atomic tag, e.g. x1.
hc (bool, optional): hermite conjugation ?
Returns:
- (ndarray) -- atomic SAMB matrix.
- (sympy) -- symmetry.
"""
if tag not in self["atomic_id"]:
return None
bk, index, comp = self["atomic_id"][tag]
mat, sym = self["atomic_samb"][bk][index]
mat = mat[comp]
sym = sym[comp]
if hc:
mat = np.array(sp.Matrix(mat).H)
return mat, sym
# ==================================================
[docs]
def Y(self, tag):
"""
Get site/bond-cluster SAMB.
Args:
tag (str): cluster tag, e.g., y1.
Returns:
- (ndarray) -- cluster SAMB vector.
- (sympy) -- symmetry.
"""
if tag not in self["cluster_id"]:
return None
wyckoff, index, comp = self["cluster_id"][tag]
vec, sym = self["cluster_samb"][wyckoff][index]
vec = vec[comp]
sym = sym[comp]
return vec, sym
# ==================================================
[docs]
def Z(self, tag, symbol=False):
"""
Get combined SAMB.
Args:
tag (str): combined tag, e.g., z1.
symbol (bool, optional): symbol expression ?
Returns:
- (list or sympy) -- combined SAMB linear combination list or expression.
- (sympy) -- symmetry.
- (str or sympy) -- symbol in LaTex or expression.
"""
if tag not in self["combined_id"]:
return None
s_symbol, u_samb_type, index, comp = self["combined_id"][tag]
clustar_str = "b" if u_samb_type.samb_type.wyckoff.count("@") > 0 else "s"
lc, sym = self["combined_samb"][u_samb_type.samb_type][index]
lc = lc[comp]
sym = sym[comp]
if symbol:
s_symbol = sp.Symbol(s_symbol)
ex = 0
for cg, t1, c1, t2, c2 in lc:
t1 = self.group.tag_multipole(t1, c1, latex=True, superscript="a")
t2 = self.group.tag_multipole(t2, c2, latex=True, superscript=clustar_str)
ex += cg * sp.Symbol(t1, commutative=False) * sp.Symbol(t2, commutative=False)
lc = ex
return lc, sym, s_symbol
# ==================================================
[docs]
def get_hr(self, parameter, combined_samb_matrix, fmt="sympy"):
"""
Get Hamiltonian matrix (real-space).
Args:
parameter (dict): parameter of SAMBs, dict[zj, float/sympy].
combined_samb_matrix (dict): combined SAMBs in matrix form (real-space), dict[zj, dict[(n1, n2, n3, m, n), (matrix element, bond_no)] ].
fmt (str, optional): sympy/value.
Returns:
- (dict) -- Hamiltonian matrix (real-space), dict[(n1, n2, n3, m, n), (matrix element, bond_no)].
Note:
- R = (n1,n2,n3) and m and n are a lattie vector (corresponding to bond_no), bra and ket indexes, respectively.
"""
# collect the terms of each matrix element, and sum them at once (adding sympy terms one by one is slow).
terms = defaultdict(list)
for zj, cj in parameter.items():
if zj not in combined_samb_matrix.keys():
raise ValueError(f"parameter {zj} is missing.")
d = combined_samb_matrix[zj]
for Rmn, (Zj, _) in d.items():
terms[Rmn].append(cj * Zj)
if fmt == "sympy":
return {Rmn: sp.Add(*t) for Rmn, t in terms.items()}
return {Rmn: sum(t, 0.0) for Rmn, t in terms.items()}
# ==================================================
[docs]
def get_multipole_expression(self):
"""
Get all of harmonics expression.
Returns:
- (dict) -- harmonics expression, dict[(X,Gamma,l,n), [expression]].
"""
amp = [v[:4] for v in sum([list(samb.keys()) for samb in self["atomic_samb"].values()], [])]
scmp = [v[:4] for v in sum([list(samb.keys()) for samb in self["cluster_samb"].values()], [])]
cmp = [v[:4] for v in sum([list(samb.keys()) for samb in self["combined_samb"].values()], [])]
lst = sorted(list(set(amp + scmp + cmp)), key=lambda i: (i[2], i[1], i[0], i[3]))
harmonics = self.group.harmonics
harmonics_lst = {}
for X, l, Gamma, n in lst:
X = X.replace("T", "Q").replace("M", "G")
idx = (X, l, Gamma, n, -1, 0, 0, "q")
if idx in harmonics.keys():
harmonics_lst[(X, Gamma, l, n)] = harmonics[idx][0]
# else: # should be never reached.
# raise Exception(f"cannot find idx={idx1[1:]}.")
return harmonics_lst
# ==================================================
[docs]
def get_ket_site(self):
"""
Get ket and corresponding site.
Returns:
- (dict) -- ket and site, dict[name, position].
"""
ket = [orbital + "@" + atom + f"({sl})" for atom, sl, rank, idx, orbital in self["full_matrix"]["ket"]]
site_dict = {
k + "_" + str(vi.sublattice): vi.position_primitive.tolist()
for k, v in self["site"]["cell"].items()
for vi in v
if vi.plus_set == 1
}
site = [site_dict[atom + "_" + str(sl)] for atom, sl, rank, idx, orbital in self["full_matrix"]["ket"]]
ket_site = dict(zip(ket, site))
return ket_site
# ==================================================
[docs]
def ket(self):
"""
Get ket string list.
Returns:
- (list) -- ket string in LaTeX.
"""
lst = []
for atom, sublattice, rank, idx, orbital in self["full_matrix"]["ket"]:
orb = self.group.tag_atomic_basis(orbital, rank, latex=True)
orb += "@" + r"{\rm " + tex_text(atom, math=True) + "}(" + str(sublattice) + ")"
lst.append(orb)
return lst
# ==================================================
[docs]
def cell_site_primitive(self):
"""
Get site position in primitive unit cell.
Returns:
- (dict) -- site dict, dict[name, [position]].
"""
lst = {
name: [i.position_primitive.tolist() for i in val if i.plus_set == 1] for name, val in self["site"]["cell"].items()
}
return lst
# ==================================================
def _write_site(self):
"""
Write site info.
"""
write_site_dict(self["site"])
# ==================================================
def _write_bond(self):
"""
Write bond info.
"""
write_bond_dict(self["bond"])
# ==================================================
def _write_grid(self):
"""
Write grid info.
"""
write_site_grid(self["site_grid"])
# ==================================================
def plot_site_bond(self, qtdraw, site_bond, rep=True):
"""
Plot definition of site or bond.
Args:
qtdraw (QtDraw): QtDraw object.
site_bond (str): site or bond, see "wyckoff".
rep (bool, optional): highlight representative ?
:meta private:
"""
if site_bond not in self["wyckoff"].keys():
raise KeyError(f"unknown site_bond, {site_bond}.")
if site_bond.count(";") > 0:
bonds = np.array([np.concat([i.vector, i.center]) for i in self["bond"]["cell"][site_bond]])
plot_bond(qtdraw, site_bond, bonds)
else:
sites = np.array([i.position for i in self["site"]["cell"][site_bond]])
plot_site(qtdraw, site_bond, sites, rep)
# ==================================================
def plot_cluster_samb(self, qtdraw, site_bond, cluster_id, label=True):
"""
Plot cluster SAMB.
Args:
qtdraw (QtDraw): QtDraw object.
site_bond (str): site or bond, see "wyckoff".
cluster_id (str): cluster id.
label (boo, optional): display label ?
:meta private:
"""
if site_bond not in self["wyckoff"].keys():
raise KeyError(f"unknown site_bond, {site_bond}.")
if cluster_id not in self["cluster_id"].keys():
raise KeyError(f"unknown cluster id, {cluster_id}.")
wp, idx, comp = self["cluster_id"][cluster_id]
if self["wyckoff"][site_bond] != wp:
raise KeyError(f"invalid wyckoff, {wp}.")
samb = self["cluster_samb"][wp][idx][0][comp]
if label:
qtdraw.add_text2d(f"idx = ({','.join(map(str,idx[:4]))},{comp})")
if site_bond.count(";") > 0:
bonds = np.array([np.concat([i.vector, i.center]) for i in self["bond"]["cell"][site_bond]])
sym = idx[0] not in ["T", "M"]
if not sym:
samb = np.vectorize(sp.im)(samb)
plot_bond_samb(qtdraw, cluster_id + "@" + site_bond, bonds, samb, sym, cluster_id)
else:
sites = np.array([i.position for i in self["site"]["cell"][site_bond]])
plot_site_samb(qtdraw, cluster_id + "@" + site_bond, sites, samb, cluster_id)
# ==================================================
def plot_atomic_samb(self, qtdraw, atomic_id, site_bond=None, label=True):
"""
Plot atomic SAMB.
Args:
qtdraw (QtDraw): QtDraw object.
atomic_id (str): atomic id.
site_bond (str, optional): site or bond, see "wyckoff".
label (boo, optional): display label ?
:meta private:
"""
conv_dict = {"Q": "Q", "G": "G", "T": "Q", "M": "G"}
if site_bond is not None and site_bond not in self["wyckoff"].keys():
raise KeyError(f"unknown site_bond, {site_bond}.")
if atomic_id not in self["atomic_id"].keys():
raise KeyError(f"unknown atomic id, {atomic_id}.")
bk_info, idx, comp = self["atomic_id"][atomic_id]
if label:
qtdraw.add_text2d(f"idx = ({','.join(map(str,idx[:4]))},{comp})")
if site_bond is None:
point = [[0, 0, 0]]
else:
if site_bond.count(";") > 0:
point = np.array([np.concat([i.vector, i.center]) for i in self["bond"]["cell"][site_bond]])
else:
point = np.array([i.position for i in self["site"]["cell"][site_bond]])
idx = tuple([conv_dict[idx[0]]] + list(idx[1:]))
samb = self.group.harmonics[idx][0][comp]
name = atomic_id if site_bond is None else atomic_id + "@" + site_bond
plot_harmonics(qtdraw, name, samb, point, atomic_id)