Source code for escnn.group.groups.dihedralgroup

from __future__ import annotations

import escnn.group
from escnn.group import Group, GroupElement
from escnn.group import IrreducibleRepresentation, Representation
from escnn.group import utils

import numpy as np
import math

from typing import Tuple, Callable, Iterable, List, Dict, Any

__all__ = ["DihedralGroup"]


[docs]class DihedralGroup(Group): PARAM = 'int' PARAMETRIZATIONS = [ 'int', # integer in 0, 1, ..., N-1 'radians', # real in 0., 2pi/N, ... i*2pi/N, ... # 'C', # point in the unit circle (i.e. cos and sin of 'radians') 'MAT', # 2x2 rotation matrix ] def __init__(self, N: int): r""" Build an instance of the dihedral group :math:`D_N` which contains reflections and ``N`` discrete planar rotations. The order of the group :math:`D_N` is :math:`2N`. The group elements are :math:`\{e,\, r,\, r^2,\, r^3,\, \dots,\, r^{N-1},\, f,\, rf,\, r^2f,\, r^3f,\, \dots,\, r^{N-1}f\}`, so an element of this group is either a rotation :math:`r^k` or a reflection :math:`r^kf` along an axis. Any group element is either a discrete rotation :math:`r^k` by an angle :math:`k\frac{2\pi}{N}` or a reflection :math:`f` followed by a rotation, i.e. :math:`r^kf`. As in :class:`~escnn.group.CyclicGroup`, combination of rotations behaves like arithmetic modulo ``N``, so :math:`r^a \cdot r^b = r^{\ a + b \!\! \mod \!\! N}\ `. Two reflections gives the identity :math:`f \cdot f = e` and a reflection commutes with a rotation by inverting it, i.e. :math:`r^k \cdot f = f \cdot r^{-k}`. A group element :math:`r^kf^j` is implemented as a pair :math:`(j, k)` with :math:`j \in \{0, 1\}` and and :math:`k \in \{0, \dots, N-1\}`. Subgroup Structure. A subgroup of :math:`D_{2N}` is identified by a tuple ``id`` :math:`(k, M)`. Here, :math:`M` is a positive integer indicating the number of discrete rotations in the subgroup while :math:`k` is either ``None`` or an integer in :math:`\{0, \dots, \frac{N}{M}-1\}`. If :math:`k` is ``None``, the subgroup does not contain any reflections. Otherwise, the subgroup contains the reflection :math:`r^k f` along the axis of the current group rotated by :math:`k\frac{\pi}{N}`. The order :math:`M` has to divide the rotation order :math:`N` of the current group (:math:`D_{2N}`). Valid combinations are: - (``None``, :math:`M`): restrict to the cyclic subgroup :math:`C_M` generated by :math:`\langle r^{N/M} \rangle`. - (:math:`k`, :math:`M`): restrict to the dihedral subgroup :math:`D_{M}` generated by :math:`\langle r^{N/M}, r^{k}f \rangle` In particular: - (``None``, :math:`1`): restrict to the cyclic subgroup of order 1 containing only the identity - (:math:`0`, :math:`1`): restrict to the reflection group generated by :math:`\langle f \rangle` - (:math:`0`, :math:`M`): restrict to the dihedral subgroup :math:`D_{M}` generated by :math:`\langle r^{N/M}, f \rangle` - (:math:`k`, :math:`1`): restrict to the reflection group generated by :math:`\langle r^{k}f \rangle = \{e, r^{k}f\}` Args: N (int): number of discrete rotations in the group Attributes: ~.reflection: the reflection element ~.rotation_order (int): the number of discrete rotations in this group (equal to the parameter ``N``) """ assert (isinstance(N, int) and N > 0), N super(DihedralGroup, self).__init__("D%d" % N, False, False) self.rotation_order = N self._elements = [self.element((0, i)) for i in range(N)] + [self.element((1, i)) for i in range(N)] self._identity = self.element((0, 0)) self.reflection = self.element((1, 0)) self._build_representations() @property def generators(self) -> List[GroupElement]: if self.rotation_order > 1: return [self.element((0, 1)), self.element((1, 0))] else: return [self.element((1, 0))] @property def identity(self) -> GroupElement: return self._identity @property def elements(self) -> List[GroupElement]: return self._elements @property def _keys(self) -> Dict[str, Any]: return {'N': self.rotation_order} @property def subgroup_trivial_id(self): return (None, 1) @property def subgroup_self_id(self): return (0, self.rotation_order) ########################################################################### # METHODS DEFINING THE GROUP LAW AND THE OPERATIONS ON THE GROUP'S ELEMENTS ########################################################################### def _inverse(self, element: Tuple[int, int], param: str = PARAM) -> Tuple[int, int]: r""" Returns the inverse element of the input element. Given the element :math:`r^kf^j` as a pair :math:`(j, k)`, the method returns :math:`r^{-k}` (as :math:`(0, -k)`) if :math:`f = 0` and :math:`fr^{-k}=r^kf` (as :math:`(1, k)`) otherwise. Args: element (tuple): a group element :math:`r^kf^j` as a pair :math:`(j, k)` Returns: its inverse """ element = self._change_param(element, p_from=param, p_to='int') inverse = element[0], (-element[1] * (-1 if element[0] else 1)) % self.rotation_order return self._change_param(inverse, p_from='int', p_to=param) def _combine(self, e1: Tuple[int, int], e2: Tuple[int, int], param: str = PARAM, param1: str = None, param2: str = None ) -> Tuple[int, float]: r""" Return the combination of the two input elements. Given two input element :math:`r^af^b` and :math:`r^cf^d`, the method returns :math:`r^af^b \cdot r^cf^d`. Args: e1 (tuple): a group element :math:`r^af^b` as a pair :math:`(b, a)` e2 (tuple): another element :math:`r^cf^d` as a pair :math:`(d, c)` Returns: their combination :math:`r^af^b \cdot r^cf^d` """ if param1 is None: param1 = param if param2 is None: param2 = param e1 = self._change_param(e1, p_from=param1, p_to='int') e2 = self._change_param(e2, p_from=param2, p_to='int') product = (e1[0] + e2[0]) % 2, (e1[1] + (-1 if e1[0] else 1) * e2[1]) % self.rotation_order return self._change_param(product, p_from='int', p_to=param) def _is_element(self, element: Tuple[int, int], param: str = PARAM, verbose: bool = False) -> bool: element = self._change_param(element, p_from=param, p_to='int') if isinstance(element, tuple) and len(element) == 2 and isinstance(element[0], int) and isinstance(element[1], int): return element[0] in {0, 1} and 0 <= element[1] < self.rotation_order else: return False def _equal(self, e1: Tuple[int, int], e2: Tuple[int, int], param: str = PARAM, param1: str = None, param2: str = None ) -> bool: r""" Check if the two input values corresponds to the same element. Args: e1 (tuple): an element e2 (tuple): another element Returns: whether they are the same element """ if param1 is None: param1 = param if param2 is None: param2 = param e1 = self._change_param(e1, p_from=param1, p_to='int') e2 = self._change_param(e2, p_from=param2, p_to='int') return e1[0] == e2[0] and e1[1] == e2[1] def _hash_element(self, element: Tuple[int, int], param: str = PARAM): element = self._change_param(element, p_from=param, p_to='int') element = element[0], element[1] % self.rotation_order return hash(element) def _repr_element(self, element: Tuple[int, int], param: str = PARAM): element = self._change_param(element, p_from=param, p_to='int') return "({}, {}[2pi/{}])".format('+' if not element[0] else '-', element[1], self.rotation_order) def _change_param(self, element: Tuple, p_from: str, p_to: str): assert p_from in self.PARAMETRIZATIONS assert p_to in self.PARAMETRIZATIONS assert isinstance(element, tuple) and len(element) == 2 assert element[0] in [0, 1] flip, rotation = element if p_from == 'MAT': assert isinstance(rotation, np.ndarray) assert rotation.shape == (2, 2) assert np.isclose(np.linalg.det(rotation), 1.) assert np.allclose(rotation @ rotation.T, np.eye(2)) cos = (rotation[0, 0] + rotation[1, 1]) / 2. sin = (rotation[1, 0] - rotation[1, 0]) / 2. rotation = np.arctan2(sin, cos) p_from = 'radians' # convert to INT if p_from == 'int': assert isinstance(rotation, int) elif p_from == 'radians': assert isinstance(rotation, float) if not utils.cycle_isclose(rotation, 0., 2 * np.pi / self.rotation_order): raise ValueError() rotation = int(round(self.rotation_order * rotation / (2 * np.pi))) % self.rotation_order else: raise ValueError('Parametrization {} not recognized'.format(p_from)) # convert from INT if p_to == 'int': return flip, rotation elif p_to == 'radians': rotation = rotation * (2 * np.pi) / self.rotation_order return flip, rotation elif p_to == 'MAT': rotation = rotation * (2 * np.pi) / self.rotation_order cos = np.cos(rotation) sin = np.sin(rotation) rotation = np.array(([ [cos, -sin], [sin, cos], ])) return flip, rotation else: raise ValueError('Parametrization {} not recognized'.format(p_to)) ########################################################################### def sample(self) -> GroupElement: return self.element((np.random.randint(0, 2), np.random.randint(0, self.rotation_order)))
[docs] def testing_elements(self) -> Iterable[GroupElement]: r""" A finite number of group elements to use for testing. """ return iter(self._elements)
def __eq__(self, other): if not isinstance(other, DihedralGroup): return False else: return self.name == other.name and self.rotation_order == other.rotation_order def _subgroup(self, id: Tuple[int, int]) -> Tuple[ Group, Callable[[GroupElement], GroupElement], Callable[[GroupElement], GroupElement] ]: r""" Restrict the current group :math:`D_{2N}` to the subgroup identified by the input ``id``, where ``id`` is a tuple :math:`(k, M)`. Args: id (tuple): the identification of the subgroup Returns: a tuple containing - the subgroup, - a function which maps an element of the subgroup to its inclusion in the original group and - a function which maps an element of the original group to the corresponding element in the subgroup (returns None if the element is not contained in the subgroup) """ assert isinstance(id, tuple) and len(id) == 2 assert id[0] is None or isinstance(id[0], int) assert isinstance(id[1], int) assert id[1] >= 1 axis = id[0] order = id[1] assert self.rotation_order % order == 0, \ "Error! The rotations order of the subgroups of a dihedral group has to divide the rotations order of the overgroup." \ " %d does not divide %d " % (order, self.rotation_order) assert axis is None or 0 <= axis < self.rotation_order # // order ratio = self.rotation_order // order if id[0] is not None and id[1] == 1: # take the elements of the group generated by "r^axis f" sg = escnn.group.cyclic_group(2) # parent_mapping = lambda e, axis=axis: self.element((e._element, axis * e._element)) # child_mapping = lambda e, axis=axis, sg=sg: None if e._element[1] != e._element[0] * axis else sg.element(e._element[0]) parent_mapping = flip_to_dn(axis, self) child_mapping = dn_to_flip(axis, sg) elif id[0] is None: # take the elements of the group generated by "r^ratio" sg = escnn.group.cyclic_group(order) # parent_mapping = lambda e, ratio=ratio: self.element((0, e._element * ratio)) # child_mapping = lambda e, ratio=ratio, sg=sg: None if (e._element[0] != 0 or e._element[1] % ratio > 0) else sg.element(int(e._element[1] / ratio)) parent_mapping = cn_to_dn(self) child_mapping = dn_to_cn(sg) else: # take the elements of the group generated by "r^ratio" and "r^axis f" sg = escnn.group.dihedral_group(order) # parent_mapping = lambda e, ratio=ratio, axis=axis: self.element((e._element[0], e._element[1] * ratio + e._element[0] * axis)) # child_mapping = lambda e, ratio=ratio, axis=axis, sg=sg: None if (e._element[1] - e._element[0] * axis) % ratio > 0 else sg.element((e._element[0], int((e._element[1] - e._element[0] * axis) / ratio))) parent_mapping = dm_to_dn(axis, self) child_mapping = dn_to_dm(axis, sg) return sg, parent_mapping, child_mapping
[docs] def grid(self, type: str, N: int) -> List[GroupElement]: r""" .. todo :: Add docs """ if type == 'rand': return [self.sample() for _ in range(N)] elif type == 'regular': assert self.rotation_order % N == 0 r = self.rotation_order // N return [self.element((0, i*r)) for i in range(N)] + [self.element((1, i*r)) for i in range(N)] else: raise ValueError(f'Grid type "{type}" not recognized!')
def _combine_subgroups(self, sg_id1, sg_id2): sg_id1 = self._process_subgroup_id(sg_id1) sg1, inclusion, restriction = self.subgroup(sg_id1) sg_id2 = sg1._process_subgroup_id(sg_id2) if sg_id1[0] is None: return (None, sg_id2) elif sg_id1[1] == 1: return sg_id1[0] if sg_id2 == 2 else None, 1 elif sg_id2[0] is None: return sg_id2 else: flip = sg_id1[0] + inclusion(sg1.element((0, sg_id2[0]))).to('int')[1] return (flip,) + sg_id2[1:] def _restrict_irrep(self, irrep: Tuple, id: Tuple[int, int]) -> Tuple[np.matrix, List[Tuple]]: r""" Restrict the input irrep of current group :math:`D_{2n}` to the subgroup identified by "id". More precisely, "id" is a tuple :math:`(k, m)`, where :math:`m` is a positive integer indicating the number of rotations in the subgroup while :math:`k` is either None (no flips in the subgroup) or an integer in :math:`[0, \frac{n}{m}-1]` (indicating the axis of flip in the subgroup). The order :math:`m` has to divide the rotation order :math:`n` of the current group (:math:`D_{2n}`). Valid combinations are: - (None, m): restrict to the cyclic subgroup with order "m" :math:`C_m` generated by :math:`\langle r^{(n/m)} \rangle`. - (1, m): restrict to the dihedral subgroup with order "2m" :math:`D_{2m}` generated by :math:`\langle r^{n/m}, f \rangle` - (k, 1): restrict to the cyclic subgroup of order 2 :math:`C_2` generated by the flip :math:`\langle r^{k}f \rangle = \{e, r^{k}f\}` - (None, 1): restrict to the cyclic subgroup of order 1 :math:`C_1` containing only the identity - (k, m): restrict to the dihedral subgroup with order "2m" :math:`D_{2m}` generated by :math:`\langle r^{n/m}, r^{k}f \rangle` Args: irrep (tuple): the identifier of the irrep to restrict id (tuple): the identification of the subgroup Returns: a pair containing the change of basis and the list of irreps of the subgroup which appear in the restricted irrep """ irr = self.irrep(*irrep) sg, _, _ = self.subgroup(id) irreps = [] change_of_basis = None if id[0] is not None and id[1] == 1: j = irr.attributes["flip_frequency"] k = irr.attributes["frequency"] if k == self.rotation_order/2: j = (j+id[0]) % 2 change_of_basis = np.eye(irr.size) if irr.size > 1: irreps.append((0,)) change_of_basis = utils.psi(0.5 * id[0] * 2 * np.pi / self.rotation_order, k) irreps.append((j,)) elif id[0] is None: order = id[1] f = irr.attributes["frequency"] % order if f > order / 2: f = order - f change_of_basis = utils.chi(1) else: change_of_basis = np.eye(irr.size) r = (f,) irreps.append(r) if sg.irrep(*r).size < irr.size: irreps.append(r) elif id[0] is not None and id[1] > 1: order = id[1] f = irr.attributes["frequency"] j = irr.attributes["flip_frequency"] if f == self.rotation_order/2: j = (j+id[0]) % 2 k = f % order if k > order / 2: k = order - k change_of_basis = utils.chi(1) else: change_of_basis = np.eye(irr.size) r = (j, k) if sg.irrep(*r).size < irr.size: irreps.append((0, k)) irreps.append(r) else: irreps.append(r) if irr.size == 2: # change_of_basis = phi(0.5 * id[0], f) @ change_of_basis change_of_basis = utils.psi(0.5 * id[0] * 2 * np.pi / self.rotation_order, f) @ change_of_basis else: raise ValueError(f"id '{id}' not recognized") return change_of_basis, irreps def _build_representations(self): r""" Build the irreps and the regular representation for this group """ n = self.rotation_order # Build all the Irreducible Representations # add Trivial representation j, k = 0, 0 self.irrep(j, k) j = 1 for k in range(0, int(n//2)+1): self.irrep(j, k) if n % 2 == 0: j = 0 self.irrep(j, k) # Build all Representations # add all the irreps to the set of representations already built for this group self.representations.update(**{irr.name : irr for irr in self.irreps()}) # build the regular representation # N.B.: it represents the LEFT-ACTION of the elements self.representations['regular'] = self.regular_representation def _build_quotient_representations(self): r""" Build all the quotient representations for this group """ for n in range(2, int(math.ceil(math.sqrt(self.rotation_order)))): if self.rotation_order % n == 0: for f in range(2): sg_id = (f, n) self.quotient_representation(sg_id)
[docs] def bl_irreps(self, L: int) -> List[Tuple]: r""" Returns a list containing the id of all irreps of (rotational) frequency smaller or equal to ``L``. This method is useful to easily specify the irreps to be used to instantiate certain objects, e.g. the Fourier based non-linearity :class:`~escnn.nn.FourierPointwise`. """ assert 0 <= L <= self.rotation_order // 2, (L, self.rotation_order) irreps = [] n = self.rotation_order j, k = 0, 0 irreps.append((j, k)) j = 1 for k in range(0, L+1): irreps.append((j, k)) if n % 2 == 0 and L == self.rotation_order // 2: j = 0 irreps.append((j, k)) return irreps
@property def trivial_representation(self) -> Representation: return self.irrep(0, 0)
[docs] def irrep(self, j: int, k: int) -> IrreducibleRepresentation: r""" Build the irrep with reflecion and rotation frequencies :math:`j` (reflection) and :math:`k` (rotation) of the current dihedral group. Note: the frequencies has to be non-negative integers, i.e. :math:`j \in [0, 1]` and :math:`k \in \{0, \dots, \left\lfloor N/2 \right\rfloor \}`, where :math:`N` is the rotational order of the group (the number of rotations, i.e. the half the group order). If :math:`N` is odd, valid parameters are :math:`(0, 0)`, :math:`(1, 0)`, :math:`(1, 1)` ... :math:`(1, \left\lfloor N/2 \right\rfloor)`. If :math:`N` is even, the group also has the irrep :math:`(0, N/2)`. Args: j (int): the frequency of the reflections in the irrep k (int): the frequency of the rotations in the irrep Returns: the corresponding irrep """ N = self.rotation_order id = (j, k) assert j in [0, 1] assert 0 <= k <= N//2 name = f"irrep_{j},{k}" if id not in self._irreps: irrep = _build_irrep_dn(j, k) character = _build_char_dn(j, k) if j == 0: if k == 0: # Trivial representation supported_nonlinearities = ['pointwise', 'norm', 'gated', 'gate', 'concatenated'] self._irreps[id] = IrreducibleRepresentation(self, id, name, irrep, 1, 'R', supported_nonlinearities=supported_nonlinearities, # trivial=True, character=character, frequency=k, flip_frequency=j ) elif N % 2 == 0 and k == N//2: supported_nonlinearities = ['norm', 'gated', 'concatenated'] self._irreps[id] = IrreducibleRepresentation(self, id, name, irrep, 1, 'R', supported_nonlinearities=supported_nonlinearities, character=character, frequency=k, flip_frequency=j ) else: raise ValueError(f"Error! Flip frequency {j} and rotational frequency {k} don't correspond to any irrep of the group {self.name}!") else: if k == 0: # Trivial on Cyclic subgroup Representation supported_nonlinearities = ['norm', 'gated', 'concatenated'] self._irreps[id] = IrreducibleRepresentation(self, id, name, irrep, 1, 'R', supported_nonlinearities=supported_nonlinearities, character=character, frequency=k, flip_frequency=j ) elif N % 2 == 0 and k == N / 2: # 1 dimensional Irreducible representation (only for groups with an even number of rotations) supported_nonlinearities = ['norm', 'gated', 'concatenated'] self._irreps[id] = IrreducibleRepresentation(self, id, name, irrep, 1, 'R', supported_nonlinearities=supported_nonlinearities, character=character, frequency=k, flip_frequency=j ) else: # 2 dimensional Irreducible Representations supported_nonlinearities = ['norm', 'gated'] self._irreps[id] = IrreducibleRepresentation(self, id, name, irrep, 2, 'R', supported_nonlinearities=supported_nonlinearities, character=character, frequency=k, flip_frequency=j ) return self._irreps[id]
_cached_group_instances = {} @classmethod def _generator(cls, N: int) -> 'DihedralGroup': if N not in cls._cached_group_instances: cls._cached_group_instances[N] = DihedralGroup(N) return cls._cached_group_instances[N]
def _build_irrep_dn(j: int, k: int): def irrep(element: GroupElement, j=j, k=k) -> np.ndarray: N = element.group.rotation_order if j == 0: if k == 0: return np.eye(1) elif N % 2 == 0 and k == N // 2: return np.array([[np.cos(k * element.to('radians')[1])]]) else: raise ValueError( f"Error! Flip frequency {j} and rotational frequency {k} don't correspond to any irrep of the group {element.group.name}!") else: if k == 0: # Trivial on Cyclic subgroup Representation return np.array([[-1 if element.to('int')[0] else 1]]) elif N % 2 == 0 and k == N / 2: e = element.to('radians') # 1 dimensional Irreducible representation (only for groups with an even number of rotations) return np.array([[np.cos(k * e[1]) * (-1 if e[0] else 1)]]) else: # 2 dimensional Irreducible Representations e = element.to('radians') return utils.psichi(e[1], e[0], k=k) return irrep def _build_char_dn(j: int, k: int): def character(element: GroupElement, j=j, k=k) -> float: N = element.group.rotation_order if j == 0: if k == 0: return 1. elif N % 2 == 0 and k == N // 2: return np.cos(k * element.to('radians')[1]) else: raise ValueError( f"Error! Flip frequency {j} and rotational frequency {k} don't correspond to any irrep of the group {element.group.name}!") else: if k == 0: # Trivial on Cyclic subgroup Representation return -1 if element.to('int')[0] else 1 elif N % 2 == 0 and k == N / 2: e = element.to('radians') # 1 dimensional Irreducible representation (only for groups with an even number of rotations) return np.cos(k * e[1]) * (-1 if e[0] else 1) else: # 2 dimensional Irreducible Representations e = element.to('radians') return 0 if e[0] else (2 * np.cos(k * e[1])) return character # Cyclic ############################### def dn_to_cn(cn: escnn.group.CyclicGroup): def _map(e: GroupElement, cn=cn): assert isinstance(e.group, DihedralGroup) flip, rotation = e.to('int') ratio = e.group.rotation_order // cn.order() if flip == 0 and rotation % ratio == 0: return cn.element(rotation // ratio, 'int') else: return None return _map def cn_to_dn(dn: DihedralGroup): def _map(e: GroupElement, dn=dn): assert isinstance(e.group, escnn.group.CyclicGroup) ratio = dn.rotation_order // e.group.order() return dn.element( (0, e.to('int') * ratio), 'int' ) return _map # Flip wrt an axis ###################################### def dn_to_flip(axis: int, flip: escnn.group.CyclicGroup): assert isinstance(flip, escnn.group.CyclicGroup) and flip.order() == 2 def _map(e: GroupElement, flip=flip, axis=axis): assert isinstance(e.group, DihedralGroup) f, rot = e.to('int') if f == 0 and rot == 0: return flip.identity elif f == 1 and rot == axis: return flip.element(1) else: return None return _map def flip_to_dn(axis: int, dn: DihedralGroup): def _map(e: GroupElement, axis=axis, dn=dn): assert isinstance(e.group, escnn.group.CyclicGroup) and e.group.order() == 2 f = e.to('int') if f == 0: return dn.identity else: return dn.element((1, axis)) return _map # Dihedral Group ###################################### def dn_to_dm(axis: int, dm: escnn.group.DihedralGroup): assert isinstance(dm, escnn.group.DihedralGroup) def _map(e: GroupElement, dm=dm, axis=axis): assert isinstance(e.group, DihedralGroup) f, rot = e.to('int') ratio = e.group.rotation_order // dm.rotation_order if (rot - f*axis) % ratio != 0: return None else: return dm.element((f, (rot - f*axis) // ratio), 'int') return _map def dm_to_dn(axis: int, dn: DihedralGroup): def _map(e: GroupElement, axis=axis, dn=dn): assert isinstance(e.group, escnn.group.DihedralGroup) f, rot = e.to('int') ratio = dn.rotation_order // e.group.rotation_order return dn.element((f, rot * ratio + f * axis), 'int') return _map