-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCpi.py
executable file
·2361 lines (2033 loc) · 74.3 KB
/
Cpi.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/env python
# Copyright (C) 2019 Alireza Rashti #
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
import sympy
from sympy import *
from sympy.tensor.tensor import TensorIndexType, tensor_indices
from sympy.tensor.tensor import TensorHead, substitute_indices
from sympy import symbols, diag
from sympy import Eijk
from collections import OrderedDict
import re
import os
# import subprocess
import argparse
import datetime
# global vars:
CPI__glob_pr_flg = 0
CPI__glob_2dim_flg = 1
CPI__glob_Cpi_version = 3.0
CPI__glob_simplification_flag = -1
CPI__glob_index_stem = "___mu___"
__author__ = "Alireza Rashti"
__date__ = "June 2019"
def main():
print("\nWelcome to Cpi\n")
intro_print()
# check the sympy version:
version_digits = sympy.__version__.split(".")
if float(version_digits[0]) < 1 or float(version_digits[1]) < 5:
raise Exception(
"\nThis script requires sympy version greater than or equal to 1.5.\n"
"Your sympy version is {}".format(sympy.__version__))
# read and parse inputs, e.g., file, flags, etc
inputs = parse_inputs()
# parsing system commands if any.
sys_commands = parse_sys_commands(inputs)
# generate C and python code
file_name = gencode(inputs)
# issue system commands:
issue_system_commands(sys_commands, file_name)
# parsing system commands if any
def parse_sys_commands(arg):
sys_commands = []
for s in arg:
if re.search(r"(?i)^Comm?and", s):
s = re.sub(r'(?i)^Comm?and\["', "", s)
s = re.sub(r'"\]@$', "", s)
sys_commands.append(s)
return sys_commands
# issue system commands on the output file:
def issue_system_commands(sys_commands, file_name):
for c in sys_commands:
cmd = c + " " + file_name
print('Issuing command:\n"{}"\n'.format(cmd))
os.system(cmd)
# subprocess.call("ls")
# subprocess.call([c,file_name])
# generating C code and python code according to the given input file
def gencode(arg):
pr("#")
print("Generating C code ...\n")
# fill Maths info data base
math_db = Maths_Info(arg)
if CPI__glob_pr_flg:
pr("-")
math_db.pr()
pr("-")
# create C file with the name of input file
C_file, file_name = creat_file(arg)
# write and execute python code and realize C instructions due to calculations
C_instructions = exec_pycode(math_db)
# write the C instructions into the given file
write_Ccode(C_instructions, math_db, C_file)
# closing the file
C_file.close()
print("Generating C code --> done! :)\n")
print('C code file is "{}".\n'.format(file_name))
pr("#")
return file_name
# write a C code according to the input file
def write_Ccode(C, CPI__db, Cfile):
print("~~~~~~~> writing C code ...\n")
# execute each C instructions:
N = len(C)
tab = ""
now = datetime.datetime.now()
## NOTE: make sure the following copyright won't get longer than
## 4 lines including '/*' and newlines since some old cpi files
## remove only these beginning 5 lines.
intro = ("/*\n These C codes generated by Cpi version {}\n"
" Copyright (C) 2019-{} Alireza Rashti.\n*/\n\n\n".format(
CPI__glob_Cpi_version, now.year))
fpr(Cfile, intro)
# implement each instruction:
for _ in range(N):
# Ccode
c = C[str(_)]
if c["job"] == "Ccode":
Cpr_str = c["Ccode"] + "\n"
fpr(Cfile, Cpr_str)
if re.search(r"^\\t+", c["Ccode"]):
tab = re.search(r"^\\t+", c["Ccode"]).group(0)
elif re.search(r"^\s+", c["Ccode"]):
tab = re.search(r"^\s+", c["Ccode"]).group(0)
else:
tab = " "
# C declare
elif c["job"] == "Cdeclare":
declare_thingsC(CPI__db, Cfile, tab, c["declare_bin"])
# populate
elif c["job"] == "Cpopulate":
Cpopulate(CPI__db, Cfile, c["Cpopulate"], tab)
elif c["job"] == "Pcode":
continue
# calculations
elif c["job"] == "calc":
point = CPI__db.point_symb
# if it has components
if c["indexed"] == 1:
sol = c[c["calc"]]
for k in sol:
ccode = "{0}double {1} =\n".format(tab, k)
rhs = sol[k]
# for the given fields that need to be evaluated on manifold point or has special arguments (C_arg)
for symb in CPI__db.symbols_ld:
if symb["obj"] == "field":
if "C_argument" in symb.keys():
array = set(symb["array_comp"]) # remove the redundants
for e in array:
if e != "0." and not re.search(r"^-", e):
Carg = symb[symb["C_argument"]]
Carg = re.sub(r"name", e, Carg)
################ if there is U? or D? ###################
if re.search(r"(?i)[UD]+\?", Carg):
Carg_indices = re.findall(r"[UD]+\?", Carg)
lCarg_indices = len(Carg_indices)
# substitute the question mark:
for _ in range(lCarg_indices):
Carg_indices[_] = re.sub(r"\?", "", Carg_indices[_])
# some checks rank and type:
if lCarg_indices != int(symb["rank"]): # check rank agrees
raise Exception(
"The indices for C_arg are not matched between {} and {}.\n"
.format(
symb["name"],
symb[symb["C_argument"]],
))
t0 = 0
for t in symb["type"]: # check type agrees
if not re.search(
r"(?i){}".format(Carg_indices[t0]),
t,
):
raise Exception(
"The indices for C_arg are not matched between {} and {}.\n"
.format(
symb["name"],
symb[symb["C_argument"]],
))
else:
t0 += 1
# parse the indices of component:
suffix = re.search(r"_[UD\d]+$", e).group(0)
# suffix = re.sub(r'^_','',suffix)
indices = re.findall(r"\d", suffix)
# now substitue indices in Carg
Carg_split = Carg.split(",")
lCarg_split = len(Carg_split)
c1 = 0
c2 = 0
Carg2 = ""
for p in Carg_split:
if re.search(r"(?i)[UD]+\?", p):
Carg_split[c1] = re.sub(
r"(?i)[UD]+\?",
"{}".format(indices[c2]),
p,
)
c2 += 1
if c1 < lCarg_split - 1:
Carg2 += (Carg_split[c1] + ",")
c1 += 1
Carg2 += Carg_split[c1 - 1]
Carg = Carg2
################ END of if there is U? or D? ###################
rhs = re.sub(
r"\b{}\b".format(e),
"{}{}".format(e, Carg),
rhs,
)
else: # if there is no C_arg
array = set(symb["array_comp"]) # remove the redundants
for e in array:
if e != "0." and not re.search(r"^-", e):
rhs = re.sub(
r"\b{}\b".format(e),
"{}[{}]".format(e, point),
rhs,
)
ccode += "{};\n".format(rhs)
ccode = re.sub(r"\b1.0\*\b", "", ccode)
ccode = style_eq_pr(ccode, tab)
fpr(Cfile, ccode)
# if doesn't have components
else:
ccode = "{0}double {1} =\n".format(tab, c["calc"])
rhs = c[c["calc"]]
# for the given fields that need to be evaluated on manifold point or has special arguments (C_arg)
for symb in CPI__db.symbols_ld:
if symb["obj"] == "field":
if "C_argument" in symb.keys():
array = set(symb["array_comp"]) # remove the redundants
for e in array:
if e != "0." and not re.search(r"^-", e):
Carg = symb[symb["C_argument"]]
Carg = re.sub(r"name", e, Carg)
################ if there is U? or D? ###################
if re.search(r"(?i)[UD]+\?", Carg):
Carg_indices = re.findall(r"[UD]+\?", Carg)
lCarg_indices = len(Carg_indices)
# substitute the question mark:
for _ in range(lCarg_indices):
Carg_indices[_] = re.sub(r"\?", "", Carg_indices[_])
# some checks rank and type:
if lCarg_indices != int(symb["rank"]): # check rank agrees
raise Exception(
"The indices for C_arg are not matched between {} and {}.\n"
.format(
symb["name"],
symb[symb["C_argument"]],
))
t0 = 0
for t in symb["type"]: # check type agrees
if not re.search(
r"(?i){}".format(Carg_indices[t0]),
t,
):
raise Exception(
"The indices for C_arg are not matched between {} and {}.\n"
.format(
symb["name"],
symb[symb["C_argument"]],
))
else:
t0 += 1
# parse the indices of component:
suffix = re.search(r"_[UD\d]+$", e).group(0)
# suffix = re.sub(r'^_','',suffix)
indices = re.findall(r"\d", suffix)
# now substitue indices in Carg
Carg_split = Carg.split(",")
lCarg_split = len(Carg_split)
c1 = 0
c2 = 0
Carg2 = ""
for p in Carg_split:
if re.search(r"(?i)[UD]+\?", p):
Carg_split[c1] = re.sub(
r"(?i)[UD]+\?",
"{}".format(indices[c2]),
p,
)
c2 += 1
if c1 < lCarg_split - 1:
Carg2 += Carg_split[c1] + ","
c1 += 1
Carg2 += Carg_split[c1 - 1]
Carg = Carg2
################ END of if there is U? or D? ###################
rhs = re.sub(
r"\b{}\b".format(e),
"{}{}".format(e, Carg),
rhs,
)
else: # if there is no C_arg
array = set(symb["array_comp"]) # remove the redundants
for e in array:
if e != "0." and not re.search(r"^-", e):
rhs = re.sub(
r"\b{}\b".format(e),
"{}[{}]".format(e, point),
rhs,
)
ccode += "{};\n".format(rhs)
ccode = re.sub(r"\b1.0\*\b", "", ccode)
ccode = style_eq_pr(ccode, tab)
fpr(Cfile, ccode)
else:
raise Exception("No job!")
# populating component in C
def Cpopulate(CPI__db, C_file, pop, tab):
fpr(C_file, "\n")
sp = pop.split("=")
lhs = sp[0]
rhs = sp[1]
# check both lhs have same rank and symmetry
lhs_obj = []
rhs_obj = []
flg1 = 1
flg2 = 1
for obj in CPI__db.symbols_ld:
if obj["name"] == lhs and flg1:
lhs_obj = obj
flg1 = 0
elif obj["name"] == rhs and flg2:
rhs_obj = obj
flg2 = 0
elif not flg1 and not flg2:
break
try:
if rhs_obj["obj"] != "local":
raise Exception(
"The Right hand side in Cpopulate[{}] cannot be used for assignment.".
format(pop))
except:
raise Exception(
"The Right hand side in Cpopulate[{}] cannot be used for assignment.".
format(pop))
if lhs_obj["rank"] != rhs_obj["rank"]:
raise Exception("Ranks are not equal for Cpopulate[{}].".format(pop))
if "symmetry" in rhs_obj.keys() or "symmetry" in lhs_obj.keys():
try:
# check all symmetries exist
for s in lhs_obj["symmetry"]:
if s not in rhs_obj["symmetry"]:
raise Exception(
"Symmetries are not equal for Cpopulate[{}].".format(pop))
for s in rhs_obj["symmetry"]:
if s not in lhs_obj["symmetry"]:
raise Exception(
"Symmetries are not equal for Cpopulate[{}].".format(pop))
except:
raise Exception("Symmetries are not equal for Cpopulate[{}].".format(pop))
# now populate:
lhs_cmp = ordered(set(lhs_obj["array_comp"]))
for cmp in lhs_cmp:
if cmp != "0." and not re.search(r"^-", cmp):
suffix = re.sub(r"^{}".format(lhs_obj["name"]), "", cmp)
rhs_cmp = rhs_obj["name"] + suffix
ccode = (tab + cmp + "[" + CPI__db.point_symb + "]" + " = " + rhs_cmp +
";" + "\n")
fpr(C_file, ccode)
# write and execute the python code according to the input file
# and realize C instructions due to calculations
# NOTE: exec() function has access to the local variable of the
# exec_pycode() function. as a result, it might happen that this
# variables have the similar name as what written in the input file!
# to fix this, each variable's name should have peculiar name.
def exec_pycode(CPI__db):
print("~~~~~~~> writing and executing sympy code ...\n")
py_head = ""
C_instructions = dict()
repl = "Tensors_db"
# declare symbols
for s in CPI__db.symbols_ld:
if ("KD" == s["name"] or "EIJK" == s["name"] or
re.search(r"KD.+i", s["name"])):
continue
if "array_comp" in s.keys():
arry_set = sorted(set(s["array_comp"])) # reduce the redundants
for comp in arry_set:
# No 0 and - sign comming from symmetry
if comp != "0." and not re.search(r"^-", comp):
py_head += "{0:20} = symbols('{0}')\n".format(comp)
# declare functions:
for s in CPI__db.symbols_ld:
if s["obj"] == "function":
py_head += "{0:20} = Function('{0}')\n".format(s["name"])
# declare indices
py_head += 'L = TensorIndexType("L",dim = {})\n'.format(CPI__db.dim_i)
for ind in CPI__db.indices_s:
py_head += '{0:5} = tensor_indices("{0}",L)\n'.format(ind)
# declare tensors
for obj in CPI__db.symbols_ld:
if (obj["obj"] == "field" or
obj["obj"] == "local") and obj["type"] != "scalar":
n = int(obj["rank"])
L = "["
ones = "["
for i in range(n - 1):
L += "L,"
ones += "[1],"
L += "L]"
ones += "[1]]"
# py_head +='{0:20} = TensorHead("{0}",{1},{2})\n'.format(obj['name'],L,ones)
# the above line was used for sympy 1.4
py_head += '{0:20} = TensorHead("{0}",{1})\n'.format(obj["name"], L)
# populate tensors
L = "diag("
for i in range(CPI__db.dim_i - 1):
L += "1.,"
L += "1.)"
indices = indices_tuple(CPI__db, CPI__db.dim_i)
py_head += "{} = {{L:{}}}\n".format(repl, L)
for obj in CPI__db.symbols_ld:
if (obj["obj"] == "field" or
obj["obj"] == "local") and obj["type"] != "scalar":
matrix = "{}".format(obj["matrix_comp"])
matrix = re.sub(r"'", "", matrix)
indices = indices_tuple(CPI__db, int(obj["rank"]))
py_head += "{0}.update({{{1}{2}:{3}}})\n".format(repl,
obj["name"],
indices,
matrix)
n = len(CPI__db.instruction_dd)
C_instructions = dict() # C instructions
for _i in range(n):
py_code = py_head
# evaluate equations and expand indices
eq_sol = ""
extra_ind = set()
if CPI__db.instruction_dd[str(_i)]["job"] == "Ccode":
job = dict()
job["job"] = "Ccode"
job["Ccode"] = CPI__db.instruction_dd[str(_i)]["Ccode"]
C_instructions[str(_i)] = job
elif CPI__db.instruction_dd[str(_i)]["job"] == "Cdeclare":
job = dict()
job["job"] = "Cdeclare"
job["declare_bin"] = CPI__db.instruction_dd[str(_i)]["declare_bin"]
C_instructions[str(_i)] = job
elif CPI__db.instruction_dd[str(_i)]["job"] == "Cpopulate":
job = dict()
job["job"] = "Cpopulate"
job["Cpopulate"] = CPI__db.instruction_dd[str(_i)]["Cpopulate"]
C_instructions[str(_i)] = job
elif CPI__db.instruction_dd[str(_i)]["job"] == "Pcode":
job = dict()
job["job"] = "Pcode"
C_instructions[str(_i)] = job
py_head += CPI__db.instruction_dd[str(_i)]["Pcode"]
py_head += "\n"
elif CPI__db.instruction_dd[str(_i)]["job"] == "calc":
job = dict()
job["job"] = "calc"
calc = CPI__db.instruction_dd[str(_i)]
eq = calc["calc"].split("=")
lhsO = eq[0] # O for original
rhsO = eq[1] # O for original
lhsA = lhsO # A for Amenable
rhsA = rhsO # A for Amenable
print("-> eq: {} ...\n".format(calc["calc"]))
# if lhs is tensorial:
if re.search(r"\([-\w,]+\)", lhsA):
lhsA = re.sub(r"\([-\w,]+\)", "", lhsA)
eqA = "{:14}".format(lhsA) + "= " + rhsA + "\n"
# making C instructions the syntax is as follows:
# C_instructions[job_number][lhs_name][lhs_component] = rhs_components
job["calc"] = lhsA
subjob = dict()
arry_set = set()
lhs_obj = dict()
comp_flg = 0
lhs_rank = 0
for s in CPI__db.symbols_ld:
if s["name"] == lhsA and "array_comp" in s.keys():
arry_set = set(s["array_comp"]) # reduce the redundants
lhs_obj = s
lhs_rank = int(s["rank"])
comp_flg = 1
if comp_flg == 1:
for comp in arry_set:
# 0 and - sign comming from symmetry
if not re.search(r"^0", comp) and not re.search(r"^-", comp):
subjob[comp] = ""
# NOTE: in python 2 the order is NOT kept when new entries
# are added to a dict.
subjob = OrderedDict(sorted(subjob.items()))
sol = "" # C solution
unmatched_indices = list()
# if lhs is not tensorial
if not re.search(r"\([-\w,]+\)", lhsO):
job["indexed"] = 0
sol = 'try:\n\tC_instructions["{0}"]["{1}"] = ccode(my_simplify(({1}.substitute_indices().replace_with_arrays({2})).doit()))\n'.format(
str(_i), lhsA, repl)
# sol += 'except 1:\n\tC_instructions["{0}"]["{1}"] = ccode(my_simplify({1}.replace_with_arrays({2})))\n'.format(str(_i),lhsA,repl)
# sol += 'except AttributeError:\n\tC_instructions["{0}"]["{1}"] = ccode(my_simplify({1}.doit()))\n'.format(str(_i),lhsA,repl)
sol += 'except:\n\tC_instructions["{0}"]["{1}"] = ccode(my_simplify({1}))\n'.format(
str(_i), lhsA, repl)
# sol += 'except:\n\tC_instructions["{0}"]["{1}"] = ccode(my_simplify({1}))\n'.format(str(_i),lhsA,repl)
sol += "try:\n\tres = str(type({}.replace_with_arrays({})))\n".format(
lhsA, repl)
sol += "\tif 'ImmutableDenseNDimArray' in res:\n"
sol += "\t\tunmatched_indices.append('yes')\n"
sol += "except:\n\tunmatched_indices.append('no')\n"
# if lhs is tensorial
else:
assert comp_flg == 1
job["indexed"] = 1
## get rhs free indices, ex: g(i,j) = ... => repl_indices = [i,j]
repl_indices = re.search(r"\([-\w,]+\)",
lhsO).group(0) # only - sign allowed
repl_indices = re.sub(r"^\(", "[", repl_indices)
repl_indices = re.sub(r"\)$", "]", repl_indices)
repl_indices = re.sub(r"-", "", repl_indices)
for comp in arry_set:
# note 0 and - sign comming from symmetry
if not re.search(r"^0", comp) and not re.search(r"^-", comp):
# getting indices:
e = re.sub(r"{}_".format(lhsA), "", comp)
e = re.sub(r"[UD]", " ", e)
index = e.split(" ")
index.remove("")
n = len(index)
suffix = "{0}.substitute_indices().replace_with_arrays({1},{2})[".format(
lhsA, repl, repl_indices)
for i in range(n - 1):
suffix += "{},".format(int(index[i]))
suffix += "{}]".format(int(index[n - 1]))
sol += 'try:\n\tC_instructions["{0}"]["{1}"]["{2}"] = ccode(my_simplify(({3}).doit()))\n'.format(
str(_i), lhsA, comp, suffix)
sol += 'except:\n\tC_instructions["{0}"]["{1}"]["{2}"] = ccode(my_simplify({3}))\n'.format(
str(_i), lhsA, comp, suffix)
eqA = "{:14}".format(lhsA) + "= " + rhsA + "\n"
eq_sol += eqA + sol
job[lhsA] = subjob
C_instructions[str(_i)] = job
for ind in extra_ind:
py_code += '{0:5} = tensor_indices("{0}",L)\n'.format(ind)
py_code += eq_sol
if CPI__glob_pr_flg:
pr("-")
print("sympy code for {}:".format(calc["calc"]))
print(py_code)
pr("-")
exec(py_code)
if len(unmatched_indices) == 1:
if unmatched_indices[0] == "yes":
raise Exception(
"\nIn eq: {}\nthe free indices are not matched!\n".format(
calc["calc"]))
try:
print("-> eq: {} {}\n".format(calc["calc"], "\u2713"))
except:
print("-> eq: {} done.\n".format(calc["calc"]))
else:
raise Exception("No job")
return C_instructions
# declare thins in C file as it is given from the input
def declare_thingsC(CPI__db, C_file, tab, bin):
# fpr(C_file,'\n')
for obj in CPI__db.symbols_ld:
# for each user call declare we have declare_bin thus:
if not "declare_bin" in obj.keys():
continue
# if bin is not matched skip
if obj["declare_bin"] != bin:
continue
# variables:
if obj["obj"] == "variable":
if obj["Ccall"] == "Ccode":
fpr(C_file, obj["Ccode"])
elif re.search(r"C_macro", obj["Ccall"]):
Cstr = C_macro_replace_built_in(obj[obj["Ccall"]],
obj["name"],
obj["name"],
"0",
tab)
fpr(C_file, Cstr)
elif obj["Ccall"] == "none":
continue
else:
raise Exception("\n No method to declare {} in C.".format(obj["name"]))
# scalars:
elif obj["obj"] == "field" and obj["type"] == "scalar":
if obj["Ccall"] == "Ccode":
fpr(C_file, obj["Ccode"])
elif re.search(r"C_macro", obj["Ccall"]):
Cstr = C_macro_replace_built_in(obj[obj["Ccall"]],
obj["name"],
obj["name"],
"0",
tab)
fpr(C_file, Cstr)
elif obj["Ccall"] == "none":
continue
else:
raise Exception("\n No method to declare {} in C.".format(obj["name"]))
# tensors:
elif obj["obj"] == "field" and obj["type"] != "scalar":
if not "Ccall" in obj.keys():
raise Exception("\n No method to declare {} in C.".format(obj["name"]))
elif obj["Ccall"] == "Ccode":
fpr(C_file, obj["Ccode"])
elif re.search(r"C_macro", obj["Ccall"]):
array = sorted(set(obj["array_comp"]))
comp_counter = 0
for cmp in array: # for each component
if cmp != "0." and not re.search(r"^-", cmp):
Cstr = C_macro_replace_built_in(
obj[obj["Ccall"]],
cmp,
obj["name"],
str(comp_counter),
tab,
)
fpr(C_file, Cstr)
comp_counter += 1
elif obj["Ccall"] == "none":
continue
else:
raise Exception("\n No method to declare {} in C.".format(obj["name"]))
# fpr(C_file,"\n\n")
# populating components of the given objects in matrix and array
def populate_components(obj, CPI__db):
if obj["obj"] == "variable":
return [obj["name"]], [obj["name"]]
elif (obj["obj"] == "field" or
obj["obj"] == "local") and obj["type"] == "scalar":
return [obj["name"]], [obj["name"]]
elif (obj["obj"] == "field" or
obj["obj"] == "local") and obj["type"] != "scalar":
return realize_components(obj, CPI__db)
else:
return [], []
# given an object it returns list of components of the object according
# to the symmetry of the objects and type and rank in array format and indexed obj format
def realize_components(obj, CPI__db):
name = obj["name"]
if not "rank" in obj.keys():
raise Exception("This object {} does not have rank.\n".format(obj["name"]))
if not "type" in obj.keys():
raise Exception("This object {} does not have type.\n".format(obj["name"]))
if re.search(r"^\d", name):
raise Exception("{} should not start with a number.\n".format(name))
rank = int(obj["rank"])
type = obj["type"]
tab = ""
comp = "'" + name + "_"
append = "'.format("
append2 = "["
indx = 0
code = ""
for i in range(rank): # fors
if i > 0:
append += ","
append2 += ","
tab += "\t"
comp += "{}{{}}".format(type[i])
append += "arg[{}]".format(i)
append2 += "_{}".format(i)
if i > 0:
code += "{}comp{} = []\n".format(tab, i)
code += "{}for _{} in range({}):\n".format(tab, i, CPI__db.dim_i)
indx = i
# populate the whole tensor with no symmetry
tab += "\t"
append += ")"
append2 += "]"
code += "{}arg = {}\n".format(tab, append2)
code += "{}comp{} = {}{}\n".format(tab, indx + 1, comp, append)
code += "{}array.append(comp{})\n".format(tab, indx + 1)
code += "{}comp{}.append(comp{})\n".format(tab, indx, indx + 1)
# going upward of the nested loop
for i in range(rank - 1, 0, -1):
tab = re.sub(r"\s{1}?$", "", tab)
code += "{}comp{}.append(comp{})\n".format(tab, i - 1, i)
comp0 = [] # matrix format of the indexed_obj (misnomer)
array = [] # array format of the the indexed_obj
try:
exec(code)
except:
raise Exception("Cannot populate components of '{}'!".format(name))
# if there is some symmetry
if len(obj["symmetry"]) != 0:
# loop over all symmetries and modify the components accordingly
for s in obj["symmetry"]:
comp0, array = reduce_symm_components(comp0, s, obj, CPI__db)
indexed_obj = comp0
return indexed_obj, array
# realize the given equation in python
def realize_eq_py(CPI__db, eq):
sympy_defined = [] # dir(sympy)
sympy_defined.append("L")
# checkup for symbols and add new symbols if necessary
parts = eq.split("=")
lhs = parts[0]
rhs = parts[1]
# check if the symbols in lhs is not already defined
name = re.sub(r"(?<=\w)\({1}(-?[a-zA-Z]+\w?,?)+\){1}", "", lhs)
for obj in CPI__db.symbols_ld:
if obj["name"] == name:
print("{} has been defined more than one time.\n"
"For each new definition one must use new name.\n".format(lhs))
raise Exception("{}={}\n{} is protected.\n".format(lhs, rhs, obj["name"]))
if re.search(r"[\.\+\*/]", lhs):
raise Exception(
"It cannot realize the left hand side of eq:\n{}.".format(eq))
# check if there is rank 3 or higher tensor on rhs with lower indices(covariant)
# as I observed there is a bug in sympy 1.5dev version which cannot correctly
# convert upper indices (contravariant) tensor of rank higher than 2 to lower indices (covariant).
# if they solve this issue, this check can be removed. right now, the way we deal with higher
# rank tensor of 3 or more would be with Kronecker delta (KD). So in the calculation
# we always use contravariant indices and we contract them with using KD as the metric.
for obj in CPI__db.symbols_ld:
if "rank" in obj.keys():
if int(obj["rank"]) > 2:
if re.search(
r"\b{}\({{1}}[\w,\-]*\-[\w,\-]*\){{1}}".format(obj["name"]),
rhs,
):
raise Exception(
"\nEq: {} got problem.\nPlease read the following:\n".format(eq) +
"I observed there is a bug in sympy 1.4 and higher versions which cannot correctly\n"
"convert upper indices (contravariant) tensor of rank higher than 2 to lower indices (covariant).\n"
"If they solve this issue, this check can be removed. right now, the way we deal with higher\n"
"rank tensor of 3 or more will be with Kronecker delta (KD). So in the calculation\n"
"we always use contravariant indices and we contract them with using KD as the metric.\n"
"For example:\n"
"cont = x(i,j,k)*x(-i,-j,-k) -> cont = x(i,j,k)*x(l,m,n)*KD(-i,-l)*KD(-j,-m)*KD(-k,-n).\n"
)
# now since this object is not defined let's add it to the CPI__db
new_obj = dict()
new_obj["name"] = name
if name in sympy_defined:
raise Exception(
"The name {} is protected for Sympy library, use another name.".format(
name))
new_obj["obj"] = "local"
rank = 0
if re.search(r"\(.*\)", lhs):
rank = len(lhs.split(",")) # e.g psi(i,j) would be 2
new_obj["rank"] = str(rank)
# type:
if rank != 0:
ty = re.sub(r"^\w+\(", "", lhs)
ty = re.sub(r"\)$", "", ty)
piece = ty.split(",")
type = []
for p in piece:
if re.search(r"^-\w+", p):
type.append("D")
else:
type.append("U")
new_obj["type"] = type
else:
new_obj["type"] = "scalar"
CPI__db.symbols_ld.append(new_obj)
# get all of the symbols in rhs by cutting their indices
trimmed = rhs
# exception is for integrate, which might need extra symbol
# so I cut it off completly
if "integrate" in rhs:
trimmed = re.sub(r"integrate\([\w\-\*\+/\(\)]+,\(?[\w\-\*\+/,]+\)?\)",
"1.",
trimmed)
# get rid of tensor indices
trimmed = re.sub(r"(?<=\w)\({1}(-?[a-zA-Z]+\w?,?)+\){1}", "", trimmed)
# get rid of sympy functions and pars their argumnets
for s in sympy_defined:
if re.search(r"\b{}\b".format(s), rhs):
# if function:
if re.search(r"\b{}\(".format(s), trimmed):
trimmed = re.sub(r"\b{}".format(s), "1.*", trimmed)
trimmed = re.sub(r",".format(s), "+", trimmed)
# if constant number:
if re.search(r"\b{}\b".format(s), trimmed):
trimmed = re.sub(r"{}".format(s), "1.", trimmed)
# some light check if the symbols in rhs all defined
# there might some quantites scape from this check but will be catch later
code = str()
N = len(CPI__db.symbols_ld)
for _ in range(N - 1):
obj = CPI__db.symbols_ld[_]
code += '{0:10} = symbols("{0}")\n'.format(obj["name"])
# add kronecker delta and levi civita too
code += '{0:10} = symbols("{0}")\n'.format("KD")
code += '{0:10} = symbols("{0}")\n'.format("KD0i")
code += '{0:10} = symbols("{0}")\n'.format("KD1i")
code += '{0:10} = symbols("{0}")\n'.format("KD2i")
code += '{0:10} = symbols("{0}")\n'.format("KD3i")
code += '{0:10} = symbols("{0}")\n'.format("EIJK")
code += "expr = {}\n".format(trimmed)
code += "___t___ = srepr(expr)\n"
if trimmed != "":
try:
exec(code)
except:
raise Exception(
"An error occurred in\n{}."
" It might be for either undefined variables or syntax error.".format(
eq))
# given file and string it prints the str into the file
def fpr(f, str):
# take care of \n
if re.search(r".*\\n+.*", str):
if re.search(r'(?:").*\\n.*(?:")', str):
str_quot = re.search(r'(?:").*\\n.*(?:")', str).group(0)
split_quot = str.split(str_quot)
if len(split_quot) == 2:
s0 = split_quot[0].split("\\n")
s0_new = "\n".join(s0)
s1 = split_quot[1].split("\\n")
s1_new = "\n".join(s1)
str = s0_new + str_quot + s1_new
else:
raise Exception(
"It cannot realize \\n in {} due to quotation mark.\n".format(str))
else:
str2 = str.split("\\n")
str = "\n".join(str2)
# take care of \t
if re.search(r".*\\t+.*", str):
str2 = str.split("\\t")
str = " ".join(str2)
f.write(str)
# given a symmetry relation, it finds the kind of symmetry
# and gives a dictionary after realization
def realize_symmetry(relation):
# check the format:
if not re.search(r"^[-\w\(,\)]+=[-+]?[-\w\(,\)]+$", relation):
raise Exception(
"The form of symmetry relation {} is not correct.".format(relation))
# symm or anti-symm
sign = ""
if re.search(r"=-{1}", relation):
sign = "-"
else:
sign = "+"
# find places of permuted indices
perm = []
sym = dict()
l1 = dict()
l2 = dict()
lhs = re.search(r"^[-\w\(,\)]+[^=]", relation).group(0)
rhs = re.search(r"(?:=)[-+]?[-\w\(,\)]+", relation).group(0)
rhs = re.sub(r"=", "", rhs)
# test
# print(lhs)
# print(rhs)
# end
# trims
lhs = re.sub(r"^\w+", "", lhs)
rhs = re.sub(r"^[-+]?\w+", "", rhs)
lhs = re.sub(r"[\(\)]", "", lhs)
rhs = re.sub(r"[\(\)]", "", rhs)
lhs_l = lhs.split(",")
rhs_l = rhs.split(",")
# test
# print(lhs_l)
# print(rhs_l)
# end