Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/14.attention.query_key_value.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/3.post_attention_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/3.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
- venv/lib/python3.10/site-packages/sympy/parsing/__init__.py +4 -0
- venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/ast_parser.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/mathematica.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/maxima.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/sym_expr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/ast_parser.py +79 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/Autolev.g4 +118 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/__init__.py +97 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_build_autolev_antlr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_listener_autolev_antlr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_parse_autolev_antlr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/_build_autolev_antlr.py +86 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/_listener_autolev_antlr.py +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/_parse_autolev_antlr.py +38 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest12.al +7 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest12.py +14 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest4.al +20 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest5.al +32 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest5.py +33 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest6.al +41 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest6.py +36 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest7.py +35 -0
- venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest8.py +49 -0
- venv/lib/python3.10/site-packages/sympy/parsing/c/__init__.py +1 -0
- venv/lib/python3.10/site-packages/sympy/parsing/c/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/c/__pycache__/c_parser.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/c/c_parser.py +1090 -0
- venv/lib/python3.10/site-packages/sympy/parsing/fortran/__init__.py +1 -0
- venv/lib/python3.10/site-packages/sympy/parsing/fortran/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/fortran/__pycache__/fortran_parser.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/fortran/fortran_parser.py +347 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/LICENSE.txt +21 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/LaTeX.g4 +312 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/__init__.py +35 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/_build_latex_antlr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/_parse_latex_antlr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/errors.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__init__.py +9 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexlexer.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexparser.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/14.attention.query_key_value.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3c9af8e8e4828e2884a5b8332e7125200bb964a2c3170af01121b4356281a760
|
3 |
+
size 50332749
|
ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cb3b9bb294659ffafd8ad29200b8a25701570e07a2670f1624b07f888c32052e
|
3 |
+
size 33555627
|
ckpts/universal/global_step80/zero/16.mlp.dense_h_to_4h_swiglu.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b1a1d1efe45051fc687a7953d3e1c72018f88f99aa282136d4e5290390c59fa6
|
3 |
+
size 33555533
|
ckpts/universal/global_step80/zero/3.post_attention_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ee70579dfea323da963d6f373cf81636ad50eb365bd2bf510c48495409f54e34
|
3 |
+
size 9372
|
ckpts/universal/global_step80/zero/3.post_attention_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:66a22d1c829ecca9056579fdf60fbe4c2781339d5e78af142d745e95acdf8049
|
3 |
+
size 9387
|
venv/lib/python3.10/site-packages/sympy/parsing/__init__.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Used for translating a string into a SymPy expression. """
|
2 |
+
__all__ = ['parse_expr']
|
3 |
+
|
4 |
+
from .sympy_parser import parse_expr
|
venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (322 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/ast_parser.cpython-310.pyc
ADDED
Binary file (3.13 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/mathematica.cpython-310.pyc
ADDED
Binary file (29 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/maxima.cpython-310.pyc
ADDED
Binary file (2.48 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/sym_expr.cpython-310.pyc
ADDED
Binary file (8.66 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-310.pyc
ADDED
Binary file (30.6 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/ast_parser.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module implements the functionality to take any Python expression as a
|
3 |
+
string and fix all numbers and other things before evaluating it,
|
4 |
+
thus
|
5 |
+
|
6 |
+
1/2
|
7 |
+
|
8 |
+
returns
|
9 |
+
|
10 |
+
Integer(1)/Integer(2)
|
11 |
+
|
12 |
+
We use the ast module for this. It is well documented at docs.python.org.
|
13 |
+
|
14 |
+
Some tips to understand how this works: use dump() to get a nice
|
15 |
+
representation of any node. Then write a string of what you want to get,
|
16 |
+
e.g. "Integer(1)", parse it, dump it and you'll see that you need to do
|
17 |
+
"Call(Name('Integer', Load()), [node], [], None, None)". You do not need
|
18 |
+
to bother with lineno and col_offset, just call fix_missing_locations()
|
19 |
+
before returning the node.
|
20 |
+
"""
|
21 |
+
|
22 |
+
from sympy.core.basic import Basic
|
23 |
+
from sympy.core.sympify import SympifyError
|
24 |
+
|
25 |
+
from ast import parse, NodeTransformer, Call, Name, Load, \
|
26 |
+
fix_missing_locations, Str, Tuple
|
27 |
+
|
28 |
+
class Transform(NodeTransformer):
|
29 |
+
|
30 |
+
def __init__(self, local_dict, global_dict):
|
31 |
+
NodeTransformer.__init__(self)
|
32 |
+
self.local_dict = local_dict
|
33 |
+
self.global_dict = global_dict
|
34 |
+
|
35 |
+
def visit_Constant(self, node):
|
36 |
+
if isinstance(node.value, int):
|
37 |
+
return fix_missing_locations(Call(func=Name('Integer', Load()),
|
38 |
+
args=[node], keywords=[]))
|
39 |
+
elif isinstance(node.value, float):
|
40 |
+
return fix_missing_locations(Call(func=Name('Float', Load()),
|
41 |
+
args=[node], keywords=[]))
|
42 |
+
return node
|
43 |
+
|
44 |
+
def visit_Name(self, node):
|
45 |
+
if node.id in self.local_dict:
|
46 |
+
return node
|
47 |
+
elif node.id in self.global_dict:
|
48 |
+
name_obj = self.global_dict[node.id]
|
49 |
+
|
50 |
+
if isinstance(name_obj, (Basic, type)) or callable(name_obj):
|
51 |
+
return node
|
52 |
+
elif node.id in ['True', 'False']:
|
53 |
+
return node
|
54 |
+
return fix_missing_locations(Call(func=Name('Symbol', Load()),
|
55 |
+
args=[Str(node.id)], keywords=[]))
|
56 |
+
|
57 |
+
def visit_Lambda(self, node):
|
58 |
+
args = [self.visit(arg) for arg in node.args.args]
|
59 |
+
body = self.visit(node.body)
|
60 |
+
n = Call(func=Name('Lambda', Load()),
|
61 |
+
args=[Tuple(args, Load()), body], keywords=[])
|
62 |
+
return fix_missing_locations(n)
|
63 |
+
|
64 |
+
def parse_expr(s, local_dict):
|
65 |
+
"""
|
66 |
+
Converts the string "s" to a SymPy expression, in local_dict.
|
67 |
+
|
68 |
+
It converts all numbers to Integers before feeding it to Python and
|
69 |
+
automatically creates Symbols.
|
70 |
+
"""
|
71 |
+
global_dict = {}
|
72 |
+
exec('from sympy import *', global_dict)
|
73 |
+
try:
|
74 |
+
a = parse(s.strip(), mode="eval")
|
75 |
+
except SyntaxError:
|
76 |
+
raise SympifyError("Cannot parse %s." % repr(s))
|
77 |
+
a = Transform(local_dict, global_dict).visit(a)
|
78 |
+
e = compile(a, "<string>", "eval")
|
79 |
+
return eval(e, global_dict, local_dict)
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/Autolev.g4
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
grammar Autolev;
|
2 |
+
|
3 |
+
options {
|
4 |
+
language = Python3;
|
5 |
+
}
|
6 |
+
|
7 |
+
prog: stat+;
|
8 |
+
|
9 |
+
stat: varDecl
|
10 |
+
| functionCall
|
11 |
+
| codeCommands
|
12 |
+
| massDecl
|
13 |
+
| inertiaDecl
|
14 |
+
| assignment
|
15 |
+
| settings
|
16 |
+
;
|
17 |
+
|
18 |
+
assignment: vec equals expr #vecAssign
|
19 |
+
| ID '[' index ']' equals expr #indexAssign
|
20 |
+
| ID diff? equals expr #regularAssign;
|
21 |
+
|
22 |
+
equals: ('='|'+='|'-='|':='|'*='|'/='|'^=');
|
23 |
+
|
24 |
+
index: expr (',' expr)* ;
|
25 |
+
|
26 |
+
diff: ('\'')+;
|
27 |
+
|
28 |
+
functionCall: ID '(' (expr (',' expr)*)? ')'
|
29 |
+
| (Mass|Inertia) '(' (ID (',' ID)*)? ')';
|
30 |
+
|
31 |
+
varDecl: varType varDecl2 (',' varDecl2)*;
|
32 |
+
|
33 |
+
varType: Newtonian|Frames|Bodies|Particles|Points|Constants
|
34 |
+
| Specifieds|Imaginary|Variables ('\'')*|MotionVariables ('\'')*;
|
35 |
+
|
36 |
+
varDecl2: ID ('{' INT ',' INT '}')? (('{' INT ':' INT (',' INT ':' INT)* '}'))? ('{' INT '}')? ('+'|'-')? ('\'')* ('=' expr)?;
|
37 |
+
|
38 |
+
ranges: ('{' INT ':' INT (',' INT ':' INT)* '}');
|
39 |
+
|
40 |
+
massDecl: Mass massDecl2 (',' massDecl2)*;
|
41 |
+
|
42 |
+
massDecl2: ID '=' expr;
|
43 |
+
|
44 |
+
inertiaDecl: Inertia ID ('(' ID ')')? (',' expr)+;
|
45 |
+
|
46 |
+
matrix: '[' expr ((','|';') expr)* ']';
|
47 |
+
matrixInOutput: (ID (ID '=' (FLOAT|INT)?))|FLOAT|INT;
|
48 |
+
|
49 |
+
codeCommands: units
|
50 |
+
| inputs
|
51 |
+
| outputs
|
52 |
+
| codegen
|
53 |
+
| commands;
|
54 |
+
|
55 |
+
settings: ID (EXP|ID|FLOAT|INT)?;
|
56 |
+
|
57 |
+
units: UnitSystem ID (',' ID)*;
|
58 |
+
inputs: Input inputs2 (',' inputs2)*;
|
59 |
+
id_diff: ID diff?;
|
60 |
+
inputs2: id_diff '=' expr expr?;
|
61 |
+
outputs: Output outputs2 (',' outputs2)*;
|
62 |
+
outputs2: expr expr?;
|
63 |
+
codegen: ID functionCall ('['matrixInOutput (',' matrixInOutput)*']')? ID'.'ID;
|
64 |
+
|
65 |
+
commands: Save ID'.'ID
|
66 |
+
| Encode ID (',' ID)*;
|
67 |
+
|
68 |
+
vec: ID ('>')+
|
69 |
+
| '0>'
|
70 |
+
| '1>>';
|
71 |
+
|
72 |
+
expr: expr '^'<assoc=right> expr # Exponent
|
73 |
+
| expr ('*'|'/') expr # MulDiv
|
74 |
+
| expr ('+'|'-') expr # AddSub
|
75 |
+
| EXP # exp
|
76 |
+
| '-' expr # negativeOne
|
77 |
+
| FLOAT # float
|
78 |
+
| INT # int
|
79 |
+
| ID('\'')* # id
|
80 |
+
| vec # VectorOrDyadic
|
81 |
+
| ID '['expr (',' expr)* ']' # Indexing
|
82 |
+
| functionCall # function
|
83 |
+
| matrix # matrices
|
84 |
+
| '(' expr ')' # parens
|
85 |
+
| expr '=' expr # idEqualsExpr
|
86 |
+
| expr ':' expr # colon
|
87 |
+
| ID? ranges ('\'')* # rangess
|
88 |
+
;
|
89 |
+
|
90 |
+
// These are to take care of the case insensitivity of Autolev.
|
91 |
+
Mass: ('M'|'m')('A'|'a')('S'|'s')('S'|'s');
|
92 |
+
Inertia: ('I'|'i')('N'|'n')('E'|'e')('R'|'r')('T'|'t')('I'|'i')('A'|'a');
|
93 |
+
Input: ('I'|'i')('N'|'n')('P'|'p')('U'|'u')('T'|'t')('S'|'s')?;
|
94 |
+
Output: ('O'|'o')('U'|'u')('T'|'t')('P'|'p')('U'|'u')('T'|'t');
|
95 |
+
Save: ('S'|'s')('A'|'a')('V'|'v')('E'|'e');
|
96 |
+
UnitSystem: ('U'|'u')('N'|'n')('I'|'i')('T'|'t')('S'|'s')('Y'|'y')('S'|'s')('T'|'t')('E'|'e')('M'|'m');
|
97 |
+
Encode: ('E'|'e')('N'|'n')('C'|'c')('O'|'o')('D'|'d')('E'|'e');
|
98 |
+
Newtonian: ('N'|'n')('E'|'e')('W'|'w')('T'|'t')('O'|'o')('N'|'n')('I'|'i')('A'|'a')('N'|'n');
|
99 |
+
Frames: ('F'|'f')('R'|'r')('A'|'a')('M'|'m')('E'|'e')('S'|'s')?;
|
100 |
+
Bodies: ('B'|'b')('O'|'o')('D'|'d')('I'|'i')('E'|'e')('S'|'s')?;
|
101 |
+
Particles: ('P'|'p')('A'|'a')('R'|'r')('T'|'t')('I'|'i')('C'|'c')('L'|'l')('E'|'e')('S'|'s')?;
|
102 |
+
Points: ('P'|'p')('O'|'o')('I'|'i')('N'|'n')('T'|'t')('S'|'s')?;
|
103 |
+
Constants: ('C'|'c')('O'|'o')('N'|'n')('S'|'s')('T'|'t')('A'|'a')('N'|'n')('T'|'t')('S'|'s')?;
|
104 |
+
Specifieds: ('S'|'s')('P'|'p')('E'|'e')('C'|'c')('I'|'i')('F'|'f')('I'|'i')('E'|'e')('D'|'d')('S'|'s')?;
|
105 |
+
Imaginary: ('I'|'i')('M'|'m')('A'|'a')('G'|'g')('I'|'i')('N'|'n')('A'|'a')('R'|'r')('Y'|'y');
|
106 |
+
Variables: ('V'|'v')('A'|'a')('R'|'r')('I'|'i')('A'|'a')('B'|'b')('L'|'l')('E'|'e')('S'|'s')?;
|
107 |
+
MotionVariables: ('M'|'m')('O'|'o')('T'|'t')('I'|'i')('O'|'o')('N'|'n')('V'|'v')('A'|'a')('R'|'r')('I'|'i')('A'|'a')('B'|'b')('L'|'l')('E'|'e')('S'|'s')?;
|
108 |
+
|
109 |
+
fragment DIFF: ('\'')*;
|
110 |
+
fragment DIGIT: [0-9];
|
111 |
+
INT: [0-9]+ ; // match integers
|
112 |
+
FLOAT: DIGIT+ '.' DIGIT*
|
113 |
+
| '.' DIGIT+;
|
114 |
+
EXP: FLOAT 'E' INT
|
115 |
+
| FLOAT 'E' '-' INT;
|
116 |
+
LINE_COMMENT : '%' .*? '\r'? '\n' -> skip ;
|
117 |
+
ID: [a-zA-Z][a-zA-Z0-9_]*;
|
118 |
+
WS: [ \t\r\n&]+ -> skip ; // toss out whitespace
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/__init__.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.external import import_module
|
2 |
+
from sympy.utilities.decorator import doctest_depends_on
|
3 |
+
|
4 |
+
@doctest_depends_on(modules=('antlr4',))
|
5 |
+
def parse_autolev(autolev_code, include_numeric=False):
|
6 |
+
"""Parses Autolev code (version 4.1) to SymPy code.
|
7 |
+
|
8 |
+
Parameters
|
9 |
+
=========
|
10 |
+
autolev_code : Can be an str or any object with a readlines() method (such as a file handle or StringIO).
|
11 |
+
include_numeric : boolean, optional
|
12 |
+
If True NumPy, PyDy, or other numeric code is included for numeric evaluation lines in the Autolev code.
|
13 |
+
|
14 |
+
Returns
|
15 |
+
=======
|
16 |
+
sympy_code : str
|
17 |
+
Equivalent SymPy and/or numpy/pydy code as the input code.
|
18 |
+
|
19 |
+
|
20 |
+
Example (Double Pendulum)
|
21 |
+
=========================
|
22 |
+
>>> my_al_text = ("MOTIONVARIABLES' Q{2}', U{2}'",
|
23 |
+
... "CONSTANTS L,M,G",
|
24 |
+
... "NEWTONIAN N",
|
25 |
+
... "FRAMES A,B",
|
26 |
+
... "SIMPROT(N, A, 3, Q1)",
|
27 |
+
... "SIMPROT(N, B, 3, Q2)",
|
28 |
+
... "W_A_N>=U1*N3>",
|
29 |
+
... "W_B_N>=U2*N3>",
|
30 |
+
... "POINT O",
|
31 |
+
... "PARTICLES P,R",
|
32 |
+
... "P_O_P> = L*A1>",
|
33 |
+
... "P_P_R> = L*B1>",
|
34 |
+
... "V_O_N> = 0>",
|
35 |
+
... "V2PTS(N, A, O, P)",
|
36 |
+
... "V2PTS(N, B, P, R)",
|
37 |
+
... "MASS P=M, R=M",
|
38 |
+
... "Q1' = U1",
|
39 |
+
... "Q2' = U2",
|
40 |
+
... "GRAVITY(G*N1>)",
|
41 |
+
... "ZERO = FR() + FRSTAR()",
|
42 |
+
... "KANE()",
|
43 |
+
... "INPUT M=1,G=9.81,L=1",
|
44 |
+
... "INPUT Q1=.1,Q2=.2,U1=0,U2=0",
|
45 |
+
... "INPUT TFINAL=10, INTEGSTP=.01",
|
46 |
+
... "CODE DYNAMICS() some_filename.c")
|
47 |
+
>>> my_al_text = '\\n'.join(my_al_text)
|
48 |
+
>>> from sympy.parsing.autolev import parse_autolev
|
49 |
+
>>> print(parse_autolev(my_al_text, include_numeric=True))
|
50 |
+
import sympy.physics.mechanics as _me
|
51 |
+
import sympy as _sm
|
52 |
+
import math as m
|
53 |
+
import numpy as _np
|
54 |
+
<BLANKLINE>
|
55 |
+
q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2')
|
56 |
+
q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1)
|
57 |
+
l, m, g = _sm.symbols('l m g', real=True)
|
58 |
+
frame_n = _me.ReferenceFrame('n')
|
59 |
+
frame_a = _me.ReferenceFrame('a')
|
60 |
+
frame_b = _me.ReferenceFrame('b')
|
61 |
+
frame_a.orient(frame_n, 'Axis', [q1, frame_n.z])
|
62 |
+
frame_b.orient(frame_n, 'Axis', [q2, frame_n.z])
|
63 |
+
frame_a.set_ang_vel(frame_n, u1*frame_n.z)
|
64 |
+
frame_b.set_ang_vel(frame_n, u2*frame_n.z)
|
65 |
+
point_o = _me.Point('o')
|
66 |
+
particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))
|
67 |
+
particle_r = _me.Particle('r', _me.Point('r_pt'), _sm.Symbol('m'))
|
68 |
+
particle_p.point.set_pos(point_o, l*frame_a.x)
|
69 |
+
particle_r.point.set_pos(particle_p.point, l*frame_b.x)
|
70 |
+
point_o.set_vel(frame_n, 0)
|
71 |
+
particle_p.point.v2pt_theory(point_o,frame_n,frame_a)
|
72 |
+
particle_r.point.v2pt_theory(particle_p.point,frame_n,frame_b)
|
73 |
+
particle_p.mass = m
|
74 |
+
particle_r.mass = m
|
75 |
+
force_p = particle_p.mass*(g*frame_n.x)
|
76 |
+
force_r = particle_r.mass*(g*frame_n.x)
|
77 |
+
kd_eqs = [q1_d - u1, q2_d - u2]
|
78 |
+
forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x)), (particle_r.point,particle_r.mass*(g*frame_n.x))]
|
79 |
+
kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u1, u2], kd_eqs = kd_eqs)
|
80 |
+
fr, frstar = kane.kanes_equations([particle_p, particle_r], forceList)
|
81 |
+
zero = fr+frstar
|
82 |
+
from pydy.system import System
|
83 |
+
sys = System(kane, constants = {l:1, m:1, g:9.81},
|
84 |
+
specifieds={},
|
85 |
+
initial_conditions={q1:.1, q2:.2, u1:0, u2:0},
|
86 |
+
times = _np.linspace(0.0, 10, 10/.01))
|
87 |
+
<BLANKLINE>
|
88 |
+
y=sys.integrate()
|
89 |
+
<BLANKLINE>
|
90 |
+
"""
|
91 |
+
|
92 |
+
_autolev = import_module(
|
93 |
+
'sympy.parsing.autolev._parse_autolev_antlr',
|
94 |
+
import_kwargs={'fromlist': ['X']})
|
95 |
+
|
96 |
+
if _autolev is not None:
|
97 |
+
return _autolev.parse_autolev(autolev_code, include_numeric)
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (3.81 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_build_autolev_antlr.cpython-310.pyc
ADDED
Binary file (2.49 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_listener_autolev_antlr.cpython-310.pyc
ADDED
Binary file (50.4 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/__pycache__/_parse_autolev_antlr.cpython-310.pyc
ADDED
Binary file (1.51 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/_build_autolev_antlr.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import subprocess
|
3 |
+
import glob
|
4 |
+
|
5 |
+
from sympy.utilities.misc import debug
|
6 |
+
|
7 |
+
here = os.path.dirname(__file__)
|
8 |
+
grammar_file = os.path.abspath(os.path.join(here, "Autolev.g4"))
|
9 |
+
dir_autolev_antlr = os.path.join(here, "_antlr")
|
10 |
+
|
11 |
+
header = '''\
|
12 |
+
# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
|
13 |
+
#
|
14 |
+
# Generated with antlr4
|
15 |
+
# antlr4 is licensed under the BSD-3-Clause License
|
16 |
+
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
|
17 |
+
'''
|
18 |
+
|
19 |
+
|
20 |
+
def check_antlr_version():
|
21 |
+
debug("Checking antlr4 version...")
|
22 |
+
|
23 |
+
try:
|
24 |
+
debug(subprocess.check_output(["antlr4"])
|
25 |
+
.decode('utf-8').split("\n")[0])
|
26 |
+
return True
|
27 |
+
except (subprocess.CalledProcessError, FileNotFoundError):
|
28 |
+
debug("The 'antlr4' command line tool is not installed, "
|
29 |
+
"or not on your PATH.\n"
|
30 |
+
"> Please refer to the README.md file for more information.")
|
31 |
+
return False
|
32 |
+
|
33 |
+
|
34 |
+
def build_parser(output_dir=dir_autolev_antlr):
|
35 |
+
check_antlr_version()
|
36 |
+
|
37 |
+
debug("Updating ANTLR-generated code in {}".format(output_dir))
|
38 |
+
|
39 |
+
if not os.path.exists(output_dir):
|
40 |
+
os.makedirs(output_dir)
|
41 |
+
|
42 |
+
with open(os.path.join(output_dir, "__init__.py"), "w+") as fp:
|
43 |
+
fp.write(header)
|
44 |
+
|
45 |
+
args = [
|
46 |
+
"antlr4",
|
47 |
+
grammar_file,
|
48 |
+
"-o", output_dir,
|
49 |
+
"-no-visitor",
|
50 |
+
]
|
51 |
+
|
52 |
+
debug("Running code generation...\n\t$ {}".format(" ".join(args)))
|
53 |
+
subprocess.check_output(args, cwd=output_dir)
|
54 |
+
|
55 |
+
debug("Applying headers, removing unnecessary files and renaming...")
|
56 |
+
# Handle case insensitive file systems. If the files are already
|
57 |
+
# generated, they will be written to autolev* but Autolev*.* won't match them.
|
58 |
+
for path in (glob.glob(os.path.join(output_dir, "Autolev*.*")) or
|
59 |
+
glob.glob(os.path.join(output_dir, "autolev*.*"))):
|
60 |
+
|
61 |
+
# Remove files ending in .interp or .tokens as they are not needed.
|
62 |
+
if not path.endswith(".py"):
|
63 |
+
os.unlink(path)
|
64 |
+
continue
|
65 |
+
|
66 |
+
new_path = os.path.join(output_dir, os.path.basename(path).lower())
|
67 |
+
with open(path, 'r') as f:
|
68 |
+
lines = [line.rstrip().replace('AutolevParser import', 'autolevparser import') +'\n'
|
69 |
+
for line in f.readlines()]
|
70 |
+
|
71 |
+
os.unlink(path)
|
72 |
+
|
73 |
+
with open(new_path, "w") as out_file:
|
74 |
+
offset = 0
|
75 |
+
while lines[offset].startswith('#'):
|
76 |
+
offset += 1
|
77 |
+
out_file.write(header)
|
78 |
+
out_file.writelines(lines[offset:])
|
79 |
+
|
80 |
+
debug("\t{}".format(new_path))
|
81 |
+
|
82 |
+
return True
|
83 |
+
|
84 |
+
|
85 |
+
if __name__ == "__main__":
|
86 |
+
build_parser()
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/_listener_autolev_antlr.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/_parse_autolev_antlr.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from importlib.metadata import version
|
2 |
+
from sympy.external import import_module
|
3 |
+
|
4 |
+
|
5 |
+
autolevparser = import_module('sympy.parsing.autolev._antlr.autolevparser',
|
6 |
+
import_kwargs={'fromlist': ['AutolevParser']})
|
7 |
+
autolevlexer = import_module('sympy.parsing.autolev._antlr.autolevlexer',
|
8 |
+
import_kwargs={'fromlist': ['AutolevLexer']})
|
9 |
+
autolevlistener = import_module('sympy.parsing.autolev._antlr.autolevlistener',
|
10 |
+
import_kwargs={'fromlist': ['AutolevListener']})
|
11 |
+
|
12 |
+
AutolevParser = getattr(autolevparser, 'AutolevParser', None)
|
13 |
+
AutolevLexer = getattr(autolevlexer, 'AutolevLexer', None)
|
14 |
+
AutolevListener = getattr(autolevlistener, 'AutolevListener', None)
|
15 |
+
|
16 |
+
|
17 |
+
def parse_autolev(autolev_code, include_numeric):
|
18 |
+
antlr4 = import_module('antlr4')
|
19 |
+
if not antlr4 or not version('antlr4-python3-runtime').startswith('4.11'):
|
20 |
+
raise ImportError("Autolev parsing requires the antlr4 Python package,"
|
21 |
+
" provided by pip (antlr4-python3-runtime)"
|
22 |
+
" conda (antlr-python-runtime), version 4.11")
|
23 |
+
try:
|
24 |
+
l = autolev_code.readlines()
|
25 |
+
input_stream = antlr4.InputStream("".join(l))
|
26 |
+
except Exception:
|
27 |
+
input_stream = antlr4.InputStream(autolev_code)
|
28 |
+
|
29 |
+
if AutolevListener:
|
30 |
+
from ._listener_autolev_antlr import MyListener
|
31 |
+
lexer = AutolevLexer(input_stream)
|
32 |
+
token_stream = antlr4.CommonTokenStream(lexer)
|
33 |
+
parser = AutolevParser(token_stream)
|
34 |
+
tree = parser.prog()
|
35 |
+
my_listener = MyListener(include_numeric)
|
36 |
+
walker = antlr4.ParseTreeWalker()
|
37 |
+
walker.walk(my_listener, tree)
|
38 |
+
return "".join(my_listener.output_code)
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest12.al
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
VARIABLES X,Y
|
2 |
+
CONSTANTS A,B,R
|
3 |
+
EQN[1] = A*X^3+B*Y^2-R
|
4 |
+
EQN[2] = A*SIN(X)^2 + B*COS(2*Y) - R^2
|
5 |
+
INPUT A=2.0, B=3.0, R=1.0
|
6 |
+
INPUT X = 30 DEG, Y = 3.14
|
7 |
+
CODE NONLINEAR(EQN,X,Y) some_filename.c
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest12.py
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sympy.physics.mechanics as _me
|
2 |
+
import sympy as _sm
|
3 |
+
import math as m
|
4 |
+
import numpy as _np
|
5 |
+
|
6 |
+
x, y = _me.dynamicsymbols('x y')
|
7 |
+
a, b, r = _sm.symbols('a b r', real=True)
|
8 |
+
eqn = _sm.Matrix([[0]])
|
9 |
+
eqn[0] = a*x**3+b*y**2-r
|
10 |
+
eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]]))
|
11 |
+
eqn[eqn.shape[0]-1] = a*_sm.sin(x)**2+b*_sm.cos(2*y)-r**2
|
12 |
+
matrix_list = []
|
13 |
+
for i in eqn:matrix_list.append(i.subs({a:2.0, b:3.0, r:1.0}))
|
14 |
+
print(_sm.nsolve(matrix_list,(x,y),(_np.deg2rad(30),3.14)))
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest4.al
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
% ruletest4.al
|
2 |
+
|
3 |
+
FRAMES A, B
|
4 |
+
MOTIONVARIABLES Q{3}
|
5 |
+
SIMPROT(A, B, 1, Q3)
|
6 |
+
DCM = A_B
|
7 |
+
M = DCM*3 - A_B
|
8 |
+
|
9 |
+
VARIABLES R
|
10 |
+
CIRCLE_AREA = PI*R^2
|
11 |
+
|
12 |
+
VARIABLES U, A
|
13 |
+
VARIABLES X, Y
|
14 |
+
S = U*T - 1/2*A*T^2
|
15 |
+
|
16 |
+
EXPR1 = 2*A*0.5 - 1.25 + 0.25
|
17 |
+
EXPR2 = -X^2 + Y^2 + 0.25*(X+Y)^2
|
18 |
+
EXPR3 = 0.5E-10
|
19 |
+
|
20 |
+
DYADIC>> = A1>*A1> + A2>*A2> + A3>*A3>
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest5.al
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
% ruletest5.al
|
2 |
+
VARIABLES X', Y'
|
3 |
+
|
4 |
+
E1 = (X+Y)^2 + (X-Y)^3
|
5 |
+
E2 = (X-Y)^2
|
6 |
+
E3 = X^2 + Y^2 + 2*X*Y
|
7 |
+
|
8 |
+
M1 = [E1;E2]
|
9 |
+
M2 = [(X+Y)^2,(X-Y)^2]
|
10 |
+
M3 = M1 + [X;Y]
|
11 |
+
|
12 |
+
AM = EXPAND(M1)
|
13 |
+
CM = EXPAND([(X+Y)^2,(X-Y)^2])
|
14 |
+
EM = EXPAND(M1 + [X;Y])
|
15 |
+
F = EXPAND(E1)
|
16 |
+
G = EXPAND(E2)
|
17 |
+
|
18 |
+
A = FACTOR(E3, X)
|
19 |
+
BM = FACTOR(M1, X)
|
20 |
+
CM = FACTOR(M1 + [X;Y], X)
|
21 |
+
|
22 |
+
A = D(E3, X)
|
23 |
+
B = D(E3, Y)
|
24 |
+
CM = D(M2, X)
|
25 |
+
DM = D(M1 + [X;Y], X)
|
26 |
+
FRAMES A, B
|
27 |
+
A_B = [1,0,0;1,0,0;1,0,0]
|
28 |
+
V1> = X*A1> + Y*A2> + X*Y*A3>
|
29 |
+
E> = D(V1>, X, B)
|
30 |
+
FM = DT(M1)
|
31 |
+
GM = DT([(X+Y)^2,(X-Y)^2])
|
32 |
+
H> = DT(V1>, B)
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest5.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sympy.physics.mechanics as _me
|
2 |
+
import sympy as _sm
|
3 |
+
import math as m
|
4 |
+
import numpy as _np
|
5 |
+
|
6 |
+
x, y = _me.dynamicsymbols('x y')
|
7 |
+
x_d, y_d = _me.dynamicsymbols('x_ y_', 1)
|
8 |
+
e1 = (x+y)**2+(x-y)**3
|
9 |
+
e2 = (x-y)**2
|
10 |
+
e3 = x**2+y**2+2*x*y
|
11 |
+
m1 = _sm.Matrix([e1,e2]).reshape(2, 1)
|
12 |
+
m2 = _sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)
|
13 |
+
m3 = m1+_sm.Matrix([x,y]).reshape(2, 1)
|
14 |
+
am = _sm.Matrix([i.expand() for i in m1]).reshape((m1).shape[0], (m1).shape[1])
|
15 |
+
cm = _sm.Matrix([i.expand() for i in _sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)]).reshape((_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[0], (_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[1])
|
16 |
+
em = _sm.Matrix([i.expand() for i in m1+_sm.Matrix([x,y]).reshape(2, 1)]).reshape((m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[0], (m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[1])
|
17 |
+
f = (e1).expand()
|
18 |
+
g = (e2).expand()
|
19 |
+
a = _sm.factor((e3), x)
|
20 |
+
bm = _sm.Matrix([_sm.factor(i, x) for i in m1]).reshape((m1).shape[0], (m1).shape[1])
|
21 |
+
cm = _sm.Matrix([_sm.factor(i, x) for i in m1+_sm.Matrix([x,y]).reshape(2, 1)]).reshape((m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[0], (m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[1])
|
22 |
+
a = (e3).diff(x)
|
23 |
+
b = (e3).diff(y)
|
24 |
+
cm = _sm.Matrix([i.diff(x) for i in m2]).reshape((m2).shape[0], (m2).shape[1])
|
25 |
+
dm = _sm.Matrix([i.diff(x) for i in m1+_sm.Matrix([x,y]).reshape(2, 1)]).reshape((m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[0], (m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[1])
|
26 |
+
frame_a = _me.ReferenceFrame('a')
|
27 |
+
frame_b = _me.ReferenceFrame('b')
|
28 |
+
frame_b.orient(frame_a, 'DCM', _sm.Matrix([1,0,0,1,0,0,1,0,0]).reshape(3, 3))
|
29 |
+
v1 = x*frame_a.x+y*frame_a.y+x*y*frame_a.z
|
30 |
+
e = (v1).diff(x, frame_b)
|
31 |
+
fm = _sm.Matrix([i.diff(_sm.Symbol('t')) for i in m1]).reshape((m1).shape[0], (m1).shape[1])
|
32 |
+
gm = _sm.Matrix([i.diff(_sm.Symbol('t')) for i in _sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)]).reshape((_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[0], (_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[1])
|
33 |
+
h = (v1).dt(frame_b)
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest6.al
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
% ruletest6.al
|
2 |
+
VARIABLES Q{2}
|
3 |
+
VARIABLES X,Y,Z
|
4 |
+
Q1 = X^2 + Y^2
|
5 |
+
Q2 = X-Y
|
6 |
+
E = Q1 + Q2
|
7 |
+
A = EXPLICIT(E)
|
8 |
+
E2 = COS(X)
|
9 |
+
E3 = COS(X*Y)
|
10 |
+
A = TAYLOR(E2, 0:2, X=0)
|
11 |
+
B = TAYLOR(E3, 0:2, X=0, Y=0)
|
12 |
+
|
13 |
+
E = EXPAND((X+Y)^2)
|
14 |
+
A = EVALUATE(E, X=1, Y=Z)
|
15 |
+
BM = EVALUATE([E;2*E], X=1, Y=Z)
|
16 |
+
|
17 |
+
E = Q1 + Q2
|
18 |
+
A = EVALUATE(E, X=2, Y=Z^2)
|
19 |
+
|
20 |
+
CONSTANTS J,K,L
|
21 |
+
P1 = POLYNOMIAL([J,K,L],X)
|
22 |
+
P2 = POLYNOMIAL(J*X+K,X,1)
|
23 |
+
|
24 |
+
ROOT1 = ROOTS(P1, X, 2)
|
25 |
+
ROOT2 = ROOTS([1;2;3])
|
26 |
+
|
27 |
+
M = [1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16]
|
28 |
+
|
29 |
+
AM = TRANSPOSE(M) + M
|
30 |
+
BM = EIG(M)
|
31 |
+
C1 = DIAGMAT(4, 1)
|
32 |
+
C2 = DIAGMAT(3, 4, 2)
|
33 |
+
DM = INV(M+C1)
|
34 |
+
E = DET(M+C1) + TRACE([1,0;0,1])
|
35 |
+
F = ELEMENT(M, 2, 3)
|
36 |
+
|
37 |
+
A = COLS(M)
|
38 |
+
BM = COLS(M, 1)
|
39 |
+
CM = COLS(M, 1, 2:4, 3)
|
40 |
+
DM = ROWS(M, 1)
|
41 |
+
EM = ROWS(M, 1, 2:4, 3)
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest6.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 |
+
x, y, z = _me.dynamicsymbols('x y z')
|
8 |
+
e = q1+q2
|
9 |
+
a = (e).subs({q1:x**2+y**2, q2:x-y})
|
10 |
+
e2 = _sm.cos(x)
|
11 |
+
e3 = _sm.cos(x*y)
|
12 |
+
a = (e2).series(x, 0, 2).removeO()
|
13 |
+
b = (e3).series(x, 0, 2).removeO().series(y, 0, 2).removeO()
|
14 |
+
e = ((x+y)**2).expand()
|
15 |
+
a = (e).subs({q1:x**2+y**2,q2:x-y}).subs({x:1,y:z})
|
16 |
+
bm = _sm.Matrix([i.subs({x:1,y:z}) for i in _sm.Matrix([e,2*e]).reshape(2, 1)]).reshape((_sm.Matrix([e,2*e]).reshape(2, 1)).shape[0], (_sm.Matrix([e,2*e]).reshape(2, 1)).shape[1])
|
17 |
+
e = q1+q2
|
18 |
+
a = (e).subs({q1:x**2+y**2,q2:x-y}).subs({x:2,y:z**2})
|
19 |
+
j, k, l = _sm.symbols('j k l', real=True)
|
20 |
+
p1 = _sm.Poly(_sm.Matrix([j,k,l]).reshape(1, 3), x)
|
21 |
+
p2 = _sm.Poly(j*x+k, x)
|
22 |
+
root1 = [i.evalf() for i in _sm.solve(p1, x)]
|
23 |
+
root2 = [i.evalf() for i in _sm.solve(_sm.Poly(_sm.Matrix([1,2,3]).reshape(3, 1), x),x)]
|
24 |
+
m = _sm.Matrix([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]).reshape(4, 4)
|
25 |
+
am = (m).T+m
|
26 |
+
bm = _sm.Matrix([i.evalf() for i in (m).eigenvals().keys()])
|
27 |
+
c1 = _sm.diag(1,1,1,1)
|
28 |
+
c2 = _sm.Matrix([2 if i==j else 0 for i in range(3) for j in range(4)]).reshape(3, 4)
|
29 |
+
dm = (m+c1)**(-1)
|
30 |
+
e = (m+c1).det()+(_sm.Matrix([1,0,0,1]).reshape(2, 2)).trace()
|
31 |
+
f = (m)[1,2]
|
32 |
+
a = (m).cols
|
33 |
+
bm = (m).col(0)
|
34 |
+
cm = _sm.Matrix([(m).T.row(0),(m).T.row(1),(m).T.row(2),(m).T.row(3),(m).T.row(2)])
|
35 |
+
dm = (m).row(0)
|
36 |
+
em = _sm.Matrix([(m).row(0),(m).row(1),(m).row(2),(m).row(3),(m).row(2)])
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest7.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sympy.physics.mechanics as _me
|
2 |
+
import sympy as _sm
|
3 |
+
import math as m
|
4 |
+
import numpy as _np
|
5 |
+
|
6 |
+
x, y = _me.dynamicsymbols('x y')
|
7 |
+
x_d, y_d = _me.dynamicsymbols('x_ y_', 1)
|
8 |
+
e = _sm.cos(x)+_sm.sin(x)+_sm.tan(x)+_sm.cosh(x)+_sm.sinh(x)+_sm.tanh(x)+_sm.acos(x)+_sm.asin(x)+_sm.atan(x)+_sm.log(x)+_sm.exp(x)+_sm.sqrt(x)+_sm.factorial(x)+_sm.ceiling(x)+_sm.floor(x)+_sm.sign(x)
|
9 |
+
e = (x)**2+_sm.log(x, 10)
|
10 |
+
a = _sm.Abs(-1*1)+int(1.5)+round(1.9)
|
11 |
+
e1 = 2*x+3*y
|
12 |
+
e2 = x+y
|
13 |
+
am = _sm.Matrix([e1.expand().coeff(x), e1.expand().coeff(y), e2.expand().coeff(x), e2.expand().coeff(y)]).reshape(2, 2)
|
14 |
+
b = (e1).expand().coeff(x)
|
15 |
+
c = (e2).expand().coeff(y)
|
16 |
+
d1 = (e1).collect(x).coeff(x,0)
|
17 |
+
d2 = (e1).collect(x).coeff(x,1)
|
18 |
+
fm = _sm.Matrix([i.collect(x)for i in _sm.Matrix([e1,e2]).reshape(1, 2)]).reshape((_sm.Matrix([e1,e2]).reshape(1, 2)).shape[0], (_sm.Matrix([e1,e2]).reshape(1, 2)).shape[1])
|
19 |
+
f = (e1).collect(y)
|
20 |
+
g = (e1).subs({x:2*x})
|
21 |
+
gm = _sm.Matrix([i.subs({x:3}) for i in _sm.Matrix([e1,e2]).reshape(2, 1)]).reshape((_sm.Matrix([e1,e2]).reshape(2, 1)).shape[0], (_sm.Matrix([e1,e2]).reshape(2, 1)).shape[1])
|
22 |
+
frame_a = _me.ReferenceFrame('a')
|
23 |
+
frame_b = _me.ReferenceFrame('b')
|
24 |
+
theta = _me.dynamicsymbols('theta')
|
25 |
+
frame_b.orient(frame_a, 'Axis', [theta, frame_a.z])
|
26 |
+
v1 = 2*frame_a.x-3*frame_a.y+frame_a.z
|
27 |
+
v2 = frame_b.x+frame_b.y+frame_b.z
|
28 |
+
a = _me.dot(v1, v2)
|
29 |
+
bm = _sm.Matrix([_me.dot(v1, v2),_me.dot(v1, 2*v2)]).reshape(2, 1)
|
30 |
+
c = _me.cross(v1, v2)
|
31 |
+
d = 2*v1.magnitude()+3*v1.magnitude()
|
32 |
+
dyadic = _me.outer(3*frame_a.x, frame_a.x)+_me.outer(frame_a.y, frame_a.y)+_me.outer(2*frame_a.z, frame_a.z)
|
33 |
+
am = (dyadic).to_matrix(frame_b)
|
34 |
+
m = _sm.Matrix([1,2,3]).reshape(3, 1)
|
35 |
+
v = m[0]*frame_a.x +m[1]*frame_a.y +m[2]*frame_a.z
|
venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest8.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sympy.physics.mechanics as _me
|
2 |
+
import sympy as _sm
|
3 |
+
import math as m
|
4 |
+
import numpy as _np
|
5 |
+
|
6 |
+
frame_a = _me.ReferenceFrame('a')
|
7 |
+
c1, c2, c3 = _sm.symbols('c1 c2 c3', real=True)
|
8 |
+
a = _me.inertia(frame_a, 1, 1, 1)
|
9 |
+
particle_p1 = _me.Particle('p1', _me.Point('p1_pt'), _sm.Symbol('m'))
|
10 |
+
particle_p2 = _me.Particle('p2', _me.Point('p2_pt'), _sm.Symbol('m'))
|
11 |
+
body_r_cm = _me.Point('r_cm')
|
12 |
+
body_r_f = _me.ReferenceFrame('r_f')
|
13 |
+
body_r = _me.RigidBody('r', body_r_cm, body_r_f, _sm.symbols('m'), (_me.outer(body_r_f.x,body_r_f.x),body_r_cm))
|
14 |
+
frame_a.orient(body_r_f, 'DCM', _sm.Matrix([1,1,1,1,1,0,0,0,1]).reshape(3, 3))
|
15 |
+
point_o = _me.Point('o')
|
16 |
+
m1 = _sm.symbols('m1')
|
17 |
+
particle_p1.mass = m1
|
18 |
+
m2 = _sm.symbols('m2')
|
19 |
+
particle_p2.mass = m2
|
20 |
+
mr = _sm.symbols('mr')
|
21 |
+
body_r.mass = mr
|
22 |
+
i1 = _sm.symbols('i1')
|
23 |
+
i2 = _sm.symbols('i2')
|
24 |
+
i3 = _sm.symbols('i3')
|
25 |
+
body_r.inertia = (_me.inertia(body_r_f, i1, i2, i3, 0, 0, 0), body_r_cm)
|
26 |
+
point_o.set_pos(particle_p1.point, c1*frame_a.x)
|
27 |
+
point_o.set_pos(particle_p2.point, c2*frame_a.y)
|
28 |
+
point_o.set_pos(body_r_cm, c3*frame_a.z)
|
29 |
+
a = _me.inertia_of_point_mass(particle_p1.mass, particle_p1.point.pos_from(point_o), frame_a)
|
30 |
+
a = _me.inertia_of_point_mass(particle_p2.mass, particle_p2.point.pos_from(point_o), frame_a)
|
31 |
+
a = body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a)
|
32 |
+
a = _me.inertia_of_point_mass(particle_p1.mass, particle_p1.point.pos_from(point_o), frame_a) + _me.inertia_of_point_mass(particle_p2.mass, particle_p2.point.pos_from(point_o), frame_a) + body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a)
|
33 |
+
a = _me.inertia_of_point_mass(particle_p1.mass, particle_p1.point.pos_from(point_o), frame_a) + body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a)
|
34 |
+
a = body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a)
|
35 |
+
a = body_r.inertia[0]
|
36 |
+
particle_p2.point.set_pos(particle_p1.point, c1*frame_a.x+c2*frame_a.y)
|
37 |
+
body_r_cm.set_pos(particle_p1.point, c3*frame_a.x)
|
38 |
+
body_r_cm.set_pos(particle_p2.point, c3*frame_a.y)
|
39 |
+
b = _me.functions.center_of_mass(point_o,particle_p1, particle_p2, body_r)
|
40 |
+
b = _me.functions.center_of_mass(point_o,particle_p1, body_r)
|
41 |
+
b = _me.functions.center_of_mass(particle_p1.point,particle_p1, particle_p2, body_r)
|
42 |
+
u1, u2, u3 = _me.dynamicsymbols('u1 u2 u3')
|
43 |
+
v = u1*frame_a.x+u2*frame_a.y+u3*frame_a.z
|
44 |
+
u = (v+c1*frame_a.x).normalize()
|
45 |
+
particle_p1.point.set_vel(frame_a, u1*frame_a.x)
|
46 |
+
a = particle_p1.point.partial_velocity(frame_a, u1)
|
47 |
+
m = particle_p1.mass+body_r.mass
|
48 |
+
m = particle_p2.mass
|
49 |
+
m = particle_p1.mass+particle_p2.mass+body_r.mass
|
venv/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"""
|
venv/lib/python3.10/site-packages/sympy/parsing/c/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (253 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/c/__pycache__/c_parser.cpython-310.pyc
ADDED
Binary file (26.2 kB). View file
|
|
venv/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
|
venv/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. """
|
venv/lib/python3.10/site-packages/sympy/parsing/fortran/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (267 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/fortran/__pycache__/fortran_parser.cpython-310.pyc
ADDED
Binary file (8.78 kB). View file
|
|
venv/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
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
The MIT License (MIT)
|
2 |
+
|
3 |
+
Copyright 2016, latex2sympy
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/LaTeX.g4
ADDED
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
ANTLR4 LaTeX Math Grammar
|
3 |
+
|
4 |
+
Ported from latex2sympy by @augustt198 https://github.com/augustt198/latex2sympy See license in
|
5 |
+
LICENSE.txt
|
6 |
+
*/
|
7 |
+
|
8 |
+
/*
|
9 |
+
After changing this file, it is necessary to run `python setup.py antlr` in the root directory of
|
10 |
+
the repository. This will regenerate the code in `sympy/parsing/latex/_antlr/*.py`.
|
11 |
+
*/
|
12 |
+
|
13 |
+
grammar LaTeX;
|
14 |
+
|
15 |
+
options {
|
16 |
+
language = Python3;
|
17 |
+
}
|
18 |
+
|
19 |
+
WS: [ \t\r\n]+ -> skip;
|
20 |
+
THINSPACE: ('\\,' | '\\thinspace') -> skip;
|
21 |
+
MEDSPACE: ('\\:' | '\\medspace') -> skip;
|
22 |
+
THICKSPACE: ('\\;' | '\\thickspace') -> skip;
|
23 |
+
QUAD: '\\quad' -> skip;
|
24 |
+
QQUAD: '\\qquad' -> skip;
|
25 |
+
NEGTHINSPACE: ('\\!' | '\\negthinspace') -> skip;
|
26 |
+
NEGMEDSPACE: '\\negmedspace' -> skip;
|
27 |
+
NEGTHICKSPACE: '\\negthickspace' -> skip;
|
28 |
+
CMD_LEFT: '\\left' -> skip;
|
29 |
+
CMD_RIGHT: '\\right' -> skip;
|
30 |
+
|
31 |
+
IGNORE:
|
32 |
+
(
|
33 |
+
'\\vrule'
|
34 |
+
| '\\vcenter'
|
35 |
+
| '\\vbox'
|
36 |
+
| '\\vskip'
|
37 |
+
| '\\vspace'
|
38 |
+
| '\\hfil'
|
39 |
+
| '\\*'
|
40 |
+
| '\\-'
|
41 |
+
| '\\.'
|
42 |
+
| '\\/'
|
43 |
+
| '\\"'
|
44 |
+
| '\\('
|
45 |
+
| '\\='
|
46 |
+
) -> skip;
|
47 |
+
|
48 |
+
ADD: '+';
|
49 |
+
SUB: '-';
|
50 |
+
MUL: '*';
|
51 |
+
DIV: '/';
|
52 |
+
|
53 |
+
L_PAREN: '(';
|
54 |
+
R_PAREN: ')';
|
55 |
+
L_BRACE: '{';
|
56 |
+
R_BRACE: '}';
|
57 |
+
L_BRACE_LITERAL: '\\{';
|
58 |
+
R_BRACE_LITERAL: '\\}';
|
59 |
+
L_BRACKET: '[';
|
60 |
+
R_BRACKET: ']';
|
61 |
+
|
62 |
+
BAR: '|';
|
63 |
+
|
64 |
+
R_BAR: '\\right|';
|
65 |
+
L_BAR: '\\left|';
|
66 |
+
|
67 |
+
L_ANGLE: '\\langle';
|
68 |
+
R_ANGLE: '\\rangle';
|
69 |
+
FUNC_LIM: '\\lim';
|
70 |
+
LIM_APPROACH_SYM:
|
71 |
+
'\\to'
|
72 |
+
| '\\rightarrow'
|
73 |
+
| '\\Rightarrow'
|
74 |
+
| '\\longrightarrow'
|
75 |
+
| '\\Longrightarrow';
|
76 |
+
FUNC_INT:
|
77 |
+
'\\int'
|
78 |
+
| '\\int\\limits';
|
79 |
+
FUNC_SUM: '\\sum';
|
80 |
+
FUNC_PROD: '\\prod';
|
81 |
+
|
82 |
+
FUNC_EXP: '\\exp';
|
83 |
+
FUNC_LOG: '\\log';
|
84 |
+
FUNC_LG: '\\lg';
|
85 |
+
FUNC_LN: '\\ln';
|
86 |
+
FUNC_SIN: '\\sin';
|
87 |
+
FUNC_COS: '\\cos';
|
88 |
+
FUNC_TAN: '\\tan';
|
89 |
+
FUNC_CSC: '\\csc';
|
90 |
+
FUNC_SEC: '\\sec';
|
91 |
+
FUNC_COT: '\\cot';
|
92 |
+
|
93 |
+
FUNC_ARCSIN: '\\arcsin';
|
94 |
+
FUNC_ARCCOS: '\\arccos';
|
95 |
+
FUNC_ARCTAN: '\\arctan';
|
96 |
+
FUNC_ARCCSC: '\\arccsc';
|
97 |
+
FUNC_ARCSEC: '\\arcsec';
|
98 |
+
FUNC_ARCCOT: '\\arccot';
|
99 |
+
|
100 |
+
FUNC_SINH: '\\sinh';
|
101 |
+
FUNC_COSH: '\\cosh';
|
102 |
+
FUNC_TANH: '\\tanh';
|
103 |
+
FUNC_ARSINH: '\\arsinh';
|
104 |
+
FUNC_ARCOSH: '\\arcosh';
|
105 |
+
FUNC_ARTANH: '\\artanh';
|
106 |
+
|
107 |
+
L_FLOOR: '\\lfloor';
|
108 |
+
R_FLOOR: '\\rfloor';
|
109 |
+
L_CEIL: '\\lceil';
|
110 |
+
R_CEIL: '\\rceil';
|
111 |
+
|
112 |
+
FUNC_SQRT: '\\sqrt';
|
113 |
+
FUNC_OVERLINE: '\\overline';
|
114 |
+
|
115 |
+
CMD_TIMES: '\\times';
|
116 |
+
CMD_CDOT: '\\cdot';
|
117 |
+
CMD_DIV: '\\div';
|
118 |
+
CMD_FRAC:
|
119 |
+
'\\frac'
|
120 |
+
| '\\dfrac'
|
121 |
+
| '\\tfrac';
|
122 |
+
CMD_BINOM: '\\binom';
|
123 |
+
CMD_DBINOM: '\\dbinom';
|
124 |
+
CMD_TBINOM: '\\tbinom';
|
125 |
+
|
126 |
+
CMD_MATHIT: '\\mathit';
|
127 |
+
|
128 |
+
UNDERSCORE: '_';
|
129 |
+
CARET: '^';
|
130 |
+
COLON: ':';
|
131 |
+
|
132 |
+
fragment WS_CHAR: [ \t\r\n];
|
133 |
+
DIFFERENTIAL: 'd' WS_CHAR*? ([a-zA-Z] | '\\' [a-zA-Z]+);
|
134 |
+
|
135 |
+
LETTER: [a-zA-Z];
|
136 |
+
DIGIT: [0-9];
|
137 |
+
|
138 |
+
EQUAL: (('&' WS_CHAR*?)? '=') | ('=' (WS_CHAR*? '&')?);
|
139 |
+
NEQ: '\\neq';
|
140 |
+
|
141 |
+
LT: '<';
|
142 |
+
LTE: ('\\leq' | '\\le' | LTE_Q | LTE_S);
|
143 |
+
LTE_Q: '\\leqq';
|
144 |
+
LTE_S: '\\leqslant';
|
145 |
+
|
146 |
+
GT: '>';
|
147 |
+
GTE: ('\\geq' | '\\ge' | GTE_Q | GTE_S);
|
148 |
+
GTE_Q: '\\geqq';
|
149 |
+
GTE_S: '\\geqslant';
|
150 |
+
|
151 |
+
BANG: '!';
|
152 |
+
|
153 |
+
SINGLE_QUOTES: '\''+;
|
154 |
+
|
155 |
+
SYMBOL: '\\' [a-zA-Z]+;
|
156 |
+
|
157 |
+
math: relation;
|
158 |
+
|
159 |
+
relation:
|
160 |
+
relation (EQUAL | LT | LTE | GT | GTE | NEQ) relation
|
161 |
+
| expr;
|
162 |
+
|
163 |
+
equality: expr EQUAL expr;
|
164 |
+
|
165 |
+
expr: additive;
|
166 |
+
|
167 |
+
additive: additive (ADD | SUB) additive | mp;
|
168 |
+
|
169 |
+
// mult part
|
170 |
+
mp:
|
171 |
+
mp (MUL | CMD_TIMES | CMD_CDOT | DIV | CMD_DIV | COLON) mp
|
172 |
+
| unary;
|
173 |
+
|
174 |
+
mp_nofunc:
|
175 |
+
mp_nofunc (
|
176 |
+
MUL
|
177 |
+
| CMD_TIMES
|
178 |
+
| CMD_CDOT
|
179 |
+
| DIV
|
180 |
+
| CMD_DIV
|
181 |
+
| COLON
|
182 |
+
) mp_nofunc
|
183 |
+
| unary_nofunc;
|
184 |
+
|
185 |
+
unary: (ADD | SUB) unary | postfix+;
|
186 |
+
|
187 |
+
unary_nofunc:
|
188 |
+
(ADD | SUB) unary_nofunc
|
189 |
+
| postfix postfix_nofunc*;
|
190 |
+
|
191 |
+
postfix: exp postfix_op*;
|
192 |
+
postfix_nofunc: exp_nofunc postfix_op*;
|
193 |
+
postfix_op: BANG | eval_at;
|
194 |
+
|
195 |
+
eval_at:
|
196 |
+
BAR (eval_at_sup | eval_at_sub | eval_at_sup eval_at_sub);
|
197 |
+
|
198 |
+
eval_at_sub: UNDERSCORE L_BRACE (expr | equality) R_BRACE;
|
199 |
+
|
200 |
+
eval_at_sup: CARET L_BRACE (expr | equality) R_BRACE;
|
201 |
+
|
202 |
+
exp: exp CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp;
|
203 |
+
|
204 |
+
exp_nofunc:
|
205 |
+
exp_nofunc CARET (atom | L_BRACE expr R_BRACE) subexpr?
|
206 |
+
| comp_nofunc;
|
207 |
+
|
208 |
+
comp:
|
209 |
+
group
|
210 |
+
| abs_group
|
211 |
+
| func
|
212 |
+
| atom
|
213 |
+
| floor
|
214 |
+
| ceil;
|
215 |
+
|
216 |
+
comp_nofunc:
|
217 |
+
group
|
218 |
+
| abs_group
|
219 |
+
| atom
|
220 |
+
| floor
|
221 |
+
| ceil;
|
222 |
+
|
223 |
+
group:
|
224 |
+
L_PAREN expr R_PAREN
|
225 |
+
| L_BRACKET expr R_BRACKET
|
226 |
+
| L_BRACE expr R_BRACE
|
227 |
+
| L_BRACE_LITERAL expr R_BRACE_LITERAL;
|
228 |
+
|
229 |
+
abs_group: BAR expr BAR;
|
230 |
+
|
231 |
+
number: DIGIT+ (',' DIGIT DIGIT DIGIT)* ('.' DIGIT+)?;
|
232 |
+
|
233 |
+
atom: (LETTER | SYMBOL) (subexpr? SINGLE_QUOTES? | SINGLE_QUOTES? subexpr?)
|
234 |
+
| number
|
235 |
+
| DIFFERENTIAL
|
236 |
+
| mathit
|
237 |
+
| frac
|
238 |
+
| binom
|
239 |
+
| bra
|
240 |
+
| ket;
|
241 |
+
|
242 |
+
bra: L_ANGLE expr (R_BAR | BAR);
|
243 |
+
ket: (L_BAR | BAR) expr R_ANGLE;
|
244 |
+
|
245 |
+
mathit: CMD_MATHIT L_BRACE mathit_text R_BRACE;
|
246 |
+
mathit_text: LETTER*;
|
247 |
+
|
248 |
+
frac: CMD_FRAC (upperd = DIGIT | L_BRACE upper = expr R_BRACE)
|
249 |
+
(lowerd = DIGIT | L_BRACE lower = expr R_BRACE);
|
250 |
+
|
251 |
+
binom:
|
252 |
+
(CMD_BINOM | CMD_DBINOM | CMD_TBINOM) L_BRACE n = expr R_BRACE L_BRACE k = expr R_BRACE;
|
253 |
+
|
254 |
+
floor: L_FLOOR val = expr R_FLOOR;
|
255 |
+
ceil: L_CEIL val = expr R_CEIL;
|
256 |
+
|
257 |
+
func_normal:
|
258 |
+
FUNC_EXP
|
259 |
+
| FUNC_LOG
|
260 |
+
| FUNC_LG
|
261 |
+
| FUNC_LN
|
262 |
+
| FUNC_SIN
|
263 |
+
| FUNC_COS
|
264 |
+
| FUNC_TAN
|
265 |
+
| FUNC_CSC
|
266 |
+
| FUNC_SEC
|
267 |
+
| FUNC_COT
|
268 |
+
| FUNC_ARCSIN
|
269 |
+
| FUNC_ARCCOS
|
270 |
+
| FUNC_ARCTAN
|
271 |
+
| FUNC_ARCCSC
|
272 |
+
| FUNC_ARCSEC
|
273 |
+
| FUNC_ARCCOT
|
274 |
+
| FUNC_SINH
|
275 |
+
| FUNC_COSH
|
276 |
+
| FUNC_TANH
|
277 |
+
| FUNC_ARSINH
|
278 |
+
| FUNC_ARCOSH
|
279 |
+
| FUNC_ARTANH;
|
280 |
+
|
281 |
+
func:
|
282 |
+
func_normal (subexpr? supexpr? | supexpr? subexpr?) (
|
283 |
+
L_PAREN func_arg R_PAREN
|
284 |
+
| func_arg_noparens
|
285 |
+
)
|
286 |
+
| (LETTER | SYMBOL) (subexpr? SINGLE_QUOTES? | SINGLE_QUOTES? subexpr?) // e.g. f(x), f_1'(x)
|
287 |
+
L_PAREN args R_PAREN
|
288 |
+
| FUNC_INT (subexpr supexpr | supexpr subexpr)? (
|
289 |
+
additive? DIFFERENTIAL
|
290 |
+
| frac
|
291 |
+
| additive
|
292 |
+
)
|
293 |
+
| FUNC_SQRT (L_BRACKET root = expr R_BRACKET)? L_BRACE base = expr R_BRACE
|
294 |
+
| FUNC_OVERLINE L_BRACE base = expr R_BRACE
|
295 |
+
| (FUNC_SUM | FUNC_PROD) (subeq supexpr | supexpr subeq) mp
|
296 |
+
| FUNC_LIM limit_sub mp;
|
297 |
+
|
298 |
+
args: (expr ',' args) | expr;
|
299 |
+
|
300 |
+
limit_sub:
|
301 |
+
UNDERSCORE L_BRACE (LETTER | SYMBOL) LIM_APPROACH_SYM expr (
|
302 |
+
CARET ((L_BRACE (ADD | SUB) R_BRACE) | ADD | SUB)
|
303 |
+
)? R_BRACE;
|
304 |
+
|
305 |
+
func_arg: expr | (expr ',' func_arg);
|
306 |
+
func_arg_noparens: mp_nofunc;
|
307 |
+
|
308 |
+
subexpr: UNDERSCORE (atom | L_BRACE expr R_BRACE);
|
309 |
+
supexpr: CARET (atom | L_BRACE expr R_BRACE);
|
310 |
+
|
311 |
+
subeq: UNDERSCORE L_BRACE equality R_BRACE;
|
312 |
+
supeq: UNDERSCORE L_BRACE equality R_BRACE;
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/__init__.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.external import import_module
|
2 |
+
from sympy.utilities.decorator import doctest_depends_on
|
3 |
+
|
4 |
+
from .errors import LaTeXParsingError # noqa
|
5 |
+
|
6 |
+
@doctest_depends_on(modules=('antlr4',))
|
7 |
+
def parse_latex(s):
|
8 |
+
r"""Converts the string ``s`` to a SymPy ``Expr``
|
9 |
+
|
10 |
+
Parameters
|
11 |
+
==========
|
12 |
+
|
13 |
+
s : str
|
14 |
+
The LaTeX string to parse. In Python source containing LaTeX,
|
15 |
+
*raw strings* (denoted with ``r"``, like this one) are preferred,
|
16 |
+
as LaTeX makes liberal use of the ``\`` character, which would
|
17 |
+
trigger escaping in normal Python strings.
|
18 |
+
|
19 |
+
Examples
|
20 |
+
========
|
21 |
+
|
22 |
+
>>> from sympy.parsing.latex import parse_latex
|
23 |
+
>>> expr = parse_latex(r"\frac {1 + \sqrt {\a}} {\b}")
|
24 |
+
>>> expr
|
25 |
+
(sqrt(a) + 1)/b
|
26 |
+
>>> expr.evalf(4, subs=dict(a=5, b=2))
|
27 |
+
1.618
|
28 |
+
"""
|
29 |
+
|
30 |
+
_latex = import_module(
|
31 |
+
'sympy.parsing.latex._parse_latex_antlr',
|
32 |
+
import_kwargs={'fromlist': ['X']})
|
33 |
+
|
34 |
+
if _latex is not None:
|
35 |
+
return _latex.parse_latex(s)
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.22 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/_build_latex_antlr.cpython-310.pyc
ADDED
Binary file (2.62 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/_parse_latex_antlr.cpython-310.pyc
ADDED
Binary file (13.6 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/errors.cpython-310.pyc
ADDED
Binary file (359 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__init__.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
|
2 |
+
#
|
3 |
+
# Generated from ../LaTeX.g4, derived from latex2sympy
|
4 |
+
# latex2sympy is licensed under the MIT license
|
5 |
+
# https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
|
6 |
+
#
|
7 |
+
# Generated with antlr4
|
8 |
+
# antlr4 is licensed under the BSD-3-Clause License
|
9 |
+
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (194 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexlexer.cpython-310.pyc
ADDED
Binary file (43.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexparser.cpython-310.pyc
ADDED
Binary file (110 kB). View file
|
|