-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_functions.sage
2274 lines (2046 loc) · 85 KB
/
main_functions.sage
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
## Contains definitions, classes and functions that are used in the
## other scripts.
from collections import Counter
from time import time
from pathlib import Path
import json
import sys
## quaternion_algebra
Q.<i,j,k> = QuaternionAlgebra(AA, -1, -1)
Q_in.<i_in,j_in,k_in> = QuaternionAlgebra(RDF, -1, -1)
## constants
ALMOST_ZERO = 1e-8
## useful unit quaternions [CS, Page 33]
sigma = (sqrt(5) - 1)/2
tau = (sqrt(5) + 1)/2
i_I = Q([0, 1/2, sigma/2, tau/2])
i_O = Q([0, 0, 1/sqrt(2), 1/sqrt(2)])
w = Q([-1/2, 1/2, 1/2, 1/2])
w_bar = w.conjugate()
e = lambda n: Q([cos(pi/n), sin(pi/n), 0, 0])
## other useful unit quaternions
sigma2 = (-sqrt(5) - 1)/2
tau2 = (-sqrt(5) + 1)/2
i_I_dag = Q([0, 1/2, sigma2/2 , tau2/2]) # DuVal
i_I2 = Q([0, -sigma/2, -tau/2, 1/2]) # i'_I in [Cs, Table 4.2]
## useful functions
def nearby_rational_angle(angle):
"""
Return a rational number `a` such that `a*pi` approximates `angle`.
"""
return (angle/pi).n().nearby_rational(ALMOST_ZERO)
def quaternion_classify(el):
"""
Classify the quaternion e by conjugacy type.
"""
return nearby_rational_angle(arccos(el[0]))
class quat_2D:
"""
Elements of the (binary) dihedral group 2D_2n.
An instance `quat_2D(alpha, p)` represents the quaternion
`(cos(alpha*pi) + i*sin(alpha*pi))*j^p`.
Here 0<=alpha<2 and p is 0 or 1.
"""
def __init__(self, alpha=0, p=0):
self.alpha = quat_2D.mod2(alpha)
self.p = p % 2
def __eq__(self,other):
return self.alpha == other.alpha and self.p == other.p
def __hash__(self):
return hash((self.alpha,self.p))
def __mul__(self, other):
if self.p == 0:
return quat_2D(self.alpha+other.alpha, other.p)
if other.p == 0:
return quat_2D(self.alpha-other.alpha, 1)
return quat_2D(1+self.alpha-other.alpha)
def __pow__(self,n):
if n == 0:
return quat_2D(0)
if n > 0:
x=x0 = quat_2D(self.alpha,self.p)
else:
if self.p == 0:
x=x0 = quat_2D(-self.alpha)
else:
x=x0 = quat_2D(1+self.alpha,-1)
for _ in range(abs(n)-1):
x *= x0
return x
def classify(self):
"""
Classify by conjugacy type.
"""
if self.p:
return 1/2 # arccos(0)
return min(self.alpha, 2-self.alpha)
def conjugate(self):
if self.p == 0:
return quat_2D(2-self.alpha)
else:
return quat_2D(1+self.alpha, 1)
def swap(self,n):
"""
Conjugate (3d-rotation) self with the quaternion
special_quaternions[n] (normalized).
The following special quaternions:
j+k (n=4), j-k (n=5), 1+i (n=6), i(n=9), j(n=10), k(n=11)
normalize the group Dn_group.
The other special quaternions only normalize the group
Q8 = {+-1, +-i, +-j, +-k}.
"""
# identity
if n<0: return self
special_quaternion = special_quaternions[n]
# ones which preserve Dn_group
if special_quaternion == j+k:
if self.p: return quat_2D(1/2-self.alpha, 1)
else: return quat_2D(-self.alpha, 0)
if special_quaternion == j-k:
if self.p: return quat_2D(3/2-self.alpha, 1)
else: quat_2D(-self.alpha, 0)
if special_quaternion == 1+i:
if self.p: return quat_2D(self.alpha-1/2, 1)
else: return quat_2D(self.alpha, 0)
if special_quaternion == i:
if self.p: return quat_2D(1+self.alpha, 1)
else: return quat_2D(self.alpha, 0)
if special_quaternion == j:
if self.p: return quat_2D(-self.alpha, 1)
else: return quat_2D(-self.alpha, 0)
if special_quaternion == k:
if self.p: return quat_2D(1-self.alpha, 1)
else: return quat_2D(-self.alpha, 0)
# one which preserve Q8
if self.alpha not in (0, 1/2, 1, 3/2):
raise ValueError("alpha not a multiple of 1/2")
return self.swap_dict[n][self]
def mod2(alpha):
while alpha < 0:
alpha += 2
while alpha >= 2:
alpha -= 2
return alpha
def to_quaternion(self):
return (cos(self.alpha*pi).n()+i_in*sin(self.alpha*pi).n()) * j_in^self.p
def to_exact_quaternion(self):
return (AA(cos(self.alpha*pi)) + i*AA(sin(self.alpha*pi))) * j^self.p
def __str__(self):
if self.p:
if self.alpha == 0:
return "j"
elif self.alpha == 1:
return "-j"
elif self.alpha == 1/2:
return "k"
elif self.alpha == 3/2:
return "-k"
return f"e^{self.alpha}*j"
else:
if self.alpha==0:
return "1"
elif self.alpha==1:
return "-1"
elif self.alpha==1/2:
return "i"
elif self.alpha==3/2:
return "-i"
return f"e^{self.alpha}"
def __repr__(self):
return f"quat_2D({self.alpha},{self.p})"
## usually used quat_2D elements
quat_i = quat_2D(1/2,0)
quat_j = quat_2D(0,1)
quat_k = quat_i*quat_j
quat_1 = quat_2D(0)
quat_minus1 = quat_2D(1)
## fill quat_2D.swap_dict
special_quaternions = [i+j, i-j, i+k, i-k, j+k, j-k,
1+i, 1-i, 1+j, 1-j, 1+k, 1-k,
i, j, k,
1+i+j+k, 1-i+j+k, 1+i-j+k, 1+i+j-k,
1-i-j+k, 1-i+j-k, 1+i-j-k, 1-i-j-k
]
def fill_swap_dict(verbose=False):
units = list(a*b for a in (quat_1, quat_minus1) for b in (quat_1, quat_i, quat_j, quat_k))
quat_2D.swap_dict = []
for n,q in enumerate(special_quaternions):
if verbose:
for e in (i,j,k):
print (f"type {n}. conjugation with ({q}) maps",e,"->",q^-1*e*q)
res = dict()
q = Q_in(list(q))
for e in units:
ee = q^-1*e.to_quaternion()*q
for f in units:
if norm(vector(f.to_quaternion()-ee))<1e-2:
res[e]=f
break
else:
raise "something is wrong"
quat_2D.swap_dict.append(res)
return
fill_swap_dict()
def tests_on_swap_dict():
units = list(a*b for a in (quat_1, quat_minus1) for b in (quat_1, quat_i, quat_j, quat_k))
for n,q in enumerate(special_quaternions):
for e in units:
ee = q^-1*e.to_exact_quaternion()*q
assert ee == e.swap(n).to_exact_quaternion(), n
return
# tests_on_swap_dict()
class FDR:
"""
A 4-dimensional orthogonal transformation [l, r] or *[l, r], where
[l, r]x: x -> l.conjugate() * x * l
is orientation preserving and,
*[l, r]x: x -> l.conjugate() * x.conjugate() * l
is orientation reversing.
INPUT:
- `l` -- quaternion or ``quat_2d``: A unit quaternion.
- `r` -- quaternion or ``quat_2d``: A unit quaternion.
- `star` -- boolean (default: ``False``): If ``False`` construct [l, r].
If `True` construct *[l, r].
"""
def __init__(self, l, r, star=False):
self.l = l
self.r = r
self.star = star
def act(self, x):
"""
Return that action of self on x, where x is a quaternion.
"""
if self.star:
x = x.conjugate()
l_bar = self.l.conjugate()
if type(l_bar) is quat_2D:
l_bar = l_bar.to_exact_quaternion()
r = self.r
if type(r) is quat_2D:
r = r.to_exact_quaternion()
return l_bar*x*r
def __mul__(self,other):
if other.star:
return FDR(self.r*other.l, self.l*other.r, not self.star)
else:
return FDR(self.l*other.l, self.r*other.r, self.star)
def inverse(self):
if self.star:
return FDR(self.r.conjugate(), self.l.conjugate(), True)
else:
return FDR(self.l.conjugate(), self.r.conjugate())
def classify(self):
"""
Classify self by its conjugacy type.
For [l, r] return (a, b) with 0 <= a, b <= 1 where
[l, 1] is a left rotation by +/- a*pi and
[1, r] is a right rotation by +- b*pi.
The pair [-l,-r], which represents the same rotation,
will yield the pair (1-a,1-b).
(Since the groups that are considered
are closed under taking negatives,
both equivalent possibilities will be present.)
Hence, we normalize by requiring that a<b or a=b<=1/2.
For *[l, r] return (7, b) with 0 <= b <= 1
representing a rotation-reflection by +/- (1-b)*pi.
"""
if self.star:
try:
lr = self.l*self.r
# except KeyError:
except (TypeError, AttributeError) as e:
if type(self.l) is quat_2D:
lr = self.l.to_exact_quaternion()*self.r
else:
lr = self.l * self.r.to_exact_quaternion()
try:
c = lr.classify()
except AttributeError:
c = quaternion_classify(lr)
return (7,c)
try:
cl = self.l.classify()
except AttributeError:
cl = quaternion_classify(self.l)
try:
cr = self.r.classify()
except AttributeError:
cr = quaternion_classify(self.r)
if cl > cr or cl == cr > 1/2:
return (1-cl,1-cr) # normalize
return (cl,cr)
def __str__(self):
brak = f"[{str(self.l)}, {str(self.r)}]"
if self.star:
return "*"+brak
return brak
def __repr__(self):
s = ""
if self.star:
s = ",1"
return f"FDR({self.l!r}, {self.r!r}{s})"
def __eq__(self,other):
return self.l == other.l and self.r == other.r and self.star == other.star
def __hash__(self):
return hash((self.l, self.r, self.star))
def to_exact_quaternions(self):
"""
return self with quaternion left and right components.
"""
newl = self.l.to_exact_quaternion() if isinstance(self.l, quat_2D) else self.l
newr = self.r.to_exact_quaternion() if isinstance(self.r, quat_2D) else self.r
return FDR(newl, newr, self.star)
def to_matrix(self):
"""
return matrix represnetation of self.
"""
M = [(self.act(a)).coefficient_tuple() for a in Q.basis()]
return matrix(Q.base_ring(), M).transpose()
## mixed one
one_HQ = FDR(Q(1),quat_1)
one_QH = FDR(quat_1,Q(1))
def element_chars(el):
"""
If `el` is instance of `quat_2D`, return `(quat_1, quat_minus1)`.
Else, return `(Q(1), Q(-1))`.
"""
if isinstance(el, quat_2D):
return quat_1, quat_minus1#, Dn_group # or Cn_group
return Q(1), Q(-1)#, Q_group
def mk_group(gens, one=None, limit=30000):
"""
Return the group generated by elements in `gens`.
INPUT:
- `gens` -- list: Generators.
- `one` -- any: The one of the group.
- `limit` -- int: Run time bound on the order of the group.
"""
if one is None:
if isinstance(gens[0], FDR):
one = FDR(element_chars(gens[0].l)[0], element_chars(gens[0].r)[0])
else:
one = Q(1)
# maintain group as a list because group
# elements are generated in a unique order
G = [one]
G_set = {G[0]}
new_in_G = list(G)
while new_in_G:
to_come = []
for g in new_in_G:
for h in gens:
new_g = g*h
if new_g not in G_set:
G.append(new_g)
G_set.add(new_g)
to_come.append(new_g)
if limit and len(G) > limit:
raise ValueError("group size over the limit")
new_in_G = to_come
return G
## Hurley
Hurley_table = { # [Brown et al., Page 55]
(-4, 6, 1): ("I'",'2222'),
(-3, 4, 1): ("Z'",'322'),
(-2, 0, -1): ("T'",'2221'),
(-2, 2, 1): ("R'",'422'),
(-2, 3, 1): ("S'",'33'),
(-1, 0, -1): ("N'",'321'),
(-1, 0, 1): ("K'",'622'),
(-1, 1, 1): ("L'",'5'),
(-1, 2, 1): ("M'",'43'),
(0, -2, 1): ("E",'2211'),
(0, -1, 1): ("C",'T=12'),
(0, 0, -1): ("F",'421'),
(0, 0, 1): ("A",'8'),
(0, 1, 1): ("B",'63'),
(0, 2, 1): ("D",'44'),
(1, 0, -1): ("N",'621'),
(1, 0, 1): ("K",'311'),
(1, 1, 1): ("L",'X=10'),
(1, 2, 1): ("M",'64'),
(2, 0, -1): ("T",'2111'),
(2, 2, 1): ("R",'411'),
(2, 3, 1): ("S",'66'),
(3, 4, 1): ("Z",'611'),
(4, 6, 1): ("I",'1111'),
}
Hurley_conversion = {
(7, 1/3): (1, 0, -1),
(11/12, 7/12): (1, 2, 1),
(1/6, 1/2): (0, 1, 1),
(1/2, 5/6): (0, 1, 1),
(7, 2/3): (-1, 0, -1),
(1, 2/3): (2, 3, 1),
(1/12, 5/12): (1, 2, 1),
(1/2, 1/2): (0, -2, 1),
(1/4, 3/4): (-2, 2, 1),
(1/2, 1/3): (0, -1, 1),
(2/3, 0): (-2, 3, 1),
(1/3, 0): (2, 3, 1),
(5/12, 1/12): (1, 2, 1),
(2/3, 1): (2, 3, 1),
(1/3, 1): (-2, 3, 1),
(1/6, 1/6): (3, 4, 1),
(2/3, 1/3): (-1, 0, 1),
(3/4, 3/4): (2, 2, 1),
(1/3, 1/3): (1, 0, 1),
(1/2, 3/4): (0, 0, 1),
(1, 0): (-4, 6, 1),
(7/12, 1/12): (-1, 2, 1),
(5/6, 5/6): (3, 4, 1),
(1/5, 3/5): (-1, 1, 1),
(0, 0): (4, 6, 1),
(2/3, 2/3): (1, 0, 1),
(1/3, 2/3): (-1, 0, 1),
(0, 1): (-4, 6, 1),
(5/6, 1/2): (0, 1, 1),
(1/4, 1/2): (0, 0, 1),
(11/12, 5/12): (-1, 2, 1),
(7, 1/2): (0, 0, -1),
(4/5, 2/5): (-1, 1, 1),
(1, 1/3): (-2, 3, 1),
(0, 1/3): (2, 3, 1),
(1/4, 1/4): (2, 2, 1),
(4/5, 3/5): (1, 1, 1),
(0, 2/3): (-2, 3, 1),
(1/2, 1): (0, 2, 1),
(3/4, 1/2): (0, 0, 1),
(5/6, 1/6): (-3, 4, 1),
(3/4, 1/4): (-2, 2, 1),
(1/12, 7/12): (-1, 2, 1),
(1/2, 1/4): (0, 0, 1),
(2/5, 1/5): (1, 1, 1),
(3/5, 1/5): (-1, 1, 1),
(1/2, 2/3): (0, -1, 1),
(2/3, 1/2): (0, -1, 1),
(1/5, 2/5): (1, 1, 1),
(1/3, 1/2): (0, -1, 1),
(5/12, 11/12): (-1, 2, 1),
(1/2, 1/6): (0, 1, 1),
(7, 0): (2, 0, -1),
(7, 1): (-2, 0, -1),
(2/5, 4/5): (-1, 1, 1),
(1, 1): (4, 6, 1),
(3/5, 4/5): (1, 1, 1),
(1, 1/2): (0, 2, 1),
(7/12, 11/12): (1, 2, 1),
(0, 1/2): (0, 2, 1),
(1/2, 0): (0, 2, 1),
(1/6, 5/6): (-3, 4, 1)
}
def Hurley_pattern(pattern):
"""
Convert "our" classification code (pairs (a,b) with multiplicities)
into Hurley-pattern; divide multiplicities by 2
"""
try:
H_cla = {}
for code in pattern.split():
# decode into class,num
class_code, num_code = code.split(":")
num = Integer(num_code)
if class_code[0]=="*":
clas = 7, Rational(class_code[1:])
else:
if "/" in class_code:
a, denominator_code = class_code.split("/")
denominator = Integer(denominator_code)
class_code = a
else:
denominator = 1
a, b = class_code.split("|")
clas = Integer(a)/denominator, Integer(b)/denominator
h3 = Hurley_conversion[clas]
hcode, _ = Hurley_table[h3]
H_cla[hcode] = H_cla.get(hcode,0) + num
H_cl = []
for k,num in sorted(H_cla.items()):
assert num % 2 == 0
H_cl.append(f"{num//2}*{k}")
return " ".join(H_cl)
except KeyError:
return # definitely not a crystallographic group.
# print("Hermann-symbol / our class. / Hurley symbol / Hurley triplet")
# for x in sorted((he,cl,hu,hurley3) for cl,hurley3 in Hurley_conversion.items()
# for hu,he in (Hurley_table[hurley3],)):
# print("{0:6} ({1[0]!s:5},{1[1]!s:5}) {2:4} ({3[0]:-2},{3[1]:3},{3[2]:3})".format(*x))
class Q_group:
"""
Quaternion group.
INPUT:
- `gens` -- list of quaternions or `quat_2D`'s: Generators of the group.
- `limit` -- int: Run time bound on the order of the group.
"""
def __init__(self, gens, limit=None):
self.gens = gens
self.one, self.minus_1 = element_chars(gens[0])
self.q = mk_group(self.gens, self.one, limit)
self.order = len(self.q)
def ensure_number(self):
"""
Construct `self.p_conjugate`, the permutation that maps
every element to its conjugate (=inverse).
"""
if hasattr(self,"number"):
return
self.number = {e:i for i,e in enumerate(self.q)} # start from 0
self.p_conjugate = Permutation([self.number[e.conjugate()]+1 for e in self.q])
def ensure_pgroup(self):
"""
construct `self.p_group`, the permutation group of `self`.
"""
if hasattr(self,"pgroup"):
return
self.ensure_number()
self.pgens = [self.mk_permutation(e) for e in self.gens]
pgens_cycles = [Permutation([x+1 for x in perm]).cycle_string() for perm in self.pgens]
self.pgroup = PermutationGroup(pgens_cycles)
def ensure_name_from_perm(self):
if hasattr(self,"name_from_perm"):
return
self.name_from_perm = {tuple(self.mk_permutation(e)):e for e in self.q}
def mk_permutation(self,e):
"""
right multiplication by e, represented as a permutation.
"""
return ([self.number[g*e] for g in self.q])
class Dn_group(Q_group):
"""
Quaternion group 2D_n (`n` even) of order 2n.
"""
def __init__(self, n):
assert n % 2 == 0
gens = [quat_2D(2/n), quat_2D(0,1)]
Q_group.__init__(self, gens)
class Cn_group(Q_group):
"""
Quaternion group 2C_n of order 2n.
"""
def __init__(self, n):
gens = [quat_2D(1/n)]
Q_group.__init__(self, gens)
def compress_pair(a, b):
"""
Compressed notation for the rational pair `(a, b)`. This is,
`a*n|b*n/n where n is the common denominator of `a` and `b`.
"""
if a == 7:
return f"*{b!s}"
an,ad = a.numerator(),a.denominator()
bn,bd = b.numerator(),b.denominator()
n = lcm(ad,bd)
res = f"{a*n}|{b*n}"
if n>1:
res += f"/{n}"
return res
def classify_group(gr):
"""
Classify a group according to the multiplicities of its
elements in the different geometric conjugacy classes.
`gr` is a list of group elements.
"""
multi = Counter()
for el in gr:
c = el.classify()
multi[c] += 1
# turn classification into a compact string
return " ".join(f"{compress_pair(a,b)}:{c}" for (a,b),c in sorted(multi.items()))
def group_string_rep(gr):
"""
A way to represent the group as a string.
"""
if type(gr) != list:
gr = gr.group
return " ".join(sorted(map(str,gr)))
class AxB_group:
"""
AxB group of a 4-dimensional point group.
In this group, both [l, r] and [-l, -r] are presented as distinct
elements. Hence, this group contains twice the number of elements of
the corresponding point group.
INPUT:
- `gens` -- list of FDR's: Generators of the group.
- `name` -- str: Group name.
- `limit` -- int: Run time bound on the order of the group.
- `group` -- list of FDR's: In case group is already generated.
In this case, gens is also required and should has the
same data type as group.
"""
def __init__(self, gens, name=None, limit=None, group=None):
self.gens = gens
self.name = name
self.limit = limit
self.achiral = any(e.star for e in gens)
l_one, l_minus1 = element_chars(gens[0].l)
r_one, r_minus1 = element_chars(gens[0].r)
self.one = FDR(l_one,r_one)
self.minus_1_minus_1 = FDR(l_minus1, r_minus1)
self.group = group if group else mk_group(gens, one=self.one, limit=limit)
self.order = len(self.group)
def show(self):
return list(str(e) for e in self.group)
def __repr__(self):
name = "a point group"
if self.name: name = self.name
return f"AxB group of {name} of order {self.order//2}"
def __eq__(self, other):
return set(self.group) == set(other.group)
def classify_group(self):
"""
Classify the group according to the multiplicities of
its elements in the conjugacy classes.
"""
return classify_group(self.group)
def Hurley_pattern(self):
"""
Classify the group according the conjugacy classes of
Hurley for crystallographic groups.
"""
return Hurley_pattern(classify_group(self.group))
def ensure_groups(self):
"""
Generate the left and the right quaternion groups Q1 and Q2.
"""
if hasattr(self,"Q1") and hasattr(self.Q1,"number"):
return
self.Lgens = [e.l for e in self.gens]
self.Rgens = [e.r for e in self.gens]
if self.achiral:
self.Lgens += self.Rgens
self.Rgens = self.Lgens
self.Q1 = self.Q2 = Q_group(self.Lgens)
self.Q1.ensure_number()
else:
self.Q1 = Q_group(self.Lgens)
self.Q2 = Q_group(self.Rgens)
self.Q1.ensure_number()
self.Q2.ensure_number()
self.nL = self.Q1.order
self.nR = self.Q2.order
def ensure_pgroup(self):
"""
If self is chiral, construct the permutation group of the AxB group.
If self is achiral, construct the permutation group of the
corresponding point group. Hence, its order is half the order
of the AxB group.
"""
if hasattr(self,"pgroup"):
return
self.ensure_groups()
if not self.achiral:
pgens = []
for g in self.gens:
pl = self.Q1.mk_permutation(g.l)
pr = self.Q2.mk_permutation(g.r)
pair = self.pair_permutation(pl,pr)
pgens.append(pair)
self.pgroup = PermutationGroup(pgens)
pl = self.Q1.mk_permutation(self.Q1.minus_1)
pr = self.Q2.mk_permutation(self.Q2.minus_1)
self.Pminus_1_minus_1 = self.pair_permutation(pl,pr)
assert self.pgroup.order() == self.order, (self.name,"WR-CHIRAL")
return
else: # achiral
# represent as a permutation group acting on some elements.
# Add i,j,k to the elements, to make sure the action is faithful.
# But [-1,-1] is the identity permutation. So we only get HALF
# of the elements.
# This would also be possible for the chiral groups, but
# then it would not be easy to translate the permutations
# into [l,r] pairs.
def to_permutation(g):
"""permutation as sequence of numbers 1,2,...."""
if g.star:
return (elementnumber[
g.l.conjugate() * e1.conjugate() * g.r ]+1
for e1 in elements)
else:
return (elementnumber[
g.l.conjugate() * e1 * g.r ]+1 for e1 in elements)
if type(self.group[0].l) is quat_2D:
extension_elements = [quat_i,quat_j,quat_k]
else:
extension_elements = [i,j,k]
elements = mk_group(self.Q1.gens + extension_elements, self.Q1.one, self.limit)
elementnumber = {e:i for i,e in enumerate(elements)}
# start from 0
self.to_AxB_group = {tuple(to_permutation(g)): g for g in self.group}
pgens = [Permutation(to_permutation(g)) for g in self.gens]
self.pgroup = PermutationGroup(pgens)
assert 2*self.pgroup.order() == self.order, (self.name,"WR-ACHIRAL")
def pair_permutation(self, perm1, perm2):
"""
Representation of [l,r] as a permutation, where
`l=perm1` and `r=perm2` are represented as permutations
(lists starting at 0).
"""
assert not self.achiral
p = Permutation([x+1 for x in perm1]+[x+self.nL+1 for x in perm2])
return p.cycle_string()
def is_isomorphic(self,other):
self.ensure_pgroup()
other.ensure_pgroup()
return self.pgroup.is_isomorphic(other.pgroup)
def conjugate_group(self, q1, q2=None, scale1=None, scale2=None):
"""
Conjugate the group elements.
See self.conjugate_element documentation.
"""
return [self.conjugate_element(f, q1, q2, scale1, scale2) for f in self.group]
@staticmethod
def conjugate_element(f, q1, q2=None, scale1=None, scale2=None):
"""
Conjugate `f` by `FDR(q1, q2)`.
Here `q1` (and `q2`) can be either:
* quaternion: if it is not normalized, then its norm squared,
scale1, should be provided.
* a 2-tuple `("S", n)`: meaning `f.l.swap(n)`.
* a 3-tuple `("S", n, qq1)`: meaning `qq1.conjugate()*f.l.swap(n)*qq1`.
"""
# set up left and right conjugation maps.
if type(q1) is tuple and q1[0]=="S":
n1 = q1[1]
if f.star:
if q1==q2 and len(q1)==2:
return FDR(f.l.swap(n1),f.r.swap(n1),True)
q2,scale2 = q1,scale1 #
raise NotImplementedError
if len(q1)==2:
conjugate_left = lambda e: e.swap(n1)
else:
qq1 = q1[2]
conjugate_left = lambda e: qq1.conjugate()*e.swap(n1)*qq1
# could try swap before or after
elif q1 is None:
conjugate_left = lambda e: e
elif scale1:
conjugate_left = lambda e: q1.conjugate()*e*q1*scale1
else:
conjugate_left = lambda e: q1.conjugate()*e*q1
if type(q2) is tuple and q2[0]=="S":
if f.star:
raise NotImplementedError
n2 = q2[1]
if len(q2)==2:
conjugate_right = lambda e: e.swap(n2)
else:
qq2 = q2[2]
conjugate_right = lambda e: qq2.conjugate()*e.swap(n2)*qq2
elif q2 is None:
conjugate_right = lambda e: e
elif scale2:
conjugate_right = lambda e: q2.conjugate()*e*q2*scale2
else:
conjugate_right = lambda e: q2.conjugate()*e*q2
if f.star:
if type(f.l) is quat_2D:
if scale1 not in [None, quat_1]:
raise ValueError
if scale2 not in [None, quat_1]:
raise ValueError
scale1s = quat_1
scale2s = quat_1
else:
scale1s = AA(sqrt(scale1)) if scale1 else 1
scale2s = AA(sqrt(scale2)) if scale2 else 1
if q2 is None:
return FDR(f.l*q1*scale1s, q1.conjugate()*f.r*scale1s, True)
else:
return FDR(q2.conjugate()*f.l*q1*scale1s*scale2s, q1.conjugate()*f.r*q2*scale1s*scale2s, True)
else:
return FDR(conjugate_left(f.l), conjugate_right(f.r), False)
def find_conjugation(self, other):
"""
Try to find conjugation between the two AxB groups.
If the groups are not conjugate, return `False`.
If the groups are conjugate, try to find the conjugation.
If the conjugation if found, return `True` and set the values
for `self.conj_name` and `self.conj_latex`.
If the conjugation is not found, raise `NotImplementedError`.
IMPORTANT:
The procedure does not guarantee to find the conjugation. It
only tests a set of special conjugations.
If the components of the elements of self are `quat_2D`, then
the procedure is faster. However, it tries a smaller set of
special quaternions.
If the components of the elements of self are quaternions,
the procedure tries a larger set of special conjugations.
Thus, it is recommended to convert the elements to be so
by using `self.to_exact_quaternion_group()`. However, this is
slower.
If the components of the elements of self are mixed of quaternions
and `quat_2D`'s, then the procedure starts by converting both
components to be quaternions by calling
`self.to_exact_quaternion_group()`.
"""
def check_equality(gr):
"""
Check if gr and other are the same.
"""
if group_string_rep(gr) == other_string:
return True
return False
def check_equality_elementwise(gr):
"""
Check if gr and other (H) are the same.
(This is used as a fallback if check_equality fails)
(Only used if components of elements of gr are quaternions)
"""
if set(gr) == H_set:
return True
return False
def swap_to_latex(n, qq=Q(1)):
"""
Convert the given conjugation to latex
"""
if isinstance(qq, quat_2D):
qq = qq.to_exact_quaternion()
if n < 0:
q = qq
else:
q = special_quaternions[n]*qq
if q.reduced_norm() == 2:
s = "\\frac1\\sqrt2"
elif q.reduced_norm() == 4:
s = "\\frac12"
elif q.reduced_norm() == 1:
s = "1"
else:
raise
return f"{s}({q})"
## check if they are conjugate
if self.classify_group() != other.classify_group():
return False
## construct group string of other
other_string = group_string_rep(other.group)
assert other_string == " ".join(sorted(other.show()))
## conjugations for quat_2D groups
only_quat_2D = type(self.group[0].l) is quat_2D and type(self.group[0].r) is quat_2D
if only_quat_2D:
## conjugation by elements of Q8
units = list(a*b for a in (quat_1, quat_minus1) for b in (quat_1, quat_i, quat_j, quat_k))
for unit1 in units:
for unit2 in units:
G_conj = self.conjugate_group(unit1, unit2)
if check_equality(G_conj):
self.conj_name = f"[{unit1}, {unit2}]"
self.conj_latex = f"[{unit1}, {unit2}]"
return True
## S conjugations from left
for n in range(-1, len(special_quaternions)):
try:
G_conj = self.conjugate_group(("S", n))
if check_equality(G_conj):
self.conj_name = f"[S_{{{n}}}, 1]"
self.conj_latex = f"[{swap_to_latex(n)}, 1]"
return True
# for unit in [quat_i, quat_j, quat_k]:
# G_conj_temp = [self.conjugate_element(e, unit) for e in G_conj]
# if check_equality(G_conj_temp):
# self.conj_name = f"[S_{{{n}}}, 1][{unit.to_exact_quaternion()}, 1]"
# self.conj_latex = f"[{swap_to_latex(n, unit)}, 1]"
# return True
except (ValueError, NotImplementedError):
continue
## S conjugations from right
for n in range(0, len(special_quaternions)):
try:
G_conj = self.conjugate_group(("S", -1), ("S", n))
if check_equality(G_conj):
self.conj_name = f"[1, S_{{{n}}}]"
self.conj_latex = f"[1, {swap_to_latex(n)}]"
return True
# for unit in [quat_i, quat_j, quat_k]:
# G_conj_temp = [self.conjugate_element(e, unit) for e in G_conj]
# if check_equality(G_conj_temp):
# self.conj_name = f"[1, S_{{{n}}}][{unit.to_exact_quaternion()}, 1]"
# self.conj_latex = f"[1, {swap_to_latex(n, unit)}]"
# return True
except (ValueError, NotImplementedError):
continue
## S conjugations from both sides
for n1 in range(0, len(special_quaternions)):
for n2 in range(0, len(special_quaternions)):
try:
G_conj = self.conjugate_group(("S", n1), ("S", n2))
if check_equality(G_conj):
self.conj_name = f"[S_{{{n1}}}, S_{{{n2}}}]"
self.conj_latex = f"[{swap_to_latex(n1)}, {swap_to_latex(n2)}]"
return True
# for unit1 in [quat_i, quat_j, quat_k]:
# for unit2 in [quat_i, quat_j, quat_k]:
# G_conj_temp = [self.conjugate_element(e, unit1, unit2) for e in G_conj]
# if check_equality(G_conj_temp):
# self.conj_name = f"[S_{{{n1}}}, S_{{{n2}}}][{unit1.to_exact_quaternion()}, {unit2.to_exact_quaternion()}]"
# self.conj_latex = f"[{swap_to_latex(n1, unit1)}, {swap_to_latex(n2, unit2)}]"
# return True
except (ValueError, NotImplementedError):
continue
# (S, alpha) conjugations from both sides
# look for elements of the form [(alpha,1),r] or [r,(alpha,1)] without star
alpha_left2 = set(e.l.alpha for e in other.group if not e.star and e.l.p)
alpha_right2 = set(e.r.alpha for e in other.group if not e.star and e.r.p)
for n1 in range(-1, len(special_quaternions)):
for n2 in range(-1, len(special_quaternions)):
try:
G_conj = self.conjugate_group(("S", n1), ("S", n2))
alpha_left = set(e.l.alpha for e in G_conj if not e.star and e.l.p)
alpha_right = set(e.r.alpha for e in G_conj if not e.star and e.r.p)
diffs_left = set((alpha-alpha2)/2 for alpha in alpha_left for alpha2 in alpha_left2)
diffs_right = set((alpha-alpha2)/2 for alpha in alpha_right for alpha2 in alpha_right2)
if not diffs_left: diffs_left = [0]
if not diffs_right: diffs_right = [0]
diffs_left = self.sort_by_abs_value(diffs_left)
diffs_right = self.sort_by_abs_value(diffs_right)