applied-ai-018 commited on
Commit
d84d2e6
·
verified ·
1 Parent(s): f624988

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np17.gz +3 -0
  2. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py34_np19.gz +3 -0
  3. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py35_np19.gz +3 -0
  4. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.bz2 +3 -0
  5. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.xz +3 -0
  6. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl +3 -0
  7. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_compressed_pickle_py36_np111.gz +3 -0
  8. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.xz +3 -0
  9. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py35_np19.gz +3 -0
  10. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl +3 -0
  11. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_03.npy +3 -0
  12. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_01.npy +3 -0
  13. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_01.npy +3 -0
  14. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_02.npy +3 -0
  15. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_04.npy +3 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/__init__.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/ast_parser.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/mathematica.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/maxima.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/sym_expr.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/__init__.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_build_autolev_antlr.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_listener_autolev_antlr.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_parse_autolev_antlr.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest11.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest12.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest4.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest6.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest8.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/chaos_pendulum.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/double_pendulum.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/mass_spring_damper.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/non_min_pendulum.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.al +33 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py +55 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al +25 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py +39 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.al +19 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py +31 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.al +20 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py +36 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/parsing/c/__init__.py +1 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/parsing/c/__pycache__/__init__.cpython-310.pyc +0 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/parsing/c/__pycache__/c_parser.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/parsing/c/c_parser.py +1090 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/parsing/fortran/__init__.py +1 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/parsing/fortran/__pycache__/__init__.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/parsing/fortran/__pycache__/fortran_parser.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/parsing/fortran/fortran_parser.py +347 -0
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np17.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1f4e8cccfca94f25ae744d1f050b0734f663263ba38ed0642181404b348b17b
3
+ size 757
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py34_np19.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1abdb3ff5b555831f51f7ff00951e66a49277fc2aa787293f18cf8775be65023
3
+ size 794
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py35_np19.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a56c3fc6e0db3a4102aaed4a19fd4e154eecd956f30b6bf9179897844ed3c01e
3
+ size 790
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.bz2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a18415232322531c918164ae04148ebc258acd3a00fa4529728416755e14a15e
3
+ size 997
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.xz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e9a63dcc7df38ab0a1137a9b44b436b13cebfa300eb19dba4ae4bce50d0fa81
3
+ size 752
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97b9ef2e896104321d3c5ce73b3de504788c38f04f08c8b56d7a29d6d1520a96
3
+ size 1068
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_compressed_pickle_py36_np111.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d56ae75c3a83a0d10f60e657d50e56af6e3addbf2f555e9fc385a6e52e1b32de
3
+ size 800
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.xz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd787f35b3197418d8c7bca77c9dc5ca47b6f22cd24524b3ccd074cf90f893d6
3
+ size 752
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py35_np19.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f33bd8a21a41b729b05dac5deeb0e868f218a092b0e3fe5988094cf167217f6
3
+ size 673
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9da8a3764db121e29d21ade67c9c3426598e76d88deae44cd7238983af8cef73
3
+ size 670
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_03.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a0c45ae2a289841cbeba2443b7ebaa3b31c0a9e9dcc73294aca5729da0092405
3
+ size 236
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_01.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809
3
+ size 120
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_01.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809
3
+ size 120
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_02.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c1cf36cb781fbcc21b953bb0a0b45df092da0eae0e765882e5963ccd70105b1
3
+ size 120
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_04.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ecbe244294ba93e08479b16c1b9a9411e3569ff660ed0459dca1d241381df05
3
+ size 104
env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (319 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/ast_parser.cpython-310.pyc ADDED
Binary file (3.13 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/mathematica.cpython-310.pyc ADDED
Binary file (29 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/maxima.cpython-310.pyc ADDED
Binary file (2.47 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/sym_expr.cpython-310.pyc ADDED
Binary file (8.66 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-310.pyc ADDED
Binary file (30.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_build_autolev_antlr.cpython-310.pyc ADDED
Binary file (2.49 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_listener_autolev_antlr.cpython-310.pyc ADDED
Binary file (50.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_parse_autolev_antlr.cpython-310.pyc ADDED
Binary file (1.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest11.cpython-310.pyc ADDED
Binary file (772 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest12.cpython-310.pyc ADDED
Binary file (806 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest4.cpython-310.pyc ADDED
Binary file (883 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest6.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest8.cpython-310.pyc ADDED
Binary file (1.87 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/chaos_pendulum.cpython-310.pyc ADDED
Binary file (2.11 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/double_pendulum.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/mass_spring_damper.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/non_min_pendulum.cpython-310.pyc ADDED
Binary file (1.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.al ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONSTANTS G,LB,W,H
2
+ MOTIONVARIABLES' THETA'',PHI'',OMEGA',ALPHA'
3
+ NEWTONIAN N
4
+ BODIES A,B
5
+ SIMPROT(N,A,2,THETA)
6
+ SIMPROT(A,B,3,PHI)
7
+ POINT O
8
+ LA = (LB-H/2)/2
9
+ P_O_AO> = LA*A3>
10
+ P_O_BO> = LB*A3>
11
+ OMEGA = THETA'
12
+ ALPHA = PHI'
13
+ W_A_N> = OMEGA*N2>
14
+ W_B_A> = ALPHA*A3>
15
+ V_O_N> = 0>
16
+ V2PTS(N, A, O, AO)
17
+ V2PTS(N, A, O, BO)
18
+ MASS A=MA, B=MB
19
+ IAXX = 1/12*MA*(2*LA)^2
20
+ IAYY = IAXX
21
+ IAZZ = 0
22
+ IBXX = 1/12*MB*H^2
23
+ IBYY = 1/12*MB*(W^2+H^2)
24
+ IBZZ = 1/12*MB*W^2
25
+ INERTIA A, IAXX, IAYY, IAZZ
26
+ INERTIA B, IBXX, IBYY, IBZZ
27
+ GRAVITY(G*N3>)
28
+ ZERO = FR() + FRSTAR()
29
+ KANE()
30
+ INPUT LB=0.2,H=0.1,W=0.2,MA=0.01,MB=0.1,G=9.81
31
+ INPUT THETA = 90 DEG, PHI = 0.5 DEG, OMEGA=0, ALPHA=0
32
+ INPUT TFINAL=10, INTEGSTP=0.02
33
+ CODE DYNAMICS() some_filename.c
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ g, lb, w, h = _sm.symbols('g lb w h', real=True)
7
+ theta, phi, omega, alpha = _me.dynamicsymbols('theta phi omega alpha')
8
+ theta_d, phi_d, omega_d, alpha_d = _me.dynamicsymbols('theta_ phi_ omega_ alpha_', 1)
9
+ theta_dd, phi_dd = _me.dynamicsymbols('theta_ phi_', 2)
10
+ frame_n = _me.ReferenceFrame('n')
11
+ body_a_cm = _me.Point('a_cm')
12
+ body_a_cm.set_vel(frame_n, 0)
13
+ body_a_f = _me.ReferenceFrame('a_f')
14
+ body_a = _me.RigidBody('a', body_a_cm, body_a_f, _sm.symbols('m'), (_me.outer(body_a_f.x,body_a_f.x),body_a_cm))
15
+ body_b_cm = _me.Point('b_cm')
16
+ body_b_cm.set_vel(frame_n, 0)
17
+ body_b_f = _me.ReferenceFrame('b_f')
18
+ body_b = _me.RigidBody('b', body_b_cm, body_b_f, _sm.symbols('m'), (_me.outer(body_b_f.x,body_b_f.x),body_b_cm))
19
+ body_a_f.orient(frame_n, 'Axis', [theta, frame_n.y])
20
+ body_b_f.orient(body_a_f, 'Axis', [phi, body_a_f.z])
21
+ point_o = _me.Point('o')
22
+ la = (lb-h/2)/2
23
+ body_a_cm.set_pos(point_o, la*body_a_f.z)
24
+ body_b_cm.set_pos(point_o, lb*body_a_f.z)
25
+ body_a_f.set_ang_vel(frame_n, omega*frame_n.y)
26
+ body_b_f.set_ang_vel(body_a_f, alpha*body_a_f.z)
27
+ point_o.set_vel(frame_n, 0)
28
+ body_a_cm.v2pt_theory(point_o,frame_n,body_a_f)
29
+ body_b_cm.v2pt_theory(point_o,frame_n,body_a_f)
30
+ ma = _sm.symbols('ma')
31
+ body_a.mass = ma
32
+ mb = _sm.symbols('mb')
33
+ body_b.mass = mb
34
+ iaxx = 1/12*ma*(2*la)**2
35
+ iayy = iaxx
36
+ iazz = 0
37
+ ibxx = 1/12*mb*h**2
38
+ ibyy = 1/12*mb*(w**2+h**2)
39
+ ibzz = 1/12*mb*w**2
40
+ body_a.inertia = (_me.inertia(body_a_f, iaxx, iayy, iazz, 0, 0, 0), body_a_cm)
41
+ body_b.inertia = (_me.inertia(body_b_f, ibxx, ibyy, ibzz, 0, 0, 0), body_b_cm)
42
+ force_a = body_a.mass*(g*frame_n.z)
43
+ force_b = body_b.mass*(g*frame_n.z)
44
+ kd_eqs = [theta_d - omega, phi_d - alpha]
45
+ forceList = [(body_a.masscenter,body_a.mass*(g*frame_n.z)), (body_b.masscenter,body_b.mass*(g*frame_n.z))]
46
+ kane = _me.KanesMethod(frame_n, q_ind=[theta,phi], u_ind=[omega, alpha], kd_eqs = kd_eqs)
47
+ fr, frstar = kane.kanes_equations([body_a, body_b], forceList)
48
+ zero = fr+frstar
49
+ from pydy.system import System
50
+ sys = System(kane, constants = {g:9.81, lb:0.2, w:0.2, h:0.1, ma:0.01, mb:0.1},
51
+ specifieds={},
52
+ initial_conditions={theta:_np.deg2rad(90), phi:_np.deg2rad(0.5), omega:0, alpha:0},
53
+ times = _np.linspace(0.0, 10, 10/0.02))
54
+
55
+ y=sys.integrate()
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MOTIONVARIABLES' Q{2}', U{2}'
2
+ CONSTANTS L,M,G
3
+ NEWTONIAN N
4
+ FRAMES A,B
5
+ SIMPROT(N, A, 3, Q1)
6
+ SIMPROT(N, B, 3, Q2)
7
+ W_A_N>=U1*N3>
8
+ W_B_N>=U2*N3>
9
+ POINT O
10
+ PARTICLES P,R
11
+ P_O_P> = L*A1>
12
+ P_P_R> = L*B1>
13
+ V_O_N> = 0>
14
+ V2PTS(N, A, O, P)
15
+ V2PTS(N, B, P, R)
16
+ MASS P=M, R=M
17
+ Q1' = U1
18
+ Q2' = U2
19
+ GRAVITY(G*N1>)
20
+ ZERO = FR() + FRSTAR()
21
+ KANE()
22
+ INPUT M=1,G=9.81,L=1
23
+ INPUT Q1=.1,Q2=.2,U1=0,U2=0
24
+ INPUT TFINAL=10, INTEGSTP=.01
25
+ CODE DYNAMICS() some_filename.c
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2')
7
+ q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1)
8
+ l, m, g = _sm.symbols('l m g', real=True)
9
+ frame_n = _me.ReferenceFrame('n')
10
+ frame_a = _me.ReferenceFrame('a')
11
+ frame_b = _me.ReferenceFrame('b')
12
+ frame_a.orient(frame_n, 'Axis', [q1, frame_n.z])
13
+ frame_b.orient(frame_n, 'Axis', [q2, frame_n.z])
14
+ frame_a.set_ang_vel(frame_n, u1*frame_n.z)
15
+ frame_b.set_ang_vel(frame_n, u2*frame_n.z)
16
+ point_o = _me.Point('o')
17
+ particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))
18
+ particle_r = _me.Particle('r', _me.Point('r_pt'), _sm.Symbol('m'))
19
+ particle_p.point.set_pos(point_o, l*frame_a.x)
20
+ particle_r.point.set_pos(particle_p.point, l*frame_b.x)
21
+ point_o.set_vel(frame_n, 0)
22
+ particle_p.point.v2pt_theory(point_o,frame_n,frame_a)
23
+ particle_r.point.v2pt_theory(particle_p.point,frame_n,frame_b)
24
+ particle_p.mass = m
25
+ particle_r.mass = m
26
+ force_p = particle_p.mass*(g*frame_n.x)
27
+ force_r = particle_r.mass*(g*frame_n.x)
28
+ kd_eqs = [q1_d - u1, q2_d - u2]
29
+ forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x)), (particle_r.point,particle_r.mass*(g*frame_n.x))]
30
+ kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u1, u2], kd_eqs = kd_eqs)
31
+ fr, frstar = kane.kanes_equations([particle_p, particle_r], forceList)
32
+ zero = fr+frstar
33
+ from pydy.system import System
34
+ sys = System(kane, constants = {l:1, m:1, g:9.81},
35
+ specifieds={},
36
+ initial_conditions={q1:.1, q2:.2, u1:0, u2:0},
37
+ times = _np.linspace(0.0, 10, 10/.01))
38
+
39
+ y=sys.integrate()
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.al ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONSTANTS M,K,B,G
2
+ MOTIONVARIABLES' POSITION',SPEED'
3
+ VARIABLES O
4
+ FORCE = O*SIN(T)
5
+ NEWTONIAN CEILING
6
+ POINTS ORIGIN
7
+ V_ORIGIN_CEILING> = 0>
8
+ PARTICLES BLOCK
9
+ P_ORIGIN_BLOCK> = POSITION*CEILING1>
10
+ MASS BLOCK=M
11
+ V_BLOCK_CEILING>=SPEED*CEILING1>
12
+ POSITION' = SPEED
13
+ FORCE_MAGNITUDE = M*G-K*POSITION-B*SPEED+FORCE
14
+ FORCE_BLOCK>=EXPLICIT(FORCE_MAGNITUDE*CEILING1>)
15
+ ZERO = FR() + FRSTAR()
16
+ KANE()
17
+ INPUT TFINAL=10.0, INTEGSTP=0.01
18
+ INPUT M=1.0, K=1.0, B=0.2, G=9.8, POSITION=0.1, SPEED=-1.0, O=2
19
+ CODE DYNAMICS() dummy_file.c
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ m, k, b, g = _sm.symbols('m k b g', real=True)
7
+ position, speed = _me.dynamicsymbols('position speed')
8
+ position_d, speed_d = _me.dynamicsymbols('position_ speed_', 1)
9
+ o = _me.dynamicsymbols('o')
10
+ force = o*_sm.sin(_me.dynamicsymbols._t)
11
+ frame_ceiling = _me.ReferenceFrame('ceiling')
12
+ point_origin = _me.Point('origin')
13
+ point_origin.set_vel(frame_ceiling, 0)
14
+ particle_block = _me.Particle('block', _me.Point('block_pt'), _sm.Symbol('m'))
15
+ particle_block.point.set_pos(point_origin, position*frame_ceiling.x)
16
+ particle_block.mass = m
17
+ particle_block.point.set_vel(frame_ceiling, speed*frame_ceiling.x)
18
+ force_magnitude = m*g-k*position-b*speed+force
19
+ force_block = (force_magnitude*frame_ceiling.x).subs({position_d:speed})
20
+ kd_eqs = [position_d - speed]
21
+ forceList = [(particle_block.point,(force_magnitude*frame_ceiling.x).subs({position_d:speed}))]
22
+ kane = _me.KanesMethod(frame_ceiling, q_ind=[position], u_ind=[speed], kd_eqs = kd_eqs)
23
+ fr, frstar = kane.kanes_equations([particle_block], forceList)
24
+ zero = fr+frstar
25
+ from pydy.system import System
26
+ sys = System(kane, constants = {m:1.0, k:1.0, b:0.2, g:9.8},
27
+ specifieds={_me.dynamicsymbols('t'):lambda x, t: t, o:2},
28
+ initial_conditions={position:0.1, speed:-1*1.0},
29
+ times = _np.linspace(0.0, 10.0, 10.0/0.01))
30
+
31
+ y=sys.integrate()
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.al ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MOTIONVARIABLES' Q{2}''
2
+ CONSTANTS L,M,G
3
+ NEWTONIAN N
4
+ POINT PN
5
+ V_PN_N> = 0>
6
+ THETA1 = ATAN(Q2/Q1)
7
+ FRAMES A
8
+ SIMPROT(N, A, 3, THETA1)
9
+ PARTICLES P
10
+ P_PN_P> = Q1*N1>+Q2*N2>
11
+ MASS P=M
12
+ V_P_N>=DT(P_P_PN>, N)
13
+ F_V = DOT(EXPRESS(V_P_N>,A), A1>)
14
+ GRAVITY(G*N1>)
15
+ DEPENDENT[1] = F_V
16
+ CONSTRAIN(DEPENDENT[Q1'])
17
+ ZERO=FR()+FRSTAR()
18
+ F_C = MAG(P_P_PN>)-L
19
+ CONFIG[1]=F_C
20
+ ZERO[2]=CONFIG[1]
env-llmeval/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ q1, q2 = _me.dynamicsymbols('q1 q2')
7
+ q1_d, q2_d = _me.dynamicsymbols('q1_ q2_', 1)
8
+ q1_dd, q2_dd = _me.dynamicsymbols('q1_ q2_', 2)
9
+ l, m, g = _sm.symbols('l m g', real=True)
10
+ frame_n = _me.ReferenceFrame('n')
11
+ point_pn = _me.Point('pn')
12
+ point_pn.set_vel(frame_n, 0)
13
+ theta1 = _sm.atan(q2/q1)
14
+ frame_a = _me.ReferenceFrame('a')
15
+ frame_a.orient(frame_n, 'Axis', [theta1, frame_n.z])
16
+ particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))
17
+ particle_p.point.set_pos(point_pn, q1*frame_n.x+q2*frame_n.y)
18
+ particle_p.mass = m
19
+ particle_p.point.set_vel(frame_n, (point_pn.pos_from(particle_p.point)).dt(frame_n))
20
+ f_v = _me.dot((particle_p.point.vel(frame_n)).express(frame_a), frame_a.x)
21
+ force_p = particle_p.mass*(g*frame_n.x)
22
+ dependent = _sm.Matrix([[0]])
23
+ dependent[0] = f_v
24
+ velocity_constraints = [i for i in dependent]
25
+ u_q1_d = _me.dynamicsymbols('u_q1_d')
26
+ u_q2_d = _me.dynamicsymbols('u_q2_d')
27
+ kd_eqs = [q1_d-u_q1_d, q2_d-u_q2_d]
28
+ forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x))]
29
+ kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u_q2_d], u_dependent=[u_q1_d], kd_eqs = kd_eqs, velocity_constraints = velocity_constraints)
30
+ fr, frstar = kane.kanes_equations([particle_p], forceList)
31
+ zero = fr+frstar
32
+ f_c = point_pn.pos_from(particle_p.point).magnitude()-l
33
+ config = _sm.Matrix([[0]])
34
+ config[0] = f_c
35
+ zero = zero.row_insert(zero.shape[0], _sm.Matrix([[0]]))
36
+ zero[zero.shape[0]-1] = config[0]
env-llmeval/lib/python3.10/site-packages/sympy/parsing/c/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Used for translating C source code into a SymPy expression"""
env-llmeval/lib/python3.10/site-packages/sympy/parsing/c/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (250 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/c/__pycache__/c_parser.cpython-310.pyc ADDED
Binary file (26.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/c/c_parser.py ADDED
@@ -0,0 +1,1090 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external import import_module
2
+ import os
3
+
4
+ cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
5
+
6
+ """
7
+ This module contains all the necessary Classes and Function used to Parse C and
8
+ C++ code into SymPy expression
9
+ The module serves as a backend for SymPyExpression to parse C code
10
+ It is also dependent on Clang's AST and SymPy's Codegen AST.
11
+ The module only supports the features currently supported by the Clang and
12
+ codegen AST which will be updated as the development of codegen AST and this
13
+ module progresses.
14
+ You might find unexpected bugs and exceptions while using the module, feel free
15
+ to report them to the SymPy Issue Tracker
16
+
17
+ Features Supported
18
+ ==================
19
+
20
+ - Variable Declarations (integers and reals)
21
+ - Assignment (using integer & floating literal and function calls)
22
+ - Function Definitions and Declaration
23
+ - Function Calls
24
+ - Compound statements, Return statements
25
+
26
+ Notes
27
+ =====
28
+
29
+ The module is dependent on an external dependency which needs to be installed
30
+ to use the features of this module.
31
+
32
+ Clang: The C and C++ compiler which is used to extract an AST from the provided
33
+ C source code.
34
+
35
+ References
36
+ ==========
37
+
38
+ .. [1] https://github.com/sympy/sympy/issues
39
+ .. [2] https://clang.llvm.org/docs/
40
+ .. [3] https://clang.llvm.org/docs/IntroductionToTheClangAST.html
41
+
42
+ """
43
+
44
+ if cin:
45
+ from sympy.codegen.ast import (Variable, Integer, Float,
46
+ FunctionPrototype, FunctionDefinition, FunctionCall,
47
+ none, Return, Assignment, intc, int8, int16, int64,
48
+ uint8, uint16, uint32, uint64, float32, float64, float80,
49
+ aug_assign, bool_, While, CodeBlock)
50
+ from sympy.codegen.cnodes import (PreDecrement, PostDecrement,
51
+ PreIncrement, PostIncrement)
52
+ from sympy.core import Add, Mod, Mul, Pow, Rel
53
+ from sympy.logic.boolalg import And, as_Boolean, Not, Or
54
+ from sympy.core.symbol import Symbol
55
+ from sympy.core.sympify import sympify
56
+ from sympy.logic.boolalg import (false, true)
57
+ import sys
58
+ import tempfile
59
+
60
+ class BaseParser:
61
+ """Base Class for the C parser"""
62
+
63
+ def __init__(self):
64
+ """Initializes the Base parser creating a Clang AST index"""
65
+ self.index = cin.Index.create()
66
+
67
+ def diagnostics(self, out):
68
+ """Diagostics function for the Clang AST"""
69
+ for diag in self.tu.diagnostics:
70
+ print('%s %s (line %s, col %s) %s' % (
71
+ {
72
+ 4: 'FATAL',
73
+ 3: 'ERROR',
74
+ 2: 'WARNING',
75
+ 1: 'NOTE',
76
+ 0: 'IGNORED',
77
+ }[diag.severity],
78
+ diag.location.file,
79
+ diag.location.line,
80
+ diag.location.column,
81
+ diag.spelling
82
+ ), file=out)
83
+
84
+ class CCodeConverter(BaseParser):
85
+ """The Code Convereter for Clang AST
86
+
87
+ The converter object takes the C source code or file as input and
88
+ converts them to SymPy Expressions.
89
+ """
90
+
91
+ def __init__(self):
92
+ """Initializes the code converter"""
93
+ super().__init__()
94
+ self._py_nodes = []
95
+ self._data_types = {
96
+ "void": {
97
+ cin.TypeKind.VOID: none
98
+ },
99
+ "bool": {
100
+ cin.TypeKind.BOOL: bool_
101
+ },
102
+ "int": {
103
+ cin.TypeKind.SCHAR: int8,
104
+ cin.TypeKind.SHORT: int16,
105
+ cin.TypeKind.INT: intc,
106
+ cin.TypeKind.LONG: int64,
107
+ cin.TypeKind.UCHAR: uint8,
108
+ cin.TypeKind.USHORT: uint16,
109
+ cin.TypeKind.UINT: uint32,
110
+ cin.TypeKind.ULONG: uint64
111
+ },
112
+ "float": {
113
+ cin.TypeKind.FLOAT: float32,
114
+ cin.TypeKind.DOUBLE: float64,
115
+ cin.TypeKind.LONGDOUBLE: float80
116
+ }
117
+ }
118
+
119
+ def parse(self, filenames, flags):
120
+ """Function to parse a file with C source code
121
+
122
+ It takes the filename as an attribute and creates a Clang AST
123
+ Translation Unit parsing the file.
124
+ Then the transformation function is called on the translation unit,
125
+ whose reults are collected into a list which is returned by the
126
+ function.
127
+
128
+ Parameters
129
+ ==========
130
+
131
+ filenames : string
132
+ Path to the C file to be parsed
133
+
134
+ flags: list
135
+ Arguments to be passed to Clang while parsing the C code
136
+
137
+ Returns
138
+ =======
139
+
140
+ py_nodes: list
141
+ A list of SymPy AST nodes
142
+
143
+ """
144
+ filename = os.path.abspath(filenames)
145
+ self.tu = self.index.parse(
146
+ filename,
147
+ args=flags,
148
+ options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD
149
+ )
150
+ for child in self.tu.cursor.get_children():
151
+ if child.kind == cin.CursorKind.VAR_DECL:
152
+ self._py_nodes.append(self.transform(child))
153
+ elif (child.kind == cin.CursorKind.FUNCTION_DECL):
154
+ self._py_nodes.append(self.transform(child))
155
+ else:
156
+ pass
157
+ return self._py_nodes
158
+
159
+ def parse_str(self, source, flags):
160
+ """Function to parse a string with C source code
161
+
162
+ It takes the source code as an attribute, stores it in a temporary
163
+ file and creates a Clang AST Translation Unit parsing the file.
164
+ Then the transformation function is called on the translation unit,
165
+ whose reults are collected into a list which is returned by the
166
+ function.
167
+
168
+ Parameters
169
+ ==========
170
+
171
+ source : string
172
+ Path to the C file to be parsed
173
+
174
+ flags: list
175
+ Arguments to be passed to Clang while parsing the C code
176
+
177
+ Returns
178
+ =======
179
+
180
+ py_nodes: list
181
+ A list of SymPy AST nodes
182
+
183
+ """
184
+ file = tempfile.NamedTemporaryFile(mode = 'w+', suffix = '.cpp')
185
+ file.write(source)
186
+ file.seek(0)
187
+ self.tu = self.index.parse(
188
+ file.name,
189
+ args=flags,
190
+ options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD
191
+ )
192
+ file.close()
193
+ for child in self.tu.cursor.get_children():
194
+ if child.kind == cin.CursorKind.VAR_DECL:
195
+ self._py_nodes.append(self.transform(child))
196
+ elif (child.kind == cin.CursorKind.FUNCTION_DECL):
197
+ self._py_nodes.append(self.transform(child))
198
+ else:
199
+ pass
200
+ return self._py_nodes
201
+
202
+ def transform(self, node):
203
+ """Transformation Function for Clang AST nodes
204
+
205
+ It determines the kind of node and calls the respective
206
+ transformation function for that node.
207
+
208
+ Raises
209
+ ======
210
+
211
+ NotImplementedError : if the transformation for the provided node
212
+ is not implemented
213
+
214
+ """
215
+ try:
216
+ handler = getattr(self, 'transform_%s' % node.kind.name.lower())
217
+ except AttributeError:
218
+ print(
219
+ "Ignoring node of type %s (%s)" % (
220
+ node.kind,
221
+ ' '.join(
222
+ t.spelling for t in node.get_tokens())
223
+ ),
224
+ file=sys.stderr
225
+ )
226
+ handler = None
227
+ if handler:
228
+ result = handler(node)
229
+ return result
230
+
231
+ def transform_var_decl(self, node):
232
+ """Transformation Function for Variable Declaration
233
+
234
+ Used to create nodes for variable declarations and assignments with
235
+ values or function call for the respective nodes in the clang AST
236
+
237
+ Returns
238
+ =======
239
+
240
+ A variable node as Declaration, with the initial value if given
241
+
242
+ Raises
243
+ ======
244
+
245
+ NotImplementedError : if called for data types not currently
246
+ implemented
247
+
248
+ Notes
249
+ =====
250
+
251
+ The function currently supports following data types:
252
+
253
+ Boolean:
254
+ bool, _Bool
255
+
256
+ Integer:
257
+ 8-bit: signed char and unsigned char
258
+ 16-bit: short, short int, signed short,
259
+ signed short int, unsigned short, unsigned short int
260
+ 32-bit: int, signed int, unsigned int
261
+ 64-bit: long, long int, signed long,
262
+ signed long int, unsigned long, unsigned long int
263
+
264
+ Floating point:
265
+ Single Precision: float
266
+ Double Precision: double
267
+ Extended Precision: long double
268
+
269
+ """
270
+ if node.type.kind in self._data_types["int"]:
271
+ type = self._data_types["int"][node.type.kind]
272
+ elif node.type.kind in self._data_types["float"]:
273
+ type = self._data_types["float"][node.type.kind]
274
+ elif node.type.kind in self._data_types["bool"]:
275
+ type = self._data_types["bool"][node.type.kind]
276
+ else:
277
+ raise NotImplementedError("Only bool, int "
278
+ "and float are supported")
279
+ try:
280
+ children = node.get_children()
281
+ child = next(children)
282
+ #ignoring namespace and type details for the variable
283
+ while child.kind == cin.CursorKind.NAMESPACE_REF:
284
+ child = next(children)
285
+
286
+ while child.kind == cin.CursorKind.TYPE_REF:
287
+ child = next(children)
288
+
289
+ val = self.transform(child)
290
+
291
+ supported_rhs = [
292
+ cin.CursorKind.INTEGER_LITERAL,
293
+ cin.CursorKind.FLOATING_LITERAL,
294
+ cin.CursorKind.UNEXPOSED_EXPR,
295
+ cin.CursorKind.BINARY_OPERATOR,
296
+ cin.CursorKind.PAREN_EXPR,
297
+ cin.CursorKind.UNARY_OPERATOR,
298
+ cin.CursorKind.CXX_BOOL_LITERAL_EXPR
299
+ ]
300
+
301
+ if child.kind in supported_rhs:
302
+ if isinstance(val, str):
303
+ value = Symbol(val)
304
+ elif isinstance(val, bool):
305
+ if node.type.kind in self._data_types["int"]:
306
+ value = Integer(0) if val == False else Integer(1)
307
+ elif node.type.kind in self._data_types["float"]:
308
+ value = Float(0.0) if val == False else Float(1.0)
309
+ elif node.type.kind in self._data_types["bool"]:
310
+ value = sympify(val)
311
+ elif isinstance(val, (Integer, int, Float, float)):
312
+ if node.type.kind in self._data_types["int"]:
313
+ value = Integer(val)
314
+ elif node.type.kind in self._data_types["float"]:
315
+ value = Float(val)
316
+ elif node.type.kind in self._data_types["bool"]:
317
+ value = sympify(bool(val))
318
+ else:
319
+ value = val
320
+
321
+ return Variable(
322
+ node.spelling
323
+ ).as_Declaration(
324
+ type = type,
325
+ value = value
326
+ )
327
+
328
+ elif child.kind == cin.CursorKind.CALL_EXPR:
329
+ return Variable(
330
+ node.spelling
331
+ ).as_Declaration(
332
+ value = val
333
+ )
334
+
335
+ else:
336
+ raise NotImplementedError("Given "
337
+ "variable declaration \"{}\" "
338
+ "is not possible to parse yet!"
339
+ .format(" ".join(
340
+ t.spelling for t in node.get_tokens()
341
+ )
342
+ ))
343
+
344
+ except StopIteration:
345
+ return Variable(
346
+ node.spelling
347
+ ).as_Declaration(
348
+ type = type
349
+ )
350
+
351
+ def transform_function_decl(self, node):
352
+ """Transformation Function For Function Declaration
353
+
354
+ Used to create nodes for function declarations and definitions for
355
+ the respective nodes in the clang AST
356
+
357
+ Returns
358
+ =======
359
+
360
+ function : Codegen AST node
361
+ - FunctionPrototype node if function body is not present
362
+ - FunctionDefinition node if the function body is present
363
+
364
+
365
+ """
366
+
367
+ if node.result_type.kind in self._data_types["int"]:
368
+ ret_type = self._data_types["int"][node.result_type.kind]
369
+ elif node.result_type.kind in self._data_types["float"]:
370
+ ret_type = self._data_types["float"][node.result_type.kind]
371
+ elif node.result_type.kind in self._data_types["bool"]:
372
+ ret_type = self._data_types["bool"][node.result_type.kind]
373
+ elif node.result_type.kind in self._data_types["void"]:
374
+ ret_type = self._data_types["void"][node.result_type.kind]
375
+ else:
376
+ raise NotImplementedError("Only void, bool, int "
377
+ "and float are supported")
378
+ body = []
379
+ param = []
380
+ try:
381
+ children = node.get_children()
382
+ child = next(children)
383
+
384
+ # If the node has any children, the first children will be the
385
+ # return type and namespace for the function declaration. These
386
+ # nodes can be ignored.
387
+ while child.kind == cin.CursorKind.NAMESPACE_REF:
388
+ child = next(children)
389
+
390
+ while child.kind == cin.CursorKind.TYPE_REF:
391
+ child = next(children)
392
+
393
+
394
+ # Subsequent nodes will be the parameters for the function.
395
+ try:
396
+ while True:
397
+ decl = self.transform(child)
398
+ if (child.kind == cin.CursorKind.PARM_DECL):
399
+ param.append(decl)
400
+ elif (child.kind == cin.CursorKind.COMPOUND_STMT):
401
+ for val in decl:
402
+ body.append(val)
403
+ else:
404
+ body.append(decl)
405
+ child = next(children)
406
+ except StopIteration:
407
+ pass
408
+ except StopIteration:
409
+ pass
410
+
411
+ if body == []:
412
+ function = FunctionPrototype(
413
+ return_type = ret_type,
414
+ name = node.spelling,
415
+ parameters = param
416
+ )
417
+ else:
418
+ function = FunctionDefinition(
419
+ return_type = ret_type,
420
+ name = node.spelling,
421
+ parameters = param,
422
+ body = body
423
+ )
424
+ return function
425
+
426
+ def transform_parm_decl(self, node):
427
+ """Transformation function for Parameter Declaration
428
+
429
+ Used to create parameter nodes for the required functions for the
430
+ respective nodes in the clang AST
431
+
432
+ Returns
433
+ =======
434
+
435
+ param : Codegen AST Node
436
+ Variable node with the value and type of the variable
437
+
438
+ Raises
439
+ ======
440
+
441
+ ValueError if multiple children encountered in the parameter node
442
+
443
+ """
444
+ if node.type.kind in self._data_types["int"]:
445
+ type = self._data_types["int"][node.type.kind]
446
+ elif node.type.kind in self._data_types["float"]:
447
+ type = self._data_types["float"][node.type.kind]
448
+ elif node.type.kind in self._data_types["bool"]:
449
+ type = self._data_types["bool"][node.type.kind]
450
+ else:
451
+ raise NotImplementedError("Only bool, int "
452
+ "and float are supported")
453
+ try:
454
+ children = node.get_children()
455
+ child = next(children)
456
+
457
+ # Any namespace nodes can be ignored
458
+ while child.kind in [cin.CursorKind.NAMESPACE_REF,
459
+ cin.CursorKind.TYPE_REF,
460
+ cin.CursorKind.TEMPLATE_REF]:
461
+ child = next(children)
462
+
463
+ # If there is a child, it is the default value of the parameter.
464
+ lit = self.transform(child)
465
+ if node.type.kind in self._data_types["int"]:
466
+ val = Integer(lit)
467
+ elif node.type.kind in self._data_types["float"]:
468
+ val = Float(lit)
469
+ elif node.type.kind in self._data_types["bool"]:
470
+ val = sympify(bool(lit))
471
+ else:
472
+ raise NotImplementedError("Only bool, int "
473
+ "and float are supported")
474
+
475
+ param = Variable(
476
+ node.spelling
477
+ ).as_Declaration(
478
+ type = type,
479
+ value = val
480
+ )
481
+ except StopIteration:
482
+ param = Variable(
483
+ node.spelling
484
+ ).as_Declaration(
485
+ type = type
486
+ )
487
+
488
+ try:
489
+ self.transform(next(children))
490
+ raise ValueError("Can't handle multiple children on parameter")
491
+ except StopIteration:
492
+ pass
493
+
494
+ return param
495
+
496
+ def transform_integer_literal(self, node):
497
+ """Transformation function for integer literal
498
+
499
+ Used to get the value and type of the given integer literal.
500
+
501
+ Returns
502
+ =======
503
+
504
+ val : list
505
+ List with two arguments type and Value
506
+ type contains the type of the integer
507
+ value contains the value stored in the variable
508
+
509
+ Notes
510
+ =====
511
+
512
+ Only Base Integer type supported for now
513
+
514
+ """
515
+ try:
516
+ value = next(node.get_tokens()).spelling
517
+ except StopIteration:
518
+ # No tokens
519
+ value = node.literal
520
+ return int(value)
521
+
522
+ def transform_floating_literal(self, node):
523
+ """Transformation function for floating literal
524
+
525
+ Used to get the value and type of the given floating literal.
526
+
527
+ Returns
528
+ =======
529
+
530
+ val : list
531
+ List with two arguments type and Value
532
+ type contains the type of float
533
+ value contains the value stored in the variable
534
+
535
+ Notes
536
+ =====
537
+
538
+ Only Base Float type supported for now
539
+
540
+ """
541
+ try:
542
+ value = next(node.get_tokens()).spelling
543
+ except (StopIteration, ValueError):
544
+ # No tokens
545
+ value = node.literal
546
+ return float(value)
547
+
548
+ def transform_string_literal(self, node):
549
+ #TODO: No string type in AST
550
+ #type =
551
+ #try:
552
+ # value = next(node.get_tokens()).spelling
553
+ #except (StopIteration, ValueError):
554
+ # No tokens
555
+ # value = node.literal
556
+ #val = [type, value]
557
+ #return val
558
+ pass
559
+
560
+ def transform_character_literal(self, node):
561
+ """Transformation function for character literal
562
+
563
+ Used to get the value of the given character literal.
564
+
565
+ Returns
566
+ =======
567
+
568
+ val : int
569
+ val contains the ascii value of the character literal
570
+
571
+ Notes
572
+ =====
573
+
574
+ Only for cases where character is assigned to a integer value,
575
+ since character literal is not in SymPy AST
576
+
577
+ """
578
+ try:
579
+ value = next(node.get_tokens()).spelling
580
+ except (StopIteration, ValueError):
581
+ # No tokens
582
+ value = node.literal
583
+ return ord(str(value[1]))
584
+
585
+ def transform_cxx_bool_literal_expr(self, node):
586
+ """Transformation function for boolean literal
587
+
588
+ Used to get the value of the given boolean literal.
589
+
590
+ Returns
591
+ =======
592
+
593
+ value : bool
594
+ value contains the boolean value of the variable
595
+
596
+ """
597
+ try:
598
+ value = next(node.get_tokens()).spelling
599
+ except (StopIteration, ValueError):
600
+ value = node.literal
601
+ return True if value == 'true' else False
602
+
603
+ def transform_unexposed_decl(self,node):
604
+ """Transformation function for unexposed declarations"""
605
+ pass
606
+
607
+ def transform_unexposed_expr(self, node):
608
+ """Transformation function for unexposed expression
609
+
610
+ Unexposed expressions are used to wrap float, double literals and
611
+ expressions
612
+
613
+ Returns
614
+ =======
615
+
616
+ expr : Codegen AST Node
617
+ the result from the wrapped expression
618
+
619
+ None : NoneType
620
+ No childs are found for the node
621
+
622
+ Raises
623
+ ======
624
+
625
+ ValueError if the expression contains multiple children
626
+
627
+ """
628
+ # Ignore unexposed nodes; pass whatever is the first
629
+ # (and should be only) child unaltered.
630
+ try:
631
+ children = node.get_children()
632
+ expr = self.transform(next(children))
633
+ except StopIteration:
634
+ return None
635
+
636
+ try:
637
+ next(children)
638
+ raise ValueError("Unexposed expression has > 1 children.")
639
+ except StopIteration:
640
+ pass
641
+
642
+ return expr
643
+
644
+ def transform_decl_ref_expr(self, node):
645
+ """Returns the name of the declaration reference"""
646
+ return node.spelling
647
+
648
+ def transform_call_expr(self, node):
649
+ """Transformation function for a call expression
650
+
651
+ Used to create function call nodes for the function calls present
652
+ in the C code
653
+
654
+ Returns
655
+ =======
656
+
657
+ FunctionCall : Codegen AST Node
658
+ FunctionCall node with parameters if any parameters are present
659
+
660
+ """
661
+ param = []
662
+ children = node.get_children()
663
+ child = next(children)
664
+
665
+ while child.kind == cin.CursorKind.NAMESPACE_REF:
666
+ child = next(children)
667
+ while child.kind == cin.CursorKind.TYPE_REF:
668
+ child = next(children)
669
+
670
+ first_child = self.transform(child)
671
+ try:
672
+ for child in children:
673
+ arg = self.transform(child)
674
+ if (child.kind == cin.CursorKind.INTEGER_LITERAL):
675
+ param.append(Integer(arg))
676
+ elif (child.kind == cin.CursorKind.FLOATING_LITERAL):
677
+ param.append(Float(arg))
678
+ else:
679
+ param.append(arg)
680
+ return FunctionCall(first_child, param)
681
+
682
+ except StopIteration:
683
+ return FunctionCall(first_child)
684
+
685
+ def transform_return_stmt(self, node):
686
+ """Returns the Return Node for a return statement"""
687
+ return Return(next(node.get_children()).spelling)
688
+
689
+ def transform_compound_stmt(self, node):
690
+ """Transformation function for compond statemets
691
+
692
+ Returns
693
+ =======
694
+
695
+ expr : list
696
+ list of Nodes for the expressions present in the statement
697
+
698
+ None : NoneType
699
+ if the compound statement is empty
700
+
701
+ """
702
+ try:
703
+ expr = []
704
+ children = node.get_children()
705
+ for child in children:
706
+ expr.append(self.transform(child))
707
+ except StopIteration:
708
+ return None
709
+ return expr
710
+
711
+ def transform_decl_stmt(self, node):
712
+ """Transformation function for declaration statements
713
+
714
+ These statements are used to wrap different kinds of declararions
715
+ like variable or function declaration
716
+ The function calls the transformer function for the child of the
717
+ given node
718
+
719
+ Returns
720
+ =======
721
+
722
+ statement : Codegen AST Node
723
+ contains the node returned by the children node for the type of
724
+ declaration
725
+
726
+ Raises
727
+ ======
728
+
729
+ ValueError if multiple children present
730
+
731
+ """
732
+ try:
733
+ children = node.get_children()
734
+ statement = self.transform(next(children))
735
+ except StopIteration:
736
+ pass
737
+
738
+ try:
739
+ self.transform(next(children))
740
+ raise ValueError("Don't know how to handle multiple statements")
741
+ except StopIteration:
742
+ pass
743
+
744
+ return statement
745
+
746
+ def transform_paren_expr(self, node):
747
+ """Transformation function for Parenthesized expressions
748
+
749
+ Returns the result from its children nodes
750
+
751
+ """
752
+ return self.transform(next(node.get_children()))
753
+
754
+ def transform_compound_assignment_operator(self, node):
755
+ """Transformation function for handling shorthand operators
756
+
757
+ Returns
758
+ =======
759
+
760
+ augmented_assignment_expression: Codegen AST node
761
+ shorthand assignment expression represented as Codegen AST
762
+
763
+ Raises
764
+ ======
765
+
766
+ NotImplementedError
767
+ If the shorthand operator for bitwise operators
768
+ (~=, ^=, &=, |=, <<=, >>=) is encountered
769
+
770
+ """
771
+ return self.transform_binary_operator(node)
772
+
773
+ def transform_unary_operator(self, node):
774
+ """Transformation function for handling unary operators
775
+
776
+ Returns
777
+ =======
778
+
779
+ unary_expression: Codegen AST node
780
+ simplified unary expression represented as Codegen AST
781
+
782
+ Raises
783
+ ======
784
+
785
+ NotImplementedError
786
+ If dereferencing operator(*), address operator(&) or
787
+ bitwise NOT operator(~) is encountered
788
+
789
+ """
790
+ # supported operators list
791
+ operators_list = ['+', '-', '++', '--', '!']
792
+ tokens = list(node.get_tokens())
793
+
794
+ # it can be either pre increment/decrement or any other operator from the list
795
+ if tokens[0].spelling in operators_list:
796
+ child = self.transform(next(node.get_children()))
797
+ # (decl_ref) e.g.; int a = ++b; or simply ++b;
798
+ if isinstance(child, str):
799
+ if tokens[0].spelling == '+':
800
+ return Symbol(child)
801
+ if tokens[0].spelling == '-':
802
+ return Mul(Symbol(child), -1)
803
+ if tokens[0].spelling == '++':
804
+ return PreIncrement(Symbol(child))
805
+ if tokens[0].spelling == '--':
806
+ return PreDecrement(Symbol(child))
807
+ if tokens[0].spelling == '!':
808
+ return Not(Symbol(child))
809
+ # e.g.; int a = -1; or int b = -(1 + 2);
810
+ else:
811
+ if tokens[0].spelling == '+':
812
+ return child
813
+ if tokens[0].spelling == '-':
814
+ return Mul(child, -1)
815
+ if tokens[0].spelling == '!':
816
+ return Not(sympify(bool(child)))
817
+
818
+ # it can be either post increment/decrement
819
+ # since variable name is obtained in token[0].spelling
820
+ elif tokens[1].spelling in ['++', '--']:
821
+ child = self.transform(next(node.get_children()))
822
+ if tokens[1].spelling == '++':
823
+ return PostIncrement(Symbol(child))
824
+ if tokens[1].spelling == '--':
825
+ return PostDecrement(Symbol(child))
826
+ else:
827
+ raise NotImplementedError("Dereferencing operator, "
828
+ "Address operator and bitwise NOT operator "
829
+ "have not been implemented yet!")
830
+
831
+ def transform_binary_operator(self, node):
832
+ """Transformation function for handling binary operators
833
+
834
+ Returns
835
+ =======
836
+
837
+ binary_expression: Codegen AST node
838
+ simplified binary expression represented as Codegen AST
839
+
840
+ Raises
841
+ ======
842
+
843
+ NotImplementedError
844
+ If a bitwise operator or
845
+ unary operator(which is a child of any binary
846
+ operator in Clang AST) is encountered
847
+
848
+ """
849
+ # get all the tokens of assignment
850
+ # and store it in the tokens list
851
+ tokens = list(node.get_tokens())
852
+
853
+ # supported operators list
854
+ operators_list = ['+', '-', '*', '/', '%','=',
855
+ '>', '>=', '<', '<=', '==', '!=', '&&', '||', '+=', '-=',
856
+ '*=', '/=', '%=']
857
+
858
+ # this stack will contain variable content
859
+ # and type of variable in the rhs
860
+ combined_variables_stack = []
861
+
862
+ # this stack will contain operators
863
+ # to be processed in the rhs
864
+ operators_stack = []
865
+
866
+ # iterate through every token
867
+ for token in tokens:
868
+ # token is either '(', ')' or
869
+ # any of the supported operators from the operator list
870
+ if token.kind == cin.TokenKind.PUNCTUATION:
871
+
872
+ # push '(' to the operators stack
873
+ if token.spelling == '(':
874
+ operators_stack.append('(')
875
+
876
+ elif token.spelling == ')':
877
+ # keep adding the expression to the
878
+ # combined variables stack unless
879
+ # '(' is found
880
+ while (operators_stack
881
+ and operators_stack[-1] != '('):
882
+ if len(combined_variables_stack) < 2:
883
+ raise NotImplementedError(
884
+ "Unary operators as a part of "
885
+ "binary operators is not "
886
+ "supported yet!")
887
+ rhs = combined_variables_stack.pop()
888
+ lhs = combined_variables_stack.pop()
889
+ operator = operators_stack.pop()
890
+ combined_variables_stack.append(
891
+ self.perform_operation(
892
+ lhs, rhs, operator))
893
+
894
+ # pop '('
895
+ operators_stack.pop()
896
+
897
+ # token is an operator (supported)
898
+ elif token.spelling in operators_list:
899
+ while (operators_stack
900
+ and self.priority_of(token.spelling)
901
+ <= self.priority_of(
902
+ operators_stack[-1])):
903
+ if len(combined_variables_stack) < 2:
904
+ raise NotImplementedError(
905
+ "Unary operators as a part of "
906
+ "binary operators is not "
907
+ "supported yet!")
908
+ rhs = combined_variables_stack.pop()
909
+ lhs = combined_variables_stack.pop()
910
+ operator = operators_stack.pop()
911
+ combined_variables_stack.append(
912
+ self.perform_operation(
913
+ lhs, rhs, operator))
914
+
915
+ # push current operator
916
+ operators_stack.append(token.spelling)
917
+
918
+ # token is a bitwise operator
919
+ elif token.spelling in ['&', '|', '^', '<<', '>>']:
920
+ raise NotImplementedError(
921
+ "Bitwise operator has not been "
922
+ "implemented yet!")
923
+
924
+ # token is a shorthand bitwise operator
925
+ elif token.spelling in ['&=', '|=', '^=', '<<=',
926
+ '>>=']:
927
+ raise NotImplementedError(
928
+ "Shorthand bitwise operator has not been "
929
+ "implemented yet!")
930
+ else:
931
+ raise NotImplementedError(
932
+ "Given token {} is not implemented yet!"
933
+ .format(token.spelling))
934
+
935
+ # token is an identifier(variable)
936
+ elif token.kind == cin.TokenKind.IDENTIFIER:
937
+ combined_variables_stack.append(
938
+ [token.spelling, 'identifier'])
939
+
940
+ # token is a literal
941
+ elif token.kind == cin.TokenKind.LITERAL:
942
+ combined_variables_stack.append(
943
+ [token.spelling, 'literal'])
944
+
945
+ # token is a keyword, either true or false
946
+ elif (token.kind == cin.TokenKind.KEYWORD
947
+ and token.spelling in ['true', 'false']):
948
+ combined_variables_stack.append(
949
+ [token.spelling, 'boolean'])
950
+ else:
951
+ raise NotImplementedError(
952
+ "Given token {} is not implemented yet!"
953
+ .format(token.spelling))
954
+
955
+ # process remaining operators
956
+ while operators_stack:
957
+ if len(combined_variables_stack) < 2:
958
+ raise NotImplementedError(
959
+ "Unary operators as a part of "
960
+ "binary operators is not "
961
+ "supported yet!")
962
+ rhs = combined_variables_stack.pop()
963
+ lhs = combined_variables_stack.pop()
964
+ operator = operators_stack.pop()
965
+ combined_variables_stack.append(
966
+ self.perform_operation(lhs, rhs, operator))
967
+
968
+ return combined_variables_stack[-1][0]
969
+
970
+ def priority_of(self, op):
971
+ """To get the priority of given operator"""
972
+ if op in ['=', '+=', '-=', '*=', '/=', '%=']:
973
+ return 1
974
+ if op in ['&&', '||']:
975
+ return 2
976
+ if op in ['<', '<=', '>', '>=', '==', '!=']:
977
+ return 3
978
+ if op in ['+', '-']:
979
+ return 4
980
+ if op in ['*', '/', '%']:
981
+ return 5
982
+ return 0
983
+
984
+ def perform_operation(self, lhs, rhs, op):
985
+ """Performs operation supported by the SymPy core
986
+
987
+ Returns
988
+ =======
989
+
990
+ combined_variable: list
991
+ contains variable content and type of variable
992
+
993
+ """
994
+ lhs_value = self.get_expr_for_operand(lhs)
995
+ rhs_value = self.get_expr_for_operand(rhs)
996
+ if op == '+':
997
+ return [Add(lhs_value, rhs_value), 'expr']
998
+ if op == '-':
999
+ return [Add(lhs_value, -rhs_value), 'expr']
1000
+ if op == '*':
1001
+ return [Mul(lhs_value, rhs_value), 'expr']
1002
+ if op == '/':
1003
+ return [Mul(lhs_value, Pow(rhs_value, Integer(-1))), 'expr']
1004
+ if op == '%':
1005
+ return [Mod(lhs_value, rhs_value), 'expr']
1006
+ if op in ['<', '<=', '>', '>=', '==', '!=']:
1007
+ return [Rel(lhs_value, rhs_value, op), 'expr']
1008
+ if op == '&&':
1009
+ return [And(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr']
1010
+ if op == '||':
1011
+ return [Or(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr']
1012
+ if op == '=':
1013
+ return [Assignment(Variable(lhs_value), rhs_value), 'expr']
1014
+ if op in ['+=', '-=', '*=', '/=', '%=']:
1015
+ return [aug_assign(Variable(lhs_value), op[0], rhs_value), 'expr']
1016
+
1017
+ def get_expr_for_operand(self, combined_variable):
1018
+ """Gives out SymPy Codegen AST node
1019
+
1020
+ AST node returned is corresponding to
1021
+ combined variable passed.Combined variable contains
1022
+ variable content and type of variable
1023
+
1024
+ """
1025
+ if combined_variable[1] == 'identifier':
1026
+ return Symbol(combined_variable[0])
1027
+ if combined_variable[1] == 'literal':
1028
+ if '.' in combined_variable[0]:
1029
+ return Float(float(combined_variable[0]))
1030
+ else:
1031
+ return Integer(int(combined_variable[0]))
1032
+ if combined_variable[1] == 'expr':
1033
+ return combined_variable[0]
1034
+ if combined_variable[1] == 'boolean':
1035
+ return true if combined_variable[0] == 'true' else false
1036
+
1037
+ def transform_null_stmt(self, node):
1038
+ """Handles Null Statement and returns None"""
1039
+ return none
1040
+
1041
+ def transform_while_stmt(self, node):
1042
+ """Transformation function for handling while statement
1043
+
1044
+ Returns
1045
+ =======
1046
+
1047
+ while statement : Codegen AST Node
1048
+ contains the while statement node having condition and
1049
+ statement block
1050
+
1051
+ """
1052
+ children = node.get_children()
1053
+
1054
+ condition = self.transform(next(children))
1055
+ statements = self.transform(next(children))
1056
+
1057
+ if isinstance(statements, list):
1058
+ statement_block = CodeBlock(*statements)
1059
+ else:
1060
+ statement_block = CodeBlock(statements)
1061
+
1062
+ return While(condition, statement_block)
1063
+
1064
+
1065
+
1066
+ else:
1067
+ class CCodeConverter(): # type: ignore
1068
+ def __init__(self, *args, **kwargs):
1069
+ raise ImportError("Module not Installed")
1070
+
1071
+
1072
+ def parse_c(source):
1073
+ """Function for converting a C source code
1074
+
1075
+ The function reads the source code present in the given file and parses it
1076
+ to give out SymPy Expressions
1077
+
1078
+ Returns
1079
+ =======
1080
+
1081
+ src : list
1082
+ List of Python expression strings
1083
+
1084
+ """
1085
+ converter = CCodeConverter()
1086
+ if os.path.exists(source):
1087
+ src = converter.parse(source, flags = [])
1088
+ else:
1089
+ src = converter.parse_str(source, flags = [])
1090
+ return src
env-llmeval/lib/python3.10/site-packages/sympy/parsing/fortran/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Used for translating Fortran source code into a SymPy expression. """
env-llmeval/lib/python3.10/site-packages/sympy/parsing/fortran/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (264 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/fortran/__pycache__/fortran_parser.cpython-310.pyc ADDED
Binary file (8.78 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/parsing/fortran/fortran_parser.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external import import_module
2
+
3
+ lfortran = import_module('lfortran')
4
+
5
+ if lfortran:
6
+ from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String,
7
+ Return, FunctionDefinition, Assignment)
8
+ from sympy.core import Add, Mul, Integer, Float
9
+ from sympy.core.symbol import Symbol
10
+
11
+ asr_mod = lfortran.asr
12
+ asr = lfortran.asr.asr
13
+ src_to_ast = lfortran.ast.src_to_ast
14
+ ast_to_asr = lfortran.semantic.ast_to_asr.ast_to_asr
15
+
16
+ """
17
+ This module contains all the necessary Classes and Function used to Parse
18
+ Fortran code into SymPy expression
19
+
20
+ The module and its API are currently under development and experimental.
21
+ It is also dependent on LFortran for the ASR that is converted to SymPy syntax
22
+ which is also under development.
23
+ The module only supports the features currently supported by the LFortran ASR
24
+ which will be updated as the development of LFortran and this module progresses
25
+
26
+ You might find unexpected bugs and exceptions while using the module, feel free
27
+ to report them to the SymPy Issue Tracker
28
+
29
+ The API for the module might also change while in development if better and
30
+ more effective ways are discovered for the process
31
+
32
+ Features Supported
33
+ ==================
34
+
35
+ - Variable Declarations (integers and reals)
36
+ - Function Definitions
37
+ - Assignments and Basic Binary Operations
38
+
39
+
40
+ Notes
41
+ =====
42
+
43
+ The module depends on an external dependency
44
+
45
+ LFortran : Required to parse Fortran source code into ASR
46
+
47
+
48
+ References
49
+ ==========
50
+
51
+ .. [1] https://github.com/sympy/sympy/issues
52
+ .. [2] https://gitlab.com/lfortran/lfortran
53
+ .. [3] https://docs.lfortran.org/
54
+
55
+ """
56
+
57
+
58
+ class ASR2PyVisitor(asr.ASTVisitor): # type: ignore
59
+ """
60
+ Visitor Class for LFortran ASR
61
+
62
+ It is a Visitor class derived from asr.ASRVisitor which visits all the
63
+ nodes of the LFortran ASR and creates corresponding AST node for each
64
+ ASR node
65
+
66
+ """
67
+
68
+ def __init__(self):
69
+ """Initialize the Parser"""
70
+ self._py_ast = []
71
+
72
+ def visit_TranslationUnit(self, node):
73
+ """
74
+ Function to visit all the elements of the Translation Unit
75
+ created by LFortran ASR
76
+ """
77
+ for s in node.global_scope.symbols:
78
+ sym = node.global_scope.symbols[s]
79
+ self.visit(sym)
80
+ for item in node.items:
81
+ self.visit(item)
82
+
83
+ def visit_Assignment(self, node):
84
+ """Visitor Function for Assignment
85
+
86
+ Visits each Assignment is the LFortran ASR and creates corresponding
87
+ assignment for SymPy.
88
+
89
+ Notes
90
+ =====
91
+
92
+ The function currently only supports variable assignment and binary
93
+ operation assignments of varying multitudes. Any type of numberS or
94
+ array is not supported.
95
+
96
+ Raises
97
+ ======
98
+
99
+ NotImplementedError() when called for Numeric assignments or Arrays
100
+
101
+ """
102
+ # TODO: Arithmetic Assignment
103
+ if isinstance(node.target, asr.Variable):
104
+ target = node.target
105
+ value = node.value
106
+ if isinstance(value, asr.Variable):
107
+ new_node = Assignment(
108
+ Variable(
109
+ target.name
110
+ ),
111
+ Variable(
112
+ value.name
113
+ )
114
+ )
115
+ elif (type(value) == asr.BinOp):
116
+ exp_ast = call_visitor(value)
117
+ for expr in exp_ast:
118
+ new_node = Assignment(
119
+ Variable(target.name),
120
+ expr
121
+ )
122
+ else:
123
+ raise NotImplementedError("Numeric assignments not supported")
124
+ else:
125
+ raise NotImplementedError("Arrays not supported")
126
+ self._py_ast.append(new_node)
127
+
128
+ def visit_BinOp(self, node):
129
+ """Visitor Function for Binary Operations
130
+
131
+ Visits each binary operation present in the LFortran ASR like addition,
132
+ subtraction, multiplication, division and creates the corresponding
133
+ operation node in SymPy's AST
134
+
135
+ In case of more than one binary operations, the function calls the
136
+ call_visitor() function on the child nodes of the binary operations
137
+ recursively until all the operations have been processed.
138
+
139
+ Notes
140
+ =====
141
+
142
+ The function currently only supports binary operations with Variables
143
+ or other binary operations. Numerics are not supported as of yet.
144
+
145
+ Raises
146
+ ======
147
+
148
+ NotImplementedError() when called for Numeric assignments
149
+
150
+ """
151
+ # TODO: Integer Binary Operations
152
+ op = node.op
153
+ lhs = node.left
154
+ rhs = node.right
155
+
156
+ if (type(lhs) == asr.Variable):
157
+ left_value = Symbol(lhs.name)
158
+ elif(type(lhs) == asr.BinOp):
159
+ l_exp_ast = call_visitor(lhs)
160
+ for exp in l_exp_ast:
161
+ left_value = exp
162
+ else:
163
+ raise NotImplementedError("Numbers Currently not supported")
164
+
165
+ if (type(rhs) == asr.Variable):
166
+ right_value = Symbol(rhs.name)
167
+ elif(type(rhs) == asr.BinOp):
168
+ r_exp_ast = call_visitor(rhs)
169
+ for exp in r_exp_ast:
170
+ right_value = exp
171
+ else:
172
+ raise NotImplementedError("Numbers Currently not supported")
173
+
174
+ if isinstance(op, asr.Add):
175
+ new_node = Add(left_value, right_value)
176
+ elif isinstance(op, asr.Sub):
177
+ new_node = Add(left_value, -right_value)
178
+ elif isinstance(op, asr.Div):
179
+ new_node = Mul(left_value, 1/right_value)
180
+ elif isinstance(op, asr.Mul):
181
+ new_node = Mul(left_value, right_value)
182
+
183
+ self._py_ast.append(new_node)
184
+
185
+ def visit_Variable(self, node):
186
+ """Visitor Function for Variable Declaration
187
+
188
+ Visits each variable declaration present in the ASR and creates a
189
+ Symbol declaration for each variable
190
+
191
+ Notes
192
+ =====
193
+
194
+ The functions currently only support declaration of integer and
195
+ real variables. Other data types are still under development.
196
+
197
+ Raises
198
+ ======
199
+
200
+ NotImplementedError() when called for unsupported data types
201
+
202
+ """
203
+ if isinstance(node.type, asr.Integer):
204
+ var_type = IntBaseType(String('integer'))
205
+ value = Integer(0)
206
+ elif isinstance(node.type, asr.Real):
207
+ var_type = FloatBaseType(String('real'))
208
+ value = Float(0.0)
209
+ else:
210
+ raise NotImplementedError("Data type not supported")
211
+
212
+ if not (node.intent == 'in'):
213
+ new_node = Variable(
214
+ node.name
215
+ ).as_Declaration(
216
+ type = var_type,
217
+ value = value
218
+ )
219
+ self._py_ast.append(new_node)
220
+
221
+ def visit_Sequence(self, seq):
222
+ """Visitor Function for code sequence
223
+
224
+ Visits a code sequence/ block and calls the visitor function on all the
225
+ children of the code block to create corresponding code in python
226
+
227
+ """
228
+ if seq is not None:
229
+ for node in seq:
230
+ self._py_ast.append(call_visitor(node))
231
+
232
+ def visit_Num(self, node):
233
+ """Visitor Function for Numbers in ASR
234
+
235
+ This function is currently under development and will be updated
236
+ with improvements in the LFortran ASR
237
+
238
+ """
239
+ # TODO:Numbers when the LFortran ASR is updated
240
+ # self._py_ast.append(Integer(node.n))
241
+ pass
242
+
243
+ def visit_Function(self, node):
244
+ """Visitor Function for function Definitions
245
+
246
+ Visits each function definition present in the ASR and creates a
247
+ function definition node in the Python AST with all the elements of the
248
+ given function
249
+
250
+ The functions declare all the variables required as SymPy symbols in
251
+ the function before the function definition
252
+
253
+ This function also the call_visior_function to parse the contents of
254
+ the function body
255
+
256
+ """
257
+ # TODO: Return statement, variable declaration
258
+ fn_args = [Variable(arg_iter.name) for arg_iter in node.args]
259
+ fn_body = []
260
+ fn_name = node.name
261
+ for i in node.body:
262
+ fn_ast = call_visitor(i)
263
+ try:
264
+ fn_body_expr = fn_ast
265
+ except UnboundLocalError:
266
+ fn_body_expr = []
267
+ for sym in node.symtab.symbols:
268
+ decl = call_visitor(node.symtab.symbols[sym])
269
+ for symbols in decl:
270
+ fn_body.append(symbols)
271
+ for elem in fn_body_expr:
272
+ fn_body.append(elem)
273
+ fn_body.append(
274
+ Return(
275
+ Variable(
276
+ node.return_var.name
277
+ )
278
+ )
279
+ )
280
+ if isinstance(node.return_var.type, asr.Integer):
281
+ ret_type = IntBaseType(String('integer'))
282
+ elif isinstance(node.return_var.type, asr.Real):
283
+ ret_type = FloatBaseType(String('real'))
284
+ else:
285
+ raise NotImplementedError("Data type not supported")
286
+ new_node = FunctionDefinition(
287
+ return_type = ret_type,
288
+ name = fn_name,
289
+ parameters = fn_args,
290
+ body = fn_body
291
+ )
292
+ self._py_ast.append(new_node)
293
+
294
+ def ret_ast(self):
295
+ """Returns the AST nodes"""
296
+ return self._py_ast
297
+ else:
298
+ class ASR2PyVisitor(): # type: ignore
299
+ def __init__(self, *args, **kwargs):
300
+ raise ImportError('lfortran not available')
301
+
302
+ def call_visitor(fort_node):
303
+ """Calls the AST Visitor on the Module
304
+
305
+ This function is used to call the AST visitor for a program or module
306
+ It imports all the required modules and calls the visit() function
307
+ on the given node
308
+
309
+ Parameters
310
+ ==========
311
+
312
+ fort_node : LFortran ASR object
313
+ Node for the operation for which the NodeVisitor is called
314
+
315
+ Returns
316
+ =======
317
+
318
+ res_ast : list
319
+ list of SymPy AST Nodes
320
+
321
+ """
322
+ v = ASR2PyVisitor()
323
+ v.visit(fort_node)
324
+ res_ast = v.ret_ast()
325
+ return res_ast
326
+
327
+
328
+ def src_to_sympy(src):
329
+ """Wrapper function to convert the given Fortran source code to SymPy Expressions
330
+
331
+ Parameters
332
+ ==========
333
+
334
+ src : string
335
+ A string with the Fortran source code
336
+
337
+ Returns
338
+ =======
339
+
340
+ py_src : string
341
+ A string with the Python source code compatible with SymPy
342
+
343
+ """
344
+ a_ast = src_to_ast(src, translation_unit=False)
345
+ a = ast_to_asr(a_ast)
346
+ py_src = call_visitor(a)
347
+ return py_src