-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfree_lie_algebra.py
2349 lines (2154 loc) · 88.4 KB
/
free_lie_algebra.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
import numpy as np
import scipy.linalg
import functools, sys, os, math, itertools, operator, six
from sympy.utilities.iterables import multiset_permutations, partitions, ordered_partitions, kbins
from sympy.ntheory import mobius, divisors
from sympy import Rational
import sympy
import unittest
import pyparsing
#This module provides free Lie algebra calculations in the manner of
#the first part of Reutenauer, on an alphabet of positive integers and
#using float (or sympy expressions) as the "field" K.
#Hopefully the code and definitions of most functions look similar.
#It is not written to be efficient, but to be hackable.
#Works on Python 2 or 3, but not caring about inefficiencies caused by
#things like "range" and "items" on Python 2
#The test() function at the bottom of this file illustrates the kind of calculations you can do.
#The main objects include Elt (which represents an element of tensor space)
#and EltElt (which represents Elts tensored together).
#This code is written defensively around them: functions do not modify
#such inputs, but they do not assume that their inputs are immutable.
#For example, return values do not share references to parts of their inputs.
#Words and coefficients, however, are considered immutable.
#The Elt object represents both an element of tensor space and its dual
#(through the function dotprod), which
#provides flexibility but is arguably not algebraically nice.
#If you know in advance that you only care about the answer up to a certain depth
# (number of levels) then you can save a lot of time in lots of functions. Most of
# the runtime of product operations is often in higher levels. These operations take a
# maxLevel parameter. You can use the context manager MaxLevelContext to set it everywhere.
#There's a simple string representation of an Elt
#(which you go *to* via pretty() and *from* via parse() )
#in which coefficients are surrounded by square brackets.
#For example "[1]" is the unit element and "[3]12-[3]21" is a multiple of signed area.
#If you want to use your own coefficient as K, make it something hashable,
#something with operators +, -, * and ==,
#and make sure * accepts float and int as well as itself
#and change the next six functions.
#The "distance" function won't work, but you can sort that yourself.
#By default, the coefficients are float, which is simple. If you use the UseRationalContext
#context manager, you get sympy.Rational.
def assert_coefficient(c):
#this should accept float and int as well as a custom coefficient
#note that isinstance(c,float) includes numpy floating point types as well as actual float
assert isinstance(c, (float, int, sympy.Basic)), (c, type(c))
#assert type(c) in (float, int), c
def unit_coefficient():
return 1
def zero_coefficient():
return 0
def isunit_coefficient(c):#should accept float and int as well as custom coefficient
return 1==c
def iszero_coefficient(c):#should accept float and int as well as custom coefficient
return 0==c
_defaultUseRational=False
def reciprocate_integer(i,useRational=None):
"""This function takes an int i and a suggestion whether to use rationals
instead of floats. It returns 1/i as a coefficient."""
if useRational is None:
useRational=_defaultUseRational
if useRational:
return Rational(1,i)
return 1.0/i
_defaultMaxLevel=None
def _getMaxLevel(level):
if level is None:
return _defaultMaxLevel
return level
class Word:
"""The alphabet is int. This class represents an immutable word on the alphabet"""
__slots__=["letters"]
def __init__(self, letters):
self.letters=tuple(int(i) for i in letters)
def __hash__(self):
return hash(self.letters)
def __eq__(self,other):
return self.letters==other.letters
def __repr__(self):
return "".join(str(i) for i in self.letters)
def crudeNumber(self):
"""for small d, the integer whose decimal representation is str(self)"""
return functools.reduce(lambda x, y: 10*x+y, self.letters)
emptyWord=Word([])
def concatenate(a,b):
assert isinstance(a,Word) and isinstance(b,Word), (a,b)
return Word(a.letters+b.letters)
#element of tensor space
class Elt:
"""An element of the tensor algebra on the alphabet.
data is a list (one for each level) of dictionaries word->coefficient.
The * operator is only used for multiplication by a scalar
"""
__slots__=["data"]
def __init__(self,data):
assert type(data)==list, data
self.data=data
def __hash__(self):
#(We don't rely on hashability of Elt in this file,
#but it could be useful.
#This is a basic implementation, not perfect because extra empty
#levels affect the hash but not ==.
return hash( tuple( frozenset(level_dict.items()) for level_dict in self.data) )
def __eq__(self,other):
#return self.data==other.data
assert isinstance(other,Elt), other
for a,b in six.moves.zip_longest(self.data, other.data,fillvalue=dict()):
for k,v in a.items():
if v!=b.get(k,0):
return False
for k,v in b.items():
if k not in a and not iszero_coefficient(v):
return False
return True
def __repr__(self):
return "E"+str(self.data)
def __rmul__(self, scale):
assert_coefficient(scale)
return self*scale
def __mul__(self, scale):
assert_coefficient(scale)
if iszero_coefficient(scale):
return zeroElt
out=[{k:scale*v
for k,v in x.items()}
for x in self.data]
return Elt(out)
def __add__(self, b):
assert isinstance(b,Elt), b
if len(self.data)<len(b.data):
return b+self
out=[i.copy() for i in self.data]
for level,d in enumerate(b.data):
for w,v in d.items():
_increment_value_in_dict_to_coeff(out[level],w,v)
return Elt(out)
def __sub__(self,b):
assert isinstance(b,Elt), b
return self+(-1*b)
def __neg__(self):
return -1*self
def truncatedToLevel(self, level):
return Elt([i.copy() for i in self.data[:level+1]])
def restrictedToLevel(self, level):
if len(self.data)<level+1:
return Elt([dict()])
o=[dict() for i in range(1+level)]
o[-1]=self.data[level].copy()
return Elt(o)
def coeffApply(self,f):
"""return a new object where f has been applied to all coefficients"""
out=[{k:f(v)
for k,v in x.items()}
for x in self.data]
return Elt(out)
def maxLetter(self):
"""get the maximum letter used"""
l=1
for i in self.data:
for j in i:
for k in j.letters:
if l<k:
l=k
return l
def highest_level(self, eps=1e-9):
"""return the highest level we have data in, or -1 if we are basically zero."""
for i in range(len(self.data),0,-1):
for k, v in self.data[i-1].items():
if math.fabs(v)>eps:
return i-1
return -1
def pretty(self, dp=15, tol=None, maxLevel=None):
"""a pretty string representation"""
return self._pretty(dp=dp, tol=tol, p=None, maxLevel=maxLevel)
def _pretty(self, dp, tol, p, maxLevel=None):
#This could be made __repr__ if we trust it
maxLevel=_getMaxLevel(maxLevel)
s=(self if maxLevel is None else self.truncatedToLevel(maxLevel))
if tol is None:
tol=10**(-dp)
if dp is None:
formatString = "[{}]"
else:
formatString = "[{:."+str(dp)+"g}]"
def item(i,j):
number = isinstance(j,(float, sympy.Number, int))
if number and math.fabs(j)<tol:
return ""
sign = ("+" if (not number or j>=0) else "-")
omitCoeff = len(i.letters)!=0 and (j==1 or j==-1)
#numpy floats inherit from float
formatString2Use = formatString if isinstance(j,(float,sympy.Float)) else "[{}]"
coeff = ("" if omitCoeff else formatString2Use.format(j if sign=="+" else -j))
if len(i.letters)!=0 and coeff=="[1]":
coeff=""
lets = "".join(str(j) for j in i.letters)
return sign+coeff+lets
if p is None:
o= "".join(item(i,a[i]) for a in s.data for i in sorted(a,key=lambda x:x.letters))
if len(o)>0 and o[0]=="+":
return o[1:]
return o
else:
first=True
for a in s.data:
for i in sorted(a, key=lambda x:x.letters):
it = item(i, a[i])
if first and len(it)>0 and it[0]=="+":
it=it[1:]
if not first:
p.breakable('')
if len(it)>0:
first=False
p.text(it)
def _repr_pretty_(self, p, cycle):
"""enable IPython pretty output"""
self._pretty(dp=15, tol=None, p=p)
def prettySympy(self):
o=""
for lev in self.data:
for k in sorted(lev,key=lambda x:x.letters):
vv=sympy.expand(lev[k])
if vv!=0:
o=o+("+[{}]{}".format(vv,k))
if len(o)>0 and o[0]=="+":
return o[1:]
return o
#TODO: almost anywhere this function is used in a loop
#is an optimisation opportunity
def word2Elt(word):
if type(word) in (str,tuple):
word=Word(word)
assert isinstance(word,Word),word
a=[dict() for i in range(1+len(word.letters))]
a[-1]={word:unit_coefficient()}
return Elt(a)
def letter2Elt(letter):
return Elt([dict(),{Word((letter,)):unit_coefficient()}])
unitElt = Elt([{emptyWord:unit_coefficient()}])
zeroElt = Elt([{emptyWord:zero_coefficient()}])
def removeTinies(a):
"""a version of an Elt with tiny elements removed"""
assert isinstance(a,Elt), a
d=[{k:v for k,v in i.items() if math.fabs(v)>1e-15} for i in a.data]
return Elt(d)
def wordIter(d,m, topOnly=False, asNumbers=False):
"""return all words with up to or exactly m of the d letters"""
from itertools import chain, product
alphabet=range(1,d+1) if asNumbers else "123456789"[:d]
if topOnly:
return product(alphabet, repeat=m)
it=chain.from_iterable(product(alphabet, repeat=r) for r in range(m+1))
return it
def randomElt(d,m,maxi=None):
"""a random Elt on d letters with m levels. If maxi not given, uniform[0,1] coeffs."""
letters=range(1,d+1)
ran = lambda:np.random.rand() if maxi is None else np.random.randint(maxi)
out=[{Word(key):ran() for key in itertools.product(letters,repeat=lev)}
for lev in range(0,m+1)]
return Elt(out)
class EltElt:
"""An element of the tensor product of the tensor algebra n times with itself.
data is a dictionary of (word,word,...)->coefficient"""
__slots__=["n","data"]
def __init__(self, data, n):
self.n=n
assert type(data)==dict, data
for k,v in data.items():
assert type(k)==tuple and len(k)==n
for i in k:
assert isinstance(i,Word),(data,n,i,k)
self.data=data
def __eq__(self,other):
return self.data==other.data
def __repr__(self):
return "EE"+str(self.data)
def get_deg(self):
if 0==len(self.data):
return 0
return max(sum(len(i.letters) for i in k) for k in self.data)
def __rmul__(self, scale):
assert_coefficient(scale)
return self*scale
def __mul__(self, scale):
assert_coefficient(scale)
if scale==0:
return EltElt(dict(),self.n)
out={k:scale*v
for k,v in self.data.items()}
return EltElt(out,self.n)
def __add__(self, b):
assert isinstance(b,EltElt), (b)
assert self.n == b.n
out=self.data.copy()
for k,v in b.data.items():
_increment_value_in_dict_to_coeff(out,k,v)
return EltElt(out,self.n)
def __neg__(self):
return -1*self
def __sub__(self,b):
assert isinstance(b,EltElt), b
assert self.n == b.n
return self+(-1*b)
def contract(self, a, b, simplify=True):
"""Tensor contraction. Return new EltElt where
the ath and bth element (starting from 1) have been contracted.
If simplify is True, return a coefficient or an Elt if possible"""
assert 1<=a<=self.n
assert 1<=b<=self.n
assert a!=b
if a > b:
b, a = a,b
d = {}
for k,v in self.data.items():
if k[a-1]==k[b-1]:
key=k[:a-1]+k[a:b-1]+k[b:]
_increment_value_in_dict_to_coeff(d, key, v)
o=EltElt(d,self.n-2)
if simplify and o.n==0:
return o.as_coefficient()
if simplify and o.n==1:
return o.as_Elt()
return o
def as_Elt(self):
"""If we are equivalent to just an Elt, return it"""
assert self.n == 1
o=functools.reduce(operator.add,(word2Elt(k)*v for (k,),v in self.data.items()))
return o
def as_coefficient(self):
"""If we are equivalent to just a coefficient, return it"""
assert self.n == 0
[o]=self.data.values()
return o
def truncatedToTotalLength(self,total):
out={k:v for k,v in self.data.items() if sum(len(i.letters) for i in k)<=total}
return EltElt(out,self.n)
def truncatedToLengths(self,lengths):
"""remove components where nth elt longer than lengths[n]"""
assert self.n == len(lengths)
out={k:v for k,v in self.data.items()
if all(j is None or len(i.letters)<=j for i,j in zip(k,lengths))}
return EltElt(out,self.n)
def restrictedToLengths(self,lengths):
"""remove components unless nth elt's length is lengths[n]"""
assert self.n == len(lengths)
out={k:v for k,v in self.data.items()
if all(j is None or len(i.letters)==j for i,j in zip(k,lengths))}
return EltElt(out,self.n)
def _key(self, x):
length = sum(len(aa.letters) for aa in x)
return (length,tuple(aa.letters for aa in x))
def _format(self, i):
if isinstance(self.data[i],(float, sympy.Float, int)):
return "{:+}{}".format(self.data[i],i)
return "+{}{}".format(self.data[i],i)
def pretty(self):
a=sorted(self.data, key=self._key)
#return [(self.data[i],i) for i in a]
return " ".join(self._format(i) for i in a)
def _repr_pretty_(self, p, cycle):
"""enable IPython pretty output"""
for i in sorted(self.data, key=self._key):
p.text(self._format(i))
p.breakable(' ')
def get_coefficient(a,word):
"""return the coefficient of the Word word in the Elt a"""
assert isinstance(a,Elt),a
assert isinstance(word,Word),word
level=len(word.letters)
if level<len(a.data):
return a.data[level].get(word,zero_coefficient())
return zero_coefficient()
def epsilon_numeric(a):
"""The coefficient of the empty word in the Elt a"""
assert isinstance(a,Elt),a
if len(a.data)==0 or emptyWord not in a.data[0]:
return 0
return a.data[0][emptyWord]
def epsilon(a):
"""The coefficient of the empty word in the Elt a, as an Elt"""
assert isinstance(a,Elt),a
return Elt(a.data[:1])
def _increment_value_in_dict_to_coeff(dict_,k,v):
if k in dict_:
if iszero_coefficient(dict_[k]+v):
del dict_[k]
else:
dict_[k]+=v
elif not iszero_coefficient(v):
dict_[k]=v
def dotprod(a,b):
"""The scalar product of the Elts a and b in the word basis"""
assert isinstance(a,Elt) and isinstance(b,Elt), (a,b)
out=zero_coefficient()
for x,y in zip(a.data,b.data):
for k in x:
if k in y:
out += x[k]*y[k]
return out
def make_dual(a, returnElt=True):
"""Turn the Elt a into the function mapping b to dotprod(a,b)
We use Elts both for tensor space and its dual, so this makes sense.
Returning an Elt by default makes sense because can pass to tensorProductFunctions"""
#alternative - let conc take coefficients as well as Elts.
#c.f. EltElt's contract method
assert isinstance(a,Elt), a
def loc_dual(b):
d=dotprod(a,b)
if returnElt:
return d*unitElt
return d
return loc_dual
def distance(a,b):
"""The distance between the Elts a and b in the word basis"""
assert isinstance(a,Elt) and isinstance(b,Elt), (a,b)
d=a-b
return math.sqrt(dotprod(d,d))
def concatenationProduct(a,b,maxLevel=None):
"""The concatenation product of the Elts a and b.
This is the _internal_ tensor product in tensor space.
Levels above maxLevel, if provided, are ignored."""
assert isinstance(a,Elt) and isinstance(b,Elt), (a,b)
topLevel = (len(a.data)-1)+(len(b.data)-1)
maxLevel = _getMaxLevel(maxLevel)
if maxLevel is None or maxLevel>topLevel:
maxLevel = topLevel
out=[dict() for i in range(maxLevel+1)]
for level in range(0,maxLevel+1):
for alevel in range(0,min(level+1,len(a.data))):
blevel=level-alevel
if blevel >= len(b.data) or b.data[blevel] is None or a.data[alevel] is None:
continue
for l1,l2 in a.data[alevel].items():
for r1,r2 in b.data[blevel].items():
prod=l2*r2
w = concatenate(l1,r1)
_increment_value_in_dict_to_coeff(out[level],w,prod)
return Elt(out)
def concatenationProductMany(a, maxLevel=None):
"""The concatenation product of many Elts (in the iterable a) all together"""
return functools.reduce(
lambda x,y : concatenationProduct(x,y,maxLevel),a)
def shuffleProduct(a,b,maxLevel=None):
"""The shuffle product of two Elts"""
assert isinstance(a,Elt) and isinstance(b,Elt), (a,b)
topLevel = (len(a.data)-1)+(len(b.data)-1)
maxLevel = _getMaxLevel(maxLevel)
if maxLevel is None or maxLevel>topLevel:
maxLevel = topLevel
out=[dict() for i in range(maxLevel+1)]
for level in range(0,maxLevel+1):
for alevel in range(0,min(level+1,len(a.data))):
blevel=level-alevel
if blevel >= len(b.data) or b.data[blevel] is None or a.data[alevel] is None:
continue
source=(0,)*alevel + (1,)*blevel
for l1,l2 in a.data[alevel].items():
for r1,r2 in b.data[blevel].items():
prod=l2*r2
out_=np.zeros(level,dtype="int32")
if level==0:
_increment_value_in_dict_to_coeff(out[0],emptyWord,prod)
else:
for mask in multiset_permutations(source):
mask=np.array(mask)
np.place(out_,1-mask,l1.letters)
np.place(out_,mask,r1.letters)
w = Word(out_)
_increment_value_in_dict_to_coeff(out[level],w,prod)
return Elt(out)
def shuffleProductMany(a, maxLevel=None):
"""The shuffle product of many Elts (in the iterable a) all together"""
return functools.reduce(
lambda x,y : shuffleProduct(x,y,maxLevel),a)
def rightHalfShuffleProduct(a,b,maxLevel=None):
r"""For two words a and b, their rightHalfShuffle is those shuffles
of a and b for which the last element is the last element of b.
This is extended to a bilinear operation on Elts.
If c is a letter then rightHalfShuffleProduct(a,bc) is (a shuffle b)c.
Usually (a shuffle b) == rightHalfShuffleProduct(a,b)+rightHalfShuffleProduct(b,a) (*)
In the current implementation, rightHalfShuffleProduct(a,b) is zero if b is the empty word,
even if a is the empty word.
Note that this means that (*) is violated if a and b are both the empty word.
This operation is often denoted $\mathbin{\succ}$, being a dendriform algebra operation.
It is not mentioned in the book."""
assert isinstance(a,Elt) and isinstance(b,Elt), (a,b)
topLevel = (len(a.data)-1)+(len(b.data)-1)
maxLevel = _getMaxLevel(maxLevel)
if maxLevel is None or maxLevel>topLevel:
maxLevel = topLevel
out=[dict() for i in range(maxLevel+1)]
for level in range(0,maxLevel+1):
for alevel in range(0,min(level+1,len(a.data))):
blevel=level-alevel
if blevel >= len(b.data) or b.data[blevel] is None or a.data[alevel] is None:
continue
if blevel ==0:
continue
source=(0,)*alevel + (1,)*(blevel-1)
for l1,l2 in a.data[alevel].items():
for r1,r2 in b.data[blevel].items():
prod=l2*r2
out_=np.zeros(level,dtype="int32")
if level==1:#so r1 is a single letter
_increment_value_in_dict_to_coeff(out[1],r1,prod)
else:
for mask in multiset_permutations(source):
mask=np.array(mask+[1,])
np.place(out_,1-mask,l1.letters)
np.place(out_,mask,r1.letters)
w = Word(out_)
_increment_value_in_dict_to_coeff(out[level],w,prod)
return Elt(out)
def leftHalfShuffleProduct(a,b,maxLevel=None):
r"""For two words a and b, their leftHalfShuffle is those shuffles
of a and b for which the first element is the first element of a.
This is extended to a bilinear operation on Elts.
If a is a letter then leftHalfShuffleProduct(ab,c) is a(b shuffle c).
Usually (a shuffle b) == leftHalfShuffleProduct(a,b)+leftHalfShuffleProduct(b,a) (*)
In the current implementation, leftHalfShuffleProduct(a,b) is zero if a is the empty word,
even if b is the empty word.
Note that this means that (*) is violated if a and b are both the empty word.
This operation might be denoted $\mathbin{\prec}$, being a dendriform algebra operation.
It is not mentioned in the book."""
assert isinstance(a,Elt) and isinstance(b,Elt), (a,b)
topLevel = (len(a.data)-1)+(len(b.data)-1)
maxLevel = _getMaxLevel(maxLevel)
if maxLevel is None or maxLevel>topLevel:
maxLevel = topLevel
out=[dict() for i in range(maxLevel+1)]
for level in range(0,maxLevel+1):
for blevel in range(0,min(level+1,len(b.data))):
alevel=level-blevel
if alevel >= len(a.data) or a.data[alevel] is None or b.data[blevel] is None:
continue
if alevel ==0:
continue
source=(0,)*(alevel-1) + (1,)*blevel
for l1,l2 in a.data[alevel].items():
for r1,r2 in b.data[blevel].items():
prod=l2*r2
out_=np.zeros(level,dtype="int32")
if level==1:#so l1 is a single letter
_increment_value_in_dict_to_coeff(out[1],l1,prod)
else:
for mask in multiset_permutations(source):
mask=np.array([0]+mask)
np.place(out_,1-mask,l1.letters)
np.place(out_,mask,r1.letters)
w = Word(out_)
_increment_value_in_dict_to_coeff(out[level],w,prod)
return Elt(out)
def _allValuesFromElt(a):
assert isinstance(a,Elt), a
return tuple(itertools.chain.from_iterable(j.items() for j in a.data))
def tensorProduct(*args):
"""construct an EltElt as a sequence of Elts and EltElts tensored together.
This is the tensor product of Elts (and EltElts), returning an EltElt.
It is the _external_ tensor product in tensor space"""
assert 0<len(args)
for a in args:
assert isinstance(a,(Elt,EltElt)), a
n_out = sum(1 if isinstance(a,Elt) else a.n for a in args)
out=dict()
vals=[[((i,),j) for i,j in _allValuesFromElt(a)] if isinstance(a,Elt) else a.data.items() for a in args]
for p in itertools.product(*vals):
k = functools.reduce(operator.concat,(i for i,j in p))
v = functools.reduce(operator.mul,(j for i,j in p))
_increment_value_in_dict_to_coeff(out,k,v)
return EltElt(out,n_out)
def tensorProductFunctions(*args, **kwargs):
r"""if f,g,h takes Elts and returns Elts or EltElts then
tensorProductFunctions(f,g,h) is the function f\otimes g\otimes h.
If some of f,g or h return EltElt with n>1, then provide a named argument n as the tensor exponent
we use to return in the case of zero input.
If you are using python 3 you should think of this function's signature as
"def tensorProductFunctions(*args, n=None):"
"""
assert 0<len(args)
if "n" in kwargs:
n=kwargs["n"]
else:
n=len(args)
def loc_tensorProductFunctions(a):
assert isinstance(a,EltElt),a
assert len(args)==a.n
out=None
for k,v in a.data.items():
val=tensorProduct(*[i(word2Elt(j)) for i,j in zip(args,k)])*v
if out is None:
out = val
else:
out = out + val
if out is None:
return EltElt(dict(),n)
return out
return loc_tensorProductFunctions
def concatenationProductEltElt(a,b):
assert isinstance(a,EltElt) and isinstance(b,EltElt), (a,b)
assert a.n == b.n
out=dict()
for k1,v1 in a.data.items():
for k2,v2 in b.data.items():
k=tuple(concatenate(i,j) for i,j in zip(k1,k2))
_increment_value_in_dict_to_coeff(out,k,v1*v2)
return EltElt(out,a.n)
def shuffleConcatProduct(a,b,maxLevel=None):
"""The operation on two (Elt tensor Elt)s which is shuffle on left and
concatenation on right.
This is the product for the algebra {\mathcal A} described on page 29.
The maxLevel argument is is just the maximum length of the first component.
In many cases, you know everything is a combination of (w1,w2) where
w1 and w2 are anagrams or at least have the same length, so this simple
maxLevel control is enough to control the runtime of this function."""
assert isinstance(a,EltElt)
assert isinstance(b,EltElt)
assert a.n==2
assert b.n==2
maxLevel = _getMaxLevel(maxLevel)
o={}
for (k11,k12),v1 in a.data.items():
lenk11=len(k11.letters)
for (k21,k22),v2 in b.data.items():
if maxLevel is not None and len(k21.letters)+lenk11>maxLevel:
continue
v1v2=v1*v2
k2=concatenate(k12,k22)
sh=shuffleProduct(word2Elt(k11),word2Elt(k21))
for k,v in _allValuesFromElt(sh):
_increment_value_in_dict_to_coeff(o,(k,k2),v1v2*v)
return EltElt(o,2)
def sum_word_tensor_word(d,m):
"""The sum of (w tensor w) for all words on d letters up to length m.
p30. Occurs in some identities."""
o={}
for w in wordIter(d,m):
ww=Word(w)
o[(ww,ww)]=1
return EltElt(o,2)
def sum_word_tensor_f_word(f,d,m):
"""The sum of (w tensor f(w)) for all words on d letters up to length m.
p30."""
o={}
for w in wordIter(d,m):
ww=Word(w)
fww=f(word2Elt(ww))
for lev in fww.data:
for k,v in lev.items():
_increment_value_in_dict_to_coeff(o,(ww,k),v)
return EltElt(o,2)
def swap_EltElt(a):
"""swap/transpose an EltElt representing (Elt tensor Elt)"""
assert isinstance(a,EltElt)
assert a.n == 2
o = {(k2,k1):v for (k1,k2),v in a.data.items()}
return EltElt(o,2)
def dot_EltElt(a,b):
"""The dot product of two EltElts in the word basis"""
assert isinstance(a,EltElt) and isinstance(b,EltElt), (a,b)
assert a.n == b.n
out=zero_coefficient()
for k,v1 in a.data.items():
if k in b.data:
out += v1 * b.data[k]
return out
def distance_EltElt(a,b):
"""The distance between the EltElts a and b in the word basis"""
assert isinstance(a,EltElt) and isinstance(b,EltElt), (a,b)
assert a.n==b.n
d=a-b
return math.sqrt(dot_EltElt(d,d))
def log1p(a,maxLevel=None,useRational=None):
"""returns the tensor logarithm of (1+a) where a is an Elt with nothing in level 0.
if maxLevel is not given, only go up to the maximum level already in a
- there is no other way to pick a maximum level
This follows the pattern of iisignature's logTensorHorner
log(1+x) = x(1-x(1/2-x(1/3-x(1/4-...))))
= x-x(x/2-x(x/3-x(x/4-...)))
When inside p brackets, we only need the first m-p levels to be calculated,
because when multiplying a tensor t by x (which has 0 in the zeroth level)
level k of t only affects level k+1 and above of xt.
"""
assert isinstance(a,Elt), a
assert iszero_coefficient(get_coefficient(a,emptyWord)), a
maxLevel = _getMaxLevel(maxLevel)
if maxLevel is None:
maxLevel = len(a.data)-1
assert type(maxLevel) is int, maxLevel
s=t=zeroElt
for depth in range(maxLevel,0,-1):
constant = reciprocate_integer(depth, useRational)
t=concatenationProduct(a,s,1+maxLevel-depth)
if depth>1:
s=a*constant-t
return a-t
def log(a,maxLevel=None,useRational=None):
"""tensor logarithm of a where a is an Elt with 1 in level 0"""
#TODO: Can generalise to level 0 being an arbitrary nonzero number,
#by dividing out the constant term, running this, and adding on
#math.log of the original constant
assert isinstance(a,Elt), a
assert isunit_coefficient(get_coefficient(a,emptyWord)), a
d=a.data[:]#Shallow copy, but ok, we won't return it
d[0]={emptyWord:zero_coefficient()}
return log1p(Elt(d), maxLevel,useRational)
#exp(x)=1+x(1+x/2(1+x/3(...
#=1+x+x/2(x+x/3(x+...))
#exp can be defined even if a has a nonzero constant term,
#by multiplying the answer by math.exp(the constant term)
#- this agrees, of course, with the limit
#of the power series.
def exp(a,maxLevel=None,useRational=None):
"""tensor exponential of the Elt a.
You almost always need to specify a maxLevel here"""
assert isinstance(a,Elt), a
assert iszero_coefficient(get_coefficient(a,emptyWord)), a
maxLevel = _getMaxLevel(maxLevel)
if maxLevel is None:
maxLevel = len(a.data)-1
assert type(maxLevel) is int, maxLevel
s=zeroElt
for depth in range(maxLevel,0,-1):
constant = reciprocate_integer(1+depth, useRational)
t=concatenationProduct(a*constant,s,1+maxLevel-depth)
s=a+t
d=[None] if s is zeroElt else s.data
d[0]={emptyWord:unit_coefficient()}
return Elt(d)
def log1p_shuffleConcat(a,maxLevel=None):
r"""returns the tensor logarithm of (1+a) in the algebra {\mathcal A}
if maxLevel is not given, only go up to the maximum level already in a
- there is no other way to pick a maximum level.
"""
assert isinstance(a,EltElt)
assert a.n==2
e_e=(emptyWord,emptyWord)
assert iszero_coefficient(a.data.get(e_e,0)), a
maxLevel = _getMaxLevel(maxLevel)
assert maxLevel is not None
assert type(maxLevel) is int, maxLevel
s=t=EltElt({},2)
for depth in range(maxLevel,0,-1):
constant = reciprocate_integer(depth)
t=shuffleConcatProduct(a,s,1+maxLevel-depth)
if depth>1:
s=a*constant-t
return a-t
def exp_shuffleConcat(a, maxLevel=None):
"""exponential in the algebra {\mathcal A}
(which is EltElts with n=2 with shuffleConcatProduct).
used e.g. in A Hopf-Algebraic Formula for Compositions of Noncommuting Flows
(Eric Gehrig and Matthias Kawski).
Note the meaning of the maxLevel argument, which is useful.
We only care about getting keys (k1,k2) correct if k1 and k2
have lengths maxLevel or less.
If you knew all keys in a were longer than 1 letter then
you don't need to run the calculation to as much depth as we do."""
assert isinstance(a,EltElt)
assert a.n==2
e_e=(emptyWord,emptyWord)
assert iszero_coefficient(a.data.get(e_e,0)), a
maxLevel = _getMaxLevel(maxLevel)
if maxLevel is None:
maxLevel = a.getdeg()/2 #sensible guess
s=EltElt({},2)
for depth in range(maxLevel,0,-1):
constant = reciprocate_integer(1+depth)
t=shuffleConcatProduct(a*constant,s,1+maxLevel-depth)
s=a+t
return s + EltElt({e_e:unit_coefficient()},2)
#This function was previously called 'id', which clashed with a python builtin
def id_Elt(a):
"""The identity on Elts, id"""
assert isinstance(a,Elt), a
return a
def I(a):
"""returns a with constant term removed"""
assert isinstance(a,Elt), a
out = a.data[:]
if len(out)>0:
out[0]=dict()
return Elt(out)
def alpha(a):
"""The antipode.
E.g. if X is the truncated signature of a path, then alpha(X) is the one for the reversed path."""
assert isinstance(a,Elt), a
out=[{Word(k.letters[::-1]):((-1)**level)*v
for k,v in x.items()}
for level, x in enumerate(a.data)]
return Elt(out)
def reverseAllWords(a):
"""returns a version of the Elt a with all words reversed"""
assert isinstance(a,Elt), a
out=[{Word(k.letters[::-1]):v
for k,v in x.items()}
for level, x in enumerate(a.data)]
return Elt(out)
def lieProduct(a,b, maxLevel=None):
"""The Lie product of Elts a and b"""
assert isinstance(a,Elt) and isinstance(b,Elt), (a,b)
return concatenationProduct(a,b,maxLevel)-concatenationProduct(b,a,maxLevel)
def deltaOfLetter(letter,p):
w=Word((letter,))
o=unit_coefficient()
tuples=[(emptyWord,)*i+(w,)+(emptyWord,)*(p-1-i) for i in range(p)]
return EltElt({i:o for i in tuples},p)
def delta(a,p=2):#sh*, adjoint of sh
r"""delta(x) is $\delta(x)$. delta(x,p) is $\delta_p(x)$
deshuffle coproduct: if w is a word, delta(w) is the sum of the pairs
of words (in both orders) of which w is a shuffle of the pair.
delta is thus clearly cocommutative
delta(ab)=delta(a)delta(b) so delta is an algebra morphism from
Elt to EltElt with each having concatenation"""
assert isinstance(a,Elt), a
assert isinstance(p,int), p
out=dict()
c = get_coefficient(a,emptyWord)
if not iszero_coefficient(c):
out[(emptyWord,)*p]=c
for i in range(1,len(a.data)):
for k,v in a.data[i].items():
x=[deltaOfLetter(j,p) for j in k.letters]
prod=functools.reduce(concatenationProductEltElt,x)
for k2,v2 in prod.data.items():
_increment_value_in_dict_to_coeff(out,k2,v2*v)
return EltElt(out,p)
def deltabar(a):
assert isinstance(a,Elt), a
d=delta(a)
out={(i,Word(j.letters[::-1])):v*((-1)**len(j.letters)) for (i,j),v in d.data.items()}
return EltElt(out,2)
#copied from sympy kbins but allow empty bins
def _partition(lista, bins):
# EnricoGiampieri's partition generator from
# http://stackoverflow.com/questions/13131491/
# partition-n-items-into-k-bins-in-python-lazily
if bins == 1:
yield [lista]
elif bins > 1:
for i in range(0, len(lista)+1):
for part in _partition(lista[i:], bins - 1):
if len([lista[:i]] + part) == bins:
yield [lista[:i]] + part
def deltadash(a,p=2): #aka conc*, p27, deconcatenation coproduct
r"""deltadash(x) is $\delta'(x)$. delta(x,p) is $\delta'_p(x)$"""
assert isinstance(a,Elt), a
assert isinstance(p,int), p
out=dict()
for x in a.data:
for k,v in x.items():
for i in _partition(k.letters,p):
k2=tuple(Word(j) for j in i)
_increment_value_in_dict_to_coeff(out,k2,v)
return EltElt(out,p)
def ad(a):
assert isinstance(a,Elt), a
return lambda b: lieProduct(a,b)
def r(a):
"""Right Lie-bracketing function, extended linearly to Elts.
e.g. 123 -> [1,[2,3]]
This is also known as the Dynkin map"""
assert isinstance(a,Elt), a
out = [dict() for i in a.data]
for i,x in enumerate(a.data):
if i>0:
for k,v in x.items():
rr = [letter2Elt(j) for j in reversed(k.letters)]
f = functools.reduce(lambda y,z:lieProduct(z,y),rr)
for k2,v2 in f.data[i].items():#We only need to look in level i
_increment_value_in_dict_to_coeff(out[i],k2,v2*v)
return Elt(out)
def l(a):
"""Left Lie-bracketing function, extended linearly to Elts.
e.g. 123 -> [[1,2],3]
page 36."""
assert isinstance(a,Elt), a
out = [dict() for i in a.data]
for i,x in enumerate(a.data):
if i>0:
for k,v in x.items():
rr = [letter2Elt(j) for j in k.letters]
f = functools.reduce(lieProduct,rr)
for k2,v2 in f.data[i].items():#We only need to look in level i
_increment_value_in_dict_to_coeff(out[i],k2,v2*v)
return Elt(out)
def Ad(a):
assert isinstance(a,Elt), a
def loc_Ad(b):
assert isinstance(b,Elt), b
out=zeroElt
for x in a.data:
for k,v in x.items():
y=b
for j in reversed(k.letters):
y=lieProduct(letter2Elt(j),y)
out = out + v*y
return out
return loc_Ad
#test (?) Ad(exp(x))(y)=exp(ad(x)(y)) ?for Lie elts x and y
#Ad is the derivative of conjugation?
def D(a):
assert isinstance(a,Elt), a
out=[{k:level*v
for k,v in x.items()}
for level, x in enumerate(a.data)]
out[0]=dict()
return Elt(out)
def dilate(a, factor):
"""multiply each level m by factor**m.
This is an automorphism of the grouplike elements.
In terms of signatures, corresponds to an enlargement/homothety/scaling
of the underlying path which is uniform/isotropic.
Commutes with lots of things - e.g. log."""
assert isinstance(a,Elt), a
multdict = lambda x,f: {k:f*v for k,v in x.items()}
out=[multdict(x,factor**level)
for level, x in enumerate(a.data)]
return Elt(out)
def D_inv(a):
"""The inverse of (D restricted to elements which are 0 in level 0).
possibly not in Reutenauer."""
assert isinstance(a,Elt), a
assert iszero_coefficient(get_coefficient(a,emptyWord)), a
out=[{k:v*(0 if level==0 else reciprocate_integer(level))
for k,v in x.items()}
for level, x in enumerate(a.data)]
return Elt(out)
def conc(a):
r"""This is both conc and conc_p, as we don't assert a.n==2 .
If you think of Elts as the tensor space of a vector space V,
then this is the obvious morphism from external-tensor-product