applied-ai-018 commited on
Commit
11007f6
·
verified ·
1 Parent(s): c633c49

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/codegen/__pycache__/__init__.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/algorithms.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/ast.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/matrix_nodes.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/pyutils.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/rewriting.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/scipy_nodes.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/__init__.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/cartan_matrix.cpython-310.pyc +0 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/cartan_type.cpython-310.pyc +0 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/dynkin_diagram.cpython-310.pyc +0 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/root_system.cpython-310.pyc +0 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_a.cpython-310.pyc +0 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_b.cpython-310.pyc +0 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_c.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_d.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_e.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_f.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_g.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/weyl_group.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_cartan_matrix.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_dynkin_diagram.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_root_system.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_type_A.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_type_C.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_and.png +3 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_or.png +3 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_xor.png +3 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/printing/__init__.py +116 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/printing/aesaracode.py +539 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/printing/c.py +747 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/printing/codeprinter.py +875 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/printing/conventions.py +88 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/printing/cxx.py +169 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/printing/defaults.py +5 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/printing/dot.py +294 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/printing/fortran.py +782 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/printing/glsl.py +557 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/printing/gtk.py +16 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/printing/jscode.py +339 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/printing/julia.py +658 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/printing/lambdarepr.py +251 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/printing/latex.py +0 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/printing/llvmjitcode.py +489 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/printing/maple.py +311 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/printing/mathematica.py +354 -0
llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/algorithms.cpython-310.pyc ADDED
Binary file (5.43 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc ADDED
Binary file (6.34 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/ast.cpython-310.pyc ADDED
Binary file (59.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-310.pyc ADDED
Binary file (14 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/matrix_nodes.cpython-310.pyc ADDED
Binary file (2.53 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-310.pyc ADDED
Binary file (3.85 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/pyutils.cpython-310.pyc ADDED
Binary file (1.17 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/rewriting.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/codegen/__pycache__/scipy_nodes.cpython-310.pyc ADDED
Binary file (3.27 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (276 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/cartan_matrix.cpython-310.pyc ADDED
Binary file (789 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/cartan_type.cpython-310.pyc ADDED
Binary file (2.21 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/dynkin_diagram.cpython-310.pyc ADDED
Binary file (801 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/root_system.cpython-310.pyc ADDED
Binary file (7.81 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_a.cpython-310.pyc ADDED
Binary file (5.48 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_b.cpython-310.pyc ADDED
Binary file (5.45 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_c.cpython-310.pyc ADDED
Binary file (5.34 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_d.cpython-310.pyc ADDED
Binary file (5.63 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_e.cpython-310.pyc ADDED
Binary file (7.13 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_f.cpython-310.pyc ADDED
Binary file (4.91 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/type_g.cpython-310.pyc ADDED
Binary file (3.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/weyl_group.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (196 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_cartan_matrix.cpython-310.pyc ADDED
Binary file (620 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_dynkin_diagram.cpython-310.pyc ADDED
Binary file (523 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_root_system.cpython-310.pyc ADDED
Binary file (1.37 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_type_A.cpython-310.pyc ADDED
Binary file (1.06 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/liealgebras/tests/__pycache__/test_type_C.cpython-310.pyc ADDED
Binary file (1.53 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_and.png ADDED

Git LFS Details

  • SHA256: 115d0b9b81ed40f93fe9e216b4f6384cf71093e3bbb64a5d648b8b9858c645a0
  • Pointer size: 129 Bytes
  • Size of remote file: 6.86 kB
llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_or.png ADDED

Git LFS Details

  • SHA256: e41ba0d3dbf2a20f82bb79a4cbba5bb458dec396ccbdba5ed195d6b200ca7f2e
  • Pointer size: 129 Bytes
  • Size of remote file: 8.81 kB
llmeval-env/lib/python3.10/site-packages/sympy/plotting/tests/test_region_xor.png ADDED

Git LFS Details

  • SHA256: 92e71558103d03df0ea5c47876277968b5d4ca8ab8cf43b80b73cce9d962052c
  • Pointer size: 130 Bytes
  • Size of remote file: 10 kB
llmeval-env/lib/python3.10/site-packages/sympy/printing/__init__.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Printing subsystem"""
2
+
3
+ from .pretty import pager_print, pretty, pretty_print, pprint, pprint_use_unicode, pprint_try_use_unicode
4
+
5
+ from .latex import latex, print_latex, multiline_latex
6
+
7
+ from .mathml import mathml, print_mathml
8
+
9
+ from .python import python, print_python
10
+
11
+ from .pycode import pycode
12
+
13
+ from .codeprinter import print_ccode, print_fcode
14
+
15
+ from .codeprinter import ccode, fcode, cxxcode # noqa:F811
16
+
17
+ from .smtlib import smtlib_code
18
+
19
+ from .glsl import glsl_code, print_glsl
20
+
21
+ from .rcode import rcode, print_rcode
22
+
23
+ from .jscode import jscode, print_jscode
24
+
25
+ from .julia import julia_code
26
+
27
+ from .mathematica import mathematica_code
28
+
29
+ from .octave import octave_code
30
+
31
+ from .rust import rust_code
32
+
33
+ from .gtk import print_gtk
34
+
35
+ from .preview import preview
36
+
37
+ from .repr import srepr
38
+
39
+ from .tree import print_tree
40
+
41
+ from .str import StrPrinter, sstr, sstrrepr
42
+
43
+ from .tableform import TableForm
44
+
45
+ from .dot import dotprint
46
+
47
+ from .maple import maple_code, print_maple_code
48
+
49
+ __all__ = [
50
+ # sympy.printing.pretty
51
+ 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
52
+ 'pprint_try_use_unicode',
53
+
54
+ # sympy.printing.latex
55
+ 'latex', 'print_latex', 'multiline_latex',
56
+
57
+ # sympy.printing.mathml
58
+ 'mathml', 'print_mathml',
59
+
60
+ # sympy.printing.python
61
+ 'python', 'print_python',
62
+
63
+ # sympy.printing.pycode
64
+ 'pycode',
65
+
66
+ # sympy.printing.codeprinter
67
+ 'ccode', 'print_ccode', 'cxxcode', 'fcode', 'print_fcode',
68
+
69
+ # sympy.printing.smtlib
70
+ 'smtlib_code',
71
+
72
+ # sympy.printing.glsl
73
+ 'glsl_code', 'print_glsl',
74
+
75
+ # sympy.printing.rcode
76
+ 'rcode', 'print_rcode',
77
+
78
+ # sympy.printing.jscode
79
+ 'jscode', 'print_jscode',
80
+
81
+ # sympy.printing.julia
82
+ 'julia_code',
83
+
84
+ # sympy.printing.mathematica
85
+ 'mathematica_code',
86
+
87
+ # sympy.printing.octave
88
+ 'octave_code',
89
+
90
+ # sympy.printing.rust
91
+ 'rust_code',
92
+
93
+ # sympy.printing.gtk
94
+ 'print_gtk',
95
+
96
+ # sympy.printing.preview
97
+ 'preview',
98
+
99
+ # sympy.printing.repr
100
+ 'srepr',
101
+
102
+ # sympy.printing.tree
103
+ 'print_tree',
104
+
105
+ # sympy.printing.str
106
+ 'StrPrinter', 'sstr', 'sstrrepr',
107
+
108
+ # sympy.printing.tableform
109
+ 'TableForm',
110
+
111
+ # sympy.printing.dot
112
+ 'dotprint',
113
+
114
+ # sympy.printing.maple
115
+ 'maple_code', 'print_maple_code',
116
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/printing/aesaracode.py ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Any
3
+
4
+ from sympy.external import import_module
5
+ from sympy.printing.printer import Printer
6
+ from sympy.utilities.iterables import is_sequence
7
+ import sympy
8
+ from functools import partial
9
+
10
+
11
+ aesara = import_module('aesara')
12
+
13
+ if aesara:
14
+ aes = aesara.scalar
15
+ aet = aesara.tensor
16
+ from aesara.tensor import nlinalg
17
+ from aesara.tensor.elemwise import Elemwise
18
+ from aesara.tensor.elemwise import DimShuffle
19
+
20
+ # `true_divide` replaced `true_div` in Aesara 2.8.11 (released 2023) to
21
+ # match NumPy
22
+ # XXX: Remove this when not needed to support older versions.
23
+ true_divide = getattr(aet, 'true_divide', None)
24
+ if true_divide is None:
25
+ true_divide = aet.true_div
26
+
27
+ mapping = {
28
+ sympy.Add: aet.add,
29
+ sympy.Mul: aet.mul,
30
+ sympy.Abs: aet.abs,
31
+ sympy.sign: aet.sgn,
32
+ sympy.ceiling: aet.ceil,
33
+ sympy.floor: aet.floor,
34
+ sympy.log: aet.log,
35
+ sympy.exp: aet.exp,
36
+ sympy.sqrt: aet.sqrt,
37
+ sympy.cos: aet.cos,
38
+ sympy.acos: aet.arccos,
39
+ sympy.sin: aet.sin,
40
+ sympy.asin: aet.arcsin,
41
+ sympy.tan: aet.tan,
42
+ sympy.atan: aet.arctan,
43
+ sympy.atan2: aet.arctan2,
44
+ sympy.cosh: aet.cosh,
45
+ sympy.acosh: aet.arccosh,
46
+ sympy.sinh: aet.sinh,
47
+ sympy.asinh: aet.arcsinh,
48
+ sympy.tanh: aet.tanh,
49
+ sympy.atanh: aet.arctanh,
50
+ sympy.re: aet.real,
51
+ sympy.im: aet.imag,
52
+ sympy.arg: aet.angle,
53
+ sympy.erf: aet.erf,
54
+ sympy.gamma: aet.gamma,
55
+ sympy.loggamma: aet.gammaln,
56
+ sympy.Pow: aet.pow,
57
+ sympy.Eq: aet.eq,
58
+ sympy.StrictGreaterThan: aet.gt,
59
+ sympy.StrictLessThan: aet.lt,
60
+ sympy.LessThan: aet.le,
61
+ sympy.GreaterThan: aet.ge,
62
+ sympy.And: aet.bitwise_and, # bitwise
63
+ sympy.Or: aet.bitwise_or, # bitwise
64
+ sympy.Not: aet.invert, # bitwise
65
+ sympy.Xor: aet.bitwise_xor, # bitwise
66
+ sympy.Max: aet.maximum, # Sympy accept >2 inputs, Aesara only 2
67
+ sympy.Min: aet.minimum, # Sympy accept >2 inputs, Aesara only 2
68
+ sympy.conjugate: aet.conj,
69
+ sympy.core.numbers.ImaginaryUnit: lambda:aet.complex(0,1),
70
+ # Matrices
71
+ sympy.MatAdd: Elemwise(aes.add),
72
+ sympy.HadamardProduct: Elemwise(aes.mul),
73
+ sympy.Trace: nlinalg.trace,
74
+ sympy.Determinant : nlinalg.det,
75
+ sympy.Inverse: nlinalg.matrix_inverse,
76
+ sympy.Transpose: DimShuffle((False, False), [1, 0]),
77
+ }
78
+
79
+
80
+ class AesaraPrinter(Printer):
81
+ """ Code printer which creates Aesara symbolic expression graphs.
82
+
83
+ Parameters
84
+ ==========
85
+
86
+ cache : dict
87
+ Cache dictionary to use. If None (default) will use
88
+ the global cache. To create a printer which does not depend on or alter
89
+ global state pass an empty dictionary. Note: the dictionary is not
90
+ copied on initialization of the printer and will be updated in-place,
91
+ so using the same dict object when creating multiple printers or making
92
+ multiple calls to :func:`.aesara_code` or :func:`.aesara_function` means
93
+ the cache is shared between all these applications.
94
+
95
+ Attributes
96
+ ==========
97
+
98
+ cache : dict
99
+ A cache of Aesara variables which have been created for SymPy
100
+ symbol-like objects (e.g. :class:`sympy.core.symbol.Symbol` or
101
+ :class:`sympy.matrices.expressions.MatrixSymbol`). This is used to
102
+ ensure that all references to a given symbol in an expression (or
103
+ multiple expressions) are printed as the same Aesara variable, which is
104
+ created only once. Symbols are differentiated only by name and type. The
105
+ format of the cache's contents should be considered opaque to the user.
106
+ """
107
+ printmethod = "_aesara"
108
+
109
+ def __init__(self, *args, **kwargs):
110
+ self.cache = kwargs.pop('cache', {})
111
+ super().__init__(*args, **kwargs)
112
+
113
+ def _get_key(self, s, name=None, dtype=None, broadcastable=None):
114
+ """ Get the cache key for a SymPy object.
115
+
116
+ Parameters
117
+ ==========
118
+
119
+ s : sympy.core.basic.Basic
120
+ SymPy object to get key for.
121
+
122
+ name : str
123
+ Name of object, if it does not have a ``name`` attribute.
124
+ """
125
+
126
+ if name is None:
127
+ name = s.name
128
+
129
+ return (name, type(s), s.args, dtype, broadcastable)
130
+
131
+ def _get_or_create(self, s, name=None, dtype=None, broadcastable=None):
132
+ """
133
+ Get the Aesara variable for a SymPy symbol from the cache, or create it
134
+ if it does not exist.
135
+ """
136
+
137
+ # Defaults
138
+ if name is None:
139
+ name = s.name
140
+ if dtype is None:
141
+ dtype = 'floatX'
142
+ if broadcastable is None:
143
+ broadcastable = ()
144
+
145
+ key = self._get_key(s, name, dtype=dtype, broadcastable=broadcastable)
146
+
147
+ if key in self.cache:
148
+ return self.cache[key]
149
+
150
+ value = aet.tensor(name=name, dtype=dtype, broadcastable=broadcastable)
151
+ self.cache[key] = value
152
+ return value
153
+
154
+ def _print_Symbol(self, s, **kwargs):
155
+ dtype = kwargs.get('dtypes', {}).get(s)
156
+ bc = kwargs.get('broadcastables', {}).get(s)
157
+ return self._get_or_create(s, dtype=dtype, broadcastable=bc)
158
+
159
+ def _print_AppliedUndef(self, s, **kwargs):
160
+ name = str(type(s)) + '_' + str(s.args[0])
161
+ dtype = kwargs.get('dtypes', {}).get(s)
162
+ bc = kwargs.get('broadcastables', {}).get(s)
163
+ return self._get_or_create(s, name=name, dtype=dtype, broadcastable=bc)
164
+
165
+ def _print_Basic(self, expr, **kwargs):
166
+ op = mapping[type(expr)]
167
+ children = [self._print(arg, **kwargs) for arg in expr.args]
168
+ return op(*children)
169
+
170
+ def _print_Number(self, n, **kwargs):
171
+ # Integers already taken care of below, interpret as float
172
+ return float(n.evalf())
173
+
174
+ def _print_MatrixSymbol(self, X, **kwargs):
175
+ dtype = kwargs.get('dtypes', {}).get(X)
176
+ return self._get_or_create(X, dtype=dtype, broadcastable=(None, None))
177
+
178
+ def _print_DenseMatrix(self, X, **kwargs):
179
+ if not hasattr(aet, 'stacklists'):
180
+ raise NotImplementedError(
181
+ "Matrix translation not yet supported in this version of Aesara")
182
+
183
+ return aet.stacklists([
184
+ [self._print(arg, **kwargs) for arg in L]
185
+ for L in X.tolist()
186
+ ])
187
+
188
+ _print_ImmutableMatrix = _print_ImmutableDenseMatrix = _print_DenseMatrix
189
+
190
+ def _print_MatMul(self, expr, **kwargs):
191
+ children = [self._print(arg, **kwargs) for arg in expr.args]
192
+ result = children[0]
193
+ for child in children[1:]:
194
+ result = aet.dot(result, child)
195
+ return result
196
+
197
+ def _print_MatPow(self, expr, **kwargs):
198
+ children = [self._print(arg, **kwargs) for arg in expr.args]
199
+ result = 1
200
+ if isinstance(children[1], int) and children[1] > 0:
201
+ for i in range(children[1]):
202
+ result = aet.dot(result, children[0])
203
+ else:
204
+ raise NotImplementedError('''Only non-negative integer
205
+ powers of matrices can be handled by Aesara at the moment''')
206
+ return result
207
+
208
+ def _print_MatrixSlice(self, expr, **kwargs):
209
+ parent = self._print(expr.parent, **kwargs)
210
+ rowslice = self._print(slice(*expr.rowslice), **kwargs)
211
+ colslice = self._print(slice(*expr.colslice), **kwargs)
212
+ return parent[rowslice, colslice]
213
+
214
+ def _print_BlockMatrix(self, expr, **kwargs):
215
+ nrows, ncols = expr.blocks.shape
216
+ blocks = [[self._print(expr.blocks[r, c], **kwargs)
217
+ for c in range(ncols)]
218
+ for r in range(nrows)]
219
+ return aet.join(0, *[aet.join(1, *row) for row in blocks])
220
+
221
+
222
+ def _print_slice(self, expr, **kwargs):
223
+ return slice(*[self._print(i, **kwargs)
224
+ if isinstance(i, sympy.Basic) else i
225
+ for i in (expr.start, expr.stop, expr.step)])
226
+
227
+ def _print_Pi(self, expr, **kwargs):
228
+ return 3.141592653589793
229
+
230
+ def _print_Piecewise(self, expr, **kwargs):
231
+ import numpy as np
232
+ e, cond = expr.args[0].args # First condition and corresponding value
233
+
234
+ # Print conditional expression and value for first condition
235
+ p_cond = self._print(cond, **kwargs)
236
+ p_e = self._print(e, **kwargs)
237
+
238
+ # One condition only
239
+ if len(expr.args) == 1:
240
+ # Return value if condition else NaN
241
+ return aet.switch(p_cond, p_e, np.nan)
242
+
243
+ # Return value_1 if condition_1 else evaluate remaining conditions
244
+ p_remaining = self._print(sympy.Piecewise(*expr.args[1:]), **kwargs)
245
+ return aet.switch(p_cond, p_e, p_remaining)
246
+
247
+ def _print_Rational(self, expr, **kwargs):
248
+ return true_divide(self._print(expr.p, **kwargs),
249
+ self._print(expr.q, **kwargs))
250
+
251
+ def _print_Integer(self, expr, **kwargs):
252
+ return expr.p
253
+
254
+ def _print_factorial(self, expr, **kwargs):
255
+ return self._print(sympy.gamma(expr.args[0] + 1), **kwargs)
256
+
257
+ def _print_Derivative(self, deriv, **kwargs):
258
+ from aesara.gradient import Rop
259
+
260
+ rv = self._print(deriv.expr, **kwargs)
261
+ for var in deriv.variables:
262
+ var = self._print(var, **kwargs)
263
+ rv = Rop(rv, var, aet.ones_like(var))
264
+ return rv
265
+
266
+ def emptyPrinter(self, expr):
267
+ return expr
268
+
269
+ def doprint(self, expr, dtypes=None, broadcastables=None):
270
+ """ Convert a SymPy expression to a Aesara graph variable.
271
+
272
+ The ``dtypes`` and ``broadcastables`` arguments are used to specify the
273
+ data type, dimension, and broadcasting behavior of the Aesara variables
274
+ corresponding to the free symbols in ``expr``. Each is a mapping from
275
+ SymPy symbols to the value of the corresponding argument to
276
+ ``aesara.tensor.var.TensorVariable``.
277
+
278
+ See the corresponding `documentation page`__ for more information on
279
+ broadcasting in Aesara.
280
+
281
+ .. __: https://aesara.readthedocs.io/en/latest/tutorial/broadcasting.html
282
+
283
+ Parameters
284
+ ==========
285
+
286
+ expr : sympy.core.expr.Expr
287
+ SymPy expression to print.
288
+
289
+ dtypes : dict
290
+ Mapping from SymPy symbols to Aesara datatypes to use when creating
291
+ new Aesara variables for those symbols. Corresponds to the ``dtype``
292
+ argument to ``aesara.tensor.var.TensorVariable``. Defaults to ``'floatX'``
293
+ for symbols not included in the mapping.
294
+
295
+ broadcastables : dict
296
+ Mapping from SymPy symbols to the value of the ``broadcastable``
297
+ argument to ``aesara.tensor.var.TensorVariable`` to use when creating Aesara
298
+ variables for those symbols. Defaults to the empty tuple for symbols
299
+ not included in the mapping (resulting in a scalar).
300
+
301
+ Returns
302
+ =======
303
+
304
+ aesara.graph.basic.Variable
305
+ A variable corresponding to the expression's value in a Aesara
306
+ symbolic expression graph.
307
+
308
+ """
309
+ if dtypes is None:
310
+ dtypes = {}
311
+ if broadcastables is None:
312
+ broadcastables = {}
313
+
314
+ return self._print(expr, dtypes=dtypes, broadcastables=broadcastables)
315
+
316
+
317
+ global_cache: dict[Any, Any] = {}
318
+
319
+
320
+ def aesara_code(expr, cache=None, **kwargs):
321
+ """
322
+ Convert a SymPy expression into a Aesara graph variable.
323
+
324
+ Parameters
325
+ ==========
326
+
327
+ expr : sympy.core.expr.Expr
328
+ SymPy expression object to convert.
329
+
330
+ cache : dict
331
+ Cached Aesara variables (see :class:`AesaraPrinter.cache
332
+ <AesaraPrinter>`). Defaults to the module-level global cache.
333
+
334
+ dtypes : dict
335
+ Passed to :meth:`.AesaraPrinter.doprint`.
336
+
337
+ broadcastables : dict
338
+ Passed to :meth:`.AesaraPrinter.doprint`.
339
+
340
+ Returns
341
+ =======
342
+
343
+ aesara.graph.basic.Variable
344
+ A variable corresponding to the expression's value in a Aesara symbolic
345
+ expression graph.
346
+
347
+ """
348
+ if not aesara:
349
+ raise ImportError("aesara is required for aesara_code")
350
+
351
+ if cache is None:
352
+ cache = global_cache
353
+
354
+ return AesaraPrinter(cache=cache, settings={}).doprint(expr, **kwargs)
355
+
356
+
357
+ def dim_handling(inputs, dim=None, dims=None, broadcastables=None):
358
+ r"""
359
+ Get value of ``broadcastables`` argument to :func:`.aesara_code` from
360
+ keyword arguments to :func:`.aesara_function`.
361
+
362
+ Included for backwards compatibility.
363
+
364
+ Parameters
365
+ ==========
366
+
367
+ inputs
368
+ Sequence of input symbols.
369
+
370
+ dim : int
371
+ Common number of dimensions for all inputs. Overrides other arguments
372
+ if given.
373
+
374
+ dims : dict
375
+ Mapping from input symbols to number of dimensions. Overrides
376
+ ``broadcastables`` argument if given.
377
+
378
+ broadcastables : dict
379
+ Explicit value of ``broadcastables`` argument to
380
+ :meth:`.AesaraPrinter.doprint`. If not None function will return this value unchanged.
381
+
382
+ Returns
383
+ =======
384
+ dict
385
+ Dictionary mapping elements of ``inputs`` to their "broadcastable"
386
+ values (tuple of ``bool``\ s).
387
+ """
388
+ if dim is not None:
389
+ return {s: (False,) * dim for s in inputs}
390
+
391
+ if dims is not None:
392
+ maxdim = max(dims.values())
393
+ return {
394
+ s: (False,) * d + (True,) * (maxdim - d)
395
+ for s, d in dims.items()
396
+ }
397
+
398
+ if broadcastables is not None:
399
+ return broadcastables
400
+
401
+ return {}
402
+
403
+
404
+ def aesara_function(inputs, outputs, scalar=False, *,
405
+ dim=None, dims=None, broadcastables=None, **kwargs):
406
+ """
407
+ Create a Aesara function from SymPy expressions.
408
+
409
+ The inputs and outputs are converted to Aesara variables using
410
+ :func:`.aesara_code` and then passed to ``aesara.function``.
411
+
412
+ Parameters
413
+ ==========
414
+
415
+ inputs
416
+ Sequence of symbols which constitute the inputs of the function.
417
+
418
+ outputs
419
+ Sequence of expressions which constitute the outputs(s) of the
420
+ function. The free symbols of each expression must be a subset of
421
+ ``inputs``.
422
+
423
+ scalar : bool
424
+ Convert 0-dimensional arrays in output to scalars. This will return a
425
+ Python wrapper function around the Aesara function object.
426
+
427
+ cache : dict
428
+ Cached Aesara variables (see :class:`AesaraPrinter.cache
429
+ <AesaraPrinter>`). Defaults to the module-level global cache.
430
+
431
+ dtypes : dict
432
+ Passed to :meth:`.AesaraPrinter.doprint`.
433
+
434
+ broadcastables : dict
435
+ Passed to :meth:`.AesaraPrinter.doprint`.
436
+
437
+ dims : dict
438
+ Alternative to ``broadcastables`` argument. Mapping from elements of
439
+ ``inputs`` to integers indicating the dimension of their associated
440
+ arrays/tensors. Overrides ``broadcastables`` argument if given.
441
+
442
+ dim : int
443
+ Another alternative to the ``broadcastables`` argument. Common number of
444
+ dimensions to use for all arrays/tensors.
445
+ ``aesara_function([x, y], [...], dim=2)`` is equivalent to using
446
+ ``broadcastables={x: (False, False), y: (False, False)}``.
447
+
448
+ Returns
449
+ =======
450
+ callable
451
+ A callable object which takes values of ``inputs`` as positional
452
+ arguments and returns an output array for each of the expressions
453
+ in ``outputs``. If ``outputs`` is a single expression the function will
454
+ return a Numpy array, if it is a list of multiple expressions the
455
+ function will return a list of arrays. See description of the ``squeeze``
456
+ argument above for the behavior when a single output is passed in a list.
457
+ The returned object will either be an instance of
458
+ ``aesara.compile.function.types.Function`` or a Python wrapper
459
+ function around one. In both cases, the returned value will have a
460
+ ``aesara_function`` attribute which points to the return value of
461
+ ``aesara.function``.
462
+
463
+ Examples
464
+ ========
465
+
466
+ >>> from sympy.abc import x, y, z
467
+ >>> from sympy.printing.aesaracode import aesara_function
468
+
469
+ A simple function with one input and one output:
470
+
471
+ >>> f1 = aesara_function([x], [x**2 - 1], scalar=True)
472
+ >>> f1(3)
473
+ 8.0
474
+
475
+ A function with multiple inputs and one output:
476
+
477
+ >>> f2 = aesara_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True)
478
+ >>> f2(3, 4, 2)
479
+ 5.0
480
+
481
+ A function with multiple inputs and multiple outputs:
482
+
483
+ >>> f3 = aesara_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True)
484
+ >>> f3(2, 3)
485
+ [13.0, -5.0]
486
+
487
+ See also
488
+ ========
489
+
490
+ dim_handling
491
+
492
+ """
493
+ if not aesara:
494
+ raise ImportError("Aesara is required for aesara_function")
495
+
496
+ # Pop off non-aesara keyword args
497
+ cache = kwargs.pop('cache', {})
498
+ dtypes = kwargs.pop('dtypes', {})
499
+
500
+ broadcastables = dim_handling(
501
+ inputs, dim=dim, dims=dims, broadcastables=broadcastables,
502
+ )
503
+
504
+ # Print inputs/outputs
505
+ code = partial(aesara_code, cache=cache, dtypes=dtypes,
506
+ broadcastables=broadcastables)
507
+ tinputs = list(map(code, inputs))
508
+ toutputs = list(map(code, outputs))
509
+
510
+ #fix constant expressions as variables
511
+ toutputs = [output if isinstance(output, aesara.graph.basic.Variable) else aet.as_tensor_variable(output) for output in toutputs]
512
+
513
+ if len(toutputs) == 1:
514
+ toutputs = toutputs[0]
515
+
516
+ # Compile aesara func
517
+ func = aesara.function(tinputs, toutputs, **kwargs)
518
+
519
+ is_0d = [len(o.variable.broadcastable) == 0 for o in func.outputs]
520
+
521
+ # No wrapper required
522
+ if not scalar or not any(is_0d):
523
+ func.aesara_function = func
524
+ return func
525
+
526
+ # Create wrapper to convert 0-dimensional outputs to scalars
527
+ def wrapper(*args):
528
+ out = func(*args)
529
+ # out can be array(1.0) or [array(1.0), array(2.0)]
530
+
531
+ if is_sequence(out):
532
+ return [o[()] if is_0d[i] else o for i, o in enumerate(out)]
533
+ else:
534
+ return out[()]
535
+
536
+ wrapper.__wrapped__ = func
537
+ wrapper.__doc__ = func.__doc__
538
+ wrapper.aesara_function = func
539
+ return wrapper
llmeval-env/lib/python3.10/site-packages/sympy/printing/c.py ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ C code printer
3
+
4
+ The C89CodePrinter & C99CodePrinter converts single SymPy expressions into
5
+ single C expressions, using the functions defined in math.h where possible.
6
+
7
+ A complete code generator, which uses ccode extensively, can be found in
8
+ sympy.utilities.codegen. The codegen module can be used to generate complete
9
+ source code files that are compilable without further modifications.
10
+
11
+
12
+ """
13
+
14
+ from __future__ import annotations
15
+ from typing import Any
16
+
17
+ from functools import wraps
18
+ from itertools import chain
19
+
20
+ from sympy.core import S
21
+ from sympy.core.numbers import equal_valued
22
+ from sympy.codegen.ast import (
23
+ Assignment, Pointer, Variable, Declaration, Type,
24
+ real, complex_, integer, bool_, float32, float64, float80,
25
+ complex64, complex128, intc, value_const, pointer_const,
26
+ int8, int16, int32, int64, uint8, uint16, uint32, uint64, untyped,
27
+ none
28
+ )
29
+ from sympy.printing.codeprinter import CodePrinter, requires
30
+ from sympy.printing.precedence import precedence, PRECEDENCE
31
+ from sympy.sets.fancysets import Range
32
+
33
+ # These are defined in the other file so we can avoid importing sympy.codegen
34
+ # from the top-level 'import sympy'. Export them here as well.
35
+ from sympy.printing.codeprinter import ccode, print_ccode # noqa:F401
36
+
37
+ # dictionary mapping SymPy function to (argument_conditions, C_function).
38
+ # Used in C89CodePrinter._print_Function(self)
39
+ known_functions_C89 = {
40
+ "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")],
41
+ "sin": "sin",
42
+ "cos": "cos",
43
+ "tan": "tan",
44
+ "asin": "asin",
45
+ "acos": "acos",
46
+ "atan": "atan",
47
+ "atan2": "atan2",
48
+ "exp": "exp",
49
+ "log": "log",
50
+ "sinh": "sinh",
51
+ "cosh": "cosh",
52
+ "tanh": "tanh",
53
+ "floor": "floor",
54
+ "ceiling": "ceil",
55
+ "sqrt": "sqrt", # To enable automatic rewrites
56
+ }
57
+
58
+ known_functions_C99 = dict(known_functions_C89, **{
59
+ 'exp2': 'exp2',
60
+ 'expm1': 'expm1',
61
+ 'log10': 'log10',
62
+ 'log2': 'log2',
63
+ 'log1p': 'log1p',
64
+ 'Cbrt': 'cbrt',
65
+ 'hypot': 'hypot',
66
+ 'fma': 'fma',
67
+ 'loggamma': 'lgamma',
68
+ 'erfc': 'erfc',
69
+ 'Max': 'fmax',
70
+ 'Min': 'fmin',
71
+ "asinh": "asinh",
72
+ "acosh": "acosh",
73
+ "atanh": "atanh",
74
+ "erf": "erf",
75
+ "gamma": "tgamma",
76
+ })
77
+
78
+ # These are the core reserved words in the C language. Taken from:
79
+ # https://en.cppreference.com/w/c/keyword
80
+
81
+ reserved_words = [
82
+ 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
83
+ 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int',
84
+ 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static',
85
+ 'struct', 'entry', # never standardized, we'll leave it here anyway
86
+ 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'
87
+ ]
88
+
89
+ reserved_words_c99 = ['inline', 'restrict']
90
+
91
+ def get_math_macros():
92
+ """ Returns a dictionary with math-related macros from math.h/cmath
93
+
94
+ Note that these macros are not strictly required by the C/C++-standard.
95
+ For MSVC they are enabled by defining "_USE_MATH_DEFINES" (preferably
96
+ via a compilation flag).
97
+
98
+ Returns
99
+ =======
100
+
101
+ Dictionary mapping SymPy expressions to strings (macro names)
102
+
103
+ """
104
+ from sympy.codegen.cfunctions import log2, Sqrt
105
+ from sympy.functions.elementary.exponential import log
106
+ from sympy.functions.elementary.miscellaneous import sqrt
107
+
108
+ return {
109
+ S.Exp1: 'M_E',
110
+ log2(S.Exp1): 'M_LOG2E',
111
+ 1/log(2): 'M_LOG2E',
112
+ log(2): 'M_LN2',
113
+ log(10): 'M_LN10',
114
+ S.Pi: 'M_PI',
115
+ S.Pi/2: 'M_PI_2',
116
+ S.Pi/4: 'M_PI_4',
117
+ 1/S.Pi: 'M_1_PI',
118
+ 2/S.Pi: 'M_2_PI',
119
+ 2/sqrt(S.Pi): 'M_2_SQRTPI',
120
+ 2/Sqrt(S.Pi): 'M_2_SQRTPI',
121
+ sqrt(2): 'M_SQRT2',
122
+ Sqrt(2): 'M_SQRT2',
123
+ 1/sqrt(2): 'M_SQRT1_2',
124
+ 1/Sqrt(2): 'M_SQRT1_2'
125
+ }
126
+
127
+
128
+ def _as_macro_if_defined(meth):
129
+ """ Decorator for printer methods
130
+
131
+ When a Printer's method is decorated using this decorator the expressions printed
132
+ will first be looked for in the attribute ``math_macros``, and if present it will
133
+ print the macro name in ``math_macros`` followed by a type suffix for the type
134
+ ``real``. e.g. printing ``sympy.pi`` would print ``M_PIl`` if real is mapped to float80.
135
+
136
+ """
137
+ @wraps(meth)
138
+ def _meth_wrapper(self, expr, **kwargs):
139
+ if expr in self.math_macros:
140
+ return '%s%s' % (self.math_macros[expr], self._get_math_macro_suffix(real))
141
+ else:
142
+ return meth(self, expr, **kwargs)
143
+
144
+ return _meth_wrapper
145
+
146
+
147
+ class C89CodePrinter(CodePrinter):
148
+ """A printer to convert Python expressions to strings of C code"""
149
+ printmethod = "_ccode"
150
+ language = "C"
151
+ standard = "C89"
152
+ reserved_words = set(reserved_words)
153
+
154
+ _default_settings: dict[str, Any] = {
155
+ 'order': None,
156
+ 'full_prec': 'auto',
157
+ 'precision': 17,
158
+ 'user_functions': {},
159
+ 'human': True,
160
+ 'allow_unknown_functions': False,
161
+ 'contract': True,
162
+ 'dereference': set(),
163
+ 'error_on_reserved': False,
164
+ 'reserved_word_suffix': '_',
165
+ }
166
+
167
+ type_aliases = {
168
+ real: float64,
169
+ complex_: complex128,
170
+ integer: intc
171
+ }
172
+
173
+ type_mappings: dict[Type, Any] = {
174
+ real: 'double',
175
+ intc: 'int',
176
+ float32: 'float',
177
+ float64: 'double',
178
+ integer: 'int',
179
+ bool_: 'bool',
180
+ int8: 'int8_t',
181
+ int16: 'int16_t',
182
+ int32: 'int32_t',
183
+ int64: 'int64_t',
184
+ uint8: 'int8_t',
185
+ uint16: 'int16_t',
186
+ uint32: 'int32_t',
187
+ uint64: 'int64_t',
188
+ }
189
+
190
+ type_headers = {
191
+ bool_: {'stdbool.h'},
192
+ int8: {'stdint.h'},
193
+ int16: {'stdint.h'},
194
+ int32: {'stdint.h'},
195
+ int64: {'stdint.h'},
196
+ uint8: {'stdint.h'},
197
+ uint16: {'stdint.h'},
198
+ uint32: {'stdint.h'},
199
+ uint64: {'stdint.h'},
200
+ }
201
+
202
+ # Macros needed to be defined when using a Type
203
+ type_macros: dict[Type, tuple[str, ...]] = {}
204
+
205
+ type_func_suffixes = {
206
+ float32: 'f',
207
+ float64: '',
208
+ float80: 'l'
209
+ }
210
+
211
+ type_literal_suffixes = {
212
+ float32: 'F',
213
+ float64: '',
214
+ float80: 'L'
215
+ }
216
+
217
+ type_math_macro_suffixes = {
218
+ float80: 'l'
219
+ }
220
+
221
+ math_macros = None
222
+
223
+ _ns = '' # namespace, C++ uses 'std::'
224
+ # known_functions-dict to copy
225
+ _kf: dict[str, Any] = known_functions_C89
226
+
227
+ def __init__(self, settings=None):
228
+ settings = settings or {}
229
+ if self.math_macros is None:
230
+ self.math_macros = settings.pop('math_macros', get_math_macros())
231
+ self.type_aliases = dict(chain(self.type_aliases.items(),
232
+ settings.pop('type_aliases', {}).items()))
233
+ self.type_mappings = dict(chain(self.type_mappings.items(),
234
+ settings.pop('type_mappings', {}).items()))
235
+ self.type_headers = dict(chain(self.type_headers.items(),
236
+ settings.pop('type_headers', {}).items()))
237
+ self.type_macros = dict(chain(self.type_macros.items(),
238
+ settings.pop('type_macros', {}).items()))
239
+ self.type_func_suffixes = dict(chain(self.type_func_suffixes.items(),
240
+ settings.pop('type_func_suffixes', {}).items()))
241
+ self.type_literal_suffixes = dict(chain(self.type_literal_suffixes.items(),
242
+ settings.pop('type_literal_suffixes', {}).items()))
243
+ self.type_math_macro_suffixes = dict(chain(self.type_math_macro_suffixes.items(),
244
+ settings.pop('type_math_macro_suffixes', {}).items()))
245
+ super().__init__(settings)
246
+ self.known_functions = dict(self._kf, **settings.get('user_functions', {}))
247
+ self._dereference = set(settings.get('dereference', []))
248
+ self.headers = set()
249
+ self.libraries = set()
250
+ self.macros = set()
251
+
252
+ def _rate_index_position(self, p):
253
+ return p*5
254
+
255
+ def _get_statement(self, codestring):
256
+ """ Get code string as a statement - i.e. ending with a semicolon. """
257
+ return codestring if codestring.endswith(';') else codestring + ';'
258
+
259
+ def _get_comment(self, text):
260
+ return "/* {} */".format(text)
261
+
262
+ def _declare_number_const(self, name, value):
263
+ type_ = self.type_aliases[real]
264
+ var = Variable(name, type=type_, value=value.evalf(type_.decimal_dig), attrs={value_const})
265
+ decl = Declaration(var)
266
+ return self._get_statement(self._print(decl))
267
+
268
+ def _format_code(self, lines):
269
+ return self.indent_code(lines)
270
+
271
+ def _traverse_matrix_indices(self, mat):
272
+ rows, cols = mat.shape
273
+ return ((i, j) for i in range(rows) for j in range(cols))
274
+
275
+ @_as_macro_if_defined
276
+ def _print_Mul(self, expr, **kwargs):
277
+ return super()._print_Mul(expr, **kwargs)
278
+
279
+ @_as_macro_if_defined
280
+ def _print_Pow(self, expr):
281
+ if "Pow" in self.known_functions:
282
+ return self._print_Function(expr)
283
+ PREC = precedence(expr)
284
+ suffix = self._get_func_suffix(real)
285
+ if equal_valued(expr.exp, -1):
286
+ literal_suffix = self._get_literal_suffix(real)
287
+ return '1.0%s/%s' % (literal_suffix, self.parenthesize(expr.base, PREC))
288
+ elif equal_valued(expr.exp, 0.5):
289
+ return '%ssqrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
290
+ elif expr.exp == S.One/3 and self.standard != 'C89':
291
+ return '%scbrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
292
+ else:
293
+ return '%spow%s(%s, %s)' % (self._ns, suffix, self._print(expr.base),
294
+ self._print(expr.exp))
295
+
296
+ def _print_Mod(self, expr):
297
+ num, den = expr.args
298
+ if num.is_integer and den.is_integer:
299
+ PREC = precedence(expr)
300
+ snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args]
301
+ # % is remainder (same sign as numerator), not modulo (same sign as
302
+ # denominator), in C. Hence, % only works as modulo if both numbers
303
+ # have the same sign
304
+ if (num.is_nonnegative and den.is_nonnegative or
305
+ num.is_nonpositive and den.is_nonpositive):
306
+ return f"{snum} % {sden}"
307
+ return f"(({snum} % {sden}) + {sden}) % {sden}"
308
+ # Not guaranteed integer
309
+ return self._print_math_func(expr, known='fmod')
310
+
311
+ def _print_Rational(self, expr):
312
+ p, q = int(expr.p), int(expr.q)
313
+ suffix = self._get_literal_suffix(real)
314
+ return '%d.0%s/%d.0%s' % (p, suffix, q, suffix)
315
+
316
+ def _print_Indexed(self, expr):
317
+ # calculate index for 1d array
318
+ offset = getattr(expr.base, 'offset', S.Zero)
319
+ strides = getattr(expr.base, 'strides', None)
320
+ indices = expr.indices
321
+
322
+ if strides is None or isinstance(strides, str):
323
+ dims = expr.shape
324
+ shift = S.One
325
+ temp = ()
326
+ if strides == 'C' or strides is None:
327
+ traversal = reversed(range(expr.rank))
328
+ indices = indices[::-1]
329
+ elif strides == 'F':
330
+ traversal = range(expr.rank)
331
+
332
+ for i in traversal:
333
+ temp += (shift,)
334
+ shift *= dims[i]
335
+ strides = temp
336
+ flat_index = sum([x[0]*x[1] for x in zip(indices, strides)]) + offset
337
+ return "%s[%s]" % (self._print(expr.base.label),
338
+ self._print(flat_index))
339
+
340
+ def _print_Idx(self, expr):
341
+ return self._print(expr.label)
342
+
343
+ @_as_macro_if_defined
344
+ def _print_NumberSymbol(self, expr):
345
+ return super()._print_NumberSymbol(expr)
346
+
347
+ def _print_Infinity(self, expr):
348
+ return 'HUGE_VAL'
349
+
350
+ def _print_NegativeInfinity(self, expr):
351
+ return '-HUGE_VAL'
352
+
353
+ def _print_Piecewise(self, expr):
354
+ if expr.args[-1].cond != True:
355
+ # We need the last conditional to be a True, otherwise the resulting
356
+ # function may not return a result.
357
+ raise ValueError("All Piecewise expressions must contain an "
358
+ "(expr, True) statement to be used as a default "
359
+ "condition. Without one, the generated "
360
+ "expression may not evaluate to anything under "
361
+ "some condition.")
362
+ lines = []
363
+ if expr.has(Assignment):
364
+ for i, (e, c) in enumerate(expr.args):
365
+ if i == 0:
366
+ lines.append("if (%s) {" % self._print(c))
367
+ elif i == len(expr.args) - 1 and c == True:
368
+ lines.append("else {")
369
+ else:
370
+ lines.append("else if (%s) {" % self._print(c))
371
+ code0 = self._print(e)
372
+ lines.append(code0)
373
+ lines.append("}")
374
+ return "\n".join(lines)
375
+ else:
376
+ # The piecewise was used in an expression, need to do inline
377
+ # operators. This has the downside that inline operators will
378
+ # not work for statements that span multiple lines (Matrix or
379
+ # Indexed expressions).
380
+ ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c),
381
+ self._print(e))
382
+ for e, c in expr.args[:-1]]
383
+ last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
384
+ return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
385
+
386
+ def _print_ITE(self, expr):
387
+ from sympy.functions import Piecewise
388
+ return self._print(expr.rewrite(Piecewise, deep=False))
389
+
390
+ def _print_MatrixElement(self, expr):
391
+ return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"],
392
+ strict=True), expr.j + expr.i*expr.parent.shape[1])
393
+
394
+ def _print_Symbol(self, expr):
395
+ name = super()._print_Symbol(expr)
396
+ if expr in self._settings['dereference']:
397
+ return '(*{})'.format(name)
398
+ else:
399
+ return name
400
+
401
+ def _print_Relational(self, expr):
402
+ lhs_code = self._print(expr.lhs)
403
+ rhs_code = self._print(expr.rhs)
404
+ op = expr.rel_op
405
+ return "{} {} {}".format(lhs_code, op, rhs_code)
406
+
407
+ def _print_For(self, expr):
408
+ target = self._print(expr.target)
409
+ if isinstance(expr.iterable, Range):
410
+ start, stop, step = expr.iterable.args
411
+ else:
412
+ raise NotImplementedError("Only iterable currently supported is Range")
413
+ body = self._print(expr.body)
414
+ return ('for ({target} = {start}; {target} < {stop}; {target} += '
415
+ '{step}) {{\n{body}\n}}').format(target=target, start=start,
416
+ stop=stop, step=step, body=body)
417
+
418
+ def _print_sign(self, func):
419
+ return '((({0}) > 0) - (({0}) < 0))'.format(self._print(func.args[0]))
420
+
421
+ def _print_Max(self, expr):
422
+ if "Max" in self.known_functions:
423
+ return self._print_Function(expr)
424
+ def inner_print_max(args): # The more natural abstraction of creating
425
+ if len(args) == 1: # and printing smaller Max objects is slow
426
+ return self._print(args[0]) # when there are many arguments.
427
+ half = len(args) // 2
428
+ return "((%(a)s > %(b)s) ? %(a)s : %(b)s)" % {
429
+ 'a': inner_print_max(args[:half]),
430
+ 'b': inner_print_max(args[half:])
431
+ }
432
+ return inner_print_max(expr.args)
433
+
434
+ def _print_Min(self, expr):
435
+ if "Min" in self.known_functions:
436
+ return self._print_Function(expr)
437
+ def inner_print_min(args): # The more natural abstraction of creating
438
+ if len(args) == 1: # and printing smaller Min objects is slow
439
+ return self._print(args[0]) # when there are many arguments.
440
+ half = len(args) // 2
441
+ return "((%(a)s < %(b)s) ? %(a)s : %(b)s)" % {
442
+ 'a': inner_print_min(args[:half]),
443
+ 'b': inner_print_min(args[half:])
444
+ }
445
+ return inner_print_min(expr.args)
446
+
447
+ def indent_code(self, code):
448
+ """Accepts a string of code or a list of code lines"""
449
+
450
+ if isinstance(code, str):
451
+ code_lines = self.indent_code(code.splitlines(True))
452
+ return ''.join(code_lines)
453
+
454
+ tab = " "
455
+ inc_token = ('{', '(', '{\n', '(\n')
456
+ dec_token = ('}', ')')
457
+
458
+ code = [line.lstrip(' \t') for line in code]
459
+
460
+ increase = [int(any(map(line.endswith, inc_token))) for line in code]
461
+ decrease = [int(any(map(line.startswith, dec_token))) for line in code]
462
+
463
+ pretty = []
464
+ level = 0
465
+ for n, line in enumerate(code):
466
+ if line in ('', '\n'):
467
+ pretty.append(line)
468
+ continue
469
+ level -= decrease[n]
470
+ pretty.append("%s%s" % (tab*level, line))
471
+ level += increase[n]
472
+ return pretty
473
+
474
+ def _get_func_suffix(self, type_):
475
+ return self.type_func_suffixes[self.type_aliases.get(type_, type_)]
476
+
477
+ def _get_literal_suffix(self, type_):
478
+ return self.type_literal_suffixes[self.type_aliases.get(type_, type_)]
479
+
480
+ def _get_math_macro_suffix(self, type_):
481
+ alias = self.type_aliases.get(type_, type_)
482
+ dflt = self.type_math_macro_suffixes.get(alias, '')
483
+ return self.type_math_macro_suffixes.get(type_, dflt)
484
+
485
+ def _print_Tuple(self, expr):
486
+ return '{'+', '.join(self._print(e) for e in expr)+'}'
487
+
488
+ _print_List = _print_Tuple
489
+
490
+ def _print_Type(self, type_):
491
+ self.headers.update(self.type_headers.get(type_, set()))
492
+ self.macros.update(self.type_macros.get(type_, set()))
493
+ return self._print(self.type_mappings.get(type_, type_.name))
494
+
495
+ def _print_Declaration(self, decl):
496
+ from sympy.codegen.cnodes import restrict
497
+ var = decl.variable
498
+ val = var.value
499
+ if var.type == untyped:
500
+ raise ValueError("C does not support untyped variables")
501
+
502
+ if isinstance(var, Pointer):
503
+ result = '{vc}{t} *{pc} {r}{s}'.format(
504
+ vc='const ' if value_const in var.attrs else '',
505
+ t=self._print(var.type),
506
+ pc=' const' if pointer_const in var.attrs else '',
507
+ r='restrict ' if restrict in var.attrs else '',
508
+ s=self._print(var.symbol)
509
+ )
510
+ elif isinstance(var, Variable):
511
+ result = '{vc}{t} {s}'.format(
512
+ vc='const ' if value_const in var.attrs else '',
513
+ t=self._print(var.type),
514
+ s=self._print(var.symbol)
515
+ )
516
+ else:
517
+ raise NotImplementedError("Unknown type of var: %s" % type(var))
518
+ if val != None: # Must be "!= None", cannot be "is not None"
519
+ result += ' = %s' % self._print(val)
520
+ return result
521
+
522
+ def _print_Float(self, flt):
523
+ type_ = self.type_aliases.get(real, real)
524
+ self.macros.update(self.type_macros.get(type_, set()))
525
+ suffix = self._get_literal_suffix(type_)
526
+ num = str(flt.evalf(type_.decimal_dig))
527
+ if 'e' not in num and '.' not in num:
528
+ num += '.0'
529
+ num_parts = num.split('e')
530
+ num_parts[0] = num_parts[0].rstrip('0')
531
+ if num_parts[0].endswith('.'):
532
+ num_parts[0] += '0'
533
+ return 'e'.join(num_parts) + suffix
534
+
535
+ @requires(headers={'stdbool.h'})
536
+ def _print_BooleanTrue(self, expr):
537
+ return 'true'
538
+
539
+ @requires(headers={'stdbool.h'})
540
+ def _print_BooleanFalse(self, expr):
541
+ return 'false'
542
+
543
+ def _print_Element(self, elem):
544
+ if elem.strides == None: # Must be "== None", cannot be "is None"
545
+ if elem.offset != None: # Must be "!= None", cannot be "is not None"
546
+ raise ValueError("Expected strides when offset is given")
547
+ idxs = ']['.join((self._print(arg) for arg in elem.indices))
548
+ else:
549
+ global_idx = sum([i*s for i, s in zip(elem.indices, elem.strides)])
550
+ if elem.offset != None: # Must be "!= None", cannot be "is not None"
551
+ global_idx += elem.offset
552
+ idxs = self._print(global_idx)
553
+
554
+ return "{symb}[{idxs}]".format(
555
+ symb=self._print(elem.symbol),
556
+ idxs=idxs
557
+ )
558
+
559
+ def _print_CodeBlock(self, expr):
560
+ """ Elements of code blocks printed as statements. """
561
+ return '\n'.join([self._get_statement(self._print(i)) for i in expr.args])
562
+
563
+ def _print_While(self, expr):
564
+ return 'while ({condition}) {{\n{body}\n}}'.format(**expr.kwargs(
565
+ apply=lambda arg: self._print(arg)))
566
+
567
+ def _print_Scope(self, expr):
568
+ return '{\n%s\n}' % self._print_CodeBlock(expr.body)
569
+
570
+ @requires(headers={'stdio.h'})
571
+ def _print_Print(self, expr):
572
+ return 'printf({fmt}, {pargs})'.format(
573
+ fmt=self._print(expr.format_string),
574
+ pargs=', '.join((self._print(arg) for arg in expr.print_args))
575
+ )
576
+
577
+ def _print_FunctionPrototype(self, expr):
578
+ pars = ', '.join((self._print(Declaration(arg)) for arg in expr.parameters))
579
+ return "%s %s(%s)" % (
580
+ tuple((self._print(arg) for arg in (expr.return_type, expr.name))) + (pars,)
581
+ )
582
+
583
+ def _print_FunctionDefinition(self, expr):
584
+ return "%s%s" % (self._print_FunctionPrototype(expr),
585
+ self._print_Scope(expr))
586
+
587
+ def _print_Return(self, expr):
588
+ arg, = expr.args
589
+ return 'return %s' % self._print(arg)
590
+
591
+ def _print_CommaOperator(self, expr):
592
+ return '(%s)' % ', '.join((self._print(arg) for arg in expr.args))
593
+
594
+ def _print_Label(self, expr):
595
+ if expr.body == none:
596
+ return '%s:' % str(expr.name)
597
+ if len(expr.body.args) == 1:
598
+ return '%s:\n%s' % (str(expr.name), self._print_CodeBlock(expr.body))
599
+ return '%s:\n{\n%s\n}' % (str(expr.name), self._print_CodeBlock(expr.body))
600
+
601
+ def _print_goto(self, expr):
602
+ return 'goto %s' % expr.label.name
603
+
604
+ def _print_PreIncrement(self, expr):
605
+ arg, = expr.args
606
+ return '++(%s)' % self._print(arg)
607
+
608
+ def _print_PostIncrement(self, expr):
609
+ arg, = expr.args
610
+ return '(%s)++' % self._print(arg)
611
+
612
+ def _print_PreDecrement(self, expr):
613
+ arg, = expr.args
614
+ return '--(%s)' % self._print(arg)
615
+
616
+ def _print_PostDecrement(self, expr):
617
+ arg, = expr.args
618
+ return '(%s)--' % self._print(arg)
619
+
620
+ def _print_struct(self, expr):
621
+ return "%(keyword)s %(name)s {\n%(lines)s}" % {
622
+ "keyword": expr.__class__.__name__, "name": expr.name, "lines": ';\n'.join(
623
+ [self._print(decl) for decl in expr.declarations] + [''])
624
+ }
625
+
626
+ def _print_BreakToken(self, _):
627
+ return 'break'
628
+
629
+ def _print_ContinueToken(self, _):
630
+ return 'continue'
631
+
632
+ _print_union = _print_struct
633
+
634
+ class C99CodePrinter(C89CodePrinter):
635
+ standard = 'C99'
636
+ reserved_words = set(reserved_words + reserved_words_c99)
637
+ type_mappings=dict(chain(C89CodePrinter.type_mappings.items(), {
638
+ complex64: 'float complex',
639
+ complex128: 'double complex',
640
+ }.items()))
641
+ type_headers = dict(chain(C89CodePrinter.type_headers.items(), {
642
+ complex64: {'complex.h'},
643
+ complex128: {'complex.h'}
644
+ }.items()))
645
+
646
+ # known_functions-dict to copy
647
+ _kf: dict[str, Any] = known_functions_C99
648
+
649
+ # functions with versions with 'f' and 'l' suffixes:
650
+ _prec_funcs = ('fabs fmod remainder remquo fma fmax fmin fdim nan exp exp2'
651
+ ' expm1 log log10 log2 log1p pow sqrt cbrt hypot sin cos tan'
652
+ ' asin acos atan atan2 sinh cosh tanh asinh acosh atanh erf'
653
+ ' erfc tgamma lgamma ceil floor trunc round nearbyint rint'
654
+ ' frexp ldexp modf scalbn ilogb logb nextafter copysign').split()
655
+
656
+ def _print_Infinity(self, expr):
657
+ return 'INFINITY'
658
+
659
+ def _print_NegativeInfinity(self, expr):
660
+ return '-INFINITY'
661
+
662
+ def _print_NaN(self, expr):
663
+ return 'NAN'
664
+
665
+ # tgamma was already covered by 'known_functions' dict
666
+
667
+ @requires(headers={'math.h'}, libraries={'m'})
668
+ @_as_macro_if_defined
669
+ def _print_math_func(self, expr, nest=False, known=None):
670
+ if known is None:
671
+ known = self.known_functions[expr.__class__.__name__]
672
+ if not isinstance(known, str):
673
+ for cb, name in known:
674
+ if cb(*expr.args):
675
+ known = name
676
+ break
677
+ else:
678
+ raise ValueError("No matching printer")
679
+ try:
680
+ return known(self, *expr.args)
681
+ except TypeError:
682
+ suffix = self._get_func_suffix(real) if self._ns + known in self._prec_funcs else ''
683
+
684
+ if nest:
685
+ args = self._print(expr.args[0])
686
+ if len(expr.args) > 1:
687
+ paren_pile = ''
688
+ for curr_arg in expr.args[1:-1]:
689
+ paren_pile += ')'
690
+ args += ', {ns}{name}{suffix}({next}'.format(
691
+ ns=self._ns,
692
+ name=known,
693
+ suffix=suffix,
694
+ next = self._print(curr_arg)
695
+ )
696
+ args += ', %s%s' % (
697
+ self._print(expr.func(expr.args[-1])),
698
+ paren_pile
699
+ )
700
+ else:
701
+ args = ', '.join((self._print(arg) for arg in expr.args))
702
+ return '{ns}{name}{suffix}({args})'.format(
703
+ ns=self._ns,
704
+ name=known,
705
+ suffix=suffix,
706
+ args=args
707
+ )
708
+
709
+ def _print_Max(self, expr):
710
+ return self._print_math_func(expr, nest=True)
711
+
712
+ def _print_Min(self, expr):
713
+ return self._print_math_func(expr, nest=True)
714
+
715
+ def _get_loop_opening_ending(self, indices):
716
+ open_lines = []
717
+ close_lines = []
718
+ loopstart = "for (int %(var)s=%(start)s; %(var)s<%(end)s; %(var)s++){" # C99
719
+ for i in indices:
720
+ # C arrays start at 0 and end at dimension-1
721
+ open_lines.append(loopstart % {
722
+ 'var': self._print(i.label),
723
+ 'start': self._print(i.lower),
724
+ 'end': self._print(i.upper + 1)})
725
+ close_lines.append("}")
726
+ return open_lines, close_lines
727
+
728
+
729
+ for k in ('Abs Sqrt exp exp2 expm1 log log10 log2 log1p Cbrt hypot fma'
730
+ ' loggamma sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh '
731
+ 'atanh erf erfc loggamma gamma ceiling floor').split():
732
+ setattr(C99CodePrinter, '_print_%s' % k, C99CodePrinter._print_math_func)
733
+
734
+
735
+ class C11CodePrinter(C99CodePrinter):
736
+
737
+ @requires(headers={'stdalign.h'})
738
+ def _print_alignof(self, expr):
739
+ arg, = expr.args
740
+ return 'alignof(%s)' % self._print(arg)
741
+
742
+
743
+ c_code_printers = {
744
+ 'c89': C89CodePrinter,
745
+ 'c99': C99CodePrinter,
746
+ 'c11': C11CodePrinter
747
+ }
llmeval-env/lib/python3.10/site-packages/sympy/printing/codeprinter.py ADDED
@@ -0,0 +1,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Any
3
+
4
+ from functools import wraps
5
+
6
+ from sympy.core import Add, Mul, Pow, S, sympify, Float
7
+ from sympy.core.basic import Basic
8
+ from sympy.core.expr import UnevaluatedExpr
9
+ from sympy.core.function import Lambda
10
+ from sympy.core.mul import _keep_coeff
11
+ from sympy.core.sorting import default_sort_key
12
+ from sympy.core.symbol import Symbol
13
+ from sympy.functions.elementary.complexes import re
14
+ from sympy.printing.str import StrPrinter
15
+ from sympy.printing.precedence import precedence, PRECEDENCE
16
+
17
+
18
+ class requires:
19
+ """ Decorator for registering requirements on print methods. """
20
+ def __init__(self, **kwargs):
21
+ self._req = kwargs
22
+
23
+ def __call__(self, method):
24
+ def _method_wrapper(self_, *args, **kwargs):
25
+ for k, v in self._req.items():
26
+ getattr(self_, k).update(v)
27
+ return method(self_, *args, **kwargs)
28
+ return wraps(method)(_method_wrapper)
29
+
30
+
31
+ class AssignmentError(Exception):
32
+ """
33
+ Raised if an assignment variable for a loop is missing.
34
+ """
35
+ pass
36
+
37
+
38
+ def _convert_python_lists(arg):
39
+ if isinstance(arg, list):
40
+ from sympy.codegen.abstract_nodes import List
41
+ return List(*(_convert_python_lists(e) for e in arg))
42
+ elif isinstance(arg, tuple):
43
+ return tuple(_convert_python_lists(e) for e in arg)
44
+ else:
45
+ return arg
46
+
47
+
48
+ class CodePrinter(StrPrinter):
49
+ """
50
+ The base class for code-printing subclasses.
51
+ """
52
+
53
+ _operators = {
54
+ 'and': '&&',
55
+ 'or': '||',
56
+ 'not': '!',
57
+ }
58
+
59
+ _default_settings: dict[str, Any] = {
60
+ 'order': None,
61
+ 'full_prec': 'auto',
62
+ 'error_on_reserved': False,
63
+ 'reserved_word_suffix': '_',
64
+ 'human': True,
65
+ 'inline': False,
66
+ 'allow_unknown_functions': False,
67
+ }
68
+
69
+ # Functions which are "simple" to rewrite to other functions that
70
+ # may be supported
71
+ # function_to_rewrite : (function_to_rewrite_to, iterable_with_other_functions_required)
72
+ _rewriteable_functions = {
73
+ 'cot': ('tan', []),
74
+ 'csc': ('sin', []),
75
+ 'sec': ('cos', []),
76
+ 'acot': ('atan', []),
77
+ 'acsc': ('asin', []),
78
+ 'asec': ('acos', []),
79
+ 'coth': ('exp', []),
80
+ 'csch': ('exp', []),
81
+ 'sech': ('exp', []),
82
+ 'acoth': ('log', []),
83
+ 'acsch': ('log', []),
84
+ 'asech': ('log', []),
85
+ 'catalan': ('gamma', []),
86
+ 'fibonacci': ('sqrt', []),
87
+ 'lucas': ('sqrt', []),
88
+ 'beta': ('gamma', []),
89
+ 'sinc': ('sin', ['Piecewise']),
90
+ 'Mod': ('floor', []),
91
+ 'factorial': ('gamma', []),
92
+ 'factorial2': ('gamma', ['Piecewise']),
93
+ 'subfactorial': ('uppergamma', []),
94
+ 'RisingFactorial': ('gamma', ['Piecewise']),
95
+ 'FallingFactorial': ('gamma', ['Piecewise']),
96
+ 'binomial': ('gamma', []),
97
+ 'frac': ('floor', []),
98
+ 'Max': ('Piecewise', []),
99
+ 'Min': ('Piecewise', []),
100
+ 'Heaviside': ('Piecewise', []),
101
+ 'erf2': ('erf', []),
102
+ 'erfc': ('erf', []),
103
+ 'Li': ('li', []),
104
+ 'Ei': ('li', []),
105
+ 'dirichlet_eta': ('zeta', []),
106
+ 'riemann_xi': ('zeta', ['gamma']),
107
+ }
108
+
109
+ def __init__(self, settings=None):
110
+
111
+ super().__init__(settings=settings)
112
+ if not hasattr(self, 'reserved_words'):
113
+ self.reserved_words = set()
114
+
115
+ def _handle_UnevaluatedExpr(self, expr):
116
+ return expr.replace(re, lambda arg: arg if isinstance(
117
+ arg, UnevaluatedExpr) and arg.args[0].is_real else re(arg))
118
+
119
+ def doprint(self, expr, assign_to=None):
120
+ """
121
+ Print the expression as code.
122
+
123
+ Parameters
124
+ ----------
125
+ expr : Expression
126
+ The expression to be printed.
127
+
128
+ assign_to : Symbol, string, MatrixSymbol, list of strings or Symbols (optional)
129
+ If provided, the printed code will set the expression to a variable or multiple variables
130
+ with the name or names given in ``assign_to``.
131
+ """
132
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
133
+ from sympy.codegen.ast import CodeBlock, Assignment
134
+
135
+ def _handle_assign_to(expr, assign_to):
136
+ if assign_to is None:
137
+ return sympify(expr)
138
+ if isinstance(assign_to, (list, tuple)):
139
+ if len(expr) != len(assign_to):
140
+ raise ValueError('Failed to assign an expression of length {} to {} variables'.format(len(expr), len(assign_to)))
141
+ return CodeBlock(*[_handle_assign_to(lhs, rhs) for lhs, rhs in zip(expr, assign_to)])
142
+ if isinstance(assign_to, str):
143
+ if expr.is_Matrix:
144
+ assign_to = MatrixSymbol(assign_to, *expr.shape)
145
+ else:
146
+ assign_to = Symbol(assign_to)
147
+ elif not isinstance(assign_to, Basic):
148
+ raise TypeError("{} cannot assign to object of type {}".format(
149
+ type(self).__name__, type(assign_to)))
150
+ return Assignment(assign_to, expr)
151
+
152
+ expr = _convert_python_lists(expr)
153
+ expr = _handle_assign_to(expr, assign_to)
154
+
155
+ # Remove re(...) nodes due to UnevaluatedExpr.is_real always is None:
156
+ expr = self._handle_UnevaluatedExpr(expr)
157
+
158
+ # keep a set of expressions that are not strictly translatable to Code
159
+ # and number constants that must be declared and initialized
160
+ self._not_supported = set()
161
+ self._number_symbols = set()
162
+
163
+ lines = self._print(expr).splitlines()
164
+
165
+ # format the output
166
+ if self._settings["human"]:
167
+ frontlines = []
168
+ if self._not_supported:
169
+ frontlines.append(self._get_comment(
170
+ "Not supported in {}:".format(self.language)))
171
+ for expr in sorted(self._not_supported, key=str):
172
+ frontlines.append(self._get_comment(type(expr).__name__))
173
+ for name, value in sorted(self._number_symbols, key=str):
174
+ frontlines.append(self._declare_number_const(name, value))
175
+ lines = frontlines + lines
176
+ lines = self._format_code(lines)
177
+ result = "\n".join(lines)
178
+ else:
179
+ lines = self._format_code(lines)
180
+ num_syms = {(k, self._print(v)) for k, v in self._number_symbols}
181
+ result = (num_syms, self._not_supported, "\n".join(lines))
182
+ self._not_supported = set()
183
+ self._number_symbols = set()
184
+ return result
185
+
186
+ def _doprint_loops(self, expr, assign_to=None):
187
+ # Here we print an expression that contains Indexed objects, they
188
+ # correspond to arrays in the generated code. The low-level implementation
189
+ # involves looping over array elements and possibly storing results in temporary
190
+ # variables or accumulate it in the assign_to object.
191
+
192
+ if self._settings.get('contract', True):
193
+ from sympy.tensor import get_contraction_structure
194
+ # Setup loops over non-dummy indices -- all terms need these
195
+ indices = self._get_expression_indices(expr, assign_to)
196
+ # Setup loops over dummy indices -- each term needs separate treatment
197
+ dummies = get_contraction_structure(expr)
198
+ else:
199
+ indices = []
200
+ dummies = {None: (expr,)}
201
+ openloop, closeloop = self._get_loop_opening_ending(indices)
202
+
203
+ # terms with no summations first
204
+ if None in dummies:
205
+ text = StrPrinter.doprint(self, Add(*dummies[None]))
206
+ else:
207
+ # If all terms have summations we must initialize array to Zero
208
+ text = StrPrinter.doprint(self, 0)
209
+
210
+ # skip redundant assignments (where lhs == rhs)
211
+ lhs_printed = self._print(assign_to)
212
+ lines = []
213
+ if text != lhs_printed:
214
+ lines.extend(openloop)
215
+ if assign_to is not None:
216
+ text = self._get_statement("%s = %s" % (lhs_printed, text))
217
+ lines.append(text)
218
+ lines.extend(closeloop)
219
+
220
+ # then terms with summations
221
+ for d in dummies:
222
+ if isinstance(d, tuple):
223
+ indices = self._sort_optimized(d, expr)
224
+ openloop_d, closeloop_d = self._get_loop_opening_ending(
225
+ indices)
226
+
227
+ for term in dummies[d]:
228
+ if term in dummies and not ([list(f.keys()) for f in dummies[term]]
229
+ == [[None] for f in dummies[term]]):
230
+ # If one factor in the term has it's own internal
231
+ # contractions, those must be computed first.
232
+ # (temporary variables?)
233
+ raise NotImplementedError(
234
+ "FIXME: no support for contractions in factor yet")
235
+ else:
236
+
237
+ # We need the lhs expression as an accumulator for
238
+ # the loops, i.e
239
+ #
240
+ # for (int d=0; d < dim; d++){
241
+ # lhs[] = lhs[] + term[][d]
242
+ # } ^.................. the accumulator
243
+ #
244
+ # We check if the expression already contains the
245
+ # lhs, and raise an exception if it does, as that
246
+ # syntax is currently undefined. FIXME: What would be
247
+ # a good interpretation?
248
+ if assign_to is None:
249
+ raise AssignmentError(
250
+ "need assignment variable for loops")
251
+ if term.has(assign_to):
252
+ raise ValueError("FIXME: lhs present in rhs,\
253
+ this is undefined in CodePrinter")
254
+
255
+ lines.extend(openloop)
256
+ lines.extend(openloop_d)
257
+ text = "%s = %s" % (lhs_printed, StrPrinter.doprint(
258
+ self, assign_to + term))
259
+ lines.append(self._get_statement(text))
260
+ lines.extend(closeloop_d)
261
+ lines.extend(closeloop)
262
+
263
+ return "\n".join(lines)
264
+
265
+ def _get_expression_indices(self, expr, assign_to):
266
+ from sympy.tensor import get_indices
267
+ rinds, junk = get_indices(expr)
268
+ linds, junk = get_indices(assign_to)
269
+
270
+ # support broadcast of scalar
271
+ if linds and not rinds:
272
+ rinds = linds
273
+ if rinds != linds:
274
+ raise ValueError("lhs indices must match non-dummy"
275
+ " rhs indices in %s" % expr)
276
+
277
+ return self._sort_optimized(rinds, assign_to)
278
+
279
+ def _sort_optimized(self, indices, expr):
280
+
281
+ from sympy.tensor.indexed import Indexed
282
+
283
+ if not indices:
284
+ return []
285
+
286
+ # determine optimized loop order by giving a score to each index
287
+ # the index with the highest score are put in the innermost loop.
288
+ score_table = {}
289
+ for i in indices:
290
+ score_table[i] = 0
291
+
292
+ arrays = expr.atoms(Indexed)
293
+ for arr in arrays:
294
+ for p, ind in enumerate(arr.indices):
295
+ try:
296
+ score_table[ind] += self._rate_index_position(p)
297
+ except KeyError:
298
+ pass
299
+
300
+ return sorted(indices, key=lambda x: score_table[x])
301
+
302
+ def _rate_index_position(self, p):
303
+ """function to calculate score based on position among indices
304
+
305
+ This method is used to sort loops in an optimized order, see
306
+ CodePrinter._sort_optimized()
307
+ """
308
+ raise NotImplementedError("This function must be implemented by "
309
+ "subclass of CodePrinter.")
310
+
311
+ def _get_statement(self, codestring):
312
+ """Formats a codestring with the proper line ending."""
313
+ raise NotImplementedError("This function must be implemented by "
314
+ "subclass of CodePrinter.")
315
+
316
+ def _get_comment(self, text):
317
+ """Formats a text string as a comment."""
318
+ raise NotImplementedError("This function must be implemented by "
319
+ "subclass of CodePrinter.")
320
+
321
+ def _declare_number_const(self, name, value):
322
+ """Declare a numeric constant at the top of a function"""
323
+ raise NotImplementedError("This function must be implemented by "
324
+ "subclass of CodePrinter.")
325
+
326
+ def _format_code(self, lines):
327
+ """Take in a list of lines of code, and format them accordingly.
328
+
329
+ This may include indenting, wrapping long lines, etc..."""
330
+ raise NotImplementedError("This function must be implemented by "
331
+ "subclass of CodePrinter.")
332
+
333
+ def _get_loop_opening_ending(self, indices):
334
+ """Returns a tuple (open_lines, close_lines) containing lists
335
+ of codelines"""
336
+ raise NotImplementedError("This function must be implemented by "
337
+ "subclass of CodePrinter.")
338
+
339
+ def _print_Dummy(self, expr):
340
+ if expr.name.startswith('Dummy_'):
341
+ return '_' + expr.name
342
+ else:
343
+ return '%s_%d' % (expr.name, expr.dummy_index)
344
+
345
+ def _print_CodeBlock(self, expr):
346
+ return '\n'.join([self._print(i) for i in expr.args])
347
+
348
+ def _print_String(self, string):
349
+ return str(string)
350
+
351
+ def _print_QuotedString(self, arg):
352
+ return '"%s"' % arg.text
353
+
354
+ def _print_Comment(self, string):
355
+ return self._get_comment(str(string))
356
+
357
+ def _print_Assignment(self, expr):
358
+ from sympy.codegen.ast import Assignment
359
+ from sympy.functions.elementary.piecewise import Piecewise
360
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
361
+ from sympy.tensor.indexed import IndexedBase
362
+ lhs = expr.lhs
363
+ rhs = expr.rhs
364
+ # We special case assignments that take multiple lines
365
+ if isinstance(expr.rhs, Piecewise):
366
+ # Here we modify Piecewise so each expression is now
367
+ # an Assignment, and then continue on the print.
368
+ expressions = []
369
+ conditions = []
370
+ for (e, c) in rhs.args:
371
+ expressions.append(Assignment(lhs, e))
372
+ conditions.append(c)
373
+ temp = Piecewise(*zip(expressions, conditions))
374
+ return self._print(temp)
375
+ elif isinstance(lhs, MatrixSymbol):
376
+ # Here we form an Assignment for each element in the array,
377
+ # printing each one.
378
+ lines = []
379
+ for (i, j) in self._traverse_matrix_indices(lhs):
380
+ temp = Assignment(lhs[i, j], rhs[i, j])
381
+ code0 = self._print(temp)
382
+ lines.append(code0)
383
+ return "\n".join(lines)
384
+ elif self._settings.get("contract", False) and (lhs.has(IndexedBase) or
385
+ rhs.has(IndexedBase)):
386
+ # Here we check if there is looping to be done, and if so
387
+ # print the required loops.
388
+ return self._doprint_loops(rhs, lhs)
389
+ else:
390
+ lhs_code = self._print(lhs)
391
+ rhs_code = self._print(rhs)
392
+ return self._get_statement("%s = %s" % (lhs_code, rhs_code))
393
+
394
+ def _print_AugmentedAssignment(self, expr):
395
+ lhs_code = self._print(expr.lhs)
396
+ rhs_code = self._print(expr.rhs)
397
+ return self._get_statement("{} {} {}".format(
398
+ *(self._print(arg) for arg in [lhs_code, expr.op, rhs_code])))
399
+
400
+ def _print_FunctionCall(self, expr):
401
+ return '%s(%s)' % (
402
+ expr.name,
403
+ ', '.join((self._print(arg) for arg in expr.function_args)))
404
+
405
+ def _print_Variable(self, expr):
406
+ return self._print(expr.symbol)
407
+
408
+ def _print_Symbol(self, expr):
409
+
410
+ name = super()._print_Symbol(expr)
411
+
412
+ if name in self.reserved_words:
413
+ if self._settings['error_on_reserved']:
414
+ msg = ('This expression includes the symbol "{}" which is a '
415
+ 'reserved keyword in this language.')
416
+ raise ValueError(msg.format(name))
417
+ return name + self._settings['reserved_word_suffix']
418
+ else:
419
+ return name
420
+
421
+ def _can_print(self, name):
422
+ """ Check if function ``name`` is either a known function or has its own
423
+ printing method. Used to check if rewriting is possible."""
424
+ return name in self.known_functions or getattr(self, '_print_{}'.format(name), False)
425
+
426
+ def _print_Function(self, expr):
427
+ if expr.func.__name__ in self.known_functions:
428
+ cond_func = self.known_functions[expr.func.__name__]
429
+ if isinstance(cond_func, str):
430
+ return "%s(%s)" % (cond_func, self.stringify(expr.args, ", "))
431
+ else:
432
+ for cond, func in cond_func:
433
+ if cond(*expr.args):
434
+ break
435
+ if func is not None:
436
+ try:
437
+ return func(*[self.parenthesize(item, 0) for item in expr.args])
438
+ except TypeError:
439
+ return "%s(%s)" % (func, self.stringify(expr.args, ", "))
440
+ elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda):
441
+ # inlined function
442
+ return self._print(expr._imp_(*expr.args))
443
+ elif expr.func.__name__ in self._rewriteable_functions:
444
+ # Simple rewrite to supported function possible
445
+ target_f, required_fs = self._rewriteable_functions[expr.func.__name__]
446
+ if self._can_print(target_f) and all(self._can_print(f) for f in required_fs):
447
+ return self._print(expr.rewrite(target_f))
448
+ if expr.is_Function and self._settings.get('allow_unknown_functions', False):
449
+ return '%s(%s)' % (self._print(expr.func), ', '.join(map(self._print, expr.args)))
450
+ else:
451
+ return self._print_not_supported(expr)
452
+
453
+ _print_Expr = _print_Function
454
+
455
+ # Don't inherit the str-printer method for Heaviside to the code printers
456
+ _print_Heaviside = None
457
+
458
+ def _print_NumberSymbol(self, expr):
459
+ if self._settings.get("inline", False):
460
+ return self._print(Float(expr.evalf(self._settings["precision"])))
461
+ else:
462
+ # A Number symbol that is not implemented here or with _printmethod
463
+ # is registered and evaluated
464
+ self._number_symbols.add((expr,
465
+ Float(expr.evalf(self._settings["precision"]))))
466
+ return str(expr)
467
+
468
+ def _print_Catalan(self, expr):
469
+ return self._print_NumberSymbol(expr)
470
+ def _print_EulerGamma(self, expr):
471
+ return self._print_NumberSymbol(expr)
472
+ def _print_GoldenRatio(self, expr):
473
+ return self._print_NumberSymbol(expr)
474
+ def _print_TribonacciConstant(self, expr):
475
+ return self._print_NumberSymbol(expr)
476
+ def _print_Exp1(self, expr):
477
+ return self._print_NumberSymbol(expr)
478
+ def _print_Pi(self, expr):
479
+ return self._print_NumberSymbol(expr)
480
+
481
+ def _print_And(self, expr):
482
+ PREC = precedence(expr)
483
+ return (" %s " % self._operators['and']).join(self.parenthesize(a, PREC)
484
+ for a in sorted(expr.args, key=default_sort_key))
485
+
486
+ def _print_Or(self, expr):
487
+ PREC = precedence(expr)
488
+ return (" %s " % self._operators['or']).join(self.parenthesize(a, PREC)
489
+ for a in sorted(expr.args, key=default_sort_key))
490
+
491
+ def _print_Xor(self, expr):
492
+ if self._operators.get('xor') is None:
493
+ return self._print(expr.to_nnf())
494
+ PREC = precedence(expr)
495
+ return (" %s " % self._operators['xor']).join(self.parenthesize(a, PREC)
496
+ for a in expr.args)
497
+
498
+ def _print_Equivalent(self, expr):
499
+ if self._operators.get('equivalent') is None:
500
+ return self._print(expr.to_nnf())
501
+ PREC = precedence(expr)
502
+ return (" %s " % self._operators['equivalent']).join(self.parenthesize(a, PREC)
503
+ for a in expr.args)
504
+
505
+ def _print_Not(self, expr):
506
+ PREC = precedence(expr)
507
+ return self._operators['not'] + self.parenthesize(expr.args[0], PREC)
508
+
509
+ def _print_BooleanFunction(self, expr):
510
+ return self._print(expr.to_nnf())
511
+
512
+ def _print_Mul(self, expr):
513
+
514
+ prec = precedence(expr)
515
+
516
+ c, e = expr.as_coeff_Mul()
517
+ if c < 0:
518
+ expr = _keep_coeff(-c, e)
519
+ sign = "-"
520
+ else:
521
+ sign = ""
522
+
523
+ a = [] # items in the numerator
524
+ b = [] # items that are in the denominator (if any)
525
+
526
+ pow_paren = [] # Will collect all pow with more than one base element and exp = -1
527
+
528
+ if self.order not in ('old', 'none'):
529
+ args = expr.as_ordered_factors()
530
+ else:
531
+ # use make_args in case expr was something like -x -> x
532
+ args = Mul.make_args(expr)
533
+
534
+ # Gather args for numerator/denominator
535
+ for item in args:
536
+ if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
537
+ if item.exp != -1:
538
+ b.append(Pow(item.base, -item.exp, evaluate=False))
539
+ else:
540
+ if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
541
+ pow_paren.append(item)
542
+ b.append(Pow(item.base, -item.exp))
543
+ else:
544
+ a.append(item)
545
+
546
+ a = a or [S.One]
547
+
548
+ if len(a) == 1 and sign == "-":
549
+ # Unary minus does not have a SymPy class, and hence there's no
550
+ # precedence weight associated with it, Python's unary minus has
551
+ # an operator precedence between multiplication and exponentiation,
552
+ # so we use this to compute a weight.
553
+ a_str = [self.parenthesize(a[0], 0.5*(PRECEDENCE["Pow"]+PRECEDENCE["Mul"]))]
554
+ else:
555
+ a_str = [self.parenthesize(x, prec) for x in a]
556
+ b_str = [self.parenthesize(x, prec) for x in b]
557
+
558
+ # To parenthesize Pow with exp = -1 and having more than one Symbol
559
+ for item in pow_paren:
560
+ if item.base in b:
561
+ b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
562
+
563
+ if not b:
564
+ return sign + '*'.join(a_str)
565
+ elif len(b) == 1:
566
+ return sign + '*'.join(a_str) + "/" + b_str[0]
567
+ else:
568
+ return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
569
+
570
+ def _print_not_supported(self, expr):
571
+ try:
572
+ self._not_supported.add(expr)
573
+ except TypeError:
574
+ # not hashable
575
+ pass
576
+ return self.emptyPrinter(expr)
577
+
578
+ # The following can not be simply translated into C or Fortran
579
+ _print_Basic = _print_not_supported
580
+ _print_ComplexInfinity = _print_not_supported
581
+ _print_Derivative = _print_not_supported
582
+ _print_ExprCondPair = _print_not_supported
583
+ _print_GeometryEntity = _print_not_supported
584
+ _print_Infinity = _print_not_supported
585
+ _print_Integral = _print_not_supported
586
+ _print_Interval = _print_not_supported
587
+ _print_AccumulationBounds = _print_not_supported
588
+ _print_Limit = _print_not_supported
589
+ _print_MatrixBase = _print_not_supported
590
+ _print_DeferredVector = _print_not_supported
591
+ _print_NaN = _print_not_supported
592
+ _print_NegativeInfinity = _print_not_supported
593
+ _print_Order = _print_not_supported
594
+ _print_RootOf = _print_not_supported
595
+ _print_RootsOf = _print_not_supported
596
+ _print_RootSum = _print_not_supported
597
+ _print_Uniform = _print_not_supported
598
+ _print_Unit = _print_not_supported
599
+ _print_Wild = _print_not_supported
600
+ _print_WildFunction = _print_not_supported
601
+ _print_Relational = _print_not_supported
602
+
603
+
604
+ # Code printer functions. These are included in this file so that they can be
605
+ # imported in the top-level __init__.py without importing the sympy.codegen
606
+ # module.
607
+
608
+ def ccode(expr, assign_to=None, standard='c99', **settings):
609
+ """Converts an expr to a string of c code
610
+
611
+ Parameters
612
+ ==========
613
+
614
+ expr : Expr
615
+ A SymPy expression to be converted.
616
+ assign_to : optional
617
+ When given, the argument is used as the name of the variable to which
618
+ the expression is assigned. Can be a string, ``Symbol``,
619
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
620
+ line-wrapping, or for expressions that generate multi-line statements.
621
+ standard : str, optional
622
+ String specifying the standard. If your compiler supports a more modern
623
+ standard you may set this to 'c99' to allow the printer to use more math
624
+ functions. [default='c89'].
625
+ precision : integer, optional
626
+ The precision for numbers such as pi [default=17].
627
+ user_functions : dict, optional
628
+ A dictionary where the keys are string representations of either
629
+ ``FunctionClass`` or ``UndefinedFunction`` instances and the values
630
+ are their desired C string representations. Alternatively, the
631
+ dictionary value can be a list of tuples i.e. [(argument_test,
632
+ cfunction_string)] or [(argument_test, cfunction_formater)]. See below
633
+ for examples.
634
+ dereference : iterable, optional
635
+ An iterable of symbols that should be dereferenced in the printed code
636
+ expression. These would be values passed by address to the function.
637
+ For example, if ``dereference=[a]``, the resulting code would print
638
+ ``(*a)`` instead of ``a``.
639
+ human : bool, optional
640
+ If True, the result is a single string that may contain some constant
641
+ declarations for the number symbols. If False, the same information is
642
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
643
+ code_text). [default=True].
644
+ contract: bool, optional
645
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
646
+ rules and the corresponding nested loops over indices are generated.
647
+ Setting contract=False will not generate loops, instead the user is
648
+ responsible to provide values for the indices in the code.
649
+ [default=True].
650
+
651
+ Examples
652
+ ========
653
+
654
+ >>> from sympy import ccode, symbols, Rational, sin, ceiling, Abs, Function
655
+ >>> x, tau = symbols("x, tau")
656
+ >>> expr = (2*tau)**Rational(7, 2)
657
+ >>> ccode(expr)
658
+ '8*M_SQRT2*pow(tau, 7.0/2.0)'
659
+ >>> ccode(expr, math_macros={})
660
+ '8*sqrt(2)*pow(tau, 7.0/2.0)'
661
+ >>> ccode(sin(x), assign_to="s")
662
+ 's = sin(x);'
663
+ >>> from sympy.codegen.ast import real, float80
664
+ >>> ccode(expr, type_aliases={real: float80})
665
+ '8*M_SQRT2l*powl(tau, 7.0L/2.0L)'
666
+
667
+ Simple custom printing can be defined for certain types by passing a
668
+ dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
669
+ Alternatively, the dictionary value can be a list of tuples i.e.
670
+ [(argument_test, cfunction_string)].
671
+
672
+ >>> custom_functions = {
673
+ ... "ceiling": "CEIL",
674
+ ... "Abs": [(lambda x: not x.is_integer, "fabs"),
675
+ ... (lambda x: x.is_integer, "ABS")],
676
+ ... "func": "f"
677
+ ... }
678
+ >>> func = Function('func')
679
+ >>> ccode(func(Abs(x) + ceiling(x)), standard='C89', user_functions=custom_functions)
680
+ 'f(fabs(x) + CEIL(x))'
681
+
682
+ or if the C-function takes a subset of the original arguments:
683
+
684
+ >>> ccode(2**x + 3**x, standard='C99', user_functions={'Pow': [
685
+ ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
686
+ ... (lambda b, e: b != 2, 'pow')]})
687
+ 'exp2(x) + pow(3, x)'
688
+
689
+ ``Piecewise`` expressions are converted into conditionals. If an
690
+ ``assign_to`` variable is provided an if statement is created, otherwise
691
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
692
+ default term, represented by ``(expr, True)`` then an error will be thrown.
693
+ This is to prevent generating an expression that may not evaluate to
694
+ anything.
695
+
696
+ >>> from sympy import Piecewise
697
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
698
+ >>> print(ccode(expr, tau, standard='C89'))
699
+ if (x > 0) {
700
+ tau = x + 1;
701
+ }
702
+ else {
703
+ tau = x;
704
+ }
705
+
706
+ Support for loops is provided through ``Indexed`` types. With
707
+ ``contract=True`` these expressions will be turned into loops, whereas
708
+ ``contract=False`` will just print the assignment expression that should be
709
+ looped over:
710
+
711
+ >>> from sympy import Eq, IndexedBase, Idx
712
+ >>> len_y = 5
713
+ >>> y = IndexedBase('y', shape=(len_y,))
714
+ >>> t = IndexedBase('t', shape=(len_y,))
715
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
716
+ >>> i = Idx('i', len_y-1)
717
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
718
+ >>> ccode(e.rhs, assign_to=e.lhs, contract=False, standard='C89')
719
+ 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
720
+
721
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
722
+ must be provided to ``assign_to``. Note that any expression that can be
723
+ generated normally can also exist inside a Matrix:
724
+
725
+ >>> from sympy import Matrix, MatrixSymbol
726
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
727
+ >>> A = MatrixSymbol('A', 3, 1)
728
+ >>> print(ccode(mat, A, standard='C89'))
729
+ A[0] = pow(x, 2);
730
+ if (x > 0) {
731
+ A[1] = x + 1;
732
+ }
733
+ else {
734
+ A[1] = x;
735
+ }
736
+ A[2] = sin(x);
737
+ """
738
+ from sympy.printing.c import c_code_printers
739
+ return c_code_printers[standard.lower()](settings).doprint(expr, assign_to)
740
+
741
+ def print_ccode(expr, **settings):
742
+ """Prints C representation of the given expression."""
743
+ print(ccode(expr, **settings))
744
+
745
+ def fcode(expr, assign_to=None, **settings):
746
+ """Converts an expr to a string of fortran code
747
+
748
+ Parameters
749
+ ==========
750
+
751
+ expr : Expr
752
+ A SymPy expression to be converted.
753
+ assign_to : optional
754
+ When given, the argument is used as the name of the variable to which
755
+ the expression is assigned. Can be a string, ``Symbol``,
756
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
757
+ line-wrapping, or for expressions that generate multi-line statements.
758
+ precision : integer, optional
759
+ DEPRECATED. Use type_mappings instead. The precision for numbers such
760
+ as pi [default=17].
761
+ user_functions : dict, optional
762
+ A dictionary where keys are ``FunctionClass`` instances and values are
763
+ their string representations. Alternatively, the dictionary value can
764
+ be a list of tuples i.e. [(argument_test, cfunction_string)]. See below
765
+ for examples.
766
+ human : bool, optional
767
+ If True, the result is a single string that may contain some constant
768
+ declarations for the number symbols. If False, the same information is
769
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
770
+ code_text). [default=True].
771
+ contract: bool, optional
772
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
773
+ rules and the corresponding nested loops over indices are generated.
774
+ Setting contract=False will not generate loops, instead the user is
775
+ responsible to provide values for the indices in the code.
776
+ [default=True].
777
+ source_format : optional
778
+ The source format can be either 'fixed' or 'free'. [default='fixed']
779
+ standard : integer, optional
780
+ The Fortran standard to be followed. This is specified as an integer.
781
+ Acceptable standards are 66, 77, 90, 95, 2003, and 2008. Default is 77.
782
+ Note that currently the only distinction internally is between
783
+ standards before 95, and those 95 and after. This may change later as
784
+ more features are added.
785
+ name_mangling : bool, optional
786
+ If True, then the variables that would become identical in
787
+ case-insensitive Fortran are mangled by appending different number
788
+ of ``_`` at the end. If False, SymPy Will not interfere with naming of
789
+ variables. [default=True]
790
+
791
+ Examples
792
+ ========
793
+
794
+ >>> from sympy import fcode, symbols, Rational, sin, ceiling, floor
795
+ >>> x, tau = symbols("x, tau")
796
+ >>> fcode((2*tau)**Rational(7, 2))
797
+ ' 8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)'
798
+ >>> fcode(sin(x), assign_to="s")
799
+ ' s = sin(x)'
800
+
801
+ Custom printing can be defined for certain types by passing a dictionary of
802
+ "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
803
+ dictionary value can be a list of tuples i.e. [(argument_test,
804
+ cfunction_string)].
805
+
806
+ >>> custom_functions = {
807
+ ... "ceiling": "CEIL",
808
+ ... "floor": [(lambda x: not x.is_integer, "FLOOR1"),
809
+ ... (lambda x: x.is_integer, "FLOOR2")]
810
+ ... }
811
+ >>> fcode(floor(x) + ceiling(x), user_functions=custom_functions)
812
+ ' CEIL(x) + FLOOR1(x)'
813
+
814
+ ``Piecewise`` expressions are converted into conditionals. If an
815
+ ``assign_to`` variable is provided an if statement is created, otherwise
816
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
817
+ default term, represented by ``(expr, True)`` then an error will be thrown.
818
+ This is to prevent generating an expression that may not evaluate to
819
+ anything.
820
+
821
+ >>> from sympy import Piecewise
822
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
823
+ >>> print(fcode(expr, tau))
824
+ if (x > 0) then
825
+ tau = x + 1
826
+ else
827
+ tau = x
828
+ end if
829
+
830
+ Support for loops is provided through ``Indexed`` types. With
831
+ ``contract=True`` these expressions will be turned into loops, whereas
832
+ ``contract=False`` will just print the assignment expression that should be
833
+ looped over:
834
+
835
+ >>> from sympy import Eq, IndexedBase, Idx
836
+ >>> len_y = 5
837
+ >>> y = IndexedBase('y', shape=(len_y,))
838
+ >>> t = IndexedBase('t', shape=(len_y,))
839
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
840
+ >>> i = Idx('i', len_y-1)
841
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
842
+ >>> fcode(e.rhs, assign_to=e.lhs, contract=False)
843
+ ' Dy(i) = (y(i + 1) - y(i))/(t(i + 1) - t(i))'
844
+
845
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
846
+ must be provided to ``assign_to``. Note that any expression that can be
847
+ generated normally can also exist inside a Matrix:
848
+
849
+ >>> from sympy import Matrix, MatrixSymbol
850
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
851
+ >>> A = MatrixSymbol('A', 3, 1)
852
+ >>> print(fcode(mat, A))
853
+ A(1, 1) = x**2
854
+ if (x > 0) then
855
+ A(2, 1) = x + 1
856
+ else
857
+ A(2, 1) = x
858
+ end if
859
+ A(3, 1) = sin(x)
860
+ """
861
+ from sympy.printing.fortran import FCodePrinter
862
+ return FCodePrinter(settings).doprint(expr, assign_to)
863
+
864
+
865
+ def print_fcode(expr, **settings):
866
+ """Prints the Fortran representation of the given expression.
867
+
868
+ See fcode for the meaning of the optional arguments.
869
+ """
870
+ print(fcode(expr, **settings))
871
+
872
+ def cxxcode(expr, assign_to=None, standard='c++11', **settings):
873
+ """ C++ equivalent of :func:`~.ccode`. """
874
+ from sympy.printing.cxx import cxx_code_printers
875
+ return cxx_code_printers[standard.lower()](settings).doprint(expr, assign_to)
llmeval-env/lib/python3.10/site-packages/sympy/printing/conventions.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A few practical conventions common to all printers.
3
+ """
4
+
5
+ import re
6
+
7
+ from collections.abc import Iterable
8
+ from sympy.core.function import Derivative
9
+
10
+ _name_with_digits_p = re.compile(r'^([^\W\d_]+)(\d+)$', re.U)
11
+
12
+
13
+ def split_super_sub(text):
14
+ """Split a symbol name into a name, superscripts and subscripts
15
+
16
+ The first part of the symbol name is considered to be its actual
17
+ 'name', followed by super- and subscripts. Each superscript is
18
+ preceded with a "^" character or by "__". Each subscript is preceded
19
+ by a "_" character. The three return values are the actual name, a
20
+ list with superscripts and a list with subscripts.
21
+
22
+ Examples
23
+ ========
24
+
25
+ >>> from sympy.printing.conventions import split_super_sub
26
+ >>> split_super_sub('a_x^1')
27
+ ('a', ['1'], ['x'])
28
+ >>> split_super_sub('var_sub1__sup_sub2')
29
+ ('var', ['sup'], ['sub1', 'sub2'])
30
+
31
+ """
32
+ if not text:
33
+ return text, [], []
34
+
35
+ pos = 0
36
+ name = None
37
+ supers = []
38
+ subs = []
39
+ while pos < len(text):
40
+ start = pos + 1
41
+ if text[pos:pos + 2] == "__":
42
+ start += 1
43
+ pos_hat = text.find("^", start)
44
+ if pos_hat < 0:
45
+ pos_hat = len(text)
46
+ pos_usc = text.find("_", start)
47
+ if pos_usc < 0:
48
+ pos_usc = len(text)
49
+ pos_next = min(pos_hat, pos_usc)
50
+ part = text[pos:pos_next]
51
+ pos = pos_next
52
+ if name is None:
53
+ name = part
54
+ elif part.startswith("^"):
55
+ supers.append(part[1:])
56
+ elif part.startswith("__"):
57
+ supers.append(part[2:])
58
+ elif part.startswith("_"):
59
+ subs.append(part[1:])
60
+ else:
61
+ raise RuntimeError("This should never happen.")
62
+
63
+ # Make a little exception when a name ends with digits, i.e. treat them
64
+ # as a subscript too.
65
+ m = _name_with_digits_p.match(name)
66
+ if m:
67
+ name, sub = m.groups()
68
+ subs.insert(0, sub)
69
+
70
+ return name, supers, subs
71
+
72
+
73
+ def requires_partial(expr):
74
+ """Return whether a partial derivative symbol is required for printing
75
+
76
+ This requires checking how many free variables there are,
77
+ filtering out the ones that are integers. Some expressions do not have
78
+ free variables. In that case, check its variable list explicitly to
79
+ get the context of the expression.
80
+ """
81
+
82
+ if isinstance(expr, Derivative):
83
+ return requires_partial(expr.expr)
84
+
85
+ if not isinstance(expr.free_symbols, Iterable):
86
+ return len(set(expr.variables)) > 1
87
+
88
+ return sum(not s.is_integer for s in expr.free_symbols) > 1
llmeval-env/lib/python3.10/site-packages/sympy/printing/cxx.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ C++ code printer
3
+ """
4
+
5
+ from itertools import chain
6
+ from sympy.codegen.ast import Type, none
7
+ from .c import C89CodePrinter, C99CodePrinter
8
+
9
+ # These are defined in the other file so we can avoid importing sympy.codegen
10
+ # from the top-level 'import sympy'. Export them here as well.
11
+ from sympy.printing.codeprinter import cxxcode # noqa:F401
12
+
13
+ # from https://en.cppreference.com/w/cpp/keyword
14
+ reserved = {
15
+ 'C++98': [
16
+ 'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor', 'bool', 'break',
17
+ 'case', 'catch,', 'char', 'class', 'compl', 'const', 'const_cast',
18
+ 'continue', 'default', 'delete', 'do', 'double', 'dynamic_cast',
19
+ 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float',
20
+ 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable',
21
+ 'namespace', 'new', 'not', 'not_eq', 'operator', 'or', 'or_eq',
22
+ 'private', 'protected', 'public', 'register', 'reinterpret_cast',
23
+ 'return', 'short', 'signed', 'sizeof', 'static', 'static_cast',
24
+ 'struct', 'switch', 'template', 'this', 'throw', 'true', 'try',
25
+ 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using',
26
+ 'virtual', 'void', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq'
27
+ ]
28
+ }
29
+
30
+ reserved['C++11'] = reserved['C++98'][:] + [
31
+ 'alignas', 'alignof', 'char16_t', 'char32_t', 'constexpr', 'decltype',
32
+ 'noexcept', 'nullptr', 'static_assert', 'thread_local'
33
+ ]
34
+ reserved['C++17'] = reserved['C++11'][:]
35
+ reserved['C++17'].remove('register')
36
+ # TM TS: atomic_cancel, atomic_commit, atomic_noexcept, synchronized
37
+ # concepts TS: concept, requires
38
+ # module TS: import, module
39
+
40
+
41
+ _math_functions = {
42
+ 'C++98': {
43
+ 'Mod': 'fmod',
44
+ 'ceiling': 'ceil',
45
+ },
46
+ 'C++11': {
47
+ 'gamma': 'tgamma',
48
+ },
49
+ 'C++17': {
50
+ 'beta': 'beta',
51
+ 'Ei': 'expint',
52
+ 'zeta': 'riemann_zeta',
53
+ }
54
+ }
55
+
56
+ # from https://en.cppreference.com/w/cpp/header/cmath
57
+ for k in ('Abs', 'exp', 'log', 'log10', 'sqrt', 'sin', 'cos', 'tan', # 'Pow'
58
+ 'asin', 'acos', 'atan', 'atan2', 'sinh', 'cosh', 'tanh', 'floor'):
59
+ _math_functions['C++98'][k] = k.lower()
60
+
61
+
62
+ for k in ('asinh', 'acosh', 'atanh', 'erf', 'erfc'):
63
+ _math_functions['C++11'][k] = k.lower()
64
+
65
+
66
+ def _attach_print_method(cls, sympy_name, func_name):
67
+ meth_name = '_print_%s' % sympy_name
68
+ if hasattr(cls, meth_name):
69
+ raise ValueError("Edit method (or subclass) instead of overwriting.")
70
+ def _print_method(self, expr):
71
+ return '{}{}({})'.format(self._ns, func_name, ', '.join(map(self._print, expr.args)))
72
+ _print_method.__doc__ = "Prints code for %s" % k
73
+ setattr(cls, meth_name, _print_method)
74
+
75
+
76
+ def _attach_print_methods(cls, cont):
77
+ for sympy_name, cxx_name in cont[cls.standard].items():
78
+ _attach_print_method(cls, sympy_name, cxx_name)
79
+
80
+
81
+ class _CXXCodePrinterBase:
82
+ printmethod = "_cxxcode"
83
+ language = 'C++'
84
+ _ns = 'std::' # namespace
85
+
86
+ def __init__(self, settings=None):
87
+ super().__init__(settings or {})
88
+
89
+ def _print_Max(self, expr):
90
+ from sympy.functions.elementary.miscellaneous import Max
91
+ if len(expr.args) == 1:
92
+ return self._print(expr.args[0])
93
+ return "%smax(%s, %s)" % (self._ns, self._print(expr.args[0]),
94
+ self._print(Max(*expr.args[1:])))
95
+
96
+ def _print_Min(self, expr):
97
+ from sympy.functions.elementary.miscellaneous import Min
98
+ if len(expr.args) == 1:
99
+ return self._print(expr.args[0])
100
+ return "%smin(%s, %s)" % (self._ns, self._print(expr.args[0]),
101
+ self._print(Min(*expr.args[1:])))
102
+
103
+ def _print_using(self, expr):
104
+ if expr.alias == none:
105
+ return 'using %s' % expr.type
106
+ else:
107
+ raise ValueError("C++98 does not support type aliases")
108
+
109
+
110
+ class CXX98CodePrinter(_CXXCodePrinterBase, C89CodePrinter):
111
+ standard = 'C++98'
112
+ reserved_words = set(reserved['C++98'])
113
+
114
+
115
+ # _attach_print_methods(CXX98CodePrinter, _math_functions)
116
+
117
+
118
+ class CXX11CodePrinter(_CXXCodePrinterBase, C99CodePrinter):
119
+ standard = 'C++11'
120
+ reserved_words = set(reserved['C++11'])
121
+ type_mappings = dict(chain(
122
+ CXX98CodePrinter.type_mappings.items(),
123
+ {
124
+ Type('int8'): ('int8_t', {'cstdint'}),
125
+ Type('int16'): ('int16_t', {'cstdint'}),
126
+ Type('int32'): ('int32_t', {'cstdint'}),
127
+ Type('int64'): ('int64_t', {'cstdint'}),
128
+ Type('uint8'): ('uint8_t', {'cstdint'}),
129
+ Type('uint16'): ('uint16_t', {'cstdint'}),
130
+ Type('uint32'): ('uint32_t', {'cstdint'}),
131
+ Type('uint64'): ('uint64_t', {'cstdint'}),
132
+ Type('complex64'): ('std::complex<float>', {'complex'}),
133
+ Type('complex128'): ('std::complex<double>', {'complex'}),
134
+ Type('bool'): ('bool', None),
135
+ }.items()
136
+ ))
137
+
138
+ def _print_using(self, expr):
139
+ if expr.alias == none:
140
+ return super()._print_using(expr)
141
+ else:
142
+ return 'using %(alias)s = %(type)s' % expr.kwargs(apply=self._print)
143
+
144
+ # _attach_print_methods(CXX11CodePrinter, _math_functions)
145
+
146
+
147
+ class CXX17CodePrinter(_CXXCodePrinterBase, C99CodePrinter):
148
+ standard = 'C++17'
149
+ reserved_words = set(reserved['C++17'])
150
+
151
+ _kf = dict(C99CodePrinter._kf, **_math_functions['C++17'])
152
+
153
+ def _print_beta(self, expr):
154
+ return self._print_math_func(expr)
155
+
156
+ def _print_Ei(self, expr):
157
+ return self._print_math_func(expr)
158
+
159
+ def _print_zeta(self, expr):
160
+ return self._print_math_func(expr)
161
+
162
+
163
+ # _attach_print_methods(CXX17CodePrinter, _math_functions)
164
+
165
+ cxx_code_printers = {
166
+ 'c++98': CXX98CodePrinter,
167
+ 'c++11': CXX11CodePrinter,
168
+ 'c++17': CXX17CodePrinter
169
+ }
llmeval-env/lib/python3.10/site-packages/sympy/printing/defaults.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from sympy.core._print_helpers import Printable
2
+
3
+ # alias for compatibility
4
+ Printable.__module__ = __name__
5
+ DefaultPrinting = Printable
llmeval-env/lib/python3.10/site-packages/sympy/printing/dot.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.basic import Basic
2
+ from sympy.core.expr import Expr
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.core.numbers import Integer, Rational, Float
5
+ from sympy.printing.repr import srepr
6
+
7
+ __all__ = ['dotprint']
8
+
9
+ default_styles = (
10
+ (Basic, {'color': 'blue', 'shape': 'ellipse'}),
11
+ (Expr, {'color': 'black'})
12
+ )
13
+
14
+ slotClasses = (Symbol, Integer, Rational, Float)
15
+ def purestr(x, with_args=False):
16
+ """A string that follows ```obj = type(obj)(*obj.args)``` exactly.
17
+
18
+ Parameters
19
+ ==========
20
+
21
+ with_args : boolean, optional
22
+ If ``True``, there will be a second argument for the return
23
+ value, which is a tuple containing ``purestr`` applied to each
24
+ of the subnodes.
25
+
26
+ If ``False``, there will not be a second argument for the
27
+ return.
28
+
29
+ Default is ``False``
30
+
31
+ Examples
32
+ ========
33
+
34
+ >>> from sympy import Float, Symbol, MatrixSymbol
35
+ >>> from sympy import Integer # noqa: F401
36
+ >>> from sympy.core.symbol import Str # noqa: F401
37
+ >>> from sympy.printing.dot import purestr
38
+
39
+ Applying ``purestr`` for basic symbolic object:
40
+ >>> code = purestr(Symbol('x'))
41
+ >>> code
42
+ "Symbol('x')"
43
+ >>> eval(code) == Symbol('x')
44
+ True
45
+
46
+ For basic numeric object:
47
+ >>> purestr(Float(2))
48
+ "Float('2.0', precision=53)"
49
+
50
+ For matrix symbol:
51
+ >>> code = purestr(MatrixSymbol('x', 2, 2))
52
+ >>> code
53
+ "MatrixSymbol(Str('x'), Integer(2), Integer(2))"
54
+ >>> eval(code) == MatrixSymbol('x', 2, 2)
55
+ True
56
+
57
+ With ``with_args=True``:
58
+ >>> purestr(Float(2), with_args=True)
59
+ ("Float('2.0', precision=53)", ())
60
+ >>> purestr(MatrixSymbol('x', 2, 2), with_args=True)
61
+ ("MatrixSymbol(Str('x'), Integer(2), Integer(2))",
62
+ ("Str('x')", 'Integer(2)', 'Integer(2)'))
63
+ """
64
+ sargs = ()
65
+ if not isinstance(x, Basic):
66
+ rv = str(x)
67
+ elif not x.args:
68
+ rv = srepr(x)
69
+ else:
70
+ args = x.args
71
+ sargs = tuple(map(purestr, args))
72
+ rv = "%s(%s)"%(type(x).__name__, ', '.join(sargs))
73
+ if with_args:
74
+ rv = rv, sargs
75
+ return rv
76
+
77
+
78
+ def styleof(expr, styles=default_styles):
79
+ """ Merge style dictionaries in order
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy import Symbol, Basic, Expr, S
85
+ >>> from sympy.printing.dot import styleof
86
+ >>> styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}),
87
+ ... (Expr, {'color': 'black'})]
88
+
89
+ >>> styleof(Basic(S(1)), styles)
90
+ {'color': 'blue', 'shape': 'ellipse'}
91
+
92
+ >>> x = Symbol('x')
93
+ >>> styleof(x + 1, styles) # this is an Expr
94
+ {'color': 'black', 'shape': 'ellipse'}
95
+ """
96
+ style = {}
97
+ for typ, sty in styles:
98
+ if isinstance(expr, typ):
99
+ style.update(sty)
100
+ return style
101
+
102
+
103
+ def attrprint(d, delimiter=', '):
104
+ """ Print a dictionary of attributes
105
+
106
+ Examples
107
+ ========
108
+
109
+ >>> from sympy.printing.dot import attrprint
110
+ >>> print(attrprint({'color': 'blue', 'shape': 'ellipse'}))
111
+ "color"="blue", "shape"="ellipse"
112
+ """
113
+ return delimiter.join('"%s"="%s"'%item for item in sorted(d.items()))
114
+
115
+
116
+ def dotnode(expr, styles=default_styles, labelfunc=str, pos=(), repeat=True):
117
+ """ String defining a node
118
+
119
+ Examples
120
+ ========
121
+
122
+ >>> from sympy.printing.dot import dotnode
123
+ >>> from sympy.abc import x
124
+ >>> print(dotnode(x))
125
+ "Symbol('x')_()" ["color"="black", "label"="x", "shape"="ellipse"];
126
+ """
127
+ style = styleof(expr, styles)
128
+
129
+ if isinstance(expr, Basic) and not expr.is_Atom:
130
+ label = str(expr.__class__.__name__)
131
+ else:
132
+ label = labelfunc(expr)
133
+ style['label'] = label
134
+ expr_str = purestr(expr)
135
+ if repeat:
136
+ expr_str += '_%s' % str(pos)
137
+ return '"%s" [%s];' % (expr_str, attrprint(style))
138
+
139
+
140
+ def dotedges(expr, atom=lambda x: not isinstance(x, Basic), pos=(), repeat=True):
141
+ """ List of strings for all expr->expr.arg pairs
142
+
143
+ See the docstring of dotprint for explanations of the options.
144
+
145
+ Examples
146
+ ========
147
+
148
+ >>> from sympy.printing.dot import dotedges
149
+ >>> from sympy.abc import x
150
+ >>> for e in dotedges(x+2):
151
+ ... print(e)
152
+ "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";
153
+ "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";
154
+ """
155
+ if atom(expr):
156
+ return []
157
+ else:
158
+ expr_str, arg_strs = purestr(expr, with_args=True)
159
+ if repeat:
160
+ expr_str += '_%s' % str(pos)
161
+ arg_strs = ['%s_%s' % (a, str(pos + (i,)))
162
+ for i, a in enumerate(arg_strs)]
163
+ return ['"%s" -> "%s";' % (expr_str, a) for a in arg_strs]
164
+
165
+ template = \
166
+ """digraph{
167
+
168
+ # Graph style
169
+ %(graphstyle)s
170
+
171
+ #########
172
+ # Nodes #
173
+ #########
174
+
175
+ %(nodes)s
176
+
177
+ #########
178
+ # Edges #
179
+ #########
180
+
181
+ %(edges)s
182
+ }"""
183
+
184
+ _graphstyle = {'rankdir': 'TD', 'ordering': 'out'}
185
+
186
+ def dotprint(expr,
187
+ styles=default_styles, atom=lambda x: not isinstance(x, Basic),
188
+ maxdepth=None, repeat=True, labelfunc=str, **kwargs):
189
+ """DOT description of a SymPy expression tree
190
+
191
+ Parameters
192
+ ==========
193
+
194
+ styles : list of lists composed of (Class, mapping), optional
195
+ Styles for different classes.
196
+
197
+ The default is
198
+
199
+ .. code-block:: python
200
+
201
+ (
202
+ (Basic, {'color': 'blue', 'shape': 'ellipse'}),
203
+ (Expr, {'color': 'black'})
204
+ )
205
+
206
+ atom : function, optional
207
+ Function used to determine if an arg is an atom.
208
+
209
+ A good choice is ``lambda x: not x.args``.
210
+
211
+ The default is ``lambda x: not isinstance(x, Basic)``.
212
+
213
+ maxdepth : integer, optional
214
+ The maximum depth.
215
+
216
+ The default is ``None``, meaning no limit.
217
+
218
+ repeat : boolean, optional
219
+ Whether to use different nodes for common subexpressions.
220
+
221
+ The default is ``True``.
222
+
223
+ For example, for ``x + x*y`` with ``repeat=True``, it will have
224
+ two nodes for ``x``; with ``repeat=False``, it will have one
225
+ node.
226
+
227
+ .. warning::
228
+ Even if a node appears twice in the same object like ``x`` in
229
+ ``Pow(x, x)``, it will still only appear once.
230
+ Hence, with ``repeat=False``, the number of arrows out of an
231
+ object might not equal the number of args it has.
232
+
233
+ labelfunc : function, optional
234
+ A function to create a label for a given leaf node.
235
+
236
+ The default is ``str``.
237
+
238
+ Another good option is ``srepr``.
239
+
240
+ For example with ``str``, the leaf nodes of ``x + 1`` are labeled,
241
+ ``x`` and ``1``. With ``srepr``, they are labeled ``Symbol('x')``
242
+ and ``Integer(1)``.
243
+
244
+ **kwargs : optional
245
+ Additional keyword arguments are included as styles for the graph.
246
+
247
+ Examples
248
+ ========
249
+
250
+ >>> from sympy import dotprint
251
+ >>> from sympy.abc import x
252
+ >>> print(dotprint(x+2)) # doctest: +NORMALIZE_WHITESPACE
253
+ digraph{
254
+ <BLANKLINE>
255
+ # Graph style
256
+ "ordering"="out"
257
+ "rankdir"="TD"
258
+ <BLANKLINE>
259
+ #########
260
+ # Nodes #
261
+ #########
262
+ <BLANKLINE>
263
+ "Add(Integer(2), Symbol('x'))_()" ["color"="black", "label"="Add", "shape"="ellipse"];
264
+ "Integer(2)_(0,)" ["color"="black", "label"="2", "shape"="ellipse"];
265
+ "Symbol('x')_(1,)" ["color"="black", "label"="x", "shape"="ellipse"];
266
+ <BLANKLINE>
267
+ #########
268
+ # Edges #
269
+ #########
270
+ <BLANKLINE>
271
+ "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";
272
+ "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";
273
+ }
274
+
275
+ """
276
+ # repeat works by adding a signature tuple to the end of each node for its
277
+ # position in the graph. For example, for expr = Add(x, Pow(x, 2)), the x in the
278
+ # Pow will have the tuple (1, 0), meaning it is expr.args[1].args[0].
279
+ graphstyle = _graphstyle.copy()
280
+ graphstyle.update(kwargs)
281
+
282
+ nodes = []
283
+ edges = []
284
+ def traverse(e, depth, pos=()):
285
+ nodes.append(dotnode(e, styles, labelfunc=labelfunc, pos=pos, repeat=repeat))
286
+ if maxdepth and depth >= maxdepth:
287
+ return
288
+ edges.extend(dotedges(e, atom=atom, pos=pos, repeat=repeat))
289
+ [traverse(arg, depth+1, pos + (i,)) for i, arg in enumerate(e.args) if not atom(arg)]
290
+ traverse(expr, 0)
291
+
292
+ return template%{'graphstyle': attrprint(graphstyle, delimiter='\n'),
293
+ 'nodes': '\n'.join(nodes),
294
+ 'edges': '\n'.join(edges)}
llmeval-env/lib/python3.10/site-packages/sympy/printing/fortran.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Fortran code printer
3
+
4
+ The FCodePrinter converts single SymPy expressions into single Fortran
5
+ expressions, using the functions defined in the Fortran 77 standard where
6
+ possible. Some useful pointers to Fortran can be found on wikipedia:
7
+
8
+ https://en.wikipedia.org/wiki/Fortran
9
+
10
+ Most of the code below is based on the "Professional Programmer\'s Guide to
11
+ Fortran77" by Clive G. Page:
12
+
13
+ https://www.star.le.ac.uk/~cgp/prof77.html
14
+
15
+ Fortran is a case-insensitive language. This might cause trouble because
16
+ SymPy is case sensitive. So, fcode adds underscores to variable names when
17
+ it is necessary to make them different for Fortran.
18
+ """
19
+
20
+ from __future__ import annotations
21
+ from typing import Any
22
+
23
+ from collections import defaultdict
24
+ from itertools import chain
25
+ import string
26
+
27
+ from sympy.codegen.ast import (
28
+ Assignment, Declaration, Pointer, value_const,
29
+ float32, float64, float80, complex64, complex128, int8, int16, int32,
30
+ int64, intc, real, integer, bool_, complex_
31
+ )
32
+ from sympy.codegen.fnodes import (
33
+ allocatable, isign, dsign, cmplx, merge, literal_dp, elemental, pure,
34
+ intent_in, intent_out, intent_inout
35
+ )
36
+ from sympy.core import S, Add, N, Float, Symbol
37
+ from sympy.core.function import Function
38
+ from sympy.core.numbers import equal_valued
39
+ from sympy.core.relational import Eq
40
+ from sympy.sets import Range
41
+ from sympy.printing.codeprinter import CodePrinter
42
+ from sympy.printing.precedence import precedence, PRECEDENCE
43
+ from sympy.printing.printer import printer_context
44
+
45
+ # These are defined in the other file so we can avoid importing sympy.codegen
46
+ # from the top-level 'import sympy'. Export them here as well.
47
+ from sympy.printing.codeprinter import fcode, print_fcode # noqa:F401
48
+
49
+ known_functions = {
50
+ "sin": "sin",
51
+ "cos": "cos",
52
+ "tan": "tan",
53
+ "asin": "asin",
54
+ "acos": "acos",
55
+ "atan": "atan",
56
+ "atan2": "atan2",
57
+ "sinh": "sinh",
58
+ "cosh": "cosh",
59
+ "tanh": "tanh",
60
+ "log": "log",
61
+ "exp": "exp",
62
+ "erf": "erf",
63
+ "Abs": "abs",
64
+ "conjugate": "conjg",
65
+ "Max": "max",
66
+ "Min": "min",
67
+ }
68
+
69
+
70
+ class FCodePrinter(CodePrinter):
71
+ """A printer to convert SymPy expressions to strings of Fortran code"""
72
+ printmethod = "_fcode"
73
+ language = "Fortran"
74
+
75
+ type_aliases = {
76
+ integer: int32,
77
+ real: float64,
78
+ complex_: complex128,
79
+ }
80
+
81
+ type_mappings = {
82
+ intc: 'integer(c_int)',
83
+ float32: 'real*4', # real(kind(0.e0))
84
+ float64: 'real*8', # real(kind(0.d0))
85
+ float80: 'real*10', # real(kind(????))
86
+ complex64: 'complex*8',
87
+ complex128: 'complex*16',
88
+ int8: 'integer*1',
89
+ int16: 'integer*2',
90
+ int32: 'integer*4',
91
+ int64: 'integer*8',
92
+ bool_: 'logical'
93
+ }
94
+
95
+ type_modules = {
96
+ intc: {'iso_c_binding': 'c_int'}
97
+ }
98
+
99
+ _default_settings: dict[str, Any] = {
100
+ 'order': None,
101
+ 'full_prec': 'auto',
102
+ 'precision': 17,
103
+ 'user_functions': {},
104
+ 'human': True,
105
+ 'allow_unknown_functions': False,
106
+ 'source_format': 'fixed',
107
+ 'contract': True,
108
+ 'standard': 77,
109
+ 'name_mangling': True,
110
+ }
111
+
112
+ _operators = {
113
+ 'and': '.and.',
114
+ 'or': '.or.',
115
+ 'xor': '.neqv.',
116
+ 'equivalent': '.eqv.',
117
+ 'not': '.not. ',
118
+ }
119
+
120
+ _relationals = {
121
+ '!=': '/=',
122
+ }
123
+
124
+ def __init__(self, settings=None):
125
+ if not settings:
126
+ settings = {}
127
+ self.mangled_symbols = {} # Dict showing mapping of all words
128
+ self.used_name = []
129
+ self.type_aliases = dict(chain(self.type_aliases.items(),
130
+ settings.pop('type_aliases', {}).items()))
131
+ self.type_mappings = dict(chain(self.type_mappings.items(),
132
+ settings.pop('type_mappings', {}).items()))
133
+ super().__init__(settings)
134
+ self.known_functions = dict(known_functions)
135
+ userfuncs = settings.get('user_functions', {})
136
+ self.known_functions.update(userfuncs)
137
+ # leading columns depend on fixed or free format
138
+ standards = {66, 77, 90, 95, 2003, 2008}
139
+ if self._settings['standard'] not in standards:
140
+ raise ValueError("Unknown Fortran standard: %s" % self._settings[
141
+ 'standard'])
142
+ self.module_uses = defaultdict(set) # e.g.: use iso_c_binding, only: c_int
143
+
144
+ @property
145
+ def _lead(self):
146
+ if self._settings['source_format'] == 'fixed':
147
+ return {'code': " ", 'cont': " @ ", 'comment': "C "}
148
+ elif self._settings['source_format'] == 'free':
149
+ return {'code': "", 'cont': " ", 'comment': "! "}
150
+ else:
151
+ raise ValueError("Unknown source format: %s" % self._settings['source_format'])
152
+
153
+ def _print_Symbol(self, expr):
154
+ if self._settings['name_mangling'] == True:
155
+ if expr not in self.mangled_symbols:
156
+ name = expr.name
157
+ while name.lower() in self.used_name:
158
+ name += '_'
159
+ self.used_name.append(name.lower())
160
+ if name == expr.name:
161
+ self.mangled_symbols[expr] = expr
162
+ else:
163
+ self.mangled_symbols[expr] = Symbol(name)
164
+
165
+ expr = expr.xreplace(self.mangled_symbols)
166
+
167
+ name = super()._print_Symbol(expr)
168
+ return name
169
+
170
+ def _rate_index_position(self, p):
171
+ return -p*5
172
+
173
+ def _get_statement(self, codestring):
174
+ return codestring
175
+
176
+ def _get_comment(self, text):
177
+ return "! {}".format(text)
178
+
179
+ def _declare_number_const(self, name, value):
180
+ return "parameter ({} = {})".format(name, self._print(value))
181
+
182
+ def _print_NumberSymbol(self, expr):
183
+ # A Number symbol that is not implemented here or with _printmethod
184
+ # is registered and evaluated
185
+ self._number_symbols.add((expr, Float(expr.evalf(self._settings['precision']))))
186
+ return str(expr)
187
+
188
+ def _format_code(self, lines):
189
+ return self._wrap_fortran(self.indent_code(lines))
190
+
191
+ def _traverse_matrix_indices(self, mat):
192
+ rows, cols = mat.shape
193
+ return ((i, j) for j in range(cols) for i in range(rows))
194
+
195
+ def _get_loop_opening_ending(self, indices):
196
+ open_lines = []
197
+ close_lines = []
198
+ for i in indices:
199
+ # fortran arrays start at 1 and end at dimension
200
+ var, start, stop = map(self._print,
201
+ [i.label, i.lower + 1, i.upper + 1])
202
+ open_lines.append("do %s = %s, %s" % (var, start, stop))
203
+ close_lines.append("end do")
204
+ return open_lines, close_lines
205
+
206
+ def _print_sign(self, expr):
207
+ from sympy.functions.elementary.complexes import Abs
208
+ arg, = expr.args
209
+ if arg.is_integer:
210
+ new_expr = merge(0, isign(1, arg), Eq(arg, 0))
211
+ elif (arg.is_complex or arg.is_infinite):
212
+ new_expr = merge(cmplx(literal_dp(0), literal_dp(0)), arg/Abs(arg), Eq(Abs(arg), literal_dp(0)))
213
+ else:
214
+ new_expr = merge(literal_dp(0), dsign(literal_dp(1), arg), Eq(arg, literal_dp(0)))
215
+ return self._print(new_expr)
216
+
217
+
218
+ def _print_Piecewise(self, expr):
219
+ if expr.args[-1].cond != True:
220
+ # We need the last conditional to be a True, otherwise the resulting
221
+ # function may not return a result.
222
+ raise ValueError("All Piecewise expressions must contain an "
223
+ "(expr, True) statement to be used as a default "
224
+ "condition. Without one, the generated "
225
+ "expression may not evaluate to anything under "
226
+ "some condition.")
227
+ lines = []
228
+ if expr.has(Assignment):
229
+ for i, (e, c) in enumerate(expr.args):
230
+ if i == 0:
231
+ lines.append("if (%s) then" % self._print(c))
232
+ elif i == len(expr.args) - 1 and c == True:
233
+ lines.append("else")
234
+ else:
235
+ lines.append("else if (%s) then" % self._print(c))
236
+ lines.append(self._print(e))
237
+ lines.append("end if")
238
+ return "\n".join(lines)
239
+ elif self._settings["standard"] >= 95:
240
+ # Only supported in F95 and newer:
241
+ # The piecewise was used in an expression, need to do inline
242
+ # operators. This has the downside that inline operators will
243
+ # not work for statements that span multiple lines (Matrix or
244
+ # Indexed expressions).
245
+ pattern = "merge({T}, {F}, {COND})"
246
+ code = self._print(expr.args[-1].expr)
247
+ terms = list(expr.args[:-1])
248
+ while terms:
249
+ e, c = terms.pop()
250
+ expr = self._print(e)
251
+ cond = self._print(c)
252
+ code = pattern.format(T=expr, F=code, COND=cond)
253
+ return code
254
+ else:
255
+ # `merge` is not supported prior to F95
256
+ raise NotImplementedError("Using Piecewise as an expression using "
257
+ "inline operators is not supported in "
258
+ "standards earlier than Fortran95.")
259
+
260
+ def _print_MatrixElement(self, expr):
261
+ return "{}({}, {})".format(self.parenthesize(expr.parent,
262
+ PRECEDENCE["Atom"], strict=True), expr.i + 1, expr.j + 1)
263
+
264
+ def _print_Add(self, expr):
265
+ # purpose: print complex numbers nicely in Fortran.
266
+ # collect the purely real and purely imaginary parts:
267
+ pure_real = []
268
+ pure_imaginary = []
269
+ mixed = []
270
+ for arg in expr.args:
271
+ if arg.is_number and arg.is_real:
272
+ pure_real.append(arg)
273
+ elif arg.is_number and arg.is_imaginary:
274
+ pure_imaginary.append(arg)
275
+ else:
276
+ mixed.append(arg)
277
+ if pure_imaginary:
278
+ if mixed:
279
+ PREC = precedence(expr)
280
+ term = Add(*mixed)
281
+ t = self._print(term)
282
+ if t.startswith('-'):
283
+ sign = "-"
284
+ t = t[1:]
285
+ else:
286
+ sign = "+"
287
+ if precedence(term) < PREC:
288
+ t = "(%s)" % t
289
+
290
+ return "cmplx(%s,%s) %s %s" % (
291
+ self._print(Add(*pure_real)),
292
+ self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
293
+ sign, t,
294
+ )
295
+ else:
296
+ return "cmplx(%s,%s)" % (
297
+ self._print(Add(*pure_real)),
298
+ self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
299
+ )
300
+ else:
301
+ return CodePrinter._print_Add(self, expr)
302
+
303
+ def _print_Function(self, expr):
304
+ # All constant function args are evaluated as floats
305
+ prec = self._settings['precision']
306
+ args = [N(a, prec) for a in expr.args]
307
+ eval_expr = expr.func(*args)
308
+ if not isinstance(eval_expr, Function):
309
+ return self._print(eval_expr)
310
+ else:
311
+ return CodePrinter._print_Function(self, expr.func(*args))
312
+
313
+ def _print_Mod(self, expr):
314
+ # NOTE : Fortran has the functions mod() and modulo(). modulo() behaves
315
+ # the same wrt to the sign of the arguments as Python and SymPy's
316
+ # modulus computations (% and Mod()) but is not available in Fortran 66
317
+ # or Fortran 77, thus we raise an error.
318
+ if self._settings['standard'] in [66, 77]:
319
+ msg = ("Python % operator and SymPy's Mod() function are not "
320
+ "supported by Fortran 66 or 77 standards.")
321
+ raise NotImplementedError(msg)
322
+ else:
323
+ x, y = expr.args
324
+ return " modulo({}, {})".format(self._print(x), self._print(y))
325
+
326
+ def _print_ImaginaryUnit(self, expr):
327
+ # purpose: print complex numbers nicely in Fortran.
328
+ return "cmplx(0,1)"
329
+
330
+ def _print_int(self, expr):
331
+ return str(expr)
332
+
333
+ def _print_Mul(self, expr):
334
+ # purpose: print complex numbers nicely in Fortran.
335
+ if expr.is_number and expr.is_imaginary:
336
+ return "cmplx(0,%s)" % (
337
+ self._print(-S.ImaginaryUnit*expr)
338
+ )
339
+ else:
340
+ return CodePrinter._print_Mul(self, expr)
341
+
342
+ def _print_Pow(self, expr):
343
+ PREC = precedence(expr)
344
+ if equal_valued(expr.exp, -1):
345
+ return '%s/%s' % (
346
+ self._print(literal_dp(1)),
347
+ self.parenthesize(expr.base, PREC)
348
+ )
349
+ elif equal_valued(expr.exp, 0.5):
350
+ if expr.base.is_integer:
351
+ # Fortran intrinsic sqrt() does not accept integer argument
352
+ if expr.base.is_Number:
353
+ return 'sqrt(%s.0d0)' % self._print(expr.base)
354
+ else:
355
+ return 'sqrt(dble(%s))' % self._print(expr.base)
356
+ else:
357
+ return 'sqrt(%s)' % self._print(expr.base)
358
+ else:
359
+ return CodePrinter._print_Pow(self, expr)
360
+
361
+ def _print_Rational(self, expr):
362
+ p, q = int(expr.p), int(expr.q)
363
+ return "%d.0d0/%d.0d0" % (p, q)
364
+
365
+ def _print_Float(self, expr):
366
+ printed = CodePrinter._print_Float(self, expr)
367
+ e = printed.find('e')
368
+ if e > -1:
369
+ return "%sd%s" % (printed[:e], printed[e + 1:])
370
+ return "%sd0" % printed
371
+
372
+ def _print_Relational(self, expr):
373
+ lhs_code = self._print(expr.lhs)
374
+ rhs_code = self._print(expr.rhs)
375
+ op = expr.rel_op
376
+ op = op if op not in self._relationals else self._relationals[op]
377
+ return "{} {} {}".format(lhs_code, op, rhs_code)
378
+
379
+ def _print_Indexed(self, expr):
380
+ inds = [ self._print(i) for i in expr.indices ]
381
+ return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
382
+
383
+ def _print_Idx(self, expr):
384
+ return self._print(expr.label)
385
+
386
+ def _print_AugmentedAssignment(self, expr):
387
+ lhs_code = self._print(expr.lhs)
388
+ rhs_code = self._print(expr.rhs)
389
+ return self._get_statement("{0} = {0} {1} {2}".format(
390
+ self._print(lhs_code), self._print(expr.binop), self._print(rhs_code)))
391
+
392
+ def _print_sum_(self, sm):
393
+ params = self._print(sm.array)
394
+ if sm.dim != None: # Must use '!= None', cannot use 'is not None'
395
+ params += ', ' + self._print(sm.dim)
396
+ if sm.mask != None: # Must use '!= None', cannot use 'is not None'
397
+ params += ', mask=' + self._print(sm.mask)
398
+ return '%s(%s)' % (sm.__class__.__name__.rstrip('_'), params)
399
+
400
+ def _print_product_(self, prod):
401
+ return self._print_sum_(prod)
402
+
403
+ def _print_Do(self, do):
404
+ excl = ['concurrent']
405
+ if do.step == 1:
406
+ excl.append('step')
407
+ step = ''
408
+ else:
409
+ step = ', {step}'
410
+
411
+ return (
412
+ 'do {concurrent}{counter} = {first}, {last}'+step+'\n'
413
+ '{body}\n'
414
+ 'end do\n'
415
+ ).format(
416
+ concurrent='concurrent ' if do.concurrent else '',
417
+ **do.kwargs(apply=lambda arg: self._print(arg), exclude=excl)
418
+ )
419
+
420
+ def _print_ImpliedDoLoop(self, idl):
421
+ step = '' if idl.step == 1 else ', {step}'
422
+ return ('({expr}, {counter} = {first}, {last}'+step+')').format(
423
+ **idl.kwargs(apply=lambda arg: self._print(arg))
424
+ )
425
+
426
+ def _print_For(self, expr):
427
+ target = self._print(expr.target)
428
+ if isinstance(expr.iterable, Range):
429
+ start, stop, step = expr.iterable.args
430
+ else:
431
+ raise NotImplementedError("Only iterable currently supported is Range")
432
+ body = self._print(expr.body)
433
+ return ('do {target} = {start}, {stop}, {step}\n'
434
+ '{body}\n'
435
+ 'end do').format(target=target, start=start, stop=stop - 1,
436
+ step=step, body=body)
437
+
438
+ def _print_Type(self, type_):
439
+ type_ = self.type_aliases.get(type_, type_)
440
+ type_str = self.type_mappings.get(type_, type_.name)
441
+ module_uses = self.type_modules.get(type_)
442
+ if module_uses:
443
+ for k, v in module_uses:
444
+ self.module_uses[k].add(v)
445
+ return type_str
446
+
447
+ def _print_Element(self, elem):
448
+ return '{symbol}({idxs})'.format(
449
+ symbol=self._print(elem.symbol),
450
+ idxs=', '.join((self._print(arg) for arg in elem.indices))
451
+ )
452
+
453
+ def _print_Extent(self, ext):
454
+ return str(ext)
455
+
456
+ def _print_Declaration(self, expr):
457
+ var = expr.variable
458
+ val = var.value
459
+ dim = var.attr_params('dimension')
460
+ intents = [intent in var.attrs for intent in (intent_in, intent_out, intent_inout)]
461
+ if intents.count(True) == 0:
462
+ intent = ''
463
+ elif intents.count(True) == 1:
464
+ intent = ', intent(%s)' % ['in', 'out', 'inout'][intents.index(True)]
465
+ else:
466
+ raise ValueError("Multiple intents specified for %s" % self)
467
+
468
+ if isinstance(var, Pointer):
469
+ raise NotImplementedError("Pointers are not available by default in Fortran.")
470
+ if self._settings["standard"] >= 90:
471
+ result = '{t}{vc}{dim}{intent}{alloc} :: {s}'.format(
472
+ t=self._print(var.type),
473
+ vc=', parameter' if value_const in var.attrs else '',
474
+ dim=', dimension(%s)' % ', '.join((self._print(arg) for arg in dim)) if dim else '',
475
+ intent=intent,
476
+ alloc=', allocatable' if allocatable in var.attrs else '',
477
+ s=self._print(var.symbol)
478
+ )
479
+ if val != None: # Must be "!= None", cannot be "is not None"
480
+ result += ' = %s' % self._print(val)
481
+ else:
482
+ if value_const in var.attrs or val:
483
+ raise NotImplementedError("F77 init./parameter statem. req. multiple lines.")
484
+ result = ' '.join((self._print(arg) for arg in [var.type, var.symbol]))
485
+
486
+ return result
487
+
488
+
489
+ def _print_Infinity(self, expr):
490
+ return '(huge(%s) + 1)' % self._print(literal_dp(0))
491
+
492
+ def _print_While(self, expr):
493
+ return 'do while ({condition})\n{body}\nend do'.format(**expr.kwargs(
494
+ apply=lambda arg: self._print(arg)))
495
+
496
+ def _print_BooleanTrue(self, expr):
497
+ return '.true.'
498
+
499
+ def _print_BooleanFalse(self, expr):
500
+ return '.false.'
501
+
502
+ def _pad_leading_columns(self, lines):
503
+ result = []
504
+ for line in lines:
505
+ if line.startswith('!'):
506
+ result.append(self._lead['comment'] + line[1:].lstrip())
507
+ else:
508
+ result.append(self._lead['code'] + line)
509
+ return result
510
+
511
+ def _wrap_fortran(self, lines):
512
+ """Wrap long Fortran lines
513
+
514
+ Argument:
515
+ lines -- a list of lines (without \\n character)
516
+
517
+ A comment line is split at white space. Code lines are split with a more
518
+ complex rule to give nice results.
519
+ """
520
+ # routine to find split point in a code line
521
+ my_alnum = set("_+-." + string.digits + string.ascii_letters)
522
+ my_white = set(" \t()")
523
+
524
+ def split_pos_code(line, endpos):
525
+ if len(line) <= endpos:
526
+ return len(line)
527
+ pos = endpos
528
+ split = lambda pos: \
529
+ (line[pos] in my_alnum and line[pos - 1] not in my_alnum) or \
530
+ (line[pos] not in my_alnum and line[pos - 1] in my_alnum) or \
531
+ (line[pos] in my_white and line[pos - 1] not in my_white) or \
532
+ (line[pos] not in my_white and line[pos - 1] in my_white)
533
+ while not split(pos):
534
+ pos -= 1
535
+ if pos == 0:
536
+ return endpos
537
+ return pos
538
+ # split line by line and add the split lines to result
539
+ result = []
540
+ if self._settings['source_format'] == 'free':
541
+ trailing = ' &'
542
+ else:
543
+ trailing = ''
544
+ for line in lines:
545
+ if line.startswith(self._lead['comment']):
546
+ # comment line
547
+ if len(line) > 72:
548
+ pos = line.rfind(" ", 6, 72)
549
+ if pos == -1:
550
+ pos = 72
551
+ hunk = line[:pos]
552
+ line = line[pos:].lstrip()
553
+ result.append(hunk)
554
+ while line:
555
+ pos = line.rfind(" ", 0, 66)
556
+ if pos == -1 or len(line) < 66:
557
+ pos = 66
558
+ hunk = line[:pos]
559
+ line = line[pos:].lstrip()
560
+ result.append("%s%s" % (self._lead['comment'], hunk))
561
+ else:
562
+ result.append(line)
563
+ elif line.startswith(self._lead['code']):
564
+ # code line
565
+ pos = split_pos_code(line, 72)
566
+ hunk = line[:pos].rstrip()
567
+ line = line[pos:].lstrip()
568
+ if line:
569
+ hunk += trailing
570
+ result.append(hunk)
571
+ while line:
572
+ pos = split_pos_code(line, 65)
573
+ hunk = line[:pos].rstrip()
574
+ line = line[pos:].lstrip()
575
+ if line:
576
+ hunk += trailing
577
+ result.append("%s%s" % (self._lead['cont'], hunk))
578
+ else:
579
+ result.append(line)
580
+ return result
581
+
582
+ def indent_code(self, code):
583
+ """Accepts a string of code or a list of code lines"""
584
+ if isinstance(code, str):
585
+ code_lines = self.indent_code(code.splitlines(True))
586
+ return ''.join(code_lines)
587
+
588
+ free = self._settings['source_format'] == 'free'
589
+ code = [ line.lstrip(' \t') for line in code ]
590
+
591
+ inc_keyword = ('do ', 'if(', 'if ', 'do\n', 'else', 'program', 'interface')
592
+ dec_keyword = ('end do', 'enddo', 'end if', 'endif', 'else', 'end program', 'end interface')
593
+
594
+ increase = [ int(any(map(line.startswith, inc_keyword)))
595
+ for line in code ]
596
+ decrease = [ int(any(map(line.startswith, dec_keyword)))
597
+ for line in code ]
598
+ continuation = [ int(any(map(line.endswith, ['&', '&\n'])))
599
+ for line in code ]
600
+
601
+ level = 0
602
+ cont_padding = 0
603
+ tabwidth = 3
604
+ new_code = []
605
+ for i, line in enumerate(code):
606
+ if line in ('', '\n'):
607
+ new_code.append(line)
608
+ continue
609
+ level -= decrease[i]
610
+
611
+ if free:
612
+ padding = " "*(level*tabwidth + cont_padding)
613
+ else:
614
+ padding = " "*level*tabwidth
615
+
616
+ line = "%s%s" % (padding, line)
617
+ if not free:
618
+ line = self._pad_leading_columns([line])[0]
619
+
620
+ new_code.append(line)
621
+
622
+ if continuation[i]:
623
+ cont_padding = 2*tabwidth
624
+ else:
625
+ cont_padding = 0
626
+ level += increase[i]
627
+
628
+ if not free:
629
+ return self._wrap_fortran(new_code)
630
+ return new_code
631
+
632
+ def _print_GoTo(self, goto):
633
+ if goto.expr: # computed goto
634
+ return "go to ({labels}), {expr}".format(
635
+ labels=', '.join((self._print(arg) for arg in goto.labels)),
636
+ expr=self._print(goto.expr)
637
+ )
638
+ else:
639
+ lbl, = goto.labels
640
+ return "go to %s" % self._print(lbl)
641
+
642
+ def _print_Program(self, prog):
643
+ return (
644
+ "program {name}\n"
645
+ "{body}\n"
646
+ "end program\n"
647
+ ).format(**prog.kwargs(apply=lambda arg: self._print(arg)))
648
+
649
+ def _print_Module(self, mod):
650
+ return (
651
+ "module {name}\n"
652
+ "{declarations}\n"
653
+ "\ncontains\n\n"
654
+ "{definitions}\n"
655
+ "end module\n"
656
+ ).format(**mod.kwargs(apply=lambda arg: self._print(arg)))
657
+
658
+ def _print_Stream(self, strm):
659
+ if strm.name == 'stdout' and self._settings["standard"] >= 2003:
660
+ self.module_uses['iso_c_binding'].add('stdint=>input_unit')
661
+ return 'input_unit'
662
+ elif strm.name == 'stderr' and self._settings["standard"] >= 2003:
663
+ self.module_uses['iso_c_binding'].add('stdint=>error_unit')
664
+ return 'error_unit'
665
+ else:
666
+ if strm.name == 'stdout':
667
+ return '*'
668
+ else:
669
+ return strm.name
670
+
671
+ def _print_Print(self, ps):
672
+ if ps.format_string != None: # Must be '!= None', cannot be 'is not None'
673
+ fmt = self._print(ps.format_string)
674
+ else:
675
+ fmt = "*"
676
+ return "print {fmt}, {iolist}".format(fmt=fmt, iolist=', '.join(
677
+ (self._print(arg) for arg in ps.print_args)))
678
+
679
+ def _print_Return(self, rs):
680
+ arg, = rs.args
681
+ return "{result_name} = {arg}".format(
682
+ result_name=self._context.get('result_name', 'sympy_result'),
683
+ arg=self._print(arg)
684
+ )
685
+
686
+ def _print_FortranReturn(self, frs):
687
+ arg, = frs.args
688
+ if arg:
689
+ return 'return %s' % self._print(arg)
690
+ else:
691
+ return 'return'
692
+
693
+ def _head(self, entity, fp, **kwargs):
694
+ bind_C_params = fp.attr_params('bind_C')
695
+ if bind_C_params is None:
696
+ bind = ''
697
+ else:
698
+ bind = ' bind(C, name="%s")' % bind_C_params[0] if bind_C_params else ' bind(C)'
699
+ result_name = self._settings.get('result_name', None)
700
+ return (
701
+ "{entity}{name}({arg_names}){result}{bind}\n"
702
+ "{arg_declarations}"
703
+ ).format(
704
+ entity=entity,
705
+ name=self._print(fp.name),
706
+ arg_names=', '.join([self._print(arg.symbol) for arg in fp.parameters]),
707
+ result=(' result(%s)' % result_name) if result_name else '',
708
+ bind=bind,
709
+ arg_declarations='\n'.join((self._print(Declaration(arg)) for arg in fp.parameters))
710
+ )
711
+
712
+ def _print_FunctionPrototype(self, fp):
713
+ entity = "{} function ".format(self._print(fp.return_type))
714
+ return (
715
+ "interface\n"
716
+ "{function_head}\n"
717
+ "end function\n"
718
+ "end interface"
719
+ ).format(function_head=self._head(entity, fp))
720
+
721
+ def _print_FunctionDefinition(self, fd):
722
+ if elemental in fd.attrs:
723
+ prefix = 'elemental '
724
+ elif pure in fd.attrs:
725
+ prefix = 'pure '
726
+ else:
727
+ prefix = ''
728
+
729
+ entity = "{} function ".format(self._print(fd.return_type))
730
+ with printer_context(self, result_name=fd.name):
731
+ return (
732
+ "{prefix}{function_head}\n"
733
+ "{body}\n"
734
+ "end function\n"
735
+ ).format(
736
+ prefix=prefix,
737
+ function_head=self._head(entity, fd),
738
+ body=self._print(fd.body)
739
+ )
740
+
741
+ def _print_Subroutine(self, sub):
742
+ return (
743
+ '{subroutine_head}\n'
744
+ '{body}\n'
745
+ 'end subroutine\n'
746
+ ).format(
747
+ subroutine_head=self._head('subroutine ', sub),
748
+ body=self._print(sub.body)
749
+ )
750
+
751
+ def _print_SubroutineCall(self, scall):
752
+ return 'call {name}({args})'.format(
753
+ name=self._print(scall.name),
754
+ args=', '.join((self._print(arg) for arg in scall.subroutine_args))
755
+ )
756
+
757
+ def _print_use_rename(self, rnm):
758
+ return "%s => %s" % tuple((self._print(arg) for arg in rnm.args))
759
+
760
+ def _print_use(self, use):
761
+ result = 'use %s' % self._print(use.namespace)
762
+ if use.rename != None: # Must be '!= None', cannot be 'is not None'
763
+ result += ', ' + ', '.join([self._print(rnm) for rnm in use.rename])
764
+ if use.only != None: # Must be '!= None', cannot be 'is not None'
765
+ result += ', only: ' + ', '.join([self._print(nly) for nly in use.only])
766
+ return result
767
+
768
+ def _print_BreakToken(self, _):
769
+ return 'exit'
770
+
771
+ def _print_ContinueToken(self, _):
772
+ return 'cycle'
773
+
774
+ def _print_ArrayConstructor(self, ac):
775
+ fmtstr = "[%s]" if self._settings["standard"] >= 2003 else '(/%s/)'
776
+ return fmtstr % ', '.join((self._print(arg) for arg in ac.elements))
777
+
778
+ def _print_ArrayElement(self, elem):
779
+ return '{symbol}({idxs})'.format(
780
+ symbol=self._print(elem.name),
781
+ idxs=', '.join((self._print(arg) for arg in elem.indices))
782
+ )
llmeval-env/lib/python3.10/site-packages/sympy/printing/glsl.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sympy.core import Basic, S
4
+ from sympy.core.function import Lambda
5
+ from sympy.core.numbers import equal_valued
6
+ from sympy.printing.codeprinter import CodePrinter
7
+ from sympy.printing.precedence import precedence
8
+ from functools import reduce
9
+
10
+ known_functions = {
11
+ 'Abs': 'abs',
12
+ 'sin': 'sin',
13
+ 'cos': 'cos',
14
+ 'tan': 'tan',
15
+ 'acos': 'acos',
16
+ 'asin': 'asin',
17
+ 'atan': 'atan',
18
+ 'atan2': 'atan',
19
+ 'ceiling': 'ceil',
20
+ 'floor': 'floor',
21
+ 'sign': 'sign',
22
+ 'exp': 'exp',
23
+ 'log': 'log',
24
+ 'add': 'add',
25
+ 'sub': 'sub',
26
+ 'mul': 'mul',
27
+ 'pow': 'pow'
28
+ }
29
+
30
+ class GLSLPrinter(CodePrinter):
31
+ """
32
+ Rudimentary, generic GLSL printing tools.
33
+
34
+ Additional settings:
35
+ 'use_operators': Boolean (should the printer use operators for +,-,*, or functions?)
36
+ """
37
+ _not_supported: set[Basic] = set()
38
+ printmethod = "_glsl"
39
+ language = "GLSL"
40
+
41
+ _default_settings = {
42
+ 'use_operators': True,
43
+ 'zero': 0,
44
+ 'mat_nested': False,
45
+ 'mat_separator': ',\n',
46
+ 'mat_transpose': False,
47
+ 'array_type': 'float',
48
+ 'glsl_types': True,
49
+
50
+ 'order': None,
51
+ 'full_prec': 'auto',
52
+ 'precision': 9,
53
+ 'user_functions': {},
54
+ 'human': True,
55
+ 'allow_unknown_functions': False,
56
+ 'contract': True,
57
+ 'error_on_reserved': False,
58
+ 'reserved_word_suffix': '_',
59
+ }
60
+
61
+ def __init__(self, settings={}):
62
+ CodePrinter.__init__(self, settings)
63
+ self.known_functions = dict(known_functions)
64
+ userfuncs = settings.get('user_functions', {})
65
+ self.known_functions.update(userfuncs)
66
+
67
+ def _rate_index_position(self, p):
68
+ return p*5
69
+
70
+ def _get_statement(self, codestring):
71
+ return "%s;" % codestring
72
+
73
+ def _get_comment(self, text):
74
+ return "// {}".format(text)
75
+
76
+ def _declare_number_const(self, name, value):
77
+ return "float {} = {};".format(name, value)
78
+
79
+ def _format_code(self, lines):
80
+ return self.indent_code(lines)
81
+
82
+ def indent_code(self, code):
83
+ """Accepts a string of code or a list of code lines"""
84
+
85
+ if isinstance(code, str):
86
+ code_lines = self.indent_code(code.splitlines(True))
87
+ return ''.join(code_lines)
88
+
89
+ tab = " "
90
+ inc_token = ('{', '(', '{\n', '(\n')
91
+ dec_token = ('}', ')')
92
+
93
+ code = [line.lstrip(' \t') for line in code]
94
+
95
+ increase = [int(any(map(line.endswith, inc_token))) for line in code]
96
+ decrease = [int(any(map(line.startswith, dec_token))) for line in code]
97
+
98
+ pretty = []
99
+ level = 0
100
+ for n, line in enumerate(code):
101
+ if line in ('', '\n'):
102
+ pretty.append(line)
103
+ continue
104
+ level -= decrease[n]
105
+ pretty.append("%s%s" % (tab*level, line))
106
+ level += increase[n]
107
+ return pretty
108
+
109
+ def _print_MatrixBase(self, mat):
110
+ mat_separator = self._settings['mat_separator']
111
+ mat_transpose = self._settings['mat_transpose']
112
+ column_vector = (mat.rows == 1) if mat_transpose else (mat.cols == 1)
113
+ A = mat.transpose() if mat_transpose != column_vector else mat
114
+
115
+ glsl_types = self._settings['glsl_types']
116
+ array_type = self._settings['array_type']
117
+ array_size = A.cols*A.rows
118
+ array_constructor = "{}[{}]".format(array_type, array_size)
119
+
120
+ if A.cols == 1:
121
+ return self._print(A[0]);
122
+ if A.rows <= 4 and A.cols <= 4 and glsl_types:
123
+ if A.rows == 1:
124
+ return "vec{}{}".format(
125
+ A.cols, A.table(self,rowstart='(',rowend=')')
126
+ )
127
+ elif A.rows == A.cols:
128
+ return "mat{}({})".format(
129
+ A.rows, A.table(self,rowsep=', ',
130
+ rowstart='',rowend='')
131
+ )
132
+ else:
133
+ return "mat{}x{}({})".format(
134
+ A.cols, A.rows,
135
+ A.table(self,rowsep=', ',
136
+ rowstart='',rowend='')
137
+ )
138
+ elif S.One in A.shape:
139
+ return "{}({})".format(
140
+ array_constructor,
141
+ A.table(self,rowsep=mat_separator,rowstart='',rowend='')
142
+ )
143
+ elif not self._settings['mat_nested']:
144
+ return "{}(\n{}\n) /* a {}x{} matrix */".format(
145
+ array_constructor,
146
+ A.table(self,rowsep=mat_separator,rowstart='',rowend=''),
147
+ A.rows, A.cols
148
+ )
149
+ elif self._settings['mat_nested']:
150
+ return "{}[{}][{}](\n{}\n)".format(
151
+ array_type, A.rows, A.cols,
152
+ A.table(self,rowsep=mat_separator,rowstart='float[](',rowend=')')
153
+ )
154
+
155
+ def _print_SparseRepMatrix(self, mat):
156
+ # do not allow sparse matrices to be made dense
157
+ return self._print_not_supported(mat)
158
+
159
+ def _traverse_matrix_indices(self, mat):
160
+ mat_transpose = self._settings['mat_transpose']
161
+ if mat_transpose:
162
+ rows,cols = mat.shape
163
+ else:
164
+ cols,rows = mat.shape
165
+ return ((i, j) for i in range(cols) for j in range(rows))
166
+
167
+ def _print_MatrixElement(self, expr):
168
+ # print('begin _print_MatrixElement')
169
+ nest = self._settings['mat_nested'];
170
+ glsl_types = self._settings['glsl_types'];
171
+ mat_transpose = self._settings['mat_transpose'];
172
+ if mat_transpose:
173
+ cols,rows = expr.parent.shape
174
+ i,j = expr.j,expr.i
175
+ else:
176
+ rows,cols = expr.parent.shape
177
+ i,j = expr.i,expr.j
178
+ pnt = self._print(expr.parent)
179
+ if glsl_types and ((rows <= 4 and cols <=4) or nest):
180
+ return "{}[{}][{}]".format(pnt, i, j)
181
+ else:
182
+ return "{}[{}]".format(pnt, i + j*rows)
183
+
184
+ def _print_list(self, expr):
185
+ l = ', '.join(self._print(item) for item in expr)
186
+ glsl_types = self._settings['glsl_types']
187
+ array_type = self._settings['array_type']
188
+ array_size = len(expr)
189
+ array_constructor = '{}[{}]'.format(array_type, array_size)
190
+
191
+ if array_size <= 4 and glsl_types:
192
+ return 'vec{}({})'.format(array_size, l)
193
+ else:
194
+ return '{}({})'.format(array_constructor, l)
195
+
196
+ _print_tuple = _print_list
197
+ _print_Tuple = _print_list
198
+
199
+ def _get_loop_opening_ending(self, indices):
200
+ open_lines = []
201
+ close_lines = []
202
+ loopstart = "for (int %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){"
203
+ for i in indices:
204
+ # GLSL arrays start at 0 and end at dimension-1
205
+ open_lines.append(loopstart % {
206
+ 'varble': self._print(i.label),
207
+ 'start': self._print(i.lower),
208
+ 'end': self._print(i.upper + 1)})
209
+ close_lines.append("}")
210
+ return open_lines, close_lines
211
+
212
+ def _print_Function_with_args(self, func, func_args):
213
+ if func in self.known_functions:
214
+ cond_func = self.known_functions[func]
215
+ func = None
216
+ if isinstance(cond_func, str):
217
+ func = cond_func
218
+ else:
219
+ for cond, func in cond_func:
220
+ if cond(func_args):
221
+ break
222
+ if func is not None:
223
+ try:
224
+ return func(*[self.parenthesize(item, 0) for item in func_args])
225
+ except TypeError:
226
+ return '{}({})'.format(func, self.stringify(func_args, ", "))
227
+ elif isinstance(func, Lambda):
228
+ # inlined function
229
+ return self._print(func(*func_args))
230
+ else:
231
+ return self._print_not_supported(func)
232
+
233
+ def _print_Piecewise(self, expr):
234
+ from sympy.codegen.ast import Assignment
235
+ if expr.args[-1].cond != True:
236
+ # We need the last conditional to be a True, otherwise the resulting
237
+ # function may not return a result.
238
+ raise ValueError("All Piecewise expressions must contain an "
239
+ "(expr, True) statement to be used as a default "
240
+ "condition. Without one, the generated "
241
+ "expression may not evaluate to anything under "
242
+ "some condition.")
243
+ lines = []
244
+ if expr.has(Assignment):
245
+ for i, (e, c) in enumerate(expr.args):
246
+ if i == 0:
247
+ lines.append("if (%s) {" % self._print(c))
248
+ elif i == len(expr.args) - 1 and c == True:
249
+ lines.append("else {")
250
+ else:
251
+ lines.append("else if (%s) {" % self._print(c))
252
+ code0 = self._print(e)
253
+ lines.append(code0)
254
+ lines.append("}")
255
+ return "\n".join(lines)
256
+ else:
257
+ # The piecewise was used in an expression, need to do inline
258
+ # operators. This has the downside that inline operators will
259
+ # not work for statements that span multiple lines (Matrix or
260
+ # Indexed expressions).
261
+ ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c),
262
+ self._print(e))
263
+ for e, c in expr.args[:-1]]
264
+ last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
265
+ return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
266
+
267
+ def _print_Idx(self, expr):
268
+ return self._print(expr.label)
269
+
270
+ def _print_Indexed(self, expr):
271
+ # calculate index for 1d array
272
+ dims = expr.shape
273
+ elem = S.Zero
274
+ offset = S.One
275
+ for i in reversed(range(expr.rank)):
276
+ elem += expr.indices[i]*offset
277
+ offset *= dims[i]
278
+ return "{}[{}]".format(
279
+ self._print(expr.base.label),
280
+ self._print(elem)
281
+ )
282
+
283
+ def _print_Pow(self, expr):
284
+ PREC = precedence(expr)
285
+ if equal_valued(expr.exp, -1):
286
+ return '1.0/%s' % (self.parenthesize(expr.base, PREC))
287
+ elif equal_valued(expr.exp, 0.5):
288
+ return 'sqrt(%s)' % self._print(expr.base)
289
+ else:
290
+ try:
291
+ e = self._print(float(expr.exp))
292
+ except TypeError:
293
+ e = self._print(expr.exp)
294
+ return self._print_Function_with_args('pow', (
295
+ self._print(expr.base),
296
+ e
297
+ ))
298
+
299
+ def _print_int(self, expr):
300
+ return str(float(expr))
301
+
302
+ def _print_Rational(self, expr):
303
+ return "{}.0/{}.0".format(expr.p, expr.q)
304
+
305
+ def _print_Relational(self, expr):
306
+ lhs_code = self._print(expr.lhs)
307
+ rhs_code = self._print(expr.rhs)
308
+ op = expr.rel_op
309
+ return "{} {} {}".format(lhs_code, op, rhs_code)
310
+
311
+ def _print_Add(self, expr, order=None):
312
+ if self._settings['use_operators']:
313
+ return CodePrinter._print_Add(self, expr, order=order)
314
+
315
+ terms = expr.as_ordered_terms()
316
+
317
+ def partition(p,l):
318
+ return reduce(lambda x, y: (x[0]+[y], x[1]) if p(y) else (x[0], x[1]+[y]), l, ([], []))
319
+ def add(a,b):
320
+ return self._print_Function_with_args('add', (a, b))
321
+ # return self.known_functions['add']+'(%s, %s)' % (a,b)
322
+ neg, pos = partition(lambda arg: arg.could_extract_minus_sign(), terms)
323
+ if pos:
324
+ s = pos = reduce(lambda a,b: add(a,b), (self._print(t) for t in pos))
325
+ else:
326
+ s = pos = self._print(self._settings['zero'])
327
+
328
+ if neg:
329
+ # sum the absolute values of the negative terms
330
+ neg = reduce(lambda a,b: add(a,b), (self._print(-n) for n in neg))
331
+ # then subtract them from the positive terms
332
+ s = self._print_Function_with_args('sub', (pos,neg))
333
+ # s = self.known_functions['sub']+'(%s, %s)' % (pos,neg)
334
+ return s
335
+
336
+ def _print_Mul(self, expr, **kwargs):
337
+ if self._settings['use_operators']:
338
+ return CodePrinter._print_Mul(self, expr, **kwargs)
339
+ terms = expr.as_ordered_factors()
340
+ def mul(a,b):
341
+ # return self.known_functions['mul']+'(%s, %s)' % (a,b)
342
+ return self._print_Function_with_args('mul', (a,b))
343
+
344
+ s = reduce(lambda a,b: mul(a,b), (self._print(t) for t in terms))
345
+ return s
346
+
347
+ def glsl_code(expr,assign_to=None,**settings):
348
+ """Converts an expr to a string of GLSL code
349
+
350
+ Parameters
351
+ ==========
352
+
353
+ expr : Expr
354
+ A SymPy expression to be converted.
355
+ assign_to : optional
356
+ When given, the argument is used for naming the variable or variables
357
+ to which the expression is assigned. Can be a string, ``Symbol``,
358
+ ``MatrixSymbol`` or ``Indexed`` type object. In cases where ``expr``
359
+ would be printed as an array, a list of string or ``Symbol`` objects
360
+ can also be passed.
361
+
362
+ This is helpful in case of line-wrapping, or for expressions that
363
+ generate multi-line statements. It can also be used to spread an array-like
364
+ expression into multiple assignments.
365
+ use_operators: bool, optional
366
+ If set to False, then *,/,+,- operators will be replaced with functions
367
+ mul, add, and sub, which must be implemented by the user, e.g. for
368
+ implementing non-standard rings or emulated quad/octal precision.
369
+ [default=True]
370
+ glsl_types: bool, optional
371
+ Set this argument to ``False`` in order to avoid using the ``vec`` and ``mat``
372
+ types. The printer will instead use arrays (or nested arrays).
373
+ [default=True]
374
+ mat_nested: bool, optional
375
+ GLSL version 4.3 and above support nested arrays (arrays of arrays). Set this to ``True``
376
+ to render matrices as nested arrays.
377
+ [default=False]
378
+ mat_separator: str, optional
379
+ By default, matrices are rendered with newlines using this separator,
380
+ making them easier to read, but less compact. By removing the newline
381
+ this option can be used to make them more vertically compact.
382
+ [default=',\n']
383
+ mat_transpose: bool, optional
384
+ GLSL's matrix multiplication implementation assumes column-major indexing.
385
+ By default, this printer ignores that convention. Setting this option to
386
+ ``True`` transposes all matrix output.
387
+ [default=False]
388
+ array_type: str, optional
389
+ The GLSL array constructor type.
390
+ [default='float']
391
+ precision : integer, optional
392
+ The precision for numbers such as pi [default=15].
393
+ user_functions : dict, optional
394
+ A dictionary where keys are ``FunctionClass`` instances and values are
395
+ their string representations. Alternatively, the dictionary value can
396
+ be a list of tuples i.e. [(argument_test, js_function_string)]. See
397
+ below for examples.
398
+ human : bool, optional
399
+ If True, the result is a single string that may contain some constant
400
+ declarations for the number symbols. If False, the same information is
401
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
402
+ code_text). [default=True].
403
+ contract: bool, optional
404
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
405
+ rules and the corresponding nested loops over indices are generated.
406
+ Setting contract=False will not generate loops, instead the user is
407
+ responsible to provide values for the indices in the code.
408
+ [default=True].
409
+
410
+ Examples
411
+ ========
412
+
413
+ >>> from sympy import glsl_code, symbols, Rational, sin, ceiling, Abs
414
+ >>> x, tau = symbols("x, tau")
415
+ >>> glsl_code((2*tau)**Rational(7, 2))
416
+ '8*sqrt(2)*pow(tau, 3.5)'
417
+ >>> glsl_code(sin(x), assign_to="float y")
418
+ 'float y = sin(x);'
419
+
420
+ Various GLSL types are supported:
421
+ >>> from sympy import Matrix, glsl_code
422
+ >>> glsl_code(Matrix([1,2,3]))
423
+ 'vec3(1, 2, 3)'
424
+
425
+ >>> glsl_code(Matrix([[1, 2],[3, 4]]))
426
+ 'mat2(1, 2, 3, 4)'
427
+
428
+ Pass ``mat_transpose = True`` to switch to column-major indexing:
429
+ >>> glsl_code(Matrix([[1, 2],[3, 4]]), mat_transpose = True)
430
+ 'mat2(1, 3, 2, 4)'
431
+
432
+ By default, larger matrices get collapsed into float arrays:
433
+ >>> print(glsl_code( Matrix([[1,2,3,4,5],[6,7,8,9,10]]) ))
434
+ float[10](
435
+ 1, 2, 3, 4, 5,
436
+ 6, 7, 8, 9, 10
437
+ ) /* a 2x5 matrix */
438
+
439
+ The type of array constructor used to print GLSL arrays can be controlled
440
+ via the ``array_type`` parameter:
441
+ >>> glsl_code(Matrix([1,2,3,4,5]), array_type='int')
442
+ 'int[5](1, 2, 3, 4, 5)'
443
+
444
+ Passing a list of strings or ``symbols`` to the ``assign_to`` parameter will yield
445
+ a multi-line assignment for each item in an array-like expression:
446
+ >>> x_struct_members = symbols('x.a x.b x.c x.d')
447
+ >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=x_struct_members))
448
+ x.a = 1;
449
+ x.b = 2;
450
+ x.c = 3;
451
+ x.d = 4;
452
+
453
+ This could be useful in cases where it's desirable to modify members of a
454
+ GLSL ``Struct``. It could also be used to spread items from an array-like
455
+ expression into various miscellaneous assignments:
456
+ >>> misc_assignments = ('x[0]', 'x[1]', 'float y', 'float z')
457
+ >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=misc_assignments))
458
+ x[0] = 1;
459
+ x[1] = 2;
460
+ float y = 3;
461
+ float z = 4;
462
+
463
+ Passing ``mat_nested = True`` instead prints out nested float arrays, which are
464
+ supported in GLSL 4.3 and above.
465
+ >>> mat = Matrix([
466
+ ... [ 0, 1, 2],
467
+ ... [ 3, 4, 5],
468
+ ... [ 6, 7, 8],
469
+ ... [ 9, 10, 11],
470
+ ... [12, 13, 14]])
471
+ >>> print(glsl_code( mat, mat_nested = True ))
472
+ float[5][3](
473
+ float[]( 0, 1, 2),
474
+ float[]( 3, 4, 5),
475
+ float[]( 6, 7, 8),
476
+ float[]( 9, 10, 11),
477
+ float[](12, 13, 14)
478
+ )
479
+
480
+
481
+
482
+ Custom printing can be defined for certain types by passing a dictionary of
483
+ "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
484
+ dictionary value can be a list of tuples i.e. [(argument_test,
485
+ js_function_string)].
486
+
487
+ >>> custom_functions = {
488
+ ... "ceiling": "CEIL",
489
+ ... "Abs": [(lambda x: not x.is_integer, "fabs"),
490
+ ... (lambda x: x.is_integer, "ABS")]
491
+ ... }
492
+ >>> glsl_code(Abs(x) + ceiling(x), user_functions=custom_functions)
493
+ 'fabs(x) + CEIL(x)'
494
+
495
+ If further control is needed, addition, subtraction, multiplication and
496
+ division operators can be replaced with ``add``, ``sub``, and ``mul``
497
+ functions. This is done by passing ``use_operators = False``:
498
+
499
+ >>> x,y,z = symbols('x,y,z')
500
+ >>> glsl_code(x*(y+z), use_operators = False)
501
+ 'mul(x, add(y, z))'
502
+ >>> glsl_code(x*(y+z*(x-y)**z), use_operators = False)
503
+ 'mul(x, add(y, mul(z, pow(sub(x, y), z))))'
504
+
505
+ ``Piecewise`` expressions are converted into conditionals. If an
506
+ ``assign_to`` variable is provided an if statement is created, otherwise
507
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
508
+ default term, represented by ``(expr, True)`` then an error will be thrown.
509
+ This is to prevent generating an expression that may not evaluate to
510
+ anything.
511
+
512
+ >>> from sympy import Piecewise
513
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
514
+ >>> print(glsl_code(expr, tau))
515
+ if (x > 0) {
516
+ tau = x + 1;
517
+ }
518
+ else {
519
+ tau = x;
520
+ }
521
+
522
+ Support for loops is provided through ``Indexed`` types. With
523
+ ``contract=True`` these expressions will be turned into loops, whereas
524
+ ``contract=False`` will just print the assignment expression that should be
525
+ looped over:
526
+
527
+ >>> from sympy import Eq, IndexedBase, Idx
528
+ >>> len_y = 5
529
+ >>> y = IndexedBase('y', shape=(len_y,))
530
+ >>> t = IndexedBase('t', shape=(len_y,))
531
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
532
+ >>> i = Idx('i', len_y-1)
533
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
534
+ >>> glsl_code(e.rhs, assign_to=e.lhs, contract=False)
535
+ 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
536
+
537
+ >>> from sympy import Matrix, MatrixSymbol
538
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
539
+ >>> A = MatrixSymbol('A', 3, 1)
540
+ >>> print(glsl_code(mat, A))
541
+ A[0][0] = pow(x, 2.0);
542
+ if (x > 0) {
543
+ A[1][0] = x + 1;
544
+ }
545
+ else {
546
+ A[1][0] = x;
547
+ }
548
+ A[2][0] = sin(x);
549
+ """
550
+ return GLSLPrinter(settings).doprint(expr,assign_to)
551
+
552
+ def print_glsl(expr, **settings):
553
+ """Prints the GLSL representation of the given expression.
554
+
555
+ See GLSLPrinter init function for settings.
556
+ """
557
+ print(glsl_code(expr, **settings))
llmeval-env/lib/python3.10/site-packages/sympy/printing/gtk.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.printing.mathml import mathml
2
+ from sympy.utilities.mathml import c2p
3
+ import tempfile
4
+ import subprocess
5
+
6
+
7
+ def print_gtk(x, start_viewer=True):
8
+ """Print to Gtkmathview, a gtk widget capable of rendering MathML.
9
+
10
+ Needs libgtkmathview-bin"""
11
+ with tempfile.NamedTemporaryFile('w') as file:
12
+ file.write(c2p(mathml(x), simple=True))
13
+ file.flush()
14
+
15
+ if start_viewer:
16
+ subprocess.check_call(('mathmlviewer', file.name))
llmeval-env/lib/python3.10/site-packages/sympy/printing/jscode.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Javascript code printer
3
+
4
+ The JavascriptCodePrinter converts single SymPy expressions into single
5
+ Javascript expressions, using the functions defined in the Javascript
6
+ Math object where possible.
7
+
8
+ """
9
+
10
+ from __future__ import annotations
11
+ from typing import Any
12
+
13
+ from sympy.core import S
14
+ from sympy.core.numbers import equal_valued
15
+ from sympy.printing.codeprinter import CodePrinter
16
+ from sympy.printing.precedence import precedence, PRECEDENCE
17
+
18
+
19
+ # dictionary mapping SymPy function to (argument_conditions, Javascript_function).
20
+ # Used in JavascriptCodePrinter._print_Function(self)
21
+ known_functions = {
22
+ 'Abs': 'Math.abs',
23
+ 'acos': 'Math.acos',
24
+ 'acosh': 'Math.acosh',
25
+ 'asin': 'Math.asin',
26
+ 'asinh': 'Math.asinh',
27
+ 'atan': 'Math.atan',
28
+ 'atan2': 'Math.atan2',
29
+ 'atanh': 'Math.atanh',
30
+ 'ceiling': 'Math.ceil',
31
+ 'cos': 'Math.cos',
32
+ 'cosh': 'Math.cosh',
33
+ 'exp': 'Math.exp',
34
+ 'floor': 'Math.floor',
35
+ 'log': 'Math.log',
36
+ 'Max': 'Math.max',
37
+ 'Min': 'Math.min',
38
+ 'sign': 'Math.sign',
39
+ 'sin': 'Math.sin',
40
+ 'sinh': 'Math.sinh',
41
+ 'tan': 'Math.tan',
42
+ 'tanh': 'Math.tanh',
43
+ }
44
+
45
+
46
+ class JavascriptCodePrinter(CodePrinter):
47
+ """"A Printer to convert Python expressions to strings of JavaScript code
48
+ """
49
+ printmethod = '_javascript'
50
+ language = 'JavaScript'
51
+
52
+ _default_settings: dict[str, Any] = {
53
+ 'order': None,
54
+ 'full_prec': 'auto',
55
+ 'precision': 17,
56
+ 'user_functions': {},
57
+ 'human': True,
58
+ 'allow_unknown_functions': False,
59
+ 'contract': True,
60
+ }
61
+
62
+ def __init__(self, settings={}):
63
+ CodePrinter.__init__(self, settings)
64
+ self.known_functions = dict(known_functions)
65
+ userfuncs = settings.get('user_functions', {})
66
+ self.known_functions.update(userfuncs)
67
+
68
+ def _rate_index_position(self, p):
69
+ return p*5
70
+
71
+ def _get_statement(self, codestring):
72
+ return "%s;" % codestring
73
+
74
+ def _get_comment(self, text):
75
+ return "// {}".format(text)
76
+
77
+ def _declare_number_const(self, name, value):
78
+ return "var {} = {};".format(name, value.evalf(self._settings['precision']))
79
+
80
+ def _format_code(self, lines):
81
+ return self.indent_code(lines)
82
+
83
+ def _traverse_matrix_indices(self, mat):
84
+ rows, cols = mat.shape
85
+ return ((i, j) for i in range(rows) for j in range(cols))
86
+
87
+ def _get_loop_opening_ending(self, indices):
88
+ open_lines = []
89
+ close_lines = []
90
+ loopstart = "for (var %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){"
91
+ for i in indices:
92
+ # Javascript arrays start at 0 and end at dimension-1
93
+ open_lines.append(loopstart % {
94
+ 'varble': self._print(i.label),
95
+ 'start': self._print(i.lower),
96
+ 'end': self._print(i.upper + 1)})
97
+ close_lines.append("}")
98
+ return open_lines, close_lines
99
+
100
+ def _print_Pow(self, expr):
101
+ PREC = precedence(expr)
102
+ if equal_valued(expr.exp, -1):
103
+ return '1/%s' % (self.parenthesize(expr.base, PREC))
104
+ elif equal_valued(expr.exp, 0.5):
105
+ return 'Math.sqrt(%s)' % self._print(expr.base)
106
+ elif expr.exp == S.One/3:
107
+ return 'Math.cbrt(%s)' % self._print(expr.base)
108
+ else:
109
+ return 'Math.pow(%s, %s)' % (self._print(expr.base),
110
+ self._print(expr.exp))
111
+
112
+ def _print_Rational(self, expr):
113
+ p, q = int(expr.p), int(expr.q)
114
+ return '%d/%d' % (p, q)
115
+
116
+ def _print_Mod(self, expr):
117
+ num, den = expr.args
118
+ PREC = precedence(expr)
119
+ snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args]
120
+ # % is remainder (same sign as numerator), not modulo (same sign as
121
+ # denominator), in js. Hence, % only works as modulo if both numbers
122
+ # have the same sign
123
+ if (num.is_nonnegative and den.is_nonnegative or
124
+ num.is_nonpositive and den.is_nonpositive):
125
+ return f"{snum} % {sden}"
126
+ return f"(({snum} % {sden}) + {sden}) % {sden}"
127
+
128
+ def _print_Relational(self, expr):
129
+ lhs_code = self._print(expr.lhs)
130
+ rhs_code = self._print(expr.rhs)
131
+ op = expr.rel_op
132
+ return "{} {} {}".format(lhs_code, op, rhs_code)
133
+
134
+ def _print_Indexed(self, expr):
135
+ # calculate index for 1d array
136
+ dims = expr.shape
137
+ elem = S.Zero
138
+ offset = S.One
139
+ for i in reversed(range(expr.rank)):
140
+ elem += expr.indices[i]*offset
141
+ offset *= dims[i]
142
+ return "%s[%s]" % (self._print(expr.base.label), self._print(elem))
143
+
144
+ def _print_Idx(self, expr):
145
+ return self._print(expr.label)
146
+
147
+ def _print_Exp1(self, expr):
148
+ return "Math.E"
149
+
150
+ def _print_Pi(self, expr):
151
+ return 'Math.PI'
152
+
153
+ def _print_Infinity(self, expr):
154
+ return 'Number.POSITIVE_INFINITY'
155
+
156
+ def _print_NegativeInfinity(self, expr):
157
+ return 'Number.NEGATIVE_INFINITY'
158
+
159
+ def _print_Piecewise(self, expr):
160
+ from sympy.codegen.ast import Assignment
161
+ if expr.args[-1].cond != True:
162
+ # We need the last conditional to be a True, otherwise the resulting
163
+ # function may not return a result.
164
+ raise ValueError("All Piecewise expressions must contain an "
165
+ "(expr, True) statement to be used as a default "
166
+ "condition. Without one, the generated "
167
+ "expression may not evaluate to anything under "
168
+ "some condition.")
169
+ lines = []
170
+ if expr.has(Assignment):
171
+ for i, (e, c) in enumerate(expr.args):
172
+ if i == 0:
173
+ lines.append("if (%s) {" % self._print(c))
174
+ elif i == len(expr.args) - 1 and c == True:
175
+ lines.append("else {")
176
+ else:
177
+ lines.append("else if (%s) {" % self._print(c))
178
+ code0 = self._print(e)
179
+ lines.append(code0)
180
+ lines.append("}")
181
+ return "\n".join(lines)
182
+ else:
183
+ # The piecewise was used in an expression, need to do inline
184
+ # operators. This has the downside that inline operators will
185
+ # not work for statements that span multiple lines (Matrix or
186
+ # Indexed expressions).
187
+ ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e))
188
+ for e, c in expr.args[:-1]]
189
+ last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
190
+ return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
191
+
192
+ def _print_MatrixElement(self, expr):
193
+ return "{}[{}]".format(self.parenthesize(expr.parent,
194
+ PRECEDENCE["Atom"], strict=True),
195
+ expr.j + expr.i*expr.parent.shape[1])
196
+
197
+ def indent_code(self, code):
198
+ """Accepts a string of code or a list of code lines"""
199
+
200
+ if isinstance(code, str):
201
+ code_lines = self.indent_code(code.splitlines(True))
202
+ return ''.join(code_lines)
203
+
204
+ tab = " "
205
+ inc_token = ('{', '(', '{\n', '(\n')
206
+ dec_token = ('}', ')')
207
+
208
+ code = [ line.lstrip(' \t') for line in code ]
209
+
210
+ increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
211
+ decrease = [ int(any(map(line.startswith, dec_token)))
212
+ for line in code ]
213
+
214
+ pretty = []
215
+ level = 0
216
+ for n, line in enumerate(code):
217
+ if line in ('', '\n'):
218
+ pretty.append(line)
219
+ continue
220
+ level -= decrease[n]
221
+ pretty.append("%s%s" % (tab*level, line))
222
+ level += increase[n]
223
+ return pretty
224
+
225
+
226
+ def jscode(expr, assign_to=None, **settings):
227
+ """Converts an expr to a string of javascript code
228
+
229
+ Parameters
230
+ ==========
231
+
232
+ expr : Expr
233
+ A SymPy expression to be converted.
234
+ assign_to : optional
235
+ When given, the argument is used as the name of the variable to which
236
+ the expression is assigned. Can be a string, ``Symbol``,
237
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
238
+ line-wrapping, or for expressions that generate multi-line statements.
239
+ precision : integer, optional
240
+ The precision for numbers such as pi [default=15].
241
+ user_functions : dict, optional
242
+ A dictionary where keys are ``FunctionClass`` instances and values are
243
+ their string representations. Alternatively, the dictionary value can
244
+ be a list of tuples i.e. [(argument_test, js_function_string)]. See
245
+ below for examples.
246
+ human : bool, optional
247
+ If True, the result is a single string that may contain some constant
248
+ declarations for the number symbols. If False, the same information is
249
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
250
+ code_text). [default=True].
251
+ contract: bool, optional
252
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
253
+ rules and the corresponding nested loops over indices are generated.
254
+ Setting contract=False will not generate loops, instead the user is
255
+ responsible to provide values for the indices in the code.
256
+ [default=True].
257
+
258
+ Examples
259
+ ========
260
+
261
+ >>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs
262
+ >>> x, tau = symbols("x, tau")
263
+ >>> jscode((2*tau)**Rational(7, 2))
264
+ '8*Math.sqrt(2)*Math.pow(tau, 7/2)'
265
+ >>> jscode(sin(x), assign_to="s")
266
+ 's = Math.sin(x);'
267
+
268
+ Custom printing can be defined for certain types by passing a dictionary of
269
+ "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
270
+ dictionary value can be a list of tuples i.e. [(argument_test,
271
+ js_function_string)].
272
+
273
+ >>> custom_functions = {
274
+ ... "ceiling": "CEIL",
275
+ ... "Abs": [(lambda x: not x.is_integer, "fabs"),
276
+ ... (lambda x: x.is_integer, "ABS")]
277
+ ... }
278
+ >>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions)
279
+ 'fabs(x) + CEIL(x)'
280
+
281
+ ``Piecewise`` expressions are converted into conditionals. If an
282
+ ``assign_to`` variable is provided an if statement is created, otherwise
283
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
284
+ default term, represented by ``(expr, True)`` then an error will be thrown.
285
+ This is to prevent generating an expression that may not evaluate to
286
+ anything.
287
+
288
+ >>> from sympy import Piecewise
289
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
290
+ >>> print(jscode(expr, tau))
291
+ if (x > 0) {
292
+ tau = x + 1;
293
+ }
294
+ else {
295
+ tau = x;
296
+ }
297
+
298
+ Support for loops is provided through ``Indexed`` types. With
299
+ ``contract=True`` these expressions will be turned into loops, whereas
300
+ ``contract=False`` will just print the assignment expression that should be
301
+ looped over:
302
+
303
+ >>> from sympy import Eq, IndexedBase, Idx
304
+ >>> len_y = 5
305
+ >>> y = IndexedBase('y', shape=(len_y,))
306
+ >>> t = IndexedBase('t', shape=(len_y,))
307
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
308
+ >>> i = Idx('i', len_y-1)
309
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
310
+ >>> jscode(e.rhs, assign_to=e.lhs, contract=False)
311
+ 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
312
+
313
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
314
+ must be provided to ``assign_to``. Note that any expression that can be
315
+ generated normally can also exist inside a Matrix:
316
+
317
+ >>> from sympy import Matrix, MatrixSymbol
318
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
319
+ >>> A = MatrixSymbol('A', 3, 1)
320
+ >>> print(jscode(mat, A))
321
+ A[0] = Math.pow(x, 2);
322
+ if (x > 0) {
323
+ A[1] = x + 1;
324
+ }
325
+ else {
326
+ A[1] = x;
327
+ }
328
+ A[2] = Math.sin(x);
329
+ """
330
+
331
+ return JavascriptCodePrinter(settings).doprint(expr, assign_to)
332
+
333
+
334
+ def print_jscode(expr, **settings):
335
+ """Prints the Javascript representation of the given expression.
336
+
337
+ See jscode for the meaning of the optional arguments.
338
+ """
339
+ print(jscode(expr, **settings))
llmeval-env/lib/python3.10/site-packages/sympy/printing/julia.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Julia code printer
3
+
4
+ The `JuliaCodePrinter` converts SymPy expressions into Julia expressions.
5
+
6
+ A complete code generator, which uses `julia_code` extensively, can be found
7
+ in `sympy.utilities.codegen`. The `codegen` module can be used to generate
8
+ complete source code files.
9
+
10
+ """
11
+
12
+ from __future__ import annotations
13
+ from typing import Any
14
+
15
+ from sympy.core import Mul, Pow, S, Rational
16
+ from sympy.core.mul import _keep_coeff
17
+ from sympy.core.numbers import equal_valued
18
+ from sympy.printing.codeprinter import CodePrinter
19
+ from sympy.printing.precedence import precedence, PRECEDENCE
20
+ from re import search
21
+
22
+ # List of known functions. First, those that have the same name in
23
+ # SymPy and Julia. This is almost certainly incomplete!
24
+ known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc",
25
+ "asin", "acos", "atan", "acot", "asec", "acsc",
26
+ "sinh", "cosh", "tanh", "coth", "sech", "csch",
27
+ "asinh", "acosh", "atanh", "acoth", "asech", "acsch",
28
+ "sinc", "atan2", "sign", "floor", "log", "exp",
29
+ "cbrt", "sqrt", "erf", "erfc", "erfi",
30
+ "factorial", "gamma", "digamma", "trigamma",
31
+ "polygamma", "beta",
32
+ "airyai", "airyaiprime", "airybi", "airybiprime",
33
+ "besselj", "bessely", "besseli", "besselk",
34
+ "erfinv", "erfcinv"]
35
+ # These functions have different names ("SymPy": "Julia"), more
36
+ # generally a mapping to (argument_conditions, julia_function).
37
+ known_fcns_src2 = {
38
+ "Abs": "abs",
39
+ "ceiling": "ceil",
40
+ "conjugate": "conj",
41
+ "hankel1": "hankelh1",
42
+ "hankel2": "hankelh2",
43
+ "im": "imag",
44
+ "re": "real"
45
+ }
46
+
47
+
48
+ class JuliaCodePrinter(CodePrinter):
49
+ """
50
+ A printer to convert expressions to strings of Julia code.
51
+ """
52
+ printmethod = "_julia"
53
+ language = "Julia"
54
+
55
+ _operators = {
56
+ 'and': '&&',
57
+ 'or': '||',
58
+ 'not': '!',
59
+ }
60
+
61
+ _default_settings: dict[str, Any] = {
62
+ 'order': None,
63
+ 'full_prec': 'auto',
64
+ 'precision': 17,
65
+ 'user_functions': {},
66
+ 'human': True,
67
+ 'allow_unknown_functions': False,
68
+ 'contract': True,
69
+ 'inline': True,
70
+ }
71
+ # Note: contract is for expressing tensors as loops (if True), or just
72
+ # assignment (if False). FIXME: this should be looked a more carefully
73
+ # for Julia.
74
+
75
+ def __init__(self, settings={}):
76
+ super().__init__(settings)
77
+ self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))
78
+ self.known_functions.update(dict(known_fcns_src2))
79
+ userfuncs = settings.get('user_functions', {})
80
+ self.known_functions.update(userfuncs)
81
+
82
+
83
+ def _rate_index_position(self, p):
84
+ return p*5
85
+
86
+
87
+ def _get_statement(self, codestring):
88
+ return "%s" % codestring
89
+
90
+
91
+ def _get_comment(self, text):
92
+ return "# {}".format(text)
93
+
94
+
95
+ def _declare_number_const(self, name, value):
96
+ return "const {} = {}".format(name, value)
97
+
98
+
99
+ def _format_code(self, lines):
100
+ return self.indent_code(lines)
101
+
102
+
103
+ def _traverse_matrix_indices(self, mat):
104
+ # Julia uses Fortran order (column-major)
105
+ rows, cols = mat.shape
106
+ return ((i, j) for j in range(cols) for i in range(rows))
107
+
108
+
109
+ def _get_loop_opening_ending(self, indices):
110
+ open_lines = []
111
+ close_lines = []
112
+ for i in indices:
113
+ # Julia arrays start at 1 and end at dimension
114
+ var, start, stop = map(self._print,
115
+ [i.label, i.lower + 1, i.upper + 1])
116
+ open_lines.append("for %s = %s:%s" % (var, start, stop))
117
+ close_lines.append("end")
118
+ return open_lines, close_lines
119
+
120
+
121
+ def _print_Mul(self, expr):
122
+ # print complex numbers nicely in Julia
123
+ if (expr.is_number and expr.is_imaginary and
124
+ expr.as_coeff_Mul()[0].is_integer):
125
+ return "%sim" % self._print(-S.ImaginaryUnit*expr)
126
+
127
+ # cribbed from str.py
128
+ prec = precedence(expr)
129
+
130
+ c, e = expr.as_coeff_Mul()
131
+ if c < 0:
132
+ expr = _keep_coeff(-c, e)
133
+ sign = "-"
134
+ else:
135
+ sign = ""
136
+
137
+ a = [] # items in the numerator
138
+ b = [] # items that are in the denominator (if any)
139
+
140
+ pow_paren = [] # Will collect all pow with more than one base element and exp = -1
141
+
142
+ if self.order not in ('old', 'none'):
143
+ args = expr.as_ordered_factors()
144
+ else:
145
+ # use make_args in case expr was something like -x -> x
146
+ args = Mul.make_args(expr)
147
+
148
+ # Gather args for numerator/denominator
149
+ for item in args:
150
+ if (item.is_commutative and item.is_Pow and item.exp.is_Rational
151
+ and item.exp.is_negative):
152
+ if item.exp != -1:
153
+ b.append(Pow(item.base, -item.exp, evaluate=False))
154
+ else:
155
+ if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
156
+ pow_paren.append(item)
157
+ b.append(Pow(item.base, -item.exp))
158
+ elif item.is_Rational and item is not S.Infinity and item.p == 1:
159
+ # Save the Rational type in julia Unless the numerator is 1.
160
+ # For example:
161
+ # julia_code(Rational(3, 7)*x) --> (3 // 7) * x
162
+ # julia_code(x/3) --> x / 3 but not x * (1 // 3)
163
+ b.append(Rational(item.q))
164
+ else:
165
+ a.append(item)
166
+
167
+ a = a or [S.One]
168
+
169
+ a_str = [self.parenthesize(x, prec) for x in a]
170
+ b_str = [self.parenthesize(x, prec) for x in b]
171
+
172
+ # To parenthesize Pow with exp = -1 and having more than one Symbol
173
+ for item in pow_paren:
174
+ if item.base in b:
175
+ b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
176
+
177
+ # from here it differs from str.py to deal with "*" and ".*"
178
+ def multjoin(a, a_str):
179
+ # here we probably are assuming the constants will come first
180
+ r = a_str[0]
181
+ for i in range(1, len(a)):
182
+ mulsym = '*' if a[i-1].is_number else '.*'
183
+ r = "%s %s %s" % (r, mulsym, a_str[i])
184
+ return r
185
+
186
+ if not b:
187
+ return sign + multjoin(a, a_str)
188
+ elif len(b) == 1:
189
+ divsym = '/' if b[0].is_number else './'
190
+ return "%s %s %s" % (sign+multjoin(a, a_str), divsym, b_str[0])
191
+ else:
192
+ divsym = '/' if all(bi.is_number for bi in b) else './'
193
+ return "%s %s (%s)" % (sign + multjoin(a, a_str), divsym, multjoin(b, b_str))
194
+
195
+ def _print_Relational(self, expr):
196
+ lhs_code = self._print(expr.lhs)
197
+ rhs_code = self._print(expr.rhs)
198
+ op = expr.rel_op
199
+ return "{} {} {}".format(lhs_code, op, rhs_code)
200
+
201
+ def _print_Pow(self, expr):
202
+ powsymbol = '^' if all(x.is_number for x in expr.args) else '.^'
203
+
204
+ PREC = precedence(expr)
205
+
206
+ if equal_valued(expr.exp, 0.5):
207
+ return "sqrt(%s)" % self._print(expr.base)
208
+
209
+ if expr.is_commutative:
210
+ if equal_valued(expr.exp, -0.5):
211
+ sym = '/' if expr.base.is_number else './'
212
+ return "1 %s sqrt(%s)" % (sym, self._print(expr.base))
213
+ if equal_valued(expr.exp, -1):
214
+ sym = '/' if expr.base.is_number else './'
215
+ return "1 %s %s" % (sym, self.parenthesize(expr.base, PREC))
216
+
217
+ return '%s %s %s' % (self.parenthesize(expr.base, PREC), powsymbol,
218
+ self.parenthesize(expr.exp, PREC))
219
+
220
+
221
+ def _print_MatPow(self, expr):
222
+ PREC = precedence(expr)
223
+ return '%s ^ %s' % (self.parenthesize(expr.base, PREC),
224
+ self.parenthesize(expr.exp, PREC))
225
+
226
+
227
+ def _print_Pi(self, expr):
228
+ if self._settings["inline"]:
229
+ return "pi"
230
+ else:
231
+ return super()._print_NumberSymbol(expr)
232
+
233
+
234
+ def _print_ImaginaryUnit(self, expr):
235
+ return "im"
236
+
237
+
238
+ def _print_Exp1(self, expr):
239
+ if self._settings["inline"]:
240
+ return "e"
241
+ else:
242
+ return super()._print_NumberSymbol(expr)
243
+
244
+
245
+ def _print_EulerGamma(self, expr):
246
+ if self._settings["inline"]:
247
+ return "eulergamma"
248
+ else:
249
+ return super()._print_NumberSymbol(expr)
250
+
251
+
252
+ def _print_Catalan(self, expr):
253
+ if self._settings["inline"]:
254
+ return "catalan"
255
+ else:
256
+ return super()._print_NumberSymbol(expr)
257
+
258
+
259
+ def _print_GoldenRatio(self, expr):
260
+ if self._settings["inline"]:
261
+ return "golden"
262
+ else:
263
+ return super()._print_NumberSymbol(expr)
264
+
265
+
266
+ def _print_Assignment(self, expr):
267
+ from sympy.codegen.ast import Assignment
268
+ from sympy.functions.elementary.piecewise import Piecewise
269
+ from sympy.tensor.indexed import IndexedBase
270
+ # Copied from codeprinter, but remove special MatrixSymbol treatment
271
+ lhs = expr.lhs
272
+ rhs = expr.rhs
273
+ # We special case assignments that take multiple lines
274
+ if not self._settings["inline"] and isinstance(expr.rhs, Piecewise):
275
+ # Here we modify Piecewise so each expression is now
276
+ # an Assignment, and then continue on the print.
277
+ expressions = []
278
+ conditions = []
279
+ for (e, c) in rhs.args:
280
+ expressions.append(Assignment(lhs, e))
281
+ conditions.append(c)
282
+ temp = Piecewise(*zip(expressions, conditions))
283
+ return self._print(temp)
284
+ if self._settings["contract"] and (lhs.has(IndexedBase) or
285
+ rhs.has(IndexedBase)):
286
+ # Here we check if there is looping to be done, and if so
287
+ # print the required loops.
288
+ return self._doprint_loops(rhs, lhs)
289
+ else:
290
+ lhs_code = self._print(lhs)
291
+ rhs_code = self._print(rhs)
292
+ return self._get_statement("%s = %s" % (lhs_code, rhs_code))
293
+
294
+
295
+ def _print_Infinity(self, expr):
296
+ return 'Inf'
297
+
298
+
299
+ def _print_NegativeInfinity(self, expr):
300
+ return '-Inf'
301
+
302
+
303
+ def _print_NaN(self, expr):
304
+ return 'NaN'
305
+
306
+
307
+ def _print_list(self, expr):
308
+ return 'Any[' + ', '.join(self._print(a) for a in expr) + ']'
309
+
310
+
311
+ def _print_tuple(self, expr):
312
+ if len(expr) == 1:
313
+ return "(%s,)" % self._print(expr[0])
314
+ else:
315
+ return "(%s)" % self.stringify(expr, ", ")
316
+ _print_Tuple = _print_tuple
317
+
318
+
319
+ def _print_BooleanTrue(self, expr):
320
+ return "true"
321
+
322
+
323
+ def _print_BooleanFalse(self, expr):
324
+ return "false"
325
+
326
+
327
+ def _print_bool(self, expr):
328
+ return str(expr).lower()
329
+
330
+
331
+ # Could generate quadrature code for definite Integrals?
332
+ #_print_Integral = _print_not_supported
333
+
334
+
335
+ def _print_MatrixBase(self, A):
336
+ # Handle zero dimensions:
337
+ if S.Zero in A.shape:
338
+ return 'zeros(%s, %s)' % (A.rows, A.cols)
339
+ elif (A.rows, A.cols) == (1, 1):
340
+ return "[%s]" % A[0, 0]
341
+ elif A.rows == 1:
342
+ return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ')
343
+ elif A.cols == 1:
344
+ # note .table would unnecessarily equispace the rows
345
+ return "[%s]" % ", ".join([self._print(a) for a in A])
346
+ return "[%s]" % A.table(self, rowstart='', rowend='',
347
+ rowsep=';\n', colsep=' ')
348
+
349
+
350
+ def _print_SparseRepMatrix(self, A):
351
+ from sympy.matrices import Matrix
352
+ L = A.col_list();
353
+ # make row vectors of the indices and entries
354
+ I = Matrix([k[0] + 1 for k in L])
355
+ J = Matrix([k[1] + 1 for k in L])
356
+ AIJ = Matrix([k[2] for k in L])
357
+ return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J),
358
+ self._print(AIJ), A.rows, A.cols)
359
+
360
+
361
+ def _print_MatrixElement(self, expr):
362
+ return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
363
+ + '[%s,%s]' % (expr.i + 1, expr.j + 1)
364
+
365
+
366
+ def _print_MatrixSlice(self, expr):
367
+ def strslice(x, lim):
368
+ l = x[0] + 1
369
+ h = x[1]
370
+ step = x[2]
371
+ lstr = self._print(l)
372
+ hstr = 'end' if h == lim else self._print(h)
373
+ if step == 1:
374
+ if l == 1 and h == lim:
375
+ return ':'
376
+ if l == h:
377
+ return lstr
378
+ else:
379
+ return lstr + ':' + hstr
380
+ else:
381
+ return ':'.join((lstr, self._print(step), hstr))
382
+ return (self._print(expr.parent) + '[' +
383
+ strslice(expr.rowslice, expr.parent.shape[0]) + ',' +
384
+ strslice(expr.colslice, expr.parent.shape[1]) + ']')
385
+
386
+
387
+ def _print_Indexed(self, expr):
388
+ inds = [ self._print(i) for i in expr.indices ]
389
+ return "%s[%s]" % (self._print(expr.base.label), ",".join(inds))
390
+
391
+
392
+ def _print_Idx(self, expr):
393
+ return self._print(expr.label)
394
+
395
+
396
+ def _print_Identity(self, expr):
397
+ return "eye(%s)" % self._print(expr.shape[0])
398
+
399
+ def _print_HadamardProduct(self, expr):
400
+ return ' .* '.join([self.parenthesize(arg, precedence(expr))
401
+ for arg in expr.args])
402
+
403
+ def _print_HadamardPower(self, expr):
404
+ PREC = precedence(expr)
405
+ return '.**'.join([
406
+ self.parenthesize(expr.base, PREC),
407
+ self.parenthesize(expr.exp, PREC)
408
+ ])
409
+
410
+ def _print_Rational(self, expr):
411
+ if expr.q == 1:
412
+ return str(expr.p)
413
+ return "%s // %s" % (expr.p, expr.q)
414
+
415
+ # Note: as of 2022, Julia doesn't have spherical Bessel functions
416
+ def _print_jn(self, expr):
417
+ from sympy.functions import sqrt, besselj
418
+ x = expr.argument
419
+ expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x)
420
+ return self._print(expr2)
421
+
422
+
423
+ def _print_yn(self, expr):
424
+ from sympy.functions import sqrt, bessely
425
+ x = expr.argument
426
+ expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x)
427
+ return self._print(expr2)
428
+
429
+
430
+ def _print_Piecewise(self, expr):
431
+ if expr.args[-1].cond != True:
432
+ # We need the last conditional to be a True, otherwise the resulting
433
+ # function may not return a result.
434
+ raise ValueError("All Piecewise expressions must contain an "
435
+ "(expr, True) statement to be used as a default "
436
+ "condition. Without one, the generated "
437
+ "expression may not evaluate to anything under "
438
+ "some condition.")
439
+ lines = []
440
+ if self._settings["inline"]:
441
+ # Express each (cond, expr) pair in a nested Horner form:
442
+ # (condition) .* (expr) + (not cond) .* (<others>)
443
+ # Expressions that result in multiple statements won't work here.
444
+ ecpairs = ["({}) ? ({}) :".format
445
+ (self._print(c), self._print(e))
446
+ for e, c in expr.args[:-1]]
447
+ elast = " (%s)" % self._print(expr.args[-1].expr)
448
+ pw = "\n".join(ecpairs) + elast
449
+ # Note: current need these outer brackets for 2*pw. Would be
450
+ # nicer to teach parenthesize() to do this for us when needed!
451
+ return "(" + pw + ")"
452
+ else:
453
+ for i, (e, c) in enumerate(expr.args):
454
+ if i == 0:
455
+ lines.append("if (%s)" % self._print(c))
456
+ elif i == len(expr.args) - 1 and c == True:
457
+ lines.append("else")
458
+ else:
459
+ lines.append("elseif (%s)" % self._print(c))
460
+ code0 = self._print(e)
461
+ lines.append(code0)
462
+ if i == len(expr.args) - 1:
463
+ lines.append("end")
464
+ return "\n".join(lines)
465
+
466
+ def _print_MatMul(self, expr):
467
+ c, m = expr.as_coeff_mmul()
468
+
469
+ sign = ""
470
+ if c.is_number:
471
+ re, im = c.as_real_imag()
472
+ if im.is_zero and re.is_negative:
473
+ expr = _keep_coeff(-c, m)
474
+ sign = "-"
475
+ elif re.is_zero and im.is_negative:
476
+ expr = _keep_coeff(-c, m)
477
+ sign = "-"
478
+
479
+ return sign + ' * '.join(
480
+ (self.parenthesize(arg, precedence(expr)) for arg in expr.args)
481
+ )
482
+
483
+
484
+ def indent_code(self, code):
485
+ """Accepts a string of code or a list of code lines"""
486
+
487
+ # code mostly copied from ccode
488
+ if isinstance(code, str):
489
+ code_lines = self.indent_code(code.splitlines(True))
490
+ return ''.join(code_lines)
491
+
492
+ tab = " "
493
+ inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ')
494
+ dec_regex = ('^end$', '^elseif ', '^else$')
495
+
496
+ # pre-strip left-space from the code
497
+ code = [ line.lstrip(' \t') for line in code ]
498
+
499
+ increase = [ int(any(search(re, line) for re in inc_regex))
500
+ for line in code ]
501
+ decrease = [ int(any(search(re, line) for re in dec_regex))
502
+ for line in code ]
503
+
504
+ pretty = []
505
+ level = 0
506
+ for n, line in enumerate(code):
507
+ if line in ('', '\n'):
508
+ pretty.append(line)
509
+ continue
510
+ level -= decrease[n]
511
+ pretty.append("%s%s" % (tab*level, line))
512
+ level += increase[n]
513
+ return pretty
514
+
515
+
516
+ def julia_code(expr, assign_to=None, **settings):
517
+ r"""Converts `expr` to a string of Julia code.
518
+
519
+ Parameters
520
+ ==========
521
+
522
+ expr : Expr
523
+ A SymPy expression to be converted.
524
+ assign_to : optional
525
+ When given, the argument is used as the name of the variable to which
526
+ the expression is assigned. Can be a string, ``Symbol``,
527
+ ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
528
+ expressions that generate multi-line statements.
529
+ precision : integer, optional
530
+ The precision for numbers such as pi [default=16].
531
+ user_functions : dict, optional
532
+ A dictionary where keys are ``FunctionClass`` instances and values are
533
+ their string representations. Alternatively, the dictionary value can
534
+ be a list of tuples i.e. [(argument_test, cfunction_string)]. See
535
+ below for examples.
536
+ human : bool, optional
537
+ If True, the result is a single string that may contain some constant
538
+ declarations for the number symbols. If False, the same information is
539
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
540
+ code_text). [default=True].
541
+ contract: bool, optional
542
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
543
+ rules and the corresponding nested loops over indices are generated.
544
+ Setting contract=False will not generate loops, instead the user is
545
+ responsible to provide values for the indices in the code.
546
+ [default=True].
547
+ inline: bool, optional
548
+ If True, we try to create single-statement code instead of multiple
549
+ statements. [default=True].
550
+
551
+ Examples
552
+ ========
553
+
554
+ >>> from sympy import julia_code, symbols, sin, pi
555
+ >>> x = symbols('x')
556
+ >>> julia_code(sin(x).series(x).removeO())
557
+ 'x .^ 5 / 120 - x .^ 3 / 6 + x'
558
+
559
+ >>> from sympy import Rational, ceiling
560
+ >>> x, y, tau = symbols("x, y, tau")
561
+ >>> julia_code((2*tau)**Rational(7, 2))
562
+ '8 * sqrt(2) * tau .^ (7 // 2)'
563
+
564
+ Note that element-wise (Hadamard) operations are used by default between
565
+ symbols. This is because its possible in Julia to write "vectorized"
566
+ code. It is harmless if the values are scalars.
567
+
568
+ >>> julia_code(sin(pi*x*y), assign_to="s")
569
+ 's = sin(pi * x .* y)'
570
+
571
+ If you need a matrix product "*" or matrix power "^", you can specify the
572
+ symbol as a ``MatrixSymbol``.
573
+
574
+ >>> from sympy import Symbol, MatrixSymbol
575
+ >>> n = Symbol('n', integer=True, positive=True)
576
+ >>> A = MatrixSymbol('A', n, n)
577
+ >>> julia_code(3*pi*A**3)
578
+ '(3 * pi) * A ^ 3'
579
+
580
+ This class uses several rules to decide which symbol to use a product.
581
+ Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*".
582
+ A HadamardProduct can be used to specify componentwise multiplication ".*"
583
+ of two MatrixSymbols. There is currently there is no easy way to specify
584
+ scalar symbols, so sometimes the code might have some minor cosmetic
585
+ issues. For example, suppose x and y are scalars and A is a Matrix, then
586
+ while a human programmer might write "(x^2*y)*A^3", we generate:
587
+
588
+ >>> julia_code(x**2*y*A**3)
589
+ '(x .^ 2 .* y) * A ^ 3'
590
+
591
+ Matrices are supported using Julia inline notation. When using
592
+ ``assign_to`` with matrices, the name can be specified either as a string
593
+ or as a ``MatrixSymbol``. The dimensions must align in the latter case.
594
+
595
+ >>> from sympy import Matrix, MatrixSymbol
596
+ >>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
597
+ >>> julia_code(mat, assign_to='A')
598
+ 'A = [x .^ 2 sin(x) ceil(x)]'
599
+
600
+ ``Piecewise`` expressions are implemented with logical masking by default.
601
+ Alternatively, you can pass "inline=False" to use if-else conditionals.
602
+ Note that if the ``Piecewise`` lacks a default term, represented by
603
+ ``(expr, True)`` then an error will be thrown. This is to prevent
604
+ generating an expression that may not evaluate to anything.
605
+
606
+ >>> from sympy import Piecewise
607
+ >>> pw = Piecewise((x + 1, x > 0), (x, True))
608
+ >>> julia_code(pw, assign_to=tau)
609
+ 'tau = ((x > 0) ? (x + 1) : (x))'
610
+
611
+ Note that any expression that can be generated normally can also exist
612
+ inside a Matrix:
613
+
614
+ >>> mat = Matrix([[x**2, pw, sin(x)]])
615
+ >>> julia_code(mat, assign_to='A')
616
+ 'A = [x .^ 2 ((x > 0) ? (x + 1) : (x)) sin(x)]'
617
+
618
+ Custom printing can be defined for certain types by passing a dictionary of
619
+ "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
620
+ dictionary value can be a list of tuples i.e., [(argument_test,
621
+ cfunction_string)]. This can be used to call a custom Julia function.
622
+
623
+ >>> from sympy import Function
624
+ >>> f = Function('f')
625
+ >>> g = Function('g')
626
+ >>> custom_functions = {
627
+ ... "f": "existing_julia_fcn",
628
+ ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
629
+ ... (lambda x: not x.is_Matrix, "my_fcn")]
630
+ ... }
631
+ >>> mat = Matrix([[1, x]])
632
+ >>> julia_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
633
+ 'existing_julia_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
634
+
635
+ Support for loops is provided through ``Indexed`` types. With
636
+ ``contract=True`` these expressions will be turned into loops, whereas
637
+ ``contract=False`` will just print the assignment expression that should be
638
+ looped over:
639
+
640
+ >>> from sympy import Eq, IndexedBase, Idx
641
+ >>> len_y = 5
642
+ >>> y = IndexedBase('y', shape=(len_y,))
643
+ >>> t = IndexedBase('t', shape=(len_y,))
644
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
645
+ >>> i = Idx('i', len_y-1)
646
+ >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
647
+ >>> julia_code(e.rhs, assign_to=e.lhs, contract=False)
648
+ 'Dy[i] = (y[i + 1] - y[i]) ./ (t[i + 1] - t[i])'
649
+ """
650
+ return JuliaCodePrinter(settings).doprint(expr, assign_to)
651
+
652
+
653
+ def print_julia_code(expr, **settings):
654
+ """Prints the Julia representation of the given expression.
655
+
656
+ See `julia_code` for the meaning of the optional arguments.
657
+ """
658
+ print(julia_code(expr, **settings))
llmeval-env/lib/python3.10/site-packages/sympy/printing/lambdarepr.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .pycode import (
2
+ PythonCodePrinter,
3
+ MpmathPrinter,
4
+ )
5
+ from .numpy import NumPyPrinter # NumPyPrinter is imported for backward compatibility
6
+ from sympy.core.sorting import default_sort_key
7
+
8
+
9
+ __all__ = [
10
+ 'PythonCodePrinter',
11
+ 'MpmathPrinter', # MpmathPrinter is published for backward compatibility
12
+ 'NumPyPrinter',
13
+ 'LambdaPrinter',
14
+ 'NumPyPrinter',
15
+ 'IntervalPrinter',
16
+ 'lambdarepr',
17
+ ]
18
+
19
+
20
+ class LambdaPrinter(PythonCodePrinter):
21
+ """
22
+ This printer converts expressions into strings that can be used by
23
+ lambdify.
24
+ """
25
+ printmethod = "_lambdacode"
26
+
27
+
28
+ def _print_And(self, expr):
29
+ result = ['(']
30
+ for arg in sorted(expr.args, key=default_sort_key):
31
+ result.extend(['(', self._print(arg), ')'])
32
+ result.append(' and ')
33
+ result = result[:-1]
34
+ result.append(')')
35
+ return ''.join(result)
36
+
37
+ def _print_Or(self, expr):
38
+ result = ['(']
39
+ for arg in sorted(expr.args, key=default_sort_key):
40
+ result.extend(['(', self._print(arg), ')'])
41
+ result.append(' or ')
42
+ result = result[:-1]
43
+ result.append(')')
44
+ return ''.join(result)
45
+
46
+ def _print_Not(self, expr):
47
+ result = ['(', 'not (', self._print(expr.args[0]), '))']
48
+ return ''.join(result)
49
+
50
+ def _print_BooleanTrue(self, expr):
51
+ return "True"
52
+
53
+ def _print_BooleanFalse(self, expr):
54
+ return "False"
55
+
56
+ def _print_ITE(self, expr):
57
+ result = [
58
+ '((', self._print(expr.args[1]),
59
+ ') if (', self._print(expr.args[0]),
60
+ ') else (', self._print(expr.args[2]), '))'
61
+ ]
62
+ return ''.join(result)
63
+
64
+ def _print_NumberSymbol(self, expr):
65
+ return str(expr)
66
+
67
+ def _print_Pow(self, expr, **kwargs):
68
+ # XXX Temporary workaround. Should Python math printer be
69
+ # isolated from PythonCodePrinter?
70
+ return super(PythonCodePrinter, self)._print_Pow(expr, **kwargs)
71
+
72
+
73
+ # numexpr works by altering the string passed to numexpr.evaluate
74
+ # rather than by populating a namespace. Thus a special printer...
75
+ class NumExprPrinter(LambdaPrinter):
76
+ # key, value pairs correspond to SymPy name and numexpr name
77
+ # functions not appearing in this dict will raise a TypeError
78
+ printmethod = "_numexprcode"
79
+
80
+ _numexpr_functions = {
81
+ 'sin' : 'sin',
82
+ 'cos' : 'cos',
83
+ 'tan' : 'tan',
84
+ 'asin': 'arcsin',
85
+ 'acos': 'arccos',
86
+ 'atan': 'arctan',
87
+ 'atan2' : 'arctan2',
88
+ 'sinh' : 'sinh',
89
+ 'cosh' : 'cosh',
90
+ 'tanh' : 'tanh',
91
+ 'asinh': 'arcsinh',
92
+ 'acosh': 'arccosh',
93
+ 'atanh': 'arctanh',
94
+ 'ln' : 'log',
95
+ 'log': 'log',
96
+ 'exp': 'exp',
97
+ 'sqrt' : 'sqrt',
98
+ 'Abs' : 'abs',
99
+ 'conjugate' : 'conj',
100
+ 'im' : 'imag',
101
+ 're' : 'real',
102
+ 'where' : 'where',
103
+ 'complex' : 'complex',
104
+ 'contains' : 'contains',
105
+ }
106
+
107
+ module = 'numexpr'
108
+
109
+ def _print_ImaginaryUnit(self, expr):
110
+ return '1j'
111
+
112
+ def _print_seq(self, seq, delimiter=', '):
113
+ # simplified _print_seq taken from pretty.py
114
+ s = [self._print(item) for item in seq]
115
+ if s:
116
+ return delimiter.join(s)
117
+ else:
118
+ return ""
119
+
120
+ def _print_Function(self, e):
121
+ func_name = e.func.__name__
122
+
123
+ nstr = self._numexpr_functions.get(func_name, None)
124
+ if nstr is None:
125
+ # check for implemented_function
126
+ if hasattr(e, '_imp_'):
127
+ return "(%s)" % self._print(e._imp_(*e.args))
128
+ else:
129
+ raise TypeError("numexpr does not support function '%s'" %
130
+ func_name)
131
+ return "%s(%s)" % (nstr, self._print_seq(e.args))
132
+
133
+ def _print_Piecewise(self, expr):
134
+ "Piecewise function printer"
135
+ exprs = [self._print(arg.expr) for arg in expr.args]
136
+ conds = [self._print(arg.cond) for arg in expr.args]
137
+ # If [default_value, True] is a (expr, cond) sequence in a Piecewise object
138
+ # it will behave the same as passing the 'default' kwarg to select()
139
+ # *as long as* it is the last element in expr.args.
140
+ # If this is not the case, it may be triggered prematurely.
141
+ ans = []
142
+ parenthesis_count = 0
143
+ is_last_cond_True = False
144
+ for cond, expr in zip(conds, exprs):
145
+ if cond == 'True':
146
+ ans.append(expr)
147
+ is_last_cond_True = True
148
+ break
149
+ else:
150
+ ans.append('where(%s, %s, ' % (cond, expr))
151
+ parenthesis_count += 1
152
+ if not is_last_cond_True:
153
+ # See https://github.com/pydata/numexpr/issues/298
154
+ #
155
+ # simplest way to put a nan but raises
156
+ # 'RuntimeWarning: invalid value encountered in log'
157
+ #
158
+ # There are other ways to do this such as
159
+ #
160
+ # >>> import numexpr as ne
161
+ # >>> nan = float('nan')
162
+ # >>> ne.evaluate('where(x < 0, -1, nan)', {'x': [-1, 2, 3], 'nan':nan})
163
+ # array([-1., nan, nan])
164
+ #
165
+ # That needs to be handled in the lambdified function though rather
166
+ # than here in the printer.
167
+ ans.append('log(-1)')
168
+ return ''.join(ans) + ')' * parenthesis_count
169
+
170
+ def _print_ITE(self, expr):
171
+ from sympy.functions.elementary.piecewise import Piecewise
172
+ return self._print(expr.rewrite(Piecewise))
173
+
174
+ def blacklisted(self, expr):
175
+ raise TypeError("numexpr cannot be used with %s" %
176
+ expr.__class__.__name__)
177
+
178
+ # blacklist all Matrix printing
179
+ _print_SparseRepMatrix = \
180
+ _print_MutableSparseMatrix = \
181
+ _print_ImmutableSparseMatrix = \
182
+ _print_Matrix = \
183
+ _print_DenseMatrix = \
184
+ _print_MutableDenseMatrix = \
185
+ _print_ImmutableMatrix = \
186
+ _print_ImmutableDenseMatrix = \
187
+ blacklisted
188
+ # blacklist some Python expressions
189
+ _print_list = \
190
+ _print_tuple = \
191
+ _print_Tuple = \
192
+ _print_dict = \
193
+ _print_Dict = \
194
+ blacklisted
195
+
196
+ def _print_NumExprEvaluate(self, expr):
197
+ evaluate = self._module_format(self.module +".evaluate")
198
+ return "%s('%s', truediv=True)" % (evaluate, self._print(expr.expr))
199
+
200
+ def doprint(self, expr):
201
+ from sympy.codegen.ast import CodegenAST
202
+ from sympy.codegen.pynodes import NumExprEvaluate
203
+ if not isinstance(expr, CodegenAST):
204
+ expr = NumExprEvaluate(expr)
205
+ return super().doprint(expr)
206
+
207
+ def _print_Return(self, expr):
208
+ from sympy.codegen.pynodes import NumExprEvaluate
209
+ r, = expr.args
210
+ if not isinstance(r, NumExprEvaluate):
211
+ expr = expr.func(NumExprEvaluate(r))
212
+ return super()._print_Return(expr)
213
+
214
+ def _print_Assignment(self, expr):
215
+ from sympy.codegen.pynodes import NumExprEvaluate
216
+ lhs, rhs, *args = expr.args
217
+ if not isinstance(rhs, NumExprEvaluate):
218
+ expr = expr.func(lhs, NumExprEvaluate(rhs), *args)
219
+ return super()._print_Assignment(expr)
220
+
221
+ def _print_CodeBlock(self, expr):
222
+ from sympy.codegen.ast import CodegenAST
223
+ from sympy.codegen.pynodes import NumExprEvaluate
224
+ args = [ arg if isinstance(arg, CodegenAST) else NumExprEvaluate(arg) for arg in expr.args ]
225
+ return super()._print_CodeBlock(self, expr.func(*args))
226
+
227
+
228
+ class IntervalPrinter(MpmathPrinter, LambdaPrinter):
229
+ """Use ``lambda`` printer but print numbers as ``mpi`` intervals. """
230
+
231
+ def _print_Integer(self, expr):
232
+ return "mpi('%s')" % super(PythonCodePrinter, self)._print_Integer(expr)
233
+
234
+ def _print_Rational(self, expr):
235
+ return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr)
236
+
237
+ def _print_Half(self, expr):
238
+ return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr)
239
+
240
+ def _print_Pow(self, expr):
241
+ return super(MpmathPrinter, self)._print_Pow(expr, rational=True)
242
+
243
+
244
+ for k in NumExprPrinter._numexpr_functions:
245
+ setattr(NumExprPrinter, '_print_%s' % k, NumExprPrinter._print_Function)
246
+
247
+ def lambdarepr(expr, **settings):
248
+ """
249
+ Returns a string usable for lambdifying.
250
+ """
251
+ return LambdaPrinter(settings).doprint(expr)
llmeval-env/lib/python3.10/site-packages/sympy/printing/latex.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/sympy/printing/llvmjitcode.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Use llvmlite to create executable functions from SymPy expressions
3
+
4
+ This module requires llvmlite (https://github.com/numba/llvmlite).
5
+ '''
6
+
7
+ import ctypes
8
+
9
+ from sympy.external import import_module
10
+ from sympy.printing.printer import Printer
11
+ from sympy.core.singleton import S
12
+ from sympy.tensor.indexed import IndexedBase
13
+ from sympy.utilities.decorator import doctest_depends_on
14
+
15
+ llvmlite = import_module('llvmlite')
16
+ if llvmlite:
17
+ ll = import_module('llvmlite.ir').ir
18
+ llvm = import_module('llvmlite.binding').binding
19
+ llvm.initialize()
20
+ llvm.initialize_native_target()
21
+ llvm.initialize_native_asmprinter()
22
+
23
+
24
+ __doctest_requires__ = {('llvm_callable'): ['llvmlite']}
25
+
26
+
27
+ class LLVMJitPrinter(Printer):
28
+ '''Convert expressions to LLVM IR'''
29
+ def __init__(self, module, builder, fn, *args, **kwargs):
30
+ self.func_arg_map = kwargs.pop("func_arg_map", {})
31
+ if not llvmlite:
32
+ raise ImportError("llvmlite is required for LLVMJITPrinter")
33
+ super().__init__(*args, **kwargs)
34
+ self.fp_type = ll.DoubleType()
35
+ self.module = module
36
+ self.builder = builder
37
+ self.fn = fn
38
+ self.ext_fn = {} # keep track of wrappers to external functions
39
+ self.tmp_var = {}
40
+
41
+ def _add_tmp_var(self, name, value):
42
+ self.tmp_var[name] = value
43
+
44
+ def _print_Number(self, n):
45
+ return ll.Constant(self.fp_type, float(n))
46
+
47
+ def _print_Integer(self, expr):
48
+ return ll.Constant(self.fp_type, float(expr.p))
49
+
50
+ def _print_Symbol(self, s):
51
+ val = self.tmp_var.get(s)
52
+ if not val:
53
+ # look up parameter with name s
54
+ val = self.func_arg_map.get(s)
55
+ if not val:
56
+ raise LookupError("Symbol not found: %s" % s)
57
+ return val
58
+
59
+ def _print_Pow(self, expr):
60
+ base0 = self._print(expr.base)
61
+ if expr.exp == S.NegativeOne:
62
+ return self.builder.fdiv(ll.Constant(self.fp_type, 1.0), base0)
63
+ if expr.exp == S.Half:
64
+ fn = self.ext_fn.get("sqrt")
65
+ if not fn:
66
+ fn_type = ll.FunctionType(self.fp_type, [self.fp_type])
67
+ fn = ll.Function(self.module, fn_type, "sqrt")
68
+ self.ext_fn["sqrt"] = fn
69
+ return self.builder.call(fn, [base0], "sqrt")
70
+ if expr.exp == 2:
71
+ return self.builder.fmul(base0, base0)
72
+
73
+ exp0 = self._print(expr.exp)
74
+ fn = self.ext_fn.get("pow")
75
+ if not fn:
76
+ fn_type = ll.FunctionType(self.fp_type, [self.fp_type, self.fp_type])
77
+ fn = ll.Function(self.module, fn_type, "pow")
78
+ self.ext_fn["pow"] = fn
79
+ return self.builder.call(fn, [base0, exp0], "pow")
80
+
81
+ def _print_Mul(self, expr):
82
+ nodes = [self._print(a) for a in expr.args]
83
+ e = nodes[0]
84
+ for node in nodes[1:]:
85
+ e = self.builder.fmul(e, node)
86
+ return e
87
+
88
+ def _print_Add(self, expr):
89
+ nodes = [self._print(a) for a in expr.args]
90
+ e = nodes[0]
91
+ for node in nodes[1:]:
92
+ e = self.builder.fadd(e, node)
93
+ return e
94
+
95
+ # TODO - assumes all called functions take one double precision argument.
96
+ # Should have a list of math library functions to validate this.
97
+ def _print_Function(self, expr):
98
+ name = expr.func.__name__
99
+ e0 = self._print(expr.args[0])
100
+ fn = self.ext_fn.get(name)
101
+ if not fn:
102
+ fn_type = ll.FunctionType(self.fp_type, [self.fp_type])
103
+ fn = ll.Function(self.module, fn_type, name)
104
+ self.ext_fn[name] = fn
105
+ return self.builder.call(fn, [e0], name)
106
+
107
+ def emptyPrinter(self, expr):
108
+ raise TypeError("Unsupported type for LLVM JIT conversion: %s"
109
+ % type(expr))
110
+
111
+
112
+ # Used when parameters are passed by array. Often used in callbacks to
113
+ # handle a variable number of parameters.
114
+ class LLVMJitCallbackPrinter(LLVMJitPrinter):
115
+ def __init__(self, *args, **kwargs):
116
+ super().__init__(*args, **kwargs)
117
+
118
+ def _print_Indexed(self, expr):
119
+ array, idx = self.func_arg_map[expr.base]
120
+ offset = int(expr.indices[0].evalf())
121
+ array_ptr = self.builder.gep(array, [ll.Constant(ll.IntType(32), offset)])
122
+ fp_array_ptr = self.builder.bitcast(array_ptr, ll.PointerType(self.fp_type))
123
+ value = self.builder.load(fp_array_ptr)
124
+ return value
125
+
126
+ def _print_Symbol(self, s):
127
+ val = self.tmp_var.get(s)
128
+ if val:
129
+ return val
130
+
131
+ array, idx = self.func_arg_map.get(s, [None, 0])
132
+ if not array:
133
+ raise LookupError("Symbol not found: %s" % s)
134
+ array_ptr = self.builder.gep(array, [ll.Constant(ll.IntType(32), idx)])
135
+ fp_array_ptr = self.builder.bitcast(array_ptr,
136
+ ll.PointerType(self.fp_type))
137
+ value = self.builder.load(fp_array_ptr)
138
+ return value
139
+
140
+
141
+ # ensure lifetime of the execution engine persists (else call to compiled
142
+ # function will seg fault)
143
+ exe_engines = []
144
+
145
+ # ensure names for generated functions are unique
146
+ link_names = set()
147
+ current_link_suffix = 0
148
+
149
+
150
+ class LLVMJitCode:
151
+ def __init__(self, signature):
152
+ self.signature = signature
153
+ self.fp_type = ll.DoubleType()
154
+ self.module = ll.Module('mod1')
155
+ self.fn = None
156
+ self.llvm_arg_types = []
157
+ self.llvm_ret_type = self.fp_type
158
+ self.param_dict = {} # map symbol name to LLVM function argument
159
+ self.link_name = ''
160
+
161
+ def _from_ctype(self, ctype):
162
+ if ctype == ctypes.c_int:
163
+ return ll.IntType(32)
164
+ if ctype == ctypes.c_double:
165
+ return self.fp_type
166
+ if ctype == ctypes.POINTER(ctypes.c_double):
167
+ return ll.PointerType(self.fp_type)
168
+ if ctype == ctypes.c_void_p:
169
+ return ll.PointerType(ll.IntType(32))
170
+ if ctype == ctypes.py_object:
171
+ return ll.PointerType(ll.IntType(32))
172
+
173
+ print("Unhandled ctype = %s" % str(ctype))
174
+
175
+ def _create_args(self, func_args):
176
+ """Create types for function arguments"""
177
+ self.llvm_ret_type = self._from_ctype(self.signature.ret_type)
178
+ self.llvm_arg_types = \
179
+ [self._from_ctype(a) for a in self.signature.arg_ctypes]
180
+
181
+ def _create_function_base(self):
182
+ """Create function with name and type signature"""
183
+ global link_names, current_link_suffix
184
+ default_link_name = 'jit_func'
185
+ current_link_suffix += 1
186
+ self.link_name = default_link_name + str(current_link_suffix)
187
+ link_names.add(self.link_name)
188
+
189
+ fn_type = ll.FunctionType(self.llvm_ret_type, self.llvm_arg_types)
190
+ self.fn = ll.Function(self.module, fn_type, name=self.link_name)
191
+
192
+ def _create_param_dict(self, func_args):
193
+ """Mapping of symbolic values to function arguments"""
194
+ for i, a in enumerate(func_args):
195
+ self.fn.args[i].name = str(a)
196
+ self.param_dict[a] = self.fn.args[i]
197
+
198
+ def _create_function(self, expr):
199
+ """Create function body and return LLVM IR"""
200
+ bb_entry = self.fn.append_basic_block('entry')
201
+ builder = ll.IRBuilder(bb_entry)
202
+
203
+ lj = LLVMJitPrinter(self.module, builder, self.fn,
204
+ func_arg_map=self.param_dict)
205
+
206
+ ret = self._convert_expr(lj, expr)
207
+ lj.builder.ret(self._wrap_return(lj, ret))
208
+
209
+ strmod = str(self.module)
210
+ return strmod
211
+
212
+ def _wrap_return(self, lj, vals):
213
+ # Return a single double if there is one return value,
214
+ # else return a tuple of doubles.
215
+
216
+ # Don't wrap return value in this case
217
+ if self.signature.ret_type == ctypes.c_double:
218
+ return vals[0]
219
+
220
+ # Use this instead of a real PyObject*
221
+ void_ptr = ll.PointerType(ll.IntType(32))
222
+
223
+ # Create a wrapped double: PyObject* PyFloat_FromDouble(double v)
224
+ wrap_type = ll.FunctionType(void_ptr, [self.fp_type])
225
+ wrap_fn = ll.Function(lj.module, wrap_type, "PyFloat_FromDouble")
226
+
227
+ wrapped_vals = [lj.builder.call(wrap_fn, [v]) for v in vals]
228
+ if len(vals) == 1:
229
+ final_val = wrapped_vals[0]
230
+ else:
231
+ # Create a tuple: PyObject* PyTuple_Pack(Py_ssize_t n, ...)
232
+
233
+ # This should be Py_ssize_t
234
+ tuple_arg_types = [ll.IntType(32)]
235
+
236
+ tuple_arg_types.extend([void_ptr]*len(vals))
237
+ tuple_type = ll.FunctionType(void_ptr, tuple_arg_types)
238
+ tuple_fn = ll.Function(lj.module, tuple_type, "PyTuple_Pack")
239
+
240
+ tuple_args = [ll.Constant(ll.IntType(32), len(wrapped_vals))]
241
+ tuple_args.extend(wrapped_vals)
242
+
243
+ final_val = lj.builder.call(tuple_fn, tuple_args)
244
+
245
+ return final_val
246
+
247
+ def _convert_expr(self, lj, expr):
248
+ try:
249
+ # Match CSE return data structure.
250
+ if len(expr) == 2:
251
+ tmp_exprs = expr[0]
252
+ final_exprs = expr[1]
253
+ if len(final_exprs) != 1 and self.signature.ret_type == ctypes.c_double:
254
+ raise NotImplementedError("Return of multiple expressions not supported for this callback")
255
+ for name, e in tmp_exprs:
256
+ val = lj._print(e)
257
+ lj._add_tmp_var(name, val)
258
+ except TypeError:
259
+ final_exprs = [expr]
260
+
261
+ vals = [lj._print(e) for e in final_exprs]
262
+
263
+ return vals
264
+
265
+ def _compile_function(self, strmod):
266
+ global exe_engines
267
+ llmod = llvm.parse_assembly(strmod)
268
+
269
+ pmb = llvm.create_pass_manager_builder()
270
+ pmb.opt_level = 2
271
+ pass_manager = llvm.create_module_pass_manager()
272
+ pmb.populate(pass_manager)
273
+
274
+ pass_manager.run(llmod)
275
+
276
+ target_machine = \
277
+ llvm.Target.from_default_triple().create_target_machine()
278
+ exe_eng = llvm.create_mcjit_compiler(llmod, target_machine)
279
+ exe_eng.finalize_object()
280
+ exe_engines.append(exe_eng)
281
+
282
+ if False:
283
+ print("Assembly")
284
+ print(target_machine.emit_assembly(llmod))
285
+
286
+ fptr = exe_eng.get_function_address(self.link_name)
287
+
288
+ return fptr
289
+
290
+
291
+ class LLVMJitCodeCallback(LLVMJitCode):
292
+ def __init__(self, signature):
293
+ super().__init__(signature)
294
+
295
+ def _create_param_dict(self, func_args):
296
+ for i, a in enumerate(func_args):
297
+ if isinstance(a, IndexedBase):
298
+ self.param_dict[a] = (self.fn.args[i], i)
299
+ self.fn.args[i].name = str(a)
300
+ else:
301
+ self.param_dict[a] = (self.fn.args[self.signature.input_arg],
302
+ i)
303
+
304
+ def _create_function(self, expr):
305
+ """Create function body and return LLVM IR"""
306
+ bb_entry = self.fn.append_basic_block('entry')
307
+ builder = ll.IRBuilder(bb_entry)
308
+
309
+ lj = LLVMJitCallbackPrinter(self.module, builder, self.fn,
310
+ func_arg_map=self.param_dict)
311
+
312
+ ret = self._convert_expr(lj, expr)
313
+
314
+ if self.signature.ret_arg:
315
+ output_fp_ptr = builder.bitcast(self.fn.args[self.signature.ret_arg],
316
+ ll.PointerType(self.fp_type))
317
+ for i, val in enumerate(ret):
318
+ index = ll.Constant(ll.IntType(32), i)
319
+ output_array_ptr = builder.gep(output_fp_ptr, [index])
320
+ builder.store(val, output_array_ptr)
321
+ builder.ret(ll.Constant(ll.IntType(32), 0)) # return success
322
+ else:
323
+ lj.builder.ret(self._wrap_return(lj, ret))
324
+
325
+ strmod = str(self.module)
326
+ return strmod
327
+
328
+
329
+ class CodeSignature:
330
+ def __init__(self, ret_type):
331
+ self.ret_type = ret_type
332
+ self.arg_ctypes = []
333
+
334
+ # Input argument array element index
335
+ self.input_arg = 0
336
+
337
+ # For the case output value is referenced through a parameter rather
338
+ # than the return value
339
+ self.ret_arg = None
340
+
341
+
342
+ def _llvm_jit_code(args, expr, signature, callback_type):
343
+ """Create a native code function from a SymPy expression"""
344
+ if callback_type is None:
345
+ jit = LLVMJitCode(signature)
346
+ else:
347
+ jit = LLVMJitCodeCallback(signature)
348
+
349
+ jit._create_args(args)
350
+ jit._create_function_base()
351
+ jit._create_param_dict(args)
352
+ strmod = jit._create_function(expr)
353
+ if False:
354
+ print("LLVM IR")
355
+ print(strmod)
356
+ fptr = jit._compile_function(strmod)
357
+ return fptr
358
+
359
+
360
+ @doctest_depends_on(modules=('llvmlite', 'scipy'))
361
+ def llvm_callable(args, expr, callback_type=None):
362
+ '''Compile function from a SymPy expression
363
+
364
+ Expressions are evaluated using double precision arithmetic.
365
+ Some single argument math functions (exp, sin, cos, etc.) are supported
366
+ in expressions.
367
+
368
+ Parameters
369
+ ==========
370
+
371
+ args : List of Symbol
372
+ Arguments to the generated function. Usually the free symbols in
373
+ the expression. Currently each one is assumed to convert to
374
+ a double precision scalar.
375
+ expr : Expr, or (Replacements, Expr) as returned from 'cse'
376
+ Expression to compile.
377
+ callback_type : string
378
+ Create function with signature appropriate to use as a callback.
379
+ Currently supported:
380
+ 'scipy.integrate'
381
+ 'scipy.integrate.test'
382
+ 'cubature'
383
+
384
+ Returns
385
+ =======
386
+
387
+ Compiled function that can evaluate the expression.
388
+
389
+ Examples
390
+ ========
391
+
392
+ >>> import sympy.printing.llvmjitcode as jit
393
+ >>> from sympy.abc import a
394
+ >>> e = a*a + a + 1
395
+ >>> e1 = jit.llvm_callable([a], e)
396
+ >>> e.subs(a, 1.1) # Evaluate via substitution
397
+ 3.31000000000000
398
+ >>> e1(1.1) # Evaluate using JIT-compiled code
399
+ 3.3100000000000005
400
+
401
+
402
+ Callbacks for integration functions can be JIT compiled.
403
+ >>> import sympy.printing.llvmjitcode as jit
404
+ >>> from sympy.abc import a
405
+ >>> from sympy import integrate
406
+ >>> from scipy.integrate import quad
407
+ >>> e = a*a
408
+ >>> e1 = jit.llvm_callable([a], e, callback_type='scipy.integrate')
409
+ >>> integrate(e, (a, 0.0, 2.0))
410
+ 2.66666666666667
411
+ >>> quad(e1, 0.0, 2.0)[0]
412
+ 2.66666666666667
413
+
414
+ The 'cubature' callback is for the Python wrapper around the
415
+ cubature package ( https://github.com/saullocastro/cubature )
416
+ and ( http://ab-initio.mit.edu/wiki/index.php/Cubature )
417
+
418
+ There are two signatures for the SciPy integration callbacks.
419
+ The first ('scipy.integrate') is the function to be passed to the
420
+ integration routine, and will pass the signature checks.
421
+ The second ('scipy.integrate.test') is only useful for directly calling
422
+ the function using ctypes variables. It will not pass the signature checks
423
+ for scipy.integrate.
424
+
425
+ The return value from the cse module can also be compiled. This
426
+ can improve the performance of the compiled function. If multiple
427
+ expressions are given to cse, the compiled function returns a tuple.
428
+ The 'cubature' callback handles multiple expressions (set `fdim`
429
+ to match in the integration call.)
430
+ >>> import sympy.printing.llvmjitcode as jit
431
+ >>> from sympy import cse
432
+ >>> from sympy.abc import x,y
433
+ >>> e1 = x*x + y*y
434
+ >>> e2 = 4*(x*x + y*y) + 8.0
435
+ >>> after_cse = cse([e1,e2])
436
+ >>> after_cse
437
+ ([(x0, x**2), (x1, y**2)], [x0 + x1, 4*x0 + 4*x1 + 8.0])
438
+ >>> j1 = jit.llvm_callable([x,y], after_cse)
439
+ >>> j1(1.0, 2.0)
440
+ (5.0, 28.0)
441
+ '''
442
+
443
+ if not llvmlite:
444
+ raise ImportError("llvmlite is required for llvmjitcode")
445
+
446
+ signature = CodeSignature(ctypes.py_object)
447
+
448
+ arg_ctypes = []
449
+ if callback_type is None:
450
+ for _ in args:
451
+ arg_ctype = ctypes.c_double
452
+ arg_ctypes.append(arg_ctype)
453
+ elif callback_type in ('scipy.integrate', 'scipy.integrate.test'):
454
+ signature.ret_type = ctypes.c_double
455
+ arg_ctypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_double)]
456
+ arg_ctypes_formal = [ctypes.c_int, ctypes.c_double]
457
+ signature.input_arg = 1
458
+ elif callback_type == 'cubature':
459
+ arg_ctypes = [ctypes.c_int,
460
+ ctypes.POINTER(ctypes.c_double),
461
+ ctypes.c_void_p,
462
+ ctypes.c_int,
463
+ ctypes.POINTER(ctypes.c_double)
464
+ ]
465
+ signature.ret_type = ctypes.c_int
466
+ signature.input_arg = 1
467
+ signature.ret_arg = 4
468
+ else:
469
+ raise ValueError("Unknown callback type: %s" % callback_type)
470
+
471
+ signature.arg_ctypes = arg_ctypes
472
+
473
+ fptr = _llvm_jit_code(args, expr, signature, callback_type)
474
+
475
+ if callback_type and callback_type == 'scipy.integrate':
476
+ arg_ctypes = arg_ctypes_formal
477
+
478
+ # PYFUNCTYPE holds the GIL which is needed to prevent a segfault when
479
+ # calling PyFloat_FromDouble on Python 3.10. Probably it is better to use
480
+ # ctypes.c_double when returning a float rather than using ctypes.py_object
481
+ # and returning a PyFloat from inside the jitted function (i.e. let ctypes
482
+ # handle the conversion from double to PyFloat).
483
+ if signature.ret_type == ctypes.py_object:
484
+ FUNCTYPE = ctypes.PYFUNCTYPE
485
+ else:
486
+ FUNCTYPE = ctypes.CFUNCTYPE
487
+
488
+ cfunc = FUNCTYPE(signature.ret_type, *arg_ctypes)(fptr)
489
+ return cfunc
llmeval-env/lib/python3.10/site-packages/sympy/printing/maple.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Maple code printer
3
+
4
+ The MapleCodePrinter converts single SymPy expressions into single
5
+ Maple expressions, using the functions defined in the Maple objects where possible.
6
+
7
+
8
+ FIXME: This module is still under actively developed. Some functions may be not completed.
9
+ """
10
+
11
+ from sympy.core import S
12
+ from sympy.core.numbers import Integer, IntegerConstant, equal_valued
13
+ from sympy.printing.codeprinter import CodePrinter
14
+ from sympy.printing.precedence import precedence, PRECEDENCE
15
+
16
+ import sympy
17
+
18
+ _known_func_same_name = (
19
+ 'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinh', 'cosh', 'tanh', 'sech',
20
+ 'csch', 'coth', 'exp', 'floor', 'factorial', 'bernoulli', 'euler',
21
+ 'fibonacci', 'gcd', 'lcm', 'conjugate', 'Ci', 'Chi', 'Ei', 'Li', 'Si', 'Shi',
22
+ 'erf', 'erfc', 'harmonic', 'LambertW',
23
+ 'sqrt', # For automatic rewrites
24
+ )
25
+
26
+ known_functions = {
27
+ # SymPy -> Maple
28
+ 'Abs': 'abs',
29
+ 'log': 'ln',
30
+ 'asin': 'arcsin',
31
+ 'acos': 'arccos',
32
+ 'atan': 'arctan',
33
+ 'asec': 'arcsec',
34
+ 'acsc': 'arccsc',
35
+ 'acot': 'arccot',
36
+ 'asinh': 'arcsinh',
37
+ 'acosh': 'arccosh',
38
+ 'atanh': 'arctanh',
39
+ 'asech': 'arcsech',
40
+ 'acsch': 'arccsch',
41
+ 'acoth': 'arccoth',
42
+ 'ceiling': 'ceil',
43
+ 'Max' : 'max',
44
+ 'Min' : 'min',
45
+
46
+ 'factorial2': 'doublefactorial',
47
+ 'RisingFactorial': 'pochhammer',
48
+ 'besseli': 'BesselI',
49
+ 'besselj': 'BesselJ',
50
+ 'besselk': 'BesselK',
51
+ 'bessely': 'BesselY',
52
+ 'hankelh1': 'HankelH1',
53
+ 'hankelh2': 'HankelH2',
54
+ 'airyai': 'AiryAi',
55
+ 'airybi': 'AiryBi',
56
+ 'appellf1': 'AppellF1',
57
+ 'fresnelc': 'FresnelC',
58
+ 'fresnels': 'FresnelS',
59
+ 'lerchphi' : 'LerchPhi',
60
+ }
61
+
62
+ for _func in _known_func_same_name:
63
+ known_functions[_func] = _func
64
+
65
+ number_symbols = {
66
+ # SymPy -> Maple
67
+ S.Pi: 'Pi',
68
+ S.Exp1: 'exp(1)',
69
+ S.Catalan: 'Catalan',
70
+ S.EulerGamma: 'gamma',
71
+ S.GoldenRatio: '(1/2 + (1/2)*sqrt(5))'
72
+ }
73
+
74
+ spec_relational_ops = {
75
+ # SymPy -> Maple
76
+ '==': '=',
77
+ '!=': '<>'
78
+ }
79
+
80
+ not_supported_symbol = [
81
+ S.ComplexInfinity
82
+ ]
83
+
84
+ class MapleCodePrinter(CodePrinter):
85
+ """
86
+ Printer which converts a SymPy expression into a maple code.
87
+ """
88
+ printmethod = "_maple"
89
+ language = "maple"
90
+
91
+ _default_settings = {
92
+ 'order': None,
93
+ 'full_prec': 'auto',
94
+ 'human': True,
95
+ 'inline': True,
96
+ 'allow_unknown_functions': True,
97
+ }
98
+
99
+ def __init__(self, settings=None):
100
+ if settings is None:
101
+ settings = {}
102
+ super().__init__(settings)
103
+ self.known_functions = dict(known_functions)
104
+ userfuncs = settings.get('user_functions', {})
105
+ self.known_functions.update(userfuncs)
106
+
107
+ def _get_statement(self, codestring):
108
+ return "%s;" % codestring
109
+
110
+ def _get_comment(self, text):
111
+ return "# {}".format(text)
112
+
113
+ def _declare_number_const(self, name, value):
114
+ return "{} := {};".format(name,
115
+ value.evalf(self._settings['precision']))
116
+
117
+ def _format_code(self, lines):
118
+ return lines
119
+
120
+ def _print_tuple(self, expr):
121
+ return self._print(list(expr))
122
+
123
+ def _print_Tuple(self, expr):
124
+ return self._print(list(expr))
125
+
126
+ def _print_Assignment(self, expr):
127
+ lhs = self._print(expr.lhs)
128
+ rhs = self._print(expr.rhs)
129
+ return "{lhs} := {rhs}".format(lhs=lhs, rhs=rhs)
130
+
131
+ def _print_Pow(self, expr, **kwargs):
132
+ PREC = precedence(expr)
133
+ if equal_valued(expr.exp, -1):
134
+ return '1/%s' % (self.parenthesize(expr.base, PREC))
135
+ elif equal_valued(expr.exp, 0.5):
136
+ return 'sqrt(%s)' % self._print(expr.base)
137
+ elif equal_valued(expr.exp, -0.5):
138
+ return '1/sqrt(%s)' % self._print(expr.base)
139
+ else:
140
+ return '{base}^{exp}'.format(
141
+ base=self.parenthesize(expr.base, PREC),
142
+ exp=self.parenthesize(expr.exp, PREC))
143
+
144
+ def _print_Piecewise(self, expr):
145
+ if (expr.args[-1].cond is not True) and (expr.args[-1].cond != S.BooleanTrue):
146
+ # We need the last conditional to be a True, otherwise the resulting
147
+ # function may not return a result.
148
+ raise ValueError("All Piecewise expressions must contain an "
149
+ "(expr, True) statement to be used as a default "
150
+ "condition. Without one, the generated "
151
+ "expression may not evaluate to anything under "
152
+ "some condition.")
153
+ _coup_list = [
154
+ ("{c}, {e}".format(c=self._print(c),
155
+ e=self._print(e)) if c is not True and c is not S.BooleanTrue else "{e}".format(
156
+ e=self._print(e)))
157
+ for e, c in expr.args]
158
+ _inbrace = ', '.join(_coup_list)
159
+ return 'piecewise({_inbrace})'.format(_inbrace=_inbrace)
160
+
161
+ def _print_Rational(self, expr):
162
+ p, q = int(expr.p), int(expr.q)
163
+ return "{p}/{q}".format(p=str(p), q=str(q))
164
+
165
+ def _print_Relational(self, expr):
166
+ PREC=precedence(expr)
167
+ lhs_code = self.parenthesize(expr.lhs, PREC)
168
+ rhs_code = self.parenthesize(expr.rhs, PREC)
169
+ op = expr.rel_op
170
+ if op in spec_relational_ops:
171
+ op = spec_relational_ops[op]
172
+ return "{lhs} {rel_op} {rhs}".format(lhs=lhs_code, rel_op=op, rhs=rhs_code)
173
+
174
+ def _print_NumberSymbol(self, expr):
175
+ return number_symbols[expr]
176
+
177
+ def _print_NegativeInfinity(self, expr):
178
+ return '-infinity'
179
+
180
+ def _print_Infinity(self, expr):
181
+ return 'infinity'
182
+
183
+ def _print_Idx(self, expr):
184
+ return self._print(expr.label)
185
+
186
+ def _print_BooleanTrue(self, expr):
187
+ return "true"
188
+
189
+ def _print_BooleanFalse(self, expr):
190
+ return "false"
191
+
192
+ def _print_bool(self, expr):
193
+ return 'true' if expr else 'false'
194
+
195
+ def _print_NaN(self, expr):
196
+ return 'undefined'
197
+
198
+ def _get_matrix(self, expr, sparse=False):
199
+ if S.Zero in expr.shape:
200
+ _strM = 'Matrix([], storage = {storage})'.format(
201
+ storage='sparse' if sparse else 'rectangular')
202
+ else:
203
+ _strM = 'Matrix({list}, storage = {storage})'.format(
204
+ list=self._print(expr.tolist()),
205
+ storage='sparse' if sparse else 'rectangular')
206
+ return _strM
207
+
208
+ def _print_MatrixElement(self, expr):
209
+ return "{parent}[{i_maple}, {j_maple}]".format(
210
+ parent=self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True),
211
+ i_maple=self._print(expr.i + 1),
212
+ j_maple=self._print(expr.j + 1))
213
+
214
+ def _print_MatrixBase(self, expr):
215
+ return self._get_matrix(expr, sparse=False)
216
+
217
+ def _print_SparseRepMatrix(self, expr):
218
+ return self._get_matrix(expr, sparse=True)
219
+
220
+ def _print_Identity(self, expr):
221
+ if isinstance(expr.rows, (Integer, IntegerConstant)):
222
+ return self._print(sympy.SparseMatrix(expr))
223
+ else:
224
+ return "Matrix({var_size}, shape = identity)".format(var_size=self._print(expr.rows))
225
+
226
+ def _print_MatMul(self, expr):
227
+ PREC=precedence(expr)
228
+ _fact_list = list(expr.args)
229
+ _const = None
230
+ if not isinstance(_fact_list[0], (sympy.MatrixBase, sympy.MatrixExpr,
231
+ sympy.MatrixSlice, sympy.MatrixSymbol)):
232
+ _const, _fact_list = _fact_list[0], _fact_list[1:]
233
+
234
+ if _const is None or _const == 1:
235
+ return '.'.join(self.parenthesize(_m, PREC) for _m in _fact_list)
236
+ else:
237
+ return '{c}*{m}'.format(c=_const, m='.'.join(self.parenthesize(_m, PREC) for _m in _fact_list))
238
+
239
+ def _print_MatPow(self, expr):
240
+ # This function requires LinearAlgebra Function in Maple
241
+ return 'MatrixPower({A}, {n})'.format(A=self._print(expr.base), n=self._print(expr.exp))
242
+
243
+ def _print_HadamardProduct(self, expr):
244
+ PREC = precedence(expr)
245
+ _fact_list = list(expr.args)
246
+ return '*'.join(self.parenthesize(_m, PREC) for _m in _fact_list)
247
+
248
+ def _print_Derivative(self, expr):
249
+ _f, (_var, _order) = expr.args
250
+
251
+ if _order != 1:
252
+ _second_arg = '{var}${order}'.format(var=self._print(_var),
253
+ order=self._print(_order))
254
+ else:
255
+ _second_arg = '{var}'.format(var=self._print(_var))
256
+ return 'diff({func_expr}, {sec_arg})'.format(func_expr=self._print(_f), sec_arg=_second_arg)
257
+
258
+
259
+ def maple_code(expr, assign_to=None, **settings):
260
+ r"""Converts ``expr`` to a string of Maple code.
261
+
262
+ Parameters
263
+ ==========
264
+
265
+ expr : Expr
266
+ A SymPy expression to be converted.
267
+ assign_to : optional
268
+ When given, the argument is used as the name of the variable to which
269
+ the expression is assigned. Can be a string, ``Symbol``,
270
+ ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
271
+ expressions that generate multi-line statements.
272
+ precision : integer, optional
273
+ The precision for numbers such as pi [default=16].
274
+ user_functions : dict, optional
275
+ A dictionary where keys are ``FunctionClass`` instances and values are
276
+ their string representations. Alternatively, the dictionary value can
277
+ be a list of tuples i.e. [(argument_test, cfunction_string)]. See
278
+ below for examples.
279
+ human : bool, optional
280
+ If True, the result is a single string that may contain some constant
281
+ declarations for the number symbols. If False, the same information is
282
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
283
+ code_text). [default=True].
284
+ contract: bool, optional
285
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
286
+ rules and the corresponding nested loops over indices are generated.
287
+ Setting contract=False will not generate loops, instead the user is
288
+ responsible to provide values for the indices in the code.
289
+ [default=True].
290
+ inline: bool, optional
291
+ If True, we try to create single-statement code instead of multiple
292
+ statements. [default=True].
293
+
294
+ """
295
+ return MapleCodePrinter(settings).doprint(expr, assign_to)
296
+
297
+
298
+ def print_maple_code(expr, **settings):
299
+ """Prints the Maple representation of the given expression.
300
+
301
+ See :func:`maple_code` for the meaning of the optional arguments.
302
+
303
+ Examples
304
+ ========
305
+
306
+ >>> from sympy import print_maple_code, symbols
307
+ >>> x, y = symbols('x y')
308
+ >>> print_maple_code(x, assign_to=y)
309
+ y := x
310
+ """
311
+ print(maple_code(expr, **settings))
llmeval-env/lib/python3.10/site-packages/sympy/printing/mathematica.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mathematica code printer
3
+ """
4
+
5
+ from __future__ import annotations
6
+ from typing import Any
7
+
8
+ from sympy.core import Basic, Expr, Float
9
+ from sympy.core.sorting import default_sort_key
10
+
11
+ from sympy.printing.codeprinter import CodePrinter
12
+ from sympy.printing.precedence import precedence
13
+
14
+ # Used in MCodePrinter._print_Function(self)
15
+ known_functions = {
16
+ "exp": [(lambda x: True, "Exp")],
17
+ "log": [(lambda x: True, "Log")],
18
+ "sin": [(lambda x: True, "Sin")],
19
+ "cos": [(lambda x: True, "Cos")],
20
+ "tan": [(lambda x: True, "Tan")],
21
+ "cot": [(lambda x: True, "Cot")],
22
+ "sec": [(lambda x: True, "Sec")],
23
+ "csc": [(lambda x: True, "Csc")],
24
+ "asin": [(lambda x: True, "ArcSin")],
25
+ "acos": [(lambda x: True, "ArcCos")],
26
+ "atan": [(lambda x: True, "ArcTan")],
27
+ "acot": [(lambda x: True, "ArcCot")],
28
+ "asec": [(lambda x: True, "ArcSec")],
29
+ "acsc": [(lambda x: True, "ArcCsc")],
30
+ "atan2": [(lambda *x: True, "ArcTan")],
31
+ "sinh": [(lambda x: True, "Sinh")],
32
+ "cosh": [(lambda x: True, "Cosh")],
33
+ "tanh": [(lambda x: True, "Tanh")],
34
+ "coth": [(lambda x: True, "Coth")],
35
+ "sech": [(lambda x: True, "Sech")],
36
+ "csch": [(lambda x: True, "Csch")],
37
+ "asinh": [(lambda x: True, "ArcSinh")],
38
+ "acosh": [(lambda x: True, "ArcCosh")],
39
+ "atanh": [(lambda x: True, "ArcTanh")],
40
+ "acoth": [(lambda x: True, "ArcCoth")],
41
+ "asech": [(lambda x: True, "ArcSech")],
42
+ "acsch": [(lambda x: True, "ArcCsch")],
43
+ "sinc": [(lambda x: True, "Sinc")],
44
+ "conjugate": [(lambda x: True, "Conjugate")],
45
+ "Max": [(lambda *x: True, "Max")],
46
+ "Min": [(lambda *x: True, "Min")],
47
+ "erf": [(lambda x: True, "Erf")],
48
+ "erf2": [(lambda *x: True, "Erf")],
49
+ "erfc": [(lambda x: True, "Erfc")],
50
+ "erfi": [(lambda x: True, "Erfi")],
51
+ "erfinv": [(lambda x: True, "InverseErf")],
52
+ "erfcinv": [(lambda x: True, "InverseErfc")],
53
+ "erf2inv": [(lambda *x: True, "InverseErf")],
54
+ "expint": [(lambda *x: True, "ExpIntegralE")],
55
+ "Ei": [(lambda x: True, "ExpIntegralEi")],
56
+ "fresnelc": [(lambda x: True, "FresnelC")],
57
+ "fresnels": [(lambda x: True, "FresnelS")],
58
+ "gamma": [(lambda x: True, "Gamma")],
59
+ "uppergamma": [(lambda *x: True, "Gamma")],
60
+ "polygamma": [(lambda *x: True, "PolyGamma")],
61
+ "loggamma": [(lambda x: True, "LogGamma")],
62
+ "beta": [(lambda *x: True, "Beta")],
63
+ "Ci": [(lambda x: True, "CosIntegral")],
64
+ "Si": [(lambda x: True, "SinIntegral")],
65
+ "Chi": [(lambda x: True, "CoshIntegral")],
66
+ "Shi": [(lambda x: True, "SinhIntegral")],
67
+ "li": [(lambda x: True, "LogIntegral")],
68
+ "factorial": [(lambda x: True, "Factorial")],
69
+ "factorial2": [(lambda x: True, "Factorial2")],
70
+ "subfactorial": [(lambda x: True, "Subfactorial")],
71
+ "catalan": [(lambda x: True, "CatalanNumber")],
72
+ "harmonic": [(lambda *x: True, "HarmonicNumber")],
73
+ "lucas": [(lambda x: True, "LucasL")],
74
+ "RisingFactorial": [(lambda *x: True, "Pochhammer")],
75
+ "FallingFactorial": [(lambda *x: True, "FactorialPower")],
76
+ "laguerre": [(lambda *x: True, "LaguerreL")],
77
+ "assoc_laguerre": [(lambda *x: True, "LaguerreL")],
78
+ "hermite": [(lambda *x: True, "HermiteH")],
79
+ "jacobi": [(lambda *x: True, "JacobiP")],
80
+ "gegenbauer": [(lambda *x: True, "GegenbauerC")],
81
+ "chebyshevt": [(lambda *x: True, "ChebyshevT")],
82
+ "chebyshevu": [(lambda *x: True, "ChebyshevU")],
83
+ "legendre": [(lambda *x: True, "LegendreP")],
84
+ "assoc_legendre": [(lambda *x: True, "LegendreP")],
85
+ "mathieuc": [(lambda *x: True, "MathieuC")],
86
+ "mathieus": [(lambda *x: True, "MathieuS")],
87
+ "mathieucprime": [(lambda *x: True, "MathieuCPrime")],
88
+ "mathieusprime": [(lambda *x: True, "MathieuSPrime")],
89
+ "stieltjes": [(lambda x: True, "StieltjesGamma")],
90
+ "elliptic_e": [(lambda *x: True, "EllipticE")],
91
+ "elliptic_f": [(lambda *x: True, "EllipticE")],
92
+ "elliptic_k": [(lambda x: True, "EllipticK")],
93
+ "elliptic_pi": [(lambda *x: True, "EllipticPi")],
94
+ "zeta": [(lambda *x: True, "Zeta")],
95
+ "dirichlet_eta": [(lambda x: True, "DirichletEta")],
96
+ "riemann_xi": [(lambda x: True, "RiemannXi")],
97
+ "besseli": [(lambda *x: True, "BesselI")],
98
+ "besselj": [(lambda *x: True, "BesselJ")],
99
+ "besselk": [(lambda *x: True, "BesselK")],
100
+ "bessely": [(lambda *x: True, "BesselY")],
101
+ "hankel1": [(lambda *x: True, "HankelH1")],
102
+ "hankel2": [(lambda *x: True, "HankelH2")],
103
+ "airyai": [(lambda x: True, "AiryAi")],
104
+ "airybi": [(lambda x: True, "AiryBi")],
105
+ "airyaiprime": [(lambda x: True, "AiryAiPrime")],
106
+ "airybiprime": [(lambda x: True, "AiryBiPrime")],
107
+ "polylog": [(lambda *x: True, "PolyLog")],
108
+ "lerchphi": [(lambda *x: True, "LerchPhi")],
109
+ "gcd": [(lambda *x: True, "GCD")],
110
+ "lcm": [(lambda *x: True, "LCM")],
111
+ "jn": [(lambda *x: True, "SphericalBesselJ")],
112
+ "yn": [(lambda *x: True, "SphericalBesselY")],
113
+ "hyper": [(lambda *x: True, "HypergeometricPFQ")],
114
+ "meijerg": [(lambda *x: True, "MeijerG")],
115
+ "appellf1": [(lambda *x: True, "AppellF1")],
116
+ "DiracDelta": [(lambda x: True, "DiracDelta")],
117
+ "Heaviside": [(lambda x: True, "HeavisideTheta")],
118
+ "KroneckerDelta": [(lambda *x: True, "KroneckerDelta")],
119
+ "sqrt": [(lambda x: True, "Sqrt")], # For automatic rewrites
120
+ }
121
+
122
+
123
+ class MCodePrinter(CodePrinter):
124
+ """A printer to convert Python expressions to
125
+ strings of the Wolfram's Mathematica code
126
+ """
127
+ printmethod = "_mcode"
128
+ language = "Wolfram Language"
129
+
130
+ _default_settings: dict[str, Any] = {
131
+ 'order': None,
132
+ 'full_prec': 'auto',
133
+ 'precision': 15,
134
+ 'user_functions': {},
135
+ 'human': True,
136
+ 'allow_unknown_functions': False,
137
+ }
138
+
139
+ _number_symbols: set[tuple[Expr, Float]] = set()
140
+ _not_supported: set[Basic] = set()
141
+
142
+ def __init__(self, settings={}):
143
+ """Register function mappings supplied by user"""
144
+ CodePrinter.__init__(self, settings)
145
+ self.known_functions = dict(known_functions)
146
+ userfuncs = settings.get('user_functions', {}).copy()
147
+ for k, v in userfuncs.items():
148
+ if not isinstance(v, list):
149
+ userfuncs[k] = [(lambda *x: True, v)]
150
+ self.known_functions.update(userfuncs)
151
+
152
+ def _format_code(self, lines):
153
+ return lines
154
+
155
+ def _print_Pow(self, expr):
156
+ PREC = precedence(expr)
157
+ return '%s^%s' % (self.parenthesize(expr.base, PREC),
158
+ self.parenthesize(expr.exp, PREC))
159
+
160
+ def _print_Mul(self, expr):
161
+ PREC = precedence(expr)
162
+ c, nc = expr.args_cnc()
163
+ res = super()._print_Mul(expr.func(*c))
164
+ if nc:
165
+ res += '*'
166
+ res += '**'.join(self.parenthesize(a, PREC) for a in nc)
167
+ return res
168
+
169
+ def _print_Relational(self, expr):
170
+ lhs_code = self._print(expr.lhs)
171
+ rhs_code = self._print(expr.rhs)
172
+ op = expr.rel_op
173
+ return "{} {} {}".format(lhs_code, op, rhs_code)
174
+
175
+ # Primitive numbers
176
+ def _print_Zero(self, expr):
177
+ return '0'
178
+
179
+ def _print_One(self, expr):
180
+ return '1'
181
+
182
+ def _print_NegativeOne(self, expr):
183
+ return '-1'
184
+
185
+ def _print_Half(self, expr):
186
+ return '1/2'
187
+
188
+ def _print_ImaginaryUnit(self, expr):
189
+ return 'I'
190
+
191
+
192
+ # Infinity and invalid numbers
193
+ def _print_Infinity(self, expr):
194
+ return 'Infinity'
195
+
196
+ def _print_NegativeInfinity(self, expr):
197
+ return '-Infinity'
198
+
199
+ def _print_ComplexInfinity(self, expr):
200
+ return 'ComplexInfinity'
201
+
202
+ def _print_NaN(self, expr):
203
+ return 'Indeterminate'
204
+
205
+
206
+ # Mathematical constants
207
+ def _print_Exp1(self, expr):
208
+ return 'E'
209
+
210
+ def _print_Pi(self, expr):
211
+ return 'Pi'
212
+
213
+ def _print_GoldenRatio(self, expr):
214
+ return 'GoldenRatio'
215
+
216
+ def _print_TribonacciConstant(self, expr):
217
+ expanded = expr.expand(func=True)
218
+ PREC = precedence(expr)
219
+ return self.parenthesize(expanded, PREC)
220
+
221
+ def _print_EulerGamma(self, expr):
222
+ return 'EulerGamma'
223
+
224
+ def _print_Catalan(self, expr):
225
+ return 'Catalan'
226
+
227
+
228
+ def _print_list(self, expr):
229
+ return '{' + ', '.join(self.doprint(a) for a in expr) + '}'
230
+ _print_tuple = _print_list
231
+ _print_Tuple = _print_list
232
+
233
+ def _print_ImmutableDenseMatrix(self, expr):
234
+ return self.doprint(expr.tolist())
235
+
236
+ def _print_ImmutableSparseMatrix(self, expr):
237
+
238
+ def print_rule(pos, val):
239
+ return '{} -> {}'.format(
240
+ self.doprint((pos[0]+1, pos[1]+1)), self.doprint(val))
241
+
242
+ def print_data():
243
+ items = sorted(expr.todok().items(), key=default_sort_key)
244
+ return '{' + \
245
+ ', '.join(print_rule(k, v) for k, v in items) + \
246
+ '}'
247
+
248
+ def print_dims():
249
+ return self.doprint(expr.shape)
250
+
251
+ return 'SparseArray[{}, {}]'.format(print_data(), print_dims())
252
+
253
+ def _print_ImmutableDenseNDimArray(self, expr):
254
+ return self.doprint(expr.tolist())
255
+
256
+ def _print_ImmutableSparseNDimArray(self, expr):
257
+ def print_string_list(string_list):
258
+ return '{' + ', '.join(a for a in string_list) + '}'
259
+
260
+ def to_mathematica_index(*args):
261
+ """Helper function to change Python style indexing to
262
+ Pathematica indexing.
263
+
264
+ Python indexing (0, 1 ... n-1)
265
+ -> Mathematica indexing (1, 2 ... n)
266
+ """
267
+ return tuple(i + 1 for i in args)
268
+
269
+ def print_rule(pos, val):
270
+ """Helper function to print a rule of Mathematica"""
271
+ return '{} -> {}'.format(self.doprint(pos), self.doprint(val))
272
+
273
+ def print_data():
274
+ """Helper function to print data part of Mathematica
275
+ sparse array.
276
+
277
+ It uses the fourth notation ``SparseArray[data,{d1,d2,...}]``
278
+ from
279
+ https://reference.wolfram.com/language/ref/SparseArray.html
280
+
281
+ ``data`` must be formatted with rule.
282
+ """
283
+ return print_string_list(
284
+ [print_rule(
285
+ to_mathematica_index(*(expr._get_tuple_index(key))),
286
+ value)
287
+ for key, value in sorted(expr._sparse_array.items())]
288
+ )
289
+
290
+ def print_dims():
291
+ """Helper function to print dimensions part of Mathematica
292
+ sparse array.
293
+
294
+ It uses the fourth notation ``SparseArray[data,{d1,d2,...}]``
295
+ from
296
+ https://reference.wolfram.com/language/ref/SparseArray.html
297
+ """
298
+ return self.doprint(expr.shape)
299
+
300
+ return 'SparseArray[{}, {}]'.format(print_data(), print_dims())
301
+
302
+ def _print_Function(self, expr):
303
+ if expr.func.__name__ in self.known_functions:
304
+ cond_mfunc = self.known_functions[expr.func.__name__]
305
+ for cond, mfunc in cond_mfunc:
306
+ if cond(*expr.args):
307
+ return "%s[%s]" % (mfunc, self.stringify(expr.args, ", "))
308
+ elif expr.func.__name__ in self._rewriteable_functions:
309
+ # Simple rewrite to supported function possible
310
+ target_f, required_fs = self._rewriteable_functions[expr.func.__name__]
311
+ if self._can_print(target_f) and all(self._can_print(f) for f in required_fs):
312
+ return self._print(expr.rewrite(target_f))
313
+ return expr.func.__name__ + "[%s]" % self.stringify(expr.args, ", ")
314
+
315
+ _print_MinMaxBase = _print_Function
316
+
317
+ def _print_LambertW(self, expr):
318
+ if len(expr.args) == 1:
319
+ return "ProductLog[{}]".format(self._print(expr.args[0]))
320
+ return "ProductLog[{}, {}]".format(
321
+ self._print(expr.args[1]), self._print(expr.args[0]))
322
+
323
+ def _print_Integral(self, expr):
324
+ if len(expr.variables) == 1 and not expr.limits[0][1:]:
325
+ args = [expr.args[0], expr.variables[0]]
326
+ else:
327
+ args = expr.args
328
+ return "Hold[Integrate[" + ', '.join(self.doprint(a) for a in args) + "]]"
329
+
330
+ def _print_Sum(self, expr):
331
+ return "Hold[Sum[" + ', '.join(self.doprint(a) for a in expr.args) + "]]"
332
+
333
+ def _print_Derivative(self, expr):
334
+ dexpr = expr.expr
335
+ dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count]
336
+ return "Hold[D[" + ', '.join(self.doprint(a) for a in [dexpr] + dvars) + "]]"
337
+
338
+
339
+ def _get_comment(self, text):
340
+ return "(* {} *)".format(text)
341
+
342
+
343
+ def mathematica_code(expr, **settings):
344
+ r"""Converts an expr to a string of the Wolfram Mathematica code
345
+
346
+ Examples
347
+ ========
348
+
349
+ >>> from sympy import mathematica_code as mcode, symbols, sin
350
+ >>> x = symbols('x')
351
+ >>> mcode(sin(x).series(x).removeO())
352
+ '(1/120)*x^5 - 1/6*x^3 + x'
353
+ """
354
+ return MCodePrinter(settings).doprint(expr)