-
-
Notifications
You must be signed in to change notification settings - Fork 405
/
modules_with_basis.py
2425 lines (1913 loc) · 91.4 KB
/
modules_with_basis.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
r"""
Modules With Basis
AUTHORS:
- Nicolas M. Thiery (2008-2014): initial revision, axiomatization
- Jason Bandlow and Florent Hivert (2010): Triangular Morphisms
- Christian Stump (2010): :trac:`9648` module_morphism's to a wider class
of codomains
"""
#*****************************************************************************
# Copyright (C) 2008 Teresa Gomez-Diaz (CNRS) <Teresa.Gomez-Diaz@univ-mlv.fr>
# 2008-2014 Nicolas M. Thiery <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#******************************************************************************
from __future__ import absolute_import
from sage.misc.lazy_import import LazyImport, lazy_import
from sage.misc.lazy_attribute import lazy_attribute
from sage.misc.cachefunc import cached_method
from sage.misc.abstract_method import abstract_method
from sage.categories.homsets import HomsetsCategory
from sage.categories.cartesian_product import CartesianProductsCategory
from sage.categories.tensor import tensor, TensorProductsCategory
from sage.categories.dual import DualObjectsCategory
from sage.categories.category_with_axiom import CategoryWithAxiom_over_base_ring
from sage.categories.fields import Fields
from sage.categories.modules import Modules
from sage.categories.poor_man_map import PoorManMap
from sage.structure.element import Element, parent
lazy_import('sage.modules.with_basis.morphism',
['ModuleMorphismByLinearity',
'ModuleMorphismFromMatrix',
'ModuleMorphismFromFunction',
'DiagonalModuleMorphism',
'TriangularModuleMorphismByLinearity',
'TriangularModuleMorphismFromFunction'])
class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
"""
The category of modules with a distinguished basis.
The elements are represented by expanding them in the distinguished basis.
The morphisms are not required to respect the distinguished basis.
EXAMPLES::
sage: ModulesWithBasis(ZZ)
Category of modules with basis over Integer Ring
sage: ModulesWithBasis(ZZ).super_categories()
[Category of modules over Integer Ring]
If the base ring is actually a field, this constructs instead the
category of vector spaces with basis::
sage: ModulesWithBasis(QQ)
Category of vector spaces with basis over Rational Field
sage: ModulesWithBasis(QQ).super_categories()
[Category of modules with basis over Rational Field,
Category of vector spaces over Rational Field]
Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"
sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"
sage: H = Hom(X, Y); H
Set of Morphisms from X to Y in Category of finite dimensional vector spaces with basis over Rational Field
The simplest morphism is the zero map::
sage: H.zero() # todo: move this test into module once we have an example
Generic morphism:
From: X
To: Y
which we can apply to elements of `X`::
sage: x = X.monomial(1) + 3 * X.monomial(2)
sage: H.zero()(x)
0
EXAMPLES:
We now construct a more interesting morphism by extending a
function by linearity::
sage: phi = H(on_basis = lambda i: Y.monomial(i+2)); phi
Generic morphism:
From: X
To: Y
sage: phi(x)
B[3] + 3*B[4]
We can retrieve the function acting on indices of the basis::
sage: f = phi.on_basis()
sage: f(1), f(2)
(B[3], B[4])
`Hom(X,Y)` has a natural module structure (except for the zero,
the operations are not yet implemented though). However since the
dimension is not necessarily finite, it is not a module with
basis; but see :class:`FiniteDimensionalModulesWithBasis` and
:class:`GradedModulesWithBasis`::
sage: H in ModulesWithBasis(QQ), H in Modules(QQ)
(False, True)
Some more playing around with categories and higher order homsets::
sage: H.category()
Category of homsets of modules with basis over Rational Field
sage: Hom(H, H).category()
Category of endsets of homsets of modules with basis over Rational Field
.. TODO:: ``End(X)`` is an algebra.
.. NOTE::
This category currently requires an implementation of an
element method ``support``. Once :trac:`18066` is merged, an
implementation of an ``items`` method will be required.
TESTS::
sage: f = H.zero().on_basis()
sage: f(1)
0
sage: f(2)
0
sage: TestSuite(ModulesWithBasis(ZZ)).run()
"""
def _call_(self, x):
"""
Construct a module with basis (resp. vector space) from the data in ``x``.
EXAMPLES::
sage: CZ = ModulesWithBasis(ZZ); CZ
Category of modules with basis over Integer Ring
sage: CQ = ModulesWithBasis(QQ); CQ
Category of vector spaces with basis over Rational Field
``x`` is returned unchanged if it is already in this category::
sage: CZ(CombinatorialFreeModule(ZZ, ('a','b','c')))
Free module generated by {'a', 'b', 'c'} over Integer Ring
sage: CZ(ZZ^3)
Ambient free module of rank 3 over the principal ideal domain Integer Ring
If needed (and possible) the base ring is changed appropriately::
sage: CQ(ZZ^3) # indirect doctest
Vector space of dimension 3 over Rational Field
If ``x`` itself is not a module with basis, but there is a
canonical one associated to it, the latter is returned::
sage: CQ(AbelianVariety(Gamma0(37))) # indirect doctest
Vector space of dimension 4 over Rational Field
"""
try:
M = x.free_module()
if M.base_ring() != self.base_ring():
M = M.change_ring(self.base_ring())
except (TypeError, AttributeError) as msg:
raise TypeError("%s\nunable to coerce x (=%s) into %s"%(msg,x,self))
return M
def is_abelian(self):
"""
Return whether this category is abelian.
This is the case if and only if the base ring is a field.
EXAMPLES::
sage: ModulesWithBasis(QQ).is_abelian()
True
sage: ModulesWithBasis(ZZ).is_abelian()
False
"""
return self.base_ring().is_field()
FiniteDimensional = LazyImport('sage.categories.finite_dimensional_modules_with_basis', 'FiniteDimensionalModulesWithBasis', at_startup=True)
Filtered = LazyImport('sage.categories.filtered_modules_with_basis', 'FilteredModulesWithBasis')
Graded = LazyImport('sage.categories.graded_modules_with_basis', 'GradedModulesWithBasis')
Super = LazyImport('sage.categories.super_modules_with_basis', 'SuperModulesWithBasis')
# To implement a module_with_basis you need to implement the
# following methods:
# - On the parent class, either basis() or an _indices attribute and
# monomial().
# - On the element class, monomial_coefficients().
class ParentMethods:
@cached_method
def basis(self):
"""
Return the basis of ``self``.
EXAMPLES::
sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])
sage: F.basis()
Finite family {'a': B['a'], 'b': B['b'], 'c': B['c']}
::
sage: QS3 = SymmetricGroupAlgebra(QQ,3)
sage: list(QS3.basis())
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
from sage.combinat.family import Family
return Family(self._indices, self.monomial)
def module_morphism(self, on_basis=None, matrix=None, function=None,
diagonal=None, triangular=None, unitriangular=False,
**keywords):
r"""
Construct a module morphism from ``self`` to ``codomain``.
Let ``self`` be a module `X` with a basis indexed by `I`.
This constructs a morphism `f: X \to Y` by linearity from
a map `I \to Y` which is to be its restriction to the
basis `(x_i)_{i \in I}` of `X`. Some variants are possible
too.
INPUT:
- ``self`` -- a parent `X` in ``ModulesWithBasis(R)`` with
basis `x=(x_i)_{i\in I}`.
Exactly one of the four following options must be
specified in order to define the morphism:
- ``on_basis`` -- a function `f` from `I` to `Y`
- ``diagonal`` -- a function `d` from `I` to `R`
- ``function`` -- a function `f` from `X` to `Y`
- ``matrix`` -- a matrix of size `\dim Y \times \dim X`
(if the keyword ``side`` is set to ``'left'``) or
`\dim Y \times \dim X` (if this keyword is ``'right'``)
Further options include:
- ``codomain`` -- the codomain `Y` of the morphism (default:
``f.codomain()`` if it's defined; otherwise it must be specified)
- ``category`` -- a category or ``None`` (default: ``None``)
- ``zero`` -- the zero of the codomain (default: ``codomain.zero()``);
can be used (with care) to define affine maps.
Only meaningful with ``on_basis``.
- ``position`` -- a non-negative integer specifying which
positional argument is used as the input of the function `f`
(default: 0); this is currently only used with ``on_basis``.
- ``triangular`` -- (default: ``None``) ``"upper"`` or
``"lower"`` or ``None``:
* ``"upper"`` - if the
:meth:`~ModulesWithBasis.ElementMethods.leading_support`
of the image of the basis vector `x_i` is `i`, or
* ``"lower"`` - if the
:meth:`~ModulesWithBasis.ElementMethods.trailing_support`
of the image of the basis vector `x_i` is `i`.
- ``unitriangular`` -- (default: ``False``) a boolean.
Only meaningful for a triangular morphism.
As a shorthand, one may use ``unitriangular="lower"``
for ``triangular="lower", unitriangular=True``.
- ``side`` -- "left" or "right" (default: "left")
Only meaningful for a morphism built from a matrix.
EXAMPLES:
With the ``on_basis`` option, this returns a function `g`
obtained by extending `f` by linearity on the
``position``-th positional argument. For example, for
``position == 1`` and a ternary function `f`, one has:
.. MATH::
g\left( a,\ \sum_i \lambda_i x_i,\ c \right)
= \sum_i \lambda_i f(a, i, c).
::
sage: X = CombinatorialFreeModule(QQ, [1,2,3]); X.rename("X")
sage: Y = CombinatorialFreeModule(QQ, [1,2,3,4]); Y.rename("Y")
sage: phi = X.module_morphism(lambda i: Y.monomial(i) + 2*Y.monomial(i+1), codomain = Y)
sage: x = X.basis(); y = Y.basis()
sage: phi(x[1] + x[3])
B[1] + 2*B[2] + B[3] + 2*B[4]
sage: phi
Generic morphism:
From: X
To: Y
By default, the category is the first of
``Modules(R).WithBasis().FiniteDimensional()``,
``Modules(R).WithBasis()``, ``Modules(R)``, and
``CommutativeAdditiveMonoids()`` that contains both the
domain and the codomain::
sage: phi.category_for()
Category of finite dimensional vector spaces with basis over Rational Field
With the ``zero`` argument, one can define affine morphisms::
sage: phi = X.module_morphism(lambda i: Y.monomial(i) + 2*Y.monomial(i+1),
....: codomain = Y, zero = 10*y[1])
sage: phi(x[1] + x[3])
11*B[1] + 2*B[2] + B[3] + 2*B[4]
In this special case, the default category is ``Sets()``::
sage: phi.category_for()
Category of sets
One can construct morphisms with the base ring as codomain::
sage: X = CombinatorialFreeModule(ZZ,[1,-1])
sage: phi = X.module_morphism( on_basis=lambda i: i, codomain=ZZ )
sage: phi( 2 * X.monomial(1) + 3 * X.monomial(-1) )
-1
sage: phi.category_for()
Category of commutative additive semigroups
sage: phi.category_for() # todo: not implemented (ZZ is currently not in Modules(ZZ))
Category of modules over Integer Ring
Or more generally any ring admitting a coercion map from
the base ring::
sage: phi = X.module_morphism(on_basis=lambda i: i, codomain=RR )
sage: phi( 2 * X.monomial(1) + 3 * X.monomial(-1) )
-1.00000000000000
sage: phi.category_for()
Category of commutative additive semigroups
sage: phi.category_for() # todo: not implemented (RR is currently not in Modules(ZZ))
Category of modules over Integer Ring
sage: phi = X.module_morphism(on_basis=lambda i: i, codomain=Zmod(4) )
sage: phi( 2 * X.monomial(1) + 3 * X.monomial(-1) )
3
sage: phi = Y.module_morphism(on_basis=lambda i: i, codomain=Zmod(4) )
Traceback (most recent call last):
...
ValueError: codomain(=Ring of integers modulo 4) should be a module over the base ring of the domain(=Y)
On can also define module morphisms between free modules
over different base rings; here we implement the natural
map from `X = \RR^2` to `Y = \CC`::
sage: X = CombinatorialFreeModule(RR,['x','y'])
sage: Y = CombinatorialFreeModule(CC,['z'])
sage: x = X.monomial('x')
sage: y = X.monomial('y')
sage: z = Y.monomial('z')
sage: def on_basis( a ):
....: if a == 'x':
....: return CC(1) * z
....: elif a == 'y':
....: return CC(I) * z
sage: phi = X.module_morphism( on_basis=on_basis, codomain=Y )
sage: v = 3 * x + 2 * y; v
3.00000000000000*B['x'] + 2.00000000000000*B['y']
sage: phi(v)
(3.00000000000000+2.00000000000000*I)*B['z']
sage: phi.category_for()
Category of commutative additive semigroups
sage: phi.category_for() # todo: not implemented (CC is currently not in Modules(RR)!)
Category of vector spaces over Real Field with 53 bits of precision
sage: Y = CombinatorialFreeModule(CC['q'],['z'])
sage: z = Y.monomial('z')
sage: phi = X.module_morphism( on_basis=on_basis, codomain=Y )
sage: phi(v)
(3.00000000000000+2.00000000000000*I)*B['z']
Of course, there should be a coercion between the
respective base rings of the domain and the codomain for
this to be meaningful::
sage: Y = CombinatorialFreeModule(QQ,['z'])
sage: phi = X.module_morphism( on_basis=on_basis, codomain=Y )
Traceback (most recent call last):
...
ValueError: codomain(=Free module generated by {'z'} over Rational Field)
should be a module over the base ring of the
domain(=Free module generated by {'x', 'y'} over Real Field with 53 bits of precision)
sage: Y = CombinatorialFreeModule(RR['q'],['z'])
sage: phi = Y.module_morphism( on_basis=on_basis, codomain=X )
Traceback (most recent call last):
...
ValueError: codomain(=Free module generated by {'x', 'y'} over Real Field with 53 bits of precision)
should be a module over the base ring of the
domain(=Free module generated by {'z'} over Univariate Polynomial Ring in q over Real Field with 53 bits of precision)
With the ``diagonal=d`` argument, this constructs the
module morphism `g` such that
.. MATH::
`g(x_i) = d(i) y_i`.
This assumes that the respective bases `x` and `y` of `X`
and `Y` have the same index set `I`::
sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X")
sage: phi = X.module_morphism(diagonal=factorial, codomain=X)
sage: x = X.basis()
sage: phi(x[1]), phi(x[2]), phi(x[3])
(B[1], 2*B[2], 6*B[3])
See also: :class:`sage.modules.with_basis.morphism.DiagonalModuleMorphism`.
With the ``matrix=m`` argument, this constructs the module
morphism whose matrix in the distinguished basis of `X`
and `Y` is `m`::
sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X"); x = X.basis()
sage: Y = CombinatorialFreeModule(ZZ, [3,4]); Y.rename("Y"); y = Y.basis()
sage: m = matrix([[0,1,2],[3,5,0]])
sage: phi = X.module_morphism(matrix=m, codomain=Y)
sage: phi(x[1])
3*B[4]
sage: phi(x[2])
B[3] + 5*B[4]
See also: :class:`sage.modules.with_basis.morphism.ModuleMorphismFromMatrix`.
With ``triangular="upper"``, the constructed module morphism is
assumed to be upper triangular; that is its matrix in the
distinguished basis of `X` and `Y` would be upper triangular with
invertible elements on its diagonal. This is used to compute
preimages and to invert the morphism::
sage: I = list(range(1, 200))
sage: X = CombinatorialFreeModule(QQ, I); X.rename("X"); x = X.basis()
sage: Y = CombinatorialFreeModule(QQ, I); Y.rename("Y"); y = Y.basis()
sage: f = Y.sum_of_monomials * divisors
sage: phi = X.module_morphism(f, triangular="upper", codomain = Y)
sage: phi(x[2])
B[1] + B[2]
sage: phi(x[6])
B[1] + B[2] + B[3] + B[6]
sage: phi(x[30])
B[1] + B[2] + B[3] + B[5] + B[6] + B[10] + B[15] + B[30]
sage: phi.preimage(y[2])
-B[1] + B[2]
sage: phi.preimage(y[6])
B[1] - B[2] - B[3] + B[6]
sage: phi.preimage(y[30])
-B[1] + B[2] + B[3] + B[5] - B[6] - B[10] - B[15] + B[30]
sage: (phi^-1)(y[30])
-B[1] + B[2] + B[3] + B[5] - B[6] - B[10] - B[15] + B[30]
Since :trac:`8678`, one can also define a triangular
morphism from a function::
sage: X = CombinatorialFreeModule(QQ, [0,1,2,3,4]); x = X.basis()
sage: from sage.modules.with_basis.morphism import TriangularModuleMorphismFromFunction
sage: def f(x): return x + X.term(0, sum(x.coefficients()))
sage: phi = X.module_morphism(function=f, codomain=X, triangular="upper")
sage: phi(x[2] + 3*x[4])
4*B[0] + B[2] + 3*B[4]
sage: phi.preimage(_)
B[2] + 3*B[4]
For details and further optional arguments, see
:class:`sage.modules.with_basis.morphism.TriangularModuleMorphism`.
.. WARNING::
As a temporary measure, until multivariate morphisms
are implemented, the constructed morphism is in
``Hom(codomain, domain, category)``. This is only
correct for unary functions.
.. TODO::
- Should codomain be ``self`` by default in the
diagonal, triangular, and matrix cases?
- Support for diagonal morphisms between modules not
sharing the same index set
TESTS::
sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X")
sage: phi = X.module_morphism(codomain=X)
Traceback (most recent call last):
...
ValueError: module_morphism() takes exactly one option
out of `matrix`, `on_basis`, `function`, `diagonal`
::
sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X")
sage: phi = X.module_morphism(diagonal=factorial, matrix=matrix(), codomain=X)
Traceback (most recent call last):
...
ValueError: module_morphism() takes exactly one option
out of `matrix`, `on_basis`, `function`, `diagonal`
::
sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X")
sage: phi = X.module_morphism(matrix=factorial, codomain=X)
Traceback (most recent call last):
...
ValueError: matrix (=factorial) should be a matrix
::
sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X")
sage: phi = X.module_morphism(diagonal=3, codomain=X)
Traceback (most recent call last):
...
ValueError: diagonal (=3) should be a function
"""
if len([x for x in [matrix, on_basis, function, diagonal] if x is not None]) != 1:
raise ValueError("module_morphism() takes exactly one option out of `matrix`, `on_basis`, `function`, `diagonal`")
if matrix is not None:
return ModuleMorphismFromMatrix(domain=self, matrix=matrix, **keywords)
if diagonal is not None:
return DiagonalModuleMorphism(domain=self, diagonal=diagonal, **keywords)
if unitriangular in ["upper", "lower"] and triangular is None:
triangular = unitriangular
unitriangular = True
if triangular is not None:
if on_basis is not None:
return TriangularModuleMorphismByLinearity(
domain=self, on_basis=on_basis,
triangular=triangular, unitriangular=unitriangular,
**keywords)
else:
return TriangularModuleMorphismFromFunction(
domain=self, function=function,
triangular=triangular, unitriangular=unitriangular,
**keywords)
if on_basis is not None:
return ModuleMorphismByLinearity(
domain=self, on_basis=on_basis, **keywords)
else:
return ModuleMorphismFromFunction( # Or just SetMorphism?
domain=self, function=function, **keywords)
_module_morphism = module_morphism
def _repr_(self):
"""
EXAMPLES::
sage: class FooBar(CombinatorialFreeModule): pass
sage: C = FooBar(QQ, (1,2,3)); C # indirect doctest
Free module generated by {1, 2, 3} over Rational Field
sage: C._name = "foobar"; C
foobar over Rational Field
sage: C.rename("barfoo"); C
barfoo
sage: class FooBar(Parent):
....: def basis(self): return Family({1:"foo", 2:"bar"})
....: def base_ring(self): return QQ
sage: FooBar(category = ModulesWithBasis(QQ))
Free module generated by [1, 2] over Rational Field
"""
if hasattr(self, "_name"):
name = self._name
else:
name = "Free module generated by {}".format(self.basis().keys())
return name + " over {}".format(self.base_ring())
def _compute_support_order(self, elements, support_order=None):
"""
Return the support of a set of elements in ``self`` sorted
in some order.
INPUT:
- ``elements`` -- the list of elements
- ``support_order`` -- (optional) either something that can
be converted into a tuple or a key function
EXAMPLES:
A finite dimensional module::
sage: V = CombinatorialFreeModule(QQ, range(10), prefix='x')
sage: B = V.basis()
sage: elts = [B[0] - 2*B[3], B[5] + 2*B[0], B[2], B[3], B[1] + B[2] + B[8]]
sage: V._compute_support_order(elts)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
sage: V._compute_support_order(elts, [1,2,0,4,3,5,9,8,7,6])
(1, 2, 0, 4, 3, 5, 9, 8, 7, 6)
sage: V._compute_support_order(elts, lambda x: -x)
(8, 5, 3, 2, 1, 0)
An infinite dimensional module::
sage: V = CombinatorialFreeModule(QQ, ZZ, prefix='z')
sage: B = V.basis()
sage: elts = [B[0] - 2*B[3], B[5] + 2*B[0], B[2], B[3], B[1] + B[2] + B[8]]
sage: V._compute_support_order(elts)
(0, 1, 2, 3, 5, 8)
sage: V._compute_support_order(elts, [1,2,0,4,3,5,9,8,7,6])
(1, 2, 0, 4, 3, 5, 9, 8, 7, 6)
sage: V._compute_support_order(elts, lambda x: -x)
(8, 5, 3, 2, 1, 0)
"""
if support_order is None:
try:
support_order = self.get_order()
except (ValueError, TypeError, NotImplementedError, AttributeError):
support_order = set()
for y in elements:
support_order.update(y.support())
try: # Try to sort to make the output more consistent
support_order = sorted(support_order)
except (ValueError, TypeError):
pass
try:
support_order = tuple(support_order)
except (ValueError, TypeError):
support = set()
for y in elements:
support.update(y.support())
support_order = sorted(support, key=support_order)
return tuple(support_order)
def echelon_form(self, elements, row_reduced=False, order=None):
r"""
Return a basis in echelon form of the subspace spanned by
a finite set of elements.
INPUT:
- ``elements`` -- a list or finite iterable of elements of ``self``
- ``row_reduced`` -- (default: ``False``) whether to compute the
basis for the row reduced echelon form
- ``order`` -- (optional) either something that can
be converted into a tuple or a key function
OUTPUT:
A list of elements of ``self`` whose expressions as vectors
form a matrix in echelon form. If ``base_ring`` is specified,
then the calculation is achieved in this base ring.
EXAMPLES::
sage: R.<x,y> = QQ[]
sage: C = CombinatorialFreeModule(R, ZZ, prefix='z')
sage: z = C.basis()
sage: C.echelon_form([z[0] - z[1], 2*z[1] - 2*z[2], z[0] - z[2]])
[z[0] - z[2], z[1] - z[2]]
"""
order = self._compute_support_order(elements, order)
from sage.matrix.constructor import matrix
mat = matrix(self.base_ring(), [[g[s] for s in order] for g in elements])
# Echelonizing a matrix over a field returned the rref
if row_reduced and self.base_ring() not in Fields():
try:
mat = mat.rref().change_ring(self.base_ring())
except (ValueError, TypeError):
raise ValueError("unable to compute the row reduced echelon form")
else:
mat.echelonize()
return [self._from_dict({order[i]: c for i, c in enumerate(vec) if c},
remove_zeros=False)
for vec in mat if vec]
def submodule(self, gens, check=True, already_echelonized=False,
unitriangular=False, support_order=None, category=None,
*args, **opts):
r"""
The submodule spanned by a finite set of elements.
INPUT:
- ``gens`` -- a list or family of elements of ``self``
- ``check`` -- (default: ``True``) whether to verify that the
elements of ``gens`` are in ``self``
- ``already_echelonized`` -- (default: ``False``) whether
the elements of ``gens`` are already in (not necessarily
reduced) echelon form
- ``unitriangular`` -- (default: ``False``) whether
the lift morphism is unitriangular
- ``support_order`` -- (optional) either something that can
be converted into a tuple or a key function
If ``already_echelonized`` is ``False``, then the
generators are put in reduced echelon form using
:meth:`echelonize`, and reindexed by `0,1,...`.
.. WARNING::
At this point, this method only works for finite
dimensional submodules and if matrices can be
echelonized over the base ring.
If in addition ``unitriangular`` is ``True``, then
the generators are made such that the coefficients of
the pivots are 1, so that lifting map is unitriangular.
The basis of the submodule uses the same index set as the
generators, and the lifting map sends `y_i` to `gens[i]`.
.. SEEALSO::
- :meth:`ModulesWithBasis.FiniteDimensional.ParentMethods.quotient_module`
- :class:`sage.modules.with_basis.subquotient.SubmoduleWithBasis`
EXAMPLES:
We construct a submodule of the free `\QQ`-module generated by
`x_0, x_1, x_2`. The submodule is spanned by `y_0 = x_0 - x_1` and
`y_1 - x_1 - x_2`, and its basis elements are indexed by `0` and `1`::
sage: X = CombinatorialFreeModule(QQ, range(3), prefix="x")
sage: x = X.basis()
sage: gens = [x[0] - x[1], x[1] - x[2]]; gens
[x[0] - x[1], x[1] - x[2]]
sage: Y = X.submodule(gens, already_echelonized=True)
sage: Y.print_options(prefix='y'); Y
Free module generated by {0, 1} over Rational Field
sage: y = Y.basis()
sage: y[1]
y[1]
sage: y[1].lift()
x[1] - x[2]
sage: Y.retract(x[0]-x[2])
y[0] + y[1]
sage: Y.retract(x[0])
Traceback (most recent call last):
...
ValueError: x[0] is not in the image
By using a family to specify a basis of the submodule, we obtain a
submodule whose index set coincides with the index set of the family::
sage: X = CombinatorialFreeModule(QQ, range(3), prefix="x")
sage: x = X.basis()
sage: gens = Family({1 : x[0] - x[1], 3: x[1] - x[2]}); gens
Finite family {1: x[0] - x[1], 3: x[1] - x[2]}
sage: Y = X.submodule(gens, already_echelonized=True)
sage: Y.print_options(prefix='y'); Y
Free module generated by {1, 3} over Rational Field
sage: y = Y.basis()
sage: y[1]
y[1]
sage: y[1].lift()
x[0] - x[1]
sage: y[3].lift()
x[1] - x[2]
sage: Y.retract(x[0]-x[2])
y[1] + y[3]
sage: Y.retract(x[0])
Traceback (most recent call last):
...
ValueError: x[0] is not in the image
It is not necessary that the generators of the submodule form
a basis (an explicit basis will be computed)::
sage: X = CombinatorialFreeModule(QQ, range(3), prefix="x")
sage: x = X.basis()
sage: gens = [x[0] - x[1], 2*x[1] - 2*x[2], x[0] - x[2]]; gens
[x[0] - x[1], 2*x[1] - 2*x[2], x[0] - x[2]]
sage: Y = X.submodule(gens, already_echelonized=False)
sage: Y.print_options(prefix='y')
sage: Y
Free module generated by {0, 1} over Rational Field
sage: [b.lift() for b in Y.basis()]
[x[0] - x[2], x[1] - x[2]]
We now implement by hand the center of the algebra of the
symmetric group `S_3`::
sage: S3 = SymmetricGroup(3)
sage: S3A = S3.algebra(QQ)
sage: basis = S3A.annihilator_basis(S3A.algebra_generators(), S3A.bracket)
sage: basis
((), (1,2,3) + (1,3,2), (2,3) + (1,2) + (1,3))
sage: center = S3A.submodule(basis,
....: category=AlgebrasWithBasis(QQ).Subobjects(),
....: already_echelonized=True)
sage: center
Free module generated by {0, 1, 2} over Rational Field
sage: center in Algebras
True
sage: center.print_options(prefix='c')
sage: c = center.basis()
sage: c[1].lift()
(1,2,3) + (1,3,2)
sage: c[0]^2
c[0]
sage: e = 1/6*(c[0]+c[1]+c[2])
sage: e.is_idempotent()
True
Of course, this center is best constructed using::
sage: center = S3A.center()
We can also automatically construct a basis such that
the lift morphism is (lower) unitriangular::
sage: R.<a,b> = QQ[]
sage: C = CombinatorialFreeModule(R, range(3), prefix='x')
sage: x = C.basis()
sage: gens = [x[0] - x[1], 2*x[1] - 2*x[2], x[0] - x[2]]
sage: Y = C.submodule(gens, unitriangular=True)
sage: Y.lift.matrix()
[ 1 0]
[ 0 1]
[-1 -1]
We now construct a (finite-dimensional) submodule of an
infinite dimensional free module::
sage: C = CombinatorialFreeModule(QQ, ZZ, prefix='z')
sage: z = C.basis()
sage: gens = [z[0] - z[1], 2*z[1] - 2*z[2], z[0] - z[2]]
sage: Y = C.submodule(gens)
sage: [Y.lift(b) for b in Y.basis()]
[z[0] - z[2], z[1] - z[2]]
TESTS::
sage: TestSuite(Y).run()
sage: TestSuite(center).run()
"""
support_order = self._compute_support_order(gens, support_order)
if not already_echelonized:
gens = self.echelon_form(gens, unitriangular, order=support_order)
from sage.modules.with_basis.subquotient import SubmoduleWithBasis
return SubmoduleWithBasis(gens, ambient=self,
support_order=support_order,
unitriangular=unitriangular,
category=category, *args, **opts)
def quotient_module(self, submodule, check=True, already_echelonized=False, category=None):
r"""
Construct the quotient module ``self`` / ``submodule``.
INPUT:
- ``submodule`` -- a submodule with basis of ``self``, or
something that can be turned into one via
``self.submodule(submodule)``
- ``check``, ``already_echelonized`` -- passed down to
:meth:`ModulesWithBasis.ParentMethods.submodule`
.. WARNING::
At this point, this only supports quotients by free
submodules admitting a basis in unitriangular echelon
form. In this case, the quotient is also a free
module, with a basis consisting of the retract of a
subset of the basis of ``self``.
EXAMPLES::
sage: X = CombinatorialFreeModule(QQ, range(3), prefix="x")
sage: x = X.basis()
sage: Y = X.quotient_module([x[0]-x[1], x[1]-x[2]], already_echelonized=True)
sage: Y.print_options(prefix='y'); Y
Free module generated by {2} over Rational Field
sage: y = Y.basis()
sage: y[2]
y[2]
sage: y[2].lift()
x[2]
sage: Y.retract(x[0]+2*x[1])
3*y[2]
sage: R.<a,b> = QQ[]
sage: C = CombinatorialFreeModule(R, range(3), prefix='x')
sage: x = C.basis()
sage: gens = [x[0] - x[1], 2*x[1] - 2*x[2], x[0] - x[2]]
sage: Y = X.quotient_module(gens)
.. SEEALSO::
- :meth:`Modules.WithBasis.ParentMethods.submodule`
- :meth:`Rings.ParentMethods.quotient`
- :class:`sage.modules.with_basis.subquotient.QuotientModuleWithBasis`
"""
from sage.modules.with_basis.subquotient import SubmoduleWithBasis, QuotientModuleWithBasis
if not isinstance(submodule, SubmoduleWithBasis):
submodule = self.submodule(submodule, check=check,
unitriangular=True,
already_echelonized=already_echelonized)
return QuotientModuleWithBasis(submodule, category=category)
def tensor(*parents, **kwargs):
"""
Return the tensor product of the parents.
EXAMPLES::
sage: C = AlgebrasWithBasis(QQ)
sage: A = C.example(); A.rename("A")
sage: A.tensor(A,A)
A # A # A
sage: A.rename(None)
"""
constructor = kwargs.pop('constructor', tensor)
cat = constructor.category_from_parents(parents)
return parents[0].__class__.Tensor(parents, category=cat)
def cardinality(self):
"""
Return the cardinality of ``self``.
EXAMPLES::
sage: S = SymmetricGroupAlgebra(QQ, 4)
sage: S.cardinality()
+Infinity
sage: S = SymmetricGroupAlgebra(GF(2), 4) # not tested -- MRO bug trac #15475
sage: S.cardinality() # not tested -- MRO bug trac #15475
16777216
sage: S.cardinality().factor() # not tested -- MRO bug trac #15475
2^24
sage: E.<x,y> = ExteriorAlgebra(QQ)
sage: E.cardinality()
+Infinity
sage: E.<x,y> = ExteriorAlgebra(GF(3))
sage: E.cardinality()
81
sage: s = SymmetricFunctions(GF(2)).s()
sage: s.cardinality()
+Infinity
"""
from sage.rings.infinity import Infinity
if self.dimension() == Infinity:
return Infinity
return self.base_ring().cardinality() ** self.dimension()
def is_finite(self):
r"""
Return whether ``self`` is finite.
This is true if and only if ``self.basis().keys()`` and
``self.base_ring()`` are both finite.
EXAMPLES::
sage: GroupAlgebra(SymmetricGroup(2), IntegerModRing(10)).is_finite()
True
sage: GroupAlgebra(SymmetricGroup(2)).is_finite()
False
sage: GroupAlgebra(AbelianGroup(1), IntegerModRing(10)).is_finite()
False
"""
return (self.base_ring().is_finite() and self.group().is_finite())
def monomial(self, i):
"""
Return the basis element indexed by ``i``.
INPUT:
- ``i`` -- an element of the index set
EXAMPLES::