applied-ai-018 commited on
Commit
e5ed7cf
·
verified ·
1 Parent(s): 390d097

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/sympy/parsing/__init__.py +4 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/parsing/ast_parser.py +79 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/Autolev.g4 +118 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/__init__.py +97 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__init__.py +5 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__pycache__/__init__.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__pycache__/autolevlexer.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__pycache__/autolevlistener.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__pycache__/autolevparser.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevlexer.py +253 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevlistener.py +421 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevparser.py +0 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_build_autolev_antlr.py +86 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_listener_autolev_antlr.py +0 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_parse_autolev_antlr.py +38 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest1.py +15 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest10.al +58 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest11.al +6 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest2.al +12 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest8.al +38 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest9.py +55 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/LICENSE.txt +21 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/LaTeX.g4 +312 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/__init__.py +35 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/__init__.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/_build_latex_antlr.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/_parse_latex_antlr.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/errors.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__init__.py +9 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/__init__.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexlexer.cpython-310.pyc +0 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexparser.cpython-310.pyc +0 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/latexlexer.py +512 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/latexparser.py +0 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_build_latex_antlr.py +91 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_parse_latex_antlr.py +604 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/errors.py +2 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/parsing/mathematica.py +1080 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/parsing/maxima.py +71 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/parsing/sym_expr.py +279 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/parsing/sympy_parser.py +1264 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__init__.py +0 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_ast_parser.cpython-310.pyc +0 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_autolev.cpython-310.pyc +0 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_c_parser.cpython-310.pyc +0 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_fortran_parser.cpython-310.pyc +0 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_implicit_multiplication_application.cpython-310.pyc +0 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_latex.cpython-310.pyc +0 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_latex_deps.cpython-310.pyc +0 -0
llmeval-env/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
llmeval-env/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)
llmeval-env/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
llmeval-env/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)
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
2
+ #
3
+ # Generated with antlr4
4
+ # antlr4 is licensed under the BSD-3-Clause License
5
+ # https://github.com/antlr/antlr4/blob/master/LICENSE.txt
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (201 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__pycache__/autolevlexer.cpython-310.pyc ADDED
Binary file (20.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__pycache__/autolevlistener.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__pycache__/autolevparser.cpython-310.pyc ADDED
Binary file (94.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevlexer.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
2
+ #
3
+ # Generated with antlr4
4
+ # antlr4 is licensed under the BSD-3-Clause License
5
+ # https://github.com/antlr/antlr4/blob/master/LICENSE.txt
6
+ from antlr4 import *
7
+ from io import StringIO
8
+ import sys
9
+ if sys.version_info[1] > 5:
10
+ from typing import TextIO
11
+ else:
12
+ from typing.io import TextIO
13
+
14
+
15
+ def serializedATN():
16
+ return [
17
+ 4,0,49,393,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,
18
+ 2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,
19
+ 13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,
20
+ 19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,
21
+ 26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,
22
+ 32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,
23
+ 39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7,
24
+ 45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,1,0,1,0,1,1,
25
+ 1,1,1,2,1,2,1,3,1,3,1,3,1,4,1,4,1,4,1,5,1,5,1,5,1,6,1,6,1,6,1,7,
26
+ 1,7,1,7,1,8,1,8,1,8,1,9,1,9,1,10,1,10,1,11,1,11,1,12,1,12,1,13,1,
27
+ 13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18,1,18,1,19,1,19,1,
28
+ 20,1,20,1,21,1,21,1,21,1,22,1,22,1,22,1,22,1,23,1,23,1,24,1,24,1,
29
+ 25,1,25,1,26,1,26,1,26,1,26,1,26,1,27,1,27,1,27,1,27,1,27,1,27,1,
30
+ 27,1,27,1,28,1,28,1,28,1,28,1,28,1,28,3,28,184,8,28,1,29,1,29,1,
31
+ 29,1,29,1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,30,1,31,1,31,1,31,1,
32
+ 31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1,
33
+ 32,1,32,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,34,1,
34
+ 34,1,34,1,34,1,34,1,34,3,34,232,8,34,1,35,1,35,1,35,1,35,1,35,1,
35
+ 35,3,35,240,8,35,1,36,1,36,1,36,1,36,1,36,1,36,1,36,1,36,1,36,3,
36
+ 36,251,8,36,1,37,1,37,1,37,1,37,1,37,1,37,3,37,259,8,37,1,38,1,38,
37
+ 1,38,1,38,1,38,1,38,1,38,1,38,1,38,3,38,270,8,38,1,39,1,39,1,39,
38
+ 1,39,1,39,1,39,1,39,1,39,1,39,1,39,3,39,282,8,39,1,40,1,40,1,40,
39
+ 1,40,1,40,1,40,1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41,1,41,1,41,
40
+ 1,41,1,41,1,41,3,41,303,8,41,1,42,1,42,1,42,1,42,1,42,1,42,1,42,
41
+ 1,42,1,42,1,42,1,42,1,42,1,42,1,42,1,42,3,42,320,8,42,1,43,5,43,
42
+ 323,8,43,10,43,12,43,326,9,43,1,44,1,44,1,45,4,45,331,8,45,11,45,
43
+ 12,45,332,1,46,4,46,336,8,46,11,46,12,46,337,1,46,1,46,5,46,342,
44
+ 8,46,10,46,12,46,345,9,46,1,46,1,46,4,46,349,8,46,11,46,12,46,350,
45
+ 3,46,353,8,46,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,3,47,
46
+ 364,8,47,1,48,1,48,5,48,368,8,48,10,48,12,48,371,9,48,1,48,3,48,
47
+ 374,8,48,1,48,1,48,1,48,1,48,1,49,1,49,5,49,382,8,49,10,49,12,49,
48
+ 385,9,49,1,50,4,50,388,8,50,11,50,12,50,389,1,50,1,50,1,369,0,51,
49
+ 1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,
50
+ 27,14,29,15,31,16,33,17,35,18,37,19,39,20,41,21,43,22,45,23,47,24,
51
+ 49,25,51,26,53,27,55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35,
52
+ 71,36,73,37,75,38,77,39,79,40,81,41,83,42,85,43,87,0,89,0,91,44,
53
+ 93,45,95,46,97,47,99,48,101,49,1,0,24,2,0,77,77,109,109,2,0,65,65,
54
+ 97,97,2,0,83,83,115,115,2,0,73,73,105,105,2,0,78,78,110,110,2,0,
55
+ 69,69,101,101,2,0,82,82,114,114,2,0,84,84,116,116,2,0,80,80,112,
56
+ 112,2,0,85,85,117,117,2,0,79,79,111,111,2,0,86,86,118,118,2,0,89,
57
+ 89,121,121,2,0,67,67,99,99,2,0,68,68,100,100,2,0,87,87,119,119,2,
58
+ 0,70,70,102,102,2,0,66,66,98,98,2,0,76,76,108,108,2,0,71,71,103,
59
+ 103,1,0,48,57,2,0,65,90,97,122,4,0,48,57,65,90,95,95,97,122,4,0,
60
+ 9,10,13,13,32,32,38,38,410,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,
61
+ 7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,
62
+ 1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,27,
63
+ 1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0,37,
64
+ 1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0,0,0,0,47,
65
+ 1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0,0,57,
66
+ 1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0,67,
67
+ 1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0,77,
68
+ 1,0,0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0,91,
69
+ 1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0,97,1,0,0,0,0,99,1,0,0,0,0,101,
70
+ 1,0,0,0,1,103,1,0,0,0,3,105,1,0,0,0,5,107,1,0,0,0,7,109,1,0,0,0,
71
+ 9,112,1,0,0,0,11,115,1,0,0,0,13,118,1,0,0,0,15,121,1,0,0,0,17,124,
72
+ 1,0,0,0,19,127,1,0,0,0,21,129,1,0,0,0,23,131,1,0,0,0,25,133,1,0,
73
+ 0,0,27,135,1,0,0,0,29,137,1,0,0,0,31,139,1,0,0,0,33,141,1,0,0,0,
74
+ 35,143,1,0,0,0,37,145,1,0,0,0,39,147,1,0,0,0,41,149,1,0,0,0,43,151,
75
+ 1,0,0,0,45,154,1,0,0,0,47,158,1,0,0,0,49,160,1,0,0,0,51,162,1,0,
76
+ 0,0,53,164,1,0,0,0,55,169,1,0,0,0,57,177,1,0,0,0,59,185,1,0,0,0,
77
+ 61,192,1,0,0,0,63,197,1,0,0,0,65,208,1,0,0,0,67,215,1,0,0,0,69,225,
78
+ 1,0,0,0,71,233,1,0,0,0,73,241,1,0,0,0,75,252,1,0,0,0,77,260,1,0,
79
+ 0,0,79,271,1,0,0,0,81,283,1,0,0,0,83,293,1,0,0,0,85,304,1,0,0,0,
80
+ 87,324,1,0,0,0,89,327,1,0,0,0,91,330,1,0,0,0,93,352,1,0,0,0,95,363,
81
+ 1,0,0,0,97,365,1,0,0,0,99,379,1,0,0,0,101,387,1,0,0,0,103,104,5,
82
+ 91,0,0,104,2,1,0,0,0,105,106,5,93,0,0,106,4,1,0,0,0,107,108,5,61,
83
+ 0,0,108,6,1,0,0,0,109,110,5,43,0,0,110,111,5,61,0,0,111,8,1,0,0,
84
+ 0,112,113,5,45,0,0,113,114,5,61,0,0,114,10,1,0,0,0,115,116,5,58,
85
+ 0,0,116,117,5,61,0,0,117,12,1,0,0,0,118,119,5,42,0,0,119,120,5,61,
86
+ 0,0,120,14,1,0,0,0,121,122,5,47,0,0,122,123,5,61,0,0,123,16,1,0,
87
+ 0,0,124,125,5,94,0,0,125,126,5,61,0,0,126,18,1,0,0,0,127,128,5,44,
88
+ 0,0,128,20,1,0,0,0,129,130,5,39,0,0,130,22,1,0,0,0,131,132,5,40,
89
+ 0,0,132,24,1,0,0,0,133,134,5,41,0,0,134,26,1,0,0,0,135,136,5,123,
90
+ 0,0,136,28,1,0,0,0,137,138,5,125,0,0,138,30,1,0,0,0,139,140,5,58,
91
+ 0,0,140,32,1,0,0,0,141,142,5,43,0,0,142,34,1,0,0,0,143,144,5,45,
92
+ 0,0,144,36,1,0,0,0,145,146,5,59,0,0,146,38,1,0,0,0,147,148,5,46,
93
+ 0,0,148,40,1,0,0,0,149,150,5,62,0,0,150,42,1,0,0,0,151,152,5,48,
94
+ 0,0,152,153,5,62,0,0,153,44,1,0,0,0,154,155,5,49,0,0,155,156,5,62,
95
+ 0,0,156,157,5,62,0,0,157,46,1,0,0,0,158,159,5,94,0,0,159,48,1,0,
96
+ 0,0,160,161,5,42,0,0,161,50,1,0,0,0,162,163,5,47,0,0,163,52,1,0,
97
+ 0,0,164,165,7,0,0,0,165,166,7,1,0,0,166,167,7,2,0,0,167,168,7,2,
98
+ 0,0,168,54,1,0,0,0,169,170,7,3,0,0,170,171,7,4,0,0,171,172,7,5,0,
99
+ 0,172,173,7,6,0,0,173,174,7,7,0,0,174,175,7,3,0,0,175,176,7,1,0,
100
+ 0,176,56,1,0,0,0,177,178,7,3,0,0,178,179,7,4,0,0,179,180,7,8,0,0,
101
+ 180,181,7,9,0,0,181,183,7,7,0,0,182,184,7,2,0,0,183,182,1,0,0,0,
102
+ 183,184,1,0,0,0,184,58,1,0,0,0,185,186,7,10,0,0,186,187,7,9,0,0,
103
+ 187,188,7,7,0,0,188,189,7,8,0,0,189,190,7,9,0,0,190,191,7,7,0,0,
104
+ 191,60,1,0,0,0,192,193,7,2,0,0,193,194,7,1,0,0,194,195,7,11,0,0,
105
+ 195,196,7,5,0,0,196,62,1,0,0,0,197,198,7,9,0,0,198,199,7,4,0,0,199,
106
+ 200,7,3,0,0,200,201,7,7,0,0,201,202,7,2,0,0,202,203,7,12,0,0,203,
107
+ 204,7,2,0,0,204,205,7,7,0,0,205,206,7,5,0,0,206,207,7,0,0,0,207,
108
+ 64,1,0,0,0,208,209,7,5,0,0,209,210,7,4,0,0,210,211,7,13,0,0,211,
109
+ 212,7,10,0,0,212,213,7,14,0,0,213,214,7,5,0,0,214,66,1,0,0,0,215,
110
+ 216,7,4,0,0,216,217,7,5,0,0,217,218,7,15,0,0,218,219,7,7,0,0,219,
111
+ 220,7,10,0,0,220,221,7,4,0,0,221,222,7,3,0,0,222,223,7,1,0,0,223,
112
+ 224,7,4,0,0,224,68,1,0,0,0,225,226,7,16,0,0,226,227,7,6,0,0,227,
113
+ 228,7,1,0,0,228,229,7,0,0,0,229,231,7,5,0,0,230,232,7,2,0,0,231,
114
+ 230,1,0,0,0,231,232,1,0,0,0,232,70,1,0,0,0,233,234,7,17,0,0,234,
115
+ 235,7,10,0,0,235,236,7,14,0,0,236,237,7,3,0,0,237,239,7,5,0,0,238,
116
+ 240,7,2,0,0,239,238,1,0,0,0,239,240,1,0,0,0,240,72,1,0,0,0,241,242,
117
+ 7,8,0,0,242,243,7,1,0,0,243,244,7,6,0,0,244,245,7,7,0,0,245,246,
118
+ 7,3,0,0,246,247,7,13,0,0,247,248,7,18,0,0,248,250,7,5,0,0,249,251,
119
+ 7,2,0,0,250,249,1,0,0,0,250,251,1,0,0,0,251,74,1,0,0,0,252,253,7,
120
+ 8,0,0,253,254,7,10,0,0,254,255,7,3,0,0,255,256,7,4,0,0,256,258,7,
121
+ 7,0,0,257,259,7,2,0,0,258,257,1,0,0,0,258,259,1,0,0,0,259,76,1,0,
122
+ 0,0,260,261,7,13,0,0,261,262,7,10,0,0,262,263,7,4,0,0,263,264,7,
123
+ 2,0,0,264,265,7,7,0,0,265,266,7,1,0,0,266,267,7,4,0,0,267,269,7,
124
+ 7,0,0,268,270,7,2,0,0,269,268,1,0,0,0,269,270,1,0,0,0,270,78,1,0,
125
+ 0,0,271,272,7,2,0,0,272,273,7,8,0,0,273,274,7,5,0,0,274,275,7,13,
126
+ 0,0,275,276,7,3,0,0,276,277,7,16,0,0,277,278,7,3,0,0,278,279,7,5,
127
+ 0,0,279,281,7,14,0,0,280,282,7,2,0,0,281,280,1,0,0,0,281,282,1,0,
128
+ 0,0,282,80,1,0,0,0,283,284,7,3,0,0,284,285,7,0,0,0,285,286,7,1,0,
129
+ 0,286,287,7,19,0,0,287,288,7,3,0,0,288,289,7,4,0,0,289,290,7,1,0,
130
+ 0,290,291,7,6,0,0,291,292,7,12,0,0,292,82,1,0,0,0,293,294,7,11,0,
131
+ 0,294,295,7,1,0,0,295,296,7,6,0,0,296,297,7,3,0,0,297,298,7,1,0,
132
+ 0,298,299,7,17,0,0,299,300,7,18,0,0,300,302,7,5,0,0,301,303,7,2,
133
+ 0,0,302,301,1,0,0,0,302,303,1,0,0,0,303,84,1,0,0,0,304,305,7,0,0,
134
+ 0,305,306,7,10,0,0,306,307,7,7,0,0,307,308,7,3,0,0,308,309,7,10,
135
+ 0,0,309,310,7,4,0,0,310,311,7,11,0,0,311,312,7,1,0,0,312,313,7,6,
136
+ 0,0,313,314,7,3,0,0,314,315,7,1,0,0,315,316,7,17,0,0,316,317,7,18,
137
+ 0,0,317,319,7,5,0,0,318,320,7,2,0,0,319,318,1,0,0,0,319,320,1,0,
138
+ 0,0,320,86,1,0,0,0,321,323,5,39,0,0,322,321,1,0,0,0,323,326,1,0,
139
+ 0,0,324,322,1,0,0,0,324,325,1,0,0,0,325,88,1,0,0,0,326,324,1,0,0,
140
+ 0,327,328,7,20,0,0,328,90,1,0,0,0,329,331,7,20,0,0,330,329,1,0,0,
141
+ 0,331,332,1,0,0,0,332,330,1,0,0,0,332,333,1,0,0,0,333,92,1,0,0,0,
142
+ 334,336,3,89,44,0,335,334,1,0,0,0,336,337,1,0,0,0,337,335,1,0,0,
143
+ 0,337,338,1,0,0,0,338,339,1,0,0,0,339,343,5,46,0,0,340,342,3,89,
144
+ 44,0,341,340,1,0,0,0,342,345,1,0,0,0,343,341,1,0,0,0,343,344,1,0,
145
+ 0,0,344,353,1,0,0,0,345,343,1,0,0,0,346,348,5,46,0,0,347,349,3,89,
146
+ 44,0,348,347,1,0,0,0,349,350,1,0,0,0,350,348,1,0,0,0,350,351,1,0,
147
+ 0,0,351,353,1,0,0,0,352,335,1,0,0,0,352,346,1,0,0,0,353,94,1,0,0,
148
+ 0,354,355,3,93,46,0,355,356,5,69,0,0,356,357,3,91,45,0,357,364,1,
149
+ 0,0,0,358,359,3,93,46,0,359,360,5,69,0,0,360,361,5,45,0,0,361,362,
150
+ 3,91,45,0,362,364,1,0,0,0,363,354,1,0,0,0,363,358,1,0,0,0,364,96,
151
+ 1,0,0,0,365,369,5,37,0,0,366,368,9,0,0,0,367,366,1,0,0,0,368,371,
152
+ 1,0,0,0,369,370,1,0,0,0,369,367,1,0,0,0,370,373,1,0,0,0,371,369,
153
+ 1,0,0,0,372,374,5,13,0,0,373,372,1,0,0,0,373,374,1,0,0,0,374,375,
154
+ 1,0,0,0,375,376,5,10,0,0,376,377,1,0,0,0,377,378,6,48,0,0,378,98,
155
+ 1,0,0,0,379,383,7,21,0,0,380,382,7,22,0,0,381,380,1,0,0,0,382,385,
156
+ 1,0,0,0,383,381,1,0,0,0,383,384,1,0,0,0,384,100,1,0,0,0,385,383,
157
+ 1,0,0,0,386,388,7,23,0,0,387,386,1,0,0,0,388,389,1,0,0,0,389,387,
158
+ 1,0,0,0,389,390,1,0,0,0,390,391,1,0,0,0,391,392,6,50,0,0,392,102,
159
+ 1,0,0,0,21,0,183,231,239,250,258,269,281,302,319,324,332,337,343,
160
+ 350,352,363,369,373,383,389,1,6,0,0
161
+ ]
162
+
163
+ class AutolevLexer(Lexer):
164
+
165
+ atn = ATNDeserializer().deserialize(serializedATN())
166
+
167
+ decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
168
+
169
+ T__0 = 1
170
+ T__1 = 2
171
+ T__2 = 3
172
+ T__3 = 4
173
+ T__4 = 5
174
+ T__5 = 6
175
+ T__6 = 7
176
+ T__7 = 8
177
+ T__8 = 9
178
+ T__9 = 10
179
+ T__10 = 11
180
+ T__11 = 12
181
+ T__12 = 13
182
+ T__13 = 14
183
+ T__14 = 15
184
+ T__15 = 16
185
+ T__16 = 17
186
+ T__17 = 18
187
+ T__18 = 19
188
+ T__19 = 20
189
+ T__20 = 21
190
+ T__21 = 22
191
+ T__22 = 23
192
+ T__23 = 24
193
+ T__24 = 25
194
+ T__25 = 26
195
+ Mass = 27
196
+ Inertia = 28
197
+ Input = 29
198
+ Output = 30
199
+ Save = 31
200
+ UnitSystem = 32
201
+ Encode = 33
202
+ Newtonian = 34
203
+ Frames = 35
204
+ Bodies = 36
205
+ Particles = 37
206
+ Points = 38
207
+ Constants = 39
208
+ Specifieds = 40
209
+ Imaginary = 41
210
+ Variables = 42
211
+ MotionVariables = 43
212
+ INT = 44
213
+ FLOAT = 45
214
+ EXP = 46
215
+ LINE_COMMENT = 47
216
+ ID = 48
217
+ WS = 49
218
+
219
+ channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
220
+
221
+ modeNames = [ "DEFAULT_MODE" ]
222
+
223
+ literalNames = [ "<INVALID>",
224
+ "'['", "']'", "'='", "'+='", "'-='", "':='", "'*='", "'/='",
225
+ "'^='", "','", "'''", "'('", "')'", "'{'", "'}'", "':'", "'+'",
226
+ "'-'", "';'", "'.'", "'>'", "'0>'", "'1>>'", "'^'", "'*'", "'/'" ]
227
+
228
+ symbolicNames = [ "<INVALID>",
229
+ "Mass", "Inertia", "Input", "Output", "Save", "UnitSystem",
230
+ "Encode", "Newtonian", "Frames", "Bodies", "Particles", "Points",
231
+ "Constants", "Specifieds", "Imaginary", "Variables", "MotionVariables",
232
+ "INT", "FLOAT", "EXP", "LINE_COMMENT", "ID", "WS" ]
233
+
234
+ ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6",
235
+ "T__7", "T__8", "T__9", "T__10", "T__11", "T__12", "T__13",
236
+ "T__14", "T__15", "T__16", "T__17", "T__18", "T__19",
237
+ "T__20", "T__21", "T__22", "T__23", "T__24", "T__25",
238
+ "Mass", "Inertia", "Input", "Output", "Save", "UnitSystem",
239
+ "Encode", "Newtonian", "Frames", "Bodies", "Particles",
240
+ "Points", "Constants", "Specifieds", "Imaginary", "Variables",
241
+ "MotionVariables", "DIFF", "DIGIT", "INT", "FLOAT", "EXP",
242
+ "LINE_COMMENT", "ID", "WS" ]
243
+
244
+ grammarFileName = "Autolev.g4"
245
+
246
+ def __init__(self, input=None, output:TextIO = sys.stdout):
247
+ super().__init__(input, output)
248
+ self.checkVersion("4.11.1")
249
+ self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
250
+ self._actions = None
251
+ self._predicates = None
252
+
253
+
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevlistener.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
2
+ #
3
+ # Generated with antlr4
4
+ # antlr4 is licensed under the BSD-3-Clause License
5
+ # https://github.com/antlr/antlr4/blob/master/LICENSE.txt
6
+ from antlr4 import *
7
+ if __name__ is not None and "." in __name__:
8
+ from .autolevparser import AutolevParser
9
+ else:
10
+ from autolevparser import AutolevParser
11
+
12
+ # This class defines a complete listener for a parse tree produced by AutolevParser.
13
+ class AutolevListener(ParseTreeListener):
14
+
15
+ # Enter a parse tree produced by AutolevParser#prog.
16
+ def enterProg(self, ctx:AutolevParser.ProgContext):
17
+ pass
18
+
19
+ # Exit a parse tree produced by AutolevParser#prog.
20
+ def exitProg(self, ctx:AutolevParser.ProgContext):
21
+ pass
22
+
23
+
24
+ # Enter a parse tree produced by AutolevParser#stat.
25
+ def enterStat(self, ctx:AutolevParser.StatContext):
26
+ pass
27
+
28
+ # Exit a parse tree produced by AutolevParser#stat.
29
+ def exitStat(self, ctx:AutolevParser.StatContext):
30
+ pass
31
+
32
+
33
+ # Enter a parse tree produced by AutolevParser#vecAssign.
34
+ def enterVecAssign(self, ctx:AutolevParser.VecAssignContext):
35
+ pass
36
+
37
+ # Exit a parse tree produced by AutolevParser#vecAssign.
38
+ def exitVecAssign(self, ctx:AutolevParser.VecAssignContext):
39
+ pass
40
+
41
+
42
+ # Enter a parse tree produced by AutolevParser#indexAssign.
43
+ def enterIndexAssign(self, ctx:AutolevParser.IndexAssignContext):
44
+ pass
45
+
46
+ # Exit a parse tree produced by AutolevParser#indexAssign.
47
+ def exitIndexAssign(self, ctx:AutolevParser.IndexAssignContext):
48
+ pass
49
+
50
+
51
+ # Enter a parse tree produced by AutolevParser#regularAssign.
52
+ def enterRegularAssign(self, ctx:AutolevParser.RegularAssignContext):
53
+ pass
54
+
55
+ # Exit a parse tree produced by AutolevParser#regularAssign.
56
+ def exitRegularAssign(self, ctx:AutolevParser.RegularAssignContext):
57
+ pass
58
+
59
+
60
+ # Enter a parse tree produced by AutolevParser#equals.
61
+ def enterEquals(self, ctx:AutolevParser.EqualsContext):
62
+ pass
63
+
64
+ # Exit a parse tree produced by AutolevParser#equals.
65
+ def exitEquals(self, ctx:AutolevParser.EqualsContext):
66
+ pass
67
+
68
+
69
+ # Enter a parse tree produced by AutolevParser#index.
70
+ def enterIndex(self, ctx:AutolevParser.IndexContext):
71
+ pass
72
+
73
+ # Exit a parse tree produced by AutolevParser#index.
74
+ def exitIndex(self, ctx:AutolevParser.IndexContext):
75
+ pass
76
+
77
+
78
+ # Enter a parse tree produced by AutolevParser#diff.
79
+ def enterDiff(self, ctx:AutolevParser.DiffContext):
80
+ pass
81
+
82
+ # Exit a parse tree produced by AutolevParser#diff.
83
+ def exitDiff(self, ctx:AutolevParser.DiffContext):
84
+ pass
85
+
86
+
87
+ # Enter a parse tree produced by AutolevParser#functionCall.
88
+ def enterFunctionCall(self, ctx:AutolevParser.FunctionCallContext):
89
+ pass
90
+
91
+ # Exit a parse tree produced by AutolevParser#functionCall.
92
+ def exitFunctionCall(self, ctx:AutolevParser.FunctionCallContext):
93
+ pass
94
+
95
+
96
+ # Enter a parse tree produced by AutolevParser#varDecl.
97
+ def enterVarDecl(self, ctx:AutolevParser.VarDeclContext):
98
+ pass
99
+
100
+ # Exit a parse tree produced by AutolevParser#varDecl.
101
+ def exitVarDecl(self, ctx:AutolevParser.VarDeclContext):
102
+ pass
103
+
104
+
105
+ # Enter a parse tree produced by AutolevParser#varType.
106
+ def enterVarType(self, ctx:AutolevParser.VarTypeContext):
107
+ pass
108
+
109
+ # Exit a parse tree produced by AutolevParser#varType.
110
+ def exitVarType(self, ctx:AutolevParser.VarTypeContext):
111
+ pass
112
+
113
+
114
+ # Enter a parse tree produced by AutolevParser#varDecl2.
115
+ def enterVarDecl2(self, ctx:AutolevParser.VarDecl2Context):
116
+ pass
117
+
118
+ # Exit a parse tree produced by AutolevParser#varDecl2.
119
+ def exitVarDecl2(self, ctx:AutolevParser.VarDecl2Context):
120
+ pass
121
+
122
+
123
+ # Enter a parse tree produced by AutolevParser#ranges.
124
+ def enterRanges(self, ctx:AutolevParser.RangesContext):
125
+ pass
126
+
127
+ # Exit a parse tree produced by AutolevParser#ranges.
128
+ def exitRanges(self, ctx:AutolevParser.RangesContext):
129
+ pass
130
+
131
+
132
+ # Enter a parse tree produced by AutolevParser#massDecl.
133
+ def enterMassDecl(self, ctx:AutolevParser.MassDeclContext):
134
+ pass
135
+
136
+ # Exit a parse tree produced by AutolevParser#massDecl.
137
+ def exitMassDecl(self, ctx:AutolevParser.MassDeclContext):
138
+ pass
139
+
140
+
141
+ # Enter a parse tree produced by AutolevParser#massDecl2.
142
+ def enterMassDecl2(self, ctx:AutolevParser.MassDecl2Context):
143
+ pass
144
+
145
+ # Exit a parse tree produced by AutolevParser#massDecl2.
146
+ def exitMassDecl2(self, ctx:AutolevParser.MassDecl2Context):
147
+ pass
148
+
149
+
150
+ # Enter a parse tree produced by AutolevParser#inertiaDecl.
151
+ def enterInertiaDecl(self, ctx:AutolevParser.InertiaDeclContext):
152
+ pass
153
+
154
+ # Exit a parse tree produced by AutolevParser#inertiaDecl.
155
+ def exitInertiaDecl(self, ctx:AutolevParser.InertiaDeclContext):
156
+ pass
157
+
158
+
159
+ # Enter a parse tree produced by AutolevParser#matrix.
160
+ def enterMatrix(self, ctx:AutolevParser.MatrixContext):
161
+ pass
162
+
163
+ # Exit a parse tree produced by AutolevParser#matrix.
164
+ def exitMatrix(self, ctx:AutolevParser.MatrixContext):
165
+ pass
166
+
167
+
168
+ # Enter a parse tree produced by AutolevParser#matrixInOutput.
169
+ def enterMatrixInOutput(self, ctx:AutolevParser.MatrixInOutputContext):
170
+ pass
171
+
172
+ # Exit a parse tree produced by AutolevParser#matrixInOutput.
173
+ def exitMatrixInOutput(self, ctx:AutolevParser.MatrixInOutputContext):
174
+ pass
175
+
176
+
177
+ # Enter a parse tree produced by AutolevParser#codeCommands.
178
+ def enterCodeCommands(self, ctx:AutolevParser.CodeCommandsContext):
179
+ pass
180
+
181
+ # Exit a parse tree produced by AutolevParser#codeCommands.
182
+ def exitCodeCommands(self, ctx:AutolevParser.CodeCommandsContext):
183
+ pass
184
+
185
+
186
+ # Enter a parse tree produced by AutolevParser#settings.
187
+ def enterSettings(self, ctx:AutolevParser.SettingsContext):
188
+ pass
189
+
190
+ # Exit a parse tree produced by AutolevParser#settings.
191
+ def exitSettings(self, ctx:AutolevParser.SettingsContext):
192
+ pass
193
+
194
+
195
+ # Enter a parse tree produced by AutolevParser#units.
196
+ def enterUnits(self, ctx:AutolevParser.UnitsContext):
197
+ pass
198
+
199
+ # Exit a parse tree produced by AutolevParser#units.
200
+ def exitUnits(self, ctx:AutolevParser.UnitsContext):
201
+ pass
202
+
203
+
204
+ # Enter a parse tree produced by AutolevParser#inputs.
205
+ def enterInputs(self, ctx:AutolevParser.InputsContext):
206
+ pass
207
+
208
+ # Exit a parse tree produced by AutolevParser#inputs.
209
+ def exitInputs(self, ctx:AutolevParser.InputsContext):
210
+ pass
211
+
212
+
213
+ # Enter a parse tree produced by AutolevParser#id_diff.
214
+ def enterId_diff(self, ctx:AutolevParser.Id_diffContext):
215
+ pass
216
+
217
+ # Exit a parse tree produced by AutolevParser#id_diff.
218
+ def exitId_diff(self, ctx:AutolevParser.Id_diffContext):
219
+ pass
220
+
221
+
222
+ # Enter a parse tree produced by AutolevParser#inputs2.
223
+ def enterInputs2(self, ctx:AutolevParser.Inputs2Context):
224
+ pass
225
+
226
+ # Exit a parse tree produced by AutolevParser#inputs2.
227
+ def exitInputs2(self, ctx:AutolevParser.Inputs2Context):
228
+ pass
229
+
230
+
231
+ # Enter a parse tree produced by AutolevParser#outputs.
232
+ def enterOutputs(self, ctx:AutolevParser.OutputsContext):
233
+ pass
234
+
235
+ # Exit a parse tree produced by AutolevParser#outputs.
236
+ def exitOutputs(self, ctx:AutolevParser.OutputsContext):
237
+ pass
238
+
239
+
240
+ # Enter a parse tree produced by AutolevParser#outputs2.
241
+ def enterOutputs2(self, ctx:AutolevParser.Outputs2Context):
242
+ pass
243
+
244
+ # Exit a parse tree produced by AutolevParser#outputs2.
245
+ def exitOutputs2(self, ctx:AutolevParser.Outputs2Context):
246
+ pass
247
+
248
+
249
+ # Enter a parse tree produced by AutolevParser#codegen.
250
+ def enterCodegen(self, ctx:AutolevParser.CodegenContext):
251
+ pass
252
+
253
+ # Exit a parse tree produced by AutolevParser#codegen.
254
+ def exitCodegen(self, ctx:AutolevParser.CodegenContext):
255
+ pass
256
+
257
+
258
+ # Enter a parse tree produced by AutolevParser#commands.
259
+ def enterCommands(self, ctx:AutolevParser.CommandsContext):
260
+ pass
261
+
262
+ # Exit a parse tree produced by AutolevParser#commands.
263
+ def exitCommands(self, ctx:AutolevParser.CommandsContext):
264
+ pass
265
+
266
+
267
+ # Enter a parse tree produced by AutolevParser#vec.
268
+ def enterVec(self, ctx:AutolevParser.VecContext):
269
+ pass
270
+
271
+ # Exit a parse tree produced by AutolevParser#vec.
272
+ def exitVec(self, ctx:AutolevParser.VecContext):
273
+ pass
274
+
275
+
276
+ # Enter a parse tree produced by AutolevParser#parens.
277
+ def enterParens(self, ctx:AutolevParser.ParensContext):
278
+ pass
279
+
280
+ # Exit a parse tree produced by AutolevParser#parens.
281
+ def exitParens(self, ctx:AutolevParser.ParensContext):
282
+ pass
283
+
284
+
285
+ # Enter a parse tree produced by AutolevParser#VectorOrDyadic.
286
+ def enterVectorOrDyadic(self, ctx:AutolevParser.VectorOrDyadicContext):
287
+ pass
288
+
289
+ # Exit a parse tree produced by AutolevParser#VectorOrDyadic.
290
+ def exitVectorOrDyadic(self, ctx:AutolevParser.VectorOrDyadicContext):
291
+ pass
292
+
293
+
294
+ # Enter a parse tree produced by AutolevParser#Exponent.
295
+ def enterExponent(self, ctx:AutolevParser.ExponentContext):
296
+ pass
297
+
298
+ # Exit a parse tree produced by AutolevParser#Exponent.
299
+ def exitExponent(self, ctx:AutolevParser.ExponentContext):
300
+ pass
301
+
302
+
303
+ # Enter a parse tree produced by AutolevParser#MulDiv.
304
+ def enterMulDiv(self, ctx:AutolevParser.MulDivContext):
305
+ pass
306
+
307
+ # Exit a parse tree produced by AutolevParser#MulDiv.
308
+ def exitMulDiv(self, ctx:AutolevParser.MulDivContext):
309
+ pass
310
+
311
+
312
+ # Enter a parse tree produced by AutolevParser#AddSub.
313
+ def enterAddSub(self, ctx:AutolevParser.AddSubContext):
314
+ pass
315
+
316
+ # Exit a parse tree produced by AutolevParser#AddSub.
317
+ def exitAddSub(self, ctx:AutolevParser.AddSubContext):
318
+ pass
319
+
320
+
321
+ # Enter a parse tree produced by AutolevParser#float.
322
+ def enterFloat(self, ctx:AutolevParser.FloatContext):
323
+ pass
324
+
325
+ # Exit a parse tree produced by AutolevParser#float.
326
+ def exitFloat(self, ctx:AutolevParser.FloatContext):
327
+ pass
328
+
329
+
330
+ # Enter a parse tree produced by AutolevParser#int.
331
+ def enterInt(self, ctx:AutolevParser.IntContext):
332
+ pass
333
+
334
+ # Exit a parse tree produced by AutolevParser#int.
335
+ def exitInt(self, ctx:AutolevParser.IntContext):
336
+ pass
337
+
338
+
339
+ # Enter a parse tree produced by AutolevParser#idEqualsExpr.
340
+ def enterIdEqualsExpr(self, ctx:AutolevParser.IdEqualsExprContext):
341
+ pass
342
+
343
+ # Exit a parse tree produced by AutolevParser#idEqualsExpr.
344
+ def exitIdEqualsExpr(self, ctx:AutolevParser.IdEqualsExprContext):
345
+ pass
346
+
347
+
348
+ # Enter a parse tree produced by AutolevParser#negativeOne.
349
+ def enterNegativeOne(self, ctx:AutolevParser.NegativeOneContext):
350
+ pass
351
+
352
+ # Exit a parse tree produced by AutolevParser#negativeOne.
353
+ def exitNegativeOne(self, ctx:AutolevParser.NegativeOneContext):
354
+ pass
355
+
356
+
357
+ # Enter a parse tree produced by AutolevParser#function.
358
+ def enterFunction(self, ctx:AutolevParser.FunctionContext):
359
+ pass
360
+
361
+ # Exit a parse tree produced by AutolevParser#function.
362
+ def exitFunction(self, ctx:AutolevParser.FunctionContext):
363
+ pass
364
+
365
+
366
+ # Enter a parse tree produced by AutolevParser#rangess.
367
+ def enterRangess(self, ctx:AutolevParser.RangessContext):
368
+ pass
369
+
370
+ # Exit a parse tree produced by AutolevParser#rangess.
371
+ def exitRangess(self, ctx:AutolevParser.RangessContext):
372
+ pass
373
+
374
+
375
+ # Enter a parse tree produced by AutolevParser#colon.
376
+ def enterColon(self, ctx:AutolevParser.ColonContext):
377
+ pass
378
+
379
+ # Exit a parse tree produced by AutolevParser#colon.
380
+ def exitColon(self, ctx:AutolevParser.ColonContext):
381
+ pass
382
+
383
+
384
+ # Enter a parse tree produced by AutolevParser#id.
385
+ def enterId(self, ctx:AutolevParser.IdContext):
386
+ pass
387
+
388
+ # Exit a parse tree produced by AutolevParser#id.
389
+ def exitId(self, ctx:AutolevParser.IdContext):
390
+ pass
391
+
392
+
393
+ # Enter a parse tree produced by AutolevParser#exp.
394
+ def enterExp(self, ctx:AutolevParser.ExpContext):
395
+ pass
396
+
397
+ # Exit a parse tree produced by AutolevParser#exp.
398
+ def exitExp(self, ctx:AutolevParser.ExpContext):
399
+ pass
400
+
401
+
402
+ # Enter a parse tree produced by AutolevParser#matrices.
403
+ def enterMatrices(self, ctx:AutolevParser.MatricesContext):
404
+ pass
405
+
406
+ # Exit a parse tree produced by AutolevParser#matrices.
407
+ def exitMatrices(self, ctx:AutolevParser.MatricesContext):
408
+ pass
409
+
410
+
411
+ # Enter a parse tree produced by AutolevParser#Indexing.
412
+ def enterIndexing(self, ctx:AutolevParser.IndexingContext):
413
+ pass
414
+
415
+ # Exit a parse tree produced by AutolevParser#Indexing.
416
+ def exitIndexing(self, ctx:AutolevParser.IndexingContext):
417
+ pass
418
+
419
+
420
+
421
+ del AutolevParser
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevparser.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/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()
llmeval-env/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
 
llmeval-env/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)
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest1.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ f = _sm.S(3)
7
+ g = _sm.S(9.81)
8
+ a, b = _sm.symbols('a b', real=True)
9
+ s, s1 = _sm.symbols('s s1', real=True)
10
+ s2, s3 = _sm.symbols('s2 s3', real=True, nonnegative=True)
11
+ s4 = _sm.symbols('s4', real=True, nonpositive=True)
12
+ k1, k2, k3, k4, l1, l2, l3, p11, p12, p13, p21, p22, p23 = _sm.symbols('k1 k2 k3 k4 l1 l2 l3 p11 p12 p13 p21 p22 p23', real=True)
13
+ c11, c12, c13, c21, c22, c23 = _sm.symbols('c11 c12 c13 c21 c22 c23', real=True)
14
+ e1 = a*f+s2-g
15
+ e2 = f**2+k3*k2*g
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest10.al ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % ruletest10.al
2
+
3
+ VARIABLES X,Y
4
+ COMPLEX ON
5
+ CONSTANTS A,B
6
+ E = A*(B*X+Y)^2
7
+ M = [E;E]
8
+ EXPAND(E)
9
+ EXPAND(M)
10
+ FACTOR(E,X)
11
+ FACTOR(M,X)
12
+
13
+ EQN[1] = A*X + B*Y
14
+ EQN[2] = 2*A*X - 3*B*Y
15
+ SOLVE(EQN, X, Y)
16
+ RHS_Y = RHS(Y)
17
+ E = (X+Y)^2 + 2*X^2
18
+ ARRANGE(E, 2, X)
19
+
20
+ CONSTANTS A,B,C
21
+ M = [A,B;C,0]
22
+ M2 = EVALUATE(M,A=1,B=2,C=3)
23
+ EIG(M2, EIGVALUE, EIGVEC)
24
+
25
+ NEWTONIAN N
26
+ FRAMES A
27
+ SIMPROT(N, A, N1>, X)
28
+ DEGREES OFF
29
+ SIMPROT(N, A, N1>, PI/2)
30
+
31
+ CONSTANTS C{3}
32
+ V> = C1*A1> + C2*A2> + C3*A3>
33
+ POINTS O, P
34
+ P_P_O> = C1*A1>
35
+ EXPRESS(V>,N)
36
+ EXPRESS(P_P_O>,N)
37
+ W_A_N> = C3*A3>
38
+ ANGVEL(A,N)
39
+
40
+ V2PTS(N,A,O,P)
41
+ PARTICLES P{2}
42
+ V2PTS(N,A,P1,P2)
43
+ A2PTS(N,A,P1,P)
44
+
45
+ BODIES B{2}
46
+ CONSTANT G
47
+ GRAVITY(G*N1>)
48
+
49
+ VARIABLE Z
50
+ V> = X*A1> + Y*A3>
51
+ P_P_O> = X*A1> + Y*A2>
52
+ X = 2*Z
53
+ Y = Z
54
+ EXPLICIT(V>)
55
+ EXPLICIT(P_P_O>)
56
+
57
+ FORCE(O/P1, X*Y*A1>)
58
+ FORCE(P2, X*Y*A1>)
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest11.al ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ VARIABLES X, Y
2
+ CONSTANTS A{1:2, 1:2}, B{1:2}
3
+ EQN[1] = A11*x + A12*y - B1
4
+ EQN[2] = A21*x + A22*y - B2
5
+ INPUT A11=2, A12=5, A21=3, A22=4, B1=7, B2=6
6
+ CODE ALGEBRAIC(EQN, X, Y) some_filename.c
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest2.al ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % ruletest2.al
2
+ VARIABLES X1,X2
3
+ SPECIFIED F1 = X1*X2 + 3*X1^2
4
+ SPECIFIED F2=X1*T+X2*T^2
5
+ VARIABLE X', Y''
6
+ MOTIONVARIABLES Q{3}, U{2}
7
+ VARIABLES P{2}'
8
+ VARIABLE W{3}', R{2}''
9
+ VARIABLES C{1:2, 1:2}
10
+ VARIABLES D{1,3}
11
+ VARIABLES J{1:2}
12
+ IMAGINARY N
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest8.al ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % ruletest8.al
2
+ FRAMES A
3
+ CONSTANTS C{3}
4
+ A>> = EXPRESS(1>>,A)
5
+ PARTICLES P1, P2
6
+ BODIES R
7
+ R_A = [1,1,1;1,1,0;0,0,1]
8
+ POINT O
9
+ MASS P1=M1, P2=M2, R=MR
10
+ INERTIA R, I1, I2, I3
11
+ P_P1_O> = C1*A1>
12
+ P_P2_O> = C2*A2>
13
+ P_RO_O> = C3*A3>
14
+ A>> = EXPRESS(I_P1_O>>, A)
15
+ A>> = EXPRESS(I_P2_O>>, A)
16
+ A>> = EXPRESS(I_R_O>>, A)
17
+ A>> = EXPRESS(INERTIA(O), A)
18
+ A>> = EXPRESS(INERTIA(O, P1, R), A)
19
+ A>> = EXPRESS(I_R_O>>, A)
20
+ A>> = EXPRESS(I_R_RO>>, A)
21
+
22
+ P_P1_P2> = C1*A1> + C2*A2>
23
+ P_P1_RO> = C3*A1>
24
+ P_P2_RO> = C3*A2>
25
+
26
+ B> = CM(O)
27
+ B> = CM(O, P1, R)
28
+ B> = CM(P1)
29
+
30
+ MOTIONVARIABLES U{3}
31
+ V> = U1*A1> + U2*A2> + U3*A3>
32
+ U> = UNITVEC(V> + C1*A1>)
33
+ V_P1_A> = U1*A1>
34
+ A> = PARTIALS(V_P1_A>, U1)
35
+
36
+ M = MASS(P1,R)
37
+ M = MASS(P2)
38
+ M = MASS()
llmeval-env/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest9.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics as _me
2
+ import sympy as _sm
3
+ import math as m
4
+ import numpy as _np
5
+
6
+ frame_n = _me.ReferenceFrame('n')
7
+ frame_a = _me.ReferenceFrame('a')
8
+ a = 0
9
+ d = _me.inertia(frame_a, 1, 1, 1)
10
+ point_po1 = _me.Point('po1')
11
+ point_po2 = _me.Point('po2')
12
+ particle_p1 = _me.Particle('p1', _me.Point('p1_pt'), _sm.Symbol('m'))
13
+ particle_p2 = _me.Particle('p2', _me.Point('p2_pt'), _sm.Symbol('m'))
14
+ c1, c2, c3 = _me.dynamicsymbols('c1 c2 c3')
15
+ c1_d, c2_d, c3_d = _me.dynamicsymbols('c1_ c2_ c3_', 1)
16
+ body_r_cm = _me.Point('r_cm')
17
+ body_r_cm.set_vel(frame_n, 0)
18
+ body_r_f = _me.ReferenceFrame('r_f')
19
+ 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))
20
+ point_po2.set_pos(particle_p1.point, c1*frame_a.x)
21
+ v = 2*point_po2.pos_from(particle_p1.point)+c2*frame_a.y
22
+ frame_a.set_ang_vel(frame_n, c3*frame_a.z)
23
+ v = 2*frame_a.ang_vel_in(frame_n)+c2*frame_a.y
24
+ body_r_f.set_ang_vel(frame_n, c3*frame_a.z)
25
+ v = 2*body_r_f.ang_vel_in(frame_n)+c2*frame_a.y
26
+ frame_a.set_ang_acc(frame_n, (frame_a.ang_vel_in(frame_n)).dt(frame_a))
27
+ v = 2*frame_a.ang_acc_in(frame_n)+c2*frame_a.y
28
+ particle_p1.point.set_vel(frame_a, c1*frame_a.x+c3*frame_a.y)
29
+ body_r_cm.set_acc(frame_n, c2*frame_a.y)
30
+ v_a = _me.cross(body_r_cm.acc(frame_n), particle_p1.point.vel(frame_a))
31
+ x_b_c = v_a
32
+ x_b_d = 2*x_b_c
33
+ a_b_c_d_e = x_b_d*2
34
+ a_b_c = 2*c1*c2*c3
35
+ a_b_c += 2*c1
36
+ a_b_c = 3*c1
37
+ q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2')
38
+ q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1)
39
+ x, y = _me.dynamicsymbols('x y')
40
+ x_d, y_d = _me.dynamicsymbols('x_ y_', 1)
41
+ x_dd, y_dd = _me.dynamicsymbols('x_ y_', 2)
42
+ yy = _me.dynamicsymbols('yy')
43
+ yy = x*x_d**2+1
44
+ m = _sm.Matrix([[0]])
45
+ m[0] = 2*x
46
+ m = m.row_insert(m.shape[0], _sm.Matrix([[0]]))
47
+ m[m.shape[0]-1] = 2*y
48
+ a = 2*m[0]
49
+ m = _sm.Matrix([1,2,3,4,5,6,7,8,9]).reshape(3, 3)
50
+ m[0,1] = 5
51
+ a = m[0, 1]*2
52
+ force_ro = q1*frame_n.x
53
+ torque_a = q2*frame_n.z
54
+ force_ro = q1*frame_n.x + q2*frame_n.y
55
+ f = force_ro*2
llmeval-env/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.
llmeval-env/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;
llmeval-env/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)
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.23 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/_build_latex_antlr.cpython-310.pyc ADDED
Binary file (2.62 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/_parse_latex_antlr.cpython-310.pyc ADDED
Binary file (13.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/errors.cpython-310.pyc ADDED
Binary file (364 Bytes). View file
 
llmeval-env/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
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (199 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexlexer.cpython-310.pyc ADDED
Binary file (43.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexparser.cpython-310.pyc ADDED
Binary file (110 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/latexlexer.py ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
10
+ from antlr4 import *
11
+ from io import StringIO
12
+ import sys
13
+ if sys.version_info[1] > 5:
14
+ from typing import TextIO
15
+ else:
16
+ from typing.io import TextIO
17
+
18
+
19
+ def serializedATN():
20
+ return [
21
+ 4,0,91,911,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,
22
+ 2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,
23
+ 13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,
24
+ 19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,
25
+ 26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,
26
+ 32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,
27
+ 39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7,
28
+ 45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,2,51,7,51,2,
29
+ 52,7,52,2,53,7,53,2,54,7,54,2,55,7,55,2,56,7,56,2,57,7,57,2,58,7,
30
+ 58,2,59,7,59,2,60,7,60,2,61,7,61,2,62,7,62,2,63,7,63,2,64,7,64,2,
31
+ 65,7,65,2,66,7,66,2,67,7,67,2,68,7,68,2,69,7,69,2,70,7,70,2,71,7,
32
+ 71,2,72,7,72,2,73,7,73,2,74,7,74,2,75,7,75,2,76,7,76,2,77,7,77,2,
33
+ 78,7,78,2,79,7,79,2,80,7,80,2,81,7,81,2,82,7,82,2,83,7,83,2,84,7,
34
+ 84,2,85,7,85,2,86,7,86,2,87,7,87,2,88,7,88,2,89,7,89,2,90,7,90,2,
35
+ 91,7,91,1,0,1,0,1,1,1,1,1,2,4,2,191,8,2,11,2,12,2,192,1,2,1,2,1,
36
+ 3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,3,3,209,8,3,1,3,1,
37
+ 3,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,3,4,224,8,4,1,4,1,
38
+ 4,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,3,5,241,8,
39
+ 5,1,5,1,5,1,6,1,6,1,6,1,6,1,6,1,6,1,6,1,6,1,7,1,7,1,7,1,7,1,7,1,
40
+ 7,1,7,1,7,1,7,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,
41
+ 8,1,8,1,8,3,8,277,8,8,1,8,1,8,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,
42
+ 9,1,9,1,9,1,9,1,9,1,9,1,9,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,
43
+ 1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,11,1,11,1,11,1,11,
44
+ 1,11,1,11,1,11,1,11,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12,
45
+ 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,
46
+ 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,
47
+ 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,
48
+ 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,3,13,
49
+ 381,8,13,1,13,1,13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18,
50
+ 1,18,1,19,1,19,1,20,1,20,1,21,1,21,1,22,1,22,1,22,1,23,1,23,1,23,
51
+ 1,24,1,24,1,25,1,25,1,26,1,26,1,27,1,27,1,27,1,27,1,27,1,27,1,27,
52
+ 1,27,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,29,1,29,1,29,1,29,1,29,
53
+ 1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,30,1,30,1,30,1,30,1,31,1,31,
54
+ 1,31,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
55
+ 1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
56
+ 1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
57
+ 1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
58
+ 1,32,1,32,1,32,1,32,1,32,1,32,3,32,504,8,32,1,33,1,33,1,33,1,33,
59
+ 1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,3,33,521,
60
+ 8,33,1,34,1,34,1,34,1,34,1,34,1,35,1,35,1,35,1,35,1,35,1,35,1,36,
61
+ 1,36,1,36,1,36,1,36,1,37,1,37,1,37,1,37,1,37,1,38,1,38,1,38,1,38,
62
+ 1,39,1,39,1,39,1,39,1,40,1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41,
63
+ 1,41,1,42,1,42,1,42,1,42,1,42,1,43,1,43,1,43,1,43,1,43,1,44,1,44,
64
+ 1,44,1,44,1,44,1,45,1,45,1,45,1,45,1,45,1,46,1,46,1,46,1,46,1,46,
65
+ 1,46,1,46,1,46,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,48,1,48,
66
+ 1,48,1,48,1,48,1,48,1,48,1,48,1,49,1,49,1,49,1,49,1,49,1,49,1,49,
67
+ 1,49,1,50,1,50,1,50,1,50,1,50,1,50,1,50,1,50,1,51,1,51,1,51,1,51,
68
+ 1,51,1,51,1,51,1,51,1,52,1,52,1,52,1,52,1,52,1,52,1,53,1,53,1,53,
69
+ 1,53,1,53,1,53,1,54,1,54,1,54,1,54,1,54,1,54,1,55,1,55,1,55,1,55,
70
+ 1,55,1,55,1,55,1,55,1,56,1,56,1,56,1,56,1,56,1,56,1,56,1,56,1,57,
71
+ 1,57,1,57,1,57,1,57,1,57,1,57,1,57,1,58,1,58,1,58,1,58,1,58,1,58,
72
+ 1,58,1,58,1,59,1,59,1,59,1,59,1,59,1,59,1,59,1,59,1,60,1,60,1,60,
73
+ 1,60,1,60,1,60,1,60,1,61,1,61,1,61,1,61,1,61,1,61,1,61,1,62,1,62,
74
+ 1,62,1,62,1,62,1,62,1,63,1,63,1,63,1,63,1,63,1,63,1,63,1,63,1,63,
75
+ 1,63,1,64,1,64,1,64,1,64,1,64,1,64,1,64,1,65,1,65,1,65,1,65,1,65,
76
+ 1,65,1,66,1,66,1,66,1,66,1,66,1,67,1,67,1,67,1,67,1,67,1,67,1,67,
77
+ 1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,3,67,753,8,67,
78
+ 1,68,1,68,1,68,1,68,1,68,1,68,1,68,1,69,1,69,1,69,1,69,1,69,1,69,
79
+ 1,69,1,69,1,70,1,70,1,70,1,70,1,70,1,70,1,70,1,70,1,71,1,71,1,71,
80
+ 1,71,1,71,1,71,1,71,1,71,1,72,1,72,1,73,1,73,1,74,1,74,1,75,1,75,
81
+ 1,76,1,76,5,76,796,8,76,10,76,12,76,799,9,76,1,76,1,76,1,76,4,76,
82
+ 804,8,76,11,76,12,76,805,3,76,808,8,76,1,77,1,77,1,78,1,78,1,79,
83
+ 1,79,5,79,816,8,79,10,79,12,79,819,9,79,3,79,821,8,79,1,79,1,79,
84
+ 1,79,5,79,826,8,79,10,79,12,79,829,9,79,1,79,3,79,832,8,79,3,79,
85
+ 834,8,79,1,80,1,80,1,80,1,80,1,80,1,81,1,81,1,82,1,82,1,82,1,82,
86
+ 1,82,1,82,1,82,1,82,1,82,3,82,852,8,82,1,83,1,83,1,83,1,83,1,83,
87
+ 1,83,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,85,1,85,
88
+ 1,86,1,86,1,86,1,86,1,86,1,86,1,86,1,86,1,86,3,86,881,8,86,1,87,
89
+ 1,87,1,87,1,87,1,87,1,87,1,88,1,88,1,88,1,88,1,88,1,88,1,88,1,88,
90
+ 1,88,1,88,1,89,1,89,1,90,4,90,902,8,90,11,90,12,90,903,1,91,1,91,
91
+ 4,91,908,8,91,11,91,12,91,909,3,797,817,827,0,92,1,1,3,2,5,3,7,4,
92
+ 9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,27,14,29,15,31,16,
93
+ 33,17,35,18,37,19,39,20,41,21,43,22,45,23,47,24,49,25,51,26,53,27,
94
+ 55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35,71,36,73,37,75,38,
95
+ 77,39,79,40,81,41,83,42,85,43,87,44,89,45,91,46,93,47,95,48,97,49,
96
+ 99,50,101,51,103,52,105,53,107,54,109,55,111,56,113,57,115,58,117,
97
+ 59,119,60,121,61,123,62,125,63,127,64,129,65,131,66,133,67,135,68,
98
+ 137,69,139,70,141,71,143,72,145,73,147,74,149,75,151,0,153,76,155,
99
+ 77,157,78,159,79,161,80,163,81,165,82,167,83,169,84,171,85,173,86,
100
+ 175,87,177,88,179,89,181,90,183,91,1,0,3,3,0,9,10,13,13,32,32,2,
101
+ 0,65,90,97,122,1,0,48,57,949,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,
102
+ 0,7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,
103
+ 17,1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,
104
+ 27,1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0,
105
+ 37,1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0,0,0,0,
106
+ 47,1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0,0,
107
+ 57,1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0,
108
+ 67,1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0,
109
+ 77,1,0,0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0,
110
+ 87,1,0,0,0,0,89,1,0,0,0,0,91,1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0,
111
+ 97,1,0,0,0,0,99,1,0,0,0,0,101,1,0,0,0,0,103,1,0,0,0,0,105,1,0,0,
112
+ 0,0,107,1,0,0,0,0,109,1,0,0,0,0,111,1,0,0,0,0,113,1,0,0,0,0,115,
113
+ 1,0,0,0,0,117,1,0,0,0,0,119,1,0,0,0,0,121,1,0,0,0,0,123,1,0,0,0,
114
+ 0,125,1,0,0,0,0,127,1,0,0,0,0,129,1,0,0,0,0,131,1,0,0,0,0,133,1,
115
+ 0,0,0,0,135,1,0,0,0,0,137,1,0,0,0,0,139,1,0,0,0,0,141,1,0,0,0,0,
116
+ 143,1,0,0,0,0,145,1,0,0,0,0,147,1,0,0,0,0,149,1,0,0,0,0,153,1,0,
117
+ 0,0,0,155,1,0,0,0,0,157,1,0,0,0,0,159,1,0,0,0,0,161,1,0,0,0,0,163,
118
+ 1,0,0,0,0,165,1,0,0,0,0,167,1,0,0,0,0,169,1,0,0,0,0,171,1,0,0,0,
119
+ 0,173,1,0,0,0,0,175,1,0,0,0,0,177,1,0,0,0,0,179,1,0,0,0,0,181,1,
120
+ 0,0,0,0,183,1,0,0,0,1,185,1,0,0,0,3,187,1,0,0,0,5,190,1,0,0,0,7,
121
+ 208,1,0,0,0,9,223,1,0,0,0,11,240,1,0,0,0,13,244,1,0,0,0,15,252,1,
122
+ 0,0,0,17,276,1,0,0,0,19,280,1,0,0,0,21,295,1,0,0,0,23,312,1,0,0,
123
+ 0,25,320,1,0,0,0,27,380,1,0,0,0,29,384,1,0,0,0,31,386,1,0,0,0,33,
124
+ 388,1,0,0,0,35,390,1,0,0,0,37,392,1,0,0,0,39,394,1,0,0,0,41,396,
125
+ 1,0,0,0,43,398,1,0,0,0,45,400,1,0,0,0,47,403,1,0,0,0,49,406,1,0,
126
+ 0,0,51,408,1,0,0,0,53,410,1,0,0,0,55,412,1,0,0,0,57,420,1,0,0,0,
127
+ 59,427,1,0,0,0,61,435,1,0,0,0,63,443,1,0,0,0,65,503,1,0,0,0,67,520,
128
+ 1,0,0,0,69,522,1,0,0,0,71,527,1,0,0,0,73,533,1,0,0,0,75,538,1,0,
129
+ 0,0,77,543,1,0,0,0,79,547,1,0,0,0,81,551,1,0,0,0,83,556,1,0,0,0,
130
+ 85,561,1,0,0,0,87,566,1,0,0,0,89,571,1,0,0,0,91,576,1,0,0,0,93,581,
131
+ 1,0,0,0,95,589,1,0,0,0,97,597,1,0,0,0,99,605,1,0,0,0,101,613,1,0,
132
+ 0,0,103,621,1,0,0,0,105,629,1,0,0,0,107,635,1,0,0,0,109,641,1,0,
133
+ 0,0,111,647,1,0,0,0,113,655,1,0,0,0,115,663,1,0,0,0,117,671,1,0,
134
+ 0,0,119,679,1,0,0,0,121,687,1,0,0,0,123,694,1,0,0,0,125,701,1,0,
135
+ 0,0,127,707,1,0,0,0,129,717,1,0,0,0,131,724,1,0,0,0,133,730,1,0,
136
+ 0,0,135,752,1,0,0,0,137,754,1,0,0,0,139,761,1,0,0,0,141,769,1,0,
137
+ 0,0,143,777,1,0,0,0,145,785,1,0,0,0,147,787,1,0,0,0,149,789,1,0,
138
+ 0,0,151,791,1,0,0,0,153,793,1,0,0,0,155,809,1,0,0,0,157,811,1,0,
139
+ 0,0,159,833,1,0,0,0,161,835,1,0,0,0,163,840,1,0,0,0,165,851,1,0,
140
+ 0,0,167,853,1,0,0,0,169,859,1,0,0,0,171,869,1,0,0,0,173,880,1,0,
141
+ 0,0,175,882,1,0,0,0,177,888,1,0,0,0,179,898,1,0,0,0,181,901,1,0,
142
+ 0,0,183,905,1,0,0,0,185,186,5,44,0,0,186,2,1,0,0,0,187,188,5,46,
143
+ 0,0,188,4,1,0,0,0,189,191,7,0,0,0,190,189,1,0,0,0,191,192,1,0,0,
144
+ 0,192,190,1,0,0,0,192,193,1,0,0,0,193,194,1,0,0,0,194,195,6,2,0,
145
+ 0,195,6,1,0,0,0,196,197,5,92,0,0,197,209,5,44,0,0,198,199,5,92,0,
146
+ 0,199,200,5,116,0,0,200,201,5,104,0,0,201,202,5,105,0,0,202,203,
147
+ 5,110,0,0,203,204,5,115,0,0,204,205,5,112,0,0,205,206,5,97,0,0,206,
148
+ 207,5,99,0,0,207,209,5,101,0,0,208,196,1,0,0,0,208,198,1,0,0,0,209,
149
+ 210,1,0,0,0,210,211,6,3,0,0,211,8,1,0,0,0,212,213,5,92,0,0,213,224,
150
+ 5,58,0,0,214,215,5,92,0,0,215,216,5,109,0,0,216,217,5,101,0,0,217,
151
+ 218,5,100,0,0,218,219,5,115,0,0,219,220,5,112,0,0,220,221,5,97,0,
152
+ 0,221,222,5,99,0,0,222,224,5,101,0,0,223,212,1,0,0,0,223,214,1,0,
153
+ 0,0,224,225,1,0,0,0,225,226,6,4,0,0,226,10,1,0,0,0,227,228,5,92,
154
+ 0,0,228,241,5,59,0,0,229,230,5,92,0,0,230,231,5,116,0,0,231,232,
155
+ 5,104,0,0,232,233,5,105,0,0,233,234,5,99,0,0,234,235,5,107,0,0,235,
156
+ 236,5,115,0,0,236,237,5,112,0,0,237,238,5,97,0,0,238,239,5,99,0,
157
+ 0,239,241,5,101,0,0,240,227,1,0,0,0,240,229,1,0,0,0,241,242,1,0,
158
+ 0,0,242,243,6,5,0,0,243,12,1,0,0,0,244,245,5,92,0,0,245,246,5,113,
159
+ 0,0,246,247,5,117,0,0,247,248,5,97,0,0,248,249,5,100,0,0,249,250,
160
+ 1,0,0,0,250,251,6,6,0,0,251,14,1,0,0,0,252,253,5,92,0,0,253,254,
161
+ 5,113,0,0,254,255,5,113,0,0,255,256,5,117,0,0,256,257,5,97,0,0,257,
162
+ 258,5,100,0,0,258,259,1,0,0,0,259,260,6,7,0,0,260,16,1,0,0,0,261,
163
+ 262,5,92,0,0,262,277,5,33,0,0,263,264,5,92,0,0,264,265,5,110,0,0,
164
+ 265,266,5,101,0,0,266,267,5,103,0,0,267,268,5,116,0,0,268,269,5,
165
+ 104,0,0,269,270,5,105,0,0,270,271,5,110,0,0,271,272,5,115,0,0,272,
166
+ 273,5,112,0,0,273,274,5,97,0,0,274,275,5,99,0,0,275,277,5,101,0,
167
+ 0,276,261,1,0,0,0,276,263,1,0,0,0,277,278,1,0,0,0,278,279,6,8,0,
168
+ 0,279,18,1,0,0,0,280,281,5,92,0,0,281,282,5,110,0,0,282,283,5,101,
169
+ 0,0,283,284,5,103,0,0,284,285,5,109,0,0,285,286,5,101,0,0,286,287,
170
+ 5,100,0,0,287,288,5,115,0,0,288,289,5,112,0,0,289,290,5,97,0,0,290,
171
+ 291,5,99,0,0,291,292,5,101,0,0,292,293,1,0,0,0,293,294,6,9,0,0,294,
172
+ 20,1,0,0,0,295,296,5,92,0,0,296,297,5,110,0,0,297,298,5,101,0,0,
173
+ 298,299,5,103,0,0,299,300,5,116,0,0,300,301,5,104,0,0,301,302,5,
174
+ 105,0,0,302,303,5,99,0,0,303,304,5,107,0,0,304,305,5,115,0,0,305,
175
+ 306,5,112,0,0,306,307,5,97,0,0,307,308,5,99,0,0,308,309,5,101,0,
176
+ 0,309,310,1,0,0,0,310,311,6,10,0,0,311,22,1,0,0,0,312,313,5,92,0,
177
+ 0,313,314,5,108,0,0,314,315,5,101,0,0,315,316,5,102,0,0,316,317,
178
+ 5,116,0,0,317,318,1,0,0,0,318,319,6,11,0,0,319,24,1,0,0,0,320,321,
179
+ 5,92,0,0,321,322,5,114,0,0,322,323,5,105,0,0,323,324,5,103,0,0,324,
180
+ 325,5,104,0,0,325,326,5,116,0,0,326,327,1,0,0,0,327,328,6,12,0,0,
181
+ 328,26,1,0,0,0,329,330,5,92,0,0,330,331,5,118,0,0,331,332,5,114,
182
+ 0,0,332,333,5,117,0,0,333,334,5,108,0,0,334,381,5,101,0,0,335,336,
183
+ 5,92,0,0,336,337,5,118,0,0,337,338,5,99,0,0,338,339,5,101,0,0,339,
184
+ 340,5,110,0,0,340,341,5,116,0,0,341,342,5,101,0,0,342,381,5,114,
185
+ 0,0,343,344,5,92,0,0,344,345,5,118,0,0,345,346,5,98,0,0,346,347,
186
+ 5,111,0,0,347,381,5,120,0,0,348,349,5,92,0,0,349,350,5,118,0,0,350,
187
+ 351,5,115,0,0,351,352,5,107,0,0,352,353,5,105,0,0,353,381,5,112,
188
+ 0,0,354,355,5,92,0,0,355,356,5,118,0,0,356,357,5,115,0,0,357,358,
189
+ 5,112,0,0,358,359,5,97,0,0,359,360,5,99,0,0,360,381,5,101,0,0,361,
190
+ 362,5,92,0,0,362,363,5,104,0,0,363,364,5,102,0,0,364,365,5,105,0,
191
+ 0,365,381,5,108,0,0,366,367,5,92,0,0,367,381,5,42,0,0,368,369,5,
192
+ 92,0,0,369,381,5,45,0,0,370,371,5,92,0,0,371,381,5,46,0,0,372,373,
193
+ 5,92,0,0,373,381,5,47,0,0,374,375,5,92,0,0,375,381,5,34,0,0,376,
194
+ 377,5,92,0,0,377,381,5,40,0,0,378,379,5,92,0,0,379,381,5,61,0,0,
195
+ 380,329,1,0,0,0,380,335,1,0,0,0,380,343,1,0,0,0,380,348,1,0,0,0,
196
+ 380,354,1,0,0,0,380,361,1,0,0,0,380,366,1,0,0,0,380,368,1,0,0,0,
197
+ 380,370,1,0,0,0,380,372,1,0,0,0,380,374,1,0,0,0,380,376,1,0,0,0,
198
+ 380,378,1,0,0,0,381,382,1,0,0,0,382,383,6,13,0,0,383,28,1,0,0,0,
199
+ 384,385,5,43,0,0,385,30,1,0,0,0,386,387,5,45,0,0,387,32,1,0,0,0,
200
+ 388,389,5,42,0,0,389,34,1,0,0,0,390,391,5,47,0,0,391,36,1,0,0,0,
201
+ 392,393,5,40,0,0,393,38,1,0,0,0,394,395,5,41,0,0,395,40,1,0,0,0,
202
+ 396,397,5,123,0,0,397,42,1,0,0,0,398,399,5,125,0,0,399,44,1,0,0,
203
+ 0,400,401,5,92,0,0,401,402,5,123,0,0,402,46,1,0,0,0,403,404,5,92,
204
+ 0,0,404,405,5,125,0,0,405,48,1,0,0,0,406,407,5,91,0,0,407,50,1,0,
205
+ 0,0,408,409,5,93,0,0,409,52,1,0,0,0,410,411,5,124,0,0,411,54,1,0,
206
+ 0,0,412,413,5,92,0,0,413,414,5,114,0,0,414,415,5,105,0,0,415,416,
207
+ 5,103,0,0,416,417,5,104,0,0,417,418,5,116,0,0,418,419,5,124,0,0,
208
+ 419,56,1,0,0,0,420,421,5,92,0,0,421,422,5,108,0,0,422,423,5,101,
209
+ 0,0,423,424,5,102,0,0,424,425,5,116,0,0,425,426,5,124,0,0,426,58,
210
+ 1,0,0,0,427,428,5,92,0,0,428,429,5,108,0,0,429,430,5,97,0,0,430,
211
+ 431,5,110,0,0,431,432,5,103,0,0,432,433,5,108,0,0,433,434,5,101,
212
+ 0,0,434,60,1,0,0,0,435,436,5,92,0,0,436,437,5,114,0,0,437,438,5,
213
+ 97,0,0,438,439,5,110,0,0,439,440,5,103,0,0,440,441,5,108,0,0,441,
214
+ 442,5,101,0,0,442,62,1,0,0,0,443,444,5,92,0,0,444,445,5,108,0,0,
215
+ 445,446,5,105,0,0,446,447,5,109,0,0,447,64,1,0,0,0,448,449,5,92,
216
+ 0,0,449,450,5,116,0,0,450,504,5,111,0,0,451,452,5,92,0,0,452,453,
217
+ 5,114,0,0,453,454,5,105,0,0,454,455,5,103,0,0,455,456,5,104,0,0,
218
+ 456,457,5,116,0,0,457,458,5,97,0,0,458,459,5,114,0,0,459,460,5,114,
219
+ 0,0,460,461,5,111,0,0,461,504,5,119,0,0,462,463,5,92,0,0,463,464,
220
+ 5,82,0,0,464,465,5,105,0,0,465,466,5,103,0,0,466,467,5,104,0,0,467,
221
+ 468,5,116,0,0,468,469,5,97,0,0,469,470,5,114,0,0,470,471,5,114,0,
222
+ 0,471,472,5,111,0,0,472,504,5,119,0,0,473,474,5,92,0,0,474,475,5,
223
+ 108,0,0,475,476,5,111,0,0,476,477,5,110,0,0,477,478,5,103,0,0,478,
224
+ 479,5,114,0,0,479,480,5,105,0,0,480,481,5,103,0,0,481,482,5,104,
225
+ 0,0,482,483,5,116,0,0,483,484,5,97,0,0,484,485,5,114,0,0,485,486,
226
+ 5,114,0,0,486,487,5,111,0,0,487,504,5,119,0,0,488,489,5,92,0,0,489,
227
+ 490,5,76,0,0,490,491,5,111,0,0,491,492,5,110,0,0,492,493,5,103,0,
228
+ 0,493,494,5,114,0,0,494,495,5,105,0,0,495,496,5,103,0,0,496,497,
229
+ 5,104,0,0,497,498,5,116,0,0,498,499,5,97,0,0,499,500,5,114,0,0,500,
230
+ 501,5,114,0,0,501,502,5,111,0,0,502,504,5,119,0,0,503,448,1,0,0,
231
+ 0,503,451,1,0,0,0,503,462,1,0,0,0,503,473,1,0,0,0,503,488,1,0,0,
232
+ 0,504,66,1,0,0,0,505,506,5,92,0,0,506,507,5,105,0,0,507,508,5,110,
233
+ 0,0,508,521,5,116,0,0,509,510,5,92,0,0,510,511,5,105,0,0,511,512,
234
+ 5,110,0,0,512,513,5,116,0,0,513,514,5,92,0,0,514,515,5,108,0,0,515,
235
+ 516,5,105,0,0,516,517,5,109,0,0,517,518,5,105,0,0,518,519,5,116,
236
+ 0,0,519,521,5,115,0,0,520,505,1,0,0,0,520,509,1,0,0,0,521,68,1,0,
237
+ 0,0,522,523,5,92,0,0,523,524,5,115,0,0,524,525,5,117,0,0,525,526,
238
+ 5,109,0,0,526,70,1,0,0,0,527,528,5,92,0,0,528,529,5,112,0,0,529,
239
+ 530,5,114,0,0,530,531,5,111,0,0,531,532,5,100,0,0,532,72,1,0,0,0,
240
+ 533,534,5,92,0,0,534,535,5,101,0,0,535,536,5,120,0,0,536,537,5,112,
241
+ 0,0,537,74,1,0,0,0,538,539,5,92,0,0,539,540,5,108,0,0,540,541,5,
242
+ 111,0,0,541,542,5,103,0,0,542,76,1,0,0,0,543,544,5,92,0,0,544,545,
243
+ 5,108,0,0,545,546,5,103,0,0,546,78,1,0,0,0,547,548,5,92,0,0,548,
244
+ 549,5,108,0,0,549,550,5,110,0,0,550,80,1,0,0,0,551,552,5,92,0,0,
245
+ 552,553,5,115,0,0,553,554,5,105,0,0,554,555,5,110,0,0,555,82,1,0,
246
+ 0,0,556,557,5,92,0,0,557,558,5,99,0,0,558,559,5,111,0,0,559,560,
247
+ 5,115,0,0,560,84,1,0,0,0,561,562,5,92,0,0,562,563,5,116,0,0,563,
248
+ 564,5,97,0,0,564,565,5,110,0,0,565,86,1,0,0,0,566,567,5,92,0,0,567,
249
+ 568,5,99,0,0,568,569,5,115,0,0,569,570,5,99,0,0,570,88,1,0,0,0,571,
250
+ 572,5,92,0,0,572,573,5,115,0,0,573,574,5,101,0,0,574,575,5,99,0,
251
+ 0,575,90,1,0,0,0,576,577,5,92,0,0,577,578,5,99,0,0,578,579,5,111,
252
+ 0,0,579,580,5,116,0,0,580,92,1,0,0,0,581,582,5,92,0,0,582,583,5,
253
+ 97,0,0,583,584,5,114,0,0,584,585,5,99,0,0,585,586,5,115,0,0,586,
254
+ 587,5,105,0,0,587,588,5,110,0,0,588,94,1,0,0,0,589,590,5,92,0,0,
255
+ 590,591,5,97,0,0,591,592,5,114,0,0,592,593,5,99,0,0,593,594,5,99,
256
+ 0,0,594,595,5,111,0,0,595,596,5,115,0,0,596,96,1,0,0,0,597,598,5,
257
+ 92,0,0,598,599,5,97,0,0,599,600,5,114,0,0,600,601,5,99,0,0,601,602,
258
+ 5,116,0,0,602,603,5,97,0,0,603,604,5,110,0,0,604,98,1,0,0,0,605,
259
+ 606,5,92,0,0,606,607,5,97,0,0,607,608,5,114,0,0,608,609,5,99,0,0,
260
+ 609,610,5,99,0,0,610,611,5,115,0,0,611,612,5,99,0,0,612,100,1,0,
261
+ 0,0,613,614,5,92,0,0,614,615,5,97,0,0,615,616,5,114,0,0,616,617,
262
+ 5,99,0,0,617,618,5,115,0,0,618,619,5,101,0,0,619,620,5,99,0,0,620,
263
+ 102,1,0,0,0,621,622,5,92,0,0,622,623,5,97,0,0,623,624,5,114,0,0,
264
+ 624,625,5,99,0,0,625,626,5,99,0,0,626,627,5,111,0,0,627,628,5,116,
265
+ 0,0,628,104,1,0,0,0,629,630,5,92,0,0,630,631,5,115,0,0,631,632,5,
266
+ 105,0,0,632,633,5,110,0,0,633,634,5,104,0,0,634,106,1,0,0,0,635,
267
+ 636,5,92,0,0,636,637,5,99,0,0,637,638,5,111,0,0,638,639,5,115,0,
268
+ 0,639,640,5,104,0,0,640,108,1,0,0,0,641,642,5,92,0,0,642,643,5,116,
269
+ 0,0,643,644,5,97,0,0,644,645,5,110,0,0,645,646,5,104,0,0,646,110,
270
+ 1,0,0,0,647,648,5,92,0,0,648,649,5,97,0,0,649,650,5,114,0,0,650,
271
+ 651,5,115,0,0,651,652,5,105,0,0,652,653,5,110,0,0,653,654,5,104,
272
+ 0,0,654,112,1,0,0,0,655,656,5,92,0,0,656,657,5,97,0,0,657,658,5,
273
+ 114,0,0,658,659,5,99,0,0,659,660,5,111,0,0,660,661,5,115,0,0,661,
274
+ 662,5,104,0,0,662,114,1,0,0,0,663,664,5,92,0,0,664,665,5,97,0,0,
275
+ 665,666,5,114,0,0,666,667,5,116,0,0,667,668,5,97,0,0,668,669,5,110,
276
+ 0,0,669,670,5,104,0,0,670,116,1,0,0,0,671,672,5,92,0,0,672,673,5,
277
+ 108,0,0,673,674,5,102,0,0,674,675,5,108,0,0,675,676,5,111,0,0,676,
278
+ 677,5,111,0,0,677,678,5,114,0,0,678,118,1,0,0,0,679,680,5,92,0,0,
279
+ 680,681,5,114,0,0,681,682,5,102,0,0,682,683,5,108,0,0,683,684,5,
280
+ 111,0,0,684,685,5,111,0,0,685,686,5,114,0,0,686,120,1,0,0,0,687,
281
+ 688,5,92,0,0,688,689,5,108,0,0,689,690,5,99,0,0,690,691,5,101,0,
282
+ 0,691,692,5,105,0,0,692,693,5,108,0,0,693,122,1,0,0,0,694,695,5,
283
+ 92,0,0,695,696,5,114,0,0,696,697,5,99,0,0,697,698,5,101,0,0,698,
284
+ 699,5,105,0,0,699,700,5,108,0,0,700,124,1,0,0,0,701,702,5,92,0,0,
285
+ 702,703,5,115,0,0,703,704,5,113,0,0,704,705,5,114,0,0,705,706,5,
286
+ 116,0,0,706,126,1,0,0,0,707,708,5,92,0,0,708,709,5,111,0,0,709,710,
287
+ 5,118,0,0,710,711,5,101,0,0,711,712,5,114,0,0,712,713,5,108,0,0,
288
+ 713,714,5,105,0,0,714,715,5,110,0,0,715,716,5,101,0,0,716,128,1,
289
+ 0,0,0,717,718,5,92,0,0,718,719,5,116,0,0,719,720,5,105,0,0,720,721,
290
+ 5,109,0,0,721,722,5,101,0,0,722,723,5,115,0,0,723,130,1,0,0,0,724,
291
+ 725,5,92,0,0,725,726,5,99,0,0,726,727,5,100,0,0,727,728,5,111,0,
292
+ 0,728,729,5,116,0,0,729,132,1,0,0,0,730,731,5,92,0,0,731,732,5,100,
293
+ 0,0,732,733,5,105,0,0,733,734,5,118,0,0,734,134,1,0,0,0,735,736,
294
+ 5,92,0,0,736,737,5,102,0,0,737,738,5,114,0,0,738,739,5,97,0,0,739,
295
+ 753,5,99,0,0,740,741,5,92,0,0,741,742,5,100,0,0,742,743,5,102,0,
296
+ 0,743,744,5,114,0,0,744,745,5,97,0,0,745,753,5,99,0,0,746,747,5,
297
+ 92,0,0,747,748,5,116,0,0,748,749,5,102,0,0,749,750,5,114,0,0,750,
298
+ 751,5,97,0,0,751,753,5,99,0,0,752,735,1,0,0,0,752,740,1,0,0,0,752,
299
+ 746,1,0,0,0,753,136,1,0,0,0,754,755,5,92,0,0,755,756,5,98,0,0,756,
300
+ 757,5,105,0,0,757,758,5,110,0,0,758,759,5,111,0,0,759,760,5,109,
301
+ 0,0,760,138,1,0,0,0,761,762,5,92,0,0,762,763,5,100,0,0,763,764,5,
302
+ 98,0,0,764,765,5,105,0,0,765,766,5,110,0,0,766,767,5,111,0,0,767,
303
+ 768,5,109,0,0,768,140,1,0,0,0,769,770,5,92,0,0,770,771,5,116,0,0,
304
+ 771,772,5,98,0,0,772,773,5,105,0,0,773,774,5,110,0,0,774,775,5,111,
305
+ 0,0,775,776,5,109,0,0,776,142,1,0,0,0,777,778,5,92,0,0,778,779,5,
306
+ 109,0,0,779,780,5,97,0,0,780,781,5,116,0,0,781,782,5,104,0,0,782,
307
+ 783,5,105,0,0,783,784,5,116,0,0,784,144,1,0,0,0,785,786,5,95,0,0,
308
+ 786,146,1,0,0,0,787,788,5,94,0,0,788,148,1,0,0,0,789,790,5,58,0,
309
+ 0,790,150,1,0,0,0,791,792,7,0,0,0,792,152,1,0,0,0,793,797,5,100,
310
+ 0,0,794,796,3,151,75,0,795,794,1,0,0,0,796,799,1,0,0,0,797,798,1,
311
+ 0,0,0,797,795,1,0,0,0,798,807,1,0,0,0,799,797,1,0,0,0,800,808,7,
312
+ 1,0,0,801,803,5,92,0,0,802,804,7,1,0,0,803,802,1,0,0,0,804,805,1,
313
+ 0,0,0,805,803,1,0,0,0,805,806,1,0,0,0,806,808,1,0,0,0,807,800,1,
314
+ 0,0,0,807,801,1,0,0,0,808,154,1,0,0,0,809,810,7,1,0,0,810,156,1,
315
+ 0,0,0,811,812,7,2,0,0,812,158,1,0,0,0,813,817,5,38,0,0,814,816,3,
316
+ 151,75,0,815,814,1,0,0,0,816,819,1,0,0,0,817,818,1,0,0,0,817,815,
317
+ 1,0,0,0,818,821,1,0,0,0,819,817,1,0,0,0,820,813,1,0,0,0,820,821,
318
+ 1,0,0,0,821,822,1,0,0,0,822,834,5,61,0,0,823,831,5,61,0,0,824,826,
319
+ 3,151,75,0,825,824,1,0,0,0,826,829,1,0,0,0,827,828,1,0,0,0,827,825,
320
+ 1,0,0,0,828,830,1,0,0,0,829,827,1,0,0,0,830,832,5,38,0,0,831,827,
321
+ 1,0,0,0,831,832,1,0,0,0,832,834,1,0,0,0,833,820,1,0,0,0,833,823,
322
+ 1,0,0,0,834,160,1,0,0,0,835,836,5,92,0,0,836,837,5,110,0,0,837,838,
323
+ 5,101,0,0,838,839,5,113,0,0,839,162,1,0,0,0,840,841,5,60,0,0,841,
324
+ 164,1,0,0,0,842,843,5,92,0,0,843,844,5,108,0,0,844,845,5,101,0,0,
325
+ 845,852,5,113,0,0,846,847,5,92,0,0,847,848,5,108,0,0,848,852,5,101,
326
+ 0,0,849,852,3,167,83,0,850,852,3,169,84,0,851,842,1,0,0,0,851,846,
327
+ 1,0,0,0,851,849,1,0,0,0,851,850,1,0,0,0,852,166,1,0,0,0,853,854,
328
+ 5,92,0,0,854,855,5,108,0,0,855,856,5,101,0,0,856,857,5,113,0,0,857,
329
+ 858,5,113,0,0,858,168,1,0,0,0,859,860,5,92,0,0,860,861,5,108,0,0,
330
+ 861,862,5,101,0,0,862,863,5,113,0,0,863,864,5,115,0,0,864,865,5,
331
+ 108,0,0,865,866,5,97,0,0,866,867,5,110,0,0,867,868,5,116,0,0,868,
332
+ 170,1,0,0,0,869,870,5,62,0,0,870,172,1,0,0,0,871,872,5,92,0,0,872,
333
+ 873,5,103,0,0,873,874,5,101,0,0,874,881,5,113,0,0,875,876,5,92,0,
334
+ 0,876,877,5,103,0,0,877,881,5,101,0,0,878,881,3,175,87,0,879,881,
335
+ 3,177,88,0,880,871,1,0,0,0,880,875,1,0,0,0,880,878,1,0,0,0,880,879,
336
+ 1,0,0,0,881,174,1,0,0,0,882,883,5,92,0,0,883,884,5,103,0,0,884,885,
337
+ 5,101,0,0,885,886,5,113,0,0,886,887,5,113,0,0,887,176,1,0,0,0,888,
338
+ 889,5,92,0,0,889,890,5,103,0,0,890,891,5,101,0,0,891,892,5,113,0,
339
+ 0,892,893,5,115,0,0,893,894,5,108,0,0,894,895,5,97,0,0,895,896,5,
340
+ 110,0,0,896,897,5,116,0,0,897,178,1,0,0,0,898,899,5,33,0,0,899,180,
341
+ 1,0,0,0,900,902,5,39,0,0,901,900,1,0,0,0,902,903,1,0,0,0,903,901,
342
+ 1,0,0,0,903,904,1,0,0,0,904,182,1,0,0,0,905,907,5,92,0,0,906,908,
343
+ 7,1,0,0,907,906,1,0,0,0,908,909,1,0,0,0,909,907,1,0,0,0,909,910,
344
+ 1,0,0,0,910,184,1,0,0,0,22,0,192,208,223,240,276,380,503,520,752,
345
+ 797,805,807,817,820,827,831,833,851,880,903,909,1,6,0,0
346
+ ]
347
+
348
+ class LaTeXLexer(Lexer):
349
+
350
+ atn = ATNDeserializer().deserialize(serializedATN())
351
+
352
+ decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
353
+
354
+ T__0 = 1
355
+ T__1 = 2
356
+ WS = 3
357
+ THINSPACE = 4
358
+ MEDSPACE = 5
359
+ THICKSPACE = 6
360
+ QUAD = 7
361
+ QQUAD = 8
362
+ NEGTHINSPACE = 9
363
+ NEGMEDSPACE = 10
364
+ NEGTHICKSPACE = 11
365
+ CMD_LEFT = 12
366
+ CMD_RIGHT = 13
367
+ IGNORE = 14
368
+ ADD = 15
369
+ SUB = 16
370
+ MUL = 17
371
+ DIV = 18
372
+ L_PAREN = 19
373
+ R_PAREN = 20
374
+ L_BRACE = 21
375
+ R_BRACE = 22
376
+ L_BRACE_LITERAL = 23
377
+ R_BRACE_LITERAL = 24
378
+ L_BRACKET = 25
379
+ R_BRACKET = 26
380
+ BAR = 27
381
+ R_BAR = 28
382
+ L_BAR = 29
383
+ L_ANGLE = 30
384
+ R_ANGLE = 31
385
+ FUNC_LIM = 32
386
+ LIM_APPROACH_SYM = 33
387
+ FUNC_INT = 34
388
+ FUNC_SUM = 35
389
+ FUNC_PROD = 36
390
+ FUNC_EXP = 37
391
+ FUNC_LOG = 38
392
+ FUNC_LG = 39
393
+ FUNC_LN = 40
394
+ FUNC_SIN = 41
395
+ FUNC_COS = 42
396
+ FUNC_TAN = 43
397
+ FUNC_CSC = 44
398
+ FUNC_SEC = 45
399
+ FUNC_COT = 46
400
+ FUNC_ARCSIN = 47
401
+ FUNC_ARCCOS = 48
402
+ FUNC_ARCTAN = 49
403
+ FUNC_ARCCSC = 50
404
+ FUNC_ARCSEC = 51
405
+ FUNC_ARCCOT = 52
406
+ FUNC_SINH = 53
407
+ FUNC_COSH = 54
408
+ FUNC_TANH = 55
409
+ FUNC_ARSINH = 56
410
+ FUNC_ARCOSH = 57
411
+ FUNC_ARTANH = 58
412
+ L_FLOOR = 59
413
+ R_FLOOR = 60
414
+ L_CEIL = 61
415
+ R_CEIL = 62
416
+ FUNC_SQRT = 63
417
+ FUNC_OVERLINE = 64
418
+ CMD_TIMES = 65
419
+ CMD_CDOT = 66
420
+ CMD_DIV = 67
421
+ CMD_FRAC = 68
422
+ CMD_BINOM = 69
423
+ CMD_DBINOM = 70
424
+ CMD_TBINOM = 71
425
+ CMD_MATHIT = 72
426
+ UNDERSCORE = 73
427
+ CARET = 74
428
+ COLON = 75
429
+ DIFFERENTIAL = 76
430
+ LETTER = 77
431
+ DIGIT = 78
432
+ EQUAL = 79
433
+ NEQ = 80
434
+ LT = 81
435
+ LTE = 82
436
+ LTE_Q = 83
437
+ LTE_S = 84
438
+ GT = 85
439
+ GTE = 86
440
+ GTE_Q = 87
441
+ GTE_S = 88
442
+ BANG = 89
443
+ SINGLE_QUOTES = 90
444
+ SYMBOL = 91
445
+
446
+ channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
447
+
448
+ modeNames = [ "DEFAULT_MODE" ]
449
+
450
+ literalNames = [ "<INVALID>",
451
+ "','", "'.'", "'\\quad'", "'\\qquad'", "'\\negmedspace'", "'\\negthickspace'",
452
+ "'\\left'", "'\\right'", "'+'", "'-'", "'*'", "'/'", "'('",
453
+ "')'", "'{'", "'}'", "'\\{'", "'\\}'", "'['", "']'", "'|'",
454
+ "'\\right|'", "'\\left|'", "'\\langle'", "'\\rangle'", "'\\lim'",
455
+ "'\\sum'", "'\\prod'", "'\\exp'", "'\\log'", "'\\lg'", "'\\ln'",
456
+ "'\\sin'", "'\\cos'", "'\\tan'", "'\\csc'", "'\\sec'", "'\\cot'",
457
+ "'\\arcsin'", "'\\arccos'", "'\\arctan'", "'\\arccsc'", "'\\arcsec'",
458
+ "'\\arccot'", "'\\sinh'", "'\\cosh'", "'\\tanh'", "'\\arsinh'",
459
+ "'\\arcosh'", "'\\artanh'", "'\\lfloor'", "'\\rfloor'", "'\\lceil'",
460
+ "'\\rceil'", "'\\sqrt'", "'\\overline'", "'\\times'", "'\\cdot'",
461
+ "'\\div'", "'\\binom'", "'\\dbinom'", "'\\tbinom'", "'\\mathit'",
462
+ "'_'", "'^'", "':'", "'\\neq'", "'<'", "'\\leqq'", "'\\leqslant'",
463
+ "'>'", "'\\geqq'", "'\\geqslant'", "'!'" ]
464
+
465
+ symbolicNames = [ "<INVALID>",
466
+ "WS", "THINSPACE", "MEDSPACE", "THICKSPACE", "QUAD", "QQUAD",
467
+ "NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE", "CMD_LEFT",
468
+ "CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL", "DIV", "L_PAREN",
469
+ "R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL", "R_BRACE_LITERAL",
470
+ "L_BRACKET", "R_BRACKET", "BAR", "R_BAR", "L_BAR", "L_ANGLE",
471
+ "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM", "FUNC_INT", "FUNC_SUM",
472
+ "FUNC_PROD", "FUNC_EXP", "FUNC_LOG", "FUNC_LG", "FUNC_LN", "FUNC_SIN",
473
+ "FUNC_COS", "FUNC_TAN", "FUNC_CSC", "FUNC_SEC", "FUNC_COT",
474
+ "FUNC_ARCSIN", "FUNC_ARCCOS", "FUNC_ARCTAN", "FUNC_ARCCSC",
475
+ "FUNC_ARCSEC", "FUNC_ARCCOT", "FUNC_SINH", "FUNC_COSH", "FUNC_TANH",
476
+ "FUNC_ARSINH", "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR",
477
+ "L_CEIL", "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES",
478
+ "CMD_CDOT", "CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM",
479
+ "CMD_TBINOM", "CMD_MATHIT", "UNDERSCORE", "CARET", "COLON",
480
+ "DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT", "LTE",
481
+ "LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S", "BANG", "SINGLE_QUOTES",
482
+ "SYMBOL" ]
483
+
484
+ ruleNames = [ "T__0", "T__1", "WS", "THINSPACE", "MEDSPACE", "THICKSPACE",
485
+ "QUAD", "QQUAD", "NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE",
486
+ "CMD_LEFT", "CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL",
487
+ "DIV", "L_PAREN", "R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL",
488
+ "R_BRACE_LITERAL", "L_BRACKET", "R_BRACKET", "BAR", "R_BAR",
489
+ "L_BAR", "L_ANGLE", "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM",
490
+ "FUNC_INT", "FUNC_SUM", "FUNC_PROD", "FUNC_EXP", "FUNC_LOG",
491
+ "FUNC_LG", "FUNC_LN", "FUNC_SIN", "FUNC_COS", "FUNC_TAN",
492
+ "FUNC_CSC", "FUNC_SEC", "FUNC_COT", "FUNC_ARCSIN", "FUNC_ARCCOS",
493
+ "FUNC_ARCTAN", "FUNC_ARCCSC", "FUNC_ARCSEC", "FUNC_ARCCOT",
494
+ "FUNC_SINH", "FUNC_COSH", "FUNC_TANH", "FUNC_ARSINH",
495
+ "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR", "L_CEIL",
496
+ "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES", "CMD_CDOT",
497
+ "CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM", "CMD_TBINOM",
498
+ "CMD_MATHIT", "UNDERSCORE", "CARET", "COLON", "WS_CHAR",
499
+ "DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT",
500
+ "LTE", "LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S",
501
+ "BANG", "SINGLE_QUOTES", "SYMBOL" ]
502
+
503
+ grammarFileName = "LaTeX.g4"
504
+
505
+ def __init__(self, input=None, output:TextIO = sys.stdout):
506
+ super().__init__(input, output)
507
+ self.checkVersion("4.11.1")
508
+ self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
509
+ self._actions = None
510
+ self._predicates = None
511
+
512
+
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/latexparser.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_build_latex_antlr.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, "LaTeX.g4"))
9
+ dir_latex_antlr = os.path.join(here, "_antlr")
10
+
11
+ header = '''\
12
+ # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
13
+ #
14
+ # Generated from ../LaTeX.g4, derived from latex2sympy
15
+ # latex2sympy is licensed under the MIT license
16
+ # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
17
+ #
18
+ # Generated with antlr4
19
+ # antlr4 is licensed under the BSD-3-Clause License
20
+ # https://github.com/antlr/antlr4/blob/master/LICENSE.txt
21
+ '''
22
+
23
+
24
+ def check_antlr_version():
25
+ debug("Checking antlr4 version...")
26
+
27
+ try:
28
+ debug(subprocess.check_output(["antlr4"])
29
+ .decode('utf-8').split("\n")[0])
30
+ return True
31
+ except (subprocess.CalledProcessError, FileNotFoundError):
32
+ debug("The 'antlr4' command line tool is not installed, "
33
+ "or not on your PATH.\n"
34
+ "> Please refer to the README.md file for more information.")
35
+ return False
36
+
37
+
38
+ def build_parser(output_dir=dir_latex_antlr):
39
+ check_antlr_version()
40
+
41
+ debug("Updating ANTLR-generated code in {}".format(output_dir))
42
+
43
+ if not os.path.exists(output_dir):
44
+ os.makedirs(output_dir)
45
+
46
+ with open(os.path.join(output_dir, "__init__.py"), "w+") as fp:
47
+ fp.write(header)
48
+
49
+ args = [
50
+ "antlr4",
51
+ grammar_file,
52
+ "-o", output_dir,
53
+ # for now, not generating these as latex2sympy did not use them
54
+ "-no-visitor",
55
+ "-no-listener",
56
+ ]
57
+
58
+ debug("Running code generation...\n\t$ {}".format(" ".join(args)))
59
+ subprocess.check_output(args, cwd=output_dir)
60
+
61
+ debug("Applying headers, removing unnecessary files and renaming...")
62
+ # Handle case insensitive file systems. If the files are already
63
+ # generated, they will be written to latex* but LaTeX*.* won't match them.
64
+ for path in (glob.glob(os.path.join(output_dir, "LaTeX*.*")) or
65
+ glob.glob(os.path.join(output_dir, "latex*.*"))):
66
+
67
+ # Remove files ending in .interp or .tokens as they are not needed.
68
+ if not path.endswith(".py"):
69
+ os.unlink(path)
70
+ continue
71
+
72
+ new_path = os.path.join(output_dir, os.path.basename(path).lower())
73
+ with open(path, 'r') as f:
74
+ lines = [line.rstrip() + '\n' for line in f.readlines()]
75
+
76
+ os.unlink(path)
77
+
78
+ with open(new_path, "w") as out_file:
79
+ offset = 0
80
+ while lines[offset].startswith('#'):
81
+ offset += 1
82
+ out_file.write(header)
83
+ out_file.writelines(lines[offset:])
84
+
85
+ debug("\t{}".format(new_path))
86
+
87
+ return True
88
+
89
+
90
+ if __name__ == "__main__":
91
+ build_parser()
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/_parse_latex_antlr.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ported from latex2sympy by @augustt198
2
+ # https://github.com/augustt198/latex2sympy
3
+ # See license in LICENSE.txt
4
+ from importlib.metadata import version
5
+ import sympy
6
+ from sympy.external import import_module
7
+ from sympy.printing.str import StrPrinter
8
+ from sympy.physics.quantum.state import Bra, Ket
9
+
10
+ from .errors import LaTeXParsingError
11
+
12
+
13
+ LaTeXParser = LaTeXLexer = MathErrorListener = None
14
+
15
+ try:
16
+ LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser',
17
+ import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser
18
+ LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer',
19
+ import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexer
20
+ except Exception:
21
+ pass
22
+
23
+ ErrorListener = import_module('antlr4.error.ErrorListener',
24
+ warn_not_installed=True,
25
+ import_kwargs={'fromlist': ['ErrorListener']}
26
+ )
27
+
28
+
29
+
30
+ if ErrorListener:
31
+ class MathErrorListener(ErrorListener.ErrorListener): # type: ignore
32
+ def __init__(self, src):
33
+ super(ErrorListener.ErrorListener, self).__init__()
34
+ self.src = src
35
+
36
+ def syntaxError(self, recog, symbol, line, col, msg, e):
37
+ fmt = "%s\n%s\n%s"
38
+ marker = "~" * col + "^"
39
+
40
+ if msg.startswith("missing"):
41
+ err = fmt % (msg, self.src, marker)
42
+ elif msg.startswith("no viable"):
43
+ err = fmt % ("I expected something else here", self.src, marker)
44
+ elif msg.startswith("mismatched"):
45
+ names = LaTeXParser.literalNames
46
+ expected = [
47
+ names[i] for i in e.getExpectedTokens() if i < len(names)
48
+ ]
49
+ if len(expected) < 10:
50
+ expected = " ".join(expected)
51
+ err = (fmt % ("I expected one of these: " + expected, self.src,
52
+ marker))
53
+ else:
54
+ err = (fmt % ("I expected something else here", self.src,
55
+ marker))
56
+ else:
57
+ err = fmt % ("I don't understand this", self.src, marker)
58
+ raise LaTeXParsingError(err)
59
+
60
+
61
+ def parse_latex(sympy):
62
+ antlr4 = import_module('antlr4')
63
+
64
+ if None in [antlr4, MathErrorListener] or \
65
+ not version('antlr4-python3-runtime').startswith('4.11'):
66
+ raise ImportError("LaTeX parsing requires the antlr4 Python package,"
67
+ " provided by pip (antlr4-python3-runtime) or"
68
+ " conda (antlr-python-runtime), version 4.11")
69
+
70
+ matherror = MathErrorListener(sympy)
71
+
72
+ stream = antlr4.InputStream(sympy)
73
+ lex = LaTeXLexer(stream)
74
+ lex.removeErrorListeners()
75
+ lex.addErrorListener(matherror)
76
+
77
+ tokens = antlr4.CommonTokenStream(lex)
78
+ parser = LaTeXParser(tokens)
79
+
80
+ # remove default console error listener
81
+ parser.removeErrorListeners()
82
+ parser.addErrorListener(matherror)
83
+
84
+ relation = parser.math().relation()
85
+ expr = convert_relation(relation)
86
+
87
+ return expr
88
+
89
+
90
+ def convert_relation(rel):
91
+ if rel.expr():
92
+ return convert_expr(rel.expr())
93
+
94
+ lh = convert_relation(rel.relation(0))
95
+ rh = convert_relation(rel.relation(1))
96
+ if rel.LT():
97
+ return sympy.StrictLessThan(lh, rh)
98
+ elif rel.LTE():
99
+ return sympy.LessThan(lh, rh)
100
+ elif rel.GT():
101
+ return sympy.StrictGreaterThan(lh, rh)
102
+ elif rel.GTE():
103
+ return sympy.GreaterThan(lh, rh)
104
+ elif rel.EQUAL():
105
+ return sympy.Eq(lh, rh)
106
+ elif rel.NEQ():
107
+ return sympy.Ne(lh, rh)
108
+
109
+
110
+ def convert_expr(expr):
111
+ return convert_add(expr.additive())
112
+
113
+
114
+ def convert_add(add):
115
+ if add.ADD():
116
+ lh = convert_add(add.additive(0))
117
+ rh = convert_add(add.additive(1))
118
+ return sympy.Add(lh, rh, evaluate=False)
119
+ elif add.SUB():
120
+ lh = convert_add(add.additive(0))
121
+ rh = convert_add(add.additive(1))
122
+ if hasattr(rh, "is_Atom") and rh.is_Atom:
123
+ return sympy.Add(lh, -1 * rh, evaluate=False)
124
+ return sympy.Add(lh, sympy.Mul(-1, rh, evaluate=False), evaluate=False)
125
+ else:
126
+ return convert_mp(add.mp())
127
+
128
+
129
+ def convert_mp(mp):
130
+ if hasattr(mp, 'mp'):
131
+ mp_left = mp.mp(0)
132
+ mp_right = mp.mp(1)
133
+ else:
134
+ mp_left = mp.mp_nofunc(0)
135
+ mp_right = mp.mp_nofunc(1)
136
+
137
+ if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT():
138
+ lh = convert_mp(mp_left)
139
+ rh = convert_mp(mp_right)
140
+ return sympy.Mul(lh, rh, evaluate=False)
141
+ elif mp.DIV() or mp.CMD_DIV() or mp.COLON():
142
+ lh = convert_mp(mp_left)
143
+ rh = convert_mp(mp_right)
144
+ return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False)
145
+ else:
146
+ if hasattr(mp, 'unary'):
147
+ return convert_unary(mp.unary())
148
+ else:
149
+ return convert_unary(mp.unary_nofunc())
150
+
151
+
152
+ def convert_unary(unary):
153
+ if hasattr(unary, 'unary'):
154
+ nested_unary = unary.unary()
155
+ else:
156
+ nested_unary = unary.unary_nofunc()
157
+ if hasattr(unary, 'postfix_nofunc'):
158
+ first = unary.postfix()
159
+ tail = unary.postfix_nofunc()
160
+ postfix = [first] + tail
161
+ else:
162
+ postfix = unary.postfix()
163
+
164
+ if unary.ADD():
165
+ return convert_unary(nested_unary)
166
+ elif unary.SUB():
167
+ numabs = convert_unary(nested_unary)
168
+ # Use Integer(-n) instead of Mul(-1, n)
169
+ return -numabs
170
+ elif postfix:
171
+ return convert_postfix_list(postfix)
172
+
173
+
174
+ def convert_postfix_list(arr, i=0):
175
+ if i >= len(arr):
176
+ raise LaTeXParsingError("Index out of bounds")
177
+
178
+ res = convert_postfix(arr[i])
179
+ if isinstance(res, sympy.Expr):
180
+ if i == len(arr) - 1:
181
+ return res # nothing to multiply by
182
+ else:
183
+ if i > 0:
184
+ left = convert_postfix(arr[i - 1])
185
+ right = convert_postfix(arr[i + 1])
186
+ if isinstance(left, sympy.Expr) and isinstance(
187
+ right, sympy.Expr):
188
+ left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol)
189
+ right_syms = convert_postfix(arr[i + 1]).atoms(
190
+ sympy.Symbol)
191
+ # if the left and right sides contain no variables and the
192
+ # symbol in between is 'x', treat as multiplication.
193
+ if not (left_syms or right_syms) and str(res) == 'x':
194
+ return convert_postfix_list(arr, i + 1)
195
+ # multiply by next
196
+ return sympy.Mul(
197
+ res, convert_postfix_list(arr, i + 1), evaluate=False)
198
+ else: # must be derivative
199
+ wrt = res[0]
200
+ if i == len(arr) - 1:
201
+ raise LaTeXParsingError("Expected expression for derivative")
202
+ else:
203
+ expr = convert_postfix_list(arr, i + 1)
204
+ return sympy.Derivative(expr, wrt)
205
+
206
+
207
+ def do_subs(expr, at):
208
+ if at.expr():
209
+ at_expr = convert_expr(at.expr())
210
+ syms = at_expr.atoms(sympy.Symbol)
211
+ if len(syms) == 0:
212
+ return expr
213
+ elif len(syms) > 0:
214
+ sym = next(iter(syms))
215
+ return expr.subs(sym, at_expr)
216
+ elif at.equality():
217
+ lh = convert_expr(at.equality().expr(0))
218
+ rh = convert_expr(at.equality().expr(1))
219
+ return expr.subs(lh, rh)
220
+
221
+
222
+ def convert_postfix(postfix):
223
+ if hasattr(postfix, 'exp'):
224
+ exp_nested = postfix.exp()
225
+ else:
226
+ exp_nested = postfix.exp_nofunc()
227
+
228
+ exp = convert_exp(exp_nested)
229
+ for op in postfix.postfix_op():
230
+ if op.BANG():
231
+ if isinstance(exp, list):
232
+ raise LaTeXParsingError("Cannot apply postfix to derivative")
233
+ exp = sympy.factorial(exp, evaluate=False)
234
+ elif op.eval_at():
235
+ ev = op.eval_at()
236
+ at_b = None
237
+ at_a = None
238
+ if ev.eval_at_sup():
239
+ at_b = do_subs(exp, ev.eval_at_sup())
240
+ if ev.eval_at_sub():
241
+ at_a = do_subs(exp, ev.eval_at_sub())
242
+ if at_b is not None and at_a is not None:
243
+ exp = sympy.Add(at_b, -1 * at_a, evaluate=False)
244
+ elif at_b is not None:
245
+ exp = at_b
246
+ elif at_a is not None:
247
+ exp = at_a
248
+
249
+ return exp
250
+
251
+
252
+ def convert_exp(exp):
253
+ if hasattr(exp, 'exp'):
254
+ exp_nested = exp.exp()
255
+ else:
256
+ exp_nested = exp.exp_nofunc()
257
+
258
+ if exp_nested:
259
+ base = convert_exp(exp_nested)
260
+ if isinstance(base, list):
261
+ raise LaTeXParsingError("Cannot raise derivative to power")
262
+ if exp.atom():
263
+ exponent = convert_atom(exp.atom())
264
+ elif exp.expr():
265
+ exponent = convert_expr(exp.expr())
266
+ return sympy.Pow(base, exponent, evaluate=False)
267
+ else:
268
+ if hasattr(exp, 'comp'):
269
+ return convert_comp(exp.comp())
270
+ else:
271
+ return convert_comp(exp.comp_nofunc())
272
+
273
+
274
+ def convert_comp(comp):
275
+ if comp.group():
276
+ return convert_expr(comp.group().expr())
277
+ elif comp.abs_group():
278
+ return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False)
279
+ elif comp.atom():
280
+ return convert_atom(comp.atom())
281
+ elif comp.floor():
282
+ return convert_floor(comp.floor())
283
+ elif comp.ceil():
284
+ return convert_ceil(comp.ceil())
285
+ elif comp.func():
286
+ return convert_func(comp.func())
287
+
288
+
289
+ def convert_atom(atom):
290
+ if atom.LETTER():
291
+ sname = atom.LETTER().getText()
292
+ if atom.subexpr():
293
+ if atom.subexpr().expr(): # subscript is expr
294
+ subscript = convert_expr(atom.subexpr().expr())
295
+ else: # subscript is atom
296
+ subscript = convert_atom(atom.subexpr().atom())
297
+ sname += '_{' + StrPrinter().doprint(subscript) + '}'
298
+ if atom.SINGLE_QUOTES():
299
+ sname += atom.SINGLE_QUOTES().getText() # put after subscript for easy identify
300
+ return sympy.Symbol(sname)
301
+ elif atom.SYMBOL():
302
+ s = atom.SYMBOL().getText()[1:]
303
+ if s == "infty":
304
+ return sympy.oo
305
+ else:
306
+ if atom.subexpr():
307
+ subscript = None
308
+ if atom.subexpr().expr(): # subscript is expr
309
+ subscript = convert_expr(atom.subexpr().expr())
310
+ else: # subscript is atom
311
+ subscript = convert_atom(atom.subexpr().atom())
312
+ subscriptName = StrPrinter().doprint(subscript)
313
+ s += '_{' + subscriptName + '}'
314
+ return sympy.Symbol(s)
315
+ elif atom.number():
316
+ s = atom.number().getText().replace(",", "")
317
+ return sympy.Number(s)
318
+ elif atom.DIFFERENTIAL():
319
+ var = get_differential_var(atom.DIFFERENTIAL())
320
+ return sympy.Symbol('d' + var.name)
321
+ elif atom.mathit():
322
+ text = rule2text(atom.mathit().mathit_text())
323
+ return sympy.Symbol(text)
324
+ elif atom.frac():
325
+ return convert_frac(atom.frac())
326
+ elif atom.binom():
327
+ return convert_binom(atom.binom())
328
+ elif atom.bra():
329
+ val = convert_expr(atom.bra().expr())
330
+ return Bra(val)
331
+ elif atom.ket():
332
+ val = convert_expr(atom.ket().expr())
333
+ return Ket(val)
334
+
335
+
336
+ def rule2text(ctx):
337
+ stream = ctx.start.getInputStream()
338
+ # starting index of starting token
339
+ startIdx = ctx.start.start
340
+ # stopping index of stopping token
341
+ stopIdx = ctx.stop.stop
342
+
343
+ return stream.getText(startIdx, stopIdx)
344
+
345
+
346
+ def convert_frac(frac):
347
+ diff_op = False
348
+ partial_op = False
349
+ if frac.lower and frac.upper:
350
+ lower_itv = frac.lower.getSourceInterval()
351
+ lower_itv_len = lower_itv[1] - lower_itv[0] + 1
352
+ if (frac.lower.start == frac.lower.stop
353
+ and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL):
354
+ wrt = get_differential_var_str(frac.lower.start.text)
355
+ diff_op = True
356
+ elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL
357
+ and frac.lower.start.text == '\\partial'
358
+ and (frac.lower.stop.type == LaTeXLexer.LETTER
359
+ or frac.lower.stop.type == LaTeXLexer.SYMBOL)):
360
+ partial_op = True
361
+ wrt = frac.lower.stop.text
362
+ if frac.lower.stop.type == LaTeXLexer.SYMBOL:
363
+ wrt = wrt[1:]
364
+
365
+ if diff_op or partial_op:
366
+ wrt = sympy.Symbol(wrt)
367
+ if (diff_op and frac.upper.start == frac.upper.stop
368
+ and frac.upper.start.type == LaTeXLexer.LETTER
369
+ and frac.upper.start.text == 'd'):
370
+ return [wrt]
371
+ elif (partial_op and frac.upper.start == frac.upper.stop
372
+ and frac.upper.start.type == LaTeXLexer.SYMBOL
373
+ and frac.upper.start.text == '\\partial'):
374
+ return [wrt]
375
+ upper_text = rule2text(frac.upper)
376
+
377
+ expr_top = None
378
+ if diff_op and upper_text.startswith('d'):
379
+ expr_top = parse_latex(upper_text[1:])
380
+ elif partial_op and frac.upper.start.text == '\\partial':
381
+ expr_top = parse_latex(upper_text[len('\\partial'):])
382
+ if expr_top:
383
+ return sympy.Derivative(expr_top, wrt)
384
+ if frac.upper:
385
+ expr_top = convert_expr(frac.upper)
386
+ else:
387
+ expr_top = sympy.Number(frac.upperd.text)
388
+ if frac.lower:
389
+ expr_bot = convert_expr(frac.lower)
390
+ else:
391
+ expr_bot = sympy.Number(frac.lowerd.text)
392
+ inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False)
393
+ if expr_top == 1:
394
+ return inverse_denom
395
+ else:
396
+ return sympy.Mul(expr_top, inverse_denom, evaluate=False)
397
+
398
+ def convert_binom(binom):
399
+ expr_n = convert_expr(binom.n)
400
+ expr_k = convert_expr(binom.k)
401
+ return sympy.binomial(expr_n, expr_k, evaluate=False)
402
+
403
+ def convert_floor(floor):
404
+ val = convert_expr(floor.val)
405
+ return sympy.floor(val, evaluate=False)
406
+
407
+ def convert_ceil(ceil):
408
+ val = convert_expr(ceil.val)
409
+ return sympy.ceiling(val, evaluate=False)
410
+
411
+ def convert_func(func):
412
+ if func.func_normal():
413
+ if func.L_PAREN(): # function called with parenthesis
414
+ arg = convert_func_arg(func.func_arg())
415
+ else:
416
+ arg = convert_func_arg(func.func_arg_noparens())
417
+
418
+ name = func.func_normal().start.text[1:]
419
+
420
+ # change arc<trig> -> a<trig>
421
+ if name in [
422
+ "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot"
423
+ ]:
424
+ name = "a" + name[3:]
425
+ expr = getattr(sympy.functions, name)(arg, evaluate=False)
426
+ if name in ["arsinh", "arcosh", "artanh"]:
427
+ name = "a" + name[2:]
428
+ expr = getattr(sympy.functions, name)(arg, evaluate=False)
429
+
430
+ if name == "exp":
431
+ expr = sympy.exp(arg, evaluate=False)
432
+
433
+ if name in ("log", "lg", "ln"):
434
+ if func.subexpr():
435
+ if func.subexpr().expr():
436
+ base = convert_expr(func.subexpr().expr())
437
+ else:
438
+ base = convert_atom(func.subexpr().atom())
439
+ elif name == "lg": # ISO 80000-2:2019
440
+ base = 10
441
+ elif name in ("ln", "log"): # SymPy's latex printer prints ln as log by default
442
+ base = sympy.E
443
+ expr = sympy.log(arg, base, evaluate=False)
444
+
445
+ func_pow = None
446
+ should_pow = True
447
+ if func.supexpr():
448
+ if func.supexpr().expr():
449
+ func_pow = convert_expr(func.supexpr().expr())
450
+ else:
451
+ func_pow = convert_atom(func.supexpr().atom())
452
+
453
+ if name in [
454
+ "sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh",
455
+ "tanh"
456
+ ]:
457
+ if func_pow == -1:
458
+ name = "a" + name
459
+ should_pow = False
460
+ expr = getattr(sympy.functions, name)(arg, evaluate=False)
461
+
462
+ if func_pow and should_pow:
463
+ expr = sympy.Pow(expr, func_pow, evaluate=False)
464
+
465
+ return expr
466
+ elif func.LETTER() or func.SYMBOL():
467
+ if func.LETTER():
468
+ fname = func.LETTER().getText()
469
+ elif func.SYMBOL():
470
+ fname = func.SYMBOL().getText()[1:]
471
+ fname = str(fname) # can't be unicode
472
+ if func.subexpr():
473
+ if func.subexpr().expr(): # subscript is expr
474
+ subscript = convert_expr(func.subexpr().expr())
475
+ else: # subscript is atom
476
+ subscript = convert_atom(func.subexpr().atom())
477
+ subscriptName = StrPrinter().doprint(subscript)
478
+ fname += '_{' + subscriptName + '}'
479
+ if func.SINGLE_QUOTES():
480
+ fname += func.SINGLE_QUOTES().getText()
481
+ input_args = func.args()
482
+ output_args = []
483
+ while input_args.args(): # handle multiple arguments to function
484
+ output_args.append(convert_expr(input_args.expr()))
485
+ input_args = input_args.args()
486
+ output_args.append(convert_expr(input_args.expr()))
487
+ return sympy.Function(fname)(*output_args)
488
+ elif func.FUNC_INT():
489
+ return handle_integral(func)
490
+ elif func.FUNC_SQRT():
491
+ expr = convert_expr(func.base)
492
+ if func.root:
493
+ r = convert_expr(func.root)
494
+ return sympy.root(expr, r, evaluate=False)
495
+ else:
496
+ return sympy.sqrt(expr, evaluate=False)
497
+ elif func.FUNC_OVERLINE():
498
+ expr = convert_expr(func.base)
499
+ return sympy.conjugate(expr, evaluate=False)
500
+ elif func.FUNC_SUM():
501
+ return handle_sum_or_prod(func, "summation")
502
+ elif func.FUNC_PROD():
503
+ return handle_sum_or_prod(func, "product")
504
+ elif func.FUNC_LIM():
505
+ return handle_limit(func)
506
+
507
+
508
+ def convert_func_arg(arg):
509
+ if hasattr(arg, 'expr'):
510
+ return convert_expr(arg.expr())
511
+ else:
512
+ return convert_mp(arg.mp_nofunc())
513
+
514
+
515
+ def handle_integral(func):
516
+ if func.additive():
517
+ integrand = convert_add(func.additive())
518
+ elif func.frac():
519
+ integrand = convert_frac(func.frac())
520
+ else:
521
+ integrand = 1
522
+
523
+ int_var = None
524
+ if func.DIFFERENTIAL():
525
+ int_var = get_differential_var(func.DIFFERENTIAL())
526
+ else:
527
+ for sym in integrand.atoms(sympy.Symbol):
528
+ s = str(sym)
529
+ if len(s) > 1 and s[0] == 'd':
530
+ if s[1] == '\\':
531
+ int_var = sympy.Symbol(s[2:])
532
+ else:
533
+ int_var = sympy.Symbol(s[1:])
534
+ int_sym = sym
535
+ if int_var:
536
+ integrand = integrand.subs(int_sym, 1)
537
+ else:
538
+ # Assume dx by default
539
+ int_var = sympy.Symbol('x')
540
+
541
+ if func.subexpr():
542
+ if func.subexpr().atom():
543
+ lower = convert_atom(func.subexpr().atom())
544
+ else:
545
+ lower = convert_expr(func.subexpr().expr())
546
+ if func.supexpr().atom():
547
+ upper = convert_atom(func.supexpr().atom())
548
+ else:
549
+ upper = convert_expr(func.supexpr().expr())
550
+ return sympy.Integral(integrand, (int_var, lower, upper))
551
+ else:
552
+ return sympy.Integral(integrand, int_var)
553
+
554
+
555
+ def handle_sum_or_prod(func, name):
556
+ val = convert_mp(func.mp())
557
+ iter_var = convert_expr(func.subeq().equality().expr(0))
558
+ start = convert_expr(func.subeq().equality().expr(1))
559
+ if func.supexpr().expr(): # ^{expr}
560
+ end = convert_expr(func.supexpr().expr())
561
+ else: # ^atom
562
+ end = convert_atom(func.supexpr().atom())
563
+
564
+ if name == "summation":
565
+ return sympy.Sum(val, (iter_var, start, end))
566
+ elif name == "product":
567
+ return sympy.Product(val, (iter_var, start, end))
568
+
569
+
570
+ def handle_limit(func):
571
+ sub = func.limit_sub()
572
+ if sub.LETTER():
573
+ var = sympy.Symbol(sub.LETTER().getText())
574
+ elif sub.SYMBOL():
575
+ var = sympy.Symbol(sub.SYMBOL().getText()[1:])
576
+ else:
577
+ var = sympy.Symbol('x')
578
+ if sub.SUB():
579
+ direction = "-"
580
+ elif sub.ADD():
581
+ direction = "+"
582
+ else:
583
+ direction = "+-"
584
+ approaching = convert_expr(sub.expr())
585
+ content = convert_mp(func.mp())
586
+
587
+ return sympy.Limit(content, var, approaching, direction)
588
+
589
+
590
+ def get_differential_var(d):
591
+ text = get_differential_var_str(d.getText())
592
+ return sympy.Symbol(text)
593
+
594
+
595
+ def get_differential_var_str(text):
596
+ for i in range(1, len(text)):
597
+ c = text[i]
598
+ if not (c == " " or c == "\r" or c == "\n" or c == "\t"):
599
+ idx = i
600
+ break
601
+ text = text[idx:]
602
+ if text[0] == "\\":
603
+ text = text[1:]
604
+ return text
llmeval-env/lib/python3.10/site-packages/sympy/parsing/latex/errors.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ class LaTeXParsingError(Exception):
2
+ pass
llmeval-env/lib/python3.10/site-packages/sympy/parsing/mathematica.py ADDED
@@ -0,0 +1,1080 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import re
3
+ import typing
4
+ from itertools import product
5
+ from typing import Any, Callable
6
+
7
+ import sympy
8
+ from sympy import Mul, Add, Pow, log, exp, sqrt, cos, sin, tan, asin, acos, acot, asec, acsc, sinh, cosh, tanh, asinh, \
9
+ acosh, atanh, acoth, asech, acsch, expand, im, flatten, polylog, cancel, expand_trig, sign, simplify, \
10
+ UnevaluatedExpr, S, atan, atan2, Mod, Max, Min, rf, Ei, Si, Ci, airyai, airyaiprime, airybi, primepi, prime, \
11
+ isprime, cot, sec, csc, csch, sech, coth, Function, I, pi, Tuple, GreaterThan, StrictGreaterThan, StrictLessThan, \
12
+ LessThan, Equality, Or, And, Lambda, Integer, Dummy, symbols
13
+ from sympy.core.sympify import sympify, _sympify
14
+ from sympy.functions.special.bessel import airybiprime
15
+ from sympy.functions.special.error_functions import li
16
+ from sympy.utilities.exceptions import sympy_deprecation_warning
17
+
18
+
19
+ def mathematica(s, additional_translations=None):
20
+ sympy_deprecation_warning(
21
+ """The ``mathematica`` function for the Mathematica parser is now
22
+ deprecated. Use ``parse_mathematica`` instead.
23
+ The parameter ``additional_translation`` can be replaced by SymPy's
24
+ .replace( ) or .subs( ) methods on the output expression instead.""",
25
+ deprecated_since_version="1.11",
26
+ active_deprecations_target="mathematica-parser-new",
27
+ )
28
+ parser = MathematicaParser(additional_translations)
29
+ return sympify(parser._parse_old(s))
30
+
31
+
32
+ def parse_mathematica(s):
33
+ """
34
+ Translate a string containing a Wolfram Mathematica expression to a SymPy
35
+ expression.
36
+
37
+ If the translator is unable to find a suitable SymPy expression, the
38
+ ``FullForm`` of the Mathematica expression will be output, using SymPy
39
+ ``Function`` objects as nodes of the syntax tree.
40
+
41
+ Examples
42
+ ========
43
+
44
+ >>> from sympy.parsing.mathematica import parse_mathematica
45
+ >>> parse_mathematica("Sin[x]^2 Tan[y]")
46
+ sin(x)**2*tan(y)
47
+ >>> e = parse_mathematica("F[7,5,3]")
48
+ >>> e
49
+ F(7, 5, 3)
50
+ >>> from sympy import Function, Max, Min
51
+ >>> e.replace(Function("F"), lambda *x: Max(*x)*Min(*x))
52
+ 21
53
+
54
+ Both standard input form and Mathematica full form are supported:
55
+
56
+ >>> parse_mathematica("x*(a + b)")
57
+ x*(a + b)
58
+ >>> parse_mathematica("Times[x, Plus[a, b]]")
59
+ x*(a + b)
60
+
61
+ To get a matrix from Wolfram's code:
62
+
63
+ >>> m = parse_mathematica("{{a, b}, {c, d}}")
64
+ >>> m
65
+ ((a, b), (c, d))
66
+ >>> from sympy import Matrix
67
+ >>> Matrix(m)
68
+ Matrix([
69
+ [a, b],
70
+ [c, d]])
71
+
72
+ If the translation into equivalent SymPy expressions fails, an SymPy
73
+ expression equivalent to Wolfram Mathematica's "FullForm" will be created:
74
+
75
+ >>> parse_mathematica("x_.")
76
+ Optional(Pattern(x, Blank()))
77
+ >>> parse_mathematica("Plus @@ {x, y, z}")
78
+ Apply(Plus, (x, y, z))
79
+ >>> parse_mathematica("f[x_, 3] := x^3 /; x > 0")
80
+ SetDelayed(f(Pattern(x, Blank()), 3), Condition(x**3, x > 0))
81
+ """
82
+ parser = MathematicaParser()
83
+ return parser.parse(s)
84
+
85
+
86
+ def _parse_Function(*args):
87
+ if len(args) == 1:
88
+ arg = args[0]
89
+ Slot = Function("Slot")
90
+ slots = arg.atoms(Slot)
91
+ numbers = [a.args[0] for a in slots]
92
+ number_of_arguments = max(numbers)
93
+ if isinstance(number_of_arguments, Integer):
94
+ variables = symbols(f"dummy0:{number_of_arguments}", cls=Dummy)
95
+ return Lambda(variables, arg.xreplace({Slot(i+1): v for i, v in enumerate(variables)}))
96
+ return Lambda((), arg)
97
+ elif len(args) == 2:
98
+ variables = args[0]
99
+ body = args[1]
100
+ return Lambda(variables, body)
101
+ else:
102
+ raise SyntaxError("Function node expects 1 or 2 arguments")
103
+
104
+
105
+ def _deco(cls):
106
+ cls._initialize_class()
107
+ return cls
108
+
109
+
110
+ @_deco
111
+ class MathematicaParser:
112
+ """
113
+ An instance of this class converts a string of a Wolfram Mathematica
114
+ expression to a SymPy expression.
115
+
116
+ The main parser acts internally in three stages:
117
+
118
+ 1. tokenizer: tokenizes the Mathematica expression and adds the missing *
119
+ operators. Handled by ``_from_mathematica_to_tokens(...)``
120
+ 2. full form list: sort the list of strings output by the tokenizer into a
121
+ syntax tree of nested lists and strings, equivalent to Mathematica's
122
+ ``FullForm`` expression output. This is handled by the function
123
+ ``_from_tokens_to_fullformlist(...)``.
124
+ 3. SymPy expression: the syntax tree expressed as full form list is visited
125
+ and the nodes with equivalent classes in SymPy are replaced. Unknown
126
+ syntax tree nodes are cast to SymPy ``Function`` objects. This is
127
+ handled by ``_from_fullformlist_to_sympy(...)``.
128
+
129
+ """
130
+
131
+ # left: Mathematica, right: SymPy
132
+ CORRESPONDENCES = {
133
+ 'Sqrt[x]': 'sqrt(x)',
134
+ 'Exp[x]': 'exp(x)',
135
+ 'Log[x]': 'log(x)',
136
+ 'Log[x,y]': 'log(y,x)',
137
+ 'Log2[x]': 'log(x,2)',
138
+ 'Log10[x]': 'log(x,10)',
139
+ 'Mod[x,y]': 'Mod(x,y)',
140
+ 'Max[*x]': 'Max(*x)',
141
+ 'Min[*x]': 'Min(*x)',
142
+ 'Pochhammer[x,y]':'rf(x,y)',
143
+ 'ArcTan[x,y]':'atan2(y,x)',
144
+ 'ExpIntegralEi[x]': 'Ei(x)',
145
+ 'SinIntegral[x]': 'Si(x)',
146
+ 'CosIntegral[x]': 'Ci(x)',
147
+ 'AiryAi[x]': 'airyai(x)',
148
+ 'AiryAiPrime[x]': 'airyaiprime(x)',
149
+ 'AiryBi[x]' :'airybi(x)',
150
+ 'AiryBiPrime[x]' :'airybiprime(x)',
151
+ 'LogIntegral[x]':' li(x)',
152
+ 'PrimePi[x]': 'primepi(x)',
153
+ 'Prime[x]': 'prime(x)',
154
+ 'PrimeQ[x]': 'isprime(x)'
155
+ }
156
+
157
+ # trigonometric, e.t.c.
158
+ for arc, tri, h in product(('', 'Arc'), (
159
+ 'Sin', 'Cos', 'Tan', 'Cot', 'Sec', 'Csc'), ('', 'h')):
160
+ fm = arc + tri + h + '[x]'
161
+ if arc: # arc func
162
+ fs = 'a' + tri.lower() + h + '(x)'
163
+ else: # non-arc func
164
+ fs = tri.lower() + h + '(x)'
165
+ CORRESPONDENCES.update({fm: fs})
166
+
167
+ REPLACEMENTS = {
168
+ ' ': '',
169
+ '^': '**',
170
+ '{': '[',
171
+ '}': ']',
172
+ }
173
+
174
+ RULES = {
175
+ # a single whitespace to '*'
176
+ 'whitespace': (
177
+ re.compile(r'''
178
+ (?:(?<=[a-zA-Z\d])|(?<=\d\.)) # a letter or a number
179
+ \s+ # any number of whitespaces
180
+ (?:(?=[a-zA-Z\d])|(?=\.\d)) # a letter or a number
181
+ ''', re.VERBOSE),
182
+ '*'),
183
+
184
+ # add omitted '*' character
185
+ 'add*_1': (
186
+ re.compile(r'''
187
+ (?:(?<=[])\d])|(?<=\d\.)) # ], ) or a number
188
+ # ''
189
+ (?=[(a-zA-Z]) # ( or a single letter
190
+ ''', re.VERBOSE),
191
+ '*'),
192
+
193
+ # add omitted '*' character (variable letter preceding)
194
+ 'add*_2': (
195
+ re.compile(r'''
196
+ (?<=[a-zA-Z]) # a letter
197
+ \( # ( as a character
198
+ (?=.) # any characters
199
+ ''', re.VERBOSE),
200
+ '*('),
201
+
202
+ # convert 'Pi' to 'pi'
203
+ 'Pi': (
204
+ re.compile(r'''
205
+ (?:
206
+ \A|(?<=[^a-zA-Z])
207
+ )
208
+ Pi # 'Pi' is 3.14159... in Mathematica
209
+ (?=[^a-zA-Z])
210
+ ''', re.VERBOSE),
211
+ 'pi'),
212
+ }
213
+
214
+ # Mathematica function name pattern
215
+ FM_PATTERN = re.compile(r'''
216
+ (?:
217
+ \A|(?<=[^a-zA-Z]) # at the top or a non-letter
218
+ )
219
+ [A-Z][a-zA-Z\d]* # Function
220
+ (?=\[) # [ as a character
221
+ ''', re.VERBOSE)
222
+
223
+ # list or matrix pattern (for future usage)
224
+ ARG_MTRX_PATTERN = re.compile(r'''
225
+ \{.*\}
226
+ ''', re.VERBOSE)
227
+
228
+ # regex string for function argument pattern
229
+ ARGS_PATTERN_TEMPLATE = r'''
230
+ (?:
231
+ \A|(?<=[^a-zA-Z])
232
+ )
233
+ {arguments} # model argument like x, y,...
234
+ (?=[^a-zA-Z])
235
+ '''
236
+
237
+ # will contain transformed CORRESPONDENCES dictionary
238
+ TRANSLATIONS: dict[tuple[str, int], dict[str, Any]] = {}
239
+
240
+ # cache for a raw users' translation dictionary
241
+ cache_original: dict[tuple[str, int], dict[str, Any]] = {}
242
+
243
+ # cache for a compiled users' translation dictionary
244
+ cache_compiled: dict[tuple[str, int], dict[str, Any]] = {}
245
+
246
+ @classmethod
247
+ def _initialize_class(cls):
248
+ # get a transformed CORRESPONDENCES dictionary
249
+ d = cls._compile_dictionary(cls.CORRESPONDENCES)
250
+ cls.TRANSLATIONS.update(d)
251
+
252
+ def __init__(self, additional_translations=None):
253
+ self.translations = {}
254
+
255
+ # update with TRANSLATIONS (class constant)
256
+ self.translations.update(self.TRANSLATIONS)
257
+
258
+ if additional_translations is None:
259
+ additional_translations = {}
260
+
261
+ # check the latest added translations
262
+ if self.__class__.cache_original != additional_translations:
263
+ if not isinstance(additional_translations, dict):
264
+ raise ValueError('The argument must be dict type')
265
+
266
+ # get a transformed additional_translations dictionary
267
+ d = self._compile_dictionary(additional_translations)
268
+
269
+ # update cache
270
+ self.__class__.cache_original = additional_translations
271
+ self.__class__.cache_compiled = d
272
+
273
+ # merge user's own translations
274
+ self.translations.update(self.__class__.cache_compiled)
275
+
276
+ @classmethod
277
+ def _compile_dictionary(cls, dic):
278
+ # for return
279
+ d = {}
280
+
281
+ for fm, fs in dic.items():
282
+ # check function form
283
+ cls._check_input(fm)
284
+ cls._check_input(fs)
285
+
286
+ # uncover '*' hiding behind a whitespace
287
+ fm = cls._apply_rules(fm, 'whitespace')
288
+ fs = cls._apply_rules(fs, 'whitespace')
289
+
290
+ # remove whitespace(s)
291
+ fm = cls._replace(fm, ' ')
292
+ fs = cls._replace(fs, ' ')
293
+
294
+ # search Mathematica function name
295
+ m = cls.FM_PATTERN.search(fm)
296
+
297
+ # if no-hit
298
+ if m is None:
299
+ err = "'{f}' function form is invalid.".format(f=fm)
300
+ raise ValueError(err)
301
+
302
+ # get Mathematica function name like 'Log'
303
+ fm_name = m.group()
304
+
305
+ # get arguments of Mathematica function
306
+ args, end = cls._get_args(m)
307
+
308
+ # function side check. (e.g.) '2*Func[x]' is invalid.
309
+ if m.start() != 0 or end != len(fm):
310
+ err = "'{f}' function form is invalid.".format(f=fm)
311
+ raise ValueError(err)
312
+
313
+ # check the last argument's 1st character
314
+ if args[-1][0] == '*':
315
+ key_arg = '*'
316
+ else:
317
+ key_arg = len(args)
318
+
319
+ key = (fm_name, key_arg)
320
+
321
+ # convert '*x' to '\\*x' for regex
322
+ re_args = [x if x[0] != '*' else '\\' + x for x in args]
323
+
324
+ # for regex. Example: (?:(x|y|z))
325
+ xyz = '(?:(' + '|'.join(re_args) + '))'
326
+
327
+ # string for regex compile
328
+ patStr = cls.ARGS_PATTERN_TEMPLATE.format(arguments=xyz)
329
+
330
+ pat = re.compile(patStr, re.VERBOSE)
331
+
332
+ # update dictionary
333
+ d[key] = {}
334
+ d[key]['fs'] = fs # SymPy function template
335
+ d[key]['args'] = args # args are ['x', 'y'] for example
336
+ d[key]['pat'] = pat
337
+
338
+ return d
339
+
340
+ def _convert_function(self, s):
341
+ '''Parse Mathematica function to SymPy one'''
342
+
343
+ # compiled regex object
344
+ pat = self.FM_PATTERN
345
+
346
+ scanned = '' # converted string
347
+ cur = 0 # position cursor
348
+ while True:
349
+ m = pat.search(s)
350
+
351
+ if m is None:
352
+ # append the rest of string
353
+ scanned += s
354
+ break
355
+
356
+ # get Mathematica function name
357
+ fm = m.group()
358
+
359
+ # get arguments, and the end position of fm function
360
+ args, end = self._get_args(m)
361
+
362
+ # the start position of fm function
363
+ bgn = m.start()
364
+
365
+ # convert Mathematica function to SymPy one
366
+ s = self._convert_one_function(s, fm, args, bgn, end)
367
+
368
+ # update cursor
369
+ cur = bgn
370
+
371
+ # append converted part
372
+ scanned += s[:cur]
373
+
374
+ # shrink s
375
+ s = s[cur:]
376
+
377
+ return scanned
378
+
379
+ def _convert_one_function(self, s, fm, args, bgn, end):
380
+ # no variable-length argument
381
+ if (fm, len(args)) in self.translations:
382
+ key = (fm, len(args))
383
+
384
+ # x, y,... model arguments
385
+ x_args = self.translations[key]['args']
386
+
387
+ # make CORRESPONDENCES between model arguments and actual ones
388
+ d = {k: v for k, v in zip(x_args, args)}
389
+
390
+ # with variable-length argument
391
+ elif (fm, '*') in self.translations:
392
+ key = (fm, '*')
393
+
394
+ # x, y,..*args (model arguments)
395
+ x_args = self.translations[key]['args']
396
+
397
+ # make CORRESPONDENCES between model arguments and actual ones
398
+ d = {}
399
+ for i, x in enumerate(x_args):
400
+ if x[0] == '*':
401
+ d[x] = ','.join(args[i:])
402
+ break
403
+ d[x] = args[i]
404
+
405
+ # out of self.translations
406
+ else:
407
+ err = "'{f}' is out of the whitelist.".format(f=fm)
408
+ raise ValueError(err)
409
+
410
+ # template string of converted function
411
+ template = self.translations[key]['fs']
412
+
413
+ # regex pattern for x_args
414
+ pat = self.translations[key]['pat']
415
+
416
+ scanned = ''
417
+ cur = 0
418
+ while True:
419
+ m = pat.search(template)
420
+
421
+ if m is None:
422
+ scanned += template
423
+ break
424
+
425
+ # get model argument
426
+ x = m.group()
427
+
428
+ # get a start position of the model argument
429
+ xbgn = m.start()
430
+
431
+ # add the corresponding actual argument
432
+ scanned += template[:xbgn] + d[x]
433
+
434
+ # update cursor to the end of the model argument
435
+ cur = m.end()
436
+
437
+ # shrink template
438
+ template = template[cur:]
439
+
440
+ # update to swapped string
441
+ s = s[:bgn] + scanned + s[end:]
442
+
443
+ return s
444
+
445
+ @classmethod
446
+ def _get_args(cls, m):
447
+ '''Get arguments of a Mathematica function'''
448
+
449
+ s = m.string # whole string
450
+ anc = m.end() + 1 # pointing the first letter of arguments
451
+ square, curly = [], [] # stack for brakets
452
+ args = []
453
+
454
+ # current cursor
455
+ cur = anc
456
+ for i, c in enumerate(s[anc:], anc):
457
+ # extract one argument
458
+ if c == ',' and (not square) and (not curly):
459
+ args.append(s[cur:i]) # add an argument
460
+ cur = i + 1 # move cursor
461
+
462
+ # handle list or matrix (for future usage)
463
+ if c == '{':
464
+ curly.append(c)
465
+ elif c == '}':
466
+ curly.pop()
467
+
468
+ # seek corresponding ']' with skipping irrevant ones
469
+ if c == '[':
470
+ square.append(c)
471
+ elif c == ']':
472
+ if square:
473
+ square.pop()
474
+ else: # empty stack
475
+ args.append(s[cur:i])
476
+ break
477
+
478
+ # the next position to ']' bracket (the function end)
479
+ func_end = i + 1
480
+
481
+ return args, func_end
482
+
483
+ @classmethod
484
+ def _replace(cls, s, bef):
485
+ aft = cls.REPLACEMENTS[bef]
486
+ s = s.replace(bef, aft)
487
+ return s
488
+
489
+ @classmethod
490
+ def _apply_rules(cls, s, bef):
491
+ pat, aft = cls.RULES[bef]
492
+ return pat.sub(aft, s)
493
+
494
+ @classmethod
495
+ def _check_input(cls, s):
496
+ for bracket in (('[', ']'), ('{', '}'), ('(', ')')):
497
+ if s.count(bracket[0]) != s.count(bracket[1]):
498
+ err = "'{f}' function form is invalid.".format(f=s)
499
+ raise ValueError(err)
500
+
501
+ if '{' in s:
502
+ err = "Currently list is not supported."
503
+ raise ValueError(err)
504
+
505
+ def _parse_old(self, s):
506
+ # input check
507
+ self._check_input(s)
508
+
509
+ # uncover '*' hiding behind a whitespace
510
+ s = self._apply_rules(s, 'whitespace')
511
+
512
+ # remove whitespace(s)
513
+ s = self._replace(s, ' ')
514
+
515
+ # add omitted '*' character
516
+ s = self._apply_rules(s, 'add*_1')
517
+ s = self._apply_rules(s, 'add*_2')
518
+
519
+ # translate function
520
+ s = self._convert_function(s)
521
+
522
+ # '^' to '**'
523
+ s = self._replace(s, '^')
524
+
525
+ # 'Pi' to 'pi'
526
+ s = self._apply_rules(s, 'Pi')
527
+
528
+ # '{', '}' to '[', ']', respectively
529
+ # s = cls._replace(s, '{') # currently list is not taken into account
530
+ # s = cls._replace(s, '}')
531
+
532
+ return s
533
+
534
+ def parse(self, s):
535
+ s2 = self._from_mathematica_to_tokens(s)
536
+ s3 = self._from_tokens_to_fullformlist(s2)
537
+ s4 = self._from_fullformlist_to_sympy(s3)
538
+ return s4
539
+
540
+ INFIX = "Infix"
541
+ PREFIX = "Prefix"
542
+ POSTFIX = "Postfix"
543
+ FLAT = "Flat"
544
+ RIGHT = "Right"
545
+ LEFT = "Left"
546
+
547
+ _mathematica_op_precedence: list[tuple[str, str | None, dict[str, str | Callable]]] = [
548
+ (POSTFIX, None, {";": lambda x: x + ["Null"] if isinstance(x, list) and x and x[0] == "CompoundExpression" else ["CompoundExpression", x, "Null"]}),
549
+ (INFIX, FLAT, {";": "CompoundExpression"}),
550
+ (INFIX, RIGHT, {"=": "Set", ":=": "SetDelayed", "+=": "AddTo", "-=": "SubtractFrom", "*=": "TimesBy", "/=": "DivideBy"}),
551
+ (INFIX, LEFT, {"//": lambda x, y: [x, y]}),
552
+ (POSTFIX, None, {"&": "Function"}),
553
+ (INFIX, LEFT, {"/.": "ReplaceAll"}),
554
+ (INFIX, RIGHT, {"->": "Rule", ":>": "RuleDelayed"}),
555
+ (INFIX, LEFT, {"/;": "Condition"}),
556
+ (INFIX, FLAT, {"|": "Alternatives"}),
557
+ (POSTFIX, None, {"..": "Repeated", "...": "RepeatedNull"}),
558
+ (INFIX, FLAT, {"||": "Or"}),
559
+ (INFIX, FLAT, {"&&": "And"}),
560
+ (PREFIX, None, {"!": "Not"}),
561
+ (INFIX, FLAT, {"===": "SameQ", "=!=": "UnsameQ"}),
562
+ (INFIX, FLAT, {"==": "Equal", "!=": "Unequal", "<=": "LessEqual", "<": "Less", ">=": "GreaterEqual", ">": "Greater"}),
563
+ (INFIX, None, {";;": "Span"}),
564
+ (INFIX, FLAT, {"+": "Plus", "-": "Plus"}),
565
+ (INFIX, FLAT, {"*": "Times", "/": "Times"}),
566
+ (INFIX, FLAT, {".": "Dot"}),
567
+ (PREFIX, None, {"-": lambda x: MathematicaParser._get_neg(x),
568
+ "+": lambda x: x}),
569
+ (INFIX, RIGHT, {"^": "Power"}),
570
+ (INFIX, RIGHT, {"@@": "Apply", "/@": "Map", "//@": "MapAll", "@@@": lambda x, y: ["Apply", x, y, ["List", "1"]]}),
571
+ (POSTFIX, None, {"'": "Derivative", "!": "Factorial", "!!": "Factorial2", "--": "Decrement"}),
572
+ (INFIX, None, {"[": lambda x, y: [x, *y], "[[": lambda x, y: ["Part", x, *y]}),
573
+ (PREFIX, None, {"{": lambda x: ["List", *x], "(": lambda x: x[0]}),
574
+ (INFIX, None, {"?": "PatternTest"}),
575
+ (POSTFIX, None, {
576
+ "_": lambda x: ["Pattern", x, ["Blank"]],
577
+ "_.": lambda x: ["Optional", ["Pattern", x, ["Blank"]]],
578
+ "__": lambda x: ["Pattern", x, ["BlankSequence"]],
579
+ "___": lambda x: ["Pattern", x, ["BlankNullSequence"]],
580
+ }),
581
+ (INFIX, None, {"_": lambda x, y: ["Pattern", x, ["Blank", y]]}),
582
+ (PREFIX, None, {"#": "Slot", "##": "SlotSequence"}),
583
+ ]
584
+
585
+ _missing_arguments_default = {
586
+ "#": lambda: ["Slot", "1"],
587
+ "##": lambda: ["SlotSequence", "1"],
588
+ }
589
+
590
+ _literal = r"[A-Za-z][A-Za-z0-9]*"
591
+ _number = r"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)"
592
+
593
+ _enclosure_open = ["(", "[", "[[", "{"]
594
+ _enclosure_close = [")", "]", "]]", "}"]
595
+
596
+ @classmethod
597
+ def _get_neg(cls, x):
598
+ return f"-{x}" if isinstance(x, str) and re.match(MathematicaParser._number, x) else ["Times", "-1", x]
599
+
600
+ @classmethod
601
+ def _get_inv(cls, x):
602
+ return ["Power", x, "-1"]
603
+
604
+ _regex_tokenizer = None
605
+
606
+ def _get_tokenizer(self):
607
+ if self._regex_tokenizer is not None:
608
+ # Check if the regular expression has already been compiled:
609
+ return self._regex_tokenizer
610
+ tokens = [self._literal, self._number]
611
+ tokens_escape = self._enclosure_open[:] + self._enclosure_close[:]
612
+ for typ, strat, symdict in self._mathematica_op_precedence:
613
+ for k in symdict:
614
+ tokens_escape.append(k)
615
+ tokens_escape.sort(key=lambda x: -len(x))
616
+ tokens.extend(map(re.escape, tokens_escape))
617
+ tokens.append(",")
618
+ tokens.append("\n")
619
+ tokenizer = re.compile("(" + "|".join(tokens) + ")")
620
+ self._regex_tokenizer = tokenizer
621
+ return self._regex_tokenizer
622
+
623
+ def _from_mathematica_to_tokens(self, code: str):
624
+ tokenizer = self._get_tokenizer()
625
+
626
+ # Find strings:
627
+ code_splits: list[str | list] = []
628
+ while True:
629
+ string_start = code.find("\"")
630
+ if string_start == -1:
631
+ if len(code) > 0:
632
+ code_splits.append(code)
633
+ break
634
+ match_end = re.search(r'(?<!\\)"', code[string_start+1:])
635
+ if match_end is None:
636
+ raise SyntaxError('mismatch in string " " expression')
637
+ string_end = string_start + match_end.start() + 1
638
+ if string_start > 0:
639
+ code_splits.append(code[:string_start])
640
+ code_splits.append(["_Str", code[string_start+1:string_end].replace('\\"', '"')])
641
+ code = code[string_end+1:]
642
+
643
+ # Remove comments:
644
+ for i, code_split in enumerate(code_splits):
645
+ if isinstance(code_split, list):
646
+ continue
647
+ while True:
648
+ pos_comment_start = code_split.find("(*")
649
+ if pos_comment_start == -1:
650
+ break
651
+ pos_comment_end = code_split.find("*)")
652
+ if pos_comment_end == -1 or pos_comment_end < pos_comment_start:
653
+ raise SyntaxError("mismatch in comment (* *) code")
654
+ code_split = code_split[:pos_comment_start] + code_split[pos_comment_end+2:]
655
+ code_splits[i] = code_split
656
+
657
+ # Tokenize the input strings with a regular expression:
658
+ token_lists = [tokenizer.findall(i) if isinstance(i, str) and i.isascii() else [i] for i in code_splits]
659
+ tokens = [j for i in token_lists for j in i]
660
+
661
+ # Remove newlines at the beginning
662
+ while tokens and tokens[0] == "\n":
663
+ tokens.pop(0)
664
+ # Remove newlines at the end
665
+ while tokens and tokens[-1] == "\n":
666
+ tokens.pop(-1)
667
+
668
+ return tokens
669
+
670
+ def _is_op(self, token: str | list) -> bool:
671
+ if isinstance(token, list):
672
+ return False
673
+ if re.match(self._literal, token):
674
+ return False
675
+ if re.match("-?" + self._number, token):
676
+ return False
677
+ return True
678
+
679
+ def _is_valid_star1(self, token: str | list) -> bool:
680
+ if token in (")", "}"):
681
+ return True
682
+ return not self._is_op(token)
683
+
684
+ def _is_valid_star2(self, token: str | list) -> bool:
685
+ if token in ("(", "{"):
686
+ return True
687
+ return not self._is_op(token)
688
+
689
+ def _from_tokens_to_fullformlist(self, tokens: list):
690
+ stack: list[list] = [[]]
691
+ open_seq = []
692
+ pointer: int = 0
693
+ while pointer < len(tokens):
694
+ token = tokens[pointer]
695
+ if token in self._enclosure_open:
696
+ stack[-1].append(token)
697
+ open_seq.append(token)
698
+ stack.append([])
699
+ elif token == ",":
700
+ if len(stack[-1]) == 0 and stack[-2][-1] == open_seq[-1]:
701
+ raise SyntaxError("%s cannot be followed by comma ," % open_seq[-1])
702
+ stack[-1] = self._parse_after_braces(stack[-1])
703
+ stack.append([])
704
+ elif token in self._enclosure_close:
705
+ ind = self._enclosure_close.index(token)
706
+ if self._enclosure_open[ind] != open_seq[-1]:
707
+ unmatched_enclosure = SyntaxError("unmatched enclosure")
708
+ if token == "]]" and open_seq[-1] == "[":
709
+ if open_seq[-2] == "[":
710
+ # These two lines would be logically correct, but are
711
+ # unnecessary:
712
+ # token = "]"
713
+ # tokens[pointer] = "]"
714
+ tokens.insert(pointer+1, "]")
715
+ elif open_seq[-2] == "[[":
716
+ if tokens[pointer+1] == "]":
717
+ tokens[pointer+1] = "]]"
718
+ elif tokens[pointer+1] == "]]":
719
+ tokens[pointer+1] = "]]"
720
+ tokens.insert(pointer+2, "]")
721
+ else:
722
+ raise unmatched_enclosure
723
+ else:
724
+ raise unmatched_enclosure
725
+ if len(stack[-1]) == 0 and stack[-2][-1] == "(":
726
+ raise SyntaxError("( ) not valid syntax")
727
+ last_stack = self._parse_after_braces(stack[-1], True)
728
+ stack[-1] = last_stack
729
+ new_stack_element = []
730
+ while stack[-1][-1] != open_seq[-1]:
731
+ new_stack_element.append(stack.pop())
732
+ new_stack_element.reverse()
733
+ if open_seq[-1] == "(" and len(new_stack_element) != 1:
734
+ raise SyntaxError("( must be followed by one expression, %i detected" % len(new_stack_element))
735
+ stack[-1].append(new_stack_element)
736
+ open_seq.pop(-1)
737
+ else:
738
+ stack[-1].append(token)
739
+ pointer += 1
740
+ assert len(stack) == 1
741
+ return self._parse_after_braces(stack[0])
742
+
743
+ def _util_remove_newlines(self, lines: list, tokens: list, inside_enclosure: bool):
744
+ pointer = 0
745
+ size = len(tokens)
746
+ while pointer < size:
747
+ token = tokens[pointer]
748
+ if token == "\n":
749
+ if inside_enclosure:
750
+ # Ignore newlines inside enclosures
751
+ tokens.pop(pointer)
752
+ size -= 1
753
+ continue
754
+ if pointer == 0:
755
+ tokens.pop(0)
756
+ size -= 1
757
+ continue
758
+ if pointer > 1:
759
+ try:
760
+ prev_expr = self._parse_after_braces(tokens[:pointer], inside_enclosure)
761
+ except SyntaxError:
762
+ tokens.pop(pointer)
763
+ size -= 1
764
+ continue
765
+ else:
766
+ prev_expr = tokens[0]
767
+ if len(prev_expr) > 0 and prev_expr[0] == "CompoundExpression":
768
+ lines.extend(prev_expr[1:])
769
+ else:
770
+ lines.append(prev_expr)
771
+ for i in range(pointer):
772
+ tokens.pop(0)
773
+ size -= pointer
774
+ pointer = 0
775
+ continue
776
+ pointer += 1
777
+
778
+ def _util_add_missing_asterisks(self, tokens: list):
779
+ size: int = len(tokens)
780
+ pointer: int = 0
781
+ while pointer < size:
782
+ if (pointer > 0 and
783
+ self._is_valid_star1(tokens[pointer - 1]) and
784
+ self._is_valid_star2(tokens[pointer])):
785
+ # This is a trick to add missing * operators in the expression,
786
+ # `"*" in op_dict` makes sure the precedence level is the same as "*",
787
+ # while `not self._is_op( ... )` makes sure this and the previous
788
+ # expression are not operators.
789
+ if tokens[pointer] == "(":
790
+ # ( has already been processed by now, replace:
791
+ tokens[pointer] = "*"
792
+ tokens[pointer + 1] = tokens[pointer + 1][0]
793
+ else:
794
+ tokens.insert(pointer, "*")
795
+ pointer += 1
796
+ size += 1
797
+ pointer += 1
798
+
799
+ def _parse_after_braces(self, tokens: list, inside_enclosure: bool = False):
800
+ op_dict: dict
801
+ changed: bool = False
802
+ lines: list = []
803
+
804
+ self._util_remove_newlines(lines, tokens, inside_enclosure)
805
+
806
+ for op_type, grouping_strat, op_dict in reversed(self._mathematica_op_precedence):
807
+ if "*" in op_dict:
808
+ self._util_add_missing_asterisks(tokens)
809
+ size: int = len(tokens)
810
+ pointer: int = 0
811
+ while pointer < size:
812
+ token = tokens[pointer]
813
+ if isinstance(token, str) and token in op_dict:
814
+ op_name: str | Callable = op_dict[token]
815
+ node: list
816
+ first_index: int
817
+ if isinstance(op_name, str):
818
+ node = [op_name]
819
+ first_index = 1
820
+ else:
821
+ node = []
822
+ first_index = 0
823
+ if token in ("+", "-") and op_type == self.PREFIX and pointer > 0 and not self._is_op(tokens[pointer - 1]):
824
+ # Make sure that PREFIX + - don't match expressions like a + b or a - b,
825
+ # the INFIX + - are supposed to match that expression:
826
+ pointer += 1
827
+ continue
828
+ if op_type == self.INFIX:
829
+ if pointer == 0 or pointer == size - 1 or self._is_op(tokens[pointer - 1]) or self._is_op(tokens[pointer + 1]):
830
+ pointer += 1
831
+ continue
832
+ changed = True
833
+ tokens[pointer] = node
834
+ if op_type == self.INFIX:
835
+ arg1 = tokens.pop(pointer-1)
836
+ arg2 = tokens.pop(pointer)
837
+ if token == "/":
838
+ arg2 = self._get_inv(arg2)
839
+ elif token == "-":
840
+ arg2 = self._get_neg(arg2)
841
+ pointer -= 1
842
+ size -= 2
843
+ node.append(arg1)
844
+ node_p = node
845
+ if grouping_strat == self.FLAT:
846
+ while pointer + 2 < size and self._check_op_compatible(tokens[pointer+1], token):
847
+ node_p.append(arg2)
848
+ other_op = tokens.pop(pointer+1)
849
+ arg2 = tokens.pop(pointer+1)
850
+ if other_op == "/":
851
+ arg2 = self._get_inv(arg2)
852
+ elif other_op == "-":
853
+ arg2 = self._get_neg(arg2)
854
+ size -= 2
855
+ node_p.append(arg2)
856
+ elif grouping_strat == self.RIGHT:
857
+ while pointer + 2 < size and tokens[pointer+1] == token:
858
+ node_p.append([op_name, arg2])
859
+ node_p = node_p[-1]
860
+ tokens.pop(pointer+1)
861
+ arg2 = tokens.pop(pointer+1)
862
+ size -= 2
863
+ node_p.append(arg2)
864
+ elif grouping_strat == self.LEFT:
865
+ while pointer + 1 < size and tokens[pointer+1] == token:
866
+ if isinstance(op_name, str):
867
+ node_p[first_index] = [op_name, node_p[first_index], arg2]
868
+ else:
869
+ node_p[first_index] = op_name(node_p[first_index], arg2)
870
+ tokens.pop(pointer+1)
871
+ arg2 = tokens.pop(pointer+1)
872
+ size -= 2
873
+ node_p.append(arg2)
874
+ else:
875
+ node.append(arg2)
876
+ elif op_type == self.PREFIX:
877
+ assert grouping_strat is None
878
+ if pointer == size - 1 or self._is_op(tokens[pointer + 1]):
879
+ tokens[pointer] = self._missing_arguments_default[token]()
880
+ else:
881
+ node.append(tokens.pop(pointer+1))
882
+ size -= 1
883
+ elif op_type == self.POSTFIX:
884
+ assert grouping_strat is None
885
+ if pointer == 0 or self._is_op(tokens[pointer - 1]):
886
+ tokens[pointer] = self._missing_arguments_default[token]()
887
+ else:
888
+ node.append(tokens.pop(pointer-1))
889
+ pointer -= 1
890
+ size -= 1
891
+ if isinstance(op_name, Callable): # type: ignore
892
+ op_call: Callable = typing.cast(Callable, op_name)
893
+ new_node = op_call(*node)
894
+ node.clear()
895
+ if isinstance(new_node, list):
896
+ node.extend(new_node)
897
+ else:
898
+ tokens[pointer] = new_node
899
+ pointer += 1
900
+ if len(tokens) > 1 or (len(lines) == 0 and len(tokens) == 0):
901
+ if changed:
902
+ # Trick to deal with cases in which an operator with lower
903
+ # precedence should be transformed before an operator of higher
904
+ # precedence. Such as in the case of `#&[x]` (that is
905
+ # equivalent to `Lambda(d_, d_)(x)` in SymPy). In this case the
906
+ # operator `&` has lower precedence than `[`, but needs to be
907
+ # evaluated first because otherwise `# (&[x])` is not a valid
908
+ # expression:
909
+ return self._parse_after_braces(tokens, inside_enclosure)
910
+ raise SyntaxError("unable to create a single AST for the expression")
911
+ if len(lines) > 0:
912
+ if tokens[0] and tokens[0][0] == "CompoundExpression":
913
+ tokens = tokens[0][1:]
914
+ compound_expression = ["CompoundExpression", *lines, *tokens]
915
+ return compound_expression
916
+ return tokens[0]
917
+
918
+ def _check_op_compatible(self, op1: str, op2: str):
919
+ if op1 == op2:
920
+ return True
921
+ muldiv = {"*", "/"}
922
+ addsub = {"+", "-"}
923
+ if op1 in muldiv and op2 in muldiv:
924
+ return True
925
+ if op1 in addsub and op2 in addsub:
926
+ return True
927
+ return False
928
+
929
+ def _from_fullform_to_fullformlist(self, wmexpr: str):
930
+ """
931
+ Parses FullForm[Downvalues[]] generated by Mathematica
932
+ """
933
+ out: list = []
934
+ stack = [out]
935
+ generator = re.finditer(r'[\[\],]', wmexpr)
936
+ last_pos = 0
937
+ for match in generator:
938
+ if match is None:
939
+ break
940
+ position = match.start()
941
+ last_expr = wmexpr[last_pos:position].replace(',', '').replace(']', '').replace('[', '').strip()
942
+
943
+ if match.group() == ',':
944
+ if last_expr != '':
945
+ stack[-1].append(last_expr)
946
+ elif match.group() == ']':
947
+ if last_expr != '':
948
+ stack[-1].append(last_expr)
949
+ stack.pop()
950
+ elif match.group() == '[':
951
+ stack[-1].append([last_expr])
952
+ stack.append(stack[-1][-1])
953
+ last_pos = match.end()
954
+ return out[0]
955
+
956
+ def _from_fullformlist_to_fullformsympy(self, pylist: list):
957
+ from sympy import Function, Symbol
958
+
959
+ def converter(expr):
960
+ if isinstance(expr, list):
961
+ if len(expr) > 0:
962
+ head = expr[0]
963
+ args = [converter(arg) for arg in expr[1:]]
964
+ return Function(head)(*args)
965
+ else:
966
+ raise ValueError("Empty list of expressions")
967
+ elif isinstance(expr, str):
968
+ return Symbol(expr)
969
+ else:
970
+ return _sympify(expr)
971
+
972
+ return converter(pylist)
973
+
974
+ _node_conversions = {
975
+ "Times": Mul,
976
+ "Plus": Add,
977
+ "Power": Pow,
978
+ "Log": lambda *a: log(*reversed(a)),
979
+ "Log2": lambda x: log(x, 2),
980
+ "Log10": lambda x: log(x, 10),
981
+ "Exp": exp,
982
+ "Sqrt": sqrt,
983
+
984
+ "Sin": sin,
985
+ "Cos": cos,
986
+ "Tan": tan,
987
+ "Cot": cot,
988
+ "Sec": sec,
989
+ "Csc": csc,
990
+
991
+ "ArcSin": asin,
992
+ "ArcCos": acos,
993
+ "ArcTan": lambda *a: atan2(*reversed(a)) if len(a) == 2 else atan(*a),
994
+ "ArcCot": acot,
995
+ "ArcSec": asec,
996
+ "ArcCsc": acsc,
997
+
998
+ "Sinh": sinh,
999
+ "Cosh": cosh,
1000
+ "Tanh": tanh,
1001
+ "Coth": coth,
1002
+ "Sech": sech,
1003
+ "Csch": csch,
1004
+
1005
+ "ArcSinh": asinh,
1006
+ "ArcCosh": acosh,
1007
+ "ArcTanh": atanh,
1008
+ "ArcCoth": acoth,
1009
+ "ArcSech": asech,
1010
+ "ArcCsch": acsch,
1011
+
1012
+ "Expand": expand,
1013
+ "Im": im,
1014
+ "Re": sympy.re,
1015
+ "Flatten": flatten,
1016
+ "Polylog": polylog,
1017
+ "Cancel": cancel,
1018
+ # Gamma=gamma,
1019
+ "TrigExpand": expand_trig,
1020
+ "Sign": sign,
1021
+ "Simplify": simplify,
1022
+ "Defer": UnevaluatedExpr,
1023
+ "Identity": S,
1024
+ # Sum=Sum_doit,
1025
+ # Module=With,
1026
+ # Block=With,
1027
+ "Null": lambda *a: S.Zero,
1028
+ "Mod": Mod,
1029
+ "Max": Max,
1030
+ "Min": Min,
1031
+ "Pochhammer": rf,
1032
+ "ExpIntegralEi": Ei,
1033
+ "SinIntegral": Si,
1034
+ "CosIntegral": Ci,
1035
+ "AiryAi": airyai,
1036
+ "AiryAiPrime": airyaiprime,
1037
+ "AiryBi": airybi,
1038
+ "AiryBiPrime": airybiprime,
1039
+ "LogIntegral": li,
1040
+ "PrimePi": primepi,
1041
+ "Prime": prime,
1042
+ "PrimeQ": isprime,
1043
+
1044
+ "List": Tuple,
1045
+ "Greater": StrictGreaterThan,
1046
+ "GreaterEqual": GreaterThan,
1047
+ "Less": StrictLessThan,
1048
+ "LessEqual": LessThan,
1049
+ "Equal": Equality,
1050
+ "Or": Or,
1051
+ "And": And,
1052
+
1053
+ "Function": _parse_Function,
1054
+ }
1055
+
1056
+ _atom_conversions = {
1057
+ "I": I,
1058
+ "Pi": pi,
1059
+ }
1060
+
1061
+ def _from_fullformlist_to_sympy(self, full_form_list):
1062
+
1063
+ def recurse(expr):
1064
+ if isinstance(expr, list):
1065
+ if isinstance(expr[0], list):
1066
+ head = recurse(expr[0])
1067
+ else:
1068
+ head = self._node_conversions.get(expr[0], Function(expr[0]))
1069
+ return head(*[recurse(arg) for arg in expr[1:]])
1070
+ else:
1071
+ return self._atom_conversions.get(expr, sympify(expr))
1072
+
1073
+ return recurse(full_form_list)
1074
+
1075
+ def _from_fullformsympy_to_sympy(self, mform):
1076
+
1077
+ expr = mform
1078
+ for mma_form, sympy_node in self._node_conversions.items():
1079
+ expr = expr.replace(Function(mma_form), sympy_node)
1080
+ return expr
llmeval-env/lib/python3.10/site-packages/sympy/parsing/maxima.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from sympy.concrete.products import product
3
+ from sympy.concrete.summations import Sum
4
+ from sympy.core.sympify import sympify
5
+ from sympy.functions.elementary.trigonometric import (cos, sin)
6
+
7
+
8
+ class MaximaHelpers:
9
+ def maxima_expand(expr):
10
+ return expr.expand()
11
+
12
+ def maxima_float(expr):
13
+ return expr.evalf()
14
+
15
+ def maxima_trigexpand(expr):
16
+ return expr.expand(trig=True)
17
+
18
+ def maxima_sum(a1, a2, a3, a4):
19
+ return Sum(a1, (a2, a3, a4)).doit()
20
+
21
+ def maxima_product(a1, a2, a3, a4):
22
+ return product(a1, (a2, a3, a4))
23
+
24
+ def maxima_csc(expr):
25
+ return 1/sin(expr)
26
+
27
+ def maxima_sec(expr):
28
+ return 1/cos(expr)
29
+
30
+ sub_dict = {
31
+ 'pi': re.compile(r'%pi'),
32
+ 'E': re.compile(r'%e'),
33
+ 'I': re.compile(r'%i'),
34
+ '**': re.compile(r'\^'),
35
+ 'oo': re.compile(r'\binf\b'),
36
+ '-oo': re.compile(r'\bminf\b'),
37
+ "'-'": re.compile(r'\bminus\b'),
38
+ 'maxima_expand': re.compile(r'\bexpand\b'),
39
+ 'maxima_float': re.compile(r'\bfloat\b'),
40
+ 'maxima_trigexpand': re.compile(r'\btrigexpand'),
41
+ 'maxima_sum': re.compile(r'\bsum\b'),
42
+ 'maxima_product': re.compile(r'\bproduct\b'),
43
+ 'cancel': re.compile(r'\bratsimp\b'),
44
+ 'maxima_csc': re.compile(r'\bcsc\b'),
45
+ 'maxima_sec': re.compile(r'\bsec\b')
46
+ }
47
+
48
+ var_name = re.compile(r'^\s*(\w+)\s*:')
49
+
50
+
51
+ def parse_maxima(str, globals=None, name_dict={}):
52
+ str = str.strip()
53
+ str = str.rstrip('; ')
54
+
55
+ for k, v in sub_dict.items():
56
+ str = v.sub(k, str)
57
+
58
+ assign_var = None
59
+ var_match = var_name.search(str)
60
+ if var_match:
61
+ assign_var = var_match.group(1)
62
+ str = str[var_match.end():].strip()
63
+
64
+ dct = MaximaHelpers.__dict__.copy()
65
+ dct.update(name_dict)
66
+ obj = sympify(str, locals=dct)
67
+
68
+ if assign_var and globals:
69
+ globals[assign_var] = obj
70
+
71
+ return obj
llmeval-env/lib/python3.10/site-packages/sympy/parsing/sym_expr.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.printing import pycode, ccode, fcode
2
+ from sympy.external import import_module
3
+ from sympy.utilities.decorator import doctest_depends_on
4
+
5
+ lfortran = import_module('lfortran')
6
+ cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
7
+
8
+ if lfortran:
9
+ from sympy.parsing.fortran.fortran_parser import src_to_sympy
10
+ if cin:
11
+ from sympy.parsing.c.c_parser import parse_c
12
+
13
+ @doctest_depends_on(modules=['lfortran', 'clang.cindex'])
14
+ class SymPyExpression: # type: ignore
15
+ """Class to store and handle SymPy expressions
16
+
17
+ This class will hold SymPy Expressions and handle the API for the
18
+ conversion to and from different languages.
19
+
20
+ It works with the C and the Fortran Parser to generate SymPy expressions
21
+ which are stored here and which can be converted to multiple language's
22
+ source code.
23
+
24
+ Notes
25
+ =====
26
+
27
+ The module and its API are currently under development and experimental
28
+ and can be changed during development.
29
+
30
+ The Fortran parser does not support numeric assignments, so all the
31
+ variables have been Initialized to zero.
32
+
33
+ The module also depends on external dependencies:
34
+
35
+ - LFortran which is required to use the Fortran parser
36
+ - Clang which is required for the C parser
37
+
38
+ Examples
39
+ ========
40
+
41
+ Example of parsing C code:
42
+
43
+ >>> from sympy.parsing.sym_expr import SymPyExpression
44
+ >>> src = '''
45
+ ... int a,b;
46
+ ... float c = 2, d =4;
47
+ ... '''
48
+ >>> a = SymPyExpression(src, 'c')
49
+ >>> a.return_expr()
50
+ [Declaration(Variable(a, type=intc)),
51
+ Declaration(Variable(b, type=intc)),
52
+ Declaration(Variable(c, type=float32, value=2.0)),
53
+ Declaration(Variable(d, type=float32, value=4.0))]
54
+
55
+ An example of variable definition:
56
+
57
+ >>> from sympy.parsing.sym_expr import SymPyExpression
58
+ >>> src2 = '''
59
+ ... integer :: a, b, c, d
60
+ ... real :: p, q, r, s
61
+ ... '''
62
+ >>> p = SymPyExpression()
63
+ >>> p.convert_to_expr(src2, 'f')
64
+ >>> p.convert_to_c()
65
+ ['int a = 0', 'int b = 0', 'int c = 0', 'int d = 0', 'double p = 0.0', 'double q = 0.0', 'double r = 0.0', 'double s = 0.0']
66
+
67
+ An example of Assignment:
68
+
69
+ >>> from sympy.parsing.sym_expr import SymPyExpression
70
+ >>> src3 = '''
71
+ ... integer :: a, b, c, d, e
72
+ ... d = a + b - c
73
+ ... e = b * d + c * e / a
74
+ ... '''
75
+ >>> p = SymPyExpression(src3, 'f')
76
+ >>> p.convert_to_python()
77
+ ['a = 0', 'b = 0', 'c = 0', 'd = 0', 'e = 0', 'd = a + b - c', 'e = b*d + c*e/a']
78
+
79
+ An example of function definition:
80
+
81
+ >>> from sympy.parsing.sym_expr import SymPyExpression
82
+ >>> src = '''
83
+ ... integer function f(a,b)
84
+ ... integer, intent(in) :: a, b
85
+ ... integer :: r
86
+ ... end function
87
+ ... '''
88
+ >>> a = SymPyExpression(src, 'f')
89
+ >>> a.convert_to_python()
90
+ ['def f(a, b):\\n f = 0\\n r = 0\\n return f']
91
+
92
+ """
93
+
94
+ def __init__(self, source_code = None, mode = None):
95
+ """Constructor for SymPyExpression class"""
96
+ super().__init__()
97
+ if not(mode or source_code):
98
+ self._expr = []
99
+ elif mode:
100
+ if source_code:
101
+ if mode.lower() == 'f':
102
+ if lfortran:
103
+ self._expr = src_to_sympy(source_code)
104
+ else:
105
+ raise ImportError("LFortran is not installed, cannot parse Fortran code")
106
+ elif mode.lower() == 'c':
107
+ if cin:
108
+ self._expr = parse_c(source_code)
109
+ else:
110
+ raise ImportError("Clang is not installed, cannot parse C code")
111
+ else:
112
+ raise NotImplementedError(
113
+ 'Parser for specified language is not implemented'
114
+ )
115
+ else:
116
+ raise ValueError('Source code not present')
117
+ else:
118
+ raise ValueError('Please specify a mode for conversion')
119
+
120
+ def convert_to_expr(self, src_code, mode):
121
+ """Converts the given source code to SymPy Expressions
122
+
123
+ Attributes
124
+ ==========
125
+
126
+ src_code : String
127
+ the source code or filename of the source code that is to be
128
+ converted
129
+
130
+ mode: String
131
+ the mode to determine which parser is to be used according to
132
+ the language of the source code
133
+ f or F for Fortran
134
+ c or C for C/C++
135
+
136
+ Examples
137
+ ========
138
+
139
+ >>> from sympy.parsing.sym_expr import SymPyExpression
140
+ >>> src3 = '''
141
+ ... integer function f(a,b) result(r)
142
+ ... integer, intent(in) :: a, b
143
+ ... integer :: x
144
+ ... r = a + b -x
145
+ ... end function
146
+ ... '''
147
+ >>> p = SymPyExpression()
148
+ >>> p.convert_to_expr(src3, 'f')
149
+ >>> p.return_expr()
150
+ [FunctionDefinition(integer, name=f, parameters=(Variable(a), Variable(b)), body=CodeBlock(
151
+ Declaration(Variable(r, type=integer, value=0)),
152
+ Declaration(Variable(x, type=integer, value=0)),
153
+ Assignment(Variable(r), a + b - x),
154
+ Return(Variable(r))
155
+ ))]
156
+
157
+
158
+
159
+
160
+ """
161
+ if mode.lower() == 'f':
162
+ if lfortran:
163
+ self._expr = src_to_sympy(src_code)
164
+ else:
165
+ raise ImportError("LFortran is not installed, cannot parse Fortran code")
166
+ elif mode.lower() == 'c':
167
+ if cin:
168
+ self._expr = parse_c(src_code)
169
+ else:
170
+ raise ImportError("Clang is not installed, cannot parse C code")
171
+ else:
172
+ raise NotImplementedError(
173
+ "Parser for specified language has not been implemented"
174
+ )
175
+
176
+ def convert_to_python(self):
177
+ """Returns a list with Python code for the SymPy expressions
178
+
179
+ Examples
180
+ ========
181
+
182
+ >>> from sympy.parsing.sym_expr import SymPyExpression
183
+ >>> src2 = '''
184
+ ... integer :: a, b, c, d
185
+ ... real :: p, q, r, s
186
+ ... c = a/b
187
+ ... d = c/a
188
+ ... s = p/q
189
+ ... r = q/p
190
+ ... '''
191
+ >>> p = SymPyExpression(src2, 'f')
192
+ >>> p.convert_to_python()
193
+ ['a = 0', 'b = 0', 'c = 0', 'd = 0', 'p = 0.0', 'q = 0.0', 'r = 0.0', 's = 0.0', 'c = a/b', 'd = c/a', 's = p/q', 'r = q/p']
194
+
195
+ """
196
+ self._pycode = []
197
+ for iter in self._expr:
198
+ self._pycode.append(pycode(iter))
199
+ return self._pycode
200
+
201
+ def convert_to_c(self):
202
+ """Returns a list with the c source code for the SymPy expressions
203
+
204
+
205
+ Examples
206
+ ========
207
+
208
+ >>> from sympy.parsing.sym_expr import SymPyExpression
209
+ >>> src2 = '''
210
+ ... integer :: a, b, c, d
211
+ ... real :: p, q, r, s
212
+ ... c = a/b
213
+ ... d = c/a
214
+ ... s = p/q
215
+ ... r = q/p
216
+ ... '''
217
+ >>> p = SymPyExpression()
218
+ >>> p.convert_to_expr(src2, 'f')
219
+ >>> p.convert_to_c()
220
+ ['int a = 0', 'int b = 0', 'int c = 0', 'int d = 0', 'double p = 0.0', 'double q = 0.0', 'double r = 0.0', 'double s = 0.0', 'c = a/b;', 'd = c/a;', 's = p/q;', 'r = q/p;']
221
+
222
+ """
223
+ self._ccode = []
224
+ for iter in self._expr:
225
+ self._ccode.append(ccode(iter))
226
+ return self._ccode
227
+
228
+ def convert_to_fortran(self):
229
+ """Returns a list with the fortran source code for the SymPy expressions
230
+
231
+ Examples
232
+ ========
233
+
234
+ >>> from sympy.parsing.sym_expr import SymPyExpression
235
+ >>> src2 = '''
236
+ ... integer :: a, b, c, d
237
+ ... real :: p, q, r, s
238
+ ... c = a/b
239
+ ... d = c/a
240
+ ... s = p/q
241
+ ... r = q/p
242
+ ... '''
243
+ >>> p = SymPyExpression(src2, 'f')
244
+ >>> p.convert_to_fortran()
245
+ [' integer*4 a', ' integer*4 b', ' integer*4 c', ' integer*4 d', ' real*8 p', ' real*8 q', ' real*8 r', ' real*8 s', ' c = a/b', ' d = c/a', ' s = p/q', ' r = q/p']
246
+
247
+ """
248
+ self._fcode = []
249
+ for iter in self._expr:
250
+ self._fcode.append(fcode(iter))
251
+ return self._fcode
252
+
253
+ def return_expr(self):
254
+ """Returns the expression list
255
+
256
+ Examples
257
+ ========
258
+
259
+ >>> from sympy.parsing.sym_expr import SymPyExpression
260
+ >>> src3 = '''
261
+ ... integer function f(a,b)
262
+ ... integer, intent(in) :: a, b
263
+ ... integer :: r
264
+ ... r = a+b
265
+ ... f = r
266
+ ... end function
267
+ ... '''
268
+ >>> p = SymPyExpression()
269
+ >>> p.convert_to_expr(src3, 'f')
270
+ >>> p.return_expr()
271
+ [FunctionDefinition(integer, name=f, parameters=(Variable(a), Variable(b)), body=CodeBlock(
272
+ Declaration(Variable(f, type=integer, value=0)),
273
+ Declaration(Variable(r, type=integer, value=0)),
274
+ Assignment(Variable(f), Variable(r)),
275
+ Return(Variable(f))
276
+ ))]
277
+
278
+ """
279
+ return self._expr
llmeval-env/lib/python3.10/site-packages/sympy/parsing/sympy_parser.py ADDED
@@ -0,0 +1,1264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Transform a string with Python-like source code into SymPy expression. """
2
+
3
+ from tokenize import (generate_tokens, untokenize, TokenError,
4
+ NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN, NEWLINE)
5
+
6
+ from keyword import iskeyword
7
+
8
+ import ast
9
+ import unicodedata
10
+ from io import StringIO
11
+ import builtins
12
+ import types
13
+ from typing import Tuple as tTuple, Dict as tDict, Any, Callable, \
14
+ List, Optional, Union as tUnion
15
+
16
+ from sympy.assumptions.ask import AssumptionKeys
17
+ from sympy.core.basic import Basic
18
+ from sympy.core import Symbol
19
+ from sympy.core.function import Function
20
+ from sympy.utilities.misc import func_name
21
+ from sympy.functions.elementary.miscellaneous import Max, Min
22
+
23
+
24
+ null = ''
25
+
26
+ TOKEN = tTuple[int, str]
27
+ DICT = tDict[str, Any]
28
+ TRANS = Callable[[List[TOKEN], DICT, DICT], List[TOKEN]]
29
+
30
+ def _token_splittable(token_name: str) -> bool:
31
+ """
32
+ Predicate for whether a token name can be split into multiple tokens.
33
+
34
+ A token is splittable if it does not contain an underscore character and
35
+ it is not the name of a Greek letter. This is used to implicitly convert
36
+ expressions like 'xyz' into 'x*y*z'.
37
+ """
38
+ if '_' in token_name:
39
+ return False
40
+ try:
41
+ return not unicodedata.lookup('GREEK SMALL LETTER ' + token_name)
42
+ except KeyError:
43
+ return len(token_name) > 1
44
+
45
+
46
+ def _token_callable(token: TOKEN, local_dict: DICT, global_dict: DICT, nextToken=None):
47
+ """
48
+ Predicate for whether a token name represents a callable function.
49
+
50
+ Essentially wraps ``callable``, but looks up the token name in the
51
+ locals and globals.
52
+ """
53
+ func = local_dict.get(token[1])
54
+ if not func:
55
+ func = global_dict.get(token[1])
56
+ return callable(func) and not isinstance(func, Symbol)
57
+
58
+
59
+ def _add_factorial_tokens(name: str, result: List[TOKEN]) -> List[TOKEN]:
60
+ if result == [] or result[-1][1] == '(':
61
+ raise TokenError()
62
+
63
+ beginning = [(NAME, name), (OP, '(')]
64
+ end = [(OP, ')')]
65
+
66
+ diff = 0
67
+ length = len(result)
68
+
69
+ for index, token in enumerate(result[::-1]):
70
+ toknum, tokval = token
71
+ i = length - index - 1
72
+
73
+ if tokval == ')':
74
+ diff += 1
75
+ elif tokval == '(':
76
+ diff -= 1
77
+
78
+ if diff == 0:
79
+ if i - 1 >= 0 and result[i - 1][0] == NAME:
80
+ return result[:i - 1] + beginning + result[i - 1:] + end
81
+ else:
82
+ return result[:i] + beginning + result[i:] + end
83
+
84
+ return result
85
+
86
+
87
+ class ParenthesisGroup(List[TOKEN]):
88
+ """List of tokens representing an expression in parentheses."""
89
+ pass
90
+
91
+
92
+ class AppliedFunction:
93
+ """
94
+ A group of tokens representing a function and its arguments.
95
+
96
+ `exponent` is for handling the shorthand sin^2, ln^2, etc.
97
+ """
98
+ def __init__(self, function: TOKEN, args: ParenthesisGroup, exponent=None):
99
+ if exponent is None:
100
+ exponent = []
101
+ self.function = function
102
+ self.args = args
103
+ self.exponent = exponent
104
+ self.items = ['function', 'args', 'exponent']
105
+
106
+ def expand(self) -> List[TOKEN]:
107
+ """Return a list of tokens representing the function"""
108
+ return [self.function, *self.args]
109
+
110
+ def __getitem__(self, index):
111
+ return getattr(self, self.items[index])
112
+
113
+ def __repr__(self):
114
+ return "AppliedFunction(%s, %s, %s)" % (self.function, self.args,
115
+ self.exponent)
116
+
117
+
118
+ def _flatten(result: List[tUnion[TOKEN, AppliedFunction]]):
119
+ result2: List[TOKEN] = []
120
+ for tok in result:
121
+ if isinstance(tok, AppliedFunction):
122
+ result2.extend(tok.expand())
123
+ else:
124
+ result2.append(tok)
125
+ return result2
126
+
127
+
128
+ def _group_parentheses(recursor: TRANS):
129
+ def _inner(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
130
+ """Group tokens between parentheses with ParenthesisGroup.
131
+
132
+ Also processes those tokens recursively.
133
+
134
+ """
135
+ result: List[tUnion[TOKEN, ParenthesisGroup]] = []
136
+ stacks: List[ParenthesisGroup] = []
137
+ stacklevel = 0
138
+ for token in tokens:
139
+ if token[0] == OP:
140
+ if token[1] == '(':
141
+ stacks.append(ParenthesisGroup([]))
142
+ stacklevel += 1
143
+ elif token[1] == ')':
144
+ stacks[-1].append(token)
145
+ stack = stacks.pop()
146
+
147
+ if len(stacks) > 0:
148
+ # We don't recurse here since the upper-level stack
149
+ # would reprocess these tokens
150
+ stacks[-1].extend(stack)
151
+ else:
152
+ # Recurse here to handle nested parentheses
153
+ # Strip off the outer parentheses to avoid an infinite loop
154
+ inner = stack[1:-1]
155
+ inner = recursor(inner,
156
+ local_dict,
157
+ global_dict)
158
+ parenGroup = [stack[0]] + inner + [stack[-1]]
159
+ result.append(ParenthesisGroup(parenGroup))
160
+ stacklevel -= 1
161
+ continue
162
+ if stacklevel:
163
+ stacks[-1].append(token)
164
+ else:
165
+ result.append(token)
166
+ if stacklevel:
167
+ raise TokenError("Mismatched parentheses")
168
+ return result
169
+ return _inner
170
+
171
+
172
+ def _apply_functions(tokens: List[tUnion[TOKEN, ParenthesisGroup]], local_dict: DICT, global_dict: DICT):
173
+ """Convert a NAME token + ParenthesisGroup into an AppliedFunction.
174
+
175
+ Note that ParenthesisGroups, if not applied to any function, are
176
+ converted back into lists of tokens.
177
+
178
+ """
179
+ result: List[tUnion[TOKEN, AppliedFunction]] = []
180
+ symbol = None
181
+ for tok in tokens:
182
+ if isinstance(tok, ParenthesisGroup):
183
+ if symbol and _token_callable(symbol, local_dict, global_dict):
184
+ result[-1] = AppliedFunction(symbol, tok)
185
+ symbol = None
186
+ else:
187
+ result.extend(tok)
188
+ elif tok[0] == NAME:
189
+ symbol = tok
190
+ result.append(tok)
191
+ else:
192
+ symbol = None
193
+ result.append(tok)
194
+ return result
195
+
196
+
197
+ def _implicit_multiplication(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT):
198
+ """Implicitly adds '*' tokens.
199
+
200
+ Cases:
201
+
202
+ - Two AppliedFunctions next to each other ("sin(x)cos(x)")
203
+
204
+ - AppliedFunction next to an open parenthesis ("sin x (cos x + 1)")
205
+
206
+ - A close parenthesis next to an AppliedFunction ("(x+2)sin x")\
207
+
208
+ - A close parenthesis next to an open parenthesis ("(x+2)(x+3)")
209
+
210
+ - AppliedFunction next to an implicitly applied function ("sin(x)cos x")
211
+
212
+ """
213
+ result: List[tUnion[TOKEN, AppliedFunction]] = []
214
+ skip = False
215
+ for tok, nextTok in zip(tokens, tokens[1:]):
216
+ result.append(tok)
217
+ if skip:
218
+ skip = False
219
+ continue
220
+ if tok[0] == OP and tok[1] == '.' and nextTok[0] == NAME:
221
+ # Dotted name. Do not do implicit multiplication
222
+ skip = True
223
+ continue
224
+ if isinstance(tok, AppliedFunction):
225
+ if isinstance(nextTok, AppliedFunction):
226
+ result.append((OP, '*'))
227
+ elif nextTok == (OP, '('):
228
+ # Applied function followed by an open parenthesis
229
+ if tok.function[1] == "Function":
230
+ tok.function = (tok.function[0], 'Symbol')
231
+ result.append((OP, '*'))
232
+ elif nextTok[0] == NAME:
233
+ # Applied function followed by implicitly applied function
234
+ result.append((OP, '*'))
235
+ else:
236
+ if tok == (OP, ')'):
237
+ if isinstance(nextTok, AppliedFunction):
238
+ # Close parenthesis followed by an applied function
239
+ result.append((OP, '*'))
240
+ elif nextTok[0] == NAME:
241
+ # Close parenthesis followed by an implicitly applied function
242
+ result.append((OP, '*'))
243
+ elif nextTok == (OP, '('):
244
+ # Close parenthesis followed by an open parenthesis
245
+ result.append((OP, '*'))
246
+ elif tok[0] == NAME and not _token_callable(tok, local_dict, global_dict):
247
+ if isinstance(nextTok, AppliedFunction) or \
248
+ (nextTok[0] == NAME and _token_callable(nextTok, local_dict, global_dict)):
249
+ # Constant followed by (implicitly applied) function
250
+ result.append((OP, '*'))
251
+ elif nextTok == (OP, '('):
252
+ # Constant followed by parenthesis
253
+ result.append((OP, '*'))
254
+ elif nextTok[0] == NAME:
255
+ # Constant followed by constant
256
+ result.append((OP, '*'))
257
+ if tokens:
258
+ result.append(tokens[-1])
259
+ return result
260
+
261
+
262
+ def _implicit_application(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT):
263
+ """Adds parentheses as needed after functions."""
264
+ result: List[tUnion[TOKEN, AppliedFunction]] = []
265
+ appendParen = 0 # number of closing parentheses to add
266
+ skip = 0 # number of tokens to delay before adding a ')' (to
267
+ # capture **, ^, etc.)
268
+ exponentSkip = False # skipping tokens before inserting parentheses to
269
+ # work with function exponentiation
270
+ for tok, nextTok in zip(tokens, tokens[1:]):
271
+ result.append(tok)
272
+ if (tok[0] == NAME and nextTok[0] not in [OP, ENDMARKER, NEWLINE]):
273
+ if _token_callable(tok, local_dict, global_dict, nextTok): # type: ignore
274
+ result.append((OP, '('))
275
+ appendParen += 1
276
+ # name followed by exponent - function exponentiation
277
+ elif (tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**'):
278
+ if _token_callable(tok, local_dict, global_dict): # type: ignore
279
+ exponentSkip = True
280
+ elif exponentSkip:
281
+ # if the last token added was an applied function (i.e. the
282
+ # power of the function exponent) OR a multiplication (as
283
+ # implicit multiplication would have added an extraneous
284
+ # multiplication)
285
+ if (isinstance(tok, AppliedFunction)
286
+ or (tok[0] == OP and tok[1] == '*')):
287
+ # don't add anything if the next token is a multiplication
288
+ # or if there's already a parenthesis (if parenthesis, still
289
+ # stop skipping tokens)
290
+ if not (nextTok[0] == OP and nextTok[1] == '*'):
291
+ if not(nextTok[0] == OP and nextTok[1] == '('):
292
+ result.append((OP, '('))
293
+ appendParen += 1
294
+ exponentSkip = False
295
+ elif appendParen:
296
+ if nextTok[0] == OP and nextTok[1] in ('^', '**', '*'):
297
+ skip = 1
298
+ continue
299
+ if skip:
300
+ skip -= 1
301
+ continue
302
+ result.append((OP, ')'))
303
+ appendParen -= 1
304
+
305
+ if tokens:
306
+ result.append(tokens[-1])
307
+
308
+ if appendParen:
309
+ result.extend([(OP, ')')] * appendParen)
310
+ return result
311
+
312
+
313
+ def function_exponentiation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
314
+ """Allows functions to be exponentiated, e.g. ``cos**2(x)``.
315
+
316
+ Examples
317
+ ========
318
+
319
+ >>> from sympy.parsing.sympy_parser import (parse_expr,
320
+ ... standard_transformations, function_exponentiation)
321
+ >>> transformations = standard_transformations + (function_exponentiation,)
322
+ >>> parse_expr('sin**4(x)', transformations=transformations)
323
+ sin(x)**4
324
+ """
325
+ result: List[TOKEN] = []
326
+ exponent: List[TOKEN] = []
327
+ consuming_exponent = False
328
+ level = 0
329
+ for tok, nextTok in zip(tokens, tokens[1:]):
330
+ if tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**':
331
+ if _token_callable(tok, local_dict, global_dict):
332
+ consuming_exponent = True
333
+ elif consuming_exponent:
334
+ if tok[0] == NAME and tok[1] == 'Function':
335
+ tok = (NAME, 'Symbol')
336
+ exponent.append(tok)
337
+
338
+ # only want to stop after hitting )
339
+ if tok[0] == nextTok[0] == OP and tok[1] == ')' and nextTok[1] == '(':
340
+ consuming_exponent = False
341
+ # if implicit multiplication was used, we may have )*( instead
342
+ if tok[0] == nextTok[0] == OP and tok[1] == '*' and nextTok[1] == '(':
343
+ consuming_exponent = False
344
+ del exponent[-1]
345
+ continue
346
+ elif exponent and not consuming_exponent:
347
+ if tok[0] == OP:
348
+ if tok[1] == '(':
349
+ level += 1
350
+ elif tok[1] == ')':
351
+ level -= 1
352
+ if level == 0:
353
+ result.append(tok)
354
+ result.extend(exponent)
355
+ exponent = []
356
+ continue
357
+ result.append(tok)
358
+ if tokens:
359
+ result.append(tokens[-1])
360
+ if exponent:
361
+ result.extend(exponent)
362
+ return result
363
+
364
+
365
+ def split_symbols_custom(predicate: Callable[[str], bool]):
366
+ """Creates a transformation that splits symbol names.
367
+
368
+ ``predicate`` should return True if the symbol name is to be split.
369
+
370
+ For instance, to retain the default behavior but avoid splitting certain
371
+ symbol names, a predicate like this would work:
372
+
373
+
374
+ >>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable,
375
+ ... standard_transformations, implicit_multiplication,
376
+ ... split_symbols_custom)
377
+ >>> def can_split(symbol):
378
+ ... if symbol not in ('list', 'of', 'unsplittable', 'names'):
379
+ ... return _token_splittable(symbol)
380
+ ... return False
381
+ ...
382
+ >>> transformation = split_symbols_custom(can_split)
383
+ >>> parse_expr('unsplittable', transformations=standard_transformations +
384
+ ... (transformation, implicit_multiplication))
385
+ unsplittable
386
+ """
387
+ def _split_symbols(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
388
+ result: List[TOKEN] = []
389
+ split = False
390
+ split_previous=False
391
+
392
+ for tok in tokens:
393
+ if split_previous:
394
+ # throw out closing parenthesis of Symbol that was split
395
+ split_previous=False
396
+ continue
397
+ split_previous=False
398
+
399
+ if tok[0] == NAME and tok[1] in ['Symbol', 'Function']:
400
+ split = True
401
+
402
+ elif split and tok[0] == NAME:
403
+ symbol = tok[1][1:-1]
404
+
405
+ if predicate(symbol):
406
+ tok_type = result[-2][1] # Symbol or Function
407
+ del result[-2:] # Get rid of the call to Symbol
408
+
409
+ i = 0
410
+ while i < len(symbol):
411
+ char = symbol[i]
412
+ if char in local_dict or char in global_dict:
413
+ result.append((NAME, "%s" % char))
414
+ elif char.isdigit():
415
+ chars = [char]
416
+ for i in range(i + 1, len(symbol)):
417
+ if not symbol[i].isdigit():
418
+ i -= 1
419
+ break
420
+ chars.append(symbol[i])
421
+ char = ''.join(chars)
422
+ result.extend([(NAME, 'Number'), (OP, '('),
423
+ (NAME, "'%s'" % char), (OP, ')')])
424
+ else:
425
+ use = tok_type if i == len(symbol) else 'Symbol'
426
+ result.extend([(NAME, use), (OP, '('),
427
+ (NAME, "'%s'" % char), (OP, ')')])
428
+ i += 1
429
+
430
+ # Set split_previous=True so will skip
431
+ # the closing parenthesis of the original Symbol
432
+ split = False
433
+ split_previous = True
434
+ continue
435
+
436
+ else:
437
+ split = False
438
+
439
+ result.append(tok)
440
+
441
+ return result
442
+
443
+ return _split_symbols
444
+
445
+
446
+ #: Splits symbol names for implicit multiplication.
447
+ #:
448
+ #: Intended to let expressions like ``xyz`` be parsed as ``x*y*z``. Does not
449
+ #: split Greek character names, so ``theta`` will *not* become
450
+ #: ``t*h*e*t*a``. Generally this should be used with
451
+ #: ``implicit_multiplication``.
452
+ split_symbols = split_symbols_custom(_token_splittable)
453
+
454
+
455
+ def implicit_multiplication(tokens: List[TOKEN], local_dict: DICT,
456
+ global_dict: DICT) -> List[TOKEN]:
457
+ """Makes the multiplication operator optional in most cases.
458
+
459
+ Use this before :func:`implicit_application`, otherwise expressions like
460
+ ``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``.
461
+
462
+ Examples
463
+ ========
464
+
465
+ >>> from sympy.parsing.sympy_parser import (parse_expr,
466
+ ... standard_transformations, implicit_multiplication)
467
+ >>> transformations = standard_transformations + (implicit_multiplication,)
468
+ >>> parse_expr('3 x y', transformations=transformations)
469
+ 3*x*y
470
+ """
471
+ # These are interdependent steps, so we don't expose them separately
472
+ res1 = _group_parentheses(implicit_multiplication)(tokens, local_dict, global_dict)
473
+ res2 = _apply_functions(res1, local_dict, global_dict)
474
+ res3 = _implicit_multiplication(res2, local_dict, global_dict)
475
+ result = _flatten(res3)
476
+ return result
477
+
478
+
479
+ def implicit_application(tokens: List[TOKEN], local_dict: DICT,
480
+ global_dict: DICT) -> List[TOKEN]:
481
+ """Makes parentheses optional in some cases for function calls.
482
+
483
+ Use this after :func:`implicit_multiplication`, otherwise expressions
484
+ like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than
485
+ ``sin(2*x)``.
486
+
487
+ Examples
488
+ ========
489
+
490
+ >>> from sympy.parsing.sympy_parser import (parse_expr,
491
+ ... standard_transformations, implicit_application)
492
+ >>> transformations = standard_transformations + (implicit_application,)
493
+ >>> parse_expr('cot z + csc z', transformations=transformations)
494
+ cot(z) + csc(z)
495
+ """
496
+ res1 = _group_parentheses(implicit_application)(tokens, local_dict, global_dict)
497
+ res2 = _apply_functions(res1, local_dict, global_dict)
498
+ res3 = _implicit_application(res2, local_dict, global_dict)
499
+ result = _flatten(res3)
500
+ return result
501
+
502
+
503
+ def implicit_multiplication_application(result: List[TOKEN], local_dict: DICT,
504
+ global_dict: DICT) -> List[TOKEN]:
505
+ """Allows a slightly relaxed syntax.
506
+
507
+ - Parentheses for single-argument method calls are optional.
508
+
509
+ - Multiplication is implicit.
510
+
511
+ - Symbol names can be split (i.e. spaces are not needed between
512
+ symbols).
513
+
514
+ - Functions can be exponentiated.
515
+
516
+ Examples
517
+ ========
518
+
519
+ >>> from sympy.parsing.sympy_parser import (parse_expr,
520
+ ... standard_transformations, implicit_multiplication_application)
521
+ >>> parse_expr("10sin**2 x**2 + 3xyz + tan theta",
522
+ ... transformations=(standard_transformations +
523
+ ... (implicit_multiplication_application,)))
524
+ 3*x*y*z + 10*sin(x**2)**2 + tan(theta)
525
+
526
+ """
527
+ for step in (split_symbols, implicit_multiplication,
528
+ implicit_application, function_exponentiation):
529
+ result = step(result, local_dict, global_dict)
530
+
531
+ return result
532
+
533
+
534
+ def auto_symbol(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
535
+ """Inserts calls to ``Symbol``/``Function`` for undefined variables."""
536
+ result: List[TOKEN] = []
537
+ prevTok = (-1, '')
538
+
539
+ tokens.append((-1, '')) # so zip traverses all tokens
540
+ for tok, nextTok in zip(tokens, tokens[1:]):
541
+ tokNum, tokVal = tok
542
+ nextTokNum, nextTokVal = nextTok
543
+ if tokNum == NAME:
544
+ name = tokVal
545
+
546
+ if (name in ['True', 'False', 'None']
547
+ or iskeyword(name)
548
+ # Don't convert attribute access
549
+ or (prevTok[0] == OP and prevTok[1] == '.')
550
+ # Don't convert keyword arguments
551
+ or (prevTok[0] == OP and prevTok[1] in ('(', ',')
552
+ and nextTokNum == OP and nextTokVal == '=')
553
+ # the name has already been defined
554
+ or name in local_dict and local_dict[name] is not null):
555
+ result.append((NAME, name))
556
+ continue
557
+ elif name in local_dict:
558
+ local_dict.setdefault(null, set()).add(name)
559
+ if nextTokVal == '(':
560
+ local_dict[name] = Function(name)
561
+ else:
562
+ local_dict[name] = Symbol(name)
563
+ result.append((NAME, name))
564
+ continue
565
+ elif name in global_dict:
566
+ obj = global_dict[name]
567
+ if isinstance(obj, (AssumptionKeys, Basic, type)) or callable(obj):
568
+ result.append((NAME, name))
569
+ continue
570
+
571
+ result.extend([
572
+ (NAME, 'Symbol' if nextTokVal != '(' else 'Function'),
573
+ (OP, '('),
574
+ (NAME, repr(str(name))),
575
+ (OP, ')'),
576
+ ])
577
+ else:
578
+ result.append((tokNum, tokVal))
579
+
580
+ prevTok = (tokNum, tokVal)
581
+
582
+ return result
583
+
584
+
585
+ def lambda_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
586
+ """Substitutes "lambda" with its SymPy equivalent Lambda().
587
+ However, the conversion does not take place if only "lambda"
588
+ is passed because that is a syntax error.
589
+
590
+ """
591
+ result: List[TOKEN] = []
592
+ flag = False
593
+ toknum, tokval = tokens[0]
594
+ tokLen = len(tokens)
595
+
596
+ if toknum == NAME and tokval == 'lambda':
597
+ if tokLen == 2 or tokLen == 3 and tokens[1][0] == NEWLINE:
598
+ # In Python 3.6.7+, inputs without a newline get NEWLINE added to
599
+ # the tokens
600
+ result.extend(tokens)
601
+ elif tokLen > 2:
602
+ result.extend([
603
+ (NAME, 'Lambda'),
604
+ (OP, '('),
605
+ (OP, '('),
606
+ (OP, ')'),
607
+ (OP, ')'),
608
+ ])
609
+ for tokNum, tokVal in tokens[1:]:
610
+ if tokNum == OP and tokVal == ':':
611
+ tokVal = ','
612
+ flag = True
613
+ if not flag and tokNum == OP and tokVal in ('*', '**'):
614
+ raise TokenError("Starred arguments in lambda not supported")
615
+ if flag:
616
+ result.insert(-1, (tokNum, tokVal))
617
+ else:
618
+ result.insert(-2, (tokNum, tokVal))
619
+ else:
620
+ result.extend(tokens)
621
+
622
+ return result
623
+
624
+
625
+ def factorial_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
626
+ """Allows standard notation for factorial."""
627
+ result: List[TOKEN] = []
628
+ nfactorial = 0
629
+ for toknum, tokval in tokens:
630
+ if toknum == ERRORTOKEN:
631
+ op = tokval
632
+ if op == '!':
633
+ nfactorial += 1
634
+ else:
635
+ nfactorial = 0
636
+ result.append((OP, op))
637
+ else:
638
+ if nfactorial == 1:
639
+ result = _add_factorial_tokens('factorial', result)
640
+ elif nfactorial == 2:
641
+ result = _add_factorial_tokens('factorial2', result)
642
+ elif nfactorial > 2:
643
+ raise TokenError
644
+ nfactorial = 0
645
+ result.append((toknum, tokval))
646
+ return result
647
+
648
+
649
+ def convert_xor(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
650
+ """Treats XOR, ``^``, as exponentiation, ``**``."""
651
+ result: List[TOKEN] = []
652
+ for toknum, tokval in tokens:
653
+ if toknum == OP:
654
+ if tokval == '^':
655
+ result.append((OP, '**'))
656
+ else:
657
+ result.append((toknum, tokval))
658
+ else:
659
+ result.append((toknum, tokval))
660
+
661
+ return result
662
+
663
+
664
+ def repeated_decimals(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
665
+ """
666
+ Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90)
667
+
668
+ Run this before auto_number.
669
+
670
+ """
671
+ result: List[TOKEN] = []
672
+
673
+ def is_digit(s):
674
+ return all(i in '0123456789_' for i in s)
675
+
676
+ # num will running match any DECIMAL [ INTEGER ]
677
+ num: List[TOKEN] = []
678
+ for toknum, tokval in tokens:
679
+ if toknum == NUMBER:
680
+ if (not num and '.' in tokval and 'e' not in tokval.lower() and
681
+ 'j' not in tokval.lower()):
682
+ num.append((toknum, tokval))
683
+ elif is_digit(tokval)and len(num) == 2:
684
+ num.append((toknum, tokval))
685
+ elif is_digit(tokval) and len(num) == 3 and is_digit(num[-1][1]):
686
+ # Python 2 tokenizes 00123 as '00', '123'
687
+ # Python 3 tokenizes 01289 as '012', '89'
688
+ num.append((toknum, tokval))
689
+ else:
690
+ num = []
691
+ elif toknum == OP:
692
+ if tokval == '[' and len(num) == 1:
693
+ num.append((OP, tokval))
694
+ elif tokval == ']' and len(num) >= 3:
695
+ num.append((OP, tokval))
696
+ elif tokval == '.' and not num:
697
+ # handle .[1]
698
+ num.append((NUMBER, '0.'))
699
+ else:
700
+ num = []
701
+ else:
702
+ num = []
703
+
704
+ result.append((toknum, tokval))
705
+
706
+ if num and num[-1][1] == ']':
707
+ # pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post,
708
+ # and d/e = repetend
709
+ result = result[:-len(num)]
710
+ pre, post = num[0][1].split('.')
711
+ repetend = num[2][1]
712
+ if len(num) == 5:
713
+ repetend += num[3][1]
714
+
715
+ pre = pre.replace('_', '')
716
+ post = post.replace('_', '')
717
+ repetend = repetend.replace('_', '')
718
+
719
+ zeros = '0'*len(post)
720
+ post, repetends = [w.lstrip('0') for w in [post, repetend]]
721
+ # or else interpreted as octal
722
+
723
+ a = pre or '0'
724
+ b, c = post or '0', '1' + zeros
725
+ d, e = repetends, ('9'*len(repetend)) + zeros
726
+
727
+ seq = [
728
+ (OP, '('),
729
+ (NAME, 'Integer'),
730
+ (OP, '('),
731
+ (NUMBER, a),
732
+ (OP, ')'),
733
+ (OP, '+'),
734
+ (NAME, 'Rational'),
735
+ (OP, '('),
736
+ (NUMBER, b),
737
+ (OP, ','),
738
+ (NUMBER, c),
739
+ (OP, ')'),
740
+ (OP, '+'),
741
+ (NAME, 'Rational'),
742
+ (OP, '('),
743
+ (NUMBER, d),
744
+ (OP, ','),
745
+ (NUMBER, e),
746
+ (OP, ')'),
747
+ (OP, ')'),
748
+ ]
749
+ result.extend(seq)
750
+ num = []
751
+
752
+ return result
753
+
754
+
755
+ def auto_number(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
756
+ """
757
+ Converts numeric literals to use SymPy equivalents.
758
+
759
+ Complex numbers use ``I``, integer literals use ``Integer``, and float
760
+ literals use ``Float``.
761
+
762
+ """
763
+ result: List[TOKEN] = []
764
+
765
+ for toknum, tokval in tokens:
766
+ if toknum == NUMBER:
767
+ number = tokval
768
+ postfix = []
769
+
770
+ if number.endswith('j') or number.endswith('J'):
771
+ number = number[:-1]
772
+ postfix = [(OP, '*'), (NAME, 'I')]
773
+
774
+ if '.' in number or (('e' in number or 'E' in number) and
775
+ not (number.startswith('0x') or number.startswith('0X'))):
776
+ seq = [(NAME, 'Float'), (OP, '('),
777
+ (NUMBER, repr(str(number))), (OP, ')')]
778
+ else:
779
+ seq = [(NAME, 'Integer'), (OP, '('), (
780
+ NUMBER, number), (OP, ')')]
781
+
782
+ result.extend(seq + postfix)
783
+ else:
784
+ result.append((toknum, tokval))
785
+
786
+ return result
787
+
788
+
789
+ def rationalize(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
790
+ """Converts floats into ``Rational``. Run AFTER ``auto_number``."""
791
+ result: List[TOKEN] = []
792
+ passed_float = False
793
+ for toknum, tokval in tokens:
794
+ if toknum == NAME:
795
+ if tokval == 'Float':
796
+ passed_float = True
797
+ tokval = 'Rational'
798
+ result.append((toknum, tokval))
799
+ elif passed_float == True and toknum == NUMBER:
800
+ passed_float = False
801
+ result.append((STRING, tokval))
802
+ else:
803
+ result.append((toknum, tokval))
804
+
805
+ return result
806
+
807
+
808
+ def _transform_equals_sign(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
809
+ """Transforms the equals sign ``=`` to instances of Eq.
810
+
811
+ This is a helper function for ``convert_equals_signs``.
812
+ Works with expressions containing one equals sign and no
813
+ nesting. Expressions like ``(1=2)=False`` will not work with this
814
+ and should be used with ``convert_equals_signs``.
815
+
816
+ Examples: 1=2 to Eq(1,2)
817
+ 1*2=x to Eq(1*2, x)
818
+
819
+ This does not deal with function arguments yet.
820
+
821
+ """
822
+ result: List[TOKEN] = []
823
+ if (OP, "=") in tokens:
824
+ result.append((NAME, "Eq"))
825
+ result.append((OP, "("))
826
+ for token in tokens:
827
+ if token == (OP, "="):
828
+ result.append((OP, ","))
829
+ continue
830
+ result.append(token)
831
+ result.append((OP, ")"))
832
+ else:
833
+ result = tokens
834
+ return result
835
+
836
+
837
+ def convert_equals_signs(tokens: List[TOKEN], local_dict: DICT,
838
+ global_dict: DICT) -> List[TOKEN]:
839
+ """ Transforms all the equals signs ``=`` to instances of Eq.
840
+
841
+ Parses the equals signs in the expression and replaces them with
842
+ appropriate Eq instances. Also works with nested equals signs.
843
+
844
+ Does not yet play well with function arguments.
845
+ For example, the expression ``(x=y)`` is ambiguous and can be interpreted
846
+ as x being an argument to a function and ``convert_equals_signs`` will not
847
+ work for this.
848
+
849
+ See also
850
+ ========
851
+ convert_equality_operators
852
+
853
+ Examples
854
+ ========
855
+
856
+ >>> from sympy.parsing.sympy_parser import (parse_expr,
857
+ ... standard_transformations, convert_equals_signs)
858
+ >>> parse_expr("1*2=x", transformations=(
859
+ ... standard_transformations + (convert_equals_signs,)))
860
+ Eq(2, x)
861
+ >>> parse_expr("(1*2=x)=False", transformations=(
862
+ ... standard_transformations + (convert_equals_signs,)))
863
+ Eq(Eq(2, x), False)
864
+
865
+ """
866
+ res1 = _group_parentheses(convert_equals_signs)(tokens, local_dict, global_dict)
867
+ res2 = _apply_functions(res1, local_dict, global_dict)
868
+ res3 = _transform_equals_sign(res2, local_dict, global_dict)
869
+ result = _flatten(res3)
870
+ return result
871
+
872
+
873
+ #: Standard transformations for :func:`parse_expr`.
874
+ #: Inserts calls to :class:`~.Symbol`, :class:`~.Integer`, and other SymPy
875
+ #: datatypes and allows the use of standard factorial notation (e.g. ``x!``).
876
+ standard_transformations: tTuple[TRANS, ...] \
877
+ = (lambda_notation, auto_symbol, repeated_decimals, auto_number,
878
+ factorial_notation)
879
+
880
+
881
+ def stringify_expr(s: str, local_dict: DICT, global_dict: DICT,
882
+ transformations: tTuple[TRANS, ...]) -> str:
883
+ """
884
+ Converts the string ``s`` to Python code, in ``local_dict``
885
+
886
+ Generally, ``parse_expr`` should be used.
887
+ """
888
+
889
+ tokens = []
890
+ input_code = StringIO(s.strip())
891
+ for toknum, tokval, _, _, _ in generate_tokens(input_code.readline):
892
+ tokens.append((toknum, tokval))
893
+
894
+ for transform in transformations:
895
+ tokens = transform(tokens, local_dict, global_dict)
896
+
897
+ return untokenize(tokens)
898
+
899
+
900
+ def eval_expr(code, local_dict: DICT, global_dict: DICT):
901
+ """
902
+ Evaluate Python code generated by ``stringify_expr``.
903
+
904
+ Generally, ``parse_expr`` should be used.
905
+ """
906
+ expr = eval(
907
+ code, global_dict, local_dict) # take local objects in preference
908
+ return expr
909
+
910
+
911
+ def parse_expr(s: str, local_dict: Optional[DICT] = None,
912
+ transformations: tUnion[tTuple[TRANS, ...], str] \
913
+ = standard_transformations,
914
+ global_dict: Optional[DICT] = None, evaluate=True):
915
+ """Converts the string ``s`` to a SymPy expression, in ``local_dict``.
916
+
917
+ Parameters
918
+ ==========
919
+
920
+ s : str
921
+ The string to parse.
922
+
923
+ local_dict : dict, optional
924
+ A dictionary of local variables to use when parsing.
925
+
926
+ global_dict : dict, optional
927
+ A dictionary of global variables. By default, this is initialized
928
+ with ``from sympy import *``; provide this parameter to override
929
+ this behavior (for instance, to parse ``"Q & S"``).
930
+
931
+ transformations : tuple or str
932
+ A tuple of transformation functions used to modify the tokens of the
933
+ parsed expression before evaluation. The default transformations
934
+ convert numeric literals into their SymPy equivalents, convert
935
+ undefined variables into SymPy symbols, and allow the use of standard
936
+ mathematical factorial notation (e.g. ``x!``). Selection via
937
+ string is available (see below).
938
+
939
+ evaluate : bool, optional
940
+ When False, the order of the arguments will remain as they were in the
941
+ string and automatic simplification that would normally occur is
942
+ suppressed. (see examples)
943
+
944
+ Examples
945
+ ========
946
+
947
+ >>> from sympy.parsing.sympy_parser import parse_expr
948
+ >>> parse_expr("1/2")
949
+ 1/2
950
+ >>> type(_)
951
+ <class 'sympy.core.numbers.Half'>
952
+ >>> from sympy.parsing.sympy_parser import standard_transformations,\\
953
+ ... implicit_multiplication_application
954
+ >>> transformations = (standard_transformations +
955
+ ... (implicit_multiplication_application,))
956
+ >>> parse_expr("2x", transformations=transformations)
957
+ 2*x
958
+
959
+ When evaluate=False, some automatic simplifications will not occur:
960
+
961
+ >>> parse_expr("2**3"), parse_expr("2**3", evaluate=False)
962
+ (8, 2**3)
963
+
964
+ In addition the order of the arguments will not be made canonical.
965
+ This feature allows one to tell exactly how the expression was entered:
966
+
967
+ >>> a = parse_expr('1 + x', evaluate=False)
968
+ >>> b = parse_expr('x + 1', evaluate=0)
969
+ >>> a == b
970
+ False
971
+ >>> a.args
972
+ (1, x)
973
+ >>> b.args
974
+ (x, 1)
975
+
976
+ Note, however, that when these expressions are printed they will
977
+ appear the same:
978
+
979
+ >>> assert str(a) == str(b)
980
+
981
+ As a convenience, transformations can be seen by printing ``transformations``:
982
+
983
+ >>> from sympy.parsing.sympy_parser import transformations
984
+
985
+ >>> print(transformations)
986
+ 0: lambda_notation
987
+ 1: auto_symbol
988
+ 2: repeated_decimals
989
+ 3: auto_number
990
+ 4: factorial_notation
991
+ 5: implicit_multiplication_application
992
+ 6: convert_xor
993
+ 7: implicit_application
994
+ 8: implicit_multiplication
995
+ 9: convert_equals_signs
996
+ 10: function_exponentiation
997
+ 11: rationalize
998
+
999
+ The ``T`` object provides a way to select these transformations:
1000
+
1001
+ >>> from sympy.parsing.sympy_parser import T
1002
+
1003
+ If you print it, you will see the same list as shown above.
1004
+
1005
+ >>> str(T) == str(transformations)
1006
+ True
1007
+
1008
+ Standard slicing will return a tuple of transformations:
1009
+
1010
+ >>> T[:5] == standard_transformations
1011
+ True
1012
+
1013
+ So ``T`` can be used to specify the parsing transformations:
1014
+
1015
+ >>> parse_expr("2x", transformations=T[:5])
1016
+ Traceback (most recent call last):
1017
+ ...
1018
+ SyntaxError: invalid syntax
1019
+ >>> parse_expr("2x", transformations=T[:6])
1020
+ 2*x
1021
+ >>> parse_expr('.3', transformations=T[3, 11])
1022
+ 3/10
1023
+ >>> parse_expr('.3x', transformations=T[:])
1024
+ 3*x/10
1025
+
1026
+ As a further convenience, strings 'implicit' and 'all' can be used
1027
+ to select 0-5 and all the transformations, respectively.
1028
+
1029
+ >>> parse_expr('.3x', transformations='all')
1030
+ 3*x/10
1031
+
1032
+ See Also
1033
+ ========
1034
+
1035
+ stringify_expr, eval_expr, standard_transformations,
1036
+ implicit_multiplication_application
1037
+
1038
+ """
1039
+
1040
+ if local_dict is None:
1041
+ local_dict = {}
1042
+ elif not isinstance(local_dict, dict):
1043
+ raise TypeError('expecting local_dict to be a dict')
1044
+ elif null in local_dict:
1045
+ raise ValueError('cannot use "" in local_dict')
1046
+
1047
+ if global_dict is None:
1048
+ global_dict = {}
1049
+ exec('from sympy import *', global_dict)
1050
+
1051
+ builtins_dict = vars(builtins)
1052
+ for name, obj in builtins_dict.items():
1053
+ if isinstance(obj, types.BuiltinFunctionType):
1054
+ global_dict[name] = obj
1055
+ global_dict['max'] = Max
1056
+ global_dict['min'] = Min
1057
+
1058
+ elif not isinstance(global_dict, dict):
1059
+ raise TypeError('expecting global_dict to be a dict')
1060
+
1061
+ transformations = transformations or ()
1062
+ if isinstance(transformations, str):
1063
+ if transformations == 'all':
1064
+ _transformations = T[:]
1065
+ elif transformations == 'implicit':
1066
+ _transformations = T[:6]
1067
+ else:
1068
+ raise ValueError('unknown transformation group name')
1069
+ else:
1070
+ _transformations = transformations
1071
+
1072
+ code = stringify_expr(s, local_dict, global_dict, _transformations)
1073
+
1074
+ if not evaluate:
1075
+ code = compile(evaluateFalse(code), '<string>', 'eval') # type: ignore
1076
+
1077
+ try:
1078
+ rv = eval_expr(code, local_dict, global_dict)
1079
+ # restore neutral definitions for names
1080
+ for i in local_dict.pop(null, ()):
1081
+ local_dict[i] = null
1082
+ return rv
1083
+ except Exception as e:
1084
+ # restore neutral definitions for names
1085
+ for i in local_dict.pop(null, ()):
1086
+ local_dict[i] = null
1087
+ raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}")
1088
+
1089
+
1090
+ def evaluateFalse(s: str):
1091
+ """
1092
+ Replaces operators with the SymPy equivalent and sets evaluate=False.
1093
+ """
1094
+ node = ast.parse(s)
1095
+ transformed_node = EvaluateFalseTransformer().visit(node)
1096
+ # node is a Module, we want an Expression
1097
+ transformed_node = ast.Expression(transformed_node.body[0].value)
1098
+
1099
+ return ast.fix_missing_locations(transformed_node)
1100
+
1101
+
1102
+ class EvaluateFalseTransformer(ast.NodeTransformer):
1103
+ operators = {
1104
+ ast.Add: 'Add',
1105
+ ast.Mult: 'Mul',
1106
+ ast.Pow: 'Pow',
1107
+ ast.Sub: 'Add',
1108
+ ast.Div: 'Mul',
1109
+ ast.BitOr: 'Or',
1110
+ ast.BitAnd: 'And',
1111
+ ast.BitXor: 'Not',
1112
+ }
1113
+ functions = (
1114
+ 'Abs', 'im', 're', 'sign', 'arg', 'conjugate',
1115
+ 'acos', 'acot', 'acsc', 'asec', 'asin', 'atan',
1116
+ 'acosh', 'acoth', 'acsch', 'asech', 'asinh', 'atanh',
1117
+ 'cos', 'cot', 'csc', 'sec', 'sin', 'tan',
1118
+ 'cosh', 'coth', 'csch', 'sech', 'sinh', 'tanh',
1119
+ 'exp', 'ln', 'log', 'sqrt', 'cbrt',
1120
+ )
1121
+
1122
+ relational_operators = {
1123
+ ast.NotEq: 'Ne',
1124
+ ast.Lt: 'Lt',
1125
+ ast.LtE: 'Le',
1126
+ ast.Gt: 'Gt',
1127
+ ast.GtE: 'Ge',
1128
+ ast.Eq: 'Eq'
1129
+ }
1130
+ def visit_Compare(self, node):
1131
+ if node.ops[0].__class__ in self.relational_operators:
1132
+ sympy_class = self.relational_operators[node.ops[0].__class__]
1133
+ right = self.visit(node.comparators[0])
1134
+ left = self.visit(node.left)
1135
+ new_node = ast.Call(
1136
+ func=ast.Name(id=sympy_class, ctx=ast.Load()),
1137
+ args=[left, right],
1138
+ keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))],
1139
+ starargs=None,
1140
+ kwargs=None
1141
+ )
1142
+ return new_node
1143
+ return node
1144
+
1145
+ def flatten(self, args, func):
1146
+ result = []
1147
+ for arg in args:
1148
+ if isinstance(arg, ast.Call):
1149
+ arg_func = arg.func
1150
+ if isinstance(arg_func, ast.Call):
1151
+ arg_func = arg_func.func
1152
+ if arg_func.id == func:
1153
+ result.extend(self.flatten(arg.args, func))
1154
+ else:
1155
+ result.append(arg)
1156
+ else:
1157
+ result.append(arg)
1158
+ return result
1159
+
1160
+ def visit_BinOp(self, node):
1161
+ if node.op.__class__ in self.operators:
1162
+ sympy_class = self.operators[node.op.__class__]
1163
+ right = self.visit(node.right)
1164
+ left = self.visit(node.left)
1165
+
1166
+ rev = False
1167
+ if isinstance(node.op, ast.Sub):
1168
+ right = ast.Call(
1169
+ func=ast.Name(id='Mul', ctx=ast.Load()),
1170
+ args=[ast.UnaryOp(op=ast.USub(), operand=ast.Num(1)), right],
1171
+ keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))],
1172
+ starargs=None,
1173
+ kwargs=None
1174
+ )
1175
+ elif isinstance(node.op, ast.Div):
1176
+ if isinstance(node.left, ast.UnaryOp):
1177
+ left, right = right, left
1178
+ rev = True
1179
+ left = ast.Call(
1180
+ func=ast.Name(id='Pow', ctx=ast.Load()),
1181
+ args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))],
1182
+ keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))],
1183
+ starargs=None,
1184
+ kwargs=None
1185
+ )
1186
+ else:
1187
+ right = ast.Call(
1188
+ func=ast.Name(id='Pow', ctx=ast.Load()),
1189
+ args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))],
1190
+ keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))],
1191
+ starargs=None,
1192
+ kwargs=None
1193
+ )
1194
+
1195
+ if rev: # undo reversal
1196
+ left, right = right, left
1197
+ new_node = ast.Call(
1198
+ func=ast.Name(id=sympy_class, ctx=ast.Load()),
1199
+ args=[left, right],
1200
+ keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))],
1201
+ starargs=None,
1202
+ kwargs=None
1203
+ )
1204
+
1205
+ if sympy_class in ('Add', 'Mul'):
1206
+ # Denest Add or Mul as appropriate
1207
+ new_node.args = self.flatten(new_node.args, sympy_class)
1208
+
1209
+ return new_node
1210
+ return node
1211
+
1212
+ def visit_Call(self, node):
1213
+ new_node = self.generic_visit(node)
1214
+ if isinstance(node.func, ast.Name) and node.func.id in self.functions:
1215
+ new_node.keywords.append(ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load())))
1216
+ return new_node
1217
+
1218
+
1219
+ _transformation = { # items can be added but never re-ordered
1220
+ 0: lambda_notation,
1221
+ 1: auto_symbol,
1222
+ 2: repeated_decimals,
1223
+ 3: auto_number,
1224
+ 4: factorial_notation,
1225
+ 5: implicit_multiplication_application,
1226
+ 6: convert_xor,
1227
+ 7: implicit_application,
1228
+ 8: implicit_multiplication,
1229
+ 9: convert_equals_signs,
1230
+ 10: function_exponentiation,
1231
+ 11: rationalize}
1232
+
1233
+ transformations = '\n'.join('%s: %s' % (i, func_name(f)) for i, f in _transformation.items())
1234
+
1235
+
1236
+ class _T():
1237
+ """class to retrieve transformations from a given slice
1238
+
1239
+ EXAMPLES
1240
+ ========
1241
+
1242
+ >>> from sympy.parsing.sympy_parser import T, standard_transformations
1243
+ >>> assert T[:5] == standard_transformations
1244
+ """
1245
+ def __init__(self):
1246
+ self.N = len(_transformation)
1247
+
1248
+ def __str__(self):
1249
+ return transformations
1250
+
1251
+ def __getitem__(self, t):
1252
+ if not type(t) is tuple:
1253
+ t = (t,)
1254
+ i = []
1255
+ for ti in t:
1256
+ if type(ti) is int:
1257
+ i.append(range(self.N)[ti])
1258
+ elif type(ti) is slice:
1259
+ i.extend(range(*ti.indices(self.N)))
1260
+ else:
1261
+ raise TypeError('unexpected slice arg')
1262
+ return tuple([_transformation[_] for _ in i])
1263
+
1264
+ T = _T()
llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_ast_parser.cpython-310.pyc ADDED
Binary file (1.11 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_autolev.cpython-310.pyc ADDED
Binary file (5.68 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_c_parser.cpython-310.pyc ADDED
Binary file (48.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_fortran_parser.cpython-310.pyc ADDED
Binary file (7.16 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_implicit_multiplication_application.cpython-310.pyc ADDED
Binary file (5.56 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_latex.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_latex_deps.cpython-310.pyc ADDED
Binary file (728 Bytes). View file