-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPyLie.py
2186 lines (2058 loc) · 106 KB
/
PyLie.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
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
__author__ = 'florian'
"""
PyLie is a python module for Lie group calculation for particle physics. In particular, it can manipulate any of the Lie
algebra, calculate the system of roots, weights, casimir, dynkin, Matrix representation and Invariants of the product of
several irrep.
It is a python implementation of the Susyno group method.
"""
import sys
sys.path.insert(0, '/Applications/HEPtools/sympy-1.0')
import numpy as np
try:
from sympy import *
except ImportError:
print("Error, importing sympy.")
exit("Error, importing sympy.")
import time
from sympy.combinatorics import Permutation
import copy as cp
import operator
import itertools
class CartanMatrix(object):
"""
Represents a Cartan Matrix
"""
def __init__(self, name, Id):
self._translation = {"SU": "A", "SP": "C", "SO": ("B", "D")}
self._classicalLieAlgebras = ["A", "B", "C", "D"]
self._name = name
self._id = Id
self.cartan = [] # store the Cartan matrix
self._constructCartanMatrix()
def _constructCartanMatrix(self):
if not (self._name in self._classicalLieAlgebras):
if self._name in self._translation:
if self._name == "SU":
self._id -= 1
self._name = self._translation[self._name]
return self._constructCartanMatrix()
elif self._name == "SP":
if self._id % 2 == 0:
self._id /= 2
self._name = self._translation[self._name]
return self._constructCartanMatrix()
else:
print("error 'SP' Id number must be even")
return
elif self._name == "SO" and self._id % 2 == 0:
if self._id < 5:
print("Error n >=3 or > 4 for SO(n)")
return
self._id /= 2
self._name = self._translation[self._name][1]
return self._constructCartanMatrix()
elif self._name == "SO" and self._id % 2 == 1:
self._id = (self._id - 1) / 2
self._name = self._translation[self._name][0]
return self._constructCartanMatrix()
else:
print"Error unknown Lie Algebra, try 'A', 'B','C' or 'D'"
return
if self._name in ["A", "B", "C"] and self._id == 1:
self.cartan = SparseMatrix([2])
if self._name == "A" and self._id > 1:
self.cartan = SparseMatrix(self._id, self._id, lambda i, j: self._fillUpFunctionA(i, j))
elif self._name == "B" and self._id > 1:
self.cartan = SparseMatrix(self._id, self._id, lambda i, j: self._fillUpFunctionB(i, j))
self.cartan[self._id - 2, self._id - 1] = -2
elif self._name == "C" and self._id > 1:
self.cartan = SparseMatrix(self._id, self._id, lambda i, j: self._fillUpFunctionC(i, j))
self.cartan[self._id - 1, self._id - 2] = -2
elif self._name == "D" and self._id > 1:
self.cartan = SparseMatrix(self._id, self._id, lambda i, j: self._fillUpFunctionD(i, j))
self.cartan[self._id - 1, self._id - 2] = 0
self.cartan[self._id - 2, self._id - 1] = 0
self.cartan[self._id - 1, self._id - 3] = -1
self.cartan[self._id - 3, self._id - 1] = -1
def _fillUpFunctionA(self, i, j):
if i == j:
return 2
elif i == j + 1 or j == i + 1:
return -1
else:
return 0
def _fillUpFunctionB(self, i, j):
return self._fillUpFunctionA(i, j)
def _fillUpFunctionC(self, i, j):
return self._fillUpFunctionA(i, j)
def _fillUpFunctionD(self, i, j):
return self._fillUpFunctionA(i, j)
class LieAlgebra(object):
"""
This is the central class implmenting all the method that one can perform on the lie algebra
"""
def __init__(self, cartanMatrix):
self.cartan = cartanMatrix
self.cm = self.cartan.cartan
self._n = self.cm.shape[0] # size of the n times n matrix
self.cminv = self.cm.inv() # inverse of the Cartan matrix
self.ncminv = matrix2numpy(self.cminv) # numpy version of the inverse of the Cartan matrix
self.ncm = matrix2numpy(self.cm) # numpy version of the Cartan Matrix
self._matD = self._matrixD() # D matrix
self._smatD = self._specialMatrixD() # Special D matrix
self._cmID = np.dot(self.ncminv, self._matD) # matrix product of the inverse Cartan matrix and D matrix
self._cmIDN = self._cmID / np.max(self._matD) # same as cmID but normalized to the max of matD
self.proots = self._positiveRoots() # calc the positive roots
# Sum the positive roots
self._deltaTimes2 = self.proots.sum(axis=0)
self.adjoint = self._getAdjoint()
self.fond = self._getFond()
self.dimAdj = self._getDimAdj()
self.longestWeylWord = self._longestWeylWord()
# store the matrices for speeding up multiple calls
self._repMinimalMatrices = {}
self._repMatrices = {}
self._dominantWeightsStore = {}
self._invariantsStore = {}
self._dimR = {}
self.a, self.b, self.c, self.d, self.e = map(IndexedBase, ['a', 'b', 'c', 'd', 'e'])
self.f, self.g, self.h, self.i = map(IndexedBase, ['f', 'g', 'h', 'i'])
self._symblist = [self.a, self.b, self.c, self.d, self.e]
self._symbdummy = [self.f, self.g, self.h, self.i]
self.p, self.q = map(Wild, ['p', 'q'])
self.pp = Wild('pp', exclude=[IndexedBase])
# create an Sn object for all the manipulation on the Sn group
self.Sn = Sn()
# create a MathGroup object for the auxiliary functions
self.math = MathGroup()
def _matrixD(self):
"""
Returns a diagonal matrix with the values <root i, root i>
"""
positions = sum(
[[(irow, icol) for icol, col in enumerate(row) if (col in [-1, -2, -3]) and (irow < icol)] for irow, row in
enumerate(self.ncm)], [])
result = np.ones((1, self._n), dtype=object)[0]
for coord1, coord2 in positions:
result[coord2] = Rational(self.cm[coord2, coord1], self.cm[coord1, coord2]) * result[coord1]
return np.diagflat(result)
def _simpleProduct(self, v1, v2, cmID):
# Scalar product from two vector and a matrix
if type(v2) == list:
v2 = np.array(v2)
if type(v1) == list:
v1 = np.array(v1)
return Rational(1, 2) * (np.dot(np.dot(v1, cmID), v2.transpose())[0, 0])
def _longestWeylWord(self):
# returns the longest Weyl word: from the Lie manual see Susyno
weight = [-1] * self._n
result = []
while map(abs, weight) != weight:
for iel, el in enumerate(weight):
if el < 0:
break
weight = self._reflectWeight(weight, iel + 1)
result.insert(0, iel + 1)
return result
def _reflectWeight(self, weight, i):
"""
Reflects a given weight. WARNING The index i is from 1 to n
"""
result = cp.deepcopy(weight)
result[i - 1] = -weight[i - 1]
for ii in range(1, 5):
if self._smatD[i - 1, ii - 1] != 0:
result[self._smatD[i - 1, ii - 1] - 1] += weight[i - 1]
return result
def _specialMatrixD(self):
result = SparseMatrix(self._n, 4, 0)
for i in range(1, self._n + 1):
k = 1
for j in range(1, self._n + 1):
if self.cm[i - 1, j - 1] == -1:
result[i - 1, k - 1] = j
k += 1
if self.cm[i - 1, j - 1] == -2:
result[i - 1, k - 1] = j
result[i - 1, k - 1 + 1] = j
k += 2
if self.cm[i - 1, j - 1] == -3:
result[i - 1, k - 1] = j
result[i - 1, k - 1 + 1] = j
result[i - 1, k - 1 + 2] = j
k += 3
return result
def _weylOrbit(self, weight):
"""
Creates the weyl orbit i.e. the system of simple root
"""
counter = 0
result, wL = [], []
wL.append([weight])
result.append(weight)
while len(wL[counter]) != 0:
counter += 1
wL.append([])
for j in range(1, len(wL[counter - 1]) + 1):
for i in range(1, self._n + 1):
if wL[counter - 1][j - 1][i - 1] > 0:
aux = self._reflectWeight(wL[counter - 1][j - 1], i)[i + 1 - 1:self._n + 1]
if aux == map(abs, aux):
wL[counter].append(self._reflectWeight(wL[counter - 1][j - 1], i))
result = result + wL[counter] # Join the list
return result
def _findM(self, ex, el, ind):
aux1 = cp.copy(el[ind - 1])
aux2 = cp.copy(el)
aux2[ind - 1] = 0
auxMax = 0
for ii in range(1, aux1 + 2):
if ex.count(aux2) == 1:
auxMax = aux1 - ii + 1
return auxMax
aux2[ind - 1] = cp.copy(aux2[ind - 1] + 1)
return auxMax
def _positiveRoots(self):
"""
Returns the positive roots of a given group
"""
aux1 = [[KroneckerDelta(i, j) for j in range(1, self._n + 1)] for i in range(1, self._n + 1)]
count = 0
weights = cp.copy(self.cm)
while count < weights.rows:
count += 1
aux2 = cp.copy(aux1[count - 1])
for inti in range(1, self._n + 1):
aux3 = cp.copy(aux2)
aux3[inti - 1] += 1
if self._findM(aux1, aux2, inti) - weights[count - 1, inti - 1] > 0 and aux1.count(aux3) == 0:
weights = weights.col_join(weights.row(count - 1) + self.cm.row(inti - 1))
aux1.append(aux3)
return matrix2numpy(weights)
def _dominantConjugate(self, weight):
weight = weight[0]
if self.cm == np.array([[2]]): # SU2 code
if weight[0] < 0:
return [-weight, 1]
else:
return [weight, 0]
else:
index = 0
dWeight = weight
i = 1
while i <= self._n:
if (dWeight[i - 1] < 0):
index += 1
dWeight = self._reflectWeight(dWeight, i)
i = min([self._smatD[i - 1, 0], i + 1])
else:
i += 1
return [dWeight, index]
def _dominantWeights(self, weight):
"""
Generate the dominant weights without dimentionality information
"""
keyStore = tuple(weight)
if keyStore in self._dominantWeightsStore:
return self._dominantWeightsStore[keyStore]
# convert the weight
weight = np.array([weight], dtype=int)
listw = [weight]
counter = 1
while counter <= len(listw):
aux = [listw[counter - 1] - self.proots[i] for i in range(len(self.proots))]
aux = [el for el in aux if np.all(el == abs(el))]
listw = listw + aux
# remove duplicates this is actually a pain since numpy are not hashable
tp = []
listw = [self._nptokey(el) for el in listw]
for el in listw:
if not (el) in tp:
tp.append(el)
listw = [np.array([el], dtype=int) for el in tp]
counter += 1
# need to sort listw
def sortList(a, b):
tp1 = list(np.dot(-(a - b), self.ncminv)[0])
return cmp(tp1, [0] * a.shape[1])
# The Sorting looks to be identical to what was done in SUSYNO willl require further checking at some point
listw.sort(sortList)
# listw = [np.array([[1,1]]),np.array([[0,0]])]
functionaux = {self._nptokey(listw[0]): 1}
result = [[listw[0], 1]]
for j in range(2, len(listw) + 1):
for i in range(1, len(self.proots) + 1):
k = 1
aux1 = self._indic(functionaux,
tuple(self._dominantConjugate(k * self.proots[i - 1] + listw[j - 1])[0]))
key = self._nptokey(listw[j - 1])
while aux1 != 0:
aux2 = k * self.proots[i - 1] + listw[j - 1]
if key in functionaux:
functionaux[key] += 2 * aux1 * self._simpleProduct(aux2, [self.proots[i - 1]], self._cmID)
else:
functionaux[key] = 2 * aux1 * self._simpleProduct(aux2, [self.proots[i - 1]], self._cmID)
k += 1
# update aux1 value
kkey = tuple(self._dominantConjugate(k * self.proots[i - 1] + listw[j - 1])[0])
if kkey in functionaux:
aux1 = functionaux[kkey]
else:
aux1 = 0
functionaux[key] /= self._simpleProduct(listw[0] + listw[j - 1] + self._deltaTimes2,
listw[0] - listw[j - 1], self._cmID)
result.append([listw[j - 1], self._indic(functionaux, self._nptokey(listw[j - 1]))])
self._dominantWeightsStore[keyStore] = result
return result
def casimir(self, irrep):
"""
Returns the casimir of a given irrep
"""
irrep = np.array([irrep])
return self._simpleProduct(irrep, irrep + self._deltaTimes2, self._cmIDN)
def dimR(self, irrep):
"""
Returns the dimention of representation irrep
"""
if type(irrep) == np.ndarray and len(irrep.shape) == 1:
irrep = np.array([irrep])
if type(irrep) == np.ndarray:
keydimR = tuple([int(el) for el in irrep.tolist()[0]])
else:
keydimR = tuple(irrep)
if keydimR in self._dimR:
return self._dimR[keydimR]
if not (type(irrep) == np.ndarray):
irrep = np.array([irrep])
delta = Rational(1, 2) * self._deltaTimes2
if self.cartan._name == 'A' and self.cartan._id == 1:
delta = np.array([delta])
result = np.prod([
self._simpleProduct([self.proots[i - 1]], irrep + delta, self._cmID) / self._simpleProduct(
[self.proots[i - 1]], [delta], self._cmID)
for i in range(1, len(self.proots) + 1)], axis=0)
result = int(float(str(result))) # there is a serious bug here I have had some 45.000 converted into 44 !
self._dimR[keydimR] = result
return result
def _representationIndex(self, irrep):
delta = np.ones((1, self._n), dtype=int)
# Factor of 2 ensures is due to the fact that SimpleProduct is defined such that Max[<\[Alpha],\[Alpha]>]=1 (considering all positive roots), but we would want it to be =2
return Rational(self.dimR(irrep), self.dimR(self.adjoint)) * 2 * self._simpleProduct(irrep, irrep + 2 * delta,
self._cmID)
def _getAdjoint(self):
# returns the adjoint of the gauge group
return np.array([self.proots[-1]]) # recast the expression
def _repsUpToDimNAuxMethod(self, weight, digit, max, reap):
"""
This is a recursive auxiliary method of repsUpToDimN
"""
waux = cp.deepcopy(weight)
waux[digit] = 0
if digit == len(weight) - 1:
while self.dimR(np.array([waux])) <= max:
reap.append(cp.deepcopy([int(el) for el in waux.ravel()]))
waux[digit] += 1
else:
while self.dimR(np.array([waux])) <= max:
self._repsUpToDimNAuxMethod(waux, digit + 1, max, reap)
waux[digit] += 1
def repsUpToDimN(self, maxdim):
"""
returns the list of irreps of dim less or equal to maxdim
"""
reap = []
self._repsUpToDimNAuxMethod(np.zeros((1, self._n))[0], 0, maxdim, reap)
# sort the list according to dimension
def sortByDimension(a, b):
dma, dmb = self.dimR(a), self.dimR(b)
repa, repb = self._representationIndex(np.array([a])), self._representationIndex(np.array([b]))
conja, conjb = self._conjugacyClass(a), self._conjugacyClass(b)
return cmp(tuple(flatten([dma, repa, conja])), tuple(flatten([dmb, repb, conjb])))
reap.sort(sortByDimension)
return reap
def _getGroupWithRankNsqr(self, n):
"""
returns the list of algebra with rank equal to n^2
"""
res = []
if n > 0: res.append(("A", n))
if n > 2: res.append(("D", n))
if n > 1: res.append(("B", n))
if n > 2: res.append(("C", n))
if n == 2: res.append(("G", 2))
if n == 4: res.append(("F", 4))
if n == 6: res.append(("E", 6))
if n == 7: res.append(("E", 7))
if n == 8: res.append(("E", 8))
return res
def _cmToFamilyAndSeries(self):
aux = self._getGroupWithRankNsqr(self._n)
# create the corresponding Cartan matrix
cartans = [CartanMatrix(*el).cartan for el in aux]
# find the position of the current group in this list
ind = [iel for iel, el in enumerate(cartans) if el == self.cm][0]
return aux[ind]
def _conjugacyClass(self, irrep):
if not (type(irrep) == np.ndarray):
irrep = np.array(irrep)
series, n = self._cmToFamilyAndSeries()
if series == "A":
return [np.sum([i * irrep[i - 1] for i in range(1, n + 1)]) % (n + 1)]
if series == "B":
return [irrep[n - 1] % 2]
if series == "C":
return [np.sum([irrep[i - 1] for i in range(1, n + 1, 2)]) % 2]
if series == "D" and n % 2 == 1:
return [(irrep[-2] + irrep[-1]) % 2,
(2 * np.sum([irrep[i - 1] for i in range(1, n - 1, 2)])
+ (n - 2) * irrep[-2] + n * irrep[-1]) % 4]
if series == "D" and n % 2 == 0:
return [(irrep[-2] + irrep[-1]) % 2,
(2 * np.sum([irrep[i - 1] for i in range(1, n - 2, 2)])
+ (n - 2) * irrep[-2] + n * irrep[-1]) % 4]
if series == "E" and n == 6:
return [(irrep[0] - irrep[1] + irrep[3] - irrep[4]) % 3]
if series == "E" and n == 7:
return [(irrep[3] + irrep[5] + irrep[6]) % 2]
if series == "E" and n == 8:
return [0]
if series == "F":
return [0]
if series == "G":
return [0]
def conjugateIrrep(self, irrep, u1in=False):
"""
returns the conjugated irrep
"""
if u1in:
irrep, u1 = irrep
lbd = lambda weight, ind: self._reflectWeight(weight, ind)
res = -reduce(lbd, [np.array([irrep])[0]] + self.longestWeylWord)
if u1in:
u1 = - u1
return [res, u1]
else:
return res
def _weights(self, weights):
"""
Reorder the weights of conjugate representations
so that RepMatrices[group,ConjugateIrrep[group,w]]=-Conjugate[RepMatrices[group,w]]
and Invariants[group,{w,ConjugateIrrep[group,w]},{False,False}]=a[1]b[1]+...+a[n]b[n]
"""
if (cmp(list(weights), list(self.conjugateIrrep(weights))) in [-1, 0]) and not (np.all(
(self.conjugateIrrep(weights)) == weights)):
return [np.array([-1, 1], dtype=int) * el for el in self._weights(self.conjugateIrrep(weights))]
else:
dw = self._dominantWeights(weights)
result = sum(
[[[np.array(el, dtype=int), dw[ii][1]] for el in self._weylOrbit(self._tolist(dw[ii][0][0]))] for ii in
range(len(dw))], [])
def sortList(a, b):
tp1 = list(np.dot(-(a[0] - b[0]), self.ncminv).ravel())
return cmp(tp1, [0] * a[0].shape[0])
result.sort(sortList)
return result
def repMinimalMatrices(self, maxW):
"""
1) The output of this function is a list of sets of 3 matrices:
{{E1, F1, H1},{E2, F2, H2},...,{En, Fn, Hn}}, where n is the group's rank.
Hi are diagonal matrices, while Ei and Fi are raising and lowering operators.
These matrices obey the Chevalley-Serre relations: [Ei, Ej]=delta_ij Hi, [Hi,Ej]= AjiEj, [Hi,Fj]= -AjiFj and [Hi,Hj=0
here A is the Cartan matrix of the group/algebra.
2) With the exception of SU(2) [n=1], these 3n matrices Ei, Fi, Hi do not generate the Lie algebra,
which is bigger, as some raising and lowering operators are missing.
However, these remaining operators can be obtained through simple commutations: [Ei,Ej], [Ei,[Ej,Ek]],...,[Fi,Fj], [Fi,[Fj,Fk]].
3) This method clearly must assume a particular basis for each representation so the results are basis dependent.
4) Also, unlike RepMatrices, the matrices given by this function are not Hermitian and therefore they do not conform with the usual requirements of model building in particle physics.
However, for some applications, they might be all that is needed.
"""
# check whether it s not been calculated already
if type(maxW) == np.ndarray:
tag = self._nptokey(maxW)
else:
tag = tuple(maxW)
maxW = np.array([maxW])
if tag in self._repMinimalMatrices:
return self._repMinimalMatrices[tag]
# auxiliary function for the repMatrices method base on the Chevalley-Serre relations
cmaxW = self.conjugateIrrep(self._tolist(maxW))
if cmp(self._tolist(maxW), self._tolist(cmaxW)) in [-1, 0] and not (np.all(cmaxW == maxW)):
return [[-1 * el[1], -1 * el[0], -1 * el[2]] for el in
self.repMinimalMatrices(cmaxW)]
else:
listw = self._weights(self._tolist(maxW))
up, dim, down = {}, {}, {}
for i in range(len(listw)):
dim[self._nptokey(listw[i][0])] = listw[i][1]
up[self._nptokey(listw[0][0])] = np.zeros((1, self._n), dtype=int)
for element in range(1, len(listw)):
matrixT = [[]]
for j in range(self._n):
col = [[]]
for i in range(self._n):
key1 = self._nptokey(listw[element][0] + self.ncm[i])
key2 = self._nptokey(listw[element][0] + self.ncm[i] + self.ncm[j])
key3 = self._nptokey(listw[element][0] + self.ncm[j])
dim1 = self._indic(dim, key1)
dim2 = self._indic(dim, key2)
dim3 = self._indic(dim, key3)
ax = 1 if col == [[]] else 0
if dim1 != 0 and dim3 != 0:
if dim2 != 0:
aux1 = up[self._nptokey(listw[element][0] + self.ncm[i])][j]
aux2 = down[self._nptokey(listw[element][0] + self.ncm[i] + self.ncm[j])][i]
if i != j:
if type(col) != np.ndarray:
col = np.dot(aux1, aux2)
else:
col = np.append(col, np.dot(aux1, aux2), axis=ax)
else:
if type(col) != np.ndarray:
col = np.dot(aux1, aux2) + (
listw[element][0][i] + self.ncm[i, i]) * np.eye(
dim1, dtype=object)
else:
col = np.append(col, np.dot(aux1, aux2) + (
listw[element][0][i] + self.ncm[i, i]) * np.eye(
dim1, dtype=object), axis=ax)
else:
if i != j:
if type(col) != np.ndarray:
col = np.zeros((dim1, dim3), dtype=object)
else:
col = np.append(col, np.zeros((dim1, dim3)), axis=ax)
else:
tmp = (listw[element][0][i] + self.ncm[i, i]) * np.eye(dim1, dtype=object)
if type(tmp) != np.ndarray:
tmp = np.array([[tmp]])
if type(col) != np.ndarray:
col = tmp
else:
col = np.append(col, tmp, axis=ax)
if type(col) != list:
if type(matrixT) != np.ndarray:
matrixT = col.transpose()
else:
matrixT = np.append(matrixT, col.transpose(), axis=0)
if matrixT == [[]]:
matrix = np.zeros((1, 1), dtype=object)
else:
matrix = matrixT.transpose()
aux1 = sum([self._indic(dim, self._nptokey(listw[element][0] + self.ncm[i])) for i in range(self._n)])
aux2 = self._indic(dim, self._nptokey(listw[element][0]))
cho = self.math._decompositionTypeCholesky(matrix)
if cho.shape == (0,):
aux3 = np.array([[0]])
else:
if aux1 - cho.shape[0] == 0 and aux2 - cho.shape[1] == 0:
aux3 = cp.copy(cho)
else:
aux3 = np.pad(cho,
pad_width=((0, max(aux1 - cho.shape[0], 0)), (0, max(aux2 - cho.shape[1], 0))),
mode='constant')
aux4 = aux3.transpose()
if np.all((np.dot(aux3, aux4)) != matrix):
print("Error in repminimal matrices:", aux3, " ", aux4, " ", matrix)
# Obtain the blocks in (w+\[Alpha]i)i and wj. Use it to feed the recursive algorith so that we can calculate the next w's
aux1 = np.array(
[[0, 0]]) # format (+-): (valid cm raise index i - 1, start position of weight w+cm[[i-1]]-1)
for i in range(self._n):
key = self._nptokey(listw[element][0] + self.ncm[i])
if key in dim:
aux1 = np.append(aux1, np.array([[i + 1, aux1[-1, 1] + dim[key]]], dtype=object), axis=0)
for i in range(len(aux1) - 1):
index = aux1[i + 1, 0]
posbegin = aux1[i, 1] + 1
posend = aux1[i + 1, 1]
key = self._nptokey(listw[element][0] + self.ncm[index - 1])
aux2 = down[key] if key in down else [[]] * self._n
aux2[index - 1] = aux3[posbegin - 1:posend]
down[key] = aux2
key2 = self._nptokey(listw[element][0])
aux2 = up[key2] if key2 in up else [[]] * self._n
aux2[index - 1] = (aux4.transpose()[posbegin - 1:posend]).transpose()
up[key2] = aux2
# Put the collected pieces together and build the 3n matrices: hi,ei,fi
begin, end = {self._nptokey(listw[0][0]): 1}, {self._nptokey(listw[0][0]): listw[0][1]}
for element in range(1, len(listw)):
key = self._nptokey(listw[element][0])
key1 = self._nptokey(listw[element - 1][0])
begin[key] = begin[key1] + listw[element - 1][1]
end[key] = end[key1] + listw[element][1]
aux2 = sum([listw[i][1] for i in range(len(listw))])
aux3 = np.zeros((aux2, aux2), dtype=object)
matrixE, matrixF, matrixH = [], [], []
for i in range(self._n):
aux6, aux7, aux8 = np.zeros((aux2, aux2), dtype=object), np.zeros((aux2, aux2), dtype=object), np.zeros(
(aux2, aux2), dtype=object) # e[i], f[i], h[i]
for element in range(len(listw)):
key = self._nptokey(listw[element][0] + self.ncm[i])
key2 = self._nptokey(listw[element][0])
key3 = self._nptokey(listw[element][0] - self.ncm[i])
if key in dim:
b1, e1 = begin[key], end[key]
b2, e2 = begin[key2], end[key2]
aux6[b1 - 1:e1, b2 - 1:e2] = (up[key2][i]).transpose()
if key3 in dim:
b1, e1 = begin[key3], end[key3]
b2, e2 = begin[key2], end[key2]
aux7[b1 - 1:e1, b2 - 1:e2] = (down[key2][i]).transpose()
b1, e1 = begin[key2], end[key2]
aux8[b1 - 1:e1, b1 - 1:e1] = listw[element][0][i] * np.eye(listw[element][1], dtype=object)
matrixE.append(SparseMatrix(aux6)) # sparse matrix transfo
matrixF.append(SparseMatrix(aux7)) # sparse matrix transfo
matrixH.append(SparseMatrix(aux8)) # sparse matrix transfo
aux1 = [[matrixE[i], matrixF[i], matrixH[i]] for i in range(self._n)]
self._repMinimalMatrices[tag] = aux1
return aux1
def invariants(self, reps, conj=[], skipSymmetrize=False, returnTensor=False, pyrate_normalization=False):
"""
Calculates the linear combinations of the components of rep1 x rep2 x ... which are invariant under the action of the group.
These are also known as the Clebsch-Gordon coefficients.
The invariants/Clebsch-Gordon coefficients returned by this function follow the following general normalization convention.
Writing each invariant as Sum_i,j,...c^ij... rep1[i] x rep2[j] x ..., then the normalization convention is Sum_i,j,...|c_ij...|^2=Sqrt[dim(rep1)dim(rep2)...]. Here, i,j, ... are the components of each representation.
conj represents wether or not the irrep should be conjugated.
"""
storedkey = tuple([(tuple(el), el1) for el, el1 in zip(reps, conj)])
key = tuple([tuple(el) for el in reps])
if storedkey in self._invariantsStore:
return self._invariantsStore[storedkey]
if conj != []:
assert len(conj) == len(reps), "Length `conj` should match length `reps`!"
assert np.all([type(el) == bool for el in conj]), "`conj` should only contains boolean!"
else:
conj = [False] * len(reps)
# Let's re-order the irreps
skey = sorted(key)
alreadyTaken = []
order = []
for el in skey:
pos = [iel for iel, elem in enumerate(key) if el == elem]
for ell in pos:
if not (ell in alreadyTaken):
alreadyTaken.append(ell)
order.append(ell)
break
alreadyTaken = []
inverseOrder = []
for el in key:
pos = [iel for iel, elem in enumerate(skey) if el == elem]
for ell in pos:
if not (ell in alreadyTaken):
alreadyTaken.append(ell)
inverseOrder.append(ell)
break
# let's reorder the conj accordingly
conj = [conj[el] for el in order]
# replacement rules
subs = [(self._symbdummy[i], self._symblist[j]) for i, j in zip(range(len(self._symblist)), order)]
if len(reps) == 2:
cjs = not (conj[0] == conj[1])
invs, maxinds = self._invariants2Irrep(skey, cjs)
elif len(reps) == 3:
if (conj[0] and conj[1] and conj[2]) or (not (conj[0]) and not (conj[1]) and not (conj[2])):
invs, maxinds = self._invariants3Irrep(skey, False)
if (conj[0] and conj[1] and not (conj[2])) or (not (conj[0]) and not (conj[1]) and conj[2]):
invs, maxinds = self._invariants3Irrep(skey, True)
if (conj[0] and not (conj[1]) and conj[2]) or (not (conj[0]) and conj[1] and not (conj[2])):
invs, maxinds = self._invariants3Irrep([skey[0], skey[2], skey[1]], True)
# do the substitutions c->b b->c
invs = [self._safePermutations(el, ((self.c, self.b), (self.b, self.c))) for el in invs]
tp = cp.deepcopy(maxinds[1])
maxinds[1] = cp.deepcopy(maxinds[2])
maxinds[2] = tp
if (not (conj[0]) and conj[1] and conj[2]) or (conj[0] and not (conj[1]) and not (conj[2])):
invs, maxinds = self._invariants3Irrep([skey[2], skey[1], skey[0]], True)
invs = [self._safePermutations(el, ((self.c, self.a), (self.a, self.c))) for el in invs]
tp = cp.deepcopy(maxinds[0])
maxinds[0] = cp.deepcopy(maxinds[-1])
maxinds[-1] = tp
elif len(reps) == 4:
invs, maxinds = self._invariants4Irrep([], skey, conj)
else:
exit("Error, only 2, 3 or 4 irrep should be passed.")
repDims = sqrt(reduce(operator.mul, [self.dimR(el) for el in
[reps[i] if not (conj[i]) else self.conjugateIrrep(reps[i]) for i in
range(len(reps))]], 1))
if invs == []:
return []
else:
if not (skipSymmetrize):
tensorExp = self._construct_tensor(invs)
# tensorExp = self._normalizeInvariantsTensor(tensorExp, repDims)
# create a matrix form of the tensor for the following
tensorMatForm = self._getTensorMatrixForm(tensorExp, maxinds)
tensorMatForm = self._normalizeInvariantsTensorMat(tensorMatForm, repDims)
tensorMatForm = self._symmetrizeInvariants(skey, tensorExp, tensorMatForm, maxinds, conj)
if tensorMatForm != []:
tensorExp = [dict([(tuple([ell + 1 for ell in el]), tensorMatForm[tuple(flatten([iell, el]))])
for el in zip(*tensorMatForm[iell, :].nonzero())])
for iell in range(tensorMatForm.shape[0])]
invs = self._reconstructFromTensor(tensorExp, maxinds)
else:
invs = []
# restore the ordering of the representations which was changed above
else:
invs = self._normalizeInvariants(reps, invs, repDims)
subsdummy = [(self._symblist[i], self._symbdummy[i]) for i in range(len(subs))]
invs = [el.subs(tuple(subsdummy)) for el in invs]
invs = [el.subs(tuple(subs)) for el in invs]
self._invariantsStore[key] = invs
if pyrate_normalization and not returnTensor:
returnTensor = True
if returnTensor:
tensorExp = self._construct_tensor(invs)
if pyrate_normalization:
tensorExp = self._pyrate_normalization(tensorExp)
return tensorExp
else:
return invs
def _pyrate_normalization(self, tensor):
# It turns out that the sqrt factors are not simplified away and need to be done by end.
# For that we look at the first element in the invariant and divide by its value if it is a sqrt
for iv, inv in enumerate(tensor):
if type(inv.values()[0]) == Mul:
temp = inv.values()[0].match(sqrt(self.p) * self.q)
if not (temp is None):
tensor[iv] = [tuple(list(key) + [val / (sqrt(temp[self.p]) * temp[self.q])]) for key, val in
inv.items()]
else: # If if is none it means it is a complicated ratio but without sqrt or the sqrt is on a different entry. In any case normalize
tensor[iv] = [tuple(list(key) + [val / inv.values()[0]]) for key, val in
inv.items()]
else:
tensor[iv] = [tuple(list(key) + [val]) for key, val
in inv.items()]
return tensor
def _construct_tensor(self, invs):
# construct tensor form from the invariant form a[1]b[i]+...
tensorExp = [el.as_coefficients_dict() for el in invs]
for iel, el in enumerate(tensorExp):
tpdic = {}
for key, val in el.items():
collect, fac = [], []
for ell in key.args:
if not (type(ell) == Indexed):
fac.append(ell)
else:
collect.append(ell.args[1])
tpdic[tuple(collect)] = val * reduce(operator.mul, fac, 1)
tensorExp[iel] = tpdic
return tensorExp
def _getTensorMatrixForm(self, tensor, maxinds):
tensorMat = np.zeros([len(tensor)] + maxinds, dtype=object)
for iel, el in enumerate(tensor):
for key, val in el.items():
if len(key) == 2:
tensorMat[iel, key[0] - 1, key[1] - 1] = val
elif len(key) == 3:
tensorMat[iel, key[0] - 1, key[1] - 1, key[2] - 1] = val
elif len(key) == 4:
tensorMat[iel, key[0] - 1, key[1] - 1, key[2] - 1, key[3] - 1] = val
else:
exit("error in `getTensorMatrixForm")
return tensorMat
def _reconstructFromTensor(self, tensor, inds):
invs = []
for el in tensor:
exp = 0
for key, val in el.items():
if len(key) == 2:
exp += self._symblist[0][key[0]] * self._symblist[1][key[1]] * val
elif len(key) == 3:
exp += self._symblist[0][key[0]] * self._symblist[1][key[1]] * self._symblist[2][key[2]] * val
elif len(key) == 4:
exp += self._symblist[0][key[0]] * self._symblist[1][key[1]] * self._symblist[2][key[2]] * \
self._symblist[3][key[3]] * val
invs.append(exp)
return invs
def _invariants2Irrep(self, reps, cjs):
"""
return the invariants of the the irreps
"""
w1, w2 = self._weights(reps[0]), self._weights(reps[1])
reps = [np.array([el]) for el in reps if type(el) != np.array]
# Warning, because the results are stored they need to be copied otherwise modifying one modifies the other one
r1, r2 = cp.deepcopy(self.repMinimalMatrices(reps[0])), cp.deepcopy(self.repMinimalMatrices(reps[1]))
if cjs:
for i in range(len(w2)):
w2[i][0] = - w2[i][0]
for i in range(self._n):
for j in range(3):
r2[i][j] = - r2[i][j].transpose()
array1, array2 = {}, {}
for i in range(len(w1)):
array1[self._nptokey(w1[i][0])] = w1[i][1]
for i in range(len(w2)):
array2[self._nptokey(w2[i][0])] = w2[i][1]
aux1 = []
for i in range(len(w1)):
if self._indic(array2, self._nptokey(-w1[i][0])) != 0:
aux1.append([w1[i][0], -w1[i][0]])
dim1 = [0]
for i in range(1, len(aux1) + 1): # WARNING dim1 is aligned with mathematica
dim1.append(dim1[i - 1] + self._indic(array1, self._nptokey(aux1[i - 1][0])) * self._indic(array2,
self._nptokey(
aux1[i - 1][
1])))
b1, e1 = {}, {}
for i in range(len(aux1)):
key = tuple([self._nptokey(el) for el in aux1[i]])
b1[key] = dim1[i] + 1
e1[key] = dim1[i + 1]
bigMatrix = []
for i in range(self._n):
aux2 = []
keysaux2 = []
for j in range(len(aux1)):
if self._indic(array1, self._nptokey(aux1[j][0] + self.ncm[i])) != 0:
val = [aux1[j][0] + self.ncm[i], aux1[j][1]]
key = tuple([self._nptokey(el) for el in val])
if not (key in keysaux2):
aux2.append(val)
keysaux2.append(key)
if self._indic(array2, self._nptokey(aux1[j][1] + self.ncm[i])) != 0:
val = [aux1[j][0], aux1[j][1] + self.ncm[i]]
key = tuple([self._nptokey(el) for el in val])
if not (key in keysaux2):
aux2.append(val)
keysaux2.append(key)
if len(w1) == 1 and len(w2) == 1: # Special care is needed if both reps are singlets
aux2 = aux1
dim2 = [0]
for k in range(1, len(aux2) + 1):
dim2.append(dim2[k - 1] + self._indic(array1, self._nptokey(aux2[k - 1][0])) * self._indic(array2,
self._nptokey(
aux2[
k - 1][
1])))
b2, e2 = {}, {}
for k in range(len(aux2)):
key = tuple([self._nptokey(el) for el in aux2[k]])
b2[key] = dim2[k] + 1
e2[key] = dim2[k + 1]
if dim2[len(aux2)] != 0 and dim1[len(aux1)] != 0:
matrixE = SparseMatrix(zeros(dim2[len(aux2)], dim1[len(aux1)]))
else:
matrixE = []
for j in range(len(aux1)):
if self._indic(array1, self._nptokey(aux1[j][0] + self.ncm[i])) != 0:
aux3 = aux1[j]
aux4 = [aux1[j][0] + self.ncm[i], aux1[j][1]]
kaux4 = tuple([self._nptokey(el) for el in aux4])
kaux3 = tuple([self._nptokey(el) for el in aux3])
matrixE[self._indic(b2, kaux4) - 1:self._indic(e2, kaux4),
self._indic(b1, kaux3) - 1:self._indic(e1, kaux3)] = np.kron(
self._blockW(aux1[j][0] + self.ncm[i], aux1[j][0], w1, r1[i][0]),
np.eye(self._indic(array2, self._nptokey(aux1[j][1])), dtype=object))
if self._indic(array2, self._nptokey(aux1[j][1] + self.ncm[i])) != 0:
aux3 = aux1[j]
aux4 = [aux1[j][0], aux1[j][1] + self.ncm[i]]
kaux4 = tuple([self._nptokey(el) for el in aux4])
kaux3 = tuple([self._nptokey(el) for el in aux3])
matrixE[self._indic(b2, kaux4) - 1:self._indic(e2, kaux4),
self._indic(b1, kaux3) - 1:self._indic(e1, kaux3)] = np.kron(
np.eye(self._indic(array1, self._nptokey(aux1[j][0])), dtype=object),
self._blockW(aux1[j][1] + self.ncm[i], aux1[j][1], w2, r2[i][0]))
if bigMatrix == [] and matrixE != []:
bigMatrix = SparseMatrix(matrixE)
elif bigMatrix != [] and matrixE != []:
bigMatrix = bigMatrix.col_join(matrixE)
dim1 = [0]
dim2 = [0]
for i in range(1, len(w1) + 1):
dim1.append(dim1[i - 1] + w1[i - 1][1])
for i in range(1, len(w2) + 1):
dim2.append(dim2[i - 1] + w2[i - 1][1])
for i in range(len(w1)):
b1[self._nptokey(w1[i][0])] = dim1[i]
for i in range(len(w2)):
b2[self._nptokey(w2[i][0])] = dim2[i]
result = []
aind, bind = [], []
if len(bigMatrix) != 0:
dt = 100 if len(bigMatrix) < 10000 else 500
aux4 = self._findNullSpace(bigMatrix, dt)
if aux4 == []:
#Sometimes sympy is fishy... Let's confirm with the internal null space function
aux4 = SparseMatrix(bigMatrix).nullspace()
# let's construct the invariant combination from the null space solution
# declare the symbols for the output of the invariants
expr = []
for i0 in range(len(aux4)):
expr.append(0)
cont = 0
for i in range(len(aux1)):
for j1 in range(self._indic(array1, self._nptokey(aux1[i][0]))):
for j2 in range(self._indic(array2, self._nptokey(aux1[i][1]))):
cont += 1
aind.append(1 + b1[self._nptokey(aux1[i][0])] + j1)
bind.append(1 + b2[self._nptokey(aux1[i][1])] + j2)
expr[i0] += aux4[0][cont - 1] * self.a[1 + b1[self._nptokey(aux1[i][0])] + j1] * self.b[
1 + b2[self._nptokey(aux1[i][1])] + j2]
result = [expr[ii] for ii in range(len(aux4))]
# Special treatment - This code ensures that well known cases come out in the expected form
if self.cartan._name == "A" and self.cartan._id == 1 and reps[0] == reps[1] and reps[0] == [1] and not (cjs):
# Todo check that this is needed here as well
result = [-el for el in result]
if aind != [] and bind != []:
return result, [max(aind), max(bind)]
else:
return result, [0, 0]
def _invariants3Irrep(self, reps, cjs):
"""
Returns the invariant for three irreps
"""
w1, w2, w3 = self._weights(reps[0]), self._weights(reps[1]), self._weights(reps[2])
reps = [np.array([el]) for el in reps if type(el) != np.array]
# Warning, because the results are stored they need to be copied otherwise modifying one modifies the other one
r1, r2, r3 = cp.deepcopy(self.repMinimalMatrices(reps[0])), cp.deepcopy(
self.repMinimalMatrices(reps[1])), cp.deepcopy(self.repMinimalMatrices(reps[2]))
if cjs:
for i in range(len(w3)):
w3[i][0] = - w3[i][0]
for i in range(self._n):
for j in range(3):
r3[i][j] = - r3[i][j].transpose()
array1, array2, array3 = {}, {}, {}
for i in range(len(w1)):
array1[self._nptokey(w1[i][0])] = w1[i][1]
for i in range(len(w2)):
array2[self._nptokey(w2[i][0])] = w2[i][1]
for i in range(len(w3)):
array3[self._nptokey(w3[i][0])] = w3[i][1]
aux1 = []
for i in range(len(w1)):
for j in range(len(w2)):
if self._indic(array3, self._nptokey(-w1[i][0] - w2[j][0])) != 0:
aux1.append([w1[i][0], w2[j][0], -w1[i][0] - w2[j][0]])
dim1 = [0]
for i in range(1, len(aux1) + 1): # WARNING dim1 is aligned with mathematica
dim1.append(dim1[i - 1] + self._indic(array1, self._nptokey(aux1[i - 1][0])) * (
self._indic(array2, self._nptokey(aux1[i - 1][1])) * self._indic(array3, self._nptokey(aux1[i - 1][2]))
))
b1, e1 = {}, {}
b3 = {}
for i in range(len(aux1)):
key = tuple([self._nptokey(el) for el in aux1[i]])
b1[key] = dim1[i] + 1
e1[key] = dim1[i + 1]
bigMatrix = []
for i in range(self._n):
aux2 = []