forked from sympy/sympy
/
GA.py
2583 lines (2332 loc) · 85.1 KB
/
GA.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
#!/usr/bin/python
"""
The module GA implements symbolic Geometric Algebra in python.
The relevant references for this module are:
1. "Geometric Algebra for Physicists" by C. Doran and A. Lazenby,
Cambridge University Press, 2003.
2. "Geometric Algebra for Computer Science" by Leo Dorst,
Daniel Fontijne, and Stephen Mann, Morgan Kaufmann Publishers, 2007.
"""
import sys
import numpy
import sympy
import re as regrep
import sympy.galgebra.latex_ex
from sympy.core.decorators import deprecated
NUMPAT = regrep.compile( '([\-0-9])|([\-0-9]/[0-9])')
"""Re pattern for rational number"""
ZERO = sympy.Rational(0)
ONE = sympy.Rational(1)
TWO = sympy.Rational(2)
HALF = sympy.Rational(1, 2)
from sympy.core import Pow as pow_type
from sympy import Abs as abs_type
from sympy.core import Mul as mul_type
from sympy.core import Add as add_type
@sympy.vectorize(0)
def substitute_array(array, *args):
return(array.subs(*args))
def is_quasi_unit_numpy_array(array):
"""
Determine if a array is square and diagonal with
entries of +1 or -1.
"""
shape = numpy.shape(array)
if len(shape) == 2 and (shape[0] == shape[1]):
n = shape[0]
ix = 0
while ix < n:
iy = 0
while iy < ix:
if array[ix][iy] != ZERO:
return(False)
iy += 1
if sympy.Abs(array[ix][ix]) != ONE:
return(False)
ix += 1
return(True)
else:
return(False)
@deprecated(value="This function is no longer needed.", issue=3379,
deprecated_since_version="0.7.2")
def set_main(main_program):
pass
def plist(lst):
if type(lst) == list:
for x in lst:
plist(x)
else:
sys.stderr.write(lst + '\n')
return
def numeric(num_str):
"""
Returns rational numbers compatible with symbols.
Input is a string representing a fraction or integer
or a simple integer.
"""
if type(num_str) == int:
a = num_str
b = 1
else:
tmp = num_str.split('/')
if len(tmp) == 1:
a = int(tmp[0])
b = 1
else:
a = int(tmp[0])
b = int(tmp[1])
return(sympy.Rational(a, b))
def collect(expr, lst):
"""
Wrapper for sympy.collect.
"""
lst = MV.scalar_to_symbol(lst)
return(sympy.collect(expr, lst))
def sqrt(expr):
return(sympy.sqrt(expr))
def isint(a):
"""
Test for integer.
"""
return(type(a) == int)
def make_null_array(n):
"""
Return list of n empty lists.
"""
a = []
for i in range(n):
a.append([])
return(a)
def test_int_flgs(lst):
"""
Test if all elements in list are 0.
"""
for i in lst:
if i:
return(1)
return(0)
def comb(N, P):
"""
Calculates the combinations of the integers [0,N-1] taken P at a time.
The output is a list of lists of integers where the inner lists are
the different combinations. Each combination is sorted in ascending
order.
"""
def rloop(n, p, combs, comb):
if p:
for i in range(n):
newcomb = comb + [i]
np = p - 1
rloop(i, np, combs, newcomb)
else:
combs.append(comb)
combs = []
rloop(N, P, combs, [])
for comb in combs:
comb.sort()
return(combs)
def diagpq(p, q=0):
"""
Returns string equivalent metric tensor for signature (p, q).
"""
n = p + q
D = []
for i in xrange(p):
D.append((i*'0 ' +'1 '+ (n-i-1)*'0 ')[:-1])
for i in xrange(p,n):
D.append((i*'0 ' +'-1 '+ (n-i-1)*'0 ')[:-1])
return ','.join(D)
def arbitrary_metric(n):
"""
Returns string equivalent metric tensor for arbitrary signature.
"""
return ','.join(n*[(n*'# ')[:-1]])
def arbitrary_metric_conformal(n):
"""
Returns string equivalent metric tensor for arbitrary signature (n+1,1).
"""
str1 = ','.join(n*[n*'# '+'0 0'])
return ','.join([str1, n*'0 '+'1 0', n*'0 '+'0 -1'])
def make_scalars(symnamelst):
"""
make_scalars takes a string of symbol names separated by
blanks and converts them to MV scalars and returns a list
of the symbols.
"""
symlst = sympy.symbols(symnamelst)
scalar_lst = []
for s in symlst:
tmp = MV(s, 'scalar')
scalar_lst.append(tmp)
return(scalar_lst)
@deprecated(useinstead="sympy.symbols()", issue=3379,
deprecated_since_version="0.7.2")
def make_symbols(symnamelst):
return sympy.symbols(symnamelst)
def israt(numstr):
"""
Test if string represents a rational number.
"""
global NUMPAT
if NUMPAT.match(numstr):
return(1)
return(0)
def dualsort(lst1, lst2):
"""
Inplace dual sort of lst1 and lst2 keyed on sorted lst1.
"""
_indices = range(len(lst1))
_indices.sort(key=lst2.__getitem__)
lst1[:] = map(lst1.__getitem__, _indices)
lst2[:] = map(lst2.__getitem__, _indices)
return
def cp(A, B):
"""
Calculates the commutator product (A*B-B*A)/2 for
the objects A and B.
"""
return(HALF*(A*B - B*A))
def reduce_base(k, base):
"""
If base is a list of sorted integers [i_1,...,i_R] then reduce_base
sorts the list [k,i_1,...,i_R] and calculates whether an odd or even
number of permutations is required to sort the list. The sorted list
is returned and +1 for even permutations or -1 for odd permutations.
"""
if k in base:
return(0, base)
grade = len(base)
if grade == 1:
if k < base[0]:
return(1, [k, base[0]])
else:
return(-1, [base[0], k])
ilo = 0
ihi = grade - 1
if k < base[0]:
return(1, [k] + base)
if k > base[ihi]:
if grade % 2 == 0:
return(1, base + [k])
else:
return(-1, base + [k])
imid = ihi + ilo
if grade == 2:
return(-1, [base[0], k, base[1]])
while True:
if ihi - ilo == 1:
break
if base[imid] > k:
ihi = imid
else:
ilo = imid
imid = (ilo + ihi)/2
if ilo % 2 == 1:
return(1, base[:ihi] + [k] + base[ihi:])
else:
return(-1, base[:ihi] + [k] + base[ihi:])
def sub_base(k, base):
"""
If base is a list of sorted integers [i_1,...,i_R] then sub_base returns
a list with the k^th element removed. Note that k=0 removes the first
element. There is no test to see if k is in the range of the list.
"""
n = len(base)
if n == 1:
return([])
if n == 2:
if k == base[0]:
return([base[1]])
else:
return([base[0]])
return(base[:k] + base[k + 1:])
def magnitude(vector):
"""
Calculate magnitude of vector containing trig expressions
and simplify. This is a hack because of way he sign of
magsq is determined and because of the way that absolute
values are removed.
"""
magsq = sympy.expand((vector | vector)())
magsq = sympy.trigsimp(magsq, deep=True, recursive=True)
#print magsq
magsq_str = sympy.galgebra.latex_ex.LatexPrinter()._print(magsq)
if magsq_str[0] == '-':
magsq = -magsq
mag = unabs(sqrt(magsq))
#print mag
return(mag)
def LaTeX_lst(lst, title=''):
"""
Output a list in LaTeX format.
"""
if title != '':
sympy.galgebra.latex_ex.LaTeX(title)
for x in lst:
sympy.galgebra.latex_ex.LaTeX(x)
return
def unabs(x):
"""
Remove absolute values from expressions so a = sqrt(a**2).
This is a hack.
"""
if type(x) == mul_type:
y = unabs(x.args[0])
for yi in x.args[1:]:
y *= unabs(yi)
return(y)
if type(x) == pow_type:
if x.args[1] == HALF and type(x.args[0]) == add_type:
return(x)
y = 1/unabs(x.args[0])
return(y)
if len(x.args) == 0:
return(x)
if type(x) == abs_type:
return(x.args[0])
return(x)
def function_lst(fstr, xtuple):
sys.stderr.write(fstr + '\n')
fct_lst = []
for xstr in fstr.split():
f = sympy.Function(xstr)(*xtuple)
fct_lst.append(f)
return(fct_lst)
def vector_fct(Fstr, x):
"""
Create a list of functions of arguments x. One function is
created for each variable in x. Fstr is a string that is
the base name of each function while each function in the
list is given the name Fstr+'__'+str(x[ix]) so that if
Fstr = 'f' and str(x[1]) = 'theta' then the LaTeX output
of the second element in the output list would be 'f^{\\theta}'.
"""
nx = len(x)
Fvec = []
for ix in range(nx):
ftmp = sympy.Function(Fstr + '__' + sympy.galgebra.latex_ex.LatexPrinter.str_basic(x[ix]))(*tuple(x))
Fvec.append(ftmp)
return(Fvec)
def print_lst(lst):
for x in lst:
print x
return
def normalize(elst, nname_lst):
"""
Normalize a list of vectors and rename the normalized vectors. 'elist' is the list
(or array) of vectors to be normalized and nname_lst is a list of the names for the
normalized vectors. The function returns the numpy arrays enlst and mags containing
the normalized vectors (enlst) and the magnitudes of the original vectors (mags).
"""
i = 0
mags = numpy.array(MV.n*[ZERO], dtype=numpy.object)
enlst = numpy.array(MV.n*[ZERO], dtype=numpy.object)
for (e, nname) in zip(elst, nname_lst):
emag = magnitude(e)
emaginv = 1/emag
mags[i] = emag
enorm = emaginv*e
enorm.name = nname
enlst[i] = enorm
i += 1
return(enlst, mags)
def build_base(base_index, base_vectors, reverse=False):
base = base_vectors[base_index[0]]
if len(base_index) > 1:
for i in base_index[1:]:
base = base ^ base_vectors[i]
if reverse:
base = base.rev()
return(base)
class MV(object):
is_setup = False
basislabel_lst = 0
curvilinear_flg = False
coords = None
@staticmethod
def pad_zeros(value, n):
"""
Pad list with zeros to length n. If length is > n
truncate list. Return padded list.
"""
nvalue = len(value)
if nvalue < n:
value = value + (n - nvalue)*[ZERO]
if nvalue > n:
value = value[:n]
return(value)
@staticmethod
def define_basis(basis):
"""
Calculates all the MV static variables needed for
basis operations. See reference 5 section 2.
"""
MV.vbasis = basis
MV.vsyms = sympy.symbols(MV.vbasis)
MV.n = len(MV.vbasis)
MV.nrg = range(MV.n)
MV.n1 = MV.n + 1
MV.n1rg = range(MV.n1)
MV.npow = 2**MV.n
MV.index = range(MV.n)
MV.gabasis = [[]]
MV.basis = (MV.n + 1)*[0]
MV.basislabel = (MV.n + 1)*[0]
MV.basis[0] = []
MV.basislabel[0] = '1'
MV.basislabel_lst = [['1']]
MV.nbasis = numpy.array((MV.n + 1)*[1], dtype=numpy.object)
for igrade in range(1, MV.n + 1):
tmp = comb(MV.n, igrade)
MV.gabasis += [tmp]
ntmp = len(tmp)
MV.nbasis[igrade] = ntmp
MV.basis[igrade] = tmp
gradelabels = []
gradelabel_lst = []
for i in range(ntmp):
tmp_lst = []
bstr = ''
for j in tmp[i]:
bstr += MV.vbasis[j]
tmp_lst.append(MV.vbasis[j])
gradelabel_lst.append(tmp_lst)
gradelabels.append(bstr)
MV.basislabel_lst.append(gradelabel_lst)
MV.basislabel[igrade] = gradelabels
MV.basis_map = [{'':0}]
igrade = 1
while igrade <= MV.n:
tmpdict = {}
bases = MV.gabasis[igrade]
ibases = 0
for base in bases:
tmpdict[str(base)] = ibases
ibases += 1
MV.basis_map.append(tmpdict)
igrade += 1
if MV.debug:
print 'basis strings =', MV.vbasis
print 'basis symbols =', MV.vsyms
print 'basis labels =', MV.basislabel
print 'basis =', MV.basis
print 'grades =', MV.nbasis
print 'index =', MV.index
return
@staticmethod
def define_metric(metric):
"""
Calculates all the MV static variables needed for
metric operations. See reference 5 section 2.
"""
if MV.metric_str:
MV.g = []
MV.metric = numpy.array(MV.n*[MV.n*[ZERO]], dtype=numpy.object)
if metric == '':
metric = numpy.array(MV.n*[MV.n*['#']], dtype=numpy.object)
for i in MV.index:
for j in MV.index:
gij = metric[i][j]
if israt(gij):
MV.metric[i][j] = numeric(gij)
else:
if gij == '#':
if i == j:
gij = '(' + MV.vbasis[j] + '**2)'
else:
gij = '(' + MV.vbasis[min(
i, j)] + '.' + MV.vbasis[max(i, j)] + ')'
tmp = sympy.Symbol(gij)
MV.metric[i][j] = tmp
if i <= j:
MV.g.append(tmp)
else:
MV.metric = metric
MV.g = []
for row in metric:
g_row = []
for col in metric:
g_row.append(col)
MV.g.append(g_row)
if MV.debug:
print 'metric =', MV.metric
return
@staticmethod
def define_reciprocal_frame():
"""
Calculates unscaled reciprocal vectors (MV.brecp) and scale
factor (MV.Esq). The ith scaled reciprocal vector is
(1/MV.Esq)*MV.brecp[i]. The pseudoscalar for the set of
basis vectors is MV.E.
"""
if MV.tables_flg:
MV.E = MV.bvec[0]
MV.brecp = []
for i in range(1, MV.n):
MV.E = MV.E ^ MV.bvec[i]
for i in range(MV.n):
tmp = ONE
if i % 2 != 0:
tmp = -ONE
for j in range(MV.n):
if i != j:
tmp = tmp ^ MV.bvec[j]
tmp = tmp*MV.E
MV.brecp.append(tmp)
MV.Esq = (MV.E*MV.E)()
MV.Esq_inv = ONE/MV.Esq
for i in range(MV.n):
MV.brecp[i] = MV.brecp[i]*MV.Esq_inv
return
@staticmethod
def reduce_basis_loop(blst):
"""
Makes one pass through basis product representation for
reduction of representation to normal form.
See reference 5 section 3.
"""
nblst = len(blst)
if nblst <= 1:
return(1)
jstep = 1
while jstep < nblst:
istep = jstep - 1
if blst[istep] == blst[jstep]:
i = blst[istep]
if len(blst) > 2:
blst = blst[:istep] + blst[jstep + 1:]
else:
blst = []
if len(blst) <= 1 or jstep == nblst - 1:
blst_flg = 0
else:
blst_flg = 1
return(MV.metric[i][i], blst, blst_flg)
if blst[istep] > blst[jstep]:
blst1 = blst[:istep] + blst[jstep + 1:]
a1 = TWO*MV.metric[blst[jstep]][blst[istep]]
blst = blst[:istep] + [blst[jstep]] + [blst[istep]] + blst[jstep + 1:]
if len(blst1) <= 1:
blst1_flg = 0
else:
blst1_flg = 1
return(a1, blst1, blst1_flg, blst)
jstep += 1
return(1)
@staticmethod
def reduce_basis(blst):
"""
Repetitively applies reduce_basis_loop to basis
product representation until normal form is
realized. See reference 5 section 3.
"""
if blst == []:
blst_coef = []
blst_expand = []
for i in MV.n1rg:
blst_coef.append([])
blst_expand.append([])
blst_expand[0].append([])
blst_coef[0].append(ONE)
return(blst_coef, blst_expand)
blst_expand = [blst]
blst_coef = [ONE]
blst_flg = [1]
while test_int_flgs(blst_flg):
for i in range(len(blst_flg)):
if blst_flg[i]:
tmp = MV.reduce_basis_loop(blst_expand[i])
if tmp == 1:
blst_flg[i] = 0
else:
if len(tmp) == 3:
blst_coef[i] = tmp[0]*blst_coef[i]
blst_expand[i] = tmp[1]
blst_flg[i] = tmp[2]
else:
blst_coef[i] = -blst_coef[i]
blst_flg[i] = 1
blst_expand[i] = tmp[3]
blst_coef.append(-blst_coef[i]*tmp[0])
blst_expand.append(tmp[1])
blst_flg.append(tmp[2])
(blst_coef, blst_expand) = MV.combine_common_factors(
blst_coef, blst_expand)
return(blst_coef, blst_expand)
@staticmethod
def combine_common_factors(blst_coef, blst_expand):
new_blst_coef = []
new_blst_expand = []
for i in range(MV.n1):
new_blst_coef.append([])
new_blst_expand.append([])
nfac = len(blst_coef)
for ifac in range(nfac):
blen = len(blst_expand[ifac])
new_blst_coef[blen].append(blst_coef[ifac])
new_blst_expand[blen].append(blst_expand[ifac])
for i in range(MV.n1):
if len(new_blst_coef[i]) > 1:
MV.contract(new_blst_coef[i], new_blst_expand[i])
return(new_blst_coef, new_blst_expand)
@staticmethod
def contract(coefs, bases):
dualsort(coefs, bases)
n = len(bases) - 1
i = 0
while i < n:
j = i + 1
if bases[i] == bases[j]:
coefs[i] += coefs[j]
bases.pop(j)
coefs.pop(j)
n -= 1
else:
i += 1
n = len(coefs)
i = 0
while i < n:
if coefs[i] == ZERO:
coefs.pop(i)
bases.pop(i)
n -= 1
else:
i += 1
return
@staticmethod
def convert(coefs, bases):
mv = MV()
mv.bladeflg = 0
for igrade in MV.n1rg:
coef = coefs[igrade]
base = bases[igrade]
if len(coef) > 0:
nbases = MV.nbasis[igrade]
mv.mv[igrade] = numpy.array(nbases*[ZERO], dtype=numpy.object)
nbaserg = range(len(base))
for ibase in nbaserg:
if igrade > 0:
k = MV.basis[igrade].index(base[ibase])
mv.mv[igrade][k] = coef[ibase]
else:
mv.mv[igrade] = numpy.array(
[coef[0]], dtype=numpy.object)
return(mv)
@staticmethod
def set_str_format(str_mode=0):
MV.str_mode = str_mode
return
@staticmethod
def str_rep(mv):
"""
Converts internal representation of a multivector to a string
for outputting. If lst_mode = 1, str_rep outputs a list of
strings where each string contains one multivector coefficient
concatenated with the corresponding base or blade symbol.
MV.str_mode Effect
0 Print entire multivector on one line (default)
1 Print each grade on a single line
2 Print each base on a single line
"""
if MV.bladeprint:
mv.convert_to_blades()
labels = MV.bladelabel
else:
if not mv.bladeflg:
labels = MV.basislabel
else:
labels = MV.bladelabel
mv.compact()
if isinstance(mv.mv[0], int):
value = ''
else:
value = (mv.mv[0][0]).__str__()
value = value.replace(' ', '')
dummy = sympy.Dummy('dummy')
for igrade in MV.n1rg[1:]:
if isinstance(mv.mv[igrade], numpy.ndarray):
j = 0
for x in mv.mv[igrade]:
if x != ZERO:
xstr = (x*dummy).__str__()
xstr = xstr.replace(' ', '')
if xstr[0] != '-' and len(value) > 0:
xstr = '+' + xstr
if xstr.find('_dummy') < 2 and xstr[-5:] != '_dummy':
xstr = xstr.replace(
'_dummy*', '') + '*' + labels[igrade][j]
else:
xstr = xstr.replace('_dummy', labels[igrade][j])
if MV.str_mode == 2:
xstr += '\n'
value += xstr
j += 1
if MV.str_mode == 1:
value += '\n'
if value == '':
value = '0'
#value = value.replace(' ','')
value = value.replace('dummy', '1')
return(value)
@staticmethod
def xstr_rep(mv, lst_mode=0):
"""
Converts internal representation of a multivector to a string
for outputing. If lst_mode = 1, str_rep outputs a list of
strings where each string contains one multivector coefficient
concatenated with the corresponding base or blade symbol.
"""
if lst_mode:
outlst = []
if MV.bladeprint:
mv.convert_to_blades()
labels = MV.bladelabel
else:
if not mv.bladeflg:
labels = MV.basislabel
else:
labels = MV.bladelabel
value = ''
for igrade in MV.n1rg:
tmp = []
if isinstance(mv.mv[igrade], numpy.ndarray):
j = 0
for x in mv.mv[igrade]:
if x != ZERO:
xstr = x.__str__()
if xstr == '+1' or xstr == '1' or xstr == '-1':
if xstr == '+1' or xstr == '1':
xstr = '+'
else:
xstr = '-'
else:
if xstr[0] != '+':
xstr = '+(' + xstr + ')'
else:
xstr = '+(' + xstr[1:] + ')'
value += xstr + labels[igrade][j]
if MV.str_mode and not lst_mode:
value += value + '\n'
if lst_mode:
tmp.append(value)
j += 1
if lst_mode:
if len(tmp) > 0:
outlst.append(tmp)
value = ''
if not lst_mode:
if len(value) > 1 and value[0] == '+':
value = value[1:]
if len(value) == 0:
value = '0'
else:
value = outlst
return(value)
@staticmethod
def setup(basis, metric='', rframe=False, coords=None, debug=False, offset=0):
"""
MV.setup initializes the MV class by calculating the static
multivector tables required for geometric algebra operations
on multivectors. See reference 5 section 2 for details on
basis and metric arguments.
"""
MV.is_setup = True
MV.metric_str = False
MV.debug = debug
MV.bladeprint = 0
MV.tables_flg = 0
MV.str_mode = 0
MV.basisroot = ''
MV.index_offset = offset
if coords is None:
MV.coords = None
else:
MV.coords = tuple(coords)
rframe = True
if type(basis) == str:
basislst = basis.split()
if len(basislst) == 1:
MV.basisroot = basislst[0]
basislst = []
for coord in coords:
basislst.append(MV.basisroot + '_' + str(coord))
MV.define_basis(basislst)
if type(metric) == str:
MV.metric_str = True
if len(metric) > 0:
if metric[0] == '[' and metric[-1] == ']':
tmps = metric[1:-1].split(',')
N = len(tmps)
metric = []
itmp = 0
for tmp in tmps:
xtmp = N*['0']
xtmp[itmp] = tmp
itmp += 1
metric.append(xtmp)
else:
tmps = metric.split(',')
metric = []
for tmp in tmps:
xlst = tmp.split()
xtmp = []
for x in xlst:
xtmp.append(x)
metric.append(xtmp)
MV.define_metric(metric)
MV.multiplication_table()
MV.blade_table()
MV.inverse_blade_table()
MV.tables_flg = 1
isym = 0
MV.bvec = []
for name in MV.vbasis:
bvar = MV(value=isym, mvtype='basisvector', mvname=name)
bvar.bladeflg = 1
MV.bvec.append(bvar)
isym += 1
if rframe:
MV.define_reciprocal_frame()
MV.I = MV(ONE, 'pseudo', 'I')
MV.ZERO = MV()
Isq = (MV.I*MV.I)()
MV.Iinv = (1/Isq)*MV.I
return MV.bvec
@staticmethod
def set_coords(coords):
MV.coords = coords
return
@staticmethod
def scalar_fct(fct_name):
"""
Create multivector scalar function with name fct_name (string) and
independent variables coords (list of variable). Default variables are
those associated with each dimension of vector space.
"""
phi = sympy.Function(fct_name)(*MV.coords)
Phi = MV(phi, 'scalar')
Phi.name = fct_name
return(Phi)
@staticmethod
def vector_fct(fct_name, vars=''):
"""
Create multivector vector function with name fct_name (string) and
independent variables coords (list of variable). Default variables are
those associated with each dimension of vector space.
"""
if isinstance(vars, str):
Acoefs = vector_fct(fct_name, MV.coords)
else:
Acoefs = numpy.array(MV.n*[ZERO], dtype=numpy.object)
x = MV.coords
if isinstance(vars, sympy.core.symbol.Symbol):
for icoef in MV.nrg:
Acoefs[icoef] = sympy.Function(fct_name + '__' +
sympy.galgebra.latex_ex.LatexPrinter.str_basic(x[icoef]))(vars)
else:
for icoef in MV.nrg:
Acoefs[icoef] = sympy.Function(fct_name + '__' +
sympy.galgebra.latex_ex.LatexPrinter.str_basic(x[icoef]))(*tuple(vars))
A = MV(Acoefs, 'vector', fct_name)
return(A)
@staticmethod
def rebase(x, coords, base_name='', debug=False, debug_level=0):
"""
Define curvilinear coordinates for previously defined vector (multivector) space (MV.setup has been run)
with position vector, x, that is a vector function of the independent coordinates, coords (list of
sympy variables equal in length to dimension of vector space), and calculate:
1. Frame (basis) vectors
2. Normalized frame (basis) vectors.
3. Metric tensor
4. Reciprocal frame vectors
5. Reciprocal metric tensor
6. Connection multivectors
The basis vectors are named with the base_name (string) and a subscript derived from the name of each
coordinate. So that if the base name is 'e' and the coordinated are [r,theta,z] the variable names
of the frame vectors would be e_r, e_theta, and e_z. For LaTeX output the names of the frame vectors
would be e_{r}, e_{\theta}, and e_{z}. Everything needed to compute the geometric, outer, and inner
derivatives of multivector functions in curvilinear coordinates is calculated.
If debug is True all the quantities in the above list are output in LaTeX format.
Currently rebase works with cylindrical and spherical coordinates in any dimension. The limitation is the
ability to automatically simplify complex sympy expressions generated while calculating the quantities in
the above list. This is why the debug option is included. The debug_level can equal 0,1,2, or 3 and
determines how far in the list to calculate (input 0 to do the entire list) while debugging.
"""
#Form root names for basis, reciprocal basis, normalized basis, and normalized reciprocal basis
if base_name == '':
base_name = MV.basisroot + 'prm'
LaTeX_base = sympy.galgebra.latex_ex.LatexPrinter.extended_symbol(
base_name)
bm = '\\bm{' + LaTeX_base + '}'
bmhat = '\\hat{' + bm + '}'
bstr = bmhat + '_{[i_{1},\dots, i_{R}]}'
base_name += 'bm'
base_name_hat = base_name + 'hat'
base_name_lst = []
nbase_name_lst = []
rbase_name_lst = []
rnbase_name_lst = []
coords_lst = []
for coord in coords:
coord_str = sympy.galgebra.latex_ex.LatexPrinter.str_basic(coord)
coords_lst.append(coord_str)
base_name_lst.append(base_name + '_' + coord_str)
rbase_name_lst.append(base_name + '__' + coord_str)
nbase_name_lst.append(base_name_hat + '_' + coord_str)
rnbase_name_lst.append(base_name_hat + '__' + coord_str)
if not (MV.n == len(coords) == len(base_name_lst)):
print 'rebaseMV inputs not congruent:'
print 'MV.n =', MV.n
print 'coords =', coords
print 'bases =', base_name
sys.exit(1)
if isinstance(x, MV):
#Calculate basis vectors from derivatives of position vector x
bases = numpy.array(MV.n*[ZERO], dtype=numpy.object)
i = 0
for coord in coords:
ei = x.diff(coords[i])
ei.set_name(base_name_lst[i])
bases[i] = ei
i += 1
#Calculate normalizee basis vectors and basis vector magnitudes
if debug:
print 'Coordinate Generating Vector'
print x
print 'Basis Vectors'
for base in bases:
print base
else: