-
Notifications
You must be signed in to change notification settings - Fork 62
/
mv.py
1964 lines (1670 loc) · 68.1 KB
/
mv.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
"""
Multivector and Linear Multivector Differential Operator
"""
import copy
import numbers
import operator
from functools import reduce
from typing import List, Any, Tuple, Union, TYPE_CHECKING
from sympy import (
Symbol, Function, S, expand, Add,
sin, cos, sinh, cosh, sqrt, trigsimp,
simplify, diff, Rational, Expr, Abs, collect, SympifyError,
)
from sympy import exp as sympy_exp
from sympy import N as Nsympy
from sympy.printing.latex import LatexPrinter as _LatexPrinter
from sympy.printing.str import StrPrinter as _StrPrinter
from . import printer
from . import metric
from .printer import ZERO_STR
from ._utils import KwargParser as _KwargParser
from . import dop
if TYPE_CHECKING:
from galgebra.ga import Ga
ONE = S(1)
ZERO = S(0)
HALF = Rational(1, 2)
half = Rational(1, 2)
# Add custom settings to the builtin latex printer
_LatexPrinter._default_settings.update({
'galgebra_mv_fmt': 1
})
_StrPrinter._default_settings.update({
'galgebra_mv_fmt': 1
})
########################### Multivector Class ##########################
class Mv(printer.GaPrintable):
"""
Wrapper class for multivector objects (``self.obj``) so that it is easy
to overload operators (``*``, ``^``, ``|``, ``<``, ``>``) for the various
multivector products and for printing.
Also provides a constructor to easily instantiate multivector objects.
Additionally, the functionality
of the multivector derivative have been added via the special vector
``grad`` so that one can take the geometric derivative of a multivector
function ``A`` by applying ``grad`` from the left, ``grad*A``, or the
right ``A*grad`` for both the left and right derivatives. The operator
between the ``grad`` and the 'A' can be any of the multivector product
operators.
If ``f`` is a scalar function ``grad*f`` is the usual gradient of a function.
If ``A`` is a vector function ``grad|f`` is the divergence of ``A`` and
``-I*(grad^A)`` is the curl of ``A`` (I is the pseudo scalar for the geometric
algebra)
Attributes
----------
obj : sympy.core.Expr
The underlying sympy expression for this multivector
"""
################### Multivector initialization #####################
# This is read by one code path in `galgebra.printer.Fmt`. Only one example
# sets it.
fmt = 1
dual_mode_lst = ['+I', 'I+', '+Iinv', 'Iinv+', '-I', 'I-', '-Iinv', 'Iinv-']
@staticmethod
def setup(ga: 'Ga') -> Tuple['Mv', List['Mv'], 'Mv']:
"""
Set up constant multivectors required for multivector class for
a given geometric algebra, `ga`.
"""
# copy basis in case the caller wanted to change it
return ga.mv_I, list(ga.mv_basis), ga.mv_x
@staticmethod
def Mul(A: 'Mv', B: 'Mv', op: str) -> 'Mv':
"""
Function for all types of geometric multiplications called by
overloaded operators for ``*``, ``^``, ``|``, ``<``, and ``>``.
"""
if not isinstance(A, Mv):
A = B.Ga.mv(A)
if not isinstance(B, Mv):
B = A.Ga.mv(B)
if op == '*':
return A * B
elif op == '^':
return A ^ B
elif op == '|':
return A | B
elif op == '<':
return A < B
elif op == '>':
return A > B
else:
raise ValueError('Operation ' + op + 'not allowed in Mv.Mul!')
def characterise_Mv(self) -> None:
if self.char_Mv:
return
obj = expand(self.obj)
if isinstance(obj, numbers.Number):
self.i_grade = 0
self.is_blade_rep = True
self.grades = [0]
return
if obj.is_commutative:
self.i_grade = 0
self.is_blade_rep = True
self.grades = [0]
return
if isinstance(obj, Add):
args = obj.args
else:
if obj in self.Ga.blades.flat:
self.is_blade_rep = True
self.i_grade = self.Ga.blades_to_grades_dict[obj]
self.grades = [self.i_grade]
self.char_Mv = True
self.blade_flg = True
return
else:
args = [obj]
grades = []
# print 'args =', args
self.is_blade_rep = True
for term in args:
if term.is_commutative:
if 0 not in grades:
grades.append(0)
else:
c, nc = term.args_cnc(split_1=False)
blade = nc[0]
# print 'blade =', blade
if blade in self.Ga.blades.flat:
grade = self.Ga.blades_to_grades_dict[blade]
if grade not in grades:
grades.append(grade)
else:
self.char_Mv = True
self.is_blade_rep = False
self.i_grade = None
return
if len(grades) == 1:
self.i_grade = grades[0]
else:
self.i_grade = None
self.grades = grades
self.char_Mv = True
# helper methods called by __init__. Note that these names must not change,
# as the part of the name after `_make_` is public API via the string
# argument passed to __init__.
#
# The double underscores in argument names are to force the passing
# positionally. When python 3.8 is the lowest supported version, we can
# switch to using the / syntax from PEP570
@staticmethod
def _make_grade(ga: 'Ga', __name_or_coeffs: Union[str, list, tuple], __grade: int, **kwargs) -> Expr:
""" Make a pure grade multivector. """
def add_superscript(root, s):
if not s:
return root
return '{}__{}'.format(root, s)
grade = __grade
kw = _KwargParser('_make_grade', kwargs)
if isinstance(__name_or_coeffs, str):
name = __name_or_coeffs
f = kw.pop('f', False)
kw.reject_remaining()
if isinstance(f, bool):
if f: # Is a multivector function of all coordinates
return sum([Function(add_superscript(name, super_script), real=True)(*ga.coords) * base
for super_script, base in zip(ga.blade_super_scripts[grade], ga.blades[grade])])
else: # Is a constant multivector function
return sum([Symbol(add_superscript(name, super_script), real=True) * base
for super_script, base in zip(ga.blade_super_scripts[grade], ga.blades[grade])])
else: # Is a multivector function of tuple f variables
return sum([Function(add_superscript(name, super_script), real=True)(*f) * base
for super_script, base in zip(ga.blade_super_scripts[grade], ga.blades[grade])])
elif isinstance(__name_or_coeffs, (list, tuple)):
coeffs = __name_or_coeffs
kw.reject_remaining()
if len(coeffs) <= len(ga.blades[grade]):
return sum([
coef * base
for coef, base in zip(coeffs, ga.blades[grade][:len(coeffs)])])
else:
raise ValueError("Too many coefficients")
else:
raise TypeError("Expected a string, list, or tuple")
@staticmethod
def _make_scalar(ga: 'Ga', __name_or_value: Union[str, Expr], **kwargs) -> Expr:
""" Make a scalar multivector """
if isinstance(__name_or_value, str):
name = __name_or_value
return Mv._make_grade(ga, name, 0, **kwargs)
else:
value = __name_or_value
return value
@staticmethod
def _make_vector(ga: 'Ga', __name_or_coeffs: Union[str, list, tuple], **kwargs) -> Expr:
""" Make a vector multivector """
return Mv._make_grade(ga, __name_or_coeffs, 1, **kwargs)
@staticmethod
def _make_bivector(ga: 'Ga', __name_or_coeffs: Union[str, list, tuple], **kwargs) -> Expr:
""" Make a bivector multivector """
return Mv._make_grade(ga, __name_or_coeffs, 2, **kwargs)
@staticmethod
def _make_pseudo(ga: 'Ga', __name_or_coeffs: Union[str, list, tuple], **kwargs) -> Expr:
""" Make a pseudo scalar multivector """
return Mv._make_grade(ga, __name_or_coeffs, ga.n, **kwargs)
@staticmethod
def _make_mv(ga: 'Ga', __name: str, **kwargs) -> Expr:
""" Make a general (2**n components) multivector """
if not isinstance(__name, str):
raise TypeError("Must be a string")
return reduce(operator.add, (
Mv._make_grade(ga, __name, grade, **kwargs)
for grade in range(ga.n + 1)
))
@staticmethod
def _make_spinor(ga: 'Ga', __name: str, **kwargs) -> Expr:
""" Make a general even (spinor) multivector """
if not isinstance(__name, str):
raise TypeError("Must be a string")
return reduce(operator.add, (
Mv._make_grade(ga, __name, grade, **kwargs)
for grade in range(0, ga.n + 1, 2)
))
@staticmethod
def _make_odd(ga: 'Ga', __name: str, **kwargs) -> Expr:
""" Make a general odd multivector """
if not isinstance(__name, str):
raise TypeError("Must be a string")
return reduce(operator.add, (
Mv._make_grade(ga, __name, grade, **kwargs)
for grade in range(1, ga.n + 1, 2)
), S(0)) # base case needed in case n == 0
# aliases
_make_grade2 = _make_bivector
_make_even = _make_spinor
def __init__(self, *args, ga, recp=None, coords=None, **kwargs):
"""
__init__(self, *args, ga, recp=None, **kwargs)
Note this constructor is overloaded, based on the type and number of
positional arguments:
.. class:: Mv(*, ga, recp=None)
Create a zero multivector
.. class:: Mv(expr, /, *, ga, recp=None)
Create a multivector from an existing vector or sympy expression
.. class:: Mv(coeffs, grade, /, ga, recp=None)
Create a multivector constant with a given grade
.. class:: Mv(name, category, /, *cat_args, ga, recp=None, f=False)
Create a multivector constant with a given category
.. class:: Mv(name, grade, /, ga, recp=None, f=False)
Create a multivector variable or function of a given grade
.. class:: Mv(coeffs, category, /, *cat_args, ga, recp=None)
Create a multivector variable or function of a given category
``*`` and ``/`` in the signatures above are python
3.8 syntax, and respectively indicate the boundaries between
positional-only, normal, and keyword-only arguments.
Parameters
----------
ga : ~galgebra.ga.Ga
Geometric algebra to be used with multivectors
recp : object, optional
Normalization for reciprocal vector. Unused.
name : str
Name of this multivector, if it is a variable or function
coeffs : sequence
Sequence of coefficients for the given category.
This is only meaningful
category : str
One of:
* ``"grade"`` - this takes an additional argument, the grade to
create, in ``cat_args``
* ``"scalar"``
* ``"vector"``
* ``"bivector"`` / ``"grade2"``
* ``"pseudo"``
* ``"mv"``
* ``"even"`` / ``"spinor"``
* ``"odd"``
f : bool, tuple
True if function of coordinates, or a tuple of those coordinates.
Only valid if a name is passed
coords :
This argument is always accepted but ignored.
It is incorrectly described internally as the coordinates to be
used with multivector functions.
"""
kw = _KwargParser('__init__', kwargs)
self.Ga = ga
self.recp = recp # not used
self.char_Mv = False
self.i_grade = None # if pure grade mv, grade value
self.grades = None # list of grades in mv
self.is_blade_rep = True # flag for blade representation
self.blade_flg = None # if is_blade is called flag is set
self.versor_flg = None # if is_versor is called flag is set
self.coords = self.Ga.coords
self.title = None
if len(args) == 0: # default constructor 0
self.obj = S(0)
self.i_grade = 0
kw.reject_remaining()
elif len(args) == 1 and not isinstance(args[0], str): # copy constructor
x = args[0]
if isinstance(x, Mv):
self.obj = x.obj
self.is_blade_rep = x.is_blade_rep
self.i_grade = x.i_grade
else:
if isinstance(x, Expr): # copy constructor for obj expression
self.obj = x
else: # copy constructor for scalar obj expression
self.obj = S(x)
self.is_blade_rep = True
self.characterise_Mv()
kw.reject_remaining()
else:
if isinstance(args[1], str):
make_args = list(args)
mode = make_args.pop(1)
make_func = getattr(Mv, '_make_{}'.format(mode), None)
if make_func is None:
raise ValueError('{!r} is not an allowed multivector type.'.format(mode))
self.obj = make_func(self.Ga, *make_args, **kwargs)
elif isinstance(args[1], int): # args[1] = r (integer) Construct grade r multivector
if args[1] == 0:
# _make_scalar interprets its coefficient argument differently
make_args = list(args)
make_args.pop(1)
self.obj = Mv._make_scalar(self.Ga, *make_args, **kwargs)
else:
self.obj = Mv._make_grade(self.Ga, *args, **kwargs)
else:
raise TypeError("Expected string or int")
if isinstance(args[0], str):
self.title = args[0]
self.characterise_Mv()
def _sympy_(self):
""" Hook used by sympy.sympify """
raise SympifyError(self, TypeError(
"Cannot safely convert an `Mv` instance to a sympy object. "
"Use `mv.obj` to obtain the internal sympy object, but note that "
"this does not overload the geometric operators, and will not "
"track the associated `Ga` instance."
))
################# Multivector member functions #####################
def reflect_in_blade(self, blade: 'Mv') -> 'Mv': # Reflect mv in blade
# See Mv class functions documentation
if blade.is_blade():
self.characterise_Mv()
blade.characterise_Mv()
blade_inv = blade.rev() / blade.norm2()
grade_dict = self.Ga.grade_decomposition(self)
blade_grade = blade.i_grade
reflect = Mv(0, 'scalar', ga=self.Ga)
for grade in list(grade_dict.keys()):
if (grade * (blade_grade + 1)) % 2 == 0:
reflect += blade * grade_dict[grade] * blade_inv
else:
reflect -= blade * grade_dict[grade] * blade_inv
return reflect
else:
raise ValueError(str(blade) + 'is not a blade in reflect_in_blade(self, blade)')
def project_in_blade(self, blade: 'Mv') -> 'Mv':
# See Mv class functions documentation
if blade.is_blade():
blade.characterise_Mv()
blade_inv = blade.rev() / blade.norm2()
return (self < blade) * blade_inv # < is left contraction
else:
raise ValueError(str(blade) + 'is not a blade in project_in_blade(self, blade)')
def rotate_multivector(self, itheta: 'Mv', hint: str = '-'):
Rm = (-itheta/S(2)).exp(hint)
Rp = (itheta/S(2)).exp(hint)
return Rm * self * Rp
def base_rep(self) -> 'Mv':
""" Express as a linear combination of geometric products """
if not self.is_blade_rep:
return self
b = copy.copy(self)
b.obj = self.Ga.blade_to_base_rep(self.obj)
b.is_blade_rep = False
return b
def blade_rep(self) -> 'Mv':
""" Express as a linear combination of blades """
if self.is_blade_rep:
return self
b = copy.copy(self)
b.obj = self.Ga.base_to_blade_rep(self.obj)
b.is_blade_rep = True
return b
def __hash__(self) -> int:
if self.is_scalar():
# ensure we match equality
return hash(self.obj)
else:
return hash((self.Ga, self.obj))
def __eq__(self, A):
if isinstance(A, Mv):
diff = (self - A).expand().simplify()
# diff = (self - A).expand()
return diff.obj == S(0)
else:
return self.is_scalar() and self.obj == A
"""
def __eq__(self, A):
if not isinstance(A, Mv):
if not self.is_scalar():
return False
if expand(self.obj) == expand(A):
return True
else:
return False
if self.is_blade_rep != A.is_blade_rep:
self = self.blade_rep()
A = A.blade_rep()
coefs, bases = metric.linear_expand(self.obj)
Acoefs, Abases = metric.linear_expand(A.obj)
if len(bases) != len(Abases):
return False
if set(bases) != set(Abases):
return False
for base in bases:
index = bases.index(base)
indexA = Abases.index(base)
if expand(coefs[index]) != expand(Acoefs[index]):
return False
return True
"""
def __neg__(self):
return Mv(-self.obj, ga=self.Ga)
def __add__(self, A):
if isinstance(A, dop._BaseDop):
return NotImplemented
if not isinstance(A, Mv):
return Mv(self.obj + A, ga=self.Ga)
if self.Ga != A.Ga:
raise ValueError('In + operation Mv arguments are not from same geometric algebra')
if self.is_blade_rep == A.is_blade_rep:
return Mv(self.obj + A.obj, ga=self.Ga)
else:
if self.is_blade_rep:
A = A.blade_rep()
else:
self = self.blade_rep()
return Mv(self.obj + A.obj, ga=self.Ga)
def __radd__(self, A):
return self + A
def __sub__(self, A):
if isinstance(A, dop._BaseDop):
return NotImplemented
if self.Ga != A.Ga:
raise ValueError('In - operation Mv arguments are not from same geometric algebra')
if self.is_blade_rep == A.is_blade_rep:
return Mv(self.obj - A.obj, ga=self.Ga)
else:
if self.is_blade_rep:
A = A.blade_rep()
else:
self = self.blade_rep()
return Mv(self.obj - A.obj, ga=self.Ga)
def __rsub__(self, A):
return -self + A
def __mul__(self, A):
if isinstance(A, dop._BaseDop):
return NotImplemented
if not isinstance(A, Mv):
return Mv(expand(A * self.obj), ga=self.Ga)
if self.Ga != A.Ga:
raise ValueError('In * operation Mv arguments are not from same geometric algebra')
if self.is_scalar():
return Mv(self.obj * A, ga=self.Ga)
if self.is_blade_rep and A.is_blade_rep:
self = self.base_rep()
A = A.base_rep()
selfxA = Mv(self.Ga.mul(self.obj, A.obj), ga=self.Ga)
selfxA.is_blade_rep = False
return selfxA.blade_rep()
elif self.is_blade_rep:
self = self.base_rep()
selfxA = Mv(self.Ga.mul(self.obj, A.obj), ga=self.Ga)
selfxA.is_blade_rep = False
return selfxA.blade_rep()
elif A.is_blade_rep:
A = A.base_rep()
selfxA = Mv(self.Ga.mul(self.obj, A.obj), ga=self.Ga)
selfxA.is_blade_rep = False
return selfxA.blade_rep()
else:
return Mv(self.Ga.mul(self.obj, A.obj), ga=self.Ga)
def __rmul__(self, A):
if isinstance(A, dop._BaseDop):
return NotImplemented
return Mv(expand(A * self.obj), ga=self.Ga)
def __truediv__(self, A):
if isinstance(A, Mv):
return self * A.inv()
else:
return self * (S(1)/A)
def __str__(self):
return printer.GaPrinter().doprint(self)
def __getitem__(self, key: int) -> 'Mv':
'''
get a specified grade of a multivector
'''
return self.grade(key)
def _sympystr(self, print_obj: printer.GaPrinter) -> str:
# note: this just replaces `self` for the rest of this function
obj = expand(self.obj)
obj = metric.Simp.apply(obj)
self = Mv(obj, ga=self.Ga)
if self.i_grade == 0:
return print_obj.doprint(self.obj)
if self.is_blade_rep or self.Ga.is_ortho:
base_keys = self.Ga.blades.flat
grade_keys = self.Ga.blades_to_grades_dict
else:
base_keys = self.Ga.bases.flat
grade_keys = self.Ga.bases_to_grades_dict
if isinstance(self.obj, Add): # collect coefficients of bases
if self.obj.is_commutative:
return self.obj
args = self.obj.args
terms = {} # dictionary with base indexes as keys
grade0 = S(0)
for arg in args:
c, nc = arg.args_cnc()
c = reduce(operator.mul, c, S(1))
if len(nc) > 0:
base = nc[0]
if base in base_keys:
index = base_keys.index(base)
if index in terms:
c_tmp, base, g_keys = terms[index]
terms[index] = (c_tmp + c, base, g_keys)
else:
terms[index] = (c, base, grade_keys[base])
else:
grade0 += c
if grade0 != S(0):
terms[-1] = (grade0, S(1), -1)
terms = list(terms.items())
sorted_terms = sorted(terms, key=operator.itemgetter(0)) # sort via base indexes
s = print_obj.doprint(sorted_terms[0][1][0] * sorted_terms[0][1][1])
if print_obj._settings['galgebra_mv_fmt'] == 3:
s = ' ' + s + '\n'
if print_obj._settings['galgebra_mv_fmt'] == 2:
s = ' ' + s
old_grade = sorted_terms[0][1][2]
for (key, (c, base, grade)) in sorted_terms[1:]:
term = print_obj.doprint(c * base)
if print_obj._settings['galgebra_mv_fmt'] == 2 and old_grade != grade: # one grade per line
old_grade = grade
s += '\n'
if term[0] == '-':
term = ' - ' + term[1:]
else:
term = ' + ' + term
if print_obj._settings['galgebra_mv_fmt'] == 3: # one base per line
s += term + '\n'
else: # one multivector per line
s += term
if s[-1] == '\n':
s = s[:-1]
return s
else:
return print_obj.doprint(self.obj)
def _latex(self, print_obj: _LatexPrinter) -> str:
if self.obj == S.Zero:
return ZERO_STR
first_line = True
def append_plus(c_str):
nonlocal first_line
if first_line:
first_line = False
return c_str
else:
c_str = c_str.strip()
if c_str[0] == '-':
return ' ' + c_str
else:
return ' + ' + c_str
# str representation of multivector
# note: this just replaces `self` for the rest of this function
obj = expand(self.obj)
obj = metric.Simp.apply(obj)
self = Mv(obj, ga=self.Ga)
if self.obj == S(0):
return ZERO_STR
if self.is_blade_rep or self.Ga.is_ortho:
base_keys = self.Ga.blades.flat
grade_keys = self.Ga.blades_to_grades_dict
else:
base_keys = self.Ga.bases.flat
grade_keys = self.Ga.bases_to_grades_dict
if isinstance(self.obj, Add):
args = self.obj.args
else:
args = [self.obj]
terms = {} # dictionary with base indexes as keys
grade0 = S(0)
for arg in args:
c, nc = arg.args_cnc(split_1=False)
c = reduce(operator.mul, c, S(1))
if len(nc) > 0:
base = nc[0]
if base in base_keys:
index = base_keys.index(base)
if index in terms:
c_tmp, base, g_keys = terms[index]
terms[index] = (c_tmp + c, base, g_keys)
else:
terms[index] = (c, base, grade_keys[base])
else:
grade0 += c
if grade0 != S(0):
terms[-1] = (grade0, S(1), 0)
terms = list(terms.items())
sorted_terms = sorted(terms, key=operator.itemgetter(0)) # sort via base indexes
if len(sorted_terms) == 1 and sorted_terms[0][1][2] == 0: # scalar
return print_obj.doprint(printer.coef_simplify(sorted_terms[0][1][0]))
lines = []
old_grade = -1
s = ''
for (index, (coef, base, grade)) in sorted_terms:
coef = printer.coef_simplify(coef)
# coef = simplify(coef)
l_coef = print_obj.doprint(coef)
if l_coef == '1' and base != S(1):
l_coef = ''
if l_coef == '-1' and base != S(1):
l_coef = '-'
if base == S(1):
l_base = ''
else:
l_base = print_obj.doprint(base)
if isinstance(coef, Add):
cb_str = '\\left ( ' + l_coef + '\\right ) ' + l_base
else:
cb_str = l_coef + ' ' + l_base
if print_obj._settings['galgebra_mv_fmt'] == 3: # One base per line
lines.append(append_plus(cb_str))
elif print_obj._settings['galgebra_mv_fmt'] == 2: # One grade per line
if grade != old_grade:
old_grade = grade
if not first_line:
lines.append(s)
s = append_plus(cb_str)
else:
s += append_plus(cb_str)
else: # One multivector per line
s += append_plus(cb_str)
if print_obj._settings['galgebra_mv_fmt'] == 2:
lines.append(s)
if print_obj._settings['galgebra_mv_fmt'] >= 2:
if len(lines) == 1:
return lines[0]
s = ' \\begin{aligned}[t] '
for line in lines:
s += ' & ' + line + ' \\\\ '
s = s[:-3] + ' \\end{aligned} '
return s
def __xor__(self, A): # wedge (^) product
if isinstance(A, dop._BaseDop):
return NotImplemented
if not isinstance(A, Mv):
return Mv(A * self.obj, ga=self.Ga)
if self.Ga != A.Ga:
raise ValueError('In ^ operation Mv arguments are not from same geometric algebra')
if self.is_scalar():
return self * A
self = self.blade_rep()
A = A.blade_rep()
return Mv(self.Ga.wedge(self.obj, A.obj), ga=self.Ga)
def __rxor__(self, A): # wedge (^) product
if isinstance(A, dop._BaseDop):
return NotImplemented
assert not isinstance(A, Mv)
return Mv(A * self.obj, ga=self.Ga)
def __or__(self, A): # dot (|) product
if isinstance(A, dop._BaseDop):
return NotImplemented
if not isinstance(A, Mv):
return Mv(ga=self.Ga)
if self.Ga != A.Ga:
raise ValueError('In | operation Mv arguments are not from same geometric algebra')
self = self.blade_rep()
A = A.blade_rep()
return Mv(self.Ga.hestenes_dot(self.obj, A.obj), ga=self.Ga)
def __ror__(self, A): # dot (|) product
if isinstance(A, dop._BaseDop):
return NotImplemented
assert not isinstance(A, Mv)
return Mv(ga=self.Ga)
def __pow__(self, n): # Integer power operator
if not isinstance(n, int):
raise ValueError('!!!!Multivector power can only be to integer power!!!!')
result = S(1)
for x in range(n):
result *= self
return result
def __lshift__(self, A): # anti-comutator (<<)
return half * (self * A + A * self)
def __rshift__(self, A): # comutator (>>)
return half * (self * A - A * self)
def __rlshift__(self, A): # anti-comutator (<<)
return half * (A * self + self * A)
def __rrshift__(self, A): # comutator (>>)
return half * (A * self - self * A)
def __lt__(self, A): # left contraction (<)
if isinstance(A, Dop):
# Cannot return `NotImplemented` here, as that would call `A > self`
return A.Mul(self, A, op='<')
elif isinstance(A, dop._BaseDop):
raise TypeError(
"'<' not supported between instances of 'Mv' and {!r}"
.format(type(A).__name__)
)
if not isinstance(A, Mv): # sympy scalar
return Mv(A * self.obj, ga=self.Ga)
if self.Ga != A.Ga:
raise ValueError('In < operation Mv arguments are not from same geometric algebra')
self = self.blade_rep()
A = A.blade_rep()
return Mv(self.Ga.left_contract(self.obj, A.obj), ga=self.Ga)
def __gt__(self, A): # right contraction (>)
if isinstance(A, Dop):
# Cannot return `NotImplemented` here, as that would call `A < self`
return A.Mul(self, A, op='>')
elif isinstance(A, dop._BaseDop):
raise TypeError(
"'>' not supported between instances of 'Mv' and {!r}"
.format(type(A).__name__)
)
if not isinstance(A, Mv): # sympy scalar
return self.Ga.mv(A * self.scalar())
if self.Ga != A.Ga:
raise ValueError('In > operation Mv arguments are not from same geometric algebra')
self = self.blade_rep()
A = A.blade_rep()
return Mv(self.Ga.right_contract(self.obj, A.obj), ga=self.Ga)
def collect(self, deep=False) -> 'Mv':
"""
group coeffients of blades of multivector
so there is only one coefficient per grade
"""
""" # dead code
self.obj = expand(self.obj)
if self.is_blade_rep or Mv.Ga.is_ortho:
c = self.Ga.blades.flat
else:
c = self.Ga.bases.flat
self.obj = self.obj.collect(c)
return self
"""
obj_dict = {}
for coef, base in metric.linear_expand_terms(self.obj):
if base in list(obj_dict.keys()):
obj_dict[base] += coef
else:
obj_dict[base] = coef
obj = S(0)
for base in list(obj_dict.keys()):
if deep:
obj += collect(obj_dict[base])*base
else:
obj += obj_dict[base]*base
return Mv(obj, ga=self.Ga)
def is_scalar(self) -> bool:
grades = self.Ga.grades(self.obj)
return grades == [0]
def is_vector(self) -> bool:
grades = self.Ga.grades(self.obj)
return grades == [1]
def is_blade(self) -> bool:
"""
True is self is blade, otherwise False
sets self.blade_flg and returns value
"""
if self.blade_flg is not None:
return self.blade_flg
else:
if self.is_versor():
if self.i_grade is not None:
self.blade_flg = True
else:
self.blade_flg = False
else:
self.blade_flg = False
return self.blade_flg
def is_base(self) -> bool:
coefs, _bases = metric.linear_expand(self.obj)
return coefs == [ONE]
def is_versor(self) -> bool:
"""
Test for versor (geometric product of vectors)
This follows Leo Dorst's test for a versor.
Leo Dorst, 'Geometric Algebra for Computer Science,' p.533
Sets self.versor_flg and returns value
"""
if self.versor_flg is not None:
return self.versor_flg
self.characterise_Mv()
self.versor_flg = False
self_rev = self.rev()
# see if self*self.rev() is a scalar
test = self*self_rev
if not test.is_scalar():
return self.versor_flg
# see if self*x*self.rev() returns a vector for x an arbitrary vector
test = self * self.Ga._XOX * self.rev()
self.versor_flg = test.is_vector()
return self.versor_flg
def is_zero(self) -> bool:
return self.obj == 0
def scalar(self) -> Expr:
""" return scalar part of multivector as sympy expression """
return self.Ga.scalar_part(self.obj)
def get_grade(self, r: int) -> 'Mv':
""" return r-th grade of multivector as a multivector """
return Mv(self.Ga.get_grade(self.obj, r), ga=self.Ga)
def components(self) -> List['Mv']:
cb = metric.linear_expand_terms(self.obj)
cb = sorted(cb, key=lambda x: self.Ga.blades.flat.index(x[1]))
return [self.Ga.mv(coef * base) for coef, base in cb]
def get_coefs(self, grade: int) -> List[Expr]:
"""
Like ``blade_coefs(self.Ga.mv_blades[grade])``, but requires all
components to be of that grade.
Raises
------
ValueError:
If the multivector is not of the given grade.
"""
blade_lst = self.Ga.blades[grade]
coef_lst = [S.Zero] * len(blade_lst)
for coef, blade in metric.linear_expand_terms(self.obj):
if coef == S.Zero:
continue # TODO: why does expansion return this?
try:
base_i = blade_lst.index(blade)
except ValueError:
raise ValueError(
"MultiVector has a {} component which is not grade {}"
.format(blade, grade)
) from None
coef_lst[base_i] += coef
return coef_lst
def blade_coefs(self, blade_lst: List['Mv'] = None) -> List[Expr]:
"""
For a multivector, A, and a list of basis blades, blade_lst return
a list (sympy expressions) of the coefficients of each basis blade
in blade_lst
"""
if blade_lst is None: