This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
free_module.py
1817 lines (1454 loc) · 65.8 KB
/
free_module.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
# -*- coding: utf-8 -*-
"""
Free modules
"""
#*****************************************************************************
# Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>,
# 2007-2009 Nicolas M. Thiery <nthiery at users.sf.net>
# 2010 Christian Stump <christian.stump@univie.ac.at>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import print_function
from six.moves import range
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.parent import Parent
from sage.structure.indexed_generators import IndexedGenerators, parse_indices_names
from sage.modules.module import Module
from sage.rings.all import Integer
from sage.structure.element import parent
from sage.modules.with_basis.indexed_element import IndexedFreeModuleElement
from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
from sage.combinat.cartesian_product import CartesianProduct_iters
from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets
from sage.misc.cachefunc import cached_method
from sage.misc.lazy_attribute import lazy_attribute
from sage.categories.all import Category, Sets, ModulesWithBasis
from sage.categories.tensor import tensor
import sage.data_structures.blas_dict as blas
from sage.typeset.ascii_art import AsciiArt
from sage.typeset.unicode_art import UnicodeArt
import six
class CombinatorialFreeModule(UniqueRepresentation, Module, IndexedGenerators):
r"""
Class for free modules with a named basis
INPUT:
- ``R`` - base ring
- ``basis_keys`` - list, tuple, family, set, etc. defining the
indexing set for the basis of this module
- ``element_class`` - the class of which elements of this module
should be instances (optional, default None, in which case the
elements are instances of
:class:`~sage.modules.with_basis.indexed_element.IndexedFreeModuleElement`)
- ``category`` - the category in which this module lies (optional,
default None, in which case use the "category of modules with
basis" over the base ring ``R``); this should be a subcategory
of :class:`ModulesWithBasis`
For the options controlling the printing of elements, see
:class:`~sage.structure.indexed_generators.IndexedGenerators`.
.. NOTE::
These print options may also be accessed and modified using the
:meth:`print_options` method, after the module has been defined.
EXAMPLES:
We construct a free module whose basis is indexed by the letters a, b, c::
sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])
sage: F
Free module generated by {'a', 'b', 'c'} over Rational Field
Its basis is a family, indexed by a, b, c::
sage: e = F.basis()
sage: e
Finite family {'a': B['a'], 'c': B['c'], 'b': B['b']}
::
sage: [x for x in e]
[B['a'], B['b'], B['c']]
sage: [k for k in e.keys()]
['a', 'b', 'c']
Let us construct some elements, and compute with them::
sage: e['a']
B['a']
sage: 2*e['a']
2*B['a']
sage: e['a'] + 3*e['b']
B['a'] + 3*B['b']
Some uses of
:meth:`sage.categories.commutative_additive_semigroups.CommutativeAdditiveSemigroups.ParentMethods.summation`
and :meth:`.sum`::
sage: F = CombinatorialFreeModule(QQ, [1,2,3,4])
sage: F.summation(F.monomial(1), F.monomial(3))
B[1] + B[3]
sage: F = CombinatorialFreeModule(QQ, [1,2,3,4])
sage: F.sum(F.monomial(i) for i in [1,2,3])
B[1] + B[2] + B[3]
Note that free modules with a given basis and parameters are unique::
sage: F1 = CombinatorialFreeModule(QQ, (1,2,3,4))
sage: F1 is F
True
The identity of the constructed free module depends on the order of the
basis and on the other parameters, like the prefix. Note that :class:`CombinatorialFreeModule` is
a :class:`~sage.structure.unique_representation.UniqueRepresentation`. Hence,
two combinatorial free modules evaluate equal if and only if they are
identical::
sage: F1 = CombinatorialFreeModule(QQ, (1,2,3,4))
sage: F1 is F
True
sage: F1 = CombinatorialFreeModule(QQ, [4,3,2,1])
sage: F1 == F
False
sage: F2 = CombinatorialFreeModule(QQ, [1,2,3,4], prefix='F')
sage: F2 == F
False
Because of this, if you create a free module with certain parameters and
then modify its prefix or other print options, this affects all modules
which were defined using the same parameters.
::
sage: F2.print_options(prefix='x')
sage: F2.prefix()
'x'
sage: F3 = CombinatorialFreeModule(QQ, [1,2,3,4], prefix='F')
sage: F3 is F2 # F3 was defined just like F2
True
sage: F3.prefix()
'x'
sage: F4 = CombinatorialFreeModule(QQ, [1,2,3,4], prefix='F', bracket=True)
sage: F4 == F2 # F4 was NOT defined just like F2
False
sage: F4.prefix()
'F'
sage: F2.print_options(prefix='F') #reset for following doctests
The constructed module is in the category of modules with basis
over the base ring::
sage: CombinatorialFreeModule(QQ, Partitions()).category()
Category of vector spaces with basis over Rational Field
If furthermore the index set is finite (i.e. in the category
``Sets().Finite()``), then the module is declared as being finite
dimensional::
sage: CombinatorialFreeModule(QQ, [1,2,3,4]).category()
Category of finite dimensional vector spaces with basis over Rational Field
sage: CombinatorialFreeModule(QQ, Partitions(3),
....: category=Algebras(QQ).WithBasis()).category()
Category of finite dimensional algebras with basis over Rational Field
See :mod:`sage.categories.examples.algebras_with_basis` and
:mod:`sage.categories.examples.hopf_algebras_with_basis` for
illustrations of the use of the ``category`` keyword, and see
:class:`sage.combinat.root_system.weight_space.WeightSpace` for an
example of the use of ``element_class``.
Customizing print and LaTeX representations of elements::
sage: F = CombinatorialFreeModule(QQ, ['a','b'], prefix='x')
sage: original_print_options = F.print_options()
sage: sorted(original_print_options.items())
[('bracket', None),
('latex_bracket', False), ('latex_prefix', None),
('latex_scalar_mult', None), ('prefix', 'x'),
('scalar_mult', '*'),
('sorting_key', <function <lambda> at ...>),
('sorting_reverse', False), ('string_quotes', True),
('tensor_symbol', None)]
sage: e = F.basis()
sage: e['a'] - 3 * e['b']
x['a'] - 3*x['b']
sage: F.print_options(prefix='x', scalar_mult=' ', bracket='{')
sage: e['a'] - 3 * e['b']
x{'a'} - 3 x{'b'}
sage: latex(e['a'] - 3 * e['b'])
x_{a} - 3 x_{b}
sage: F.print_options(latex_prefix='y')
sage: latex(e['a'] - 3 * e['b'])
y_{a} - 3 y_{b}
sage: F.print_options(sorting_reverse=True)
sage: e['a'] - 3 * e['b']
-3 x{'b'} + x{'a'}
sage: F.print_options(**original_print_options) # reset print options
sage: F = CombinatorialFreeModule(QQ, [(1,2), (3,4)])
sage: e = F.basis()
sage: e[(1,2)] - 3 * e[(3,4)]
B[(1, 2)] - 3*B[(3, 4)]
sage: F.print_options(bracket=['_{', '}'])
sage: e[(1,2)] - 3 * e[(3,4)]
B_{(1, 2)} - 3*B_{(3, 4)}
sage: F.print_options(prefix='', bracket=False)
sage: e[(1,2)] - 3 * e[(3,4)]
(1, 2) - 3*(3, 4)
TESTS:
Before :trac:`14054`, combinatorial free modules violated the unique
parent condition. That caused a problem. The tensor product construction
involves maps, but maps check that their domain and the parent of a
to-be-mapped element are identical (not just equal). However, the tensor
product was cached by a :class:`~sage.misc.cachefunc.cached_method`, which
involves comparison by equality (not identity). Hence, the last line of
the following example used to fail with an assertion error::
sage: F = CombinatorialFreeModule(ZZ, [1,2,3], prefix="F")
sage: G = CombinatorialFreeModule(ZZ, [1,2,3,4], prefix="G")
sage: f = F.monomial(1) + 2 * F.monomial(2)
sage: g = 2*G.monomial(3) + G.monomial(4)
sage: tensor([f, g])
2*F[1] # G[3] + F[1] # G[4] + 4*F[2] # G[3] + 2*F[2] # G[4]
sage: F = CombinatorialFreeModule(ZZ, [1,2,3], prefix='x')
sage: G = CombinatorialFreeModule(ZZ, [1,2,3,4], prefix='y')
sage: f = F.monomial(1) + 2 * F.monomial(2)
sage: g = 2*G.monomial(3) + G.monomial(4)
sage: tensor([f, g])
2*x[1] # y[3] + x[1] # y[4] + 4*x[2] # y[3] + 2*x[2] # y[4]
We check that we can use the shorthand ``C.<a,b,...> = ...``::
sage: C.<x,y,z> = CombinatorialFreeModule(QQ)
sage: C
Free module generated by {'x', 'y', 'z'} over Rational Field
sage: a = x - y + 4*z; a
x - y + 4*z
sage: a.parent() is C
True
"""
@staticmethod
def __classcall_private__(cls, base_ring, basis_keys=None, category=None,
prefix=None, names=None, **keywords):
"""
TESTS::
sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])
sage: G = CombinatorialFreeModule(QQ, ('a','b','c'))
sage: F is G
True
sage: F = CombinatorialFreeModule(QQ, ['a','b','c'], latex_bracket=['LEFT', 'RIGHT'])
sage: F.print_options()['latex_bracket']
('LEFT', 'RIGHT')
sage: F is G
False
We check that the category is properly straightened::
sage: F = CombinatorialFreeModule(QQ, ['a','b'])
sage: F1 = CombinatorialFreeModule(QQ, ['a','b'], category = ModulesWithBasis(QQ))
sage: F2 = CombinatorialFreeModule(QQ, ['a','b'], category = [ModulesWithBasis(QQ)])
sage: F3 = CombinatorialFreeModule(QQ, ['a','b'], category = (ModulesWithBasis(QQ),))
sage: F4 = CombinatorialFreeModule(QQ, ['a','b'], category = (ModulesWithBasis(QQ),CommutativeAdditiveSemigroups()))
sage: F5 = CombinatorialFreeModule(QQ, ['a','b'], category = (ModulesWithBasis(QQ),Category.join((LeftModules(QQ), RightModules(QQ)))))
sage: F1 is F, F2 is F, F3 is F, F4 is F, F5 is F
(True, True, True, True, True)
sage: G = CombinatorialFreeModule(QQ, ['a','b'], category = AlgebrasWithBasis(QQ))
sage: F is G
False
"""
if isinstance(basis_keys, range):
basis_keys = tuple(basis_keys)
if isinstance(basis_keys, (list, tuple)):
basis_keys = FiniteEnumeratedSet(basis_keys)
category = ModulesWithBasis(base_ring).or_subcategory(category)
# bracket or latex_bracket might be lists, so convert
# them to tuples so that they're hashable.
bracket = keywords.get('bracket', None)
if isinstance(bracket, list):
keywords['bracket'] = tuple(bracket)
latex_bracket = keywords.get('latex_bracket', None)
if isinstance(latex_bracket, list):
keywords['latex_bracket'] = tuple(latex_bracket)
names, basis_keys, prefix = parse_indices_names(names, basis_keys, prefix, keywords)
if prefix is None:
prefix = "B"
return super(CombinatorialFreeModule, cls).__classcall__(cls,
base_ring, basis_keys, category=category, prefix=prefix, names=names,
**keywords)
# We make this explicitly a Python class so that the methods,
# specifically _mul_, from category framework still works. -- TCS
# We also need to deal with the old pickles too. -- TCS
Element = IndexedFreeModuleElement
@lazy_attribute
def element_class(self):
"""
The (default) class for the elements of this parent
Overrides :meth:`Parent.element_class` to force the
construction of Python class. This is currently needed to
inherit really all the features from categories, and in
particular the initialization of ``_mul_`` in
:meth:`Magmas.ParentMethods.__init_extra__`.
EXAMPLES::
sage: A = Algebras(QQ).WithBasis().example(); A
An example of an algebra with basis:
the free algebra on the generators ('a', 'b', 'c') over Rational Field
sage: A.element_class.mro()
[<class 'sage.categories.examples.algebras_with_basis.FreeAlgebra_with_category.element_class'>,
<type 'sage.modules.with_basis.indexed_element.IndexedFreeModuleElement'>,
...]
sage: a,b,c = A.algebra_generators()
sage: a * b
B[word: ab]
TESTS::
sage: A.__class__.element_class.__module__
'sage.combinat.free_module'
"""
return self.__make_element_class__(self.Element,
name="%s.element_class"%self.__class__.__name__,
module=self.__class__.__module__,
inherit=True)
def __init__(self, R, basis_keys=None, element_class=None, category=None,
prefix=None, names=None, **kwds):
r"""
TESTS::
sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])
sage: F.category()
Category of finite dimensional vector spaces with basis over Rational Field
One may specify the category this module belongs to::
sage: F = CombinatorialFreeModule(QQ, ['a','b','c'], category=AlgebrasWithBasis(QQ))
sage: F.category()
Category of finite dimensional algebras with basis over Rational Field
sage: F = CombinatorialFreeModule(GF(3), ['a','b','c'],
....: category=(Modules(GF(3)).WithBasis(), Semigroups()))
sage: F.category()
Join of Category of finite semigroups
and Category of finite dimensional modules with basis over Finite Field of size 3
and Category of vector spaces with basis over Finite Field of size 3
sage: F = CombinatorialFreeModule(QQ, ['a','b','c'], category = FiniteDimensionalModulesWithBasis(QQ))
sage: F.basis()
Finite family {'a': B['a'], 'c': B['c'], 'b': B['b']}
sage: F.category()
Category of finite dimensional vector spaces with basis over Rational Field
sage: TestSuite(F).run()
TESTS:
Regression test for :trac:`10127`: ``self._indices`` needs to be
set early enough, in case the initialization of the categories
use ``self.basis().keys()``. This occured on several occasions
in non trivial constructions. In the following example,
:class:`AlgebrasWithBasis` constructs ``Homset(self,self)`` to
extend by bilinearity method ``product_on_basis``, which in
turn triggers ``self._repr_()``::
sage: class MyAlgebra(CombinatorialFreeModule):
....: def _repr_(self):
....: return "MyAlgebra on %s"%(self.basis().keys())
....: def product_on_basis(self,i,j):
....: pass
sage: MyAlgebra(ZZ, ZZ, category = AlgebrasWithBasis(QQ))
MyAlgebra on Integer Ring
A simpler example would be welcome!
We check that unknown options are caught::
sage: CombinatorialFreeModule(ZZ, [1,2,3], keyy=2)
Traceback (most recent call last):
...
ValueError: keyy is not a valid print option.
"""
#Make sure R is a ring with unit element
from sage.categories.all import Rings
if R not in Rings():
raise TypeError("Argument R must be a ring.")
if element_class is not None:
self.Element = element_class
# The following is to ensure that basis keys is indeed a parent.
# tuple/list are converted to FiniteEnumeratedSet and set/frozenset to
# Set
# (e.g. root systems passes lists)
basis_keys = Sets()(basis_keys, enumerated_set=True)
# This is needed for the Cartesian product
# TODO: Remove this duplication from __classcall_private__
names, basis_keys, prefix = parse_indices_names(names, basis_keys, prefix, kwds)
if prefix is None:
prefix = "B"
# ignore the optional 'key' since it only affects CachedRepresentation
kwds.pop('key', None)
# This needs to be first as per #10127
if 'monomial_cmp' in kwds:
from sage.misc.superseded import deprecation
deprecation(17229, "Option monomial_cmp is deprecated, use sorting_key and sorting_reverse instead.")
from functools import cmp_to_key
kwds['sorting_key'] = cmp_to_key(kwds['monomial_cmp'])
del kwds['monomial_cmp']
if 'monomial_key' in kwds:
kwds['sorting_key'] = kwds.pop('monomial_key')
if 'monomial_reverse' in kwds:
kwds['sorting_reverse'] = kwds.pop('monomial_reverse')
IndexedGenerators.__init__(self, basis_keys, prefix, **kwds)
if category is None:
category = ModulesWithBasis(R)
elif isinstance(category, tuple):
category = Category.join(category)
if basis_keys in Sets().Finite():
category = category.FiniteDimensional()
Parent.__init__(self, base=R, category=category, names=names,
# Could we get rid of this?
element_constructor=self._element_constructor_)
self._order = None
# For backwards compatibility
_repr_term = IndexedGenerators._repr_generator
_latex_term = IndexedGenerators._latex_generator
def _ascii_art_term(self, m):
r"""
Return an ascii art representation of the term indexed by ``m``.
TESTS::
sage: R = NonCommutativeSymmetricFunctions(QQ).R()
sage: ascii_art(R.one()) # indirect doctest
1
"""
try:
if m == self.one_basis():
return AsciiArt(["1"])
except Exception:
pass
return IndexedGenerators._ascii_art_generator(self, m)
def _unicode_art_term(self, m):
r"""
Return an unicode art representation of the term indexed by ``m``.
TESTS::
sage: R = NonCommutativeSymmetricFunctions(QQ).R()
sage: unicode_art(R.one()) # indirect doctest
1
"""
from sage.typeset.unicode_art import UnicodeArt
try:
if m == self.one_basis():
return UnicodeArt(["1"])
except Exception:
pass
return IndexedGenerators._unicode_art_generator(self, m)
# mostly for backward compatibility
@lazy_attribute
def _element_class(self):
"""
TESTS::
sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])
sage: F._element_class
<class 'sage.combinat.free_module.CombinatorialFreeModule_with_category.element_class'>
"""
return self.element_class
def _an_element_(self):
"""
EXAMPLES::
sage: CombinatorialFreeModule(QQ, ("a", "b", "c")).an_element()
2*B['a'] + 2*B['b'] + 3*B['c']
sage: CombinatorialFreeModule(QQ, ("a", "b", "c"))._an_element_()
2*B['a'] + 2*B['b'] + 3*B['c']
sage: CombinatorialFreeModule(QQ, ()).an_element()
0
sage: CombinatorialFreeModule(QQ, ZZ).an_element()
3*B[-1] + B[0] + 3*B[1]
sage: CombinatorialFreeModule(QQ, RR).an_element()
B[1.00000000000000]
"""
# Try a couple heuristics to build a not completely trivial
# element, while handling cases where R.an_element is not
# implemented, or R has no iterator, or R has few elements.
x = self.zero()
I = self.basis().keys()
R = self.base_ring()
try:
x = x + self.monomial(I.an_element())
except Exception:
pass
try:
g = iter(self.basis().keys())
for c in range(1,4):
x = x + self.term(next(g), R(c))
except Exception:
pass
return x
# What semantic do we want for containment?
# Accepting anything that can be coerced is not reasonable, especially
# if we allow coercion from the enumerated set.
# Accepting anything that can be converted is an option, but that would
# be expensive. So far, x in self if x.parent() == self
def __contains__(self, x):
"""
TESTS::
sage: F = CombinatorialFreeModule(QQ,["a", "b"])
sage: G = CombinatorialFreeModule(ZZ,["a", "b"])
sage: F.monomial("a") in F
True
sage: G.monomial("a") in F
False
sage: "a" in F
False
sage: 5/3 in F
False
"""
return parent(x) == self # is self?
def _element_constructor_(self, x):
"""
Convert ``x`` into ``self``.
EXAMPLES::
sage: F = CombinatorialFreeModule(QQ,["a", "b"])
sage: F(F.monomial("a")) # indirect doctest
B['a']
Do not rely on the following feature which may be removed in the future::
sage: QS3 = SymmetricGroupAlgebra(QQ,3)
sage: QS3([2,3,1]) # indirect doctest
[2, 3, 1]
instead, use::
sage: P = QS3.basis().keys()
sage: QS3.monomial(P([2,3,1])) # indirect doctest
[2, 3, 1]
or:
sage: B = QS3.basis()
sage: B[P([2,3,1])]
[2, 3, 1]
TODO: The symmetric group algebra (and in general,
combinatorial free modules on word-like object could instead
provide an appropriate short-hand syntax QS3[2,3,1]).
Rationale: this conversion is ambiguous in situations like::
sage: F = CombinatorialFreeModule(QQ,[0,1])
Is ``0`` the zero of the base ring, or the index of a basis
element? I.e. should the result be ``0`` or ``B[0]``?
sage: F = CombinatorialFreeModule(QQ,[0,1])
sage: F(0) # this feature may eventually disappear
0
sage: F(1)
Traceback (most recent call last):
...
TypeError: do not know how to make x (= 1) an element of Free module generated by ... over Rational Field
It is preferable not to rely either on the above, and instead, use::
sage: F.zero()
0
Note that, on the other hand, conversions from the ground ring
are systematically defined (and mathematically meaningful) for
algebras.
Conversions between distinct free modules are not allowed any
more::
sage: F = CombinatorialFreeModule(ZZ, ["a", "b"]); F.rename("F")
sage: G = CombinatorialFreeModule(QQ, ["a", "b"]); G.rename("G")
sage: H = CombinatorialFreeModule(ZZ, ["a", "b", "c"]); H.rename("H")
sage: G(F.monomial("a"))
Traceback (most recent call last):
...
TypeError: do not know how to make x (= B['a']) an element of self (=G)
sage: H(F.monomial("a"))
Traceback (most recent call last):
...
TypeError: do not know how to make x (= B['a']) an element of self (=H)
Here is a real life example illustrating that this yielded
mathematically wrong results::
sage: S = SymmetricFunctions(QQ)
sage: s = S.s(); p = S.p()
sage: ss = tensor([s,s]); pp = tensor([p,p])
sage: a = tensor((s[2],s[2]))
The following originally used to yield ``p[[2]] # p[[2]]``, and if
there was no natural coercion between ``s`` and ``p``, this would
raise a ``NotImplementedError``. Since :trac:`15305`, this takes the
coercion between ``s`` and ``p`` and lifts it to the tensor product. ::
sage: pp(a)
1/4*p[1, 1] # p[1, 1] + 1/4*p[1, 1] # p[2] + 1/4*p[2] # p[1, 1] + 1/4*p[2] # p[2]
Extensions of the ground ring should probably be reintroduced
at some point, but via coercions, and with stronger sanity
checks (ensuring that the codomain is really obtained by
extending the scalar of the domain; checking that they share
the same class is not sufficient).
TESTS:
Conversion from the ground ring is implemented for algebras::
sage: QS3 = SymmetricGroupAlgebra(QQ,3)
sage: QS3(2)
2*[1, 2, 3]
"""
R = self.base_ring()
#Coerce ints to Integers
if isinstance(x, int):
x = Integer(x)
if x in R:
if x == 0:
return self.zero()
else:
raise TypeError("do not know how to make x (= %s) an element of %s"%(x, self))
#x is an element of the basis enumerated set;
# This is a very ugly way of testing this
elif ((hasattr(self._indices, 'element_class') and
isinstance(self._indices.element_class, type) and
isinstance(x, self._indices.element_class))
or (parent(x) == self._indices)):
return self.monomial(x)
elif x in self._indices:
return self.monomial(self._indices(x))
else:
if hasattr(self, '_coerce_end'):
try:
return self._coerce_end(x)
except TypeError:
pass
raise TypeError("do not know how to make x (= %s) an element of self (=%s)"%(x,self))
def _an_element_impl(self):
"""
Return an element of ``self``, namely the zero element.
EXAMPLES::
sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'])
sage: F._an_element_impl()
0
sage: _.parent() is F
True
"""
return self.element_class(self, {})
def _first_ngens(self, n):
"""
Used by the preparser for ``F.<x> = ...``.
EXAMPLES::
sage: C = CombinatorialFreeModule(QQ, ZZ)
sage: C._first_ngens(3)
(B[0], B[1], B[-1])
sage: R.<x,y> = FreeAlgebra(QQ, 2)
sage: x,y
(x, y)
"""
try:
# Try gens first for compatibility with classes that
# rely on this (e.g., FreeAlgebra)
return tuple(self.gens())[:n]
except (AttributeError, ValueError, TypeError):
pass
B = self.basis()
it = iter(self._indices)
return tuple(B[next(it)] for i in range(n))
def dimension(self):
"""
Return the dimension of the free module (which is given
by the number of elements in the basis).
EXAMPLES::
sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'])
sage: F.dimension()
3
sage: F.basis().cardinality()
3
sage: F.basis().keys().cardinality()
3
Rank is available as a synonym::
sage: F.rank()
3
::
sage: s = SymmetricFunctions(QQ).schur()
sage: s.dimension()
+Infinity
"""
return self._indices.cardinality()
rank = dimension
def gens(self):
"""
Return a tuple consisting of the basis elements of ``self``.
EXAMPLES::
sage: F = CombinatorialFreeModule(ZZ, ['a', 'b', 'c'])
sage: F.gens()
(B['a'], B['b'], B['c'])
"""
return tuple(self.basis().values())
def set_order(self, order):
"""
Set the order of the elements of the basis.
If :meth:`set_order` has not been called, then the ordering is
the one used in the generation of the elements of self's
associated enumerated set.
.. WARNING::
Many cached methods depend on this order, in
particular for constructing subspaces and quotients.
Changing the order after some computations have been
cached does not invalidate the cache, and is likely to
introduce inconsistencies.
EXAMPLES::
sage: QS2 = SymmetricGroupAlgebra(QQ,2)
sage: b = list(QS2.basis().keys())
sage: b.reverse()
sage: QS2.set_order(b)
sage: QS2.get_order()
[[2, 1], [1, 2]]
"""
self._order = order
from sage.combinat.ranker import rank_from_list
self._rank_basis = rank_from_list(self._order)
@cached_method
def get_order(self):
"""
Return the order of the elements in the basis.
EXAMPLES::
sage: QS2 = SymmetricGroupAlgebra(QQ,2)
sage: QS2.get_order() # note: order changed on 2009-03-13
[[2, 1], [1, 2]]
"""
if self._order is None:
self.set_order(self.basis().keys().list())
return self._order
def get_order_cmp(self):
"""
Return a comparison function on the basis indices that is
compatible with the current term order.
EXAMPLES::
sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example()
sage: Acmp = A.get_order_cmp()
sage: sorted(A.basis().keys(), Acmp)
['x', 'y', 'a', 'b']
sage: A.set_order(list(reversed(A.basis().keys())))
sage: Acmp = A.get_order_cmp()
sage: sorted(A.basis().keys(), Acmp)
['b', 'a', 'y', 'x']
"""
self.get_order()
return self._order_cmp
def _order_cmp(self, x, y):
"""
Compare `x` and `y` w.r.t. the term order.
INPUT:
- ``x``, ``y`` -- indices of the basis of ``self``
OUTPUT:
`-1`, `0`, or `1` depending on whether `x<y`, `x==y`, or `x>y`
w.r.t. the term order.
EXAMPLES::
sage: A = CombinatorialFreeModule(QQ, ['x','y','a','b'])
sage: A.set_order(['x', 'y', 'a', 'b'])
sage: A._order_cmp('x', 'y')
-1
sage: A._order_cmp('y', 'y')
0
sage: A._order_cmp('a', 'y')
1
"""
return cmp(self._rank_basis(x), self._rank_basis(y))
def get_order_key(self):
"""
Return a comparison key on the basis indices that is
compatible with the current term order.
EXAMPLES::
sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example()
sage: A.set_order(['x', 'y', 'a', 'b'])
sage: Akey = A.get_order_key()
sage: sorted(A.basis().keys(), key=Akey)
['x', 'y', 'a', 'b']
sage: A.set_order(list(reversed(A.basis().keys())))
sage: Akey = A.get_order_key()
sage: sorted(A.basis().keys(), key=Akey)
['b', 'a', 'y', 'x']
"""
self.get_order()
return self._order_key
def _order_key(self, x):
"""
Return a key for `x` compatible with the term order.
INPUT:
- ``x`` -- indices of the basis of ``self``
EXAMPLES::
sage: A = CombinatorialFreeModule(QQ, ['x','y','a','b'])
sage: A.set_order(['x', 'y', 'a', 'b'])
sage: A._order_key('x')
0
sage: A._order_key('y')
1
sage: A._order_key('a')
2
"""
return self._rank_basis(x)
def from_vector(self, vector):
"""
Build an element of ``self`` from a (sparse) vector.
.. SEEALSO:: :meth:`get_order`, :meth:`CombinatorialFreeModule.Element._vector_`
EXAMPLES::
sage: QS3 = SymmetricGroupAlgebra(QQ, 3)
sage: b = QS3.from_vector(vector((2, 0, 0, 0, 0, 4))); b
2*[1, 2, 3] + 4*[3, 2, 1]
sage: a = 2*QS3([1,2,3])+4*QS3([3,2,1])
sage: a == b
True
"""
cc = self.get_order()
return self._from_dict({cc[index]: coeff for (index,coeff) in six.iteritems(vector)})
def __cmp__(self, other):
"""
EXAMPLES::
sage: XQ = SchubertPolynomialRing(QQ)
sage: XZ = SchubertPolynomialRing(ZZ)
sage: XQ == XZ #indirect doctest
False
sage: XQ == XQ
True
"""
if not isinstance(other, self.__class__):
return -1
c = cmp(self.base_ring(), other.base_ring())
if c:
return c
return 0
def sum(self, iter_of_elements):
"""
Return the sum of all elements in ``iter_of_elements``.
Overrides method inherited from commutative additive monoid as it
is much faster on dicts directly.
INPUT:
- ``iter_of_elements`` -- iterator of elements of ``self``
EXAMPLES::
sage: F = CombinatorialFreeModule(QQ,[1,2])
sage: f = F.an_element(); f
2*B[1] + 2*B[2]
sage: F.sum( f for _ in range(5) )
10*B[1] + 10*B[2]
"""
D = blas.sum(element._monomial_coefficients for element in iter_of_elements)
return self._from_dict(D, remove_zeros=False)
def linear_combination(self, iter_of_elements_coeff, factor_on_left=True):
"""
Return the linear combination `\lambda_1 v_1 + \cdots +
\lambda_k v_k` (resp. the linear combination `v_1 \lambda_1 +
\cdots + v_k \lambda_k`) where ``iter_of_elements_coeff`` iterates
through the sequence `((\lambda_1, v_1), ..., (\lambda_k, v_k))`.
INPUT:
- ``iter_of_elements_coeff`` -- iterator of pairs ``(element, coeff)``
with ``element`` in ``self`` and ``coeff`` in ``self.base_ring()``
- ``factor_on_left`` -- (optional) if ``True``, the coefficients are
multiplied from the left if ``False``, the coefficients are
multiplied from the right
EXAMPLES::
sage: F = CombinatorialFreeModule(QQ,[1,2])
sage: f = F.an_element(); f
2*B[1] + 2*B[2]
sage: F.linear_combination( (f,i) for i in range(5) )
20*B[1] + 20*B[2]
"""
return self._from_dict(blas.linear_combination( ((element._monomial_coefficients, coeff)
for element, coeff in iter_of_elements_coeff),
factor_on_left=factor_on_left ),
remove_zeros=False)
def term(self, index, coeff=None):
"""
Construct a term in ``self``.
INPUT:
- ``index`` -- the index of a basis element
- ``coeff`` -- an element of the coefficient ring (default: one)
EXAMPLES::
sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c'])
sage: F.term('a',3)
3*B['a']
sage: F.term('a')
B['a']