Source code for morphogen.symmetry

"""Finite symmetry groups of periodic cells and their real irreducible representations,
for the equivariant bifurcation analysis of architectured materials (Azulay &
Combescure 2024).

A symmetry ``g = (R, t)`` maps a point ``x`` to ``R (x - c) + c + t`` modulo the lattice
of the cell (``c`` the centre of the point operations): the point operations of a
primitive cell combined with its translations inside a supercell of ``n1 x n2`` (``x
n3``) primitive cells, a group ``G = P ⋉ (Z_n1 x Z_n2)``, generated by closure from its
generators and known by its multiplication table.

The real irreducible representations come from the regular representation, without
tables (GAP): a random symmetric operator averaged over the group, ``S = Σ_g R(g) A
R(g)^T``, commutes with the group, so that its eigenspaces are, generically, irreducible
subspaces; their characters ``χ(g) = tr(Q^T R(g) Q)`` tell them apart, and each irrep is
kept with its orthogonal matrices ``D(g) = Q^T R(g) Q``. Its isotypic projector on any
orthogonal representation ``T`` is ``P = d / (|G| <χ, χ>) Σ_g χ(g) T(g)`` (``<χ, χ>`` = 1, 2
or 4 for irreps of real, complex or quaternionic type).

The equivariant branching lemma (Vanderbauwhede 1980): an isotropy subgroup ``H`` of an
irrep with a one-dimensional fixed-point subspace, ``dim Fix(H) = (1/|H|) Σ_h tr D(h) =
1``, carries a branch of bifurcated solutions of symmetry ``H``. The fixed-point
subspaces of the subgroups are the intersections of those of the elements; each line
among them is the fixed-point subspace of its stabilizer, an axial isotropy subgroup;
conjugate subgroups (``g H g^-1``) give the same pattern turned or shifted, a class.
"""

from __future__ import annotations

from dataclasses import dataclass, field

import numpy as np


def _canonical(t: np.ndarray, lattice: np.ndarray, inverse: np.ndarray, tol: float) -> np.ndarray:
    """A translation reduced modulo the lattice (fractional coordinates in ``[0, 1)``)."""
    frac = inverse @ t
    frac = frac - np.floor(frac + tol)
    frac[np.abs(frac - 1.0) < tol] = 0.0
    return lattice @ frac


