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
/
comp.py
5651 lines (4901 loc) · 208 KB
/
comp.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"""
Components as indexed sets of ring elements
The class :class:`Components` is a technical class to take in charge the
storage and manipulation of **indexed elements of a commutative ring** that
represent the components of some "mathematical entity" with respect to some
"frame". Examples of *entity/frame* are *vector/vector-space basis* or
*vector field/vector frame on some manifold*. More generally, the components
can be those of a tensor on a free module or those of a tensor field on a
manifold. They can also be non-tensorial quantities, like connection
coefficients or structure coefficients of a vector frame.
The individual components are assumed to belong to a given commutative ring
and are labelled by *indices*, which are *tuples of integers*.
The following operations are implemented on components with respect
to a given frame:
* arithmetics (addition, subtraction, multiplication by a ring element)
* handling of symmetries or antisymmetries on the indices
* symmetrization and antisymmetrization
* tensor product
* contraction
Various subclasses of class :class:`Components` are
* :class:`CompWithSym` for components with symmetries or antisymmetries w.r.t.
index permutations
* :class:`CompFullySym` for fully symmetric components w.r.t. index
permutations
* :class:`KroneckerDelta` for the Kronecker delta symbol
* :class:`CompFullyAntiSym` for fully antisymmetric components w.r.t. index
permutations
AUTHORS:
- Eric Gourgoulhon, Michal Bejger (2014-2015): initial version
- Joris Vankerschaver (2010): for the idea of storing only the non-zero
components as dictionaries, whose keys are the component indices (implemented
in the old class ``DifferentialForm``; see :trac:`24444`)
- Marco Mancini (2015) : parallelization of some computations
EXAMPLES:
Set of components with 2 indices on a 3-dimensional vector space, the frame
being some basis of the vector space::
sage: from sage.tensor.modules.comp import Components
sage: V = VectorSpace(QQ,3)
sage: basis = V.basis() ; basis
[
(1, 0, 0),
(0, 1, 0),
(0, 0, 1)
]
sage: c = Components(QQ, basis, 2) ; c
2-indices components w.r.t. [
(1, 0, 0),
(0, 1, 0),
(0, 0, 1)
]
Actually, the frame can be any object that has some length, i.e. on which
the function :func:`len()` can be called::
sage: basis1 = V.gens() ; basis1
((1, 0, 0), (0, 1, 0), (0, 0, 1))
sage: c1 = Components(QQ, basis1, 2) ; c1
2-indices components w.r.t. ((1, 0, 0), (0, 1, 0), (0, 0, 1))
sage: basis2 = ['a', 'b' , 'c']
sage: c2 = Components(QQ, basis2, 2) ; c2
2-indices components w.r.t. ['a', 'b', 'c']
A just created set of components is initialized to zero::
sage: c.is_zero()
True
sage: c == 0
True
This can also be checked on the list of components, which is returned by
the operator ``[:]``::
sage: c[:]
[0 0 0]
[0 0 0]
[0 0 0]
Individual components are accessed by providing their indices inside
square brackets::
sage: c[1,2] = -3
sage: c[:]
[ 0 0 0]
[ 0 0 -3]
[ 0 0 0]
sage: v = Components(QQ, basis, 1)
sage: v[:]
[0, 0, 0]
sage: v[0]
0
sage: v[:] = (-1,3,2)
sage: v[:]
[-1, 3, 2]
sage: v[0]
-1
Sets of components with 2 indices can be converted into a matrix::
sage: matrix(c)
[ 0 0 0]
[ 0 0 -3]
[ 0 0 0]
sage: matrix(c).parent()
Full MatrixSpace of 3 by 3 dense matrices over Rational Field
By default, the indices range from `0` to `n-1`, where `n` is the length
of the frame. This can be changed via the argument ``start_index`` in
the :class:`Components` constructor::
sage: v1 = Components(QQ, basis, 1, start_index=1)
sage: v1[:]
[0, 0, 0]
sage: v1[0]
Traceback (most recent call last):
...
IndexError: index out of range: 0 not in [1, 3]
sage: v1[1]
0
sage: v1[:] = v[:] # list copy of all components
sage: v1[:]
[-1, 3, 2]
sage: v1[1], v1[2], v1[3]
(-1, 3, 2)
sage: v[0], v[1], v[2]
(-1, 3, 2)
If some formatter function or unbound method is provided via the argument
``output_formatter`` in the :class:`Components` constructor, it is used to
change the output of the access operator ``[...]``::
sage: a = Components(QQ, basis, 2, output_formatter=Rational.numerical_approx)
sage: a[1,2] = 1/3
sage: a[1,2]
0.333333333333333
The format can be passed to the formatter as the last argument of the
access operator ``[...]``::
sage: a[1,2,10] # here the format is 10, for 10 bits of precision
0.33
sage: a[1,2,100]
0.33333333333333333333333333333
The raw (unformatted) components are then accessed by the double bracket
operator::
sage: a[[1,2]]
1/3
For sets of components declared without any output formatter, there is no
difference between ``[...]`` and ``[[...]]``::
sage: c[1,2] = 1/3
sage: c[1,2], c[[1,2]]
(1/3, 1/3)
The formatter is also used for the complete list of components::
sage: a[:]
[0.000000000000000 0.000000000000000 0.000000000000000]
[0.000000000000000 0.000000000000000 0.333333333333333]
[0.000000000000000 0.000000000000000 0.000000000000000]
sage: a[:,10] # with a format different from the default one (53 bits)
[0.00 0.00 0.00]
[0.00 0.00 0.33]
[0.00 0.00 0.00]
The complete list of components in raw form can be recovered by the double
bracket operator, replacing ``:`` by ``slice(None)`` (since ``a[[:]]``
generates a Python syntax error)::
sage: a[[slice(None)]]
[ 0 0 0]
[ 0 0 1/3]
[ 0 0 0]
Another example of formatter: the Python built-in function :func:`str`
to generate string outputs::
sage: b = Components(QQ, V.basis(), 1, output_formatter=str)
sage: b[:] = (1, 0, -4)
sage: b[:]
['1', '0', '-4']
For such a formatter, 2-indices components are no longer displayed as a
matrix::
sage: b = Components(QQ, basis, 2, output_formatter=str)
sage: b[0,1] = 1/3
sage: b[:]
[['0', '1/3', '0'], ['0', '0', '0'], ['0', '0', '0']]
But unformatted outputs still are::
sage: b[[slice(None)]]
[ 0 1/3 0]
[ 0 0 0]
[ 0 0 0]
Internally, the components are stored as a dictionary (:attr:`_comp`) whose
keys are the indices; only the non-zero components are stored::
sage: a[:]
[0.000000000000000 0.000000000000000 0.000000000000000]
[0.000000000000000 0.000000000000000 0.333333333333333]
[0.000000000000000 0.000000000000000 0.000000000000000]
sage: a._comp
{(1, 2): 1/3}
sage: v[:] = (-1, 0, 3)
sage: v._comp # random output order of the component dictionary
{(0,): -1, (2,): 3}
In case of symmetries, only non-redundant components are stored::
sage: from sage.tensor.modules.comp import CompFullyAntiSym
sage: c = CompFullyAntiSym(QQ, basis, 2)
sage: c[0,1] = 3
sage: c[:]
[ 0 3 0]
[-3 0 0]
[ 0 0 0]
sage: c._comp
{(0, 1): 3}
"""
# *****************************************************************************
# Copyright (C) 2015 Eric Gourgoulhon <eric.gourgoulhon@obspm.fr>
# Copyright (C) 2015 Michal Bejger <bejger@camk.edu.pl>
# Copyright (C) 2015 Marco Mancini <marco.mancini@obspm.fr>
#
# 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.
# http://www.gnu.org/licenses/
#******************************************************************************
from sage.structure.sage_object import SageObject
from sage.rings.integer import Integer
from sage.parallel.decorate import parallel
from sage.parallel.parallelism import Parallelism
from operator import itemgetter
class Components(SageObject):
r"""
Indexed set of ring elements forming some components with respect
to a given "frame".
The "frame" can be a basis of some vector space or a vector frame on some
manifold (i.e. a field of bases).
The stored quantities can be tensor components or non-tensorial quantities,
such as connection coefficients or structure coefficients. The symmetries
over some indices are dealt by subclasses of the class :class:`Components`.
INPUT:
- ``ring`` -- commutative ring in which each component takes its value
- ``frame`` -- frame with respect to which the components are defined;
whatever type ``frame`` is, it should have a method ``__len__()``
implemented, so that ``len(frame)`` returns the dimension, i.e. the size
of a single index range
- ``nb_indices`` -- number of integer indices labeling the components
- ``start_index`` -- (default: 0) first value of a single index;
accordingly a component index i must obey
``start_index <= i <= start_index + dim - 1``, where ``dim = len(frame)``.
- ``output_formatter`` -- (default: ``None``) function or unbound
method called to format the output of the component access
operator ``[...]`` (method __getitem__); ``output_formatter`` must take
1 or 2 arguments: the 1st argument must be an element of ``ring`` and
the second one, if any, some format specification.
EXAMPLES:
Set of components with 2 indices on a 3-dimensional vector space, the frame
being some basis of the vector space::
sage: from sage.tensor.modules.comp import Components
sage: V = VectorSpace(QQ,3)
sage: basis = V.basis() ; basis
[
(1, 0, 0),
(0, 1, 0),
(0, 0, 1)
]
sage: c = Components(QQ, basis, 2) ; c
2-indices components w.r.t. [
(1, 0, 0),
(0, 1, 0),
(0, 0, 1)
]
Actually, the frame can be any object that has some length, i.e. on which
the function :func:`len()` can be called::
sage: basis1 = V.gens() ; basis1
((1, 0, 0), (0, 1, 0), (0, 0, 1))
sage: c1 = Components(QQ, basis1, 2) ; c1
2-indices components w.r.t. ((1, 0, 0), (0, 1, 0), (0, 0, 1))
sage: basis2 = ['a', 'b' , 'c']
sage: c2 = Components(QQ, basis2, 2) ; c2
2-indices components w.r.t. ['a', 'b', 'c']
By default, the indices range from `0` to `n-1`, where `n` is the length
of the frame. This can be changed via the argument ``start_index``::
sage: c1 = Components(QQ, basis, 2, start_index=1)
sage: c1[0,1]
Traceback (most recent call last):
...
IndexError: index out of range: 0 not in [1, 3]
sage: c[0,1] # for c, the index 0 is OK
0
sage: c[0,1] = -3
sage: c1[:] = c[:] # list copy of all components
sage: c1[1,2] # (1,2) = (0,1) shifted by 1
-3
If some formatter function or unbound method is provided via the argument
``output_formatter``, it is used to change the output of the access
operator ``[...]``::
sage: a = Components(QQ, basis, 2, output_formatter=Rational.numerical_approx)
sage: a[1,2] = 1/3
sage: a[1,2]
0.333333333333333
The format can be passed to the formatter as the last argument of the
access operator ``[...]``::
sage: a[1,2,10] # here the format is 10, for 10 bits of precision
0.33
sage: a[1,2,100]
0.33333333333333333333333333333
The raw (unformatted) components are then accessed by the double bracket
operator::
sage: a[[1,2]]
1/3
For sets of components declared without any output formatter, there is no
difference between ``[...]`` and ``[[...]]``::
sage: c[1,2] = 1/3
sage: c[1,2], c[[1,2]]
(1/3, 1/3)
The formatter is also used for the complete list of components::
sage: a[:]
[0.000000000000000 0.000000000000000 0.000000000000000]
[0.000000000000000 0.000000000000000 0.333333333333333]
[0.000000000000000 0.000000000000000 0.000000000000000]
sage: a[:,10] # with a format different from the default one (53 bits)
[0.00 0.00 0.00]
[0.00 0.00 0.33]
[0.00 0.00 0.00]
The complete list of components in raw form can be recovered by the double
bracket operator, replacing ``:`` by ``slice(None)`` (since ``a[[:]]``
generates a Python syntax error)::
sage: a[[slice(None)]]
[ 0 0 0]
[ 0 0 1/3]
[ 0 0 0]
Another example of formatter: the Python built-in function :func:`str`
to generate string outputs::
sage: b = Components(QQ, V.basis(), 1, output_formatter=str)
sage: b[:] = (1, 0, -4)
sage: b[:]
['1', '0', '-4']
For such a formatter, 2-indices components are no longer displayed as a
matrix::
sage: b = Components(QQ, basis, 2, output_formatter=str)
sage: b[0,1] = 1/3
sage: b[:]
[['0', '1/3', '0'], ['0', '0', '0'], ['0', '0', '0']]
But unformatted outputs still are::
sage: b[[slice(None)]]
[ 0 1/3 0]
[ 0 0 0]
[ 0 0 0]
Internally, the components are stored as a dictionary (:attr:`_comp`) whose
keys are the indices; only the non-zero components are stored::
sage: a[:]
[0.000000000000000 0.000000000000000 0.000000000000000]
[0.000000000000000 0.000000000000000 0.333333333333333]
[0.000000000000000 0.000000000000000 0.000000000000000]
sage: a._comp
{(1, 2): 1/3}
sage: v = Components(QQ, basis, 1)
sage: v[:] = (-1, 0, 3)
sage: v._comp # random output order of the component dictionary
{(0,): -1, (2,): 3}
.. RUBRIC:: ARITHMETIC EXAMPLES:
Unary plus operator::
sage: a = Components(QQ, basis, 1)
sage: a[:] = (-1, 0, 3)
sage: s = +a ; s[:]
[-1, 0, 3]
sage: +a == a
True
Unary minus operator::
sage: s = -a ; s[:]
[1, 0, -3]
Addition::
sage: b = Components(QQ, basis, 1)
sage: b[:] = (2, 1, 4)
sage: s = a + b ; s[:]
[1, 1, 7]
sage: a + b == b + a
True
sage: a + (-a) == 0
True
Subtraction::
sage: s = a - b ; s[:]
[-3, -1, -1]
sage: s + b == a
True
sage: a - b == - (b - a)
True
Multiplication by a scalar::
sage: s = 2*a ; s[:]
[-2, 0, 6]
Division by a scalar::
sage: s = a/2 ; s[:]
[-1/2, 0, 3/2]
sage: 2*(a/2) == a
True
Tensor product (by means of the operator ``*``)::
sage: c = a*b ; c
2-indices components w.r.t. [
(1, 0, 0),
(0, 1, 0),
(0, 0, 1)
]
sage: a[:], b[:]
([-1, 0, 3], [2, 1, 4])
sage: c[:]
[-2 -1 -4]
[ 0 0 0]
[ 6 3 12]
sage: d = c*a ; d
3-indices components w.r.t. [
(1, 0, 0),
(0, 1, 0),
(0, 0, 1)
]
sage: d[:]
[[[2, 0, -6], [1, 0, -3], [4, 0, -12]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[-6, 0, 18], [-3, 0, 9], [-12, 0, 36]]]
sage: d[0,1,2] == a[0]*b[1]*a[2]
True
"""
def __init__(self, ring, frame, nb_indices, start_index=0,
output_formatter=None):
r"""
TESTS::
sage: from sage.tensor.modules.comp import Components
sage: Components(ZZ, [1,2,3], 2)
2-indices components w.r.t. [1, 2, 3]
"""
# For efficiency, no test is performed regarding the type and range of
# the arguments:
self._ring = ring
self._frame = frame
self._nid = nb_indices
self._dim = len(frame)
self._sindex = start_index
self._output_formatter = output_formatter
self._comp = {} # the dictionary of components, with the index tuples
# as keys
def _repr_(self):
r"""
Return a string representation of ``self``.
EXAMPLES::
sage: from sage.tensor.modules.comp import Components
sage: c = Components(ZZ, [1,2,3], 2)
sage: c._repr_()
'2-indices components w.r.t. [1, 2, 3]'
"""
description = str(self._nid)
if self._nid == 1:
description += "-index"
else:
description += "-indices"
description += " components w.r.t. " + str(self._frame)
return description
def _new_instance(self):
r"""
Creates a :class:`Components` instance of the same number of indices
and w.r.t. the same frame.
This method must be redefined by derived classes of
:class:`Components`.
EXAMPLES::
sage: from sage.tensor.modules.comp import Components
sage: c = Components(ZZ, [1,2,3], 2)
sage: c._new_instance()
2-indices components w.r.t. [1, 2, 3]
"""
return Components(self._ring, self._frame, self._nid, self._sindex,
self._output_formatter)
def copy(self):
r"""
Return an exact copy of ``self``.
EXAMPLES:
Copy of a set of components with a single index::
sage: from sage.tensor.modules.comp import Components
sage: V = VectorSpace(QQ,3)
sage: a = Components(QQ, V.basis(), 1)
sage: a[:] = -2, 1, 5
sage: b = a.copy() ; b
1-index components w.r.t. [
(1, 0, 0),
(0, 1, 0),
(0, 0, 1)
]
sage: b[:]
[-2, 1, 5]
sage: b == a
True
sage: b is a # b is a distinct object
False
"""
result = self._new_instance()
for ind, val in self._comp.items():
if isinstance(val, SageObject) and hasattr(val, 'copy'):
result._comp[ind] = val.copy()
else:
result._comp[ind] = val
return result
def _del_zeros(self):
r"""
Deletes all the zeros in the dictionary :attr:`_comp`
NB: The use case of this method must be rare because zeros are not
stored in :attr:`_comp`.
EXAMPLES::
sage: from sage.tensor.modules.comp import Components
sage: c = Components(ZZ, [1,2,3], 2)
sage: c._comp = {(0,1): 3, (0,2): 0, (1,2): -5, (2,2): 0} # enforcing zero storage
sage: c._del_zeros()
sage: c._comp
{(0, 1): 3, (1, 2): -5}
"""
# The zeros are first searched; they are deleted in a second stage, to
# avoid changing the dictionary while it is read
zeros = []
for ind, value in self._comp.items():
if value == 0:
zeros.append(ind)
for ind in zeros:
del self._comp[ind]
def _check_indices(self, indices):
r"""
Check the validity of a list of indices and returns a tuple from it
INPUT:
- ``indices`` -- list of indices (possibly a single integer if
self is a 1-index object)
OUTPUT:
- a tuple containing valid indices
EXAMPLES::
sage: from sage.tensor.modules.comp import Components
sage: c = Components(ZZ, [1,2,3], 2)
sage: c._check_indices((0,1))
(0, 1)
sage: c._check_indices([0,1])
(0, 1)
sage: c._check_indices([2,1])
(2, 1)
sage: c._check_indices([2,3])
Traceback (most recent call last):
...
IndexError: index out of range: 3 not in [0, 2]
sage: c._check_indices(1)
Traceback (most recent call last):
...
ValueError: wrong number of indices: 2 expected, while 1 are provided
sage: c._check_indices([1,2,3])
Traceback (most recent call last):
...
ValueError: wrong number of indices: 2 expected, while 3 are provided
"""
if isinstance(indices, (int, Integer)):
ind = (indices,)
else:
ind = tuple(indices)
if len(ind) != self._nid:
raise ValueError(("wrong number of indices: {} expected,"
" while {} are provided").format(self._nid, len(ind)))
si = self._sindex
imax = self._dim - 1 + si
for k in range(self._nid):
i = ind[k]
if i < si or i > imax:
raise IndexError("index out of range: " +
"{} not in [{}, {}]".format(i, si, imax))
return ind
def __getitem__(self, args):
r"""
Returns the component corresponding to the given indices.
INPUT:
- ``args`` -- list of indices (possibly a single integer if
self is a 1-index object) or the character ``:`` for the full list
of components
OUTPUT:
- the component corresponding to ``args`` or, if ``args`` = ``:``,
the full list of components, in the form ``T[i][j]...`` for the
components `T_{ij...}` (for a 2-indices object, a matrix is returned)
EXAMPLES::
sage: from sage.tensor.modules.comp import Components
sage: c = Components(ZZ, [1,2,3], 2)
sage: c[1,2] # unset components are zero
0
sage: c.__getitem__((1,2))
0
sage: c.__getitem__([1,2])
0
sage: c[1,2] = -4
sage: c[1,2]
-4
sage: c.__getitem__((1,2))
-4
sage: c[:]
[ 0 0 0]
[ 0 0 -4]
[ 0 0 0]
sage: c.__getitem__(slice(None))
[ 0 0 0]
[ 0 0 -4]
[ 0 0 0]
"""
no_format = self._output_formatter is None
format_type = None # default value, possibly redefined below
if isinstance(args, list): # case of [[...]] syntax
no_format = True
if isinstance(args[0], slice):
indices = args[0]
elif isinstance(args[0], (tuple, list)): # to ensure equivalence between
indices = args[0] # [[(i,j,...)]] or [[[i,j,...]]] and [[i,j,...]]
else:
indices = tuple(args)
else:
# Determining from the input the list of indices and the format
if isinstance(args, (int, Integer, slice)):
indices = args
elif isinstance(args[0], slice):
indices = args[0]
if len(args) == 2:
format_type = args[1]
elif len(args) == self._nid:
indices = args
else:
format_type = args[-1]
indices = args[:-1]
if isinstance(indices, slice):
return self._get_list(indices, no_format, format_type)
else:
ind = self._check_indices(indices)
if ind in self._comp:
if no_format:
return self._comp[ind]
elif format_type is None:
return self._output_formatter(self._comp[ind])
else:
return self._output_formatter(self._comp[ind], format_type)
else: # if the value is not stored in self._comp, it is zero:
if no_format:
return self._ring.zero()
elif format_type is None:
return self._output_formatter(self._ring.zero())
else:
return self._output_formatter(self._ring.zero(),
format_type)
def _get_list(self, ind_slice, no_format=True, format_type=None):
r"""
Return the list of components (as nested list or matrix).
INPUT:
- ``ind_slice`` -- a slice object. Unless the dimension is 1,
this must be ``[:]``.
- ``no_format`` -- (default: ``True``) determines whether some
formatting of the components is to be performed
- ``format_type`` -- (default: ``None``) argument to be passed
to the formatting function ``self._output_formatter``, as the
second (optional) argument
OUTPUT:
- general case: the nested list of components in the form
``T[i][j]...`` for the components `T_{ij...}`.
- in the 1-dim case, a slice of that list if
``ind_slice = [a:b]``.
- in the 2-dim case, a matrix (over the base ring of the components or
of the formatted components if ``no_format`` is ``False``) is
returned instead, except if the formatted components do not belong
to any ring (for instance if they are strings).
EXAMPLES::
sage: from sage.tensor.modules.comp import Components
sage: c = Components(ZZ, [1,2,3], 2)
sage: c[0,1], c[1,2] = 5, -4
sage: c._get_list(slice(None))
[ 0 5 0]
[ 0 0 -4]
[ 0 0 0]
sage: v = Components(ZZ, [1,2,3], 1)
sage: v[:] = 4, 5, 6
sage: v._get_list(slice(None))
[4, 5, 6]
sage: v._get_list(slice(0,1))
[4]
sage: v._get_list(slice(0,2))
[4, 5]
sage: v._get_list(slice(2,3))
[6]
"""
si = self._sindex
nsi = si + self._dim
if self._nid == 1:
if ind_slice.start is None:
start = si
else:
start = ind_slice.start
if ind_slice.stop is None:
stop = nsi
else:
stop = ind_slice.stop
if ind_slice.step is not None:
raise NotImplementedError("function [start:stop:step] not implemented")
if no_format:
return [self[[i]] for i in range(start, stop)]
else:
return [self[i, format_type] for i in range(start, stop)]
if ind_slice.start is not None or ind_slice.stop is not None:
raise NotImplementedError("function [start:stop] not " +
"implemented for components with {} indices".format(self._nid))
resu = [self._gen_list([i], no_format, format_type)
for i in range(si, nsi)]
if self._nid == 2:
# 2-dim case: convert to matrix for a nicer output
from sage.matrix.constructor import matrix
from sage.structure.element import parent
from sage.categories.rings import Rings
if parent(resu[0][0]) in Rings():
return matrix(resu)
return resu
def _gen_list(self, ind, no_format=True, format_type=None):
r"""
Recursive function to generate the list of values.
EXAMPLES::
sage: from sage.tensor.modules.comp import Components
sage: c = Components(ZZ, [1,2,3], 2)
sage: c[0,1], c[1,2] = 5, -4
sage: c._gen_list([])
[[0, 5, 0], [0, 0, -4], [0, 0, 0]]
sage: c._gen_list([0])
[0, 5, 0]
sage: c._gen_list([1])
[0, 0, -4]
sage: c._gen_list([2])
[0, 0, 0]
sage: c._gen_list([0,1])
5
"""
if len(ind) == self._nid:
if no_format:
return self[ind]
else:
args = tuple(ind + [format_type])
return self[args]
else:
si = self._sindex
nsi = si + self._dim
return [self._gen_list(ind + [i], no_format, format_type)
for i in range(si, nsi)]
def __setitem__(self, args, value):
r"""
Sets the component corresponding to the given indices.
INPUT:
- ``args`` -- list of indices (possibly a single integer if
self is a 1-index object); if ``[:]`` is provided, all the
components are set
- ``value`` -- the value to be set or a list of values if
``args = [:]`` (``slice(None)``)
EXAMPLES::
sage: from sage.tensor.modules.comp import Components
sage: c = Components(ZZ, [1,2,3], 2)
sage: c.__setitem__((0,1), -4)
sage: c[:]
[ 0 -4 0]
[ 0 0 0]
[ 0 0 0]
sage: c[0,1] = -4
sage: c[:]
[ 0 -4 0]
[ 0 0 0]
[ 0 0 0]
sage: c.__setitem__(slice(None), [[0, 1, 2], [3, 4, 5], [6, 7, 8]])
sage: c[:]
[0 1 2]
[3 4 5]
[6 7 8]
"""
format_type = None # default value, possibly redefined below
if isinstance(args, list): # case of [[...]] syntax
if isinstance(args[0], slice):
indices = args[0]
elif isinstance(args[0], (tuple, list)): # to ensure equivalence between
indices = args[0] # [[(i,j,...)]] or [[[i,j,...]]] and [[i,j,...]]
else:
indices = tuple(args)
else:
# Determining from the input the list of indices and the format
if isinstance(args, (int, Integer, slice)):
indices = args
elif isinstance(args[0], slice):
indices = args[0]
if len(args) == 2:
format_type = args[1]
elif len(args) == self._nid:
indices = args
else:
format_type = args[-1]
indices = args[:-1]
if isinstance(indices, slice):
self._set_list(indices, format_type, value)
else:
ind = self._check_indices(indices)
# Check for a zero value
# The fast method is_trivial_zero() is employed preferably
# to the (possibly expensive) direct comparison to zero:
if hasattr(value, 'is_trivial_zero'):
zero_value = value.is_trivial_zero()
else:
zero_value = value == 0
if zero_value:
# if the component has been set previously, it is deleted,
# otherwise nothing is done (zero components are not stored):
if ind in self._comp:
del self._comp[ind]
else:
if format_type is None:
self._comp[ind] = self._ring(value)
else:
self._comp[ind] = self._ring({format_type: value})
# NB: the writing
# self._comp[ind] = self._ring(value, format_type)
# is not allowed when ring is an algebra and value some
# element of the algebra's base ring, cf. the discussion at
# http://trac.sagemath.org/ticket/16054
def _set_list(self, ind_slice, format_type, values):
r"""
Set the components from a list.
INPUT:
- ``ind_slice`` -- a slice object
- ``format_type`` -- format possibly used to construct a ring element
- ``values`` -- list of values for the components : the full list if
``ind_slice = [:]``, in the form ``T[i][j]...`` for the
component `T_{ij...}`; in the 1-D case, ``ind_slice`` can be
a slice of the full list, in the form ``[a:b]``
EXAMPLES::
sage: from sage.tensor.modules.comp import Components
sage: c = Components(ZZ, [1,2,3], 2)
sage: c._set_list(slice(None), None, [[0, 1, 2], [3, 4, 5], [6, 7, 8]])
sage: c[:]
[0 1 2]
[3 4 5]
[6 7 8]
"""
si = self._sindex
nsi = si + self._dim
if self._nid == 1:
if ind_slice.start is None:
start = si
else:
start = ind_slice.start
if ind_slice.stop is None:
stop = nsi
else:
stop = ind_slice.stop
if ind_slice.step is not None:
raise NotImplementedError("function [start:stop:step] not implemented")
for i in range(start, stop):
self[i, format_type] = values[i-start]
else:
if ind_slice.start is not None or ind_slice.stop is not None:
raise NotImplementedError("function [start:stop] not " +
"implemented for components with {} indices".format(self._nid))
for i in range(si, nsi):
self._set_value_list([i], format_type, values[i-si])
def _set_value_list(self, ind, format_type, val):
r"""
Recursive function to set a list of values to ``self``.
EXAMPLES::
sage: from sage.tensor.modules.comp import Components
sage: c = Components(ZZ, [1,2,3], 2)
sage: c._set_value_list([], None, [[1,2,3], [4,5,6], [7,8,9]])
sage: c[:]