/
finitely_presented_algebra.py
582 lines (495 loc) · 22.6 KB
/
finitely_presented_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
# -*- coding: utf-8 -*-
"""
Finitely presented algebras
AUTHORs:
- Kyle Rhoads (2019-07)
An implementation of finitely presented algebras into SageMath. Creates two classes,
`FinitelyPresentedAlgebra` and `FinitelyPresentedAlgebraElement`, and provides functions that
implements algorithms for finite dimensional representations of this object.
"""
#========================================================================#
# #
# Copyright (C) 2019 Kyle Rhoads <rhoadskj@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# http://www.gnu.org/licenses/ #
# #
#========================================================================#
from __future__ import absolute_import
from sage import *
from sage.algebras.algebra import Algebra
from sage.algebras.free_algebra import FreeAlgebra
from sage.rings.quotient_ring import QuotientRing_nc
from sage.structure.element import AlgebraElement
from sage.rings.quotient_ring_element import QuotientRingElement
from sage.algebras.free_algebra_element import FreeAlgebraElement
from sage.categories.fields import Fields
from sage.categories.number_fields import NumberFields
from sage.categories.finite_fields import FiniteFields
from sage.categories.algebras_with_basis import AlgebrasWithBasis
from sage.rings.all import ZZ
from sage.combinat.words.word import Word
from sage.matrix.matrix_space import MatrixSpace
class FinitelyPresentedAlgebraElement(QuotientRingElement, AlgebraElement):
"""
A class for elements of finitely presented algebras.
"""
def __init__(self, A, f, reduce=True):
"""
An element of a finitely presented algebra `A`.
"""
if not isinstance(f, FreeAlgebraElement):
R = A.free_algebra()
f = R(f)
self.__rep = f
QuotientRingElement.__init__(self, A, f, reduce)
def _repr_(self):
"""
Returns a text representation of `self`.
"""
return self.__rep._repr_()
def _latex_(self):
"""
Returns a LaTeX representation of `self`.
"""
return self.__rep._latex_()
def _reduce_(self):
"""
Reduces `self` based on the relations of its parent, `A`. Only matters for relations of
two or fewer terms.
"""
repeat = True
words = _to_words(self.__rep)
while repeat:
old_words = words
for w in words:
for rel in self.parent()._reduce:
if rel[0].is_factor(w[0]):
w[0] = _replace(self.parent().free_algebra(), w[0], rel[0], rel[1])
w[1] = w[1]*rel[2]
if old_words == words: repeat = False
self.__rep = _to_element(self.parent().free_algebra(), words)
def lift(self):
"""
Returns the value of `self` lifted to the base free algebra of its parent. The returned
value will be a `FreeAlgebraElement`.
"""
return self.__rep
def is_constant(self):
"""
Returns `True` if `self` is constant, and `False` otherwise. That is, whether `self` is
contained in the base field of its parent.
"""
return self.__rep.variables() == []
class FinitelyPresentedAlgebra(QuotientRing_nc, Algebra):
"""
A class for finitely presented algebras.
"""
Element = FinitelyPresentedAlgebraElement
def __init__(self, field, relations, names):
"""
The finitely presented algebra equivalent to the free algebra over `field` generated by
`names` modulo the ideal generated by `relations`.
"""
if field not in Fields: raise TypeError('Base ring must be a field.')
if type(relations) == str: relations = tuple(relations.split(','))
elif type(relations) == list: relations = tuple(relations)
elif not isinstance(relations, tuple):
raise TypeError('Relations must be given as a list, tuple, or string.')
if type(names) == str: names = tuple(names.split(','))
elif type(names) == list: names = tuple(names)
elif not isinstance(names, tuple):
raise TypeError('Generators must be given as a list, tuple, or string.')
self._ngens = len(names)
self._nrels = len(relations)
self._free_alg = FreeAlgebra(field, self._ngens, names)
self._ideal = self._free_alg.ideal(relations)
self._reduce = []
for f in self._ideal.gens():
mons = f.monomials()
if len(mons) == 1:
self._reduce.append([_to_word(f), Word(''), field.zero()])
if len(mons) == 2:
coeffs = f.coefficients()
if mons[0] < mons[1]:
self._reduce.append([_to_word(mons[1]), _to_word(mons[0]),
-coeffs[0]*coeffs[1]**(-1)])
elif mons[0] > mons[1]:
self._reduce.append([_to_word(mons[0]), _to_word(mons[1]),
-coeffs[1]*coeffs[0]**(-1)])
QuotientRing_nc.__init__(self, self._free_alg, self._ideal, names,
category=AlgebrasWithBasis(field))
def _repr_(self):
"""
Returns a text representation of `self`.
"""
return 'Finitely presented algebra over {} with presentation <{} | {}>'.format(
self.base_field(),
', '.join([str(self.gen(i)) for i in range(self.ngens())]),
', '.join([str(self.rel(i)) for i in range(self.nrels())]))
def _latex_(self):
"""
Returns a LaTeX representation of `self`.
"""
return '{} \\langle {} \\mid {} \\rangle'.format(
self.base_field()._latex_(),
', '.join(self.free_algebra().latex_variable_names()),
', '.join([self.rel(i)._latex_() for i in range(self.nrels())]))
def _element_constructor_(self, f, coerce=True):
"""
Converts `f` into an element of `self`.
"""
if isinstance(f, FinitelyPresentedAlgebraElement):
if f.parent() is self:
return f
f = f.lift()
if coerce:
A = self.free_algebra()
f = A(f)
return self.element_class(self, f)
def ngens(self):
"""
Returns the number of generations of `self`.
"""
return self._ngens
def nrels(self):
"""
Returns the number of relations of `self`.
"""
return self._nrels
def base_ring(self):
"""
Returns the number of relations of `self`.
"""
return self.free_algebra().base_ring()
def base_field(self):
"""
Same functionality as `base_ring()`.
"""
return self.free_algebra().base_ring()
def free_algebra(self):
"""
Returns the base free algebra of `self`, which is a `FreeAlgebra` object over its base
field with generators matching the generators of `self`.
"""
return self._free_alg
def gen(self, i):
"""
Returns the i-th generator of `self`, as a `FreeAlgebraElement`.
"""
return self.free_algebra().gen(i)
def gens(self):
"""
Returns the generators of `self`, as a tuple.
"""
return self.free_algebra().gens()
def rel(self, i):
"""
Returns the i-th relation of `self`, as a `FreeAlgebraElement`.
"""
return self.defining_ideal().gen(i)
def rels(self):
"""
Returns the relations of `self`, as a tuple.
"""
return self.defining_ideal().gens()
def one(self):
"""
Returns the multiplicative identity of `self`, which is equal to the multiplicative
identity of its base field.
"""
return self.element_class(self, self.free_algebra().one())
def zero(self):
"""
Returns the additive identity of `self`, which is equal to the additive identity of its
base field.
"""
return self.element_class(self, self.free_algebra().zero())
def monoid(self):
"""
Returns the free monoid on the generators of `self`.
"""
return self.free_algebra().monoid()
def has_rep(self, n, restrict=None, force=False):
"""
Returns `True` if there exists an `n`-dimensional representation of `self`, and `False`
otherwise.
The optional argument `restrict` may be used to restrict the possible images of the
generators. To do so, `restrict` must be a tuple with entries of `None`, `'diagonal'`,
`'lower'`, or `'upper'`. Its length must match the number of generators of `self`.
Use `force=True` if the function does not recognize the base field as computable, but the
field is computable.
"""
if (not force and self.base_field() not in NumberFields
and self.base_field() not in FiniteFields):
raise TypeError('Base field must be computable. If %s is computable'%self.base_field()
+ ' then use force=True to bypass this.')
if n not in ZZ or n < 1:
raise ValueError('Dimension must be a positive integer.')
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
import math
B = PolynomialRing(self.base_field(), (self.ngens()*n**2 + 1), 'x', order='deglex')
M = MatrixSpace(B, n, sparse=True)
gen_matrix = list()
if not isinstance(restrict, (tuple, list)):
restrict = [None for i in range(self.ngens())]
if len(restrict) != self.ngens():
raise ValueError('Length of restrict does not match number of generators.')
for i in range(self.ngens()):
ith_gen_matrix = []
for j in range(n):
for k in range(n):
if restrict[i] == 'upper' and j > k:
ith_gen_matrix.append(B.zero())
elif restrict[i] == 'lower' and j < k:
ith_gen_matrix.append(B.zero())
elif restrict[i] == 'diagonal' and j != k:
ith_gen_matrix.append(B.zero())
else: ith_gen_matrix.append(B.gen(j + (j + 1)*k + i*n**2))
gen_matrix.append(M(ith_gen_matrix))
relB_list = list()
for i in range(self.nrels()):
relB_list += self._to_matrix(self.rel(i), M, gen_matrix).list()
relB = B.ideal(relB_list)
if relB.dimension() == -1: return False
else: return True
def has_irred_rep(self, n, gen_set=None, restrict=None, force=False):
"""
Returns `True` if there exists an `n`-dimensional irreducible representation of `self`,
and `False` otherwise. Of course, this function runs `has_rep(n, restrict)` to verify
there is a representation in the first place, and returns `False` if not.
The argument `restrict` may be used equivalenty to its use in `has_rep()`.
The argument `gen_set` may be set to `'PBW'` or `'pbw'`, if `self` has an algebra basis
similar to that of a Poincaré-Birkhoff-Witt basis.
Alternatively, an explicit generating set for the algorithm implemented by this function
can be given, as a tuple or array of `FreeAlgebraElements`. This is only useful if the
package cannot reduce the elements of `self`, but they can be reduced in theory.
Use `force=True` if the function does not recognize the base field as computable, but the
field is computable.
"""
if (not force and self.base_field() not in NumberFields
and self.base_field() not in FiniteFields):
raise TypeError('Base field must be computable. If %s is computable'%self.base_field()
+ ' then use force=True to bypass this.')
if n not in ZZ or n < 1:
raise ValueError('Dimension must be a positive integer.')
if not self.has_rep(n, restrict): return False
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.groups.all import SymmetricGroup
import math
B = PolynomialRing(self.base_field(), (self.ngens()*n**2 + 1), 'x', order='deglex')
M = MatrixSpace(B, n, sparse=True)
gen_matrix = list()
if not isinstance(restrict, (tuple, list)):
restrict = [None for i in range(self.ngens())]
if len(restrict) != self.ngens():
raise ValueError('Length of restrict does not match number of generators.')
for i in range(self.ngens()):
ith_gen_matrix = []
for j in range(n):
for k in range(n):
if restrict[i] == 'upper' and j > k:
ith_gen_matrix.append(B.zero())
elif restrict[i] == 'lower' and j < k:
ith_gen_matrix.append(B.zero())
elif restrict[i] == 'diagonal' and j != k:
ith_gen_matrix.append(B.zero())
else: ith_gen_matrix.append(B.gen(j + (j + 1)*k + i*n**2))
gen_matrix.append(M(ith_gen_matrix))
relB = list()
for i in range(self.nrels()):
relB += self._to_matrix(self.rel(i), M, gen_matrix).list()
Z = FreeAlgebra(ZZ, 2*n - 2, 'Y')
standard_poly = Z(0)
for s in SymmetricGroup(2*n - 2).list():
standard_poly += s.sign()*reduce(
lambda x, y: x*y, [Z('Y%s'%(i-1)) for i in s.tuple()])
if n <= 6 and is_NumberField(self.base_field()): p = 2*n
else: p = int(math.floor(n*math.sqrt(2*n**2/float(n - 1) + 1/float(4)) + n/float(2) - 3))
if isinstance(gen_set, (tuple, list)):
try: gen_set = [self._to_matrix(elt, M, gen_matrix) for elt in gen_set]
except (NameError, TypeError) as error: print(error)
if gen_set == None:
word_gen_set = list(self._create_rep_gen_set(n, p))
gen_set = [self._to_matrix(_to_element(self, [[word, self.one()]]),
M, gen_matrix) for word in word_gen_set]
elif gen_set == 'pbw' or gen_set == 'PBW':
word_gen_set = list(self._create_pbw_rep_gen_set(n, p))
gen_set = [self._to_matrix(_to_element(self, [[word, self.one()]]),
M, gen_matrix) for word in word_gen_set]
else: raise TypeError('Invalid generating set.')
ordering = [i for i in range(2*n - 2)]
max_ordering = [len(gen_set) - (2*n - 2) + i for i in range(2*n - 2)]
ordering.insert(0, 0)
max_ordering.insert(0, len(gen_set))
rep_exists = False
z = B.gen(B.ngens() - 1)
while ordering[0] != max_ordering[0]:
y = gen_set[ordering[0]].trace_of_product(standard_poly.subs(
{Z('Y%s'%(j-1)):gen_set[ordering[j]] for j in range(1, 2*n - 1)}))
radB_test = relB + [B(1) - z*y]
if B.one() not in B.ideal(radB_test):
rep_exists = True
break
for i in range(2*n - 2, -1, -1):
if i != 0 and ordering[i] != max_ordering[i]:
ordering[i] += 1
break
elif i == 0:
ordering[i] += 1
if ordering[i] != max_ordering[i]:
for j in range(1, 2*n - 1): ordering[j] = j - 1
return rep_exists
def is_rep(self, image, n, force=False):
"""
Returns `True` if the map generated by mapping the generators to the matrices defined in
`image` is an `n`-dimensional representation of `self`, and `False` otherwise. The entries
of `image` must be `n`-by-`n` matrices with entries in the algebraic closure of the base
field of `self`. Its length must match the number of generators of `self.`
Use `force=True` if the function does not recognize the base field as computable, but the
field is computable.
"""
if (not force and self.base_field() not in NumberFields
and self.base_field() not in FiniteFields):
raise TypeError('Base field must be computable. If %s is'%self.base_field()
+ ' computable then use force=True to bypass this.')
if n not in ZZ or n < 1:
raise ValueError('Dimension must be a positive integer.')
M = MatrixSpace(self.base_field().algebraic_closure(), n, sparse=True)
if len(image) != self.ngens():
raise ValueError('Length of image does not match number of generators.')
if False in {mat in M for mat in image}:
raise TypeError('Improper image, must contain elements of %s.'%M._repr_())
image = [M(image[i]) for i in range(len(image))]
for rel in self.rels():
if self._to_matrix(rel, M, image) != M.zero(): return False
return True
def is_irred_rep(self, image, n, force=False):
"""
Returns `True` if the map generated by mapping the generators to the matrices defined in
`image` is an `n`-dimensional irreducible representation of `self`, and `False` otherwise.
Like above, the entries of `image` must be `n`-by-`n` matrices with entries in the
algebraic closure of the base field of `self`. Its length must match the number of
generators of `self.`
Use `force=True` if the function does not recognize the base field as computable, but the
field is computable.
"""
if (not force and self.base_field() not in NumberFields
and self.base_field() not in FiniteFields):
raise TypeError('Base field must be computable. If %s is computable'%self.base_field()
+ ' then use force=True to bypass this.')
if n not in ZZ or n < 1:
raise ValueError('Dimension must be a positive integer.')
if not self.is_rep(image, n): return False
from sage.matrix.all import Matrix
from sage.rings.number_field.number_field import is_NumberField
import math
M = MatrixSpace(self.base_field().algebraic_closure(), n, sparse=True)
image = [M(image[i]).list() for i in range(len(image))]
if n <= 6 and is_NumberField(self.base_field()): p = 2*n
else: p = int(math.floor(n*math.sqrt(2*n**2/float(n - 1) + 1/float(4)) + n/float(2) - 3))
prod_set = list(self._create_prod_set(image, n, p))
prod_set.append(M.one())
vector = [mat.list() for mat in prod_set]
return 0 not in Matrix(vector).echelon_form().diagonal()
def _create_rep_gen_set(self, n, p):
"""
A helper function. Creates the gen_set for has_irred_rep().
"""
import itertools
alphabet = [_to_word(self.gen(i)) for i in range(self.ngens())]
power_word = [alphabet[i]**n for i in range(self.ngens())]
for i in range(1, p + 1):
for words in itertools.product(alphabet, repeat=i):
yield_word = True
word = Word('')
for w in words: word = word * w
rewrite = []
empty_word = Word('')
for rel in self._reduce:
if rel[0].is_factor(word):
yield_word = False
break
if yield_word:
for pw in power_word:
if pw.is_factor(word):
yield_word = False
break
if yield_word: yield word
def _create_pbw_rep_gen_set(self, n, p):
"""
A helper function. Creates the `gen_set` for `has_irred_rep()` when `gen_set='pbw'`.
"""
import itertools
alphabet = [_to_word(self.gen(i)) for i in range(self.ngens())]
power_word = [alphabet[i]**n for i in range(self.ngens())]
commuter = []
for w in alphabet:
for v in alphabet:
if w > v: commuter.append(w*v)
for i in range(1, p + 1):
for words in itertools.product(alphabet, repeat=i):
yield_word = True
word = Word('')
for w in words: word = word * w
for c in commuter:
if c.is_factor(word): yield_word = False
for pw in power_word:
if pw.is_factor(word): yield_word = False
if yield_word: yield word
def _create_prod_set(self, image, n, p):
"""
A helper function. Creates all products of matrices up to and including length `p`.
"""
import itertools
M = MatrixSpace(self.base_field().algebraic_closure(), n, sparse=True)
for i in range(1, p + 1):
for matrices in itertools.product(image, repeat=i):
result = M.one()
for m in matrices: result = result * M(m)
yield result
def _to_matrix(self, f, M, image):
"""
A helper function. Converts a `FinitelyPresentedAlgebraElement` into a matrix.
"""
f_string = str(f).replace('^', '**')
for i in range(self.ngens()):
f_string = f_string.replace(str(self.gen(i)), '$' + str(self.gen(i)))
for j in range(self.ngens()):
f_string = f_string.replace('$' + str(self.gen(j)), 'image[%s]'%j)
return M(eval(f_string))
def _to_word(m):
"""
A helper function. Converts a monomial into a word.
"""
if len(m.monomials()) != 1: raise TypeError('')
return Word(m.leading_support().to_list())
def _to_words(f):
"""
A helper function. Converts a `FinitelyPresentedAlgebraElement` into an array of words and
coefficients.
"""
L = []
for m in f.terms():
L.append([_to_word(m), m.coefficients()[0]])
return L
def _replace(parent, word, old, new):
"""
A helper function. Replaces subwords in a word with a new subword.
"""
return _to_word(parent('*'.join(str(word).replace(str(old), str(new)))))
def _to_element(parent, words):
"""
A helper function. Inverse of _to_word() or _to_words().
"""
element = parent.zero()
for w in words:
monomial = parent(w[1])
for i in range(len(w[0])):
monomial = monomial * parent(w[0][i])
element = element + monomial
return element