[docs] @dataclass class Group: """A finite group of isometries ``(R, t)`` of a periodic cell (lattice vectors in the columns of ``lattice``, point operations about ``centre``), with its multiplication table (``table[a, b]`` is the element ``a b``: first ``b``, then ``a``) and inverses.""" rotations: np.ndarray translations: np.ndarray lattice: np.ndarray centre: np.ndarray table: np.ndarray inverse: np.ndarray _irreps: list | None = field(default=None, repr=False, compare=False) @property def order(self) -> int: return len(self.rotations)
[docs] @classmethod def generate(cls, generators, lattice, centre=None, tol: float = 1e-8) -> Group: """The group generated by ``generators`` (pairs ``(R, t)``), closed modulo the lattice (its vectors in the columns).""" lattice = np.atleast_2d(np.asarray(lattice, dtype=float)) dim = lattice.shape[0] inv = np.linalg.inv(lattice) centre = np.zeros(dim) if centre is None else np.asarray(centre, dtype=float) def keys(r, t): """Integer keys of elements (rounded rotations, fractional translations in [0, 1)) and their translations reduced modulo the lattice.""" frac = t @ inv.T frac = frac - np.floor(frac + tol) frac[np.abs(frac - 1.0) < tol] = 0.0 kr = np.round(r.reshape(len(r), -1) * 1e6).astype(np.int64) kt = np.round(frac * 1e6).astype(np.int64) % 1000000 return np.hstack([kr, kt]), frac @ lattice.T gr = np.array([np.asarray(r, dtype=float) for r, _ in generators]).reshape(-1, dim, dim) gt = np.array([np.asarray(t, dtype=float) for _, t in generators]).reshape(-1, dim) k0, t0 = keys(np.eye(dim)[None], np.zeros((1, dim))) index = {k0[0].tobytes(): 0} rotations, translations = [np.eye(dim)], [t0[0]] frontier_r, frontier_t = np.eye(dim)[None], t0 while len(frontier_r): # products g h of the generators and the newest elements r = np.einsum("gij,hjk->ghik", gr, frontier_r).reshape(-1, dim, dim) t = (np.einsum("gij,hj->ghi", gr, frontier_t) + gt[:, None, :]).reshape(-1, dim) k, t = keys(r, t) fresh = [] for i, row in enumerate(k): b = row.tobytes() if b not in index: index[b] = len(rotations) rotations.append(r[i]) translations.append(t[i]) fresh.append(i) frontier_r, frontier_t = r[fresh], t[fresh] if len(rotations) > 20000: raise ValueError("Group.generate: the group is not finite (or too large)") rotations, translations = np.array(rotations), np.array(translations) n = len(rotations) r = np.einsum("aij,bjk->abik", rotations, rotations).reshape(-1, dim, dim) t = (np.einsum("aij,bj->abi", rotations, translations) + translations[:, None, :]).reshape( -1, dim ) k, _ = keys(r, t) table = np.array([index[row.tobytes()] for row in k], dtype=np.int64).reshape(n, n) inverse = np.argmax(table == 0, axis=1) return cls(rotations, translations, lattice, centre, table, inverse)
[docs] def subgroup(self, keep) -> Group: """The subgroup of the elements ``keep`` (indices or a mask, closed under products), as a group of its own.""" keep = np.flatnonzero(keep) if np.asarray(keep).dtype == bool else np.asarray(keep) position = np.full(self.order, -1) position[keep] = np.arange(len(keep)) table = position[self.table[np.ix_(keep, keep)]] if np.any(table < 0): raise ValueError("subgroup: the elements are not closed under products") inverse = position[self.inverse[keep]] return Group( self.rotations[keep], self.translations[keep], self.lattice, self.centre, table, inverse )
[docs] def stabilizer_of(self, tensor, tol: float = 1e-9) -> np.ndarray: """Mask of the elements whose point operation leaves a second-order ``tensor`` invariant (``R E R^T = E``): the symmetry of a macroscopic loading.""" e = np.asarray(tensor, dtype=float) scale = max(float(np.abs(e).max()), 1e-300) return np.array([np.abs(r @ e @ r.T - e).max() <= tol * scale for r in self.rotations])
[docs] def action(self, points, tol: float = 1e-6) -> np.ndarray: """``perm[g, i]``: the point that ``g`` maps point ``i`` to (points mapped onto themselves modulo the lattice; an error otherwise).""" from scipy.spatial import cKDTree x = np.atleast_2d(np.asarray(points, dtype=float)) inv = np.linalg.inv(self.lattice) def unit(y): # fractional coordinates in [0, 1) frac = y @ inv.T frac = frac - np.floor(frac) return np.where(frac >= 1.0, 0.0, frac) tree = cKDTree(unit(x), boxsize=1.0) perm = np.empty((self.order, len(x)), dtype=np.int64) for g in range(self.order): y = (x - self.centre) @ self.rotations[g].T + self.centre + self.translations[g] dist, idx = tree.query(unit(y)) if np.any(dist > tol): raise ValueError("action: the points are not invariant under the group") perm[g] = idx return perm
[docs] def conjugate(self, members) -> list[frozenset]: """The distinct conjugates ``g H g^-1`` of a subgroup (a set of element indices).""" h = np.fromiter(members, dtype=np.int64) out = { frozenset(self.table[self.table[g, h], self.inverse[g]].tolist()) for g in range(self.order) } return sorted(out, key=sorted)
[docs] def irreps(self, seed: int = 0) -> list[Irrep]: """The real irreducible representations, the trivial one first, then by dimension.""" if self._irreps is None: self._irreps = _real_irreps(self, seed) return self._irreps
[docs] def describe(self, members) -> dict: """Order, point operations (rotations and mirrors) and translations of a subgroup.""" h = np.fromiter(members, dtype=np.int64) points = {tuple(np.round(self.rotations[g].ravel(), 6)) for g in h} dim = self.rotations.shape[1] dets = [np.linalg.det(np.reshape(p, (dim, dim))) for p in points] pure = [g for g in h if np.allclose(self.rotations[g], np.eye(dim))] mirrors = int(sum(d < 0 for d in dets)) rotations = len(points) - mirrors if dim == 2: name = f"D{rotations}" if mirrors else f"C{rotations}" else: name = schoenflies([np.reshape(q, (3, 3)) for q in points]) return { "order": len(h), "point_group": name, "point_order": len(points), "mirrors": mirrors, "translations": len(pure), }
def _rotation_group(rotations) -> tuple[str, int]: """The type of a finite group of proper rotations: ``C<n>``, ``D<n>``, ``T``, ``O``, ``I``, and its order.""" m = len(rotations) orders = [] for r in rotations: angle = np.degrees(np.arccos(np.clip((np.trace(r) - 1.0) / 2.0, -1.0, 1.0))) orders.append(round(360.0 / angle) if angle > 1e-6 else 1) if m == 12 and max(orders) == 3 and orders.count(3) == 8: return "T", m if m == 24 and max(orders) == 4 and orders.count(3) == 8: return "O", m if m == 60: return "I", m top = max(orders) return (f"C{m}", m) if top == m else (f"D{m // 2}", m)
[docs] def schoenflies(operations) -> str: """The Schoenflies symbol of a finite group of 3 x 3 orthogonal matrices (the point operations of a crystal: ``C1``, ``Ci``, ``Cs``, ``C4v``, ``D4h``, ``Td``, ``Oh``...).""" ops = [np.asarray(r, dtype=float) for r in operations] proper = [r for r in ops if np.linalg.det(r) > 0] kind, _ = _rotation_group(proper) if len(proper) == len(ops): return kind if any(np.allclose(r, -np.eye(3)) for r in ops): # G = P x Ci n = int(kind[1:]) if kind[0] in "CD" else 0 if kind == "C1": return "Ci" if kind[0] == "C": return f"S{2 * n}" if n % 2 else f"C{n}h" if kind[0] == "D": return f"D{n}d" if n % 2 else f"D{n}h" return kind + "h" # no inversion: the rotation group isomorphic to G (-g for the improper g) twin, _ = _rotation_group([r if np.linalg.det(r) > 0 else -r for r in ops]) if kind == "C1": return "Cs" if kind == "T": return "Td" n = int(kind[1:]) if kind[0] == "C": if twin[0] == "D": return f"C{n}v" return f"S{2 * n}" if n % 2 == 0 else f"C{n}h" return f"D{n}d" if twin == f"D{2 * n}" and n % 2 == 0 else f"D{n}h"
[docs] @dataclass class Irrep: """A real irreducible representation: its dimension, character, orthogonal matrices ``D(g)`` and type (``<χ, χ>``: 1 real, 2 complex, 4 quaternionic).""" dim: int character: np.ndarray matrices: np.ndarray kind: int
[docs] def projector_weights(self) -> np.ndarray: """``w(g)`` of the isotypic projector ``P = Σ_g w(g) T(g)`` of any representation.""" n = len(self.character) return self.dim / (n * self.kind) * self.character
[docs] def fixed_dimension(self, members) -> float: """``dim Fix(H)`` by the trace formula.""" h = np.fromiter(members, dtype=np.int64) return float(np.trace(self.matrices[h], axis1=1, axis2=2).mean())
def _real_irreps(group: Group, seed: int) -> list[Irrep]: n = group.order rng = np.random.default_rng(seed) a = rng.normal(size=(n, n)) a = a + a.T # regular representation: R(g) e_h = e_{gh}; S = Σ_g R(g) A R(g)^T s = np.zeros((n, n)) for g in range(n): p = group.table[g] # h -> g h s[np.ix_(p, p)] += a values, vectors = np.linalg.eigh(s) scale = max(float(np.abs(values).max()), 1.0) breaks = np.flatnonzero(np.diff(values) > 1e-7 * scale) + 1 found: list[Irrep] = [] for block in np.split(np.arange(n), breaks): q = vectors[:, block] d = np.empty((n, len(block), len(block))) for g in range(n): moved = np.empty_like(q) moved[group.table[g]] = q # (R(g) q)[g h] = q[h] d[g] = q.T @ moved chi = np.trace(d, axis1=1, axis2=2) if any(np.allclose(chi, other.character, atol=1e-6) for other in found): continue kind = round(float(np.mean(chi**2))) found.append(Irrep(len(block), chi, d, kind)) trivial = [i for i, r in enumerate(found) if r.dim == 1 and np.allclose(r.character, 1.0)] others = [i for i in range(len(found)) if i not in trivial] order = trivial + sorted(others, key=lambda i: (found[i].dim, -found[i].character.sum())) return [found[i] for i in order] def _null(m: np.ndarray, tol: float = 1e-8) -> np.ndarray: """Orthonormal basis of the null space of ``m``.""" if m.size == 0: return np.eye(m.shape[1]) _, s, vt = np.linalg.svd(m) rank = int(np.sum(s > tol * max(1.0, float(s.max()) if s.size else 1.0))) return vt[rank:].T def _key(basis: np.ndarray) -> bytes: p = basis @ basis.T return np.round(p, 6).tobytes()
[docs] @dataclass class AxialClass: """A class of conjugate axial isotropy subgroups of an irrep: the subgroups (sets of element indices; the first is the representative), the fixed vector of the first in the irrep and its description.""" subgroups: list[frozenset] vector: np.ndarray description: dict
[docs] def axial_subgroups(group: Group, irrep: Irrep) -> list[AxialClass]: """The classes of isotropy subgroups of ``irrep`` with one-dimensional fixed-point subspaces (the equivariant branching lemma), the largest first.""" d = irrep.dim _, sv, vt = np.linalg.svd(irrep.matrices - np.eye(d)) fixed = {} for g in range(group.order): rank = int(np.sum(sv[g] > 1e-8)) if rank < d: basis = vt[g, rank:].T fixed.setdefault(_key(basis), basis) projectors = np.array([b @ b.T for b in fixed.values()]) lattice = dict(fixed) frontier = [b for b in fixed.values() if b.shape[1] > 1] while frontier: # intersections with the fixed spaces of the elements new = [] for u in frontier: k = u.shape[1] _, s_u, v_u = np.linalg.svd(u[None] - projectors @ u) # (I - P_w) u for all w ranks = np.sum(s_u > 1e-8, axis=1) for w in np.flatnonzero((ranks > 0) & (ranks < k)): basis = u @ v_u[w, ranks[w] :].T key = _key(basis) if key not in lattice: lattice[key] = basis if basis.shape[1] > 1: new.append(basis) frontier = new subgroups = {} for basis in lattice.values(): if basis.shape[1] != 1: continue v = basis[:, 0] moved = np.einsum("gij,j->gi", irrep.matrices, v) members = frozenset(np.flatnonzero(np.abs(moved - v).max(axis=1) < 1e-7).tolist()) if abs(irrep.fixed_dimension(members) - 1.0) < 1e-6: subgroups.setdefault(members, v) classes, seen = [], set() for members in sorted(subgroups, key=lambda m: (-len(m), sorted(m))): if members in seen: continue conj = [c for c in group.conjugate(members) if c in subgroups] seen.update(conj) ordered = [members] + [c for c in conj if c != members] classes.append(AxialClass(ordered, subgroups[members], group.describe(members))) return classes
[docs] def representation(group: Group, perm: np.ndarray, blocks) -> list: """The sparse matrices ``T(g)`` of the action of the group on nodal vectors: point ``i`` carried to ``perm[g, i]`` and its values transformed by ``blocks[g]`` (k x k).""" import scipy.sparse as sp n = perm.shape[1] out = [] for g in range(group.order): b = np.asarray(blocks[g], dtype=float) k = b.shape[0] rows = (k * perm[g])[:, None, None] + np.arange(k)[None, :, None] cols = (k * np.arange(n))[:, None, None] + np.arange(k)[None, None, :] rows, cols = np.broadcast_arrays(rows, cols) vals = np.broadcast_to(b, (n, k, k)) mat = sp.csr_matrix((vals.ravel(), (rows.ravel(), cols.ravel())), shape=(k * n, k * n)) mat.eliminate_zeros() out.append(mat) return out