Source code for multipie.util.util_samb_figure

# 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 SAMB figures (QtDraw), keeping polar and axial parts distinct.

At each center (the origin for an atomic SAMB, the sites or bond centers of the cluster otherwise), the harmonics of
the atomic SAMB are multiplied by the cluster weights and summed, separately for each type X = Q, G, T, M of the
atomic SAMB:

    f_X(r) = sum_{terms with atomic type X} c * Y_cluster[i] * O_atomic(r).

A cluster SAMB is drawn as a combined SAMB whose atomic SAMB is Q0 (O_atomic = 1), except an antisymmetric (T, M) bond
cluster, which is drawn as arrows along the bonds (the flow given by Im(Y), like a bond current). The harmonics of
Q_l and G_l (T_l and M_l) are the same polynomial, so that each type is drawn in its own way:

    Q (polar, time-even): lobes abs(f) colored by sign (BrBG, teal + / brown -).
    T (polar, time-odd): lobes abs(f) colored by sign (coolwarm, red + / blue -).
    G (axial, time-even): translucent lobes with axial-vector arrows inside (forestgreen).
    M (axial, time-odd): translucent lobes with axial-vector arrows inside (dodgerblue).

An axial multipole of rank l is drawn as the axial-vector field A(r) = r_hat f(r_hat): an arrow along r_hat inside each
lobe, outward for f > 0 and inward for f < 0, which transforms as an axial vector (like a spin). The contraction of
r_hat O_lm with an axial vector has the parity (-1)^(l+1) of G_l. For a constant f (G_0), the arrows are put in the six
directions +-x, +-y, +-z (a hedgehog). For an antisymmetric (T/M) bond cluster, Im(Y) refers to the bond direction:
the object at the bond center is (atomic part) x T, the T being the flow along the bond, shown by a red arrow along the
bond direction (tail to head) with the sign in the lobes. When the atomic part is Q0 (a constant), the sign and the
magnitude go to the arrow and no lobe is drawn, as for a cluster SAMB. Magnitudes are normalized by the max. abs(f) of
all centers and types.
"""

import numpy as np
import sympy as sp

from multipie.util.util_plot import plot_site

x_, y_, z_ = sp.symbols("x y z", real=True)

# X: (kind, positive ring color, negative ring color, colormap of polar lobes).
TYPE_INFO = {
    "Q": ("polar", None, None, "BrBG"),
    "T": ("polar", None, None, "coolwarm"),
    "G": ("axial", "forestgreen", "forestgreen", None),
    "M": ("axial", "dodgerblue", "dodgerblue", None),
}
ARROW_COLOR = {"G": "forestgreen", "M": "dodgerblue"}
BOND_FLOW_COLOR = "crimson"  # arrows of an antisymmetric bond cluster SAMB (y): each is a T (imaginary hopping).
BOND_FLOW_LENGTH = 0.7  # max. arrow length / bond length.
BOND_FLOW_WIDTH = 0.025  # arrow width / shortest bond.
REVERSE_CMAP = set()  # types whose colormap is reversed (surface = -f).
ONE_SIGN_COLOR = {  # X: (positive, negative), color of a polar lobe of one sign (middle of the colormap).
    "Q": ("mediumaquamarine", "burlywood"),
    "T": ("darksalmon", "cornflowerblue"),
}

SAMB_FIGURE_SIZE = 0.5  # default lobe length for the max. abs(f) in draw_center.
SAMB_FIGURE_SIZE_RATIO = 0.2  # lobe length for the max. abs(f) / the shortest bond (cluster and combined SAMB).
SAMB_FIGURE_SIZE_ATOMIC = 0.8  # lobe length for an atomic SAMB at the origin.
SAMB_FIGURE_DIGITS = 5  # significant digits of the coefficients given to QtDraw (shorter strings are parsed faster).

_SPHERE = None
_SPHERE_DOT = None


# ==================================================
def _sphere():
    global _SPHERE, _SPHERE_DOT
    if _SPHERE is None:
        n = 2000
        i = np.arange(n) + 0.5
        phi = np.arccos(1 - 2 * i / n)
        th = np.pi * (1 + 5**0.5) * i
        _SPHERE = np.stack([np.cos(th) * np.sin(phi), np.sin(th) * np.sin(phi), np.cos(phi)], axis=1)
        _SPHERE_DOT = _SPHERE @ _SPHERE.T
    return _SPHERE, _SPHERE_DOT


# ==================================================
def _eval(expr, pts):
    expr = sp.sympify(expr)
    if not expr.free_symbols:  # not is_constant(), which calls simplify.
        return np.full(len(pts), float(expr))
    f = sp.lambdify((x_, y_, z_), expr, "numpy")
    return np.asarray(f(pts[:, 0], pts[:, 1], pts[:, 2]), dtype=float) * np.ones(len(pts))


# ==================================================
[docs] def max_abs(expr): """ Max. of abs(f) on the unit sphere. Args: expr (sympy or str): polynomial in x, y, z. Returns: - (float) -- max. abs(f). """ pts, _ = _sphere() return float(np.max(np.abs(_eval(expr, pts))))
# ================================================== def _polar_color(X, expr, values): """ Color and surface polynomial of a polar lobe. QtDraw maps the color range to [-v, v] only when the values have both signs ([0, v] or [-v, 0] otherwise), so that a lobe of one sign (e.g. a constant) is colored uniformly by ONE_SIGN_COLOR, the middle color of its sign. Args: X (str): type, "Q" or "T". expr (sympy): polynomial. values (ndarray): values on the sphere points. Returns: - (str) -- color or colormap. - (str) -- surface polynomial. """ sgn = -1 if X in REVERSE_CMAP else 1 if values.min() < -1e-12 and values.max() > 1e-12: return TYPE_INFO[X][3], str(sgn * expr) positive = (values.max() > 1e-12) == (sgn > 0) return ONE_SIGN_COLOR[X][0 if positive else 1], "1" # ==================================================
[docs] def lobe_directions(expr, threshold=0.35, min_angle=55.0, values=None): """ Directions of the lobe tips of abs(f) (local maxima on the unit sphere). Args: expr (sympy or str): polynomial in x, y, z. threshold (float, optional): keep maxima with abs(f) >= threshold * max. abs(f). min_angle (float, optional): minimum angle between two tips [deg]. values (ndarray, optional): values of expr on the sphere points (computed if None). Returns: - (list) -- [(direction ndarray, f value)]. """ pts, dots = _sphere() v = _eval(expr, pts) if values is None else values a = np.abs(v) amax = a.max() if amax < 1e-12: return [] if a.min() > 0.999 * amax: # constant on the sphere (rank 0): six directions. d = np.array([[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]], dtype=float) return [(di, float(_eval(expr, di[None, :])[0])) for di in d] cosn = np.cos(np.deg2rad(8.0)) cosm = np.cos(np.deg2rad(min_angle)) tips = [] for i in np.argsort(-a): if a[i] < threshold * amax: break if a[i] < a[dots[i] > cosn].max() - 1e-12: continue if any(np.dot(pts[i], t[0]) > cosm for t in tips): continue tips.append((pts[i].copy(), float(v[i]))) return tips
# ================================================== def _ring_points(center, d, radius, sense, arc=300.0, n=40): d = d / np.linalg.norm(d) t = np.array([1.0, 0, 0]) if abs(d[0]) < 0.9 else np.array([0, 1.0, 0]) e1 = np.cross(d, t) e1 /= np.linalg.norm(e1) e2 = np.cross(d, e1) # e1 x e2 = d: increasing angle = counterclockwise seen from the tip. th = np.deg2rad(np.linspace(0, arc, n)) * (1 if sense > 0 else -1) return center + radius * (np.outer(np.cos(th), e1) + np.outer(np.sin(th), e2)) # ==================================================
[docs] def draw_center( qtdraw, position, poly, scale=1.0, size=SAMB_FIGURE_SIZE, A=None, axial_opacity=0.3, polar_opacity_mixed=0.55, arrow_width=None, axial_style="arrow", name="samb", ): """ Draw polynomials of the four types at one center. Args: qtdraw (PyVistaWidget): QtDraw widget. position (array-like): center (fractional). poly (dict): X -> polynomial (sympy or str), X = Q, G, T, M. scale (float, optional): normalization (max. abs(f) of all centers). size (float, optional): lobe length for abs(f) = scale. A (ndarray, optional): unit-cell vectors as columns (cartesian = A @ fractional), for the arrows. axial_opacity (float, optional): opacity of the axial lobes. polar_opacity_mixed (float, optional): opacity of the polar lobes when axial parts exist at the same center. arrow_width (float, optional): width of the arrows (default: 0.06 * size). axial_style (str, optional): "arrow" (axial vector inside each lobe) or "ring" (rotation ring at each lobe tip). name (str, optional): group name. """ if arrow_width is None: arrow_width = 0.06 * size pos = np.asarray(position, dtype=float) A = np.eye(3) if A is None else np.asarray(A, dtype=float)[0:3, 0:3] pts, _ = _sphere() poly = {X: sp.sympify(poly.get(X, 0)) for X in "QGTM"} values = {X: _eval(e, pts) / scale for X, e in poly.items() if e != 0} poly = {X: poly[X] for X, v in values.items() if np.abs(v).max() > 1e-8} has_axial = any(X in poly for X in "GM") for X in ["Q", "T", "G", "M"]: if X not in poly: continue kind, cp, cn, cmap = TYPE_INFO[X] e = sp.N(poly[X] / scale, SAMB_FIGURE_DIGITS) if kind == "polar": color, surf = _polar_color(X, e, values[X]) op = polar_opacity_mixed if has_axial else 1.0 qtdraw.add_orbital(shape=str(e), surface=surf, size=-size, color=color, opacity=op, position=pos.tolist(), name=name) continue s_ax = 1.05 * size qtdraw.add_orbital( shape=str(e), surface="1", size=-s_ax, color="silver", opacity=axial_opacity, position=pos.tolist(), name=name ) for d, fv in lobe_directions(e, values=values[X]): L = abs(fv) * s_ax if axial_style == "arrow": # inside the lobe: centered at 55% of the lobe length, length 50% of it. la = 0.5 * L start = d * (0.55 * L) - 0.5 * la * np.sign(fv) * d qtdraw.add_vector( position=(pos + np.linalg.solve(A, start)).tolist(), direction=(np.sign(fv) * d).tolist(), length=la, width=arrow_width, offset=0.0, tip_length=0.3, color=ARROW_COLOR[X], cartesian=True, name=name, ) else: rad = 0.18 * size + 0.12 * L pts = _ring_points(d * (L + 0.02 * size), d, rad, np.sign(fv)) qtdraw.add_spline( point=np.round(pts, 6).tolist(), width=2 * arrow_width / 3, arrow2=True, tip_R=2.5, tip_length=0.25 * rad, color=cp if fv > 0 else cn, cartesian=True, position=pos.tolist(), name=name, )
# ==================================================
[docs] def harmonic_expression(group, key, comp): """ Polynomial of an atomic SAMB key (X, l, Gamma, n, p, s, k, "q") and component (T -> Q, M -> G). Args: group (Group): group. key (tuple): atomic SAMB key. comp (int): component. Returns: - (sympy) -- polynomial in x, y, z. """ X, l, Gamma, n = key[0:4] X = {"T": "Q", "M": "G"}.get(X, X) return sp.sympify(group.harmonics[(X, l, Gamma, n, -1, 0, 0, "q")][0][comp])
# ==================================================
[docs] def combined_site_bond(mm, usamb): """ Site or bond of a combined SAMB. Args: mm (MaterialModel): model. usamb (UniqueSAMBType): unique SAMB type of the combined SAMB. Returns: - (str) -- site or bond, see "wyckoff". """ st = usamb.samb_type for sb, wp in mm["wyckoff"].items(): if wp != st.wyckoff: continue if ";" not in sb: if "@" not in wp and sb == st.head: return sb elif sb.split("_")[0] == f"{st.head};{st.tail}" and int(sb.split("_")[1]) == usamb.neighbor: return sb raise KeyError(f"site/bond for {usamb} is not found.")
# ================================================== def _centers(mm, site_bond): if ";" in site_bond: cell = mm["bond"]["cell"][site_bond] return np.array([b.center for b in cell], dtype=float), np.array([b.vector for b in cell], dtype=float) cell = mm["site"]["cell"][site_bond] return np.array([s.position for s in cell], dtype=float), None # ==================================================
[docs] def center_polynomials(mm, terms, site_bond): """ Polynomials f_X at the centers of a site or bond cluster. Args: mm (MaterialModel): model. terms (list): [(coeff, O_atomic (sympy), atomic type X, cluster key, cluster comp.)]. site_bond (str): site or bond. Returns: - (ndarray) -- centers (fractional). - (ndarray or None) -- bond vectors (fractional). - (dict) -- X -> [polynomial at each center]. - (ndarray) -- bool, direction of the bond is shown ? """ wp = mm["wyckoff"][site_bond] centers, vectors = _centers(mm, site_bond) N = len(centers) is_bond = ";" in site_bond poly = {X: [sp.S(0)] * N for X in "QGTM"} directed = np.zeros(N, dtype=bool) for c, O, X, ckey, ccomp in terms: Y = np.array(mm["cluster_samb"][wp][ckey][0][ccomp]).reshape(-1) antisym = is_bond and ckey[0] in ("T", "M") for i in range(N): w = sp.sympify(Y[i % len(Y)]) if antisym: w = sp.im(w) if w != 0: directed[i] |= antisym poly[X][i] += sp.sympify(c) * w * O poly = {X: [sp.expand(e) for e in lst] for X, lst in poly.items()} return centers, vectors, poly, directed
# ==================================================
[docs] def samb_figure_type(tag): """ Kind of a SAMB tag. Args: tag (str): "x1", "y2", "z3", ... Returns: - (str) -- "atomic", "cluster" or "combined". """ kind = {"x": "atomic", "y": "cluster", "z": "combined"}.get(tag[:1]) if isinstance(tag, str) else None if kind is None or not tag[1:].isdigit(): raise ValueError(f"invalid SAMB tag for samb_figure, {tag!r} (x: atomic, y: cluster, z: combined, e.g. 'z3').") return kind
# ==================================================
[docs] def select_samb_figure(mm, samb_figure): """ SAMBs to draw. Args: mm (MaterialModel): model. samb_figure (bool or list): 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 tags, e.g. ["x1", "y2", "z3"]. Returns: - (list) -- tags. """ if samb_figure is True: max_neighbor = mm["qtdraw_prop"]["max_neighbor"] site_bond = [s for s in mm["wyckoff"].keys() if s.count(";") == 0 or int(s.split("_")[1]) < max_neighbor] wps = {mm["wyckoff"][s] for s in site_bond} y = [yn for yn, (wp, _, _) in mm["cluster_id"].items() if wp in wps] z = [zn for zn, (_, usamb, _, _) in mm["combined_id"].items() if combined_site_bond(mm, usamb) in site_bond] return list(mm["atomic_id"].keys()) + y + z if isinstance(samb_figure, str) or not isinstance(samb_figure, (list, tuple)): raise ValueError(f"samb_figure must be True, False, or a list of SAMB tags, not {samb_figure!r}.") id_dict = {"atomic": "atomic_id", "cluster": "cluster_id", "combined": "combined_id"} tags = [] for tag in samb_figure: kind = samb_figure_type(tag) if tag not in mm[id_dict[kind]]: raise ValueError(f"unknown {kind} SAMB in samb_figure, {tag}.") if tag not in tags: tags.append(tag) return tags
# ==================================================
[docs] def draw_structure(qtdraw, mm, site_bond=()): """ Set the crystal and draw the sites (and the bonds of the SAMB). Args: qtdraw (PyVistaWidget): QtDraw widget. mm (MaterialModel): model. site_bond (list, optional): sites or bonds of the SAMB (bonds are drawn in white). """ qtdraw.set_crystal(mm["crystal"]) qtdraw.set_unit_cell(mm["cell_info"]["cell"]) qtdraw.set_cell("off" if mm.group.is_point_group else "single") for sb, sites in mm["site"]["cell"].items(): plot_site(qtdraw, sb, np.array([s.position for s in sites]), rep=False) for sb in site_bond: if ";" in sb: for b in mm["bond"]["cell"][sb]: qtdraw.add_bond( position=b.center, direction=b.vector, color="white", color2="white", width=0.03, cartesian=False, opacity=0.6, name=sb, )
# ==================================================
[docs] def samb_figure_size(mm): """ Lobe length for the max. abs(f) of cluster and combined SAMBs: SAMB_FIGURE_SIZE_RATIO times the shortest bond of the model (0.1 times the shortest cell length without bonds). Args: mm (MaterialModel): model. Returns: - (float) -- lobe length. """ distance = [float(b.distance) for b in mm["bond"]["representative"].values()] if distance: return SAMB_FIGURE_SIZE_RATIO * min(distance) cell = mm["cell_info"]["cell"] return 0.1 * min(float(cell[k]) for k in ["a", "b", "c"])
# ==================================================
[docs] def draw_bond_flow(qtdraw, mm, site_bond, ckey, comp, name="samb"): """ Draw an antisymmetric (T, M) bond cluster SAMB as arrows along the bonds. The weight Im(Y) refers to the bond direction (tail to head): each bond has an arrow along +vector for Im(Y) > 0 and along -vector for Im(Y) < 0 (the flow, like a bond current), with the length proportional to abs(Im(Y)). Each arrow is a T (an imaginary hopping), drawn in one color; the type of the cluster (T or M) is that of the whole pattern, e.g. circulating flows for an M-type cluster. Args: qtdraw (PyVistaWidget): QtDraw widget. mm (MaterialModel): model. site_bond (list): bonds of the cluster. ckey (tuple): cluster SAMB key. comp (int): component. name (str, optional): group name. """ wp = mm["wyckoff"][site_bond[0]] Y = np.array(mm["cluster_samb"][wp][ckey][0][comp]).reshape(-1) w = np.array([float(sp.im(sp.sympify(v))) for v in Y]) wmax = max(np.abs(w).max(), 1e-12) dmin = min(float(b.distance) for b in mm["bond"]["representative"].values()) for sb in site_bond: for i, b in enumerate(mm["bond"]["cell"][sb]): wi = w[i % len(w)] if abs(wi) < 1e-8 * wmax: continue v = np.sign(wi) * np.asarray(b.vector, dtype=float) _flow_arrow(qtdraw, b.center, v, BOND_FLOW_LENGTH * abs(wi) / wmax, dmin, name)
# ================================================== def _flow_arrow(qtdraw, center, vector, fraction, dmin, name): """ Red arrow (a T, an imaginary hopping) at a bond center along vector, with the length fraction * |vector|. """ qtdraw.add_vector( position=np.asarray(center, dtype=float).tolist(), direction=np.asarray(vector, dtype=float).tolist(), length=-fraction, width=BOND_FLOW_WIDTH * dmin, color=BOND_FLOW_COLOR, cartesian=False, name=name, ) # ==================================================
[docs] def draw_samb_figure(qtdraw, mm, tag, size=None, axial_style="arrow"): """ Draw an atomic (x), cluster (y) or combined (z) SAMB. Args: qtdraw (PyVistaWidget): QtDraw widget. mm (MaterialModel): model. tag (str): SAMB tag, "x1", "y2", "z3", ... size (float, optional): lobe length for the max. abs(f) (cluster and combined SAMB), default: samb_figure_size(mm). axial_style (str, optional): "arrow" or "ring". """ kind = samb_figure_type(tag) if size is None: size = samb_figure_size(mm) qtdraw.clear_data() qtdraw.set_model(f"{mm['model']}_{tag}") A = mm["cell_info"]["A"] if kind == "atomic": _, key, comp = mm["atomic_id"][tag] qtdraw.set_crystal(mm["crystal"]) qtdraw.set_unit_cell(mm["cell_info"]["cell"]) qtdraw.set_cell("off") poly = {key[0]: harmonic_expression(mm.group, key, comp)} scale = max(max_abs(poly[key[0]]), 1e-12) draw_center(qtdraw, [0, 0, 0], poly, scale, SAMB_FIGURE_SIZE_ATOMIC, A, axial_style=axial_style, name=tag) qtdraw.add_site(position=[0, 0, 0], size=0.03, color="black", name=tag) return if kind == "cluster": # atomic SAMB = Q0. wp, ckey, comp = mm["cluster_id"][tag] site_bond = [sb for sb, w in mm["wyckoff"].items() if w == wp] if "@" in wp and ckey[0] in ("T", "M"): # antisymmetric bond cluster: flow along the bonds. draw_structure(qtdraw, mm, site_bond) draw_bond_flow(qtdraw, mm, site_bond, ckey, comp, name=tag) return terms = [(1, sp.S(1), "Q", ckey, comp)] else: _, usamb, _, _ = mm["combined_id"][tag] lc, _, _ = mm.Z(tag) site_bond = [combined_site_bond(mm, usamb)] terms = [(cg, harmonic_expression(mm.group, akey, acomp), akey[0], ckey, ccomp) for cg, akey, acomp, ckey, ccomp in lc] draw_structure(qtdraw, mm, site_bond) data = [center_polynomials(mm, terms, sb) for sb in site_bond] scale = max([max_abs(e) for _, _, poly, _ in data for lst in poly.values() for e in lst] + [1e-12]) dmin = min([float(b.distance) for b in mm["bond"]["representative"].values()] + [np.inf]) for centers, vectors, poly, directed in data: for i, c in enumerate(centers): p = {X: poly[X][i] for X in "QGTM"} if directed[i]: # antisymmetric bond: (atomic part) x T, the T being the flow along the bond (red arrow). nz = {X: e for X, e in p.items() if e != 0} if list(nz) == ["Q"] and not nz["Q"].free_symbols: # atomic Q0: the sign goes to the arrow, as y. val = float(nz["Q"]) / scale _flow_arrow(qtdraw, c, np.sign(val) * vectors[i], BOND_FLOW_LENGTH * abs(val), dmin, tag) continue _flow_arrow(qtdraw, c, vectors[i], BOND_FLOW_LENGTH, dmin, tag) # fixed direction, sign in lobes. draw_center(qtdraw, c, p, scale, size, A, axial_style=axial_style, name=tag)
# ================================================== def _fix_orbital_normals(actor): """ Orbital meshes of QtDraw keep the radial normals of the unit sphere, which shade a lobe facing downward dark with smooth shading: give the mapper a copy with the normals of the deformed surface (for PNG only). """ import pyvista as pv mapper = getattr(actor, "mapper", None) if mapper is None: return alg = mapper.GetInputAlgorithm() data = alg.GetOutputDataObject(0) if alg is not None else mapper.GetInput() if data is None: return m = pv.wrap(data) if not isinstance(m, pv.PolyData) or "surface" not in m.array_names or "Normals" not in m.array_names: return m = m.copy() del m.point_data["Normals"] m = m.compute_normals(cell_normals=False, split_vertices=False, consistent_normals=True) nm = np.asarray(m.point_data["Normals"]) if np.mean(np.sum(nm * (m.points - m.points.mean(axis=0)), axis=1)) < 0: m.point_data["Normals"] = -nm m.set_active_scalars("surface") mapper.SetInputData(m) # ==================================================
[docs] def save_samb_png(qtdraw, filename, view=None, window_size=(900, 900)): """ Save PNG of the objects of a QtDraw widget, rendered off screen with a white background. Args: qtdraw (PyVistaWidget): QtDraw widget. filename (str): PNG file name. view (list, optional): view indices [a1,a2,a3] (QtDraw default if None). window_size (tuple, optional): image size. """ import pyvista as pv qtdraw.set_view(view) p = pv.Plotter(off_screen=True, window_size=window_size) try: p.set_background("white") p.enable_anti_aliasing() p.enable_lightkit() p.add_light(pv.Light(light_type="headlight", intensity=0.45)) for n, a in qtdraw.renderer.actors.items(): _fix_orbital_normals(a) if hasattr(a, "prop") and hasattr(a.prop, "ambient"): a.prop.ambient = 0.3 a.prop.diffuse = 0.75 p.add_actor(a, name=n, reset_camera=False) p.camera_position = qtdraw.camera_position p.camera.parallel_projection = True p.reset_camera() p.screenshot(filename) finally: p.close()