-
-
Notifications
You must be signed in to change notification settings - Fork 447
/
free_module_tensor.py
3339 lines (2788 loc) · 123 KB
/
free_module_tensor.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"""
Tensors on free modules
The class :class:`FreeModuleTensor` implements tensors on a free module `M`
of finite rank over a commutative ring. A *tensor of type* `(k,l)` on `M`
is a multilinear map:
.. MATH::
\underbrace{M^*\times\cdots\times M^*}_{k\ \; \mbox{times}}
\times \underbrace{M\times\cdots\times M}_{l\ \; \mbox{times}}
\longrightarrow R
where `R` is the commutative ring over which the free module `M` is defined
and `M^* = \mathrm{Hom}_R(M,R)` is the dual of `M`. The integer `k + l` is
called the *tensor rank*. The set `T^{(k,l)}(M)` of tensors of type `(k,l)`
on `M` is a free module of finite rank over `R`, described by the
class :class:`~sage.tensor.modules.tensor_free_module.TensorFreeModule`.
Various derived classes of :class:`FreeModuleTensor` are devoted to specific
tensors:
* :class:`~sage.tensor.modules.alternating_contr_tensor.AlternatingContrTensor`
for fully antisymmetric type-`(k, 0)` tensors *(alternating contravariant
tensors)*;
- :class:`~sage.tensor.modules.free_module_element.FiniteRankFreeModuleElement`
for elements of `M`, considered as type-`(1,0)` tensors thanks to the
canonical identification `M^{**}=M` (which holds since `M` is a free module
of finite rank);
* :class:`~sage.tensor.modules.free_module_alt_form.FreeModuleAltForm` for
fully antisymmetric type-`(0, l)` tensors *(alternating forms)*;
* :class:`~sage.tensor.modules.free_module_automorphism.FreeModuleAutomorphism`
for type-`(1,1)` tensors representing invertible endomorphisms.
Each of these classes is a Sage *element* class, the corresponding *parent*
class being:
* :class:`~sage.tensor.modules.tensor_free_module.TensorFreeModule` for
:class:`FreeModuleTensor`;
* :class:`~sage.tensor.modules.finite_rank_free_module.FiniteRankFreeModule`
for :class:`~sage.tensor.modules.free_module_element.FiniteRankFreeModuleElement`;
* :class:`~sage.tensor.modules.ext_pow_free_module.ExtPowerFreeModule` for
:class:`~sage.tensor.modules.alternating_contr_tensor.AlternatingContrTensor`;
* :class:`~sage.tensor.modules.ext_pow_free_module.ExtPowerDualFreeModule` for
:class:`~sage.tensor.modules.free_module_alt_form.FreeModuleAltForm`;
* :class:`~sage.tensor.modules.free_module_linear_group.FreeModuleLinearGroup`
for
:class:`~sage.tensor.modules.free_module_automorphism.FreeModuleAutomorphism`.
AUTHORS:
- Eric Gourgoulhon, Michal Bejger (2014-2015): initial version
- Michael Jung (2019): improve treatment of the zero element; add method
``copy_from``
REFERENCES:
- Chap. 21 of R. Godement : *Algebra* [God1968]_
- Chap. 12 of J. M. Lee: *Introduction to Smooth Manifolds* [Lee2013]_ (only
when the free module is a vector space)
- Chap. 2 of B. O'Neill: *Semi-Riemannian Geometry* [ONe1983]_
EXAMPLES:
A tensor of type `(1, 1)` on a rank-3 free module over `\ZZ`::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: t = M.tensor((1,1), name='t') ; t
Type-(1,1) tensor t on the Rank-3 free module M over the Integer Ring
sage: t.parent()
Free module of type-(1,1) tensors on the Rank-3 free module M
over the Integer Ring
sage: t.parent() is M.tensor_module(1,1)
True
sage: t in M.tensor_module(1,1)
True
Setting some component of the tensor in a given basis::
sage: e = M.basis('e') ; e
Basis (e_0,e_1,e_2) on the Rank-3 free module M over the Integer Ring
sage: t.set_comp(e)[0,0] = -3 # the component [0,0] w.r.t. basis e is set to -3
The unset components are assumed to be zero::
sage: t.comp(e)[:] # list of all components w.r.t. basis e
[-3 0 0]
[ 0 0 0]
[ 0 0 0]
sage: t.display(e) # displays the expansion of t on the basis e_i⊗e^j of T^(1,1)(M)
t = -3 e_0⊗e^0
The commands ``t.set_comp(e)`` and ``t.comp(e)`` can be abridged by providing
the basis as the first argument in the square brackets::
sage: t[e,0,0] = -3
sage: t[e,:]
[-3 0 0]
[ 0 0 0]
[ 0 0 0]
Actually, since ``e`` is ``M``'s default basis, the mention of ``e``
can be omitted::
sage: t[0,0] = -3
sage: t[:]
[-3 0 0]
[ 0 0 0]
[ 0 0 0]
For tensors of rank 2, the matrix of components w.r.t. a given basis is
obtained via the function ``matrix``::
sage: matrix(t.comp(e))
[-3 0 0]
[ 0 0 0]
[ 0 0 0]
sage: matrix(t.comp(e)).parent()
Full MatrixSpace of 3 by 3 dense matrices over Integer Ring
Tensor components can be modified (reset) at any time::
sage: t[0,0] = 0
sage: t[:]
[0 0 0]
[0 0 0]
[0 0 0]
Checking that ``t`` is zero::
sage: t.is_zero()
True
sage: t == 0
True
sage: t == M.tensor_module(1,1).zero() # the zero element of the module of all type-(1,1) tensors on M
True
The components are managed by the class
:class:`~sage.tensor.modules.comp.Components`::
sage: type(t.comp(e))
<class 'sage.tensor.modules.comp.Components'>
Only non-zero components are actually stored, in the dictionary :attr:`_comp`
of class :class:`~sage.tensor.modules.comp.Components`, whose keys are
the indices::
sage: t.comp(e)._comp
{}
sage: t.set_comp(e)[0,0] = -3 ; t.set_comp(e)[1,2] = 2
sage: t.comp(e)._comp # random output order (dictionary)
{(0, 0): -3, (1, 2): 2}
sage: t.display(e)
t = -3 e_0⊗e^0 + 2 e_1⊗e^2
Further tests of the comparison operator::
sage: t.is_zero()
False
sage: t == 0
False
sage: t == M.tensor_module(1,1).zero()
False
sage: t1 = t.copy()
sage: t1 == t
True
sage: t1[2,0] = 4
sage: t1 == t
False
As a multilinear map `M^* \times M \rightarrow \ZZ`, the type-`(1,1)`
tensor ``t`` acts on pairs formed by a linear form and a module element::
sage: a = M.linear_form(name='a') ; a[:] = (2, 1, -3) ; a
Linear form a on the Rank-3 free module M over the Integer Ring
sage: b = M([1,-6,2], name='b') ; b
Element b of the Rank-3 free module M over the Integer Ring
sage: t(a,b)
-2
"""
# *****************************************************************************
# Copyright (C) 2015 Eric Gourgoulhon <[email protected]>
# Copyright (C) 2015 Michal Bejger <[email protected]>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# https://www.gnu.org/licenses/
# *****************************************************************************
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Optional, Union
from sage.parallel.decorate import parallel
from sage.parallel.parallelism import Parallelism
from sage.rings.integer import Integer
from sage.structure.element import ModuleElementWithMutability
from sage.tensor.modules.comp import (
CompFullyAntiSym,
CompFullySym,
Components,
CompWithSym,
)
from sage.tensor.modules.tensor_with_indices import TensorWithIndices
if TYPE_CHECKING:
from sage.symbolic.expression import Expression
from sage.tensor.modules.finite_rank_free_module import FiniteRankFreeModule
from sage.tensor.modules.free_module_basis import FreeModuleBasis
from sage.manifolds.differentiable.metric import PseudoRiemannianMetric
from sage.manifolds.differentiable.poisson_tensor import PoissonTensorField
from sage.manifolds.differentiable.symplectic_form import SymplecticForm
class FreeModuleTensor(ModuleElementWithMutability):
r"""
Tensor over a free module of finite rank over a commutative ring.
This is a Sage *element* class, the corresponding *parent* class being
:class:`~sage.tensor.modules.tensor_free_module.TensorFreeModule`.
INPUT:
- ``fmodule`` -- free module `M` of finite rank over a commutative ring
`R`, as an instance of
:class:`~sage.tensor.modules.finite_rank_free_module.FiniteRankFreeModule`
- ``tensor_type`` -- pair ``(k, l)`` with ``k`` being the contravariant
rank and ``l`` the covariant rank
- ``name`` -- (default: ``None``) name given to the tensor
- ``latex_name`` -- (default: ``None``) LaTeX symbol to denote the tensor;
if none is provided, the LaTeX symbol is set to ``name``
- ``sym`` -- (default: ``None``) a symmetry or a list of symmetries among
the tensor arguments: each symmetry is described by a tuple containing
the positions of the involved arguments, with the convention
``position=0`` for the first argument. For instance:
* ``sym = (0,1)`` for a symmetry between the 1st and 2nd arguments;
* ``sym = [(0,2), (1,3,4)]`` for a symmetry between the 1st and 3rd
arguments and a symmetry between the 2nd, 4th and 5th arguments.
- ``antisym`` -- (default: ``None``) antisymmetry or list of antisymmetries
among the arguments, with the same convention as for ``sym``
- ``parent`` -- (default: ``None``) some specific parent (e.g. exterior
power for alternating forms); if ``None``, ``fmodule.tensor_module(k,l)``
is used
EXAMPLES:
A tensor of type `(1,1)` on a rank-3 free module over `\ZZ`::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: t = M.tensor((1,1), name='t') ; t
Type-(1,1) tensor t on the Rank-3 free module M over the Integer Ring
Tensors are *Element* objects whose parents are tensor free modules::
sage: t.parent()
Free module of type-(1,1) tensors on the
Rank-3 free module M over the Integer Ring
sage: t.parent() is M.tensor_module(1,1)
True
"""
_fmodule: FiniteRankFreeModule
def __init__(
self,
fmodule: FiniteRankFreeModule,
tensor_type,
name: Optional[str] = None,
latex_name: Optional[str] = None,
sym=None,
antisym=None,
parent=None,
):
r"""
TESTS::
sage: from sage.tensor.modules.free_module_tensor import FreeModuleTensor
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: t = FreeModuleTensor(M, (2,1), name='t', latex_name=r'\tau', sym=(0,1))
sage: t[e,0,0,0] = -3
sage: TestSuite(t).run(skip="_test_category") # see below
In the above test suite, _test_category fails because t is not an
instance of t.parent().category().element_class. Actually tensors
must be constructed via TensorFreeModule.element_class and
not by a direct call to FreeModuleTensor::
sage: t1 = M.tensor_module(2,1).element_class(M, (2,1), name='t',
....: latex_name=r'\tau',
....: sym=(0,1))
sage: t1[e,0,0,0] = -3
sage: TestSuite(t1).run()
"""
if parent is None:
parent = fmodule.tensor_module(*tensor_type)
ModuleElementWithMutability.__init__(self, parent)
self._fmodule = fmodule
self._tensor_type = tuple(tensor_type)
self._tensor_rank = self._tensor_type[0] + self._tensor_type[1]
self._is_zero = False # a priori, may be changed below or via
# method __bool__()
self._name = name
if latex_name is None:
self._latex_name = self._name
else:
self._latex_name = latex_name
self._components: Dict[FreeModuleBasis, Components] = {} # dict. of the sets of components on various
# bases, with the bases as keys (initially empty)
# Treatment of symmetry declarations:
self._sym, self._antisym = CompWithSym._canonicalize_sym_antisym(
self._tensor_rank, sym, antisym)
# Initialization of derived quantities:
FreeModuleTensor._init_derived(self)
####### Required methods for ModuleElement (beside arithmetic) #######
def __bool__(self):
r"""
Return ``True`` if ``self`` is nonzero and ``False`` otherwise.
This method is called by ``self.is_zero()``.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: e = M.basis('e')
sage: t = M.tensor((2,1))
sage: t.add_comp(e)
3-indices components w.r.t. Basis (e_0,e_1,e_2) on the
Rank-3 free module M over the Integer Ring
sage: bool(t) # uninitialized components are zero
False
sage: t == 0
True
sage: t[e,1,0,2] = 4 # setting a non-zero component in basis e
sage: t.display()
4 e_1⊗e_0⊗e^2
sage: bool(t)
True
sage: t == 0
False
sage: t[e,1,0,2] = 0
sage: t.display()
0
sage: bool(t)
False
sage: t == 0
True
"""
basis = self.pick_a_basis()
if not self._components[basis].is_zero():
self._is_zero = False
return True
self._is_zero = True
return False
##### End of required methods for ModuleElement (beside arithmetic) #####
def _repr_(self):
r"""
Return a string representation of ``self``.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: t = M.tensor((2,1), name='t')
sage: t
Type-(2,1) tensor t on the Rank-3 free module M over the Integer Ring
"""
# Special cases
if self._tensor_type == (0,2) and self._sym == ((0,1),):
description = "Symmetric bilinear form "
else:
# Generic case
description = "Type-({},{}) tensor".format(
self._tensor_type[0], self._tensor_type[1])
if self._name is not None:
description += " " + self._name
description += " on the {}".format(self._fmodule)
return description
def _latex_(self):
r"""
LaTeX representation of the object.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: t = M.tensor((2,1), name='t')
sage: t._latex_()
't'
sage: latex(t)
t
sage: t = M.tensor((2,1), name='t', latex_name=r'\tau')
sage: t._latex_()
'\\tau'
sage: latex(t)
\tau
sage: t = M.tensor((2,1)) # unnamed tensor
sage: t._latex_()
'\\mbox{Type-(2,1) tensor on the Rank-3 free module M over the Integer Ring}'
"""
if self._latex_name is None:
return r'\mbox{' + str(self) + r'}'
return self._latex_name
def _init_derived(self):
r"""
Initialize the derived quantities
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: t = M.tensor((2,1), name='t')
sage: t._init_derived()
"""
pass # no derived quantities
def _del_derived(self):
r"""
Delete the derived quantities
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: t = M.tensor((2,1), name='t')
sage: t._del_derived()
"""
pass # no derived quantities
#### Simple accessors ####
def tensor_type(self):
r"""
Return the tensor type of ``self``.
OUTPUT:
- pair ``(k, l)``, where ``k`` is the contravariant rank and ``l``
is the covariant rank
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3)
sage: M.an_element().tensor_type()
(1, 0)
sage: t = M.tensor((2,1))
sage: t.tensor_type()
(2, 1)
"""
return self._tensor_type
def tensor_rank(self):
r"""
Return the tensor rank of ``self``.
OUTPUT:
- integer ``k+l``, where ``k`` is the contravariant rank and ``l``
is the covariant rank
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3)
sage: M.an_element().tensor_rank()
1
sage: t = M.tensor((2,1))
sage: t.tensor_rank()
3
"""
return self._tensor_rank
def base_module(self):
r"""
Return the module on which ``self`` is defined.
OUTPUT:
- instance of :class:`FiniteRankFreeModule` representing the free
module on which the tensor is defined.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: M.an_element().base_module()
Rank-3 free module M over the Integer Ring
sage: t = M.tensor((2,1))
sage: t.base_module()
Rank-3 free module M over the Integer Ring
sage: t.base_module() is M
True
"""
return self._fmodule
def symmetries(self):
r"""
Print the list of symmetries and antisymmetries of ``self``.
EXAMPLES:
Various symmetries / antisymmetries for a rank-4 tensor::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: t = M.tensor((4,0), name='T') # no symmetry declared
sage: t.symmetries()
no symmetry; no antisymmetry
sage: t = M.tensor((4,0), name='T', sym=(0,1))
sage: t.symmetries()
symmetry: (0, 1); no antisymmetry
sage: t = M.tensor((4,0), name='T', sym=[(0,1), (2,3)])
sage: t.symmetries()
symmetries: [(0, 1), (2, 3)]; no antisymmetry
sage: t = M.tensor((4,0), name='T', sym=(0,1), antisym=(2,3))
sage: t.symmetries()
symmetry: (0, 1); antisymmetry: (2, 3)
"""
if len(self._sym) == 0:
s = "no symmetry; "
elif len(self._sym) == 1:
s = "symmetry: {}; ".format(self._sym[0])
else:
s = "symmetries: {}; ".format(list(self._sym))
if len(self._antisym) == 0:
a = "no antisymmetry"
elif len(self._antisym) == 1:
a = "antisymmetry: {}".format(self._antisym[0])
else:
a = "antisymmetries: {}".format(list(self._antisym))
print(s+a)
#### End of simple accessors #####
def _preparse_display(self, basis=None, format_spec=None):
r"""
Helper function for display (to be used in the derived classes
FreeModuleAltForm and AlternatingContrTensor as well)
TESTS::
sage: M = FiniteRankFreeModule(ZZ, 2, name='M')
sage: e = M.basis('e')
sage: f = M.basis('f')
sage: v = M([1,-2])
sage: v._preparse_display()
(Basis (e_0,e_1) on the Rank-2 free module M over the Integer Ring, None)
sage: v._preparse_display(f)
(Basis (f_0,f_1) on the Rank-2 free module M over the Integer Ring, None)
sage: v._preparse_display(e, 10)
(Basis (e_0,e_1) on the Rank-2 free module M over the Integer Ring, 10)
sage: v._preparse_display(format_spec=10)
(Basis (e_0,e_1) on the Rank-2 free module M over the Integer Ring, 10)
"""
if basis is None:
basis = self._fmodule._def_basis
return (basis, format_spec)
def display(self, basis=None, format_spec=None):
r"""
Display ``self`` in terms of its expansion w.r.t. a given module basis.
The expansion is actually performed onto tensor products of elements
of the given basis and of elements of its dual basis (see examples
below).
The output is either text-formatted (console mode) or LaTeX-formatted
(notebook mode).
INPUT:
- ``basis`` -- (default: ``None``) basis of the free module with
respect to which the tensor is expanded; if none is provided,
the module's default basis is assumed
- ``format_spec`` -- (default: ``None``) format specification passed
to ``self._fmodule._output_formatter`` to format the output
EXAMPLES:
Display of a module element (type-`(1,0)` tensor)::
sage: M = FiniteRankFreeModule(QQ, 2, name='M', start_index=1)
sage: e = M.basis('e') ; e
Basis (e_1,e_2) on the 2-dimensional vector space M over the
Rational Field
sage: v = M([1/3,-2], name='v')
sage: v.display(e)
v = 1/3 e_1 - 2 e_2
sage: v.display() # a shortcut since e is M's default basis
v = 1/3 e_1 - 2 e_2
sage: latex(v.display()) # display in the notebook
v = \frac{1}{3} e_{1} -2 e_{2}
A shortcut is ``disp()``::
sage: v.disp()
v = 1/3 e_1 - 2 e_2
Display of a linear form (type-`(0,1)` tensor)::
sage: de = e.dual_basis() ; de
Dual basis (e^1,e^2) on the 2-dimensional vector space M over the
Rational Field
sage: w = - 3/4 * de[1] + de[2] ; w
Linear form on the 2-dimensional vector space M over the Rational
Field
sage: w.set_name('w', latex_name='\\omega')
sage: w.display()
w = -3/4 e^1 + e^2
sage: latex(w.display()) # display in the notebook
\omega = -\frac{3}{4} e^{1} +e^{2}
Display of a type-`(1,1)` tensor::
sage: t = v*w ; t # the type-(1,1) is formed as the tensor product of v by w
Type-(1,1) tensor v⊗w on the 2-dimensional vector space M over the
Rational Field
sage: t.display()
v⊗w = -1/4 e_1⊗e^1 + 1/3 e_1⊗e^2 + 3/2 e_2⊗e^1 - 2 e_2⊗e^2
sage: latex(t.display()) # display in the notebook
v\otimes \omega = -\frac{1}{4} e_{1}\otimes e^{1} +
\frac{1}{3} e_{1}\otimes e^{2} + \frac{3}{2} e_{2}\otimes e^{1}
-2 e_{2}\otimes e^{2}
Display in a basis which is not the default one::
sage: a = M.automorphism(matrix=[[1,2],[3,4]], basis=e)
sage: f = e.new_basis(a, 'f')
sage: v.display(f) # the components w.r.t basis f are first computed via the change-of-basis formula defined by a
v = -8/3 f_1 + 3/2 f_2
sage: w.display(f)
w = 9/4 f^1 + 5/2 f^2
sage: t.display(f)
v⊗w = -6 f_1⊗f^1 - 20/3 f_1⊗f^2 + 27/8 f_2⊗f^1 + 15/4 f_2⊗f^2
Parallel computation::
sage: Parallelism().set('tensor', nproc=2)
sage: t2 = v*w
sage: t2.display(f)
v⊗w = -6 f_1⊗f^1 - 20/3 f_1⊗f^2 + 27/8 f_2⊗f^1 + 15/4 f_2⊗f^2
sage: t2[f,:] == t[f,:] # check of the parallel computation
True
sage: Parallelism().set('tensor', nproc=1) # switch off parallelization
The output format can be set via the argument ``output_formatter``
passed at the module construction::
sage: N = FiniteRankFreeModule(QQ, 2, name='N', start_index=1,
....: output_formatter=Rational.numerical_approx)
sage: e = N.basis('e')
sage: v = N([1/3,-2], name='v')
sage: v.display() # default format (53 bits of precision)
v = 0.333333333333333 e_1 - 2.00000000000000 e_2
sage: latex(v.display())
v = 0.333333333333333 e_{1} -2.00000000000000 e_{2}
The output format is then controlled by the argument ``format_spec`` of
the method :meth:`display`::
sage: v.display(format_spec=10) # 10 bits of precision
v = 0.33 e_1 - 2.0 e_2
Check that the bug reported in :issue:`22520` is fixed::
sage: # needs sage.symbolic
sage: M = FiniteRankFreeModule(SR, 3, name='M')
sage: e = M.basis('e')
sage: t = SR.var('t', domain='real')
sage: (t*e[0]).display()
t e_0
"""
from sage.misc.latex import latex
from sage.typeset.unicode_characters import unicode_otimes
from .format_utilities import is_atomic, FormattedExpansion
basis, format_spec = self._preparse_display(basis=basis,
format_spec=format_spec)
cobasis = basis.dual_basis()
comp = self.comp(basis)
terms_txt = []
terms_latex = []
n_con = self._tensor_type[0]
for ind in comp.index_generator():
ind_arg = ind + (format_spec,)
coef = comp[ind_arg]
# Check whether the coefficient is zero, preferably via
# the fast method is_trivial_zero():
if hasattr(coef, 'is_trivial_zero'):
zero_coef = coef.is_trivial_zero()
else:
zero_coef = coef == 0
if not zero_coef:
bases_txt = []
bases_latex = []
for k in range(n_con):
bases_txt.append(basis[ind[k]]._name)
bases_latex.append(latex(basis[ind[k]]))
for k in range(n_con, self._tensor_rank):
bases_txt.append(cobasis[ind[k]]._name)
bases_latex.append(latex(cobasis[ind[k]]))
basis_term_txt = unicode_otimes.join(bases_txt)
basis_term_latex = r'\otimes '.join(bases_latex)
coef_txt = repr(coef)
if coef_txt == '1':
terms_txt.append(basis_term_txt)
terms_latex.append(basis_term_latex)
elif coef_txt == '-1':
terms_txt.append('-' + basis_term_txt)
terms_latex.append('-' + basis_term_latex)
else:
coef_latex = latex(coef)
if is_atomic(coef_txt):
terms_txt.append(coef_txt + ' ' + basis_term_txt)
else:
terms_txt.append('(' + coef_txt + ') ' +
basis_term_txt)
if is_atomic(coef_latex):
terms_latex.append(coef_latex + basis_term_latex)
else:
terms_latex.append(r'\left(' + coef_latex +
r'\right)' + basis_term_latex)
if terms_txt == []:
expansion_txt = '0'
else:
expansion_txt = terms_txt[0]
for term in terms_txt[1:]:
if term[0] == '-':
expansion_txt += ' - ' + term[1:]
else:
expansion_txt += ' + ' + term
if terms_latex == []:
expansion_latex = '0'
else:
expansion_latex = terms_latex[0]
for term in terms_latex[1:]:
if term[0] == '-':
expansion_latex += term
else:
expansion_latex += '+' + term
if self._name is None:
resu_txt = expansion_txt
else:
resu_txt = self._name + ' = ' + expansion_txt
if self._latex_name is None:
resu_latex = expansion_latex
else:
resu_latex = latex(self) + ' = ' + expansion_latex
return FormattedExpansion(resu_txt, resu_latex)
disp = display
def display_comp(self, basis=None, format_spec=None, symbol=None,
latex_symbol=None, index_labels=None,
index_latex_labels=None, only_nonzero=True,
only_nonredundant=False):
r"""
Display the tensor components with respect to a given module
basis, one per line.
The output is either text-formatted (console mode) or LaTeX-formatted
(notebook mode).
INPUT:
- ``basis`` -- (default: ``None``) basis of the free module with
respect to which the tensor components are defined; if ``None``,
the module's default basis is assumed
- ``format_spec`` -- (default: ``None``) format specification passed
to ``self._fmodule._output_formatter`` to format the output
- ``symbol`` -- (default: ``None``) string (typically a single letter)
specifying the symbol for the components; if ``None``, the tensor
name is used if it has been set, otherwise ``'X'`` is used
- ``latex_symbol`` -- (default: ``None``) string specifying the LaTeX
symbol for the components; if ``None``, the tensor LaTeX name
is used if it has been set, otherwise ``'X'`` is used
- ``index_labels`` -- (default: ``None``) list of strings representing
the labels of each of the individual indices; if ``None``, integer
labels are used
- ``index_latex_labels`` -- (default: ``None``) list of strings
representing the LaTeX labels of each of the individual indices; if
``None``, integers labels are used
- ``only_nonzero`` -- (default: ``True``) boolean; if ``True``, only
nonzero components are displayed
- ``only_nonredundant`` -- (default: ``False``) boolean; if ``True``,
only nonredundant components are displayed in case of symmetries
EXAMPLES:
Display of the components of a type-`(2,1)` tensor on a rank 2
vector space over `\QQ`::
sage: FiniteRankFreeModule._clear_cache_() # for doctests only
sage: M = FiniteRankFreeModule(QQ, 2, name='M', start_index=1)
sage: e = M.basis('e')
sage: t = M.tensor((2,1), name='T', sym=(0,1))
sage: t[1,2,1], t[1,2,2], t[2,2,2] = 2/3, -1/4, 3
sage: t.display()
T = 2/3 e_1⊗e_2⊗e^1 - 1/4 e_1⊗e_2⊗e^2 + 2/3 e_2⊗e_1⊗e^1
- 1/4 e_2⊗e_1⊗e^2 + 3 e_2⊗e_2⊗e^2
sage: t.display_comp()
T^12_1 = 2/3
T^12_2 = -1/4
T^21_1 = 2/3
T^21_2 = -1/4
T^22_2 = 3
The LaTeX output for the notebook::
sage: latex(t.display_comp())
\begin{array}{lcl} {T}_{\phantom{\, 1}\phantom{\, 2}\,1}^{\,1\,2\phantom{\, 1}}
& = & \frac{2}{3} \\ {T}_{\phantom{\, 1}\phantom{\, 2}\,2}^{\,1\,2\phantom{\, 2}}
& = & -\frac{1}{4} \\ {T}_{\phantom{\, 2}\phantom{\, 1}\,1}^{\,2\,1\phantom{\, 1}}
& = & \frac{2}{3} \\ {T}_{\phantom{\, 2}\phantom{\, 1}\,2}^{\,2\,1\phantom{\, 2}}
& = & -\frac{1}{4} \\ {T}_{\phantom{\, 2}\phantom{\, 2}\,2}^{\,2\,2\phantom{\, 2}}
& = & 3 \end{array}
By default, only the non-vanishing components are displayed; to see
all the components, the argument ``only_nonzero`` must be set to
``False``::
sage: t.display_comp(only_nonzero=False)
T^11_1 = 0
T^11_2 = 0
T^12_1 = 2/3
T^12_2 = -1/4
T^21_1 = 2/3
T^21_2 = -1/4
T^22_1 = 0
T^22_2 = 3
``t`` being symmetric w.r.t. to its first two indices, one may ask to
skip the components that can be deduced by symmetry::
sage: t.display_comp(only_nonredundant=True)
T^12_1 = 2/3
T^12_2 = -1/4
T^22_2 = 3
The index symbols can be customized::
sage: t.display_comp(index_labels=['x', 'y'])
T^xy_x = 2/3
T^xy_y = -1/4
T^yx_x = 2/3
T^yx_y = -1/4
T^yy_y = 3
Display of the components w.r.t. a basis different from the
default one::
sage: f = M.basis('f', from_family=(-e[1]+e[2], e[1]+e[2]))
sage: t.display_comp(basis=f)
T^11_1 = 29/24
T^11_2 = 13/24
T^12_1 = 3/4
T^12_2 = 3/4
T^21_1 = 3/4
T^21_2 = 3/4
T^22_1 = 7/24
T^22_2 = 23/24
"""
if basis is None:
basis = self._fmodule._def_basis
if symbol is None:
if self._name is not None:
symbol = self._name
else:
symbol = 'X'
if latex_symbol is None:
if self._latex_name is not None:
latex_symbol = r'{' + self._latex_name + r'}'
else:
latex_symbol = 'X'
index_positions = self._tensor_type[0]*'u' + self._tensor_type[1]*'d'
return self.comp(basis).display(symbol,
latex_symbol=latex_symbol,
index_positions=index_positions,
index_labels=index_labels,
index_latex_labels=index_latex_labels,
format_spec=format_spec,
only_nonzero=only_nonzero,
only_nonredundant=only_nonredundant)
def set_name(self, name: Optional[str] = None, latex_name: Optional[str] = None):
r"""
Set (or change) the text name and LaTeX name of ``self``.
INPUT:
- ``name`` -- (default: ``None``) string; name given to the tensor
- ``latex_name`` -- (default: ``None``) string; LaTeX symbol to denote
the tensor; if None while ``name`` is provided, the LaTeX symbol
is set to ``name``
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: t = M.tensor((2,1)) ; t
Type-(2,1) tensor on the Rank-3 free module M over the Integer Ring
sage: t.set_name('t') ; t
Type-(2,1) tensor t on the Rank-3 free module M over the Integer Ring
sage: latex(t)
t
sage: t.set_name(latex_name=r'\tau') ; t
Type-(2,1) tensor t on the Rank-3 free module M over the Integer Ring
sage: latex(t)
\tau
"""
if name is not None:
self._name = name
if latex_name is None:
self._latex_name = self._name
if latex_name is not None:
self._latex_name = latex_name
def _new_instance(self):
r"""
Create a tensor of the same tensor type and with the same symmetries
as ``self``.
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: t = M.tensor((2,1), name='t')
sage: t._new_instance()
Type-(2,1) tensor on the Rank-3 free module M over the Integer Ring
sage: t._new_instance().parent() is t.parent()
True
"""
return self.__class__(self._fmodule, self._tensor_type, sym=self._sym,
antisym=self._antisym)
def _new_comp(self, basis):
r"""
Create some (uninitialized) components of ``self`` w.r.t a given
module basis.
This method, to be called by :meth:`comp`, must be redefined by derived
classes to adapt the output to the relevant subclass of
:class:`~sage.tensor.modules.comp.Components`.
INPUT:
- ``basis`` -- basis of the free module on which ``self`` is defined
OUTPUT:
- an instance of :class:`~sage.tensor.modules.comp.Components`
(or of one of its subclasses)
EXAMPLES::
sage: M = FiniteRankFreeModule(ZZ, 3, name='M')
sage: t = M.tensor((2,1), name='t')
sage: e = M.basis('e')
sage: t._new_comp(e)
3-indices components w.r.t. Basis (e_0,e_1,e_2) on the
Rank-3 free module M over the Integer Ring
sage: a = M.tensor((2,1), name='a', sym=(0,1))
sage: a._new_comp(e)
3-indices components w.r.t. Basis (e_0,e_1,e_2) on the
Rank-3 free module M over the Integer Ring,
with symmetry on the index positions (0, 1)
"""
fmodule = self._fmodule # the base free module
if not self._sym and not self._antisym:
return Components(fmodule._ring, basis, self._tensor_rank,
start_index=fmodule._sindex,
output_formatter=fmodule._output_formatter)
for isym in self._sym:
if len(isym) == self._tensor_rank:
return CompFullySym(fmodule._ring, basis, self._tensor_rank,
start_index=fmodule._sindex,
output_formatter=fmodule._output_formatter)
for isym in self._antisym:
if len(isym) == self._tensor_rank:
return CompFullyAntiSym(fmodule._ring, basis, self._tensor_rank,
start_index=fmodule._sindex,
output_formatter=fmodule._output_formatter)