-
Notifications
You must be signed in to change notification settings - Fork 42
/
dihedralgroup.py
793 lines (579 loc) · 30.2 KB
/
dihedralgroup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
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"]
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)))
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
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)
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)
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