Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/17.attention.query_key_value.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/17.attention.query_key_value.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/25.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/25.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/4.post_attention_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/4.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/4.post_attention_layernorm.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/sympy/printing/__init__.py +116 -0
- venv/lib/python3.10/site-packages/sympy/printing/__pycache__/mathematica.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/printing/aesaracode.py +539 -0
- venv/lib/python3.10/site-packages/sympy/printing/c.py +747 -0
- venv/lib/python3.10/site-packages/sympy/printing/codeprinter.py +875 -0
- venv/lib/python3.10/site-packages/sympy/printing/cxx.py +169 -0
- venv/lib/python3.10/site-packages/sympy/printing/dot.py +294 -0
- venv/lib/python3.10/site-packages/sympy/printing/glsl.py +557 -0
- venv/lib/python3.10/site-packages/sympy/printing/gtk.py +16 -0
- venv/lib/python3.10/site-packages/sympy/printing/julia.py +658 -0
- venv/lib/python3.10/site-packages/sympy/printing/lambdarepr.py +251 -0
- venv/lib/python3.10/site-packages/sympy/printing/llvmjitcode.py +489 -0
- venv/lib/python3.10/site-packages/sympy/printing/mathematica.py +354 -0
- venv/lib/python3.10/site-packages/sympy/printing/octave.py +719 -0
- venv/lib/python3.10/site-packages/sympy/printing/precedence.py +177 -0
- venv/lib/python3.10/site-packages/sympy/printing/preview.py +390 -0
- venv/lib/python3.10/site-packages/sympy/printing/printer.py +396 -0
- venv/lib/python3.10/site-packages/sympy/printing/pycode.py +750 -0
- venv/lib/python3.10/site-packages/sympy/printing/python.py +93 -0
- venv/lib/python3.10/site-packages/sympy/printing/rcode.py +410 -0
- venv/lib/python3.10/site-packages/sympy/printing/repr.py +342 -0
- venv/lib/python3.10/site-packages/sympy/printing/rust.py +625 -0
- venv/lib/python3.10/site-packages/sympy/printing/smtlib.py +526 -0
- venv/lib/python3.10/site-packages/sympy/printing/str.py +1027 -0
- venv/lib/python3.10/site-packages/sympy/printing/tableform.py +366 -0
- venv/lib/python3.10/site-packages/sympy/printing/tensorflow.py +216 -0
- venv/lib/python3.10/site-packages/sympy/printing/theanocode.py +565 -0
- venv/lib/python3.10/site-packages/sympy/printing/tree.py +175 -0
- venv/lib/python3.10/site-packages/sympy/vector/__init__.py +47 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/basisdependent.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/coordsysrect.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/deloperator.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/dyadic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/functions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/implicitregion.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/integrals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/operators.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/orienters.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/parametricregion.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/point.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/scalar.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/vector/__pycache__/vector.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/17.attention.query_key_value.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:df5971a9070051d06a7fb30f6fc48ecb11967173c601666828847b77f0bf91cf
|
3 |
+
size 50332828
|
ckpts/universal/global_step80/zero/17.attention.query_key_value.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:26030bf56bad0424bc62434e186e4028cd203b922fb6a2839321558bb99dfc23
|
3 |
+
size 50332749
|
ckpts/universal/global_step80/zero/25.mlp.dense_4h_to_h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b32f636d35133a1b13a64fabbf8e2d9e3b8c58ea74d97cfdaf1f48258917e9cc
|
3 |
+
size 33555612
|
ckpts/universal/global_step80/zero/25.mlp.dense_4h_to_h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:51d252bc74c8b7ca01fd4bafbf305b4ac34a36e0595cea15d2c1a6980eba3cfe
|
3 |
+
size 33555533
|
ckpts/universal/global_step80/zero/4.post_attention_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a808d80a8bbe3c9dedaccae4744b1b7d35ac51f6e3f65068d849d086acf424c4
|
3 |
+
size 9372
|
ckpts/universal/global_step80/zero/4.post_attention_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3a29dfde7a6f36331e5a3213802f0808b04ef40cffc25a73d43259cc76947006
|
3 |
+
size 9387
|
ckpts/universal/global_step80/zero/4.post_attention_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:86613d6296174c3b637bc504ec97f826ac8c0eee949481461b096ef596a1f6bd
|
3 |
+
size 9293
|
venv/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 |
+
]
|
venv/lib/python3.10/site-packages/sympy/printing/__pycache__/mathematica.cpython-310.pyc
ADDED
Binary file (24 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/printing/aesaracode.py
ADDED
@@ -0,0 +1,539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
venv/lib/python3.10/site-packages/sympy/printing/c.py
ADDED
@@ -0,0 +1,747 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
}
|
venv/lib/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
venv/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 |
+
}
|
venv/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)}
|
venv/lib/python3.10/site-packages/sympy/printing/glsl.py
ADDED
@@ -0,0 +1,557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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))
|
venv/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))
|
venv/lib/python3.10/site-packages/sympy/printing/julia.py
ADDED
@@ -0,0 +1,658 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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))
|
venv/lib/python3.10/site-packages/sympy/printing/lambdarepr.py
ADDED
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
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)
|
venv/lib/python3.10/site-packages/sympy/printing/llvmjitcode.py
ADDED
@@ -0,0 +1,489 @@
|
|
|
|
|
|
|
|
|
|
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+
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 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
venv/lib/python3.10/site-packages/sympy/printing/octave.py
ADDED
@@ -0,0 +1,719 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Octave (and Matlab) code printer
|
3 |
+
|
4 |
+
The `OctaveCodePrinter` converts SymPy expressions into Octave expressions.
|
5 |
+
It uses a subset of the Octave language for Matlab compatibility.
|
6 |
+
|
7 |
+
A complete code generator, which uses `octave_code` extensively, can be found
|
8 |
+
in `sympy.utilities.codegen`. The `codegen` module can be used to generate
|
9 |
+
complete source code files.
|
10 |
+
|
11 |
+
"""
|
12 |
+
|
13 |
+
from __future__ import annotations
|
14 |
+
from typing import Any
|
15 |
+
|
16 |
+
from sympy.core import Mul, Pow, S, Rational
|
17 |
+
from sympy.core.mul import _keep_coeff
|
18 |
+
from sympy.core.numbers import equal_valued
|
19 |
+
from sympy.printing.codeprinter import CodePrinter
|
20 |
+
from sympy.printing.precedence import precedence, PRECEDENCE
|
21 |
+
from re import search
|
22 |
+
|
23 |
+
# List of known functions. First, those that have the same name in
|
24 |
+
# SymPy and Octave. This is almost certainly incomplete!
|
25 |
+
known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc",
|
26 |
+
"asin", "acos", "acot", "atan", "atan2", "asec", "acsc",
|
27 |
+
"sinh", "cosh", "tanh", "coth", "csch", "sech",
|
28 |
+
"asinh", "acosh", "atanh", "acoth", "asech", "acsch",
|
29 |
+
"erfc", "erfi", "erf", "erfinv", "erfcinv",
|
30 |
+
"besseli", "besselj", "besselk", "bessely",
|
31 |
+
"bernoulli", "beta", "euler", "exp", "factorial", "floor",
|
32 |
+
"fresnelc", "fresnels", "gamma", "harmonic", "log",
|
33 |
+
"polylog", "sign", "zeta", "legendre"]
|
34 |
+
|
35 |
+
# These functions have different names ("SymPy": "Octave"), more
|
36 |
+
# generally a mapping to (argument_conditions, octave_function).
|
37 |
+
known_fcns_src2 = {
|
38 |
+
"Abs": "abs",
|
39 |
+
"arg": "angle", # arg/angle ok in Octave but only angle in Matlab
|
40 |
+
"binomial": "bincoeff",
|
41 |
+
"ceiling": "ceil",
|
42 |
+
"chebyshevu": "chebyshevU",
|
43 |
+
"chebyshevt": "chebyshevT",
|
44 |
+
"Chi": "coshint",
|
45 |
+
"Ci": "cosint",
|
46 |
+
"conjugate": "conj",
|
47 |
+
"DiracDelta": "dirac",
|
48 |
+
"Heaviside": "heaviside",
|
49 |
+
"im": "imag",
|
50 |
+
"laguerre": "laguerreL",
|
51 |
+
"LambertW": "lambertw",
|
52 |
+
"li": "logint",
|
53 |
+
"loggamma": "gammaln",
|
54 |
+
"Max": "max",
|
55 |
+
"Min": "min",
|
56 |
+
"Mod": "mod",
|
57 |
+
"polygamma": "psi",
|
58 |
+
"re": "real",
|
59 |
+
"RisingFactorial": "pochhammer",
|
60 |
+
"Shi": "sinhint",
|
61 |
+
"Si": "sinint",
|
62 |
+
}
|
63 |
+
|
64 |
+
|
65 |
+
class OctaveCodePrinter(CodePrinter):
|
66 |
+
"""
|
67 |
+
A printer to convert expressions to strings of Octave/Matlab code.
|
68 |
+
"""
|
69 |
+
printmethod = "_octave"
|
70 |
+
language = "Octave"
|
71 |
+
|
72 |
+
_operators = {
|
73 |
+
'and': '&',
|
74 |
+
'or': '|',
|
75 |
+
'not': '~',
|
76 |
+
}
|
77 |
+
|
78 |
+
_default_settings: dict[str, Any] = {
|
79 |
+
'order': None,
|
80 |
+
'full_prec': 'auto',
|
81 |
+
'precision': 17,
|
82 |
+
'user_functions': {},
|
83 |
+
'human': True,
|
84 |
+
'allow_unknown_functions': False,
|
85 |
+
'contract': True,
|
86 |
+
'inline': True,
|
87 |
+
}
|
88 |
+
# Note: contract is for expressing tensors as loops (if True), or just
|
89 |
+
# assignment (if False). FIXME: this should be looked a more carefully
|
90 |
+
# for Octave.
|
91 |
+
|
92 |
+
|
93 |
+
def __init__(self, settings={}):
|
94 |
+
super().__init__(settings)
|
95 |
+
self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))
|
96 |
+
self.known_functions.update(dict(known_fcns_src2))
|
97 |
+
userfuncs = settings.get('user_functions', {})
|
98 |
+
self.known_functions.update(userfuncs)
|
99 |
+
|
100 |
+
|
101 |
+
def _rate_index_position(self, p):
|
102 |
+
return p*5
|
103 |
+
|
104 |
+
|
105 |
+
def _get_statement(self, codestring):
|
106 |
+
return "%s;" % codestring
|
107 |
+
|
108 |
+
|
109 |
+
def _get_comment(self, text):
|
110 |
+
return "% {}".format(text)
|
111 |
+
|
112 |
+
|
113 |
+
def _declare_number_const(self, name, value):
|
114 |
+
return "{} = {};".format(name, value)
|
115 |
+
|
116 |
+
|
117 |
+
def _format_code(self, lines):
|
118 |
+
return self.indent_code(lines)
|
119 |
+
|
120 |
+
|
121 |
+
def _traverse_matrix_indices(self, mat):
|
122 |
+
# Octave uses Fortran order (column-major)
|
123 |
+
rows, cols = mat.shape
|
124 |
+
return ((i, j) for j in range(cols) for i in range(rows))
|
125 |
+
|
126 |
+
|
127 |
+
def _get_loop_opening_ending(self, indices):
|
128 |
+
open_lines = []
|
129 |
+
close_lines = []
|
130 |
+
for i in indices:
|
131 |
+
# Octave arrays start at 1 and end at dimension
|
132 |
+
var, start, stop = map(self._print,
|
133 |
+
[i.label, i.lower + 1, i.upper + 1])
|
134 |
+
open_lines.append("for %s = %s:%s" % (var, start, stop))
|
135 |
+
close_lines.append("end")
|
136 |
+
return open_lines, close_lines
|
137 |
+
|
138 |
+
|
139 |
+
def _print_Mul(self, expr):
|
140 |
+
# print complex numbers nicely in Octave
|
141 |
+
if (expr.is_number and expr.is_imaginary and
|
142 |
+
(S.ImaginaryUnit*expr).is_Integer):
|
143 |
+
return "%si" % self._print(-S.ImaginaryUnit*expr)
|
144 |
+
|
145 |
+
# cribbed from str.py
|
146 |
+
prec = precedence(expr)
|
147 |
+
|
148 |
+
c, e = expr.as_coeff_Mul()
|
149 |
+
if c < 0:
|
150 |
+
expr = _keep_coeff(-c, e)
|
151 |
+
sign = "-"
|
152 |
+
else:
|
153 |
+
sign = ""
|
154 |
+
|
155 |
+
a = [] # items in the numerator
|
156 |
+
b = [] # items that are in the denominator (if any)
|
157 |
+
|
158 |
+
pow_paren = [] # Will collect all pow with more than one base element and exp = -1
|
159 |
+
|
160 |
+
if self.order not in ('old', 'none'):
|
161 |
+
args = expr.as_ordered_factors()
|
162 |
+
else:
|
163 |
+
# use make_args in case expr was something like -x -> x
|
164 |
+
args = Mul.make_args(expr)
|
165 |
+
|
166 |
+
# Gather args for numerator/denominator
|
167 |
+
for item in args:
|
168 |
+
if (item.is_commutative and item.is_Pow and item.exp.is_Rational
|
169 |
+
and item.exp.is_negative):
|
170 |
+
if item.exp != -1:
|
171 |
+
b.append(Pow(item.base, -item.exp, evaluate=False))
|
172 |
+
else:
|
173 |
+
if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
|
174 |
+
pow_paren.append(item)
|
175 |
+
b.append(Pow(item.base, -item.exp))
|
176 |
+
elif item.is_Rational and item is not S.Infinity:
|
177 |
+
if item.p != 1:
|
178 |
+
a.append(Rational(item.p))
|
179 |
+
if item.q != 1:
|
180 |
+
b.append(Rational(item.q))
|
181 |
+
else:
|
182 |
+
a.append(item)
|
183 |
+
|
184 |
+
a = a or [S.One]
|
185 |
+
|
186 |
+
a_str = [self.parenthesize(x, prec) for x in a]
|
187 |
+
b_str = [self.parenthesize(x, prec) for x in b]
|
188 |
+
|
189 |
+
# To parenthesize Pow with exp = -1 and having more than one Symbol
|
190 |
+
for item in pow_paren:
|
191 |
+
if item.base in b:
|
192 |
+
b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
|
193 |
+
|
194 |
+
# from here it differs from str.py to deal with "*" and ".*"
|
195 |
+
def multjoin(a, a_str):
|
196 |
+
# here we probably are assuming the constants will come first
|
197 |
+
r = a_str[0]
|
198 |
+
for i in range(1, len(a)):
|
199 |
+
mulsym = '*' if a[i-1].is_number else '.*'
|
200 |
+
r = r + mulsym + a_str[i]
|
201 |
+
return r
|
202 |
+
|
203 |
+
if not b:
|
204 |
+
return sign + multjoin(a, a_str)
|
205 |
+
elif len(b) == 1:
|
206 |
+
divsym = '/' if b[0].is_number else './'
|
207 |
+
return sign + multjoin(a, a_str) + divsym + b_str[0]
|
208 |
+
else:
|
209 |
+
divsym = '/' if all(bi.is_number for bi in b) else './'
|
210 |
+
return (sign + multjoin(a, a_str) +
|
211 |
+
divsym + "(%s)" % multjoin(b, b_str))
|
212 |
+
|
213 |
+
def _print_Relational(self, expr):
|
214 |
+
lhs_code = self._print(expr.lhs)
|
215 |
+
rhs_code = self._print(expr.rhs)
|
216 |
+
op = expr.rel_op
|
217 |
+
return "{} {} {}".format(lhs_code, op, rhs_code)
|
218 |
+
|
219 |
+
def _print_Pow(self, expr):
|
220 |
+
powsymbol = '^' if all(x.is_number for x in expr.args) else '.^'
|
221 |
+
|
222 |
+
PREC = precedence(expr)
|
223 |
+
|
224 |
+
if equal_valued(expr.exp, 0.5):
|
225 |
+
return "sqrt(%s)" % self._print(expr.base)
|
226 |
+
|
227 |
+
if expr.is_commutative:
|
228 |
+
if equal_valued(expr.exp, -0.5):
|
229 |
+
sym = '/' if expr.base.is_number else './'
|
230 |
+
return "1" + sym + "sqrt(%s)" % self._print(expr.base)
|
231 |
+
if equal_valued(expr.exp, -1):
|
232 |
+
sym = '/' if expr.base.is_number else './'
|
233 |
+
return "1" + sym + "%s" % self.parenthesize(expr.base, PREC)
|
234 |
+
|
235 |
+
return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol,
|
236 |
+
self.parenthesize(expr.exp, PREC))
|
237 |
+
|
238 |
+
|
239 |
+
def _print_MatPow(self, expr):
|
240 |
+
PREC = precedence(expr)
|
241 |
+
return '%s^%s' % (self.parenthesize(expr.base, PREC),
|
242 |
+
self.parenthesize(expr.exp, PREC))
|
243 |
+
|
244 |
+
def _print_MatrixSolve(self, expr):
|
245 |
+
PREC = precedence(expr)
|
246 |
+
return "%s \\ %s" % (self.parenthesize(expr.matrix, PREC),
|
247 |
+
self.parenthesize(expr.vector, PREC))
|
248 |
+
|
249 |
+
def _print_Pi(self, expr):
|
250 |
+
return 'pi'
|
251 |
+
|
252 |
+
|
253 |
+
def _print_ImaginaryUnit(self, expr):
|
254 |
+
return "1i"
|
255 |
+
|
256 |
+
|
257 |
+
def _print_Exp1(self, expr):
|
258 |
+
return "exp(1)"
|
259 |
+
|
260 |
+
|
261 |
+
def _print_GoldenRatio(self, expr):
|
262 |
+
# FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)?
|
263 |
+
#return self._print((1+sqrt(S(5)))/2)
|
264 |
+
return "(1+sqrt(5))/2"
|
265 |
+
|
266 |
+
|
267 |
+
def _print_Assignment(self, expr):
|
268 |
+
from sympy.codegen.ast import Assignment
|
269 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
270 |
+
from sympy.tensor.indexed import IndexedBase
|
271 |
+
# Copied from codeprinter, but remove special MatrixSymbol treatment
|
272 |
+
lhs = expr.lhs
|
273 |
+
rhs = expr.rhs
|
274 |
+
# We special case assignments that take multiple lines
|
275 |
+
if not self._settings["inline"] and isinstance(expr.rhs, Piecewise):
|
276 |
+
# Here we modify Piecewise so each expression is now
|
277 |
+
# an Assignment, and then continue on the print.
|
278 |
+
expressions = []
|
279 |
+
conditions = []
|
280 |
+
for (e, c) in rhs.args:
|
281 |
+
expressions.append(Assignment(lhs, e))
|
282 |
+
conditions.append(c)
|
283 |
+
temp = Piecewise(*zip(expressions, conditions))
|
284 |
+
return self._print(temp)
|
285 |
+
if self._settings["contract"] and (lhs.has(IndexedBase) or
|
286 |
+
rhs.has(IndexedBase)):
|
287 |
+
# Here we check if there is looping to be done, and if so
|
288 |
+
# print the required loops.
|
289 |
+
return self._doprint_loops(rhs, lhs)
|
290 |
+
else:
|
291 |
+
lhs_code = self._print(lhs)
|
292 |
+
rhs_code = self._print(rhs)
|
293 |
+
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
|
294 |
+
|
295 |
+
|
296 |
+
def _print_Infinity(self, expr):
|
297 |
+
return 'inf'
|
298 |
+
|
299 |
+
|
300 |
+
def _print_NegativeInfinity(self, expr):
|
301 |
+
return '-inf'
|
302 |
+
|
303 |
+
|
304 |
+
def _print_NaN(self, expr):
|
305 |
+
return 'NaN'
|
306 |
+
|
307 |
+
|
308 |
+
def _print_list(self, expr):
|
309 |
+
return '{' + ', '.join(self._print(a) for a in expr) + '}'
|
310 |
+
_print_tuple = _print_list
|
311 |
+
_print_Tuple = _print_list
|
312 |
+
_print_List = _print_list
|
313 |
+
|
314 |
+
|
315 |
+
def _print_BooleanTrue(self, expr):
|
316 |
+
return "true"
|
317 |
+
|
318 |
+
|
319 |
+
def _print_BooleanFalse(self, expr):
|
320 |
+
return "false"
|
321 |
+
|
322 |
+
|
323 |
+
def _print_bool(self, expr):
|
324 |
+
return str(expr).lower()
|
325 |
+
|
326 |
+
|
327 |
+
# Could generate quadrature code for definite Integrals?
|
328 |
+
#_print_Integral = _print_not_supported
|
329 |
+
|
330 |
+
|
331 |
+
def _print_MatrixBase(self, A):
|
332 |
+
# Handle zero dimensions:
|
333 |
+
if (A.rows, A.cols) == (0, 0):
|
334 |
+
return '[]'
|
335 |
+
elif S.Zero in A.shape:
|
336 |
+
return 'zeros(%s, %s)' % (A.rows, A.cols)
|
337 |
+
elif (A.rows, A.cols) == (1, 1):
|
338 |
+
# Octave does not distinguish between scalars and 1x1 matrices
|
339 |
+
return self._print(A[0, 0])
|
340 |
+
return "[%s]" % "; ".join(" ".join([self._print(a) for a in A[r, :]])
|
341 |
+
for r in range(A.rows))
|
342 |
+
|
343 |
+
|
344 |
+
def _print_SparseRepMatrix(self, A):
|
345 |
+
from sympy.matrices import Matrix
|
346 |
+
L = A.col_list();
|
347 |
+
# make row vectors of the indices and entries
|
348 |
+
I = Matrix([[k[0] + 1 for k in L]])
|
349 |
+
J = Matrix([[k[1] + 1 for k in L]])
|
350 |
+
AIJ = Matrix([[k[2] for k in L]])
|
351 |
+
return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J),
|
352 |
+
self._print(AIJ), A.rows, A.cols)
|
353 |
+
|
354 |
+
|
355 |
+
def _print_MatrixElement(self, expr):
|
356 |
+
return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
|
357 |
+
+ '(%s, %s)' % (expr.i + 1, expr.j + 1)
|
358 |
+
|
359 |
+
|
360 |
+
def _print_MatrixSlice(self, expr):
|
361 |
+
def strslice(x, lim):
|
362 |
+
l = x[0] + 1
|
363 |
+
h = x[1]
|
364 |
+
step = x[2]
|
365 |
+
lstr = self._print(l)
|
366 |
+
hstr = 'end' if h == lim else self._print(h)
|
367 |
+
if step == 1:
|
368 |
+
if l == 1 and h == lim:
|
369 |
+
return ':'
|
370 |
+
if l == h:
|
371 |
+
return lstr
|
372 |
+
else:
|
373 |
+
return lstr + ':' + hstr
|
374 |
+
else:
|
375 |
+
return ':'.join((lstr, self._print(step), hstr))
|
376 |
+
return (self._print(expr.parent) + '(' +
|
377 |
+
strslice(expr.rowslice, expr.parent.shape[0]) + ', ' +
|
378 |
+
strslice(expr.colslice, expr.parent.shape[1]) + ')')
|
379 |
+
|
380 |
+
|
381 |
+
def _print_Indexed(self, expr):
|
382 |
+
inds = [ self._print(i) for i in expr.indices ]
|
383 |
+
return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
|
384 |
+
|
385 |
+
|
386 |
+
def _print_Idx(self, expr):
|
387 |
+
return self._print(expr.label)
|
388 |
+
|
389 |
+
|
390 |
+
def _print_KroneckerDelta(self, expr):
|
391 |
+
prec = PRECEDENCE["Pow"]
|
392 |
+
return "double(%s == %s)" % tuple(self.parenthesize(x, prec)
|
393 |
+
for x in expr.args)
|
394 |
+
|
395 |
+
def _print_HadamardProduct(self, expr):
|
396 |
+
return '.*'.join([self.parenthesize(arg, precedence(expr))
|
397 |
+
for arg in expr.args])
|
398 |
+
|
399 |
+
def _print_HadamardPower(self, expr):
|
400 |
+
PREC = precedence(expr)
|
401 |
+
return '.**'.join([
|
402 |
+
self.parenthesize(expr.base, PREC),
|
403 |
+
self.parenthesize(expr.exp, PREC)
|
404 |
+
])
|
405 |
+
|
406 |
+
def _print_Identity(self, expr):
|
407 |
+
shape = expr.shape
|
408 |
+
if len(shape) == 2 and shape[0] == shape[1]:
|
409 |
+
shape = [shape[0]]
|
410 |
+
s = ", ".join(self._print(n) for n in shape)
|
411 |
+
return "eye(" + s + ")"
|
412 |
+
|
413 |
+
def _print_lowergamma(self, expr):
|
414 |
+
# Octave implements regularized incomplete gamma function
|
415 |
+
return "(gammainc({1}, {0}).*gamma({0}))".format(
|
416 |
+
self._print(expr.args[0]), self._print(expr.args[1]))
|
417 |
+
|
418 |
+
|
419 |
+
def _print_uppergamma(self, expr):
|
420 |
+
return "(gammainc({1}, {0}, 'upper').*gamma({0}))".format(
|
421 |
+
self._print(expr.args[0]), self._print(expr.args[1]))
|
422 |
+
|
423 |
+
|
424 |
+
def _print_sinc(self, expr):
|
425 |
+
#Note: Divide by pi because Octave implements normalized sinc function.
|
426 |
+
return "sinc(%s)" % self._print(expr.args[0]/S.Pi)
|
427 |
+
|
428 |
+
|
429 |
+
def _print_hankel1(self, expr):
|
430 |
+
return "besselh(%s, 1, %s)" % (self._print(expr.order),
|
431 |
+
self._print(expr.argument))
|
432 |
+
|
433 |
+
|
434 |
+
def _print_hankel2(self, expr):
|
435 |
+
return "besselh(%s, 2, %s)" % (self._print(expr.order),
|
436 |
+
self._print(expr.argument))
|
437 |
+
|
438 |
+
|
439 |
+
# Note: as of 2015, Octave doesn't have spherical Bessel functions
|
440 |
+
def _print_jn(self, expr):
|
441 |
+
from sympy.functions import sqrt, besselj
|
442 |
+
x = expr.argument
|
443 |
+
expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x)
|
444 |
+
return self._print(expr2)
|
445 |
+
|
446 |
+
|
447 |
+
def _print_yn(self, expr):
|
448 |
+
from sympy.functions import sqrt, bessely
|
449 |
+
x = expr.argument
|
450 |
+
expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x)
|
451 |
+
return self._print(expr2)
|
452 |
+
|
453 |
+
|
454 |
+
def _print_airyai(self, expr):
|
455 |
+
return "airy(0, %s)" % self._print(expr.args[0])
|
456 |
+
|
457 |
+
|
458 |
+
def _print_airyaiprime(self, expr):
|
459 |
+
return "airy(1, %s)" % self._print(expr.args[0])
|
460 |
+
|
461 |
+
|
462 |
+
def _print_airybi(self, expr):
|
463 |
+
return "airy(2, %s)" % self._print(expr.args[0])
|
464 |
+
|
465 |
+
|
466 |
+
def _print_airybiprime(self, expr):
|
467 |
+
return "airy(3, %s)" % self._print(expr.args[0])
|
468 |
+
|
469 |
+
|
470 |
+
def _print_expint(self, expr):
|
471 |
+
mu, x = expr.args
|
472 |
+
if mu != 1:
|
473 |
+
return self._print_not_supported(expr)
|
474 |
+
return "expint(%s)" % self._print(x)
|
475 |
+
|
476 |
+
|
477 |
+
def _one_or_two_reversed_args(self, expr):
|
478 |
+
assert len(expr.args) <= 2
|
479 |
+
return '{name}({args})'.format(
|
480 |
+
name=self.known_functions[expr.__class__.__name__],
|
481 |
+
args=", ".join([self._print(x) for x in reversed(expr.args)])
|
482 |
+
)
|
483 |
+
|
484 |
+
|
485 |
+
_print_DiracDelta = _print_LambertW = _one_or_two_reversed_args
|
486 |
+
|
487 |
+
|
488 |
+
def _nested_binary_math_func(self, expr):
|
489 |
+
return '{name}({arg1}, {arg2})'.format(
|
490 |
+
name=self.known_functions[expr.__class__.__name__],
|
491 |
+
arg1=self._print(expr.args[0]),
|
492 |
+
arg2=self._print(expr.func(*expr.args[1:]))
|
493 |
+
)
|
494 |
+
|
495 |
+
_print_Max = _print_Min = _nested_binary_math_func
|
496 |
+
|
497 |
+
|
498 |
+
def _print_Piecewise(self, expr):
|
499 |
+
if expr.args[-1].cond != True:
|
500 |
+
# We need the last conditional to be a True, otherwise the resulting
|
501 |
+
# function may not return a result.
|
502 |
+
raise ValueError("All Piecewise expressions must contain an "
|
503 |
+
"(expr, True) statement to be used as a default "
|
504 |
+
"condition. Without one, the generated "
|
505 |
+
"expression may not evaluate to anything under "
|
506 |
+
"some condition.")
|
507 |
+
lines = []
|
508 |
+
if self._settings["inline"]:
|
509 |
+
# Express each (cond, expr) pair in a nested Horner form:
|
510 |
+
# (condition) .* (expr) + (not cond) .* (<others>)
|
511 |
+
# Expressions that result in multiple statements won't work here.
|
512 |
+
ecpairs = ["({0}).*({1}) + (~({0})).*(".format
|
513 |
+
(self._print(c), self._print(e))
|
514 |
+
for e, c in expr.args[:-1]]
|
515 |
+
elast = "%s" % self._print(expr.args[-1].expr)
|
516 |
+
pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs)
|
517 |
+
# Note: current need these outer brackets for 2*pw. Would be
|
518 |
+
# nicer to teach parenthesize() to do this for us when needed!
|
519 |
+
return "(" + pw + ")"
|
520 |
+
else:
|
521 |
+
for i, (e, c) in enumerate(expr.args):
|
522 |
+
if i == 0:
|
523 |
+
lines.append("if (%s)" % self._print(c))
|
524 |
+
elif i == len(expr.args) - 1 and c == True:
|
525 |
+
lines.append("else")
|
526 |
+
else:
|
527 |
+
lines.append("elseif (%s)" % self._print(c))
|
528 |
+
code0 = self._print(e)
|
529 |
+
lines.append(code0)
|
530 |
+
if i == len(expr.args) - 1:
|
531 |
+
lines.append("end")
|
532 |
+
return "\n".join(lines)
|
533 |
+
|
534 |
+
|
535 |
+
def _print_zeta(self, expr):
|
536 |
+
if len(expr.args) == 1:
|
537 |
+
return "zeta(%s)" % self._print(expr.args[0])
|
538 |
+
else:
|
539 |
+
# Matlab two argument zeta is not equivalent to SymPy's
|
540 |
+
return self._print_not_supported(expr)
|
541 |
+
|
542 |
+
|
543 |
+
def indent_code(self, code):
|
544 |
+
"""Accepts a string of code or a list of code lines"""
|
545 |
+
|
546 |
+
# code mostly copied from ccode
|
547 |
+
if isinstance(code, str):
|
548 |
+
code_lines = self.indent_code(code.splitlines(True))
|
549 |
+
return ''.join(code_lines)
|
550 |
+
|
551 |
+
tab = " "
|
552 |
+
inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ')
|
553 |
+
dec_regex = ('^end$', '^elseif ', '^else$')
|
554 |
+
|
555 |
+
# pre-strip left-space from the code
|
556 |
+
code = [ line.lstrip(' \t') for line in code ]
|
557 |
+
|
558 |
+
increase = [ int(any(search(re, line) for re in inc_regex))
|
559 |
+
for line in code ]
|
560 |
+
decrease = [ int(any(search(re, line) for re in dec_regex))
|
561 |
+
for line in code ]
|
562 |
+
|
563 |
+
pretty = []
|
564 |
+
level = 0
|
565 |
+
for n, line in enumerate(code):
|
566 |
+
if line in ('', '\n'):
|
567 |
+
pretty.append(line)
|
568 |
+
continue
|
569 |
+
level -= decrease[n]
|
570 |
+
pretty.append("%s%s" % (tab*level, line))
|
571 |
+
level += increase[n]
|
572 |
+
return pretty
|
573 |
+
|
574 |
+
|
575 |
+
def octave_code(expr, assign_to=None, **settings):
|
576 |
+
r"""Converts `expr` to a string of Octave (or Matlab) code.
|
577 |
+
|
578 |
+
The string uses a subset of the Octave language for Matlab compatibility.
|
579 |
+
|
580 |
+
Parameters
|
581 |
+
==========
|
582 |
+
|
583 |
+
expr : Expr
|
584 |
+
A SymPy expression to be converted.
|
585 |
+
assign_to : optional
|
586 |
+
When given, the argument is used as the name of the variable to which
|
587 |
+
the expression is assigned. Can be a string, ``Symbol``,
|
588 |
+
``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
|
589 |
+
expressions that generate multi-line statements.
|
590 |
+
precision : integer, optional
|
591 |
+
The precision for numbers such as pi [default=16].
|
592 |
+
user_functions : dict, optional
|
593 |
+
A dictionary where keys are ``FunctionClass`` instances and values are
|
594 |
+
their string representations. Alternatively, the dictionary value can
|
595 |
+
be a list of tuples i.e. [(argument_test, cfunction_string)]. See
|
596 |
+
below for examples.
|
597 |
+
human : bool, optional
|
598 |
+
If True, the result is a single string that may contain some constant
|
599 |
+
declarations for the number symbols. If False, the same information is
|
600 |
+
returned in a tuple of (symbols_to_declare, not_supported_functions,
|
601 |
+
code_text). [default=True].
|
602 |
+
contract: bool, optional
|
603 |
+
If True, ``Indexed`` instances are assumed to obey tensor contraction
|
604 |
+
rules and the corresponding nested loops over indices are generated.
|
605 |
+
Setting contract=False will not generate loops, instead the user is
|
606 |
+
responsible to provide values for the indices in the code.
|
607 |
+
[default=True].
|
608 |
+
inline: bool, optional
|
609 |
+
If True, we try to create single-statement code instead of multiple
|
610 |
+
statements. [default=True].
|
611 |
+
|
612 |
+
Examples
|
613 |
+
========
|
614 |
+
|
615 |
+
>>> from sympy import octave_code, symbols, sin, pi
|
616 |
+
>>> x = symbols('x')
|
617 |
+
>>> octave_code(sin(x).series(x).removeO())
|
618 |
+
'x.^5/120 - x.^3/6 + x'
|
619 |
+
|
620 |
+
>>> from sympy import Rational, ceiling
|
621 |
+
>>> x, y, tau = symbols("x, y, tau")
|
622 |
+
>>> octave_code((2*tau)**Rational(7, 2))
|
623 |
+
'8*sqrt(2)*tau.^(7/2)'
|
624 |
+
|
625 |
+
Note that element-wise (Hadamard) operations are used by default between
|
626 |
+
symbols. This is because its very common in Octave to write "vectorized"
|
627 |
+
code. It is harmless if the values are scalars.
|
628 |
+
|
629 |
+
>>> octave_code(sin(pi*x*y), assign_to="s")
|
630 |
+
's = sin(pi*x.*y);'
|
631 |
+
|
632 |
+
If you need a matrix product "*" or matrix power "^", you can specify the
|
633 |
+
symbol as a ``MatrixSymbol``.
|
634 |
+
|
635 |
+
>>> from sympy import Symbol, MatrixSymbol
|
636 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
637 |
+
>>> A = MatrixSymbol('A', n, n)
|
638 |
+
>>> octave_code(3*pi*A**3)
|
639 |
+
'(3*pi)*A^3'
|
640 |
+
|
641 |
+
This class uses several rules to decide which symbol to use a product.
|
642 |
+
Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*".
|
643 |
+
A HadamardProduct can be used to specify componentwise multiplication ".*"
|
644 |
+
of two MatrixSymbols. There is currently there is no easy way to specify
|
645 |
+
scalar symbols, so sometimes the code might have some minor cosmetic
|
646 |
+
issues. For example, suppose x and y are scalars and A is a Matrix, then
|
647 |
+
while a human programmer might write "(x^2*y)*A^3", we generate:
|
648 |
+
|
649 |
+
>>> octave_code(x**2*y*A**3)
|
650 |
+
'(x.^2.*y)*A^3'
|
651 |
+
|
652 |
+
Matrices are supported using Octave inline notation. When using
|
653 |
+
``assign_to`` with matrices, the name can be specified either as a string
|
654 |
+
or as a ``MatrixSymbol``. The dimensions must align in the latter case.
|
655 |
+
|
656 |
+
>>> from sympy import Matrix, MatrixSymbol
|
657 |
+
>>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
|
658 |
+
>>> octave_code(mat, assign_to='A')
|
659 |
+
'A = [x.^2 sin(x) ceil(x)];'
|
660 |
+
|
661 |
+
``Piecewise`` expressions are implemented with logical masking by default.
|
662 |
+
Alternatively, you can pass "inline=False" to use if-else conditionals.
|
663 |
+
Note that if the ``Piecewise`` lacks a default term, represented by
|
664 |
+
``(expr, True)`` then an error will be thrown. This is to prevent
|
665 |
+
generating an expression that may not evaluate to anything.
|
666 |
+
|
667 |
+
>>> from sympy import Piecewise
|
668 |
+
>>> pw = Piecewise((x + 1, x > 0), (x, True))
|
669 |
+
>>> octave_code(pw, assign_to=tau)
|
670 |
+
'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));'
|
671 |
+
|
672 |
+
Note that any expression that can be generated normally can also exist
|
673 |
+
inside a Matrix:
|
674 |
+
|
675 |
+
>>> mat = Matrix([[x**2, pw, sin(x)]])
|
676 |
+
>>> octave_code(mat, assign_to='A')
|
677 |
+
'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];'
|
678 |
+
|
679 |
+
Custom printing can be defined for certain types by passing a dictionary of
|
680 |
+
"type" : "function" to the ``user_functions`` kwarg. Alternatively, the
|
681 |
+
dictionary value can be a list of tuples i.e., [(argument_test,
|
682 |
+
cfunction_string)]. This can be used to call a custom Octave function.
|
683 |
+
|
684 |
+
>>> from sympy import Function
|
685 |
+
>>> f = Function('f')
|
686 |
+
>>> g = Function('g')
|
687 |
+
>>> custom_functions = {
|
688 |
+
... "f": "existing_octave_fcn",
|
689 |
+
... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
|
690 |
+
... (lambda x: not x.is_Matrix, "my_fcn")]
|
691 |
+
... }
|
692 |
+
>>> mat = Matrix([[1, x]])
|
693 |
+
>>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
|
694 |
+
'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
|
695 |
+
|
696 |
+
Support for loops is provided through ``Indexed`` types. With
|
697 |
+
``contract=True`` these expressions will be turned into loops, whereas
|
698 |
+
``contract=False`` will just print the assignment expression that should be
|
699 |
+
looped over:
|
700 |
+
|
701 |
+
>>> from sympy import Eq, IndexedBase, Idx
|
702 |
+
>>> len_y = 5
|
703 |
+
>>> y = IndexedBase('y', shape=(len_y,))
|
704 |
+
>>> t = IndexedBase('t', shape=(len_y,))
|
705 |
+
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
|
706 |
+
>>> i = Idx('i', len_y-1)
|
707 |
+
>>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
|
708 |
+
>>> octave_code(e.rhs, assign_to=e.lhs, contract=False)
|
709 |
+
'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));'
|
710 |
+
"""
|
711 |
+
return OctaveCodePrinter(settings).doprint(expr, assign_to)
|
712 |
+
|
713 |
+
|
714 |
+
def print_octave_code(expr, **settings):
|
715 |
+
"""Prints the Octave (or Matlab) representation of the given expression.
|
716 |
+
|
717 |
+
See `octave_code` for the meaning of the optional arguments.
|
718 |
+
"""
|
719 |
+
print(octave_code(expr, **settings))
|
venv/lib/python3.10/site-packages/sympy/printing/precedence.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""A module providing information about the necessity of brackets"""
|
2 |
+
|
3 |
+
|
4 |
+
# Default precedence values for some basic types
|
5 |
+
PRECEDENCE = {
|
6 |
+
"Lambda": 1,
|
7 |
+
"Xor": 10,
|
8 |
+
"Or": 20,
|
9 |
+
"And": 30,
|
10 |
+
"Relational": 35,
|
11 |
+
"Add": 40,
|
12 |
+
"Mul": 50,
|
13 |
+
"Pow": 60,
|
14 |
+
"Func": 70,
|
15 |
+
"Not": 100,
|
16 |
+
"Atom": 1000,
|
17 |
+
"BitwiseOr": 36,
|
18 |
+
"BitwiseXor": 37,
|
19 |
+
"BitwiseAnd": 38
|
20 |
+
}
|
21 |
+
|
22 |
+
# A dictionary assigning precedence values to certain classes. These values are
|
23 |
+
# treated like they were inherited, so not every single class has to be named
|
24 |
+
# here.
|
25 |
+
# Do not use this with printers other than StrPrinter
|
26 |
+
PRECEDENCE_VALUES = {
|
27 |
+
"Equivalent": PRECEDENCE["Xor"],
|
28 |
+
"Xor": PRECEDENCE["Xor"],
|
29 |
+
"Implies": PRECEDENCE["Xor"],
|
30 |
+
"Or": PRECEDENCE["Or"],
|
31 |
+
"And": PRECEDENCE["And"],
|
32 |
+
"Add": PRECEDENCE["Add"],
|
33 |
+
"Pow": PRECEDENCE["Pow"],
|
34 |
+
"Relational": PRECEDENCE["Relational"],
|
35 |
+
"Sub": PRECEDENCE["Add"],
|
36 |
+
"Not": PRECEDENCE["Not"],
|
37 |
+
"Function" : PRECEDENCE["Func"],
|
38 |
+
"NegativeInfinity": PRECEDENCE["Add"],
|
39 |
+
"MatAdd": PRECEDENCE["Add"],
|
40 |
+
"MatPow": PRECEDENCE["Pow"],
|
41 |
+
"MatrixSolve": PRECEDENCE["Mul"],
|
42 |
+
"Mod": PRECEDENCE["Mul"],
|
43 |
+
"TensAdd": PRECEDENCE["Add"],
|
44 |
+
# As soon as `TensMul` is a subclass of `Mul`, remove this:
|
45 |
+
"TensMul": PRECEDENCE["Mul"],
|
46 |
+
"HadamardProduct": PRECEDENCE["Mul"],
|
47 |
+
"HadamardPower": PRECEDENCE["Pow"],
|
48 |
+
"KroneckerProduct": PRECEDENCE["Mul"],
|
49 |
+
"Equality": PRECEDENCE["Mul"],
|
50 |
+
"Unequality": PRECEDENCE["Mul"],
|
51 |
+
}
|
52 |
+
|
53 |
+
# Sometimes it's not enough to assign a fixed precedence value to a
|
54 |
+
# class. Then a function can be inserted in this dictionary that takes
|
55 |
+
# an instance of this class as argument and returns the appropriate
|
56 |
+
# precedence value.
|
57 |
+
|
58 |
+
# Precedence functions
|
59 |
+
|
60 |
+
|
61 |
+
def precedence_Mul(item):
|
62 |
+
if item.could_extract_minus_sign():
|
63 |
+
return PRECEDENCE["Add"]
|
64 |
+
return PRECEDENCE["Mul"]
|
65 |
+
|
66 |
+
|
67 |
+
def precedence_Rational(item):
|
68 |
+
if item.p < 0:
|
69 |
+
return PRECEDENCE["Add"]
|
70 |
+
return PRECEDENCE["Mul"]
|
71 |
+
|
72 |
+
|
73 |
+
def precedence_Integer(item):
|
74 |
+
if item.p < 0:
|
75 |
+
return PRECEDENCE["Add"]
|
76 |
+
return PRECEDENCE["Atom"]
|
77 |
+
|
78 |
+
|
79 |
+
def precedence_Float(item):
|
80 |
+
if item < 0:
|
81 |
+
return PRECEDENCE["Add"]
|
82 |
+
return PRECEDENCE["Atom"]
|
83 |
+
|
84 |
+
|
85 |
+
def precedence_PolyElement(item):
|
86 |
+
if item.is_generator:
|
87 |
+
return PRECEDENCE["Atom"]
|
88 |
+
elif item.is_ground:
|
89 |
+
return precedence(item.coeff(1))
|
90 |
+
elif item.is_term:
|
91 |
+
return PRECEDENCE["Mul"]
|
92 |
+
else:
|
93 |
+
return PRECEDENCE["Add"]
|
94 |
+
|
95 |
+
|
96 |
+
def precedence_FracElement(item):
|
97 |
+
if item.denom == 1:
|
98 |
+
return precedence_PolyElement(item.numer)
|
99 |
+
else:
|
100 |
+
return PRECEDENCE["Mul"]
|
101 |
+
|
102 |
+
|
103 |
+
def precedence_UnevaluatedExpr(item):
|
104 |
+
return precedence(item.args[0]) - 0.5
|
105 |
+
|
106 |
+
|
107 |
+
PRECEDENCE_FUNCTIONS = {
|
108 |
+
"Integer": precedence_Integer,
|
109 |
+
"Mul": precedence_Mul,
|
110 |
+
"Rational": precedence_Rational,
|
111 |
+
"Float": precedence_Float,
|
112 |
+
"PolyElement": precedence_PolyElement,
|
113 |
+
"FracElement": precedence_FracElement,
|
114 |
+
"UnevaluatedExpr": precedence_UnevaluatedExpr,
|
115 |
+
}
|
116 |
+
|
117 |
+
|
118 |
+
def precedence(item):
|
119 |
+
"""Returns the precedence of a given object.
|
120 |
+
|
121 |
+
This is the precedence for StrPrinter.
|
122 |
+
"""
|
123 |
+
if hasattr(item, "precedence"):
|
124 |
+
return item.precedence
|
125 |
+
try:
|
126 |
+
mro = item.__class__.__mro__
|
127 |
+
except AttributeError:
|
128 |
+
return PRECEDENCE["Atom"]
|
129 |
+
for i in mro:
|
130 |
+
n = i.__name__
|
131 |
+
if n in PRECEDENCE_FUNCTIONS:
|
132 |
+
return PRECEDENCE_FUNCTIONS[n](item)
|
133 |
+
elif n in PRECEDENCE_VALUES:
|
134 |
+
return PRECEDENCE_VALUES[n]
|
135 |
+
return PRECEDENCE["Atom"]
|
136 |
+
|
137 |
+
|
138 |
+
PRECEDENCE_TRADITIONAL = PRECEDENCE.copy()
|
139 |
+
PRECEDENCE_TRADITIONAL['Integral'] = PRECEDENCE["Mul"]
|
140 |
+
PRECEDENCE_TRADITIONAL['Sum'] = PRECEDENCE["Mul"]
|
141 |
+
PRECEDENCE_TRADITIONAL['Product'] = PRECEDENCE["Mul"]
|
142 |
+
PRECEDENCE_TRADITIONAL['Limit'] = PRECEDENCE["Mul"]
|
143 |
+
PRECEDENCE_TRADITIONAL['Derivative'] = PRECEDENCE["Mul"]
|
144 |
+
PRECEDENCE_TRADITIONAL['TensorProduct'] = PRECEDENCE["Mul"]
|
145 |
+
PRECEDENCE_TRADITIONAL['Transpose'] = PRECEDENCE["Pow"]
|
146 |
+
PRECEDENCE_TRADITIONAL['Adjoint'] = PRECEDENCE["Pow"]
|
147 |
+
PRECEDENCE_TRADITIONAL['Dot'] = PRECEDENCE["Mul"] - 1
|
148 |
+
PRECEDENCE_TRADITIONAL['Cross'] = PRECEDENCE["Mul"] - 1
|
149 |
+
PRECEDENCE_TRADITIONAL['Gradient'] = PRECEDENCE["Mul"] - 1
|
150 |
+
PRECEDENCE_TRADITIONAL['Divergence'] = PRECEDENCE["Mul"] - 1
|
151 |
+
PRECEDENCE_TRADITIONAL['Curl'] = PRECEDENCE["Mul"] - 1
|
152 |
+
PRECEDENCE_TRADITIONAL['Laplacian'] = PRECEDENCE["Mul"] - 1
|
153 |
+
PRECEDENCE_TRADITIONAL['Union'] = PRECEDENCE['Xor']
|
154 |
+
PRECEDENCE_TRADITIONAL['Intersection'] = PRECEDENCE['Xor']
|
155 |
+
PRECEDENCE_TRADITIONAL['Complement'] = PRECEDENCE['Xor']
|
156 |
+
PRECEDENCE_TRADITIONAL['SymmetricDifference'] = PRECEDENCE['Xor']
|
157 |
+
PRECEDENCE_TRADITIONAL['ProductSet'] = PRECEDENCE['Xor']
|
158 |
+
|
159 |
+
|
160 |
+
def precedence_traditional(item):
|
161 |
+
"""Returns the precedence of a given object according to the
|
162 |
+
traditional rules of mathematics.
|
163 |
+
|
164 |
+
This is the precedence for the LaTeX and pretty printer.
|
165 |
+
"""
|
166 |
+
# Integral, Sum, Product, Limit have the precedence of Mul in LaTeX,
|
167 |
+
# the precedence of Atom for other printers:
|
168 |
+
from sympy.core.expr import UnevaluatedExpr
|
169 |
+
|
170 |
+
if isinstance(item, UnevaluatedExpr):
|
171 |
+
return precedence_traditional(item.args[0])
|
172 |
+
|
173 |
+
n = item.__class__.__name__
|
174 |
+
if n in PRECEDENCE_TRADITIONAL:
|
175 |
+
return PRECEDENCE_TRADITIONAL[n]
|
176 |
+
|
177 |
+
return precedence(item)
|
venv/lib/python3.10/site-packages/sympy/printing/preview.py
ADDED
@@ -0,0 +1,390 @@
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from os.path import join
|
3 |
+
import shutil
|
4 |
+
import tempfile
|
5 |
+
|
6 |
+
try:
|
7 |
+
from subprocess import STDOUT, CalledProcessError, check_output
|
8 |
+
except ImportError:
|
9 |
+
pass
|
10 |
+
|
11 |
+
from sympy.utilities.decorator import doctest_depends_on
|
12 |
+
from sympy.utilities.misc import debug
|
13 |
+
from .latex import latex
|
14 |
+
|
15 |
+
__doctest_requires__ = {('preview',): ['pyglet']}
|
16 |
+
|
17 |
+
|
18 |
+
def _check_output_no_window(*args, **kwargs):
|
19 |
+
# Avoid showing a cmd.exe window when running this
|
20 |
+
# on Windows
|
21 |
+
if os.name == 'nt':
|
22 |
+
creation_flag = 0x08000000 # CREATE_NO_WINDOW
|
23 |
+
else:
|
24 |
+
creation_flag = 0 # Default value
|
25 |
+
return check_output(*args, creationflags=creation_flag, **kwargs)
|
26 |
+
|
27 |
+
|
28 |
+
def system_default_viewer(fname, fmt):
|
29 |
+
""" Open fname with the default system viewer.
|
30 |
+
|
31 |
+
In practice, it is impossible for python to know when the system viewer is
|
32 |
+
done. For this reason, we ensure the passed file will not be deleted under
|
33 |
+
it, and this function does not attempt to block.
|
34 |
+
"""
|
35 |
+
# copy to a new temporary file that will not be deleted
|
36 |
+
with tempfile.NamedTemporaryFile(prefix='sympy-preview-',
|
37 |
+
suffix=os.path.splitext(fname)[1],
|
38 |
+
delete=False) as temp_f:
|
39 |
+
with open(fname, 'rb') as f:
|
40 |
+
shutil.copyfileobj(f, temp_f)
|
41 |
+
|
42 |
+
import platform
|
43 |
+
if platform.system() == 'Darwin':
|
44 |
+
import subprocess
|
45 |
+
subprocess.call(('open', temp_f.name))
|
46 |
+
elif platform.system() == 'Windows':
|
47 |
+
os.startfile(temp_f.name)
|
48 |
+
else:
|
49 |
+
import subprocess
|
50 |
+
subprocess.call(('xdg-open', temp_f.name))
|
51 |
+
|
52 |
+
|
53 |
+
def pyglet_viewer(fname, fmt):
|
54 |
+
try:
|
55 |
+
from pyglet import window, image, gl
|
56 |
+
from pyglet.window import key
|
57 |
+
from pyglet.image.codecs import ImageDecodeException
|
58 |
+
except ImportError:
|
59 |
+
raise ImportError("pyglet is required for preview.\n visit https://pyglet.org/")
|
60 |
+
|
61 |
+
try:
|
62 |
+
img = image.load(fname)
|
63 |
+
except ImageDecodeException:
|
64 |
+
raise ValueError("pyglet preview does not work for '{}' files.".format(fmt))
|
65 |
+
|
66 |
+
offset = 25
|
67 |
+
|
68 |
+
config = gl.Config(double_buffer=False)
|
69 |
+
win = window.Window(
|
70 |
+
width=img.width + 2*offset,
|
71 |
+
height=img.height + 2*offset,
|
72 |
+
caption="SymPy",
|
73 |
+
resizable=False,
|
74 |
+
config=config
|
75 |
+
)
|
76 |
+
|
77 |
+
win.set_vsync(False)
|
78 |
+
|
79 |
+
try:
|
80 |
+
def on_close():
|
81 |
+
win.has_exit = True
|
82 |
+
|
83 |
+
win.on_close = on_close
|
84 |
+
|
85 |
+
def on_key_press(symbol, modifiers):
|
86 |
+
if symbol in [key.Q, key.ESCAPE]:
|
87 |
+
on_close()
|
88 |
+
|
89 |
+
win.on_key_press = on_key_press
|
90 |
+
|
91 |
+
def on_expose():
|
92 |
+
gl.glClearColor(1.0, 1.0, 1.0, 1.0)
|
93 |
+
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
|
94 |
+
|
95 |
+
img.blit(
|
96 |
+
(win.width - img.width) / 2,
|
97 |
+
(win.height - img.height) / 2
|
98 |
+
)
|
99 |
+
|
100 |
+
win.on_expose = on_expose
|
101 |
+
|
102 |
+
while not win.has_exit:
|
103 |
+
win.dispatch_events()
|
104 |
+
win.flip()
|
105 |
+
except KeyboardInterrupt:
|
106 |
+
pass
|
107 |
+
|
108 |
+
win.close()
|
109 |
+
|
110 |
+
|
111 |
+
def _get_latex_main(expr, *, preamble=None, packages=(), extra_preamble=None,
|
112 |
+
euler=True, fontsize=None, **latex_settings):
|
113 |
+
"""
|
114 |
+
Generate string of a LaTeX document rendering ``expr``.
|
115 |
+
"""
|
116 |
+
if preamble is None:
|
117 |
+
actual_packages = packages + ("amsmath", "amsfonts")
|
118 |
+
if euler:
|
119 |
+
actual_packages += ("euler",)
|
120 |
+
package_includes = "\n" + "\n".join(["\\usepackage{%s}" % p
|
121 |
+
for p in actual_packages])
|
122 |
+
if extra_preamble:
|
123 |
+
package_includes += extra_preamble
|
124 |
+
|
125 |
+
if not fontsize:
|
126 |
+
fontsize = "12pt"
|
127 |
+
elif isinstance(fontsize, int):
|
128 |
+
fontsize = "{}pt".format(fontsize)
|
129 |
+
preamble = r"""\documentclass[varwidth,%s]{standalone}
|
130 |
+
%s
|
131 |
+
|
132 |
+
\begin{document}
|
133 |
+
""" % (fontsize, package_includes)
|
134 |
+
else:
|
135 |
+
if packages or extra_preamble:
|
136 |
+
raise ValueError("The \"packages\" or \"extra_preamble\" keywords"
|
137 |
+
"must not be set if a "
|
138 |
+
"custom LaTeX preamble was specified")
|
139 |
+
|
140 |
+
if isinstance(expr, str):
|
141 |
+
latex_string = expr
|
142 |
+
else:
|
143 |
+
latex_string = ('$\\displaystyle ' +
|
144 |
+
latex(expr, mode='plain', **latex_settings) +
|
145 |
+
'$')
|
146 |
+
|
147 |
+
return preamble + '\n' + latex_string + '\n\n' + r"\end{document}"
|
148 |
+
|
149 |
+
|
150 |
+
@doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',),
|
151 |
+
disable_viewers=('evince', 'gimp', 'superior-dvi-viewer'))
|
152 |
+
def preview(expr, output='png', viewer=None, euler=True, packages=(),
|
153 |
+
filename=None, outputbuffer=None, preamble=None, dvioptions=None,
|
154 |
+
outputTexFile=None, extra_preamble=None, fontsize=None,
|
155 |
+
**latex_settings):
|
156 |
+
r"""
|
157 |
+
View expression or LaTeX markup in PNG, DVI, PostScript or PDF form.
|
158 |
+
|
159 |
+
If the expr argument is an expression, it will be exported to LaTeX and
|
160 |
+
then compiled using the available TeX distribution. The first argument,
|
161 |
+
'expr', may also be a LaTeX string. The function will then run the
|
162 |
+
appropriate viewer for the given output format or use the user defined
|
163 |
+
one. By default png output is generated.
|
164 |
+
|
165 |
+
By default pretty Euler fonts are used for typesetting (they were used to
|
166 |
+
typeset the well known "Concrete Mathematics" book). For that to work, you
|
167 |
+
need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the
|
168 |
+
texlive-fonts-extra package). If you prefer default AMS fonts or your
|
169 |
+
system lacks 'eulervm' LaTeX package then unset the 'euler' keyword
|
170 |
+
argument.
|
171 |
+
|
172 |
+
To use viewer auto-detection, lets say for 'png' output, issue
|
173 |
+
|
174 |
+
>>> from sympy import symbols, preview, Symbol
|
175 |
+
>>> x, y = symbols("x,y")
|
176 |
+
|
177 |
+
>>> preview(x + y, output='png')
|
178 |
+
|
179 |
+
This will choose 'pyglet' by default. To select a different one, do
|
180 |
+
|
181 |
+
>>> preview(x + y, output='png', viewer='gimp')
|
182 |
+
|
183 |
+
The 'png' format is considered special. For all other formats the rules
|
184 |
+
are slightly different. As an example we will take 'dvi' output format. If
|
185 |
+
you would run
|
186 |
+
|
187 |
+
>>> preview(x + y, output='dvi')
|
188 |
+
|
189 |
+
then 'view' will look for available 'dvi' viewers on your system
|
190 |
+
(predefined in the function, so it will try evince, first, then kdvi and
|
191 |
+
xdvi). If nothing is found, it will fall back to using a system file
|
192 |
+
association (via ``open`` and ``xdg-open``). To always use your system file
|
193 |
+
association without searching for the above readers, use
|
194 |
+
|
195 |
+
>>> from sympy.printing.preview import system_default_viewer
|
196 |
+
>>> preview(x + y, output='dvi', viewer=system_default_viewer)
|
197 |
+
|
198 |
+
If this still does not find the viewer you want, it can be set explicitly.
|
199 |
+
|
200 |
+
>>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')
|
201 |
+
|
202 |
+
This will skip auto-detection and will run user specified
|
203 |
+
'superior-dvi-viewer'. If ``view`` fails to find it on your system it will
|
204 |
+
gracefully raise an exception.
|
205 |
+
|
206 |
+
You may also enter ``'file'`` for the viewer argument. Doing so will cause
|
207 |
+
this function to return a file object in read-only mode, if ``filename``
|
208 |
+
is unset. However, if it was set, then 'preview' writes the generated
|
209 |
+
file to this filename instead.
|
210 |
+
|
211 |
+
There is also support for writing to a ``io.BytesIO`` like object, which
|
212 |
+
needs to be passed to the ``outputbuffer`` argument.
|
213 |
+
|
214 |
+
>>> from io import BytesIO
|
215 |
+
>>> obj = BytesIO()
|
216 |
+
>>> preview(x + y, output='png', viewer='BytesIO',
|
217 |
+
... outputbuffer=obj)
|
218 |
+
|
219 |
+
The LaTeX preamble can be customized by setting the 'preamble' keyword
|
220 |
+
argument. This can be used, e.g., to set a different font size, use a
|
221 |
+
custom documentclass or import certain set of LaTeX packages.
|
222 |
+
|
223 |
+
>>> preamble = "\\documentclass[10pt]{article}\n" \
|
224 |
+
... "\\usepackage{amsmath,amsfonts}\\begin{document}"
|
225 |
+
>>> preview(x + y, output='png', preamble=preamble)
|
226 |
+
|
227 |
+
It is also possible to use the standard preamble and provide additional
|
228 |
+
information to the preamble using the ``extra_preamble`` keyword argument.
|
229 |
+
|
230 |
+
>>> from sympy import sin
|
231 |
+
>>> extra_preamble = "\\renewcommand{\\sin}{\\cos}"
|
232 |
+
>>> preview(sin(x), output='png', extra_preamble=extra_preamble)
|
233 |
+
|
234 |
+
If the value of 'output' is different from 'dvi' then command line
|
235 |
+
options can be set ('dvioptions' argument) for the execution of the
|
236 |
+
'dvi'+output conversion tool. These options have to be in the form of a
|
237 |
+
list of strings (see ``subprocess.Popen``).
|
238 |
+
|
239 |
+
Additional keyword args will be passed to the :func:`~sympy.printing.latex.latex` call,
|
240 |
+
e.g., the ``symbol_names`` flag.
|
241 |
+
|
242 |
+
>>> phidd = Symbol('phidd')
|
243 |
+
>>> preview(phidd, symbol_names={phidd: r'\ddot{\varphi}'})
|
244 |
+
|
245 |
+
For post-processing the generated TeX File can be written to a file by
|
246 |
+
passing the desired filename to the 'outputTexFile' keyword
|
247 |
+
argument. To write the TeX code to a file named
|
248 |
+
``"sample.tex"`` and run the default png viewer to display the resulting
|
249 |
+
bitmap, do
|
250 |
+
|
251 |
+
>>> preview(x + y, outputTexFile="sample.tex")
|
252 |
+
|
253 |
+
|
254 |
+
"""
|
255 |
+
# pyglet is the default for png
|
256 |
+
if viewer is None and output == "png":
|
257 |
+
try:
|
258 |
+
import pyglet # noqa: F401
|
259 |
+
except ImportError:
|
260 |
+
pass
|
261 |
+
else:
|
262 |
+
viewer = pyglet_viewer
|
263 |
+
|
264 |
+
# look up a known application
|
265 |
+
if viewer is None:
|
266 |
+
# sorted in order from most pretty to most ugly
|
267 |
+
# very discussable, but indeed 'gv' looks awful :)
|
268 |
+
candidates = {
|
269 |
+
"dvi": [ "evince", "okular", "kdvi", "xdvi" ],
|
270 |
+
"ps": [ "evince", "okular", "gsview", "gv" ],
|
271 |
+
"pdf": [ "evince", "okular", "kpdf", "acroread", "xpdf", "gv" ],
|
272 |
+
}
|
273 |
+
|
274 |
+
for candidate in candidates.get(output, []):
|
275 |
+
path = shutil.which(candidate)
|
276 |
+
if path is not None:
|
277 |
+
viewer = path
|
278 |
+
break
|
279 |
+
|
280 |
+
# otherwise, use the system default for file association
|
281 |
+
if viewer is None:
|
282 |
+
viewer = system_default_viewer
|
283 |
+
|
284 |
+
if viewer == "file":
|
285 |
+
if filename is None:
|
286 |
+
raise ValueError("filename has to be specified if viewer=\"file\"")
|
287 |
+
elif viewer == "BytesIO":
|
288 |
+
if outputbuffer is None:
|
289 |
+
raise ValueError("outputbuffer has to be a BytesIO "
|
290 |
+
"compatible object if viewer=\"BytesIO\"")
|
291 |
+
elif not callable(viewer) and not shutil.which(viewer):
|
292 |
+
raise OSError("Unrecognized viewer: %s" % viewer)
|
293 |
+
|
294 |
+
latex_main = _get_latex_main(expr, preamble=preamble, packages=packages,
|
295 |
+
euler=euler, extra_preamble=extra_preamble,
|
296 |
+
fontsize=fontsize, **latex_settings)
|
297 |
+
|
298 |
+
debug("Latex code:")
|
299 |
+
debug(latex_main)
|
300 |
+
with tempfile.TemporaryDirectory() as workdir:
|
301 |
+
with open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh:
|
302 |
+
fh.write(latex_main)
|
303 |
+
|
304 |
+
if outputTexFile is not None:
|
305 |
+
shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile)
|
306 |
+
|
307 |
+
if not shutil.which('latex'):
|
308 |
+
raise RuntimeError("latex program is not installed")
|
309 |
+
|
310 |
+
try:
|
311 |
+
_check_output_no_window(
|
312 |
+
['latex', '-halt-on-error', '-interaction=nonstopmode',
|
313 |
+
'texput.tex'],
|
314 |
+
cwd=workdir,
|
315 |
+
stderr=STDOUT)
|
316 |
+
except CalledProcessError as e:
|
317 |
+
raise RuntimeError(
|
318 |
+
"'latex' exited abnormally with the following output:\n%s" %
|
319 |
+
e.output)
|
320 |
+
|
321 |
+
src = "texput.%s" % (output)
|
322 |
+
|
323 |
+
if output != "dvi":
|
324 |
+
# in order of preference
|
325 |
+
commandnames = {
|
326 |
+
"ps": ["dvips"],
|
327 |
+
"pdf": ["dvipdfmx", "dvipdfm", "dvipdf"],
|
328 |
+
"png": ["dvipng"],
|
329 |
+
"svg": ["dvisvgm"],
|
330 |
+
}
|
331 |
+
try:
|
332 |
+
cmd_variants = commandnames[output]
|
333 |
+
except KeyError:
|
334 |
+
raise ValueError("Invalid output format: %s" % output) from None
|
335 |
+
|
336 |
+
# find an appropriate command
|
337 |
+
for cmd_variant in cmd_variants:
|
338 |
+
cmd_path = shutil.which(cmd_variant)
|
339 |
+
if cmd_path:
|
340 |
+
cmd = [cmd_path]
|
341 |
+
break
|
342 |
+
else:
|
343 |
+
if len(cmd_variants) > 1:
|
344 |
+
raise RuntimeError("None of %s are installed" % ", ".join(cmd_variants))
|
345 |
+
else:
|
346 |
+
raise RuntimeError("%s is not installed" % cmd_variants[0])
|
347 |
+
|
348 |
+
defaultoptions = {
|
349 |
+
"dvipng": ["-T", "tight", "-z", "9", "--truecolor"],
|
350 |
+
"dvisvgm": ["--no-fonts"],
|
351 |
+
}
|
352 |
+
|
353 |
+
commandend = {
|
354 |
+
"dvips": ["-o", src, "texput.dvi"],
|
355 |
+
"dvipdf": ["texput.dvi", src],
|
356 |
+
"dvipdfm": ["-o", src, "texput.dvi"],
|
357 |
+
"dvipdfmx": ["-o", src, "texput.dvi"],
|
358 |
+
"dvipng": ["-o", src, "texput.dvi"],
|
359 |
+
"dvisvgm": ["-o", src, "texput.dvi"],
|
360 |
+
}
|
361 |
+
|
362 |
+
if dvioptions is not None:
|
363 |
+
cmd.extend(dvioptions)
|
364 |
+
else:
|
365 |
+
cmd.extend(defaultoptions.get(cmd_variant, []))
|
366 |
+
cmd.extend(commandend[cmd_variant])
|
367 |
+
|
368 |
+
try:
|
369 |
+
_check_output_no_window(cmd, cwd=workdir, stderr=STDOUT)
|
370 |
+
except CalledProcessError as e:
|
371 |
+
raise RuntimeError(
|
372 |
+
"'%s' exited abnormally with the following output:\n%s" %
|
373 |
+
(' '.join(cmd), e.output))
|
374 |
+
|
375 |
+
|
376 |
+
if viewer == "file":
|
377 |
+
shutil.move(join(workdir, src), filename)
|
378 |
+
elif viewer == "BytesIO":
|
379 |
+
with open(join(workdir, src), 'rb') as fh:
|
380 |
+
outputbuffer.write(fh.read())
|
381 |
+
elif callable(viewer):
|
382 |
+
viewer(join(workdir, src), fmt=output)
|
383 |
+
else:
|
384 |
+
try:
|
385 |
+
_check_output_no_window(
|
386 |
+
[viewer, src], cwd=workdir, stderr=STDOUT)
|
387 |
+
except CalledProcessError as e:
|
388 |
+
raise RuntimeError(
|
389 |
+
"'%s %s' exited abnormally with the following output:\n%s" %
|
390 |
+
(viewer, src, e.output))
|
venv/lib/python3.10/site-packages/sympy/printing/printer.py
ADDED
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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to a designated Printer who then is responsible to return an
|
5 |
+
adequate representation of that expression.
|
6 |
+
|
7 |
+
**The basic concept is the following:**
|
8 |
+
|
9 |
+
1. Let the object print itself if it knows how.
|
10 |
+
2. Take the best fitting method defined in the printer.
|
11 |
+
3. As fall-back use the emptyPrinter method for the printer.
|
12 |
+
|
13 |
+
Which Method is Responsible for Printing?
|
14 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
15 |
+
|
16 |
+
The whole printing process is started by calling ``.doprint(expr)`` on the printer
|
17 |
+
which you want to use. This method looks for an appropriate method which can
|
18 |
+
print the given expression in the given style that the printer defines.
|
19 |
+
While looking for the method, it follows these steps:
|
20 |
+
|
21 |
+
1. **Let the object print itself if it knows how.**
|
22 |
+
|
23 |
+
The printer looks for a specific method in every object. The name of that method
|
24 |
+
depends on the specific printer and is defined under ``Printer.printmethod``.
|
25 |
+
For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``.
|
26 |
+
Look at the documentation of the printer that you want to use.
|
27 |
+
The name of the method is specified there.
|
28 |
+
|
29 |
+
This was the original way of doing printing in sympy. Every class had
|
30 |
+
its own latex, mathml, str and repr methods, but it turned out that it
|
31 |
+
is hard to produce a high quality printer, if all the methods are spread
|
32 |
+
out that far. Therefore all printing code was combined into the different
|
33 |
+
printers, which works great for built-in SymPy objects, but not that
|
34 |
+
good for user defined classes where it is inconvenient to patch the
|
35 |
+
printers.
|
36 |
+
|
37 |
+
2. **Take the best fitting method defined in the printer.**
|
38 |
+
|
39 |
+
The printer loops through expr classes (class + its bases), and tries
|
40 |
+
to dispatch the work to ``_print_<EXPR_CLASS>``
|
41 |
+
|
42 |
+
e.g., suppose we have the following class hierarchy::
|
43 |
+
|
44 |
+
Basic
|
45 |
+
|
|
46 |
+
Atom
|
47 |
+
|
|
48 |
+
Number
|
49 |
+
|
|
50 |
+
Rational
|
51 |
+
|
52 |
+
then, for ``expr=Rational(...)``, the Printer will try
|
53 |
+
to call printer methods in the order as shown in the figure below::
|
54 |
+
|
55 |
+
p._print(expr)
|
56 |
+
|
|
57 |
+
|-- p._print_Rational(expr)
|
58 |
+
|
|
59 |
+
|-- p._print_Number(expr)
|
60 |
+
|
|
61 |
+
|-- p._print_Atom(expr)
|
62 |
+
|
|
63 |
+
`-- p._print_Basic(expr)
|
64 |
+
|
65 |
+
if ``._print_Rational`` method exists in the printer, then it is called,
|
66 |
+
and the result is returned back. Otherwise, the printer tries to call
|
67 |
+
``._print_Number`` and so on.
|
68 |
+
|
69 |
+
3. **As a fall-back use the emptyPrinter method for the printer.**
|
70 |
+
|
71 |
+
As fall-back ``self.emptyPrinter`` will be called with the expression. If
|
72 |
+
not defined in the Printer subclass this will be the same as ``str(expr)``.
|
73 |
+
|
74 |
+
.. _printer_example:
|
75 |
+
|
76 |
+
Example of Custom Printer
|
77 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^
|
78 |
+
|
79 |
+
In the example below, we have a printer which prints the derivative of a function
|
80 |
+
in a shorter form.
|
81 |
+
|
82 |
+
.. code-block:: python
|
83 |
+
|
84 |
+
from sympy.core.symbol import Symbol
|
85 |
+
from sympy.printing.latex import LatexPrinter, print_latex
|
86 |
+
from sympy.core.function import UndefinedFunction, Function
|
87 |
+
|
88 |
+
|
89 |
+
class MyLatexPrinter(LatexPrinter):
|
90 |
+
\"\"\"Print derivative of a function of symbols in a shorter form.
|
91 |
+
\"\"\"
|
92 |
+
def _print_Derivative(self, expr):
|
93 |
+
function, *vars = expr.args
|
94 |
+
if not isinstance(type(function), UndefinedFunction) or \\
|
95 |
+
not all(isinstance(i, Symbol) for i in vars):
|
96 |
+
return super()._print_Derivative(expr)
|
97 |
+
|
98 |
+
# If you want the printer to work correctly for nested
|
99 |
+
# expressions then use self._print() instead of str() or latex().
|
100 |
+
# See the example of nested modulo below in the custom printing
|
101 |
+
# method section.
|
102 |
+
return "{}_{{{}}}".format(
|
103 |
+
self._print(Symbol(function.func.__name__)),
|
104 |
+
''.join(self._print(i) for i in vars))
|
105 |
+
|
106 |
+
|
107 |
+
def print_my_latex(expr):
|
108 |
+
\"\"\" Most of the printers define their own wrappers for print().
|
109 |
+
These wrappers usually take printer settings. Our printer does not have
|
110 |
+
any settings.
|
111 |
+
\"\"\"
|
112 |
+
print(MyLatexPrinter().doprint(expr))
|
113 |
+
|
114 |
+
|
115 |
+
y = Symbol("y")
|
116 |
+
x = Symbol("x")
|
117 |
+
f = Function("f")
|
118 |
+
expr = f(x, y).diff(x, y)
|
119 |
+
|
120 |
+
# Print the expression using the normal latex printer and our custom
|
121 |
+
# printer.
|
122 |
+
print_latex(expr)
|
123 |
+
print_my_latex(expr)
|
124 |
+
|
125 |
+
The output of the code above is::
|
126 |
+
|
127 |
+
\\frac{\\partial^{2}}{\\partial x\\partial y} f{\\left(x,y \\right)}
|
128 |
+
f_{xy}
|
129 |
+
|
130 |
+
.. _printer_method_example:
|
131 |
+
|
132 |
+
Example of Custom Printing Method
|
133 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
134 |
+
|
135 |
+
In the example below, the latex printing of the modulo operator is modified.
|
136 |
+
This is done by overriding the method ``_latex`` of ``Mod``.
|
137 |
+
|
138 |
+
>>> from sympy import Symbol, Mod, Integer, print_latex
|
139 |
+
|
140 |
+
>>> # Always use printer._print()
|
141 |
+
>>> class ModOp(Mod):
|
142 |
+
... def _latex(self, printer):
|
143 |
+
... a, b = [printer._print(i) for i in self.args]
|
144 |
+
... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
|
145 |
+
|
146 |
+
Comparing the output of our custom operator to the builtin one:
|
147 |
+
|
148 |
+
>>> x = Symbol('x')
|
149 |
+
>>> m = Symbol('m')
|
150 |
+
>>> print_latex(Mod(x, m))
|
151 |
+
x \\bmod m
|
152 |
+
>>> print_latex(ModOp(x, m))
|
153 |
+
\\operatorname{Mod}{\\left(x, m\\right)}
|
154 |
+
|
155 |
+
Common mistakes
|
156 |
+
~~~~~~~~~~~~~~~
|
157 |
+
It's important to always use ``self._print(obj)`` to print subcomponents of
|
158 |
+
an expression when customizing a printer. Mistakes include:
|
159 |
+
|
160 |
+
1. Using ``self.doprint(obj)`` instead:
|
161 |
+
|
162 |
+
>>> # This example does not work properly, as only the outermost call may use
|
163 |
+
>>> # doprint.
|
164 |
+
>>> class ModOpModeWrong(Mod):
|
165 |
+
... def _latex(self, printer):
|
166 |
+
... a, b = [printer.doprint(i) for i in self.args]
|
167 |
+
... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
|
168 |
+
|
169 |
+
This fails when the ``mode`` argument is passed to the printer:
|
170 |
+
|
171 |
+
>>> print_latex(ModOp(x, m), mode='inline') # ok
|
172 |
+
$\\operatorname{Mod}{\\left(x, m\\right)}$
|
173 |
+
>>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad
|
174 |
+
$\\operatorname{Mod}{\\left($x$, $m$\\right)}$
|
175 |
+
|
176 |
+
2. Using ``str(obj)`` instead:
|
177 |
+
|
178 |
+
>>> class ModOpNestedWrong(Mod):
|
179 |
+
... def _latex(self, printer):
|
180 |
+
... a, b = [str(i) for i in self.args]
|
181 |
+
... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
|
182 |
+
|
183 |
+
This fails on nested objects:
|
184 |
+
|
185 |
+
>>> # Nested modulo.
|
186 |
+
>>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok
|
187 |
+
\\operatorname{Mod}{\\left(\\operatorname{Mod}{\\left(x, m\\right)}, 7\\right)}
|
188 |
+
>>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad
|
189 |
+
\\operatorname{Mod}{\\left(ModOpNestedWrong(x, m), 7\\right)}
|
190 |
+
|
191 |
+
3. Using ``LatexPrinter()._print(obj)`` instead.
|
192 |
+
|
193 |
+
>>> from sympy.printing.latex import LatexPrinter
|
194 |
+
>>> class ModOpSettingsWrong(Mod):
|
195 |
+
... def _latex(self, printer):
|
196 |
+
... a, b = [LatexPrinter()._print(i) for i in self.args]
|
197 |
+
... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
|
198 |
+
|
199 |
+
This causes all the settings to be discarded in the subobjects. As an
|
200 |
+
example, the ``full_prec`` setting which shows floats to full precision is
|
201 |
+
ignored:
|
202 |
+
|
203 |
+
>>> from sympy import Float
|
204 |
+
>>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok
|
205 |
+
\\operatorname{Mod}{\\left(1.00000000000000 x, m\\right)}
|
206 |
+
>>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad
|
207 |
+
\\operatorname{Mod}{\\left(1.0 x, m\\right)}
|
208 |
+
|
209 |
+
"""
|
210 |
+
|
211 |
+
from __future__ import annotations
|
212 |
+
import sys
|
213 |
+
from typing import Any, Type
|
214 |
+
import inspect
|
215 |
+
from contextlib import contextmanager
|
216 |
+
from functools import cmp_to_key, update_wrapper
|
217 |
+
|
218 |
+
from sympy.core.add import Add
|
219 |
+
from sympy.core.basic import Basic
|
220 |
+
|
221 |
+
from sympy.core.function import AppliedUndef, UndefinedFunction, Function
|
222 |
+
|
223 |
+
|
224 |
+
|
225 |
+
@contextmanager
|
226 |
+
def printer_context(printer, **kwargs):
|
227 |
+
original = printer._context.copy()
|
228 |
+
try:
|
229 |
+
printer._context.update(kwargs)
|
230 |
+
yield
|
231 |
+
finally:
|
232 |
+
printer._context = original
|
233 |
+
|
234 |
+
|
235 |
+
class Printer:
|
236 |
+
""" Generic printer
|
237 |
+
|
238 |
+
Its job is to provide infrastructure for implementing new printers easily.
|
239 |
+
|
240 |
+
If you want to define your custom Printer or your custom printing method
|
241 |
+
for your custom class then see the example above: printer_example_ .
|
242 |
+
"""
|
243 |
+
|
244 |
+
_global_settings: dict[str, Any] = {}
|
245 |
+
|
246 |
+
_default_settings: dict[str, Any] = {}
|
247 |
+
|
248 |
+
printmethod = None # type: str
|
249 |
+
|
250 |
+
@classmethod
|
251 |
+
def _get_initial_settings(cls):
|
252 |
+
settings = cls._default_settings.copy()
|
253 |
+
for key, val in cls._global_settings.items():
|
254 |
+
if key in cls._default_settings:
|
255 |
+
settings[key] = val
|
256 |
+
return settings
|
257 |
+
|
258 |
+
def __init__(self, settings=None):
|
259 |
+
self._str = str
|
260 |
+
|
261 |
+
self._settings = self._get_initial_settings()
|
262 |
+
self._context = {} # mutable during printing
|
263 |
+
|
264 |
+
if settings is not None:
|
265 |
+
self._settings.update(settings)
|
266 |
+
|
267 |
+
if len(self._settings) > len(self._default_settings):
|
268 |
+
for key in self._settings:
|
269 |
+
if key not in self._default_settings:
|
270 |
+
raise TypeError("Unknown setting '%s'." % key)
|
271 |
+
|
272 |
+
# _print_level is the number of times self._print() was recursively
|
273 |
+
# called. See StrPrinter._print_Float() for an example of usage
|
274 |
+
self._print_level = 0
|
275 |
+
|
276 |
+
@classmethod
|
277 |
+
def set_global_settings(cls, **settings):
|
278 |
+
"""Set system-wide printing settings. """
|
279 |
+
for key, val in settings.items():
|
280 |
+
if val is not None:
|
281 |
+
cls._global_settings[key] = val
|
282 |
+
|
283 |
+
@property
|
284 |
+
def order(self):
|
285 |
+
if 'order' in self._settings:
|
286 |
+
return self._settings['order']
|
287 |
+
else:
|
288 |
+
raise AttributeError("No order defined.")
|
289 |
+
|
290 |
+
def doprint(self, expr):
|
291 |
+
"""Returns printer's representation for expr (as a string)"""
|
292 |
+
return self._str(self._print(expr))
|
293 |
+
|
294 |
+
def _print(self, expr, **kwargs) -> str:
|
295 |
+
"""Internal dispatcher
|
296 |
+
|
297 |
+
Tries the following concepts to print an expression:
|
298 |
+
1. Let the object print itself if it knows how.
|
299 |
+
2. Take the best fitting method defined in the printer.
|
300 |
+
3. As fall-back use the emptyPrinter method for the printer.
|
301 |
+
"""
|
302 |
+
self._print_level += 1
|
303 |
+
try:
|
304 |
+
# If the printer defines a name for a printing method
|
305 |
+
# (Printer.printmethod) and the object knows for itself how it
|
306 |
+
# should be printed, use that method.
|
307 |
+
if self.printmethod and hasattr(expr, self.printmethod):
|
308 |
+
if not (isinstance(expr, type) and issubclass(expr, Basic)):
|
309 |
+
return getattr(expr, self.printmethod)(self, **kwargs)
|
310 |
+
|
311 |
+
# See if the class of expr is known, or if one of its super
|
312 |
+
# classes is known, and use that print function
|
313 |
+
# Exception: ignore the subclasses of Undefined, so that, e.g.,
|
314 |
+
# Function('gamma') does not get dispatched to _print_gamma
|
315 |
+
classes = type(expr).__mro__
|
316 |
+
if AppliedUndef in classes:
|
317 |
+
classes = classes[classes.index(AppliedUndef):]
|
318 |
+
if UndefinedFunction in classes:
|
319 |
+
classes = classes[classes.index(UndefinedFunction):]
|
320 |
+
# Another exception: if someone subclasses a known function, e.g.,
|
321 |
+
# gamma, and changes the name, then ignore _print_gamma
|
322 |
+
if Function in classes:
|
323 |
+
i = classes.index(Function)
|
324 |
+
classes = tuple(c for c in classes[:i] if \
|
325 |
+
c.__name__ == classes[0].__name__ or \
|
326 |
+
c.__name__.endswith("Base")) + classes[i:]
|
327 |
+
for cls in classes:
|
328 |
+
printmethodname = '_print_' + cls.__name__
|
329 |
+
printmethod = getattr(self, printmethodname, None)
|
330 |
+
if printmethod is not None:
|
331 |
+
return printmethod(expr, **kwargs)
|
332 |
+
# Unknown object, fall back to the emptyPrinter.
|
333 |
+
return self.emptyPrinter(expr)
|
334 |
+
finally:
|
335 |
+
self._print_level -= 1
|
336 |
+
|
337 |
+
def emptyPrinter(self, expr):
|
338 |
+
return str(expr)
|
339 |
+
|
340 |
+
def _as_ordered_terms(self, expr, order=None):
|
341 |
+
"""A compatibility function for ordering terms in Add. """
|
342 |
+
order = order or self.order
|
343 |
+
|
344 |
+
if order == 'old':
|
345 |
+
return sorted(Add.make_args(expr), key=cmp_to_key(Basic._compare_pretty))
|
346 |
+
elif order == 'none':
|
347 |
+
return list(expr.args)
|
348 |
+
else:
|
349 |
+
return expr.as_ordered_terms(order=order)
|
350 |
+
|
351 |
+
|
352 |
+
class _PrintFunction:
|
353 |
+
"""
|
354 |
+
Function wrapper to replace ``**settings`` in the signature with printer defaults
|
355 |
+
"""
|
356 |
+
def __init__(self, f, print_cls: Type[Printer]):
|
357 |
+
# find all the non-setting arguments
|
358 |
+
params = list(inspect.signature(f).parameters.values())
|
359 |
+
assert params.pop(-1).kind == inspect.Parameter.VAR_KEYWORD
|
360 |
+
self.__other_params = params
|
361 |
+
|
362 |
+
self.__print_cls = print_cls
|
363 |
+
update_wrapper(self, f)
|
364 |
+
|
365 |
+
def __reduce__(self):
|
366 |
+
# Since this is used as a decorator, it replaces the original function.
|
367 |
+
# The default pickling will try to pickle self.__wrapped__ and fail
|
368 |
+
# because the wrapped function can't be retrieved by name.
|
369 |
+
return self.__wrapped__.__qualname__
|
370 |
+
|
371 |
+
def __call__(self, *args, **kwargs):
|
372 |
+
return self.__wrapped__(*args, **kwargs)
|
373 |
+
|
374 |
+
@property
|
375 |
+
def __signature__(self) -> inspect.Signature:
|
376 |
+
settings = self.__print_cls._get_initial_settings()
|
377 |
+
return inspect.Signature(
|
378 |
+
parameters=self.__other_params + [
|
379 |
+
inspect.Parameter(k, inspect.Parameter.KEYWORD_ONLY, default=v)
|
380 |
+
for k, v in settings.items()
|
381 |
+
],
|
382 |
+
return_annotation=self.__wrapped__.__annotations__.get('return', inspect.Signature.empty) # type:ignore
|
383 |
+
)
|
384 |
+
|
385 |
+
|
386 |
+
def print_function(print_cls):
|
387 |
+
""" A decorator to replace kwargs with the printer settings in __signature__ """
|
388 |
+
def decorator(f):
|
389 |
+
if sys.version_info < (3, 9):
|
390 |
+
# We have to create a subclass so that `help` actually shows the docstring in older Python versions.
|
391 |
+
# IPython and Sphinx do not need this, only a raw Python console.
|
392 |
+
cls = type(f'{f.__qualname__}_PrintFunction', (_PrintFunction,), {"__doc__": f.__doc__})
|
393 |
+
else:
|
394 |
+
cls = _PrintFunction
|
395 |
+
return cls(f, print_cls)
|
396 |
+
return decorator
|
venv/lib/python3.10/site-packages/sympy/printing/pycode.py
ADDED
@@ -0,0 +1,750 @@
|
|
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
|
5 |
+
"""
|
6 |
+
from collections import defaultdict
|
7 |
+
from itertools import chain
|
8 |
+
from sympy.core import S
|
9 |
+
from sympy.core.mod import Mod
|
10 |
+
from .precedence import precedence
|
11 |
+
from .codeprinter import CodePrinter
|
12 |
+
|
13 |
+
_kw = {
|
14 |
+
'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
|
15 |
+
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in',
|
16 |
+
'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
|
17 |
+
'with', 'yield', 'None', 'False', 'nonlocal', 'True'
|
18 |
+
}
|
19 |
+
|
20 |
+
_known_functions = {
|
21 |
+
'Abs': 'abs',
|
22 |
+
'Min': 'min',
|
23 |
+
'Max': 'max',
|
24 |
+
}
|
25 |
+
_known_functions_math = {
|
26 |
+
'acos': 'acos',
|
27 |
+
'acosh': 'acosh',
|
28 |
+
'asin': 'asin',
|
29 |
+
'asinh': 'asinh',
|
30 |
+
'atan': 'atan',
|
31 |
+
'atan2': 'atan2',
|
32 |
+
'atanh': 'atanh',
|
33 |
+
'ceiling': 'ceil',
|
34 |
+
'cos': 'cos',
|
35 |
+
'cosh': 'cosh',
|
36 |
+
'erf': 'erf',
|
37 |
+
'erfc': 'erfc',
|
38 |
+
'exp': 'exp',
|
39 |
+
'expm1': 'expm1',
|
40 |
+
'factorial': 'factorial',
|
41 |
+
'floor': 'floor',
|
42 |
+
'gamma': 'gamma',
|
43 |
+
'hypot': 'hypot',
|
44 |
+
'loggamma': 'lgamma',
|
45 |
+
'log': 'log',
|
46 |
+
'ln': 'log',
|
47 |
+
'log10': 'log10',
|
48 |
+
'log1p': 'log1p',
|
49 |
+
'log2': 'log2',
|
50 |
+
'sin': 'sin',
|
51 |
+
'sinh': 'sinh',
|
52 |
+
'Sqrt': 'sqrt',
|
53 |
+
'tan': 'tan',
|
54 |
+
'tanh': 'tanh'
|
55 |
+
} # Not used from ``math``: [copysign isclose isfinite isinf isnan ldexp frexp pow modf
|
56 |
+
# radians trunc fmod fsum gcd degrees fabs]
|
57 |
+
_known_constants_math = {
|
58 |
+
'Exp1': 'e',
|
59 |
+
'Pi': 'pi',
|
60 |
+
'E': 'e',
|
61 |
+
'Infinity': 'inf',
|
62 |
+
'NaN': 'nan',
|
63 |
+
'ComplexInfinity': 'nan'
|
64 |
+
}
|
65 |
+
|
66 |
+
def _print_known_func(self, expr):
|
67 |
+
known = self.known_functions[expr.__class__.__name__]
|
68 |
+
return '{name}({args})'.format(name=self._module_format(known),
|
69 |
+
args=', '.join((self._print(arg) for arg in expr.args)))
|
70 |
+
|
71 |
+
|
72 |
+
def _print_known_const(self, expr):
|
73 |
+
known = self.known_constants[expr.__class__.__name__]
|
74 |
+
return self._module_format(known)
|
75 |
+
|
76 |
+
|
77 |
+
class AbstractPythonCodePrinter(CodePrinter):
|
78 |
+
printmethod = "_pythoncode"
|
79 |
+
language = "Python"
|
80 |
+
reserved_words = _kw
|
81 |
+
modules = None # initialized to a set in __init__
|
82 |
+
tab = ' '
|
83 |
+
_kf = dict(chain(
|
84 |
+
_known_functions.items(),
|
85 |
+
[(k, 'math.' + v) for k, v in _known_functions_math.items()]
|
86 |
+
))
|
87 |
+
_kc = {k: 'math.'+v for k, v in _known_constants_math.items()}
|
88 |
+
_operators = {'and': 'and', 'or': 'or', 'not': 'not'}
|
89 |
+
_default_settings = dict(
|
90 |
+
CodePrinter._default_settings,
|
91 |
+
user_functions={},
|
92 |
+
precision=17,
|
93 |
+
inline=True,
|
94 |
+
fully_qualified_modules=True,
|
95 |
+
contract=False,
|
96 |
+
standard='python3',
|
97 |
+
)
|
98 |
+
|
99 |
+
def __init__(self, settings=None):
|
100 |
+
super().__init__(settings)
|
101 |
+
|
102 |
+
# Python standard handler
|
103 |
+
std = self._settings['standard']
|
104 |
+
if std is None:
|
105 |
+
import sys
|
106 |
+
std = 'python{}'.format(sys.version_info.major)
|
107 |
+
if std != 'python3':
|
108 |
+
raise ValueError('Only Python 3 is supported.')
|
109 |
+
self.standard = std
|
110 |
+
|
111 |
+
self.module_imports = defaultdict(set)
|
112 |
+
|
113 |
+
# Known functions and constants handler
|
114 |
+
self.known_functions = dict(self._kf, **(settings or {}).get(
|
115 |
+
'user_functions', {}))
|
116 |
+
self.known_constants = dict(self._kc, **(settings or {}).get(
|
117 |
+
'user_constants', {}))
|
118 |
+
|
119 |
+
def _declare_number_const(self, name, value):
|
120 |
+
return "%s = %s" % (name, value)
|
121 |
+
|
122 |
+
def _module_format(self, fqn, register=True):
|
123 |
+
parts = fqn.split('.')
|
124 |
+
if register and len(parts) > 1:
|
125 |
+
self.module_imports['.'.join(parts[:-1])].add(parts[-1])
|
126 |
+
|
127 |
+
if self._settings['fully_qualified_modules']:
|
128 |
+
return fqn
|
129 |
+
else:
|
130 |
+
return fqn.split('(')[0].split('[')[0].split('.')[-1]
|
131 |
+
|
132 |
+
def _format_code(self, lines):
|
133 |
+
return lines
|
134 |
+
|
135 |
+
def _get_statement(self, codestring):
|
136 |
+
return "{}".format(codestring)
|
137 |
+
|
138 |
+
def _get_comment(self, text):
|
139 |
+
return " # {}".format(text)
|
140 |
+
|
141 |
+
def _expand_fold_binary_op(self, op, args):
|
142 |
+
"""
|
143 |
+
This method expands a fold on binary operations.
|
144 |
+
|
145 |
+
``functools.reduce`` is an example of a folded operation.
|
146 |
+
|
147 |
+
For example, the expression
|
148 |
+
|
149 |
+
`A + B + C + D`
|
150 |
+
|
151 |
+
is folded into
|
152 |
+
|
153 |
+
`((A + B) + C) + D`
|
154 |
+
"""
|
155 |
+
if len(args) == 1:
|
156 |
+
return self._print(args[0])
|
157 |
+
else:
|
158 |
+
return "%s(%s, %s)" % (
|
159 |
+
self._module_format(op),
|
160 |
+
self._expand_fold_binary_op(op, args[:-1]),
|
161 |
+
self._print(args[-1]),
|
162 |
+
)
|
163 |
+
|
164 |
+
def _expand_reduce_binary_op(self, op, args):
|
165 |
+
"""
|
166 |
+
This method expands a reductin on binary operations.
|
167 |
+
|
168 |
+
Notice: this is NOT the same as ``functools.reduce``.
|
169 |
+
|
170 |
+
For example, the expression
|
171 |
+
|
172 |
+
`A + B + C + D`
|
173 |
+
|
174 |
+
is reduced into:
|
175 |
+
|
176 |
+
`(A + B) + (C + D)`
|
177 |
+
"""
|
178 |
+
if len(args) == 1:
|
179 |
+
return self._print(args[0])
|
180 |
+
else:
|
181 |
+
N = len(args)
|
182 |
+
Nhalf = N // 2
|
183 |
+
return "%s(%s, %s)" % (
|
184 |
+
self._module_format(op),
|
185 |
+
self._expand_reduce_binary_op(args[:Nhalf]),
|
186 |
+
self._expand_reduce_binary_op(args[Nhalf:]),
|
187 |
+
)
|
188 |
+
|
189 |
+
def _print_NaN(self, expr):
|
190 |
+
return "float('nan')"
|
191 |
+
|
192 |
+
def _print_Infinity(self, expr):
|
193 |
+
return "float('inf')"
|
194 |
+
|
195 |
+
def _print_NegativeInfinity(self, expr):
|
196 |
+
return "float('-inf')"
|
197 |
+
|
198 |
+
def _print_ComplexInfinity(self, expr):
|
199 |
+
return self._print_NaN(expr)
|
200 |
+
|
201 |
+
def _print_Mod(self, expr):
|
202 |
+
PREC = precedence(expr)
|
203 |
+
return ('{} % {}'.format(*(self.parenthesize(x, PREC) for x in expr.args)))
|
204 |
+
|
205 |
+
def _print_Piecewise(self, expr):
|
206 |
+
result = []
|
207 |
+
i = 0
|
208 |
+
for arg in expr.args:
|
209 |
+
e = arg.expr
|
210 |
+
c = arg.cond
|
211 |
+
if i == 0:
|
212 |
+
result.append('(')
|
213 |
+
result.append('(')
|
214 |
+
result.append(self._print(e))
|
215 |
+
result.append(')')
|
216 |
+
result.append(' if ')
|
217 |
+
result.append(self._print(c))
|
218 |
+
result.append(' else ')
|
219 |
+
i += 1
|
220 |
+
result = result[:-1]
|
221 |
+
if result[-1] == 'True':
|
222 |
+
result = result[:-2]
|
223 |
+
result.append(')')
|
224 |
+
else:
|
225 |
+
result.append(' else None)')
|
226 |
+
return ''.join(result)
|
227 |
+
|
228 |
+
def _print_Relational(self, expr):
|
229 |
+
"Relational printer for Equality and Unequality"
|
230 |
+
op = {
|
231 |
+
'==' :'equal',
|
232 |
+
'!=' :'not_equal',
|
233 |
+
'<' :'less',
|
234 |
+
'<=' :'less_equal',
|
235 |
+
'>' :'greater',
|
236 |
+
'>=' :'greater_equal',
|
237 |
+
}
|
238 |
+
if expr.rel_op in op:
|
239 |
+
lhs = self._print(expr.lhs)
|
240 |
+
rhs = self._print(expr.rhs)
|
241 |
+
return '({lhs} {op} {rhs})'.format(op=expr.rel_op, lhs=lhs, rhs=rhs)
|
242 |
+
return super()._print_Relational(expr)
|
243 |
+
|
244 |
+
def _print_ITE(self, expr):
|
245 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
246 |
+
return self._print(expr.rewrite(Piecewise))
|
247 |
+
|
248 |
+
def _print_Sum(self, expr):
|
249 |
+
loops = (
|
250 |
+
'for {i} in range({a}, {b}+1)'.format(
|
251 |
+
i=self._print(i),
|
252 |
+
a=self._print(a),
|
253 |
+
b=self._print(b))
|
254 |
+
for i, a, b in expr.limits)
|
255 |
+
return '(builtins.sum({function} {loops}))'.format(
|
256 |
+
function=self._print(expr.function),
|
257 |
+
loops=' '.join(loops))
|
258 |
+
|
259 |
+
def _print_ImaginaryUnit(self, expr):
|
260 |
+
return '1j'
|
261 |
+
|
262 |
+
def _print_KroneckerDelta(self, expr):
|
263 |
+
a, b = expr.args
|
264 |
+
|
265 |
+
return '(1 if {a} == {b} else 0)'.format(
|
266 |
+
a = self._print(a),
|
267 |
+
b = self._print(b)
|
268 |
+
)
|
269 |
+
|
270 |
+
def _print_MatrixBase(self, expr):
|
271 |
+
name = expr.__class__.__name__
|
272 |
+
func = self.known_functions.get(name, name)
|
273 |
+
return "%s(%s)" % (func, self._print(expr.tolist()))
|
274 |
+
|
275 |
+
_print_SparseRepMatrix = \
|
276 |
+
_print_MutableSparseMatrix = \
|
277 |
+
_print_ImmutableSparseMatrix = \
|
278 |
+
_print_Matrix = \
|
279 |
+
_print_DenseMatrix = \
|
280 |
+
_print_MutableDenseMatrix = \
|
281 |
+
_print_ImmutableMatrix = \
|
282 |
+
_print_ImmutableDenseMatrix = \
|
283 |
+
lambda self, expr: self._print_MatrixBase(expr)
|
284 |
+
|
285 |
+
def _indent_codestring(self, codestring):
|
286 |
+
return '\n'.join([self.tab + line for line in codestring.split('\n')])
|
287 |
+
|
288 |
+
def _print_FunctionDefinition(self, fd):
|
289 |
+
body = '\n'.join((self._print(arg) for arg in fd.body))
|
290 |
+
return "def {name}({parameters}):\n{body}".format(
|
291 |
+
name=self._print(fd.name),
|
292 |
+
parameters=', '.join([self._print(var.symbol) for var in fd.parameters]),
|
293 |
+
body=self._indent_codestring(body)
|
294 |
+
)
|
295 |
+
|
296 |
+
def _print_While(self, whl):
|
297 |
+
body = '\n'.join((self._print(arg) for arg in whl.body))
|
298 |
+
return "while {cond}:\n{body}".format(
|
299 |
+
cond=self._print(whl.condition),
|
300 |
+
body=self._indent_codestring(body)
|
301 |
+
)
|
302 |
+
|
303 |
+
def _print_Declaration(self, decl):
|
304 |
+
return '%s = %s' % (
|
305 |
+
self._print(decl.variable.symbol),
|
306 |
+
self._print(decl.variable.value)
|
307 |
+
)
|
308 |
+
|
309 |
+
def _print_Return(self, ret):
|
310 |
+
arg, = ret.args
|
311 |
+
return 'return %s' % self._print(arg)
|
312 |
+
|
313 |
+
def _print_Print(self, prnt):
|
314 |
+
print_args = ', '.join((self._print(arg) for arg in prnt.print_args))
|
315 |
+
if prnt.format_string != None: # Must be '!= None', cannot be 'is not None'
|
316 |
+
print_args = '{} % ({})'.format(
|
317 |
+
self._print(prnt.format_string), print_args)
|
318 |
+
if prnt.file != None: # Must be '!= None', cannot be 'is not None'
|
319 |
+
print_args += ', file=%s' % self._print(prnt.file)
|
320 |
+
|
321 |
+
return 'print(%s)' % print_args
|
322 |
+
|
323 |
+
def _print_Stream(self, strm):
|
324 |
+
if str(strm.name) == 'stdout':
|
325 |
+
return self._module_format('sys.stdout')
|
326 |
+
elif str(strm.name) == 'stderr':
|
327 |
+
return self._module_format('sys.stderr')
|
328 |
+
else:
|
329 |
+
return self._print(strm.name)
|
330 |
+
|
331 |
+
def _print_NoneToken(self, arg):
|
332 |
+
return 'None'
|
333 |
+
|
334 |
+
def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'):
|
335 |
+
"""Printing helper function for ``Pow``
|
336 |
+
|
337 |
+
Notes
|
338 |
+
=====
|
339 |
+
|
340 |
+
This preprocesses the ``sqrt`` as math formatter and prints division
|
341 |
+
|
342 |
+
Examples
|
343 |
+
========
|
344 |
+
|
345 |
+
>>> from sympy import sqrt
|
346 |
+
>>> from sympy.printing.pycode import PythonCodePrinter
|
347 |
+
>>> from sympy.abc import x
|
348 |
+
|
349 |
+
Python code printer automatically looks up ``math.sqrt``.
|
350 |
+
|
351 |
+
>>> printer = PythonCodePrinter()
|
352 |
+
>>> printer._hprint_Pow(sqrt(x), rational=True)
|
353 |
+
'x**(1/2)'
|
354 |
+
>>> printer._hprint_Pow(sqrt(x), rational=False)
|
355 |
+
'math.sqrt(x)'
|
356 |
+
>>> printer._hprint_Pow(1/sqrt(x), rational=True)
|
357 |
+
'x**(-1/2)'
|
358 |
+
>>> printer._hprint_Pow(1/sqrt(x), rational=False)
|
359 |
+
'1/math.sqrt(x)'
|
360 |
+
>>> printer._hprint_Pow(1/x, rational=False)
|
361 |
+
'1/x'
|
362 |
+
>>> printer._hprint_Pow(1/x, rational=True)
|
363 |
+
'x**(-1)'
|
364 |
+
|
365 |
+
Using sqrt from numpy or mpmath
|
366 |
+
|
367 |
+
>>> printer._hprint_Pow(sqrt(x), sqrt='numpy.sqrt')
|
368 |
+
'numpy.sqrt(x)'
|
369 |
+
>>> printer._hprint_Pow(sqrt(x), sqrt='mpmath.sqrt')
|
370 |
+
'mpmath.sqrt(x)'
|
371 |
+
|
372 |
+
See Also
|
373 |
+
========
|
374 |
+
|
375 |
+
sympy.printing.str.StrPrinter._print_Pow
|
376 |
+
"""
|
377 |
+
PREC = precedence(expr)
|
378 |
+
|
379 |
+
if expr.exp == S.Half and not rational:
|
380 |
+
func = self._module_format(sqrt)
|
381 |
+
arg = self._print(expr.base)
|
382 |
+
return '{func}({arg})'.format(func=func, arg=arg)
|
383 |
+
|
384 |
+
if expr.is_commutative and not rational:
|
385 |
+
if -expr.exp is S.Half:
|
386 |
+
func = self._module_format(sqrt)
|
387 |
+
num = self._print(S.One)
|
388 |
+
arg = self._print(expr.base)
|
389 |
+
return f"{num}/{func}({arg})"
|
390 |
+
if expr.exp is S.NegativeOne:
|
391 |
+
num = self._print(S.One)
|
392 |
+
arg = self.parenthesize(expr.base, PREC, strict=False)
|
393 |
+
return f"{num}/{arg}"
|
394 |
+
|
395 |
+
|
396 |
+
base_str = self.parenthesize(expr.base, PREC, strict=False)
|
397 |
+
exp_str = self.parenthesize(expr.exp, PREC, strict=False)
|
398 |
+
return "{}**{}".format(base_str, exp_str)
|
399 |
+
|
400 |
+
|
401 |
+
class ArrayPrinter:
|
402 |
+
|
403 |
+
def _arrayify(self, indexed):
|
404 |
+
from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
|
405 |
+
try:
|
406 |
+
return convert_indexed_to_array(indexed)
|
407 |
+
except Exception:
|
408 |
+
return indexed
|
409 |
+
|
410 |
+
def _get_einsum_string(self, subranks, contraction_indices):
|
411 |
+
letters = self._get_letter_generator_for_einsum()
|
412 |
+
contraction_string = ""
|
413 |
+
counter = 0
|
414 |
+
d = {j: min(i) for i in contraction_indices for j in i}
|
415 |
+
indices = []
|
416 |
+
for rank_arg in subranks:
|
417 |
+
lindices = []
|
418 |
+
for i in range(rank_arg):
|
419 |
+
if counter in d:
|
420 |
+
lindices.append(d[counter])
|
421 |
+
else:
|
422 |
+
lindices.append(counter)
|
423 |
+
counter += 1
|
424 |
+
indices.append(lindices)
|
425 |
+
mapping = {}
|
426 |
+
letters_free = []
|
427 |
+
letters_dum = []
|
428 |
+
for i in indices:
|
429 |
+
for j in i:
|
430 |
+
if j not in mapping:
|
431 |
+
l = next(letters)
|
432 |
+
mapping[j] = l
|
433 |
+
else:
|
434 |
+
l = mapping[j]
|
435 |
+
contraction_string += l
|
436 |
+
if j in d:
|
437 |
+
if l not in letters_dum:
|
438 |
+
letters_dum.append(l)
|
439 |
+
else:
|
440 |
+
letters_free.append(l)
|
441 |
+
contraction_string += ","
|
442 |
+
contraction_string = contraction_string[:-1]
|
443 |
+
return contraction_string, letters_free, letters_dum
|
444 |
+
|
445 |
+
def _get_letter_generator_for_einsum(self):
|
446 |
+
for i in range(97, 123):
|
447 |
+
yield chr(i)
|
448 |
+
for i in range(65, 91):
|
449 |
+
yield chr(i)
|
450 |
+
raise ValueError("out of letters")
|
451 |
+
|
452 |
+
def _print_ArrayTensorProduct(self, expr):
|
453 |
+
letters = self._get_letter_generator_for_einsum()
|
454 |
+
contraction_string = ",".join(["".join([next(letters) for j in range(i)]) for i in expr.subranks])
|
455 |
+
return '%s("%s", %s)' % (
|
456 |
+
self._module_format(self._module + "." + self._einsum),
|
457 |
+
contraction_string,
|
458 |
+
", ".join([self._print(arg) for arg in expr.args])
|
459 |
+
)
|
460 |
+
|
461 |
+
def _print_ArrayContraction(self, expr):
|
462 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
|
463 |
+
base = expr.expr
|
464 |
+
contraction_indices = expr.contraction_indices
|
465 |
+
|
466 |
+
if isinstance(base, ArrayTensorProduct):
|
467 |
+
elems = ",".join(["%s" % (self._print(arg)) for arg in base.args])
|
468 |
+
ranks = base.subranks
|
469 |
+
else:
|
470 |
+
elems = self._print(base)
|
471 |
+
ranks = [len(base.shape)]
|
472 |
+
|
473 |
+
contraction_string, letters_free, letters_dum = self._get_einsum_string(ranks, contraction_indices)
|
474 |
+
|
475 |
+
if not contraction_indices:
|
476 |
+
return self._print(base)
|
477 |
+
if isinstance(base, ArrayTensorProduct):
|
478 |
+
elems = ",".join(["%s" % (self._print(arg)) for arg in base.args])
|
479 |
+
else:
|
480 |
+
elems = self._print(base)
|
481 |
+
return "%s(\"%s\", %s)" % (
|
482 |
+
self._module_format(self._module + "." + self._einsum),
|
483 |
+
"{}->{}".format(contraction_string, "".join(sorted(letters_free))),
|
484 |
+
elems,
|
485 |
+
)
|
486 |
+
|
487 |
+
def _print_ArrayDiagonal(self, expr):
|
488 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
|
489 |
+
diagonal_indices = list(expr.diagonal_indices)
|
490 |
+
if isinstance(expr.expr, ArrayTensorProduct):
|
491 |
+
subranks = expr.expr.subranks
|
492 |
+
elems = expr.expr.args
|
493 |
+
else:
|
494 |
+
subranks = expr.subranks
|
495 |
+
elems = [expr.expr]
|
496 |
+
diagonal_string, letters_free, letters_dum = self._get_einsum_string(subranks, diagonal_indices)
|
497 |
+
elems = [self._print(i) for i in elems]
|
498 |
+
return '%s("%s", %s)' % (
|
499 |
+
self._module_format(self._module + "." + self._einsum),
|
500 |
+
"{}->{}".format(diagonal_string, "".join(letters_free+letters_dum)),
|
501 |
+
", ".join(elems)
|
502 |
+
)
|
503 |
+
|
504 |
+
def _print_PermuteDims(self, expr):
|
505 |
+
return "%s(%s, %s)" % (
|
506 |
+
self._module_format(self._module + "." + self._transpose),
|
507 |
+
self._print(expr.expr),
|
508 |
+
self._print(expr.permutation.array_form),
|
509 |
+
)
|
510 |
+
|
511 |
+
def _print_ArrayAdd(self, expr):
|
512 |
+
return self._expand_fold_binary_op(self._module + "." + self._add, expr.args)
|
513 |
+
|
514 |
+
def _print_OneArray(self, expr):
|
515 |
+
return "%s((%s,))" % (
|
516 |
+
self._module_format(self._module+ "." + self._ones),
|
517 |
+
','.join(map(self._print,expr.args))
|
518 |
+
)
|
519 |
+
|
520 |
+
def _print_ZeroArray(self, expr):
|
521 |
+
return "%s((%s,))" % (
|
522 |
+
self._module_format(self._module+ "." + self._zeros),
|
523 |
+
','.join(map(self._print,expr.args))
|
524 |
+
)
|
525 |
+
|
526 |
+
def _print_Assignment(self, expr):
|
527 |
+
#XXX: maybe this needs to happen at a higher level e.g. at _print or
|
528 |
+
#doprint?
|
529 |
+
lhs = self._print(self._arrayify(expr.lhs))
|
530 |
+
rhs = self._print(self._arrayify(expr.rhs))
|
531 |
+
return "%s = %s" % ( lhs, rhs )
|
532 |
+
|
533 |
+
def _print_IndexedBase(self, expr):
|
534 |
+
return self._print_ArraySymbol(expr)
|
535 |
+
|
536 |
+
|
537 |
+
class PythonCodePrinter(AbstractPythonCodePrinter):
|
538 |
+
|
539 |
+
def _print_sign(self, e):
|
540 |
+
return '(0.0 if {e} == 0 else {f}(1, {e}))'.format(
|
541 |
+
f=self._module_format('math.copysign'), e=self._print(e.args[0]))
|
542 |
+
|
543 |
+
def _print_Not(self, expr):
|
544 |
+
PREC = precedence(expr)
|
545 |
+
return self._operators['not'] + self.parenthesize(expr.args[0], PREC)
|
546 |
+
|
547 |
+
def _print_Indexed(self, expr):
|
548 |
+
base = expr.args[0]
|
549 |
+
index = expr.args[1:]
|
550 |
+
return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index]))
|
551 |
+
|
552 |
+
def _print_Pow(self, expr, rational=False):
|
553 |
+
return self._hprint_Pow(expr, rational=rational)
|
554 |
+
|
555 |
+
def _print_Rational(self, expr):
|
556 |
+
return '{}/{}'.format(expr.p, expr.q)
|
557 |
+
|
558 |
+
def _print_Half(self, expr):
|
559 |
+
return self._print_Rational(expr)
|
560 |
+
|
561 |
+
def _print_frac(self, expr):
|
562 |
+
return self._print_Mod(Mod(expr.args[0], 1))
|
563 |
+
|
564 |
+
def _print_Symbol(self, expr):
|
565 |
+
|
566 |
+
name = super()._print_Symbol(expr)
|
567 |
+
|
568 |
+
if name in self.reserved_words:
|
569 |
+
if self._settings['error_on_reserved']:
|
570 |
+
msg = ('This expression includes the symbol "{}" which is a '
|
571 |
+
'reserved keyword in this language.')
|
572 |
+
raise ValueError(msg.format(name))
|
573 |
+
return name + self._settings['reserved_word_suffix']
|
574 |
+
elif '{' in name: # Remove curly braces from subscripted variables
|
575 |
+
return name.replace('{', '').replace('}', '')
|
576 |
+
else:
|
577 |
+
return name
|
578 |
+
|
579 |
+
_print_lowergamma = CodePrinter._print_not_supported
|
580 |
+
_print_uppergamma = CodePrinter._print_not_supported
|
581 |
+
_print_fresnelc = CodePrinter._print_not_supported
|
582 |
+
_print_fresnels = CodePrinter._print_not_supported
|
583 |
+
|
584 |
+
|
585 |
+
for k in PythonCodePrinter._kf:
|
586 |
+
setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func)
|
587 |
+
|
588 |
+
for k in _known_constants_math:
|
589 |
+
setattr(PythonCodePrinter, '_print_%s' % k, _print_known_const)
|
590 |
+
|
591 |
+
|
592 |
+
def pycode(expr, **settings):
|
593 |
+
""" Converts an expr to a string of Python code
|
594 |
+
|
595 |
+
Parameters
|
596 |
+
==========
|
597 |
+
|
598 |
+
expr : Expr
|
599 |
+
A SymPy expression.
|
600 |
+
fully_qualified_modules : bool
|
601 |
+
Whether or not to write out full module names of functions
|
602 |
+
(``math.sin`` vs. ``sin``). default: ``True``.
|
603 |
+
standard : str or None, optional
|
604 |
+
Only 'python3' (default) is supported.
|
605 |
+
This parameter may be removed in the future.
|
606 |
+
|
607 |
+
Examples
|
608 |
+
========
|
609 |
+
|
610 |
+
>>> from sympy import pycode, tan, Symbol
|
611 |
+
>>> pycode(tan(Symbol('x')) + 1)
|
612 |
+
'math.tan(x) + 1'
|
613 |
+
|
614 |
+
"""
|
615 |
+
return PythonCodePrinter(settings).doprint(expr)
|
616 |
+
|
617 |
+
|
618 |
+
_not_in_mpmath = 'log1p log2'.split()
|
619 |
+
_in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath]
|
620 |
+
_known_functions_mpmath = dict(_in_mpmath, **{
|
621 |
+
'beta': 'beta',
|
622 |
+
'frac': 'frac',
|
623 |
+
'fresnelc': 'fresnelc',
|
624 |
+
'fresnels': 'fresnels',
|
625 |
+
'sign': 'sign',
|
626 |
+
'loggamma': 'loggamma',
|
627 |
+
'hyper': 'hyper',
|
628 |
+
'meijerg': 'meijerg',
|
629 |
+
'besselj': 'besselj',
|
630 |
+
'bessely': 'bessely',
|
631 |
+
'besseli': 'besseli',
|
632 |
+
'besselk': 'besselk',
|
633 |
+
})
|
634 |
+
_known_constants_mpmath = {
|
635 |
+
'Exp1': 'e',
|
636 |
+
'Pi': 'pi',
|
637 |
+
'GoldenRatio': 'phi',
|
638 |
+
'EulerGamma': 'euler',
|
639 |
+
'Catalan': 'catalan',
|
640 |
+
'NaN': 'nan',
|
641 |
+
'Infinity': 'inf',
|
642 |
+
'NegativeInfinity': 'ninf'
|
643 |
+
}
|
644 |
+
|
645 |
+
|
646 |
+
def _unpack_integral_limits(integral_expr):
|
647 |
+
""" helper function for _print_Integral that
|
648 |
+
- accepts an Integral expression
|
649 |
+
- returns a tuple of
|
650 |
+
- a list variables of integration
|
651 |
+
- a list of tuples of the upper and lower limits of integration
|
652 |
+
"""
|
653 |
+
integration_vars = []
|
654 |
+
limits = []
|
655 |
+
for integration_range in integral_expr.limits:
|
656 |
+
if len(integration_range) == 3:
|
657 |
+
integration_var, lower_limit, upper_limit = integration_range
|
658 |
+
else:
|
659 |
+
raise NotImplementedError("Only definite integrals are supported")
|
660 |
+
integration_vars.append(integration_var)
|
661 |
+
limits.append((lower_limit, upper_limit))
|
662 |
+
return integration_vars, limits
|
663 |
+
|
664 |
+
|
665 |
+
class MpmathPrinter(PythonCodePrinter):
|
666 |
+
"""
|
667 |
+
Lambda printer for mpmath which maintains precision for floats
|
668 |
+
"""
|
669 |
+
printmethod = "_mpmathcode"
|
670 |
+
|
671 |
+
language = "Python with mpmath"
|
672 |
+
|
673 |
+
_kf = dict(chain(
|
674 |
+
_known_functions.items(),
|
675 |
+
[(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()]
|
676 |
+
))
|
677 |
+
_kc = {k: 'mpmath.'+v for k, v in _known_constants_mpmath.items()}
|
678 |
+
|
679 |
+
def _print_Float(self, e):
|
680 |
+
# XXX: This does not handle setting mpmath.mp.dps. It is assumed that
|
681 |
+
# the caller of the lambdified function will have set it to sufficient
|
682 |
+
# precision to match the Floats in the expression.
|
683 |
+
|
684 |
+
# Remove 'mpz' if gmpy is installed.
|
685 |
+
args = str(tuple(map(int, e._mpf_)))
|
686 |
+
return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args)
|
687 |
+
|
688 |
+
|
689 |
+
def _print_Rational(self, e):
|
690 |
+
return "{func}({p})/{func}({q})".format(
|
691 |
+
func=self._module_format('mpmath.mpf'),
|
692 |
+
q=self._print(e.q),
|
693 |
+
p=self._print(e.p)
|
694 |
+
)
|
695 |
+
|
696 |
+
def _print_Half(self, e):
|
697 |
+
return self._print_Rational(e)
|
698 |
+
|
699 |
+
def _print_uppergamma(self, e):
|
700 |
+
return "{}({}, {}, {})".format(
|
701 |
+
self._module_format('mpmath.gammainc'),
|
702 |
+
self._print(e.args[0]),
|
703 |
+
self._print(e.args[1]),
|
704 |
+
self._module_format('mpmath.inf'))
|
705 |
+
|
706 |
+
def _print_lowergamma(self, e):
|
707 |
+
return "{}({}, 0, {})".format(
|
708 |
+
self._module_format('mpmath.gammainc'),
|
709 |
+
self._print(e.args[0]),
|
710 |
+
self._print(e.args[1]))
|
711 |
+
|
712 |
+
def _print_log2(self, e):
|
713 |
+
return '{0}({1})/{0}(2)'.format(
|
714 |
+
self._module_format('mpmath.log'), self._print(e.args[0]))
|
715 |
+
|
716 |
+
def _print_log1p(self, e):
|
717 |
+
return '{}({})'.format(
|
718 |
+
self._module_format('mpmath.log1p'), self._print(e.args[0]))
|
719 |
+
|
720 |
+
def _print_Pow(self, expr, rational=False):
|
721 |
+
return self._hprint_Pow(expr, rational=rational, sqrt='mpmath.sqrt')
|
722 |
+
|
723 |
+
def _print_Integral(self, e):
|
724 |
+
integration_vars, limits = _unpack_integral_limits(e)
|
725 |
+
|
726 |
+
return "{}(lambda {}: {}, {})".format(
|
727 |
+
self._module_format("mpmath.quad"),
|
728 |
+
", ".join(map(self._print, integration_vars)),
|
729 |
+
self._print(e.args[0]),
|
730 |
+
", ".join("(%s, %s)" % tuple(map(self._print, l)) for l in limits))
|
731 |
+
|
732 |
+
|
733 |
+
for k in MpmathPrinter._kf:
|
734 |
+
setattr(MpmathPrinter, '_print_%s' % k, _print_known_func)
|
735 |
+
|
736 |
+
for k in _known_constants_mpmath:
|
737 |
+
setattr(MpmathPrinter, '_print_%s' % k, _print_known_const)
|
738 |
+
|
739 |
+
|
740 |
+
class SymPyPrinter(AbstractPythonCodePrinter):
|
741 |
+
|
742 |
+
language = "Python with SymPy"
|
743 |
+
|
744 |
+
def _print_Function(self, expr):
|
745 |
+
mod = expr.func.__module__ or ''
|
746 |
+
return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__),
|
747 |
+
', '.join((self._print(arg) for arg in expr.args)))
|
748 |
+
|
749 |
+
def _print_Pow(self, expr, rational=False):
|
750 |
+
return self._hprint_Pow(expr, rational=rational, sqrt='sympy.sqrt')
|
venv/lib/python3.10/site-packages/sympy/printing/python.py
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import keyword as kw
|
2 |
+
import sympy
|
3 |
+
from .repr import ReprPrinter
|
4 |
+
from .str import StrPrinter
|
5 |
+
|
6 |
+
# A list of classes that should be printed using StrPrinter
|
7 |
+
STRPRINT = ("Add", "Infinity", "Integer", "Mul", "NegativeInfinity",
|
8 |
+
"Pow", "Zero")
|
9 |
+
|
10 |
+
|
11 |
+
class PythonPrinter(ReprPrinter, StrPrinter):
|
12 |
+
"""A printer which converts an expression into its Python interpretation."""
|
13 |
+
|
14 |
+
def __init__(self, settings=None):
|
15 |
+
super().__init__(settings)
|
16 |
+
self.symbols = []
|
17 |
+
self.functions = []
|
18 |
+
|
19 |
+
# Create print methods for classes that should use StrPrinter instead
|
20 |
+
# of ReprPrinter.
|
21 |
+
for name in STRPRINT:
|
22 |
+
f_name = "_print_%s" % name
|
23 |
+
f = getattr(StrPrinter, f_name)
|
24 |
+
setattr(PythonPrinter, f_name, f)
|
25 |
+
|
26 |
+
def _print_Function(self, expr):
|
27 |
+
func = expr.func.__name__
|
28 |
+
if not hasattr(sympy, func) and func not in self.functions:
|
29 |
+
self.functions.append(func)
|
30 |
+
return StrPrinter._print_Function(self, expr)
|
31 |
+
|
32 |
+
# procedure (!) for defining symbols which have be defined in print_python()
|
33 |
+
def _print_Symbol(self, expr):
|
34 |
+
symbol = self._str(expr)
|
35 |
+
if symbol not in self.symbols:
|
36 |
+
self.symbols.append(symbol)
|
37 |
+
return StrPrinter._print_Symbol(self, expr)
|
38 |
+
|
39 |
+
def _print_module(self, expr):
|
40 |
+
raise ValueError('Modules in the expression are unacceptable')
|
41 |
+
|
42 |
+
|
43 |
+
def python(expr, **settings):
|
44 |
+
"""Return Python interpretation of passed expression
|
45 |
+
(can be passed to the exec() function without any modifications)"""
|
46 |
+
|
47 |
+
printer = PythonPrinter(settings)
|
48 |
+
exprp = printer.doprint(expr)
|
49 |
+
|
50 |
+
result = ''
|
51 |
+
# Returning found symbols and functions
|
52 |
+
renamings = {}
|
53 |
+
for symbolname in printer.symbols:
|
54 |
+
# Remove curly braces from subscripted variables
|
55 |
+
if '{' in symbolname:
|
56 |
+
newsymbolname = symbolname.replace('{', '').replace('}', '')
|
57 |
+
renamings[sympy.Symbol(symbolname)] = newsymbolname
|
58 |
+
else:
|
59 |
+
newsymbolname = symbolname
|
60 |
+
|
61 |
+
# Escape symbol names that are reserved Python keywords
|
62 |
+
if kw.iskeyword(newsymbolname):
|
63 |
+
while True:
|
64 |
+
newsymbolname += "_"
|
65 |
+
if (newsymbolname not in printer.symbols and
|
66 |
+
newsymbolname not in printer.functions):
|
67 |
+
renamings[sympy.Symbol(
|
68 |
+
symbolname)] = sympy.Symbol(newsymbolname)
|
69 |
+
break
|
70 |
+
result += newsymbolname + ' = Symbol(\'' + symbolname + '\')\n'
|
71 |
+
|
72 |
+
for functionname in printer.functions:
|
73 |
+
newfunctionname = functionname
|
74 |
+
# Escape function names that are reserved Python keywords
|
75 |
+
if kw.iskeyword(newfunctionname):
|
76 |
+
while True:
|
77 |
+
newfunctionname += "_"
|
78 |
+
if (newfunctionname not in printer.symbols and
|
79 |
+
newfunctionname not in printer.functions):
|
80 |
+
renamings[sympy.Function(
|
81 |
+
functionname)] = sympy.Function(newfunctionname)
|
82 |
+
break
|
83 |
+
result += newfunctionname + ' = Function(\'' + functionname + '\')\n'
|
84 |
+
|
85 |
+
if renamings:
|
86 |
+
exprp = expr.subs(renamings)
|
87 |
+
result += 'e = ' + printer._str(exprp)
|
88 |
+
return result
|
89 |
+
|
90 |
+
|
91 |
+
def print_python(expr, **settings):
|
92 |
+
"""Print output of python() function"""
|
93 |
+
print(python(expr, **settings))
|
venv/lib/python3.10/site-packages/sympy/printing/rcode.py
ADDED
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
R code printer
|
3 |
+
|
4 |
+
The RCodePrinter converts single SymPy expressions into single R expressions,
|
5 |
+
using the functions defined in math.h where possible.
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
"""
|
10 |
+
|
11 |
+
from __future__ import annotations
|
12 |
+
from typing import Any
|
13 |
+
|
14 |
+
from sympy.core.numbers import equal_valued
|
15 |
+
from sympy.printing.codeprinter import CodePrinter
|
16 |
+
from sympy.printing.precedence import precedence, PRECEDENCE
|
17 |
+
from sympy.sets.fancysets import Range
|
18 |
+
|
19 |
+
# dictionary mapping SymPy function to (argument_conditions, C_function).
|
20 |
+
# Used in RCodePrinter._print_Function(self)
|
21 |
+
known_functions = {
|
22 |
+
#"Abs": [(lambda x: not x.is_integer, "fabs")],
|
23 |
+
"Abs": "abs",
|
24 |
+
"sin": "sin",
|
25 |
+
"cos": "cos",
|
26 |
+
"tan": "tan",
|
27 |
+
"asin": "asin",
|
28 |
+
"acos": "acos",
|
29 |
+
"atan": "atan",
|
30 |
+
"atan2": "atan2",
|
31 |
+
"exp": "exp",
|
32 |
+
"log": "log",
|
33 |
+
"erf": "erf",
|
34 |
+
"sinh": "sinh",
|
35 |
+
"cosh": "cosh",
|
36 |
+
"tanh": "tanh",
|
37 |
+
"asinh": "asinh",
|
38 |
+
"acosh": "acosh",
|
39 |
+
"atanh": "atanh",
|
40 |
+
"floor": "floor",
|
41 |
+
"ceiling": "ceiling",
|
42 |
+
"sign": "sign",
|
43 |
+
"Max": "max",
|
44 |
+
"Min": "min",
|
45 |
+
"factorial": "factorial",
|
46 |
+
"gamma": "gamma",
|
47 |
+
"digamma": "digamma",
|
48 |
+
"trigamma": "trigamma",
|
49 |
+
"beta": "beta",
|
50 |
+
"sqrt": "sqrt", # To enable automatic rewrite
|
51 |
+
}
|
52 |
+
|
53 |
+
# These are the core reserved words in the R language. Taken from:
|
54 |
+
# https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Reserved-words
|
55 |
+
|
56 |
+
reserved_words = ['if',
|
57 |
+
'else',
|
58 |
+
'repeat',
|
59 |
+
'while',
|
60 |
+
'function',
|
61 |
+
'for',
|
62 |
+
'in',
|
63 |
+
'next',
|
64 |
+
'break',
|
65 |
+
'TRUE',
|
66 |
+
'FALSE',
|
67 |
+
'NULL',
|
68 |
+
'Inf',
|
69 |
+
'NaN',
|
70 |
+
'NA',
|
71 |
+
'NA_integer_',
|
72 |
+
'NA_real_',
|
73 |
+
'NA_complex_',
|
74 |
+
'NA_character_',
|
75 |
+
'volatile']
|
76 |
+
|
77 |
+
|
78 |
+
class RCodePrinter(CodePrinter):
|
79 |
+
"""A printer to convert SymPy expressions to strings of R code"""
|
80 |
+
printmethod = "_rcode"
|
81 |
+
language = "R"
|
82 |
+
|
83 |
+
_default_settings: dict[str, Any] = {
|
84 |
+
'order': None,
|
85 |
+
'full_prec': 'auto',
|
86 |
+
'precision': 15,
|
87 |
+
'user_functions': {},
|
88 |
+
'human': True,
|
89 |
+
'contract': True,
|
90 |
+
'dereference': set(),
|
91 |
+
'error_on_reserved': False,
|
92 |
+
'reserved_word_suffix': '_',
|
93 |
+
}
|
94 |
+
_operators = {
|
95 |
+
'and': '&',
|
96 |
+
'or': '|',
|
97 |
+
'not': '!',
|
98 |
+
}
|
99 |
+
|
100 |
+
_relationals: dict[str, str] = {}
|
101 |
+
|
102 |
+
def __init__(self, settings={}):
|
103 |
+
CodePrinter.__init__(self, settings)
|
104 |
+
self.known_functions = dict(known_functions)
|
105 |
+
userfuncs = settings.get('user_functions', {})
|
106 |
+
self.known_functions.update(userfuncs)
|
107 |
+
self._dereference = set(settings.get('dereference', []))
|
108 |
+
self.reserved_words = set(reserved_words)
|
109 |
+
|
110 |
+
def _rate_index_position(self, p):
|
111 |
+
return p*5
|
112 |
+
|
113 |
+
def _get_statement(self, codestring):
|
114 |
+
return "%s;" % codestring
|
115 |
+
|
116 |
+
def _get_comment(self, text):
|
117 |
+
return "// {}".format(text)
|
118 |
+
|
119 |
+
def _declare_number_const(self, name, value):
|
120 |
+
return "{} = {};".format(name, value)
|
121 |
+
|
122 |
+
def _format_code(self, lines):
|
123 |
+
return self.indent_code(lines)
|
124 |
+
|
125 |
+
def _traverse_matrix_indices(self, mat):
|
126 |
+
rows, cols = mat.shape
|
127 |
+
return ((i, j) for i in range(rows) for j in range(cols))
|
128 |
+
|
129 |
+
def _get_loop_opening_ending(self, indices):
|
130 |
+
"""Returns a tuple (open_lines, close_lines) containing lists of codelines
|
131 |
+
"""
|
132 |
+
open_lines = []
|
133 |
+
close_lines = []
|
134 |
+
loopstart = "for (%(var)s in %(start)s:%(end)s){"
|
135 |
+
for i in indices:
|
136 |
+
# R arrays start at 1 and end at dimension
|
137 |
+
open_lines.append(loopstart % {
|
138 |
+
'var': self._print(i.label),
|
139 |
+
'start': self._print(i.lower+1),
|
140 |
+
'end': self._print(i.upper + 1)})
|
141 |
+
close_lines.append("}")
|
142 |
+
return open_lines, close_lines
|
143 |
+
|
144 |
+
def _print_Pow(self, expr):
|
145 |
+
if "Pow" in self.known_functions:
|
146 |
+
return self._print_Function(expr)
|
147 |
+
PREC = precedence(expr)
|
148 |
+
if equal_valued(expr.exp, -1):
|
149 |
+
return '1.0/%s' % (self.parenthesize(expr.base, PREC))
|
150 |
+
elif equal_valued(expr.exp, 0.5):
|
151 |
+
return 'sqrt(%s)' % self._print(expr.base)
|
152 |
+
else:
|
153 |
+
return '%s^%s' % (self.parenthesize(expr.base, PREC),
|
154 |
+
self.parenthesize(expr.exp, PREC))
|
155 |
+
|
156 |
+
|
157 |
+
def _print_Rational(self, expr):
|
158 |
+
p, q = int(expr.p), int(expr.q)
|
159 |
+
return '%d.0/%d.0' % (p, q)
|
160 |
+
|
161 |
+
def _print_Indexed(self, expr):
|
162 |
+
inds = [ self._print(i) for i in expr.indices ]
|
163 |
+
return "%s[%s]" % (self._print(expr.base.label), ", ".join(inds))
|
164 |
+
|
165 |
+
def _print_Idx(self, expr):
|
166 |
+
return self._print(expr.label)
|
167 |
+
|
168 |
+
def _print_Exp1(self, expr):
|
169 |
+
return "exp(1)"
|
170 |
+
|
171 |
+
def _print_Pi(self, expr):
|
172 |
+
return 'pi'
|
173 |
+
|
174 |
+
def _print_Infinity(self, expr):
|
175 |
+
return 'Inf'
|
176 |
+
|
177 |
+
def _print_NegativeInfinity(self, expr):
|
178 |
+
return '-Inf'
|
179 |
+
|
180 |
+
def _print_Assignment(self, expr):
|
181 |
+
from sympy.codegen.ast import Assignment
|
182 |
+
|
183 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
184 |
+
from sympy.tensor.indexed import IndexedBase
|
185 |
+
lhs = expr.lhs
|
186 |
+
rhs = expr.rhs
|
187 |
+
# We special case assignments that take multiple lines
|
188 |
+
#if isinstance(expr.rhs, Piecewise):
|
189 |
+
# from sympy.functions.elementary.piecewise import Piecewise
|
190 |
+
# # Here we modify Piecewise so each expression is now
|
191 |
+
# # an Assignment, and then continue on the print.
|
192 |
+
# expressions = []
|
193 |
+
# conditions = []
|
194 |
+
# for (e, c) in rhs.args:
|
195 |
+
# expressions.append(Assignment(lhs, e))
|
196 |
+
# conditions.append(c)
|
197 |
+
# temp = Piecewise(*zip(expressions, conditions))
|
198 |
+
# return self._print(temp)
|
199 |
+
#elif isinstance(lhs, MatrixSymbol):
|
200 |
+
if isinstance(lhs, MatrixSymbol):
|
201 |
+
# Here we form an Assignment for each element in the array,
|
202 |
+
# printing each one.
|
203 |
+
lines = []
|
204 |
+
for (i, j) in self._traverse_matrix_indices(lhs):
|
205 |
+
temp = Assignment(lhs[i, j], rhs[i, j])
|
206 |
+
code0 = self._print(temp)
|
207 |
+
lines.append(code0)
|
208 |
+
return "\n".join(lines)
|
209 |
+
elif self._settings["contract"] and (lhs.has(IndexedBase) or
|
210 |
+
rhs.has(IndexedBase)):
|
211 |
+
# Here we check if there is looping to be done, and if so
|
212 |
+
# print the required loops.
|
213 |
+
return self._doprint_loops(rhs, lhs)
|
214 |
+
else:
|
215 |
+
lhs_code = self._print(lhs)
|
216 |
+
rhs_code = self._print(rhs)
|
217 |
+
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
|
218 |
+
|
219 |
+
def _print_Piecewise(self, expr):
|
220 |
+
# This method is called only for inline if constructs
|
221 |
+
# Top level piecewise is handled in doprint()
|
222 |
+
if expr.args[-1].cond == True:
|
223 |
+
last_line = "%s" % self._print(expr.args[-1].expr)
|
224 |
+
else:
|
225 |
+
last_line = "ifelse(%s,%s,NA)" % (self._print(expr.args[-1].cond), self._print(expr.args[-1].expr))
|
226 |
+
code=last_line
|
227 |
+
for e, c in reversed(expr.args[:-1]):
|
228 |
+
code= "ifelse(%s,%s," % (self._print(c), self._print(e))+code+")"
|
229 |
+
return(code)
|
230 |
+
|
231 |
+
def _print_ITE(self, expr):
|
232 |
+
from sympy.functions import Piecewise
|
233 |
+
return self._print(expr.rewrite(Piecewise))
|
234 |
+
|
235 |
+
def _print_MatrixElement(self, expr):
|
236 |
+
return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"],
|
237 |
+
strict=True), expr.j + expr.i*expr.parent.shape[1])
|
238 |
+
|
239 |
+
def _print_Symbol(self, expr):
|
240 |
+
name = super()._print_Symbol(expr)
|
241 |
+
if expr in self._dereference:
|
242 |
+
return '(*{})'.format(name)
|
243 |
+
else:
|
244 |
+
return name
|
245 |
+
|
246 |
+
def _print_Relational(self, expr):
|
247 |
+
lhs_code = self._print(expr.lhs)
|
248 |
+
rhs_code = self._print(expr.rhs)
|
249 |
+
op = expr.rel_op
|
250 |
+
return "{} {} {}".format(lhs_code, op, rhs_code)
|
251 |
+
|
252 |
+
def _print_AugmentedAssignment(self, expr):
|
253 |
+
lhs_code = self._print(expr.lhs)
|
254 |
+
op = expr.op
|
255 |
+
rhs_code = self._print(expr.rhs)
|
256 |
+
return "{} {} {};".format(lhs_code, op, rhs_code)
|
257 |
+
|
258 |
+
def _print_For(self, expr):
|
259 |
+
target = self._print(expr.target)
|
260 |
+
if isinstance(expr.iterable, Range):
|
261 |
+
start, stop, step = expr.iterable.args
|
262 |
+
else:
|
263 |
+
raise NotImplementedError("Only iterable currently supported is Range")
|
264 |
+
body = self._print(expr.body)
|
265 |
+
return 'for({target} in seq(from={start}, to={stop}, by={step}){{\n{body}\n}}'.format(target=target, start=start,
|
266 |
+
stop=stop-1, step=step, body=body)
|
267 |
+
|
268 |
+
|
269 |
+
def indent_code(self, code):
|
270 |
+
"""Accepts a string of code or a list of code lines"""
|
271 |
+
|
272 |
+
if isinstance(code, str):
|
273 |
+
code_lines = self.indent_code(code.splitlines(True))
|
274 |
+
return ''.join(code_lines)
|
275 |
+
|
276 |
+
tab = " "
|
277 |
+
inc_token = ('{', '(', '{\n', '(\n')
|
278 |
+
dec_token = ('}', ')')
|
279 |
+
|
280 |
+
code = [ line.lstrip(' \t') for line in code ]
|
281 |
+
|
282 |
+
increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
|
283 |
+
decrease = [ int(any(map(line.startswith, dec_token)))
|
284 |
+
for line in code ]
|
285 |
+
|
286 |
+
pretty = []
|
287 |
+
level = 0
|
288 |
+
for n, line in enumerate(code):
|
289 |
+
if line in ('', '\n'):
|
290 |
+
pretty.append(line)
|
291 |
+
continue
|
292 |
+
level -= decrease[n]
|
293 |
+
pretty.append("%s%s" % (tab*level, line))
|
294 |
+
level += increase[n]
|
295 |
+
return pretty
|
296 |
+
|
297 |
+
|
298 |
+
def rcode(expr, assign_to=None, **settings):
|
299 |
+
"""Converts an expr to a string of r code
|
300 |
+
|
301 |
+
Parameters
|
302 |
+
==========
|
303 |
+
|
304 |
+
expr : Expr
|
305 |
+
A SymPy expression to be converted.
|
306 |
+
assign_to : optional
|
307 |
+
When given, the argument is used as the name of the variable to which
|
308 |
+
the expression is assigned. Can be a string, ``Symbol``,
|
309 |
+
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
|
310 |
+
line-wrapping, or for expressions that generate multi-line statements.
|
311 |
+
precision : integer, optional
|
312 |
+
The precision for numbers such as pi [default=15].
|
313 |
+
user_functions : dict, optional
|
314 |
+
A dictionary where the keys are string representations of either
|
315 |
+
``FunctionClass`` or ``UndefinedFunction`` instances and the values
|
316 |
+
are their desired R string representations. Alternatively, the
|
317 |
+
dictionary value can be a list of tuples i.e. [(argument_test,
|
318 |
+
rfunction_string)] or [(argument_test, rfunction_formater)]. See below
|
319 |
+
for examples.
|
320 |
+
human : bool, optional
|
321 |
+
If True, the result is a single string that may contain some constant
|
322 |
+
declarations for the number symbols. If False, the same information is
|
323 |
+
returned in a tuple of (symbols_to_declare, not_supported_functions,
|
324 |
+
code_text). [default=True].
|
325 |
+
contract: bool, optional
|
326 |
+
If True, ``Indexed`` instances are assumed to obey tensor contraction
|
327 |
+
rules and the corresponding nested loops over indices are generated.
|
328 |
+
Setting contract=False will not generate loops, instead the user is
|
329 |
+
responsible to provide values for the indices in the code.
|
330 |
+
[default=True].
|
331 |
+
|
332 |
+
Examples
|
333 |
+
========
|
334 |
+
|
335 |
+
>>> from sympy import rcode, symbols, Rational, sin, ceiling, Abs, Function
|
336 |
+
>>> x, tau = symbols("x, tau")
|
337 |
+
>>> rcode((2*tau)**Rational(7, 2))
|
338 |
+
'8*sqrt(2)*tau^(7.0/2.0)'
|
339 |
+
>>> rcode(sin(x), assign_to="s")
|
340 |
+
's = sin(x);'
|
341 |
+
|
342 |
+
Simple custom printing can be defined for certain types by passing a
|
343 |
+
dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
|
344 |
+
Alternatively, the dictionary value can be a list of tuples i.e.
|
345 |
+
[(argument_test, cfunction_string)].
|
346 |
+
|
347 |
+
>>> custom_functions = {
|
348 |
+
... "ceiling": "CEIL",
|
349 |
+
... "Abs": [(lambda x: not x.is_integer, "fabs"),
|
350 |
+
... (lambda x: x.is_integer, "ABS")],
|
351 |
+
... "func": "f"
|
352 |
+
... }
|
353 |
+
>>> func = Function('func')
|
354 |
+
>>> rcode(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
|
355 |
+
'f(fabs(x) + CEIL(x))'
|
356 |
+
|
357 |
+
or if the R-function takes a subset of the original arguments:
|
358 |
+
|
359 |
+
>>> rcode(2**x + 3**x, user_functions={'Pow': [
|
360 |
+
... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
|
361 |
+
... (lambda b, e: b != 2, 'pow')]})
|
362 |
+
'exp2(x) + pow(3, x)'
|
363 |
+
|
364 |
+
``Piecewise`` expressions are converted into conditionals. If an
|
365 |
+
``assign_to`` variable is provided an if statement is created, otherwise
|
366 |
+
the ternary operator is used. Note that if the ``Piecewise`` lacks a
|
367 |
+
default term, represented by ``(expr, True)`` then an error will be thrown.
|
368 |
+
This is to prevent generating an expression that may not evaluate to
|
369 |
+
anything.
|
370 |
+
|
371 |
+
>>> from sympy import Piecewise
|
372 |
+
>>> expr = Piecewise((x + 1, x > 0), (x, True))
|
373 |
+
>>> print(rcode(expr, assign_to=tau))
|
374 |
+
tau = ifelse(x > 0,x + 1,x);
|
375 |
+
|
376 |
+
Support for loops is provided through ``Indexed`` types. With
|
377 |
+
``contract=True`` these expressions will be turned into loops, whereas
|
378 |
+
``contract=False`` will just print the assignment expression that should be
|
379 |
+
looped over:
|
380 |
+
|
381 |
+
>>> from sympy import Eq, IndexedBase, Idx
|
382 |
+
>>> len_y = 5
|
383 |
+
>>> y = IndexedBase('y', shape=(len_y,))
|
384 |
+
>>> t = IndexedBase('t', shape=(len_y,))
|
385 |
+
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
|
386 |
+
>>> i = Idx('i', len_y-1)
|
387 |
+
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
|
388 |
+
>>> rcode(e.rhs, assign_to=e.lhs, contract=False)
|
389 |
+
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
|
390 |
+
|
391 |
+
Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
|
392 |
+
must be provided to ``assign_to``. Note that any expression that can be
|
393 |
+
generated normally can also exist inside a Matrix:
|
394 |
+
|
395 |
+
>>> from sympy import Matrix, MatrixSymbol
|
396 |
+
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
|
397 |
+
>>> A = MatrixSymbol('A', 3, 1)
|
398 |
+
>>> print(rcode(mat, A))
|
399 |
+
A[0] = x^2;
|
400 |
+
A[1] = ifelse(x > 0,x + 1,x);
|
401 |
+
A[2] = sin(x);
|
402 |
+
|
403 |
+
"""
|
404 |
+
|
405 |
+
return RCodePrinter(settings).doprint(expr, assign_to)
|
406 |
+
|
407 |
+
|
408 |
+
def print_rcode(expr, **settings):
|
409 |
+
"""Prints R representation of the given expression."""
|
410 |
+
print(rcode(expr, **settings))
|
venv/lib/python3.10/site-packages/sympy/printing/repr.py
ADDED
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A Printer for generating executable code.
|
3 |
+
|
4 |
+
The most important function here is srepr that returns a string so that the
|
5 |
+
relation eval(srepr(expr))=expr holds in an appropriate environment.
|
6 |
+
"""
|
7 |
+
|
8 |
+
from __future__ import annotations
|
9 |
+
from typing import Any
|
10 |
+
|
11 |
+
from sympy.core.function import AppliedUndef
|
12 |
+
from sympy.core.mul import Mul
|
13 |
+
from mpmath.libmp import repr_dps, to_str as mlib_to_str
|
14 |
+
|
15 |
+
from .printer import Printer, print_function
|
16 |
+
|
17 |
+
|
18 |
+
class ReprPrinter(Printer):
|
19 |
+
printmethod = "_sympyrepr"
|
20 |
+
|
21 |
+
_default_settings: dict[str, Any] = {
|
22 |
+
"order": None,
|
23 |
+
"perm_cyclic" : True,
|
24 |
+
}
|
25 |
+
|
26 |
+
def reprify(self, args, sep):
|
27 |
+
"""
|
28 |
+
Prints each item in `args` and joins them with `sep`.
|
29 |
+
"""
|
30 |
+
return sep.join([self.doprint(item) for item in args])
|
31 |
+
|
32 |
+
def emptyPrinter(self, expr):
|
33 |
+
"""
|
34 |
+
The fallback printer.
|
35 |
+
"""
|
36 |
+
if isinstance(expr, str):
|
37 |
+
return expr
|
38 |
+
elif hasattr(expr, "__srepr__"):
|
39 |
+
return expr.__srepr__()
|
40 |
+
elif hasattr(expr, "args") and hasattr(expr.args, "__iter__"):
|
41 |
+
l = []
|
42 |
+
for o in expr.args:
|
43 |
+
l.append(self._print(o))
|
44 |
+
return expr.__class__.__name__ + '(%s)' % ', '.join(l)
|
45 |
+
elif hasattr(expr, "__module__") and hasattr(expr, "__name__"):
|
46 |
+
return "<'%s.%s'>" % (expr.__module__, expr.__name__)
|
47 |
+
else:
|
48 |
+
return str(expr)
|
49 |
+
|
50 |
+
def _print_Add(self, expr, order=None):
|
51 |
+
args = self._as_ordered_terms(expr, order=order)
|
52 |
+
args = map(self._print, args)
|
53 |
+
clsname = type(expr).__name__
|
54 |
+
return clsname + "(%s)" % ", ".join(args)
|
55 |
+
|
56 |
+
def _print_Cycle(self, expr):
|
57 |
+
return expr.__repr__()
|
58 |
+
|
59 |
+
def _print_Permutation(self, expr):
|
60 |
+
from sympy.combinatorics.permutations import Permutation, Cycle
|
61 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
62 |
+
|
63 |
+
perm_cyclic = Permutation.print_cyclic
|
64 |
+
if perm_cyclic is not None:
|
65 |
+
sympy_deprecation_warning(
|
66 |
+
f"""
|
67 |
+
Setting Permutation.print_cyclic is deprecated. Instead use
|
68 |
+
init_printing(perm_cyclic={perm_cyclic}).
|
69 |
+
""",
|
70 |
+
deprecated_since_version="1.6",
|
71 |
+
active_deprecations_target="deprecated-permutation-print_cyclic",
|
72 |
+
stacklevel=7,
|
73 |
+
)
|
74 |
+
else:
|
75 |
+
perm_cyclic = self._settings.get("perm_cyclic", True)
|
76 |
+
|
77 |
+
if perm_cyclic:
|
78 |
+
if not expr.size:
|
79 |
+
return 'Permutation()'
|
80 |
+
# before taking Cycle notation, see if the last element is
|
81 |
+
# a singleton and move it to the head of the string
|
82 |
+
s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):]
|
83 |
+
last = s.rfind('(')
|
84 |
+
if not last == 0 and ',' not in s[last:]:
|
85 |
+
s = s[last:] + s[:last]
|
86 |
+
return 'Permutation%s' %s
|
87 |
+
else:
|
88 |
+
s = expr.support()
|
89 |
+
if not s:
|
90 |
+
if expr.size < 5:
|
91 |
+
return 'Permutation(%s)' % str(expr.array_form)
|
92 |
+
return 'Permutation([], size=%s)' % expr.size
|
93 |
+
trim = str(expr.array_form[:s[-1] + 1]) + ', size=%s' % expr.size
|
94 |
+
use = full = str(expr.array_form)
|
95 |
+
if len(trim) < len(full):
|
96 |
+
use = trim
|
97 |
+
return 'Permutation(%s)' % use
|
98 |
+
|
99 |
+
def _print_Function(self, expr):
|
100 |
+
r = self._print(expr.func)
|
101 |
+
r += '(%s)' % ', '.join([self._print(a) for a in expr.args])
|
102 |
+
return r
|
103 |
+
|
104 |
+
def _print_Heaviside(self, expr):
|
105 |
+
# Same as _print_Function but uses pargs to suppress default value for
|
106 |
+
# 2nd arg.
|
107 |
+
r = self._print(expr.func)
|
108 |
+
r += '(%s)' % ', '.join([self._print(a) for a in expr.pargs])
|
109 |
+
return r
|
110 |
+
|
111 |
+
def _print_FunctionClass(self, expr):
|
112 |
+
if issubclass(expr, AppliedUndef):
|
113 |
+
return 'Function(%r)' % (expr.__name__)
|
114 |
+
else:
|
115 |
+
return expr.__name__
|
116 |
+
|
117 |
+
def _print_Half(self, expr):
|
118 |
+
return 'Rational(1, 2)'
|
119 |
+
|
120 |
+
def _print_RationalConstant(self, expr):
|
121 |
+
return str(expr)
|
122 |
+
|
123 |
+
def _print_AtomicExpr(self, expr):
|
124 |
+
return str(expr)
|
125 |
+
|
126 |
+
def _print_NumberSymbol(self, expr):
|
127 |
+
return str(expr)
|
128 |
+
|
129 |
+
def _print_Integer(self, expr):
|
130 |
+
return 'Integer(%i)' % expr.p
|
131 |
+
|
132 |
+
def _print_Complexes(self, expr):
|
133 |
+
return 'Complexes'
|
134 |
+
|
135 |
+
def _print_Integers(self, expr):
|
136 |
+
return 'Integers'
|
137 |
+
|
138 |
+
def _print_Naturals(self, expr):
|
139 |
+
return 'Naturals'
|
140 |
+
|
141 |
+
def _print_Naturals0(self, expr):
|
142 |
+
return 'Naturals0'
|
143 |
+
|
144 |
+
def _print_Rationals(self, expr):
|
145 |
+
return 'Rationals'
|
146 |
+
|
147 |
+
def _print_Reals(self, expr):
|
148 |
+
return 'Reals'
|
149 |
+
|
150 |
+
def _print_EmptySet(self, expr):
|
151 |
+
return 'EmptySet'
|
152 |
+
|
153 |
+
def _print_UniversalSet(self, expr):
|
154 |
+
return 'UniversalSet'
|
155 |
+
|
156 |
+
def _print_EmptySequence(self, expr):
|
157 |
+
return 'EmptySequence'
|
158 |
+
|
159 |
+
def _print_list(self, expr):
|
160 |
+
return "[%s]" % self.reprify(expr, ", ")
|
161 |
+
|
162 |
+
def _print_dict(self, expr):
|
163 |
+
sep = ", "
|
164 |
+
dict_kvs = ["%s: %s" % (self.doprint(key), self.doprint(value)) for key, value in expr.items()]
|
165 |
+
return "{%s}" % sep.join(dict_kvs)
|
166 |
+
|
167 |
+
def _print_set(self, expr):
|
168 |
+
if not expr:
|
169 |
+
return "set()"
|
170 |
+
return "{%s}" % self.reprify(expr, ", ")
|
171 |
+
|
172 |
+
def _print_MatrixBase(self, expr):
|
173 |
+
# special case for some empty matrices
|
174 |
+
if (expr.rows == 0) ^ (expr.cols == 0):
|
175 |
+
return '%s(%s, %s, %s)' % (expr.__class__.__name__,
|
176 |
+
self._print(expr.rows),
|
177 |
+
self._print(expr.cols),
|
178 |
+
self._print([]))
|
179 |
+
l = []
|
180 |
+
for i in range(expr.rows):
|
181 |
+
l.append([])
|
182 |
+
for j in range(expr.cols):
|
183 |
+
l[-1].append(expr[i, j])
|
184 |
+
return '%s(%s)' % (expr.__class__.__name__, self._print(l))
|
185 |
+
|
186 |
+
def _print_BooleanTrue(self, expr):
|
187 |
+
return "true"
|
188 |
+
|
189 |
+
def _print_BooleanFalse(self, expr):
|
190 |
+
return "false"
|
191 |
+
|
192 |
+
def _print_NaN(self, expr):
|
193 |
+
return "nan"
|
194 |
+
|
195 |
+
def _print_Mul(self, expr, order=None):
|
196 |
+
if self.order not in ('old', 'none'):
|
197 |
+
args = expr.as_ordered_factors()
|
198 |
+
else:
|
199 |
+
# use make_args in case expr was something like -x -> x
|
200 |
+
args = Mul.make_args(expr)
|
201 |
+
|
202 |
+
args = map(self._print, args)
|
203 |
+
clsname = type(expr).__name__
|
204 |
+
return clsname + "(%s)" % ", ".join(args)
|
205 |
+
|
206 |
+
def _print_Rational(self, expr):
|
207 |
+
return 'Rational(%s, %s)' % (self._print(expr.p), self._print(expr.q))
|
208 |
+
|
209 |
+
def _print_PythonRational(self, expr):
|
210 |
+
return "%s(%d, %d)" % (expr.__class__.__name__, expr.p, expr.q)
|
211 |
+
|
212 |
+
def _print_Fraction(self, expr):
|
213 |
+
return 'Fraction(%s, %s)' % (self._print(expr.numerator), self._print(expr.denominator))
|
214 |
+
|
215 |
+
def _print_Float(self, expr):
|
216 |
+
r = mlib_to_str(expr._mpf_, repr_dps(expr._prec))
|
217 |
+
return "%s('%s', precision=%i)" % (expr.__class__.__name__, r, expr._prec)
|
218 |
+
|
219 |
+
def _print_Sum2(self, expr):
|
220 |
+
return "Sum2(%s, (%s, %s, %s))" % (self._print(expr.f), self._print(expr.i),
|
221 |
+
self._print(expr.a), self._print(expr.b))
|
222 |
+
|
223 |
+
def _print_Str(self, s):
|
224 |
+
return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
|
225 |
+
|
226 |
+
def _print_Symbol(self, expr):
|
227 |
+
d = expr._assumptions_orig
|
228 |
+
# print the dummy_index like it was an assumption
|
229 |
+
if expr.is_Dummy:
|
230 |
+
d['dummy_index'] = expr.dummy_index
|
231 |
+
|
232 |
+
if d == {}:
|
233 |
+
return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name))
|
234 |
+
else:
|
235 |
+
attr = ['%s=%s' % (k, v) for k, v in d.items()]
|
236 |
+
return "%s(%s, %s)" % (expr.__class__.__name__,
|
237 |
+
self._print(expr.name), ', '.join(attr))
|
238 |
+
|
239 |
+
def _print_CoordinateSymbol(self, expr):
|
240 |
+
d = expr._assumptions.generator
|
241 |
+
|
242 |
+
if d == {}:
|
243 |
+
return "%s(%s, %s)" % (
|
244 |
+
expr.__class__.__name__,
|
245 |
+
self._print(expr.coord_sys),
|
246 |
+
self._print(expr.index)
|
247 |
+
)
|
248 |
+
else:
|
249 |
+
attr = ['%s=%s' % (k, v) for k, v in d.items()]
|
250 |
+
return "%s(%s, %s, %s)" % (
|
251 |
+
expr.__class__.__name__,
|
252 |
+
self._print(expr.coord_sys),
|
253 |
+
self._print(expr.index),
|
254 |
+
', '.join(attr)
|
255 |
+
)
|
256 |
+
|
257 |
+
def _print_Predicate(self, expr):
|
258 |
+
return "Q.%s" % expr.name
|
259 |
+
|
260 |
+
def _print_AppliedPredicate(self, expr):
|
261 |
+
# will be changed to just expr.args when args overriding is removed
|
262 |
+
args = expr._args
|
263 |
+
return "%s(%s)" % (expr.__class__.__name__, self.reprify(args, ", "))
|
264 |
+
|
265 |
+
def _print_str(self, expr):
|
266 |
+
return repr(expr)
|
267 |
+
|
268 |
+
def _print_tuple(self, expr):
|
269 |
+
if len(expr) == 1:
|
270 |
+
return "(%s,)" % self._print(expr[0])
|
271 |
+
else:
|
272 |
+
return "(%s)" % self.reprify(expr, ", ")
|
273 |
+
|
274 |
+
def _print_WildFunction(self, expr):
|
275 |
+
return "%s('%s')" % (expr.__class__.__name__, expr.name)
|
276 |
+
|
277 |
+
def _print_AlgebraicNumber(self, expr):
|
278 |
+
return "%s(%s, %s)" % (expr.__class__.__name__,
|
279 |
+
self._print(expr.root), self._print(expr.coeffs()))
|
280 |
+
|
281 |
+
def _print_PolyRing(self, ring):
|
282 |
+
return "%s(%s, %s, %s)" % (ring.__class__.__name__,
|
283 |
+
self._print(ring.symbols), self._print(ring.domain), self._print(ring.order))
|
284 |
+
|
285 |
+
def _print_FracField(self, field):
|
286 |
+
return "%s(%s, %s, %s)" % (field.__class__.__name__,
|
287 |
+
self._print(field.symbols), self._print(field.domain), self._print(field.order))
|
288 |
+
|
289 |
+
def _print_PolyElement(self, poly):
|
290 |
+
terms = list(poly.terms())
|
291 |
+
terms.sort(key=poly.ring.order, reverse=True)
|
292 |
+
return "%s(%s, %s)" % (poly.__class__.__name__, self._print(poly.ring), self._print(terms))
|
293 |
+
|
294 |
+
def _print_FracElement(self, frac):
|
295 |
+
numer_terms = list(frac.numer.terms())
|
296 |
+
numer_terms.sort(key=frac.field.order, reverse=True)
|
297 |
+
denom_terms = list(frac.denom.terms())
|
298 |
+
denom_terms.sort(key=frac.field.order, reverse=True)
|
299 |
+
numer = self._print(numer_terms)
|
300 |
+
denom = self._print(denom_terms)
|
301 |
+
return "%s(%s, %s, %s)" % (frac.__class__.__name__, self._print(frac.field), numer, denom)
|
302 |
+
|
303 |
+
def _print_FractionField(self, domain):
|
304 |
+
cls = domain.__class__.__name__
|
305 |
+
field = self._print(domain.field)
|
306 |
+
return "%s(%s)" % (cls, field)
|
307 |
+
|
308 |
+
def _print_PolynomialRingBase(self, ring):
|
309 |
+
cls = ring.__class__.__name__
|
310 |
+
dom = self._print(ring.domain)
|
311 |
+
gens = ', '.join(map(self._print, ring.gens))
|
312 |
+
order = str(ring.order)
|
313 |
+
if order != ring.default_order:
|
314 |
+
orderstr = ", order=" + order
|
315 |
+
else:
|
316 |
+
orderstr = ""
|
317 |
+
return "%s(%s, %s%s)" % (cls, dom, gens, orderstr)
|
318 |
+
|
319 |
+
def _print_DMP(self, p):
|
320 |
+
cls = p.__class__.__name__
|
321 |
+
rep = self._print(p.rep)
|
322 |
+
dom = self._print(p.dom)
|
323 |
+
if p.ring is not None:
|
324 |
+
ringstr = ", ring=" + self._print(p.ring)
|
325 |
+
else:
|
326 |
+
ringstr = ""
|
327 |
+
return "%s(%s, %s%s)" % (cls, rep, dom, ringstr)
|
328 |
+
|
329 |
+
def _print_MonogenicFiniteExtension(self, ext):
|
330 |
+
# The expanded tree shown by srepr(ext.modulus)
|
331 |
+
# is not practical.
|
332 |
+
return "FiniteExtension(%s)" % str(ext.modulus)
|
333 |
+
|
334 |
+
def _print_ExtensionElement(self, f):
|
335 |
+
rep = self._print(f.rep)
|
336 |
+
ext = self._print(f.ext)
|
337 |
+
return "ExtElem(%s, %s)" % (rep, ext)
|
338 |
+
|
339 |
+
@print_function(ReprPrinter)
|
340 |
+
def srepr(expr, **settings):
|
341 |
+
"""return expr in repr form"""
|
342 |
+
return ReprPrinter(settings).doprint(expr)
|
ven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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Rust code printer
|
3 |
+
|
4 |
+
The `RustCodePrinter` converts SymPy expressions into Rust expressions.
|
5 |
+
|
6 |
+
A complete code generator, which uses `rust_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 |
+
# Possible Improvement
|
13 |
+
#
|
14 |
+
# * make sure we follow Rust Style Guidelines_
|
15 |
+
# * make use of pattern matching
|
16 |
+
# * better support for reference
|
17 |
+
# * generate generic code and use trait to make sure they have specific methods
|
18 |
+
# * use crates_ to get more math support
|
19 |
+
# - num_
|
20 |
+
# + BigInt_, BigUint_
|
21 |
+
# + Complex_
|
22 |
+
# + Rational64_, Rational32_, BigRational_
|
23 |
+
#
|
24 |
+
# .. _crates: https://crates.io/
|
25 |
+
# .. _Guidelines: https://github.com/rust-lang/rust/tree/master/src/doc/style
|
26 |
+
# .. _num: http://rust-num.github.io/num/num/
|
27 |
+
# .. _BigInt: http://rust-num.github.io/num/num/bigint/struct.BigInt.html
|
28 |
+
# .. _BigUint: http://rust-num.github.io/num/num/bigint/struct.BigUint.html
|
29 |
+
# .. _Complex: http://rust-num.github.io/num/num/complex/struct.Complex.html
|
30 |
+
# .. _Rational32: http://rust-num.github.io/num/num/rational/type.Rational32.html
|
31 |
+
# .. _Rational64: http://rust-num.github.io/num/num/rational/type.Rational64.html
|
32 |
+
# .. _BigRational: http://rust-num.github.io/num/num/rational/type.BigRational.html
|
33 |
+
|
34 |
+
from __future__ import annotations
|
35 |
+
from typing import Any
|
36 |
+
|
37 |
+
from sympy.core import S, Rational, Float, Lambda
|
38 |
+
from sympy.core.numbers import equal_valued
|
39 |
+
from sympy.printing.codeprinter import CodePrinter
|
40 |
+
|
41 |
+
# Rust's methods for integer and float can be found at here :
|
42 |
+
#
|
43 |
+
# * `Rust - Primitive Type f64 <https://doc.rust-lang.org/std/primitive.f64.html>`_
|
44 |
+
# * `Rust - Primitive Type i64 <https://doc.rust-lang.org/std/primitive.i64.html>`_
|
45 |
+
#
|
46 |
+
# Function Style :
|
47 |
+
#
|
48 |
+
# 1. args[0].func(args[1:]), method with arguments
|
49 |
+
# 2. args[0].func(), method without arguments
|
50 |
+
# 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp())
|
51 |
+
# 4. func(args), function with arguments
|
52 |
+
|
53 |
+
# dictionary mapping SymPy function to (argument_conditions, Rust_function).
|
54 |
+
# Used in RustCodePrinter._print_Function(self)
|
55 |
+
|
56 |
+
# f64 method in Rust
|
57 |
+
known_functions = {
|
58 |
+
# "": "is_nan",
|
59 |
+
# "": "is_infinite",
|
60 |
+
# "": "is_finite",
|
61 |
+
# "": "is_normal",
|
62 |
+
# "": "classify",
|
63 |
+
"floor": "floor",
|
64 |
+
"ceiling": "ceil",
|
65 |
+
# "": "round",
|
66 |
+
# "": "trunc",
|
67 |
+
# "": "fract",
|
68 |
+
"Abs": "abs",
|
69 |
+
"sign": "signum",
|
70 |
+
# "": "is_sign_positive",
|
71 |
+
# "": "is_sign_negative",
|
72 |
+
# "": "mul_add",
|
73 |
+
"Pow": [(lambda base, exp: equal_valued(exp, -1), "recip", 2), # 1.0/x
|
74 |
+
(lambda base, exp: equal_valued(exp, 0.5), "sqrt", 2), # x ** 0.5
|
75 |
+
(lambda base, exp: equal_valued(exp, -0.5), "sqrt().recip", 2), # 1/(x ** 0.5)
|
76 |
+
(lambda base, exp: exp == Rational(1, 3), "cbrt", 2), # x ** (1/3)
|
77 |
+
(lambda base, exp: equal_valued(base, 2), "exp2", 3), # 2 ** x
|
78 |
+
(lambda base, exp: exp.is_integer, "powi", 1), # x ** y, for i32
|
79 |
+
(lambda base, exp: not exp.is_integer, "powf", 1)], # x ** y, for f64
|
80 |
+
"exp": [(lambda exp: True, "exp", 2)], # e ** x
|
81 |
+
"log": "ln",
|
82 |
+
# "": "log", # number.log(base)
|
83 |
+
# "": "log2",
|
84 |
+
# "": "log10",
|
85 |
+
# "": "to_degrees",
|
86 |
+
# "": "to_radians",
|
87 |
+
"Max": "max",
|
88 |
+
"Min": "min",
|
89 |
+
# "": "hypot", # (x**2 + y**2) ** 0.5
|
90 |
+
"sin": "sin",
|
91 |
+
"cos": "cos",
|
92 |
+
"tan": "tan",
|
93 |
+
"asin": "asin",
|
94 |
+
"acos": "acos",
|
95 |
+
"atan": "atan",
|
96 |
+
"atan2": "atan2",
|
97 |
+
# "": "sin_cos",
|
98 |
+
# "": "exp_m1", # e ** x - 1
|
99 |
+
# "": "ln_1p", # ln(1 + x)
|
100 |
+
"sinh": "sinh",
|
101 |
+
"cosh": "cosh",
|
102 |
+
"tanh": "tanh",
|
103 |
+
"asinh": "asinh",
|
104 |
+
"acosh": "acosh",
|
105 |
+
"atanh": "atanh",
|
106 |
+
"sqrt": "sqrt", # To enable automatic rewrites
|
107 |
+
}
|
108 |
+
|
109 |
+
# i64 method in Rust
|
110 |
+
# known_functions_i64 = {
|
111 |
+
# "": "min_value",
|
112 |
+
# "": "max_value",
|
113 |
+
# "": "from_str_radix",
|
114 |
+
# "": "count_ones",
|
115 |
+
# "": "count_zeros",
|
116 |
+
# "": "leading_zeros",
|
117 |
+
# "": "trainling_zeros",
|
118 |
+
# "": "rotate_left",
|
119 |
+
# "": "rotate_right",
|
120 |
+
# "": "swap_bytes",
|
121 |
+
# "": "from_be",
|
122 |
+
# "": "from_le",
|
123 |
+
# "": "to_be", # to big endian
|
124 |
+
# "": "to_le", # to little endian
|
125 |
+
# "": "checked_add",
|
126 |
+
# "": "checked_sub",
|
127 |
+
# "": "checked_mul",
|
128 |
+
# "": "checked_div",
|
129 |
+
# "": "checked_rem",
|
130 |
+
# "": "checked_neg",
|
131 |
+
# "": "checked_shl",
|
132 |
+
# "": "checked_shr",
|
133 |
+
# "": "checked_abs",
|
134 |
+
# "": "saturating_add",
|
135 |
+
# "": "saturating_sub",
|
136 |
+
# "": "saturating_mul",
|
137 |
+
# "": "wrapping_add",
|
138 |
+
# "": "wrapping_sub",
|
139 |
+
# "": "wrapping_mul",
|
140 |
+
# "": "wrapping_div",
|
141 |
+
# "": "wrapping_rem",
|
142 |
+
# "": "wrapping_neg",
|
143 |
+
# "": "wrapping_shl",
|
144 |
+
# "": "wrapping_shr",
|
145 |
+
# "": "wrapping_abs",
|
146 |
+
# "": "overflowing_add",
|
147 |
+
# "": "overflowing_sub",
|
148 |
+
# "": "overflowing_mul",
|
149 |
+
# "": "overflowing_div",
|
150 |
+
# "": "overflowing_rem",
|
151 |
+
# "": "overflowing_neg",
|
152 |
+
# "": "overflowing_shl",
|
153 |
+
# "": "overflowing_shr",
|
154 |
+
# "": "overflowing_abs",
|
155 |
+
# "Pow": "pow",
|
156 |
+
# "Abs": "abs",
|
157 |
+
# "sign": "signum",
|
158 |
+
# "": "is_positive",
|
159 |
+
# "": "is_negnative",
|
160 |
+
# }
|
161 |
+
|
162 |
+
# These are the core reserved words in the Rust language. Taken from:
|
163 |
+
# http://doc.rust-lang.org/grammar.html#keywords
|
164 |
+
|
165 |
+
reserved_words = ['abstract',
|
166 |
+
'alignof',
|
167 |
+
'as',
|
168 |
+
'become',
|
169 |
+
'box',
|
170 |
+
'break',
|
171 |
+
'const',
|
172 |
+
'continue',
|
173 |
+
'crate',
|
174 |
+
'do',
|
175 |
+
'else',
|
176 |
+
'enum',
|
177 |
+
'extern',
|
178 |
+
'false',
|
179 |
+
'final',
|
180 |
+
'fn',
|
181 |
+
'for',
|
182 |
+
'if',
|
183 |
+
'impl',
|
184 |
+
'in',
|
185 |
+
'let',
|
186 |
+
'loop',
|
187 |
+
'macro',
|
188 |
+
'match',
|
189 |
+
'mod',
|
190 |
+
'move',
|
191 |
+
'mut',
|
192 |
+
'offsetof',
|
193 |
+
'override',
|
194 |
+
'priv',
|
195 |
+
'proc',
|
196 |
+
'pub',
|
197 |
+
'pure',
|
198 |
+
'ref',
|
199 |
+
'return',
|
200 |
+
'Self',
|
201 |
+
'self',
|
202 |
+
'sizeof',
|
203 |
+
'static',
|
204 |
+
'struct',
|
205 |
+
'super',
|
206 |
+
'trait',
|
207 |
+
'true',
|
208 |
+
'type',
|
209 |
+
'typeof',
|
210 |
+
'unsafe',
|
211 |
+
'unsized',
|
212 |
+
'use',
|
213 |
+
'virtual',
|
214 |
+
'where',
|
215 |
+
'while',
|
216 |
+
'yield']
|
217 |
+
|
218 |
+
|
219 |
+
class RustCodePrinter(CodePrinter):
|
220 |
+
"""A printer to convert SymPy expressions to strings of Rust code"""
|
221 |
+
printmethod = "_rust_code"
|
222 |
+
language = "Rust"
|
223 |
+
|
224 |
+
_default_settings: dict[str, Any] = {
|
225 |
+
'order': None,
|
226 |
+
'full_prec': 'auto',
|
227 |
+
'precision': 17,
|
228 |
+
'user_functions': {},
|
229 |
+
'human': True,
|
230 |
+
'contract': True,
|
231 |
+
'dereference': set(),
|
232 |
+
'error_on_reserved': False,
|
233 |
+
'reserved_word_suffix': '_',
|
234 |
+
'inline': False,
|
235 |
+
}
|
236 |
+
|
237 |
+
def __init__(self, settings={}):
|
238 |
+
CodePrinter.__init__(self, settings)
|
239 |
+
self.known_functions = dict(known_functions)
|
240 |
+
userfuncs = settings.get('user_functions', {})
|
241 |
+
self.known_functions.update(userfuncs)
|
242 |
+
self._dereference = set(settings.get('dereference', []))
|
243 |
+
self.reserved_words = set(reserved_words)
|
244 |
+
|
245 |
+
def _rate_index_position(self, p):
|
246 |
+
return p*5
|
247 |
+
|
248 |
+
def _get_statement(self, codestring):
|
249 |
+
return "%s;" % codestring
|
250 |
+
|
251 |
+
def _get_comment(self, text):
|
252 |
+
return "// %s" % text
|
253 |
+
|
254 |
+
def _declare_number_const(self, name, value):
|
255 |
+
return "const %s: f64 = %s;" % (name, value)
|
256 |
+
|
257 |
+
def _format_code(self, lines):
|
258 |
+
return self.indent_code(lines)
|
259 |
+
|
260 |
+
def _traverse_matrix_indices(self, mat):
|
261 |
+
rows, cols = mat.shape
|
262 |
+
return ((i, j) for i in range(rows) for j in range(cols))
|
263 |
+
|
264 |
+
def _get_loop_opening_ending(self, indices):
|
265 |
+
open_lines = []
|
266 |
+
close_lines = []
|
267 |
+
loopstart = "for %(var)s in %(start)s..%(end)s {"
|
268 |
+
for i in indices:
|
269 |
+
# Rust arrays start at 0 and end at dimension-1
|
270 |
+
open_lines.append(loopstart % {
|
271 |
+
'var': self._print(i),
|
272 |
+
'start': self._print(i.lower),
|
273 |
+
'end': self._print(i.upper + 1)})
|
274 |
+
close_lines.append("}")
|
275 |
+
return open_lines, close_lines
|
276 |
+
|
277 |
+
def _print_caller_var(self, expr):
|
278 |
+
if len(expr.args) > 1:
|
279 |
+
# for something like `sin(x + y + z)`,
|
280 |
+
# make sure we can get '(x + y + z).sin()'
|
281 |
+
# instead of 'x + y + z.sin()'
|
282 |
+
return '(' + self._print(expr) + ')'
|
283 |
+
elif expr.is_number:
|
284 |
+
return self._print(expr, _type=True)
|
285 |
+
else:
|
286 |
+
return self._print(expr)
|
287 |
+
|
288 |
+
def _print_Function(self, expr):
|
289 |
+
"""
|
290 |
+
basic function for printing `Function`
|
291 |
+
|
292 |
+
Function Style :
|
293 |
+
|
294 |
+
1. args[0].func(args[1:]), method with arguments
|
295 |
+
2. args[0].func(), method without arguments
|
296 |
+
3. args[1].func(), method without arguments (e.g. (e, x) => x.exp())
|
297 |
+
4. func(args), function with arguments
|
298 |
+
"""
|
299 |
+
|
300 |
+
if expr.func.__name__ in self.known_functions:
|
301 |
+
cond_func = self.known_functions[expr.func.__name__]
|
302 |
+
func = None
|
303 |
+
style = 1
|
304 |
+
if isinstance(cond_func, str):
|
305 |
+
func = cond_func
|
306 |
+
else:
|
307 |
+
for cond, func, style in cond_func:
|
308 |
+
if cond(*expr.args):
|
309 |
+
break
|
310 |
+
if func is not None:
|
311 |
+
if style == 1:
|
312 |
+
ret = "%(var)s.%(method)s(%(args)s)" % {
|
313 |
+
'var': self._print_caller_var(expr.args[0]),
|
314 |
+
'method': func,
|
315 |
+
'args': self.stringify(expr.args[1:], ", ") if len(expr.args) > 1 else ''
|
316 |
+
}
|
317 |
+
elif style == 2:
|
318 |
+
ret = "%(var)s.%(method)s()" % {
|
319 |
+
'var': self._print_caller_var(expr.args[0]),
|
320 |
+
'method': func,
|
321 |
+
}
|
322 |
+
elif style == 3:
|
323 |
+
ret = "%(var)s.%(method)s()" % {
|
324 |
+
'var': self._print_caller_var(expr.args[1]),
|
325 |
+
'method': func,
|
326 |
+
}
|
327 |
+
else:
|
328 |
+
ret = "%(func)s(%(args)s)" % {
|
329 |
+
'func': func,
|
330 |
+
'args': self.stringify(expr.args, ", "),
|
331 |
+
}
|
332 |
+
return ret
|
333 |
+
elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda):
|
334 |
+
# inlined function
|
335 |
+
return self._print(expr._imp_(*expr.args))
|
336 |
+
elif expr.func.__name__ in self._rewriteable_functions:
|
337 |
+
# Simple rewrite to supported function possible
|
338 |
+
target_f, required_fs = self._rewriteable_functions[expr.func.__name__]
|
339 |
+
if self._can_print(target_f) and all(self._can_print(f) for f in required_fs):
|
340 |
+
return self._print(expr.rewrite(target_f))
|
341 |
+
else:
|
342 |
+
return self._print_not_supported(expr)
|
343 |
+
|
344 |
+
def _print_Pow(self, expr):
|
345 |
+
if expr.base.is_integer and not expr.exp.is_integer:
|
346 |
+
expr = type(expr)(Float(expr.base), expr.exp)
|
347 |
+
return self._print(expr)
|
348 |
+
return self._print_Function(expr)
|
349 |
+
|
350 |
+
def _print_Float(self, expr, _type=False):
|
351 |
+
ret = super()._print_Float(expr)
|
352 |
+
if _type:
|
353 |
+
return ret + '_f64'
|
354 |
+
else:
|
355 |
+
return ret
|
356 |
+
|
357 |
+
def _print_Integer(self, expr, _type=False):
|
358 |
+
ret = super()._print_Integer(expr)
|
359 |
+
if _type:
|
360 |
+
return ret + '_i32'
|
361 |
+
else:
|
362 |
+
return ret
|
363 |
+
|
364 |
+
def _print_Rational(self, expr):
|
365 |
+
p, q = int(expr.p), int(expr.q)
|
366 |
+
return '%d_f64/%d.0' % (p, q)
|
367 |
+
|
368 |
+
def _print_Relational(self, expr):
|
369 |
+
lhs_code = self._print(expr.lhs)
|
370 |
+
rhs_code = self._print(expr.rhs)
|
371 |
+
op = expr.rel_op
|
372 |
+
return "{} {} {}".format(lhs_code, op, rhs_code)
|
373 |
+
|
374 |
+
def _print_Indexed(self, expr):
|
375 |
+
# calculate index for 1d array
|
376 |
+
dims = expr.shape
|
377 |
+
elem = S.Zero
|
378 |
+
offset = S.One
|
379 |
+
for i in reversed(range(expr.rank)):
|
380 |
+
elem += expr.indices[i]*offset
|
381 |
+
offset *= dims[i]
|
382 |
+
return "%s[%s]" % (self._print(expr.base.label), self._print(elem))
|
383 |
+
|
384 |
+
def _print_Idx(self, expr):
|
385 |
+
return expr.label.name
|
386 |
+
|
387 |
+
def _print_Dummy(self, expr):
|
388 |
+
return expr.name
|
389 |
+
|
390 |
+
def _print_Exp1(self, expr, _type=False):
|
391 |
+
return "E"
|
392 |
+
|
393 |
+
def _print_Pi(self, expr, _type=False):
|
394 |
+
return 'PI'
|
395 |
+
|
396 |
+
def _print_Infinity(self, expr, _type=False):
|
397 |
+
return 'INFINITY'
|
398 |
+
|
399 |
+
def _print_NegativeInfinity(self, expr, _type=False):
|
400 |
+
return 'NEG_INFINITY'
|
401 |
+
|
402 |
+
def _print_BooleanTrue(self, expr, _type=False):
|
403 |
+
return "true"
|
404 |
+
|
405 |
+
def _print_BooleanFalse(self, expr, _type=False):
|
406 |
+
return "false"
|
407 |
+
|
408 |
+
def _print_bool(self, expr, _type=False):
|
409 |
+
return str(expr).lower()
|
410 |
+
|
411 |
+
def _print_NaN(self, expr, _type=False):
|
412 |
+
return "NAN"
|
413 |
+
|
414 |
+
def _print_Piecewise(self, expr):
|
415 |
+
if expr.args[-1].cond != True:
|
416 |
+
# We need the last conditional to be a True, otherwise the resulting
|
417 |
+
# function may not return a result.
|
418 |
+
raise ValueError("All Piecewise expressions must contain an "
|
419 |
+
"(expr, True) statement to be used as a default "
|
420 |
+
"condition. Without one, the generated "
|
421 |
+
"expression may not evaluate to anything under "
|
422 |
+
"some condition.")
|
423 |
+
lines = []
|
424 |
+
|
425 |
+
for i, (e, c) in enumerate(expr.args):
|
426 |
+
if i == 0:
|
427 |
+
lines.append("if (%s) {" % self._print(c))
|
428 |
+
elif i == len(expr.args) - 1 and c == True:
|
429 |
+
lines[-1] += " else {"
|
430 |
+
else:
|
431 |
+
lines[-1] += " else if (%s) {" % self._print(c)
|
432 |
+
code0 = self._print(e)
|
433 |
+
lines.append(code0)
|
434 |
+
lines.append("}")
|
435 |
+
|
436 |
+
if self._settings['inline']:
|
437 |
+
return " ".join(lines)
|
438 |
+
else:
|
439 |
+
return "\n".join(lines)
|
440 |
+
|
441 |
+
def _print_ITE(self, expr):
|
442 |
+
from sympy.functions import Piecewise
|
443 |
+
return self._print(expr.rewrite(Piecewise, deep=False))
|
444 |
+
|
445 |
+
def _print_MatrixBase(self, A):
|
446 |
+
if A.cols == 1:
|
447 |
+
return "[%s]" % ", ".join(self._print(a) for a in A)
|
448 |
+
else:
|
449 |
+
raise ValueError("Full Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).")
|
450 |
+
|
451 |
+
def _print_SparseRepMatrix(self, mat):
|
452 |
+
# do not allow sparse matrices to be made dense
|
453 |
+
return self._print_not_supported(mat)
|
454 |
+
|
455 |
+
def _print_MatrixElement(self, expr):
|
456 |
+
return "%s[%s]" % (expr.parent,
|
457 |
+
expr.j + expr.i*expr.parent.shape[1])
|
458 |
+
|
459 |
+
def _print_Symbol(self, expr):
|
460 |
+
|
461 |
+
name = super()._print_Symbol(expr)
|
462 |
+
|
463 |
+
if expr in self._dereference:
|
464 |
+
return '(*%s)' % name
|
465 |
+
else:
|
466 |
+
return name
|
467 |
+
|
468 |
+
def _print_Assignment(self, expr):
|
469 |
+
from sympy.tensor.indexed import IndexedBase
|
470 |
+
lhs = expr.lhs
|
471 |
+
rhs = expr.rhs
|
472 |
+
if self._settings["contract"] and (lhs.has(IndexedBase) or
|
473 |
+
rhs.has(IndexedBase)):
|
474 |
+
# Here we check if there is looping to be done, and if so
|
475 |
+
# print the required loops.
|
476 |
+
return self._doprint_loops(rhs, lhs)
|
477 |
+
else:
|
478 |
+
lhs_code = self._print(lhs)
|
479 |
+
rhs_code = self._print(rhs)
|
480 |
+
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
|
481 |
+
|
482 |
+
def indent_code(self, code):
|
483 |
+
"""Accepts a string of code or a list of code lines"""
|
484 |
+
|
485 |
+
if isinstance(code, str):
|
486 |
+
code_lines = self.indent_code(code.splitlines(True))
|
487 |
+
return ''.join(code_lines)
|
488 |
+
|
489 |
+
tab = " "
|
490 |
+
inc_token = ('{', '(', '{\n', '(\n')
|
491 |
+
dec_token = ('}', ')')
|
492 |
+
|
493 |
+
code = [ line.lstrip(' \t') for line in code ]
|
494 |
+
|
495 |
+
increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
|
496 |
+
decrease = [ int(any(map(line.startswith, dec_token)))
|
497 |
+
for line in code ]
|
498 |
+
|
499 |
+
pretty = []
|
500 |
+
level = 0
|
501 |
+
for n, line in enumerate(code):
|
502 |
+
if line in ('', '\n'):
|
503 |
+
pretty.append(line)
|
504 |
+
continue
|
505 |
+
level -= decrease[n]
|
506 |
+
pretty.append("%s%s" % (tab*level, line))
|
507 |
+
level += increase[n]
|
508 |
+
return pretty
|
509 |
+
|
510 |
+
|
511 |
+
def rust_code(expr, assign_to=None, **settings):
|
512 |
+
"""Converts an expr to a string of Rust code
|
513 |
+
|
514 |
+
Parameters
|
515 |
+
==========
|
516 |
+
|
517 |
+
expr : Expr
|
518 |
+
A SymPy expression to be converted.
|
519 |
+
assign_to : optional
|
520 |
+
When given, the argument is used as the name of the variable to which
|
521 |
+
the expression is assigned. Can be a string, ``Symbol``,
|
522 |
+
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
|
523 |
+
line-wrapping, or for expressions that generate multi-line statements.
|
524 |
+
precision : integer, optional
|
525 |
+
The precision for numbers such as pi [default=15].
|
526 |
+
user_functions : dict, optional
|
527 |
+
A dictionary where the keys are string representations of either
|
528 |
+
``FunctionClass`` or ``UndefinedFunction`` instances and the values
|
529 |
+
are their desired C string representations. Alternatively, the
|
530 |
+
dictionary value can be a list of tuples i.e. [(argument_test,
|
531 |
+
cfunction_string)]. See below for examples.
|
532 |
+
dereference : iterable, optional
|
533 |
+
An iterable of symbols that should be dereferenced in the printed code
|
534 |
+
expression. These would be values passed by address to the function.
|
535 |
+
For example, if ``dereference=[a]``, the resulting code would print
|
536 |
+
``(*a)`` instead of ``a``.
|
537 |
+
human : bool, optional
|
538 |
+
If True, the result is a single string that may contain some constant
|
539 |
+
declarations for the number symbols. If False, the same information is
|
540 |
+
returned in a tuple of (symbols_to_declare, not_supported_functions,
|
541 |
+
code_text). [default=True].
|
542 |
+
contract: bool, optional
|
543 |
+
If True, ``Indexed`` instances are assumed to obey tensor contraction
|
544 |
+
rules and the corresponding nested loops over indices are generated.
|
545 |
+
Setting contract=False will not generate loops, instead the user is
|
546 |
+
responsible to provide values for the indices in the code.
|
547 |
+
[default=True].
|
548 |
+
|
549 |
+
Examples
|
550 |
+
========
|
551 |
+
|
552 |
+
>>> from sympy import rust_code, symbols, Rational, sin, ceiling, Abs, Function
|
553 |
+
>>> x, tau = symbols("x, tau")
|
554 |
+
>>> rust_code((2*tau)**Rational(7, 2))
|
555 |
+
'8*1.4142135623731*tau.powf(7_f64/2.0)'
|
556 |
+
>>> rust_code(sin(x), assign_to="s")
|
557 |
+
's = x.sin();'
|
558 |
+
|
559 |
+
Simple custom printing can be defined for certain types by passing a
|
560 |
+
dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
|
561 |
+
Alternatively, the dictionary value can be a list of tuples i.e.
|
562 |
+
[(argument_test, cfunction_string)].
|
563 |
+
|
564 |
+
>>> custom_functions = {
|
565 |
+
... "ceiling": "CEIL",
|
566 |
+
... "Abs": [(lambda x: not x.is_integer, "fabs", 4),
|
567 |
+
... (lambda x: x.is_integer, "ABS", 4)],
|
568 |
+
... "func": "f"
|
569 |
+
... }
|
570 |
+
>>> func = Function('func')
|
571 |
+
>>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
|
572 |
+
'(fabs(x) + x.CEIL()).f()'
|
573 |
+
|
574 |
+
``Piecewise`` expressions are converted into conditionals. If an
|
575 |
+
``assign_to`` variable is provided an if statement is created, otherwise
|
576 |
+
the ternary operator is used. Note that if the ``Piecewise`` lacks a
|
577 |
+
default term, represented by ``(expr, True)`` then an error will be thrown.
|
578 |
+
This is to prevent generating an expression that may not evaluate to
|
579 |
+
anything.
|
580 |
+
|
581 |
+
>>> from sympy import Piecewise
|
582 |
+
>>> expr = Piecewise((x + 1, x > 0), (x, True))
|
583 |
+
>>> print(rust_code(expr, tau))
|
584 |
+
tau = if (x > 0) {
|
585 |
+
x + 1
|
586 |
+
} else {
|
587 |
+
x
|
588 |
+
};
|
589 |
+
|
590 |
+
Support for loops is provided through ``Indexed`` types. With
|
591 |
+
``contract=True`` these expressions will be turned into loops, whereas
|
592 |
+
``contract=False`` will just print the assignment expression that should be
|
593 |
+
looped over:
|
594 |
+
|
595 |
+
>>> from sympy import Eq, IndexedBase, Idx
|
596 |
+
>>> len_y = 5
|
597 |
+
>>> y = IndexedBase('y', shape=(len_y,))
|
598 |
+
>>> t = IndexedBase('t', shape=(len_y,))
|
599 |
+
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
|
600 |
+
>>> i = Idx('i', len_y-1)
|
601 |
+
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
|
602 |
+
>>> rust_code(e.rhs, assign_to=e.lhs, contract=False)
|
603 |
+
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
|
604 |
+
|
605 |
+
Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
|
606 |
+
must be provided to ``assign_to``. Note that any expression that can be
|
607 |
+
generated normally can also exist inside a Matrix:
|
608 |
+
|
609 |
+
>>> from sympy import Matrix, MatrixSymbol
|
610 |
+
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
|
611 |
+
>>> A = MatrixSymbol('A', 3, 1)
|
612 |
+
>>> print(rust_code(mat, A))
|
613 |
+
A = [x.powi(2), if (x > 0) {
|
614 |
+
x + 1
|
615 |
+
} else {
|
616 |
+
x
|
617 |
+
}, x.sin()];
|
618 |
+
"""
|
619 |
+
|
620 |
+
return RustCodePrinter(settings).doprint(expr, assign_to)
|
621 |
+
|
622 |
+
|
623 |
+
def print_rust_code(expr, **settings):
|
624 |
+
"""Prints Rust representation of the given expression."""
|
625 |
+
print(rust_code(expr, **settings))
|
venv/lib/python3.10/site-packages/sympy/printing/smtlib.py
ADDED
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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symbol, Expr, Float, Rational, Integer, Basic
|
6 |
+
from sympy.core.function import UndefinedFunction, Function
|
7 |
+
from sympy.core.relational import Relational, Unequality, Equality, LessThan, GreaterThan, StrictLessThan, StrictGreaterThan
|
8 |
+
from sympy.functions.elementary.complexes import Abs
|
9 |
+
from sympy.functions.elementary.exponential import exp, log, Pow
|
10 |
+
from sympy.functions.elementary.hyperbolic import sinh, cosh, tanh
|
11 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
12 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
13 |
+
from sympy.functions.elementary.trigonometric import sin, cos, tan, asin, acos, atan, atan2
|
14 |
+
from sympy.logic.boolalg import And, Or, Xor, Implies, Boolean
|
15 |
+
from sympy.logic.boolalg import BooleanTrue, BooleanFalse, BooleanFunction, Not, ITE
|
16 |
+
from sympy.printing.printer import Printer
|
17 |
+
from sympy.sets import Interval
|
18 |
+
|
19 |
+
|
20 |
+
class SMTLibPrinter(Printer):
|
21 |
+
printmethod = "_smtlib"
|
22 |
+
|
23 |
+
# based on dReal, an automated reasoning tool for solving problems that can be encoded as first-order logic formulas over the real numbers.
|
24 |
+
# dReal's special strength is in handling problems that involve a wide range of nonlinear real functions.
|
25 |
+
_default_settings: dict = {
|
26 |
+
'precision': None,
|
27 |
+
'known_types': {
|
28 |
+
bool: 'Bool',
|
29 |
+
int: 'Int',
|
30 |
+
float: 'Real'
|
31 |
+
},
|
32 |
+
'known_constants': {
|
33 |
+
# pi: 'MY_VARIABLE_PI_DECLARED_ELSEWHERE',
|
34 |
+
},
|
35 |
+
'known_functions': {
|
36 |
+
Add: '+',
|
37 |
+
Mul: '*',
|
38 |
+
|
39 |
+
Equality: '=',
|
40 |
+
LessThan: '<=',
|
41 |
+
GreaterThan: '>=',
|
42 |
+
StrictLessThan: '<',
|
43 |
+
StrictGreaterThan: '>',
|
44 |
+
|
45 |
+
exp: 'exp',
|
46 |
+
log: 'log',
|
47 |
+
Abs: 'abs',
|
48 |
+
sin: 'sin',
|
49 |
+
cos: 'cos',
|
50 |
+
tan: 'tan',
|
51 |
+
asin: 'arcsin',
|
52 |
+
acos: 'arccos',
|
53 |
+
atan: 'arctan',
|
54 |
+
atan2: 'arctan2',
|
55 |
+
sinh: 'sinh',
|
56 |
+
cosh: 'cosh',
|
57 |
+
tanh: 'tanh',
|
58 |
+
Min: 'min',
|
59 |
+
Max: 'max',
|
60 |
+
Pow: 'pow',
|
61 |
+
|
62 |
+
And: 'and',
|
63 |
+
Or: 'or',
|
64 |
+
Xor: 'xor',
|
65 |
+
Not: 'not',
|
66 |
+
ITE: 'ite',
|
67 |
+
Implies: '=>',
|
68 |
+
}
|
69 |
+
}
|
70 |
+
|
71 |
+
symbol_table: dict
|
72 |
+
|
73 |
+
def __init__(self, settings: typing.Optional[dict] = None,
|
74 |
+
symbol_table=None):
|
75 |
+
settings = settings or {}
|
76 |
+
self.symbol_table = symbol_table or {}
|
77 |
+
Printer.__init__(self, settings)
|
78 |
+
self._precision = self._settings['precision']
|
79 |
+
self._known_types = dict(self._settings['known_types'])
|
80 |
+
self._known_constants = dict(self._settings['known_constants'])
|
81 |
+
self._known_functions = dict(self._settings['known_functions'])
|
82 |
+
|
83 |
+
for _ in self._known_types.values(): assert self._is_legal_name(_)
|
84 |
+
for _ in self._known_constants.values(): assert self._is_legal_name(_)
|
85 |
+
# for _ in self._known_functions.values(): assert self._is_legal_name(_) # +, *, <, >, etc.
|
86 |
+
|
87 |
+
def _is_legal_name(self, s: str):
|
88 |
+
if not s: return False
|
89 |
+
if s[0].isnumeric(): return False
|
90 |
+
return all(_.isalnum() or _ == '_' for _ in s)
|
91 |
+
|
92 |
+
def _s_expr(self, op: str, args: typing.Union[list, tuple]) -> str:
|
93 |
+
args_str = ' '.join(
|
94 |
+
a if isinstance(a, str)
|
95 |
+
else self._print(a)
|
96 |
+
for a in args
|
97 |
+
)
|
98 |
+
return f'({op} {args_str})'
|
99 |
+
|
100 |
+
def _print_Function(self, e):
|
101 |
+
if e in self._known_functions:
|
102 |
+
op = self._known_functions[e]
|
103 |
+
elif type(e) in self._known_functions:
|
104 |
+
op = self._known_functions[type(e)]
|
105 |
+
elif type(type(e)) == UndefinedFunction:
|
106 |
+
op = e.name
|
107 |
+
else:
|
108 |
+
op = self._known_functions[e] # throw KeyError
|
109 |
+
|
110 |
+
return self._s_expr(op, e.args)
|
111 |
+
|
112 |
+
def _print_Relational(self, e: Relational):
|
113 |
+
return self._print_Function(e)
|
114 |
+
|
115 |
+
def _print_BooleanFunction(self, e: BooleanFunction):
|
116 |
+
return self._print_Function(e)
|
117 |
+
|
118 |
+
def _print_Expr(self, e: Expr):
|
119 |
+
return self._print_Function(e)
|
120 |
+
|
121 |
+
def _print_Unequality(self, e: Unequality):
|
122 |
+
if type(e) in self._known_functions:
|
123 |
+
return self._print_Relational(e) # default
|
124 |
+
else:
|
125 |
+
eq_op = self._known_functions[Equality]
|
126 |
+
not_op = self._known_functions[Not]
|
127 |
+
return self._s_expr(not_op, [self._s_expr(eq_op, e.args)])
|
128 |
+
|
129 |
+
def _print_Piecewise(self, e: Piecewise):
|
130 |
+
def _print_Piecewise_recursive(args: typing.Union[list, tuple]):
|
131 |
+
e, c = args[0]
|
132 |
+
if len(args) == 1:
|
133 |
+
assert (c is True) or isinstance(c, BooleanTrue)
|
134 |
+
return self._print(e)
|
135 |
+
else:
|
136 |
+
ite = self._known_functions[ITE]
|
137 |
+
return self._s_expr(ite, [
|
138 |
+
c, e, _print_Piecewise_recursive(args[1:])
|
139 |
+
])
|
140 |
+
|
141 |
+
return _print_Piecewise_recursive(e.args)
|
142 |
+
|
143 |
+
def _print_Interval(self, e: Interval):
|
144 |
+
if e.start.is_infinite and e.end.is_infinite:
|
145 |
+
return ''
|
146 |
+
elif e.start.is_infinite != e.end.is_infinite:
|
147 |
+
raise ValueError(f'One-sided intervals (`{e}`) are not supported in SMT.')
|
148 |
+
else:
|
149 |
+
return f'[{e.start}, {e.end}]'
|
150 |
+
|
151 |
+
# todo: Sympy does not support quantifiers yet as of 2022, but quantifiers can be handy in SMT.
|
152 |
+
# For now, users can extend this class and build in their own quantifier support.
|
153 |
+
# See `test_quantifier_extensions()` in test_smtlib.py for an example of how this might look.
|
154 |
+
|
155 |
+
# def _print_ForAll(self, e: ForAll):
|
156 |
+
# return self._s('forall', [
|
157 |
+
# self._s('', [
|
158 |
+
# self._s(sym.name, [self._type_name(sym), Interval(start, end)])
|
159 |
+
# for sym, start, end in e.limits
|
160 |
+
# ]),
|
161 |
+
# e.function
|
162 |
+
# ])
|
163 |
+
|
164 |
+
def _print_BooleanTrue(self, x: BooleanTrue):
|
165 |
+
return 'true'
|
166 |
+
|
167 |
+
def _print_BooleanFalse(self, x: BooleanFalse):
|
168 |
+
return 'false'
|
169 |
+
|
170 |
+
def _print_Float(self, x: Float):
|
171 |
+
f = x.evalf(self._precision) if self._precision else x.evalf()
|
172 |
+
return str(f).rstrip('0')
|
173 |
+
|
174 |
+
def _print_float(self, x: float):
|
175 |
+
return str(x)
|
176 |
+
|
177 |
+
def _print_Rational(self, x: Rational):
|
178 |
+
return self._s_expr('/', [x.p, x.q])
|
179 |
+
|
180 |
+
def _print_Integer(self, x: Integer):
|
181 |
+
assert x.q == 1
|
182 |
+
return str(x.p)
|
183 |
+
|
184 |
+
def _print_int(self, x: int):
|
185 |
+
return str(x)
|
186 |
+
|
187 |
+
def _print_Symbol(self, x: Symbol):
|
188 |
+
assert self._is_legal_name(x.name)
|
189 |
+
return x.name
|
190 |
+
|
191 |
+
def _print_NumberSymbol(self, x):
|
192 |
+
name = self._known_constants.get(x)
|
193 |
+
return name if name else self._print_Float(x)
|
194 |
+
|
195 |
+
def _print_UndefinedFunction(self, x):
|
196 |
+
assert self._is_legal_name(x.name)
|
197 |
+
return x.name
|
198 |
+
|
199 |
+
def _print_Exp1(self, x):
|
200 |
+
return (
|
201 |
+
self._print_Function(exp(1, evaluate=False))
|
202 |
+
if exp in self._known_functions else
|
203 |
+
self._print_NumberSymbol(x)
|
204 |
+
)
|
205 |
+
|
206 |
+
def emptyPrinter(self, expr):
|
207 |
+
raise NotImplementedError(f'Cannot convert `{repr(expr)}` of type `{type(expr)}` to SMT.')
|
208 |
+
|
209 |
+
|
210 |
+
def smtlib_code(
|
211 |
+
expr,
|
212 |
+
auto_assert=True, auto_declare=True,
|
213 |
+
precision=None,
|
214 |
+
symbol_table=None,
|
215 |
+
known_types=None, known_constants=None, known_functions=None,
|
216 |
+
prefix_expressions=None, suffix_expressions=None,
|
217 |
+
log_warn=None
|
218 |
+
):
|
219 |
+
r"""Converts ``expr`` to a string of smtlib code.
|
220 |
+
|
221 |
+
Parameters
|
222 |
+
==========
|
223 |
+
|
224 |
+
expr : Expr | List[Expr]
|
225 |
+
A SymPy expression or system to be converted.
|
226 |
+
auto_assert : bool, optional
|
227 |
+
If false, do not modify expr and produce only the S-Expression equivalent of expr.
|
228 |
+
If true, assume expr is a system and assert each boolean element.
|
229 |
+
auto_declare : bool, optional
|
230 |
+
If false, do not produce declarations for the symbols used in expr.
|
231 |
+
If true, prepend all necessary declarations for variables used in expr based on symbol_table.
|
232 |
+
precision : integer, optional
|
233 |
+
The ``evalf(..)`` precision for numbers such as pi.
|
234 |
+
symbol_table : dict, optional
|
235 |
+
A dictionary where keys are ``Symbol`` or ``Function`` instances and values are their Python type i.e. ``bool``, ``int``, ``float``, or ``Callable[...]``.
|
236 |
+
If incomplete, an attempt will be made to infer types from ``expr``.
|
237 |
+
known_types: dict, optional
|
238 |
+
A dictionary where keys are ``bool``, ``int``, ``float`` etc. and values are their corresponding SMT type names.
|
239 |
+
If not given, a partial listing compatible with several solvers will be used.
|
240 |
+
known_functions : dict, optional
|
241 |
+
A dictionary where keys are ``Function``, ``Relational``, ``BooleanFunction``, or ``Expr`` instances and values are their SMT string representations.
|
242 |
+
If not given, a partial listing optimized for dReal solver (but compatible with others) will be used.
|
243 |
+
known_constants: dict, optional
|
244 |
+
A dictionary where keys are ``NumberSymbol`` instances and values are their SMT variable names.
|
245 |
+
When using this feature, extra caution must be taken to avoid naming collisions between user symbols and listed constants.
|
246 |
+
If not given, constants will be expanded inline i.e. ``3.14159`` instead of ``MY_SMT_VARIABLE_FOR_PI``.
|
247 |
+
prefix_expressions: list, optional
|
248 |
+
A list of lists of ``str`` and/or expressions to convert into SMTLib and prefix to the output.
|
249 |
+
suffix_expressions: list, optional
|
250 |
+
A list of lists of ``str`` and/or expressions to convert into SMTLib and postfix to the output.
|
251 |
+
log_warn: lambda function, optional
|
252 |
+
A function to record all warnings during potentially risky operations.
|
253 |
+
Soundness is a core value in SMT solving, so it is good to log all assumptions made.
|
254 |
+
|
255 |
+
Examples
|
256 |
+
========
|
257 |
+
>>> from sympy import smtlib_code, symbols, sin, Eq
|
258 |
+
>>> x = symbols('x')
|
259 |
+
>>> smtlib_code(sin(x).series(x).removeO(), log_warn=print)
|
260 |
+
Could not infer type of `x`. Defaulting to float.
|
261 |
+
Non-Boolean expression `x**5/120 - x**3/6 + x` will not be asserted. Converting to SMTLib verbatim.
|
262 |
+
'(declare-const x Real)\n(+ x (* (/ -1 6) (pow x 3)) (* (/ 1 120) (pow x 5)))'
|
263 |
+
|
264 |
+
>>> from sympy import Rational
|
265 |
+
>>> x, y, tau = symbols("x, y, tau")
|
266 |
+
>>> smtlib_code((2*tau)**Rational(7, 2), log_warn=print)
|
267 |
+
Could not infer type of `tau`. Defaulting to float.
|
268 |
+
Non-Boolean expression `8*sqrt(2)*tau**(7/2)` will not be asserted. Converting to SMTLib verbatim.
|
269 |
+
'(declare-const tau Real)\n(* 8 (pow 2 (/ 1 2)) (pow tau (/ 7 2)))'
|
270 |
+
|
271 |
+
``Piecewise`` expressions are implemented with ``ite`` expressions by default.
|
272 |
+
Note that if the ``Piecewise`` lacks a default term, represented by
|
273 |
+
``(expr, True)`` then an error will be thrown. This is to prevent
|
274 |
+
generating an expression that may not evaluate to anything.
|
275 |
+
|
276 |
+
>>> from sympy import Piecewise
|
277 |
+
>>> pw = Piecewise((x + 1, x > 0), (x, True))
|
278 |
+
>>> smtlib_code(Eq(pw, 3), symbol_table={x: float}, log_warn=print)
|
279 |
+
'(declare-const x Real)\n(assert (= (ite (> x 0) (+ 1 x) x) 3))'
|
280 |
+
|
281 |
+
Custom printing can be defined for certain types by passing a dictionary of
|
282 |
+
PythonType : "SMT Name" to the ``known_types``, ``known_constants``, and ``known_functions`` kwargs.
|
283 |
+
|
284 |
+
>>> from typing import Callable
|
285 |
+
>>> from sympy import Function, Add
|
286 |
+
>>> f = Function('f')
|
287 |
+
>>> g = Function('g')
|
288 |
+
>>> smt_builtin_funcs = { # functions our SMT solver will understand
|
289 |
+
... f: "existing_smtlib_fcn",
|
290 |
+
... Add: "sum",
|
291 |
+
... }
|
292 |
+
>>> user_def_funcs = { # functions defined by the user must have their types specified explicitly
|
293 |
+
... g: Callable[[int], float],
|
294 |
+
... }
|
295 |
+
>>> smtlib_code(f(x) + g(x), symbol_table=user_def_funcs, known_functions=smt_builtin_funcs, log_warn=print)
|
296 |
+
Non-Boolean expression `f(x) + g(x)` will not be asserted. Converting to SMTLib verbatim.
|
297 |
+
'(declare-const x Int)\n(declare-fun g (Int) Real)\n(sum (existing_smtlib_fcn x) (g x))'
|
298 |
+
"""
|
299 |
+
log_warn = log_warn or (lambda _: None)
|
300 |
+
|
301 |
+
if not isinstance(expr, list): expr = [expr]
|
302 |
+
expr = [
|
303 |
+
sympy.sympify(_, strict=True, evaluate=False, convert_xor=False)
|
304 |
+
for _ in expr
|
305 |
+
]
|
306 |
+
|
307 |
+
if not symbol_table: symbol_table = {}
|
308 |
+
symbol_table = _auto_infer_smtlib_types(
|
309 |
+
*expr, symbol_table=symbol_table
|
310 |
+
)
|
311 |
+
# See [FALLBACK RULES]
|
312 |
+
# Need SMTLibPrinter to populate known_functions and known_constants first.
|
313 |
+
|
314 |
+
settings = {}
|
315 |
+
if precision: settings['precision'] = precision
|
316 |
+
del precision
|
317 |
+
|
318 |
+
if known_types: settings['known_types'] = known_types
|
319 |
+
del known_types
|
320 |
+
|
321 |
+
if known_functions: settings['known_functions'] = known_functions
|
322 |
+
del known_functions
|
323 |
+
|
324 |
+
if known_constants: settings['known_constants'] = known_constants
|
325 |
+
del known_constants
|
326 |
+
|
327 |
+
if not prefix_expressions: prefix_expressions = []
|
328 |
+
if not suffix_expressions: suffix_expressions = []
|
329 |
+
|
330 |
+
p = SMTLibPrinter(settings, symbol_table)
|
331 |
+
del symbol_table
|
332 |
+
|
333 |
+
# [FALLBACK RULES]
|
334 |
+
for e in expr:
|
335 |
+
for sym in e.atoms(Symbol, Function):
|
336 |
+
if (
|
337 |
+
sym.is_Symbol and
|
338 |
+
sym not in p._known_constants and
|
339 |
+
sym not in p.symbol_table
|
340 |
+
):
|
341 |
+
log_warn(f"Could not infer type of `{sym}`. Defaulting to float.")
|
342 |
+
p.symbol_table[sym] = float
|
343 |
+
if (
|
344 |
+
sym.is_Function and
|
345 |
+
type(sym) not in p._known_functions and
|
346 |
+
type(sym) not in p.symbol_table and
|
347 |
+
not sym.is_Piecewise
|
348 |
+
): raise TypeError(
|
349 |
+
f"Unknown type of undefined function `{sym}`. "
|
350 |
+
f"Must be mapped to ``str`` in known_functions or mapped to ``Callable[..]`` in symbol_table."
|
351 |
+
)
|
352 |
+
|
353 |
+
declarations = []
|
354 |
+
if auto_declare:
|
355 |
+
constants = {sym.name: sym for e in expr for sym in e.free_symbols
|
356 |
+
if sym not in p._known_constants}
|
357 |
+
functions = {fnc.name: fnc for e in expr for fnc in e.atoms(Function)
|
358 |
+
if type(fnc) not in p._known_functions and not fnc.is_Piecewise}
|
359 |
+
declarations = \
|
360 |
+
[
|
361 |
+
_auto_declare_smtlib(sym, p, log_warn)
|
362 |
+
for sym in constants.values()
|
363 |
+
] + [
|
364 |
+
_auto_declare_smtlib(fnc, p, log_warn)
|
365 |
+
for fnc in functions.values()
|
366 |
+
]
|
367 |
+
declarations = [decl for decl in declarations if decl]
|
368 |
+
|
369 |
+
if auto_assert:
|
370 |
+
expr = [_auto_assert_smtlib(e, p, log_warn) for e in expr]
|
371 |
+
|
372 |
+
# return SMTLibPrinter().doprint(expr)
|
373 |
+
return '\n'.join([
|
374 |
+
# ';; PREFIX EXPRESSIONS',
|
375 |
+
*[
|
376 |
+
e if isinstance(e, str) else p.doprint(e)
|
377 |
+
for e in prefix_expressions
|
378 |
+
],
|
379 |
+
|
380 |
+
# ';; DECLARATIONS',
|
381 |
+
*sorted(e for e in declarations),
|
382 |
+
|
383 |
+
# ';; EXPRESSIONS',
|
384 |
+
*[
|
385 |
+
e if isinstance(e, str) else p.doprint(e)
|
386 |
+
for e in expr
|
387 |
+
],
|
388 |
+
|
389 |
+
# ';; SUFFIX EXPRESSIONS',
|
390 |
+
*[
|
391 |
+
e if isinstance(e, str) else p.doprint(e)
|
392 |
+
for e in suffix_expressions
|
393 |
+
],
|
394 |
+
])
|
395 |
+
|
396 |
+
|
397 |
+
def _auto_declare_smtlib(sym: typing.Union[Symbol, Function], p: SMTLibPrinter, log_warn: typing.Callable[[str], None]):
|
398 |
+
if sym.is_Symbol:
|
399 |
+
type_signature = p.symbol_table[sym]
|
400 |
+
assert isinstance(type_signature, type)
|
401 |
+
type_signature = p._known_types[type_signature]
|
402 |
+
return p._s_expr('declare-const', [sym, type_signature])
|
403 |
+
|
404 |
+
elif sym.is_Function:
|
405 |
+
type_signature = p.symbol_table[type(sym)]
|
406 |
+
assert callable(type_signature)
|
407 |
+
type_signature = [p._known_types[_] for _ in type_signature.__args__]
|
408 |
+
assert len(type_signature) > 0
|
409 |
+
params_signature = f"({' '.join(type_signature[:-1])})"
|
410 |
+
return_signature = type_signature[-1]
|
411 |
+
return p._s_expr('declare-fun', [type(sym), params_signature, return_signature])
|
412 |
+
|
413 |
+
else:
|
414 |
+
log_warn(f"Non-Symbol/Function `{sym}` will not be declared.")
|
415 |
+
return None
|
416 |
+
|
417 |
+
|
418 |
+
def _auto_assert_smtlib(e: Expr, p: SMTLibPrinter, log_warn: typing.Callable[[str], None]):
|
419 |
+
if isinstance(e, Boolean) or (
|
420 |
+
e in p.symbol_table and p.symbol_table[e] == bool
|
421 |
+
) or (
|
422 |
+
e.is_Function and
|
423 |
+
type(e) in p.symbol_table and
|
424 |
+
p.symbol_table[type(e)].__args__[-1] == bool
|
425 |
+
):
|
426 |
+
return p._s_expr('assert', [e])
|
427 |
+
else:
|
428 |
+
log_warn(f"Non-Boolean expression `{e}` will not be asserted. Converting to SMTLib verbatim.")
|
429 |
+
return e
|
430 |
+
|
431 |
+
|
432 |
+
def _auto_infer_smtlib_types(
|
433 |
+
*exprs: Basic,
|
434 |
+
symbol_table: typing.Optional[dict] = None
|
435 |
+
) -> dict:
|
436 |
+
# [TYPE INFERENCE RULES]
|
437 |
+
# X is alone in an expr => X is bool
|
438 |
+
# X in BooleanFunction.args => X is bool
|
439 |
+
# X matches to a bool param of a symbol_table function => X is bool
|
440 |
+
# X matches to an int param of a symbol_table function => X is int
|
441 |
+
# X.is_integer => X is int
|
442 |
+
# X == Y, where X is T => Y is T
|
443 |
+
|
444 |
+
# [FALLBACK RULES]
|
445 |
+
# see _auto_declare_smtlib(..)
|
446 |
+
# X is not bool and X is not int and X is Symbol => X is float
|
447 |
+
# else (e.g. X is Function) => error. must be specified explicitly.
|
448 |
+
|
449 |
+
_symbols = dict(symbol_table) if symbol_table else {}
|
450 |
+
|
451 |
+
def safe_update(syms: set, inf):
|
452 |
+
for s in syms:
|
453 |
+
assert s.is_Symbol
|
454 |
+
if (old_type := _symbols.setdefault(s, inf)) != inf:
|
455 |
+
raise TypeError(f"Could not infer type of `{s}`. Apparently both `{old_type}` and `{inf}`?")
|
456 |
+
|
457 |
+
# EXPLICIT TYPES
|
458 |
+
safe_update({
|
459 |
+
e
|
460 |
+
for e in exprs
|
461 |
+
if e.is_Symbol
|
462 |
+
}, bool)
|
463 |
+
|
464 |
+
safe_update({
|
465 |
+
symbol
|
466 |
+
for e in exprs
|
467 |
+
for boolfunc in e.atoms(BooleanFunction)
|
468 |
+
for symbol in boolfunc.args
|
469 |
+
if symbol.is_Symbol
|
470 |
+
}, bool)
|
471 |
+
|
472 |
+
safe_update({
|
473 |
+
symbol
|
474 |
+
for e in exprs
|
475 |
+
for boolfunc in e.atoms(Function)
|
476 |
+
if type(boolfunc) in _symbols
|
477 |
+
for symbol, param in zip(boolfunc.args, _symbols[type(boolfunc)].__args__)
|
478 |
+
if symbol.is_Symbol and param == bool
|
479 |
+
}, bool)
|
480 |
+
|
481 |
+
safe_update({
|
482 |
+
symbol
|
483 |
+
for e in exprs
|
484 |
+
for intfunc in e.atoms(Function)
|
485 |
+
if type(intfunc) in _symbols
|
486 |
+
for symbol, param in zip(intfunc.args, _symbols[type(intfunc)].__args__)
|
487 |
+
if symbol.is_Symbol and param == int
|
488 |
+
}, int)
|
489 |
+
|
490 |
+
safe_update({
|
491 |
+
symbol
|
492 |
+
for e in exprs
|
493 |
+
for symbol in e.atoms(Symbol)
|
494 |
+
if symbol.is_integer
|
495 |
+
}, int)
|
496 |
+
|
497 |
+
safe_update({
|
498 |
+
symbol
|
499 |
+
for e in exprs
|
500 |
+
for symbol in e.atoms(Symbol)
|
501 |
+
if symbol.is_real and not symbol.is_integer
|
502 |
+
}, float)
|
503 |
+
|
504 |
+
# EQUALITY RELATION RULE
|
505 |
+
rels = [rel for expr in exprs for rel in expr.atoms(Equality)]
|
506 |
+
rels = [
|
507 |
+
(rel.lhs, rel.rhs) for rel in rels if rel.lhs.is_Symbol
|
508 |
+
] + [
|
509 |
+
(rel.rhs, rel.lhs) for rel in rels if rel.rhs.is_Symbol
|
510 |
+
]
|
511 |
+
for infer, reltd in rels:
|
512 |
+
inference = (
|
513 |
+
_symbols[infer] if infer in _symbols else
|
514 |
+
_symbols[reltd] if reltd in _symbols else
|
515 |
+
|
516 |
+
_symbols[type(reltd)].__args__[-1]
|
517 |
+
if reltd.is_Function and type(reltd) in _symbols else
|
518 |
+
|
519 |
+
bool if reltd.is_Boolean else
|
520 |
+
int if reltd.is_integer or reltd.is_Integer else
|
521 |
+
float if reltd.is_real else
|
522 |
+
None
|
523 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A Printer for generating readable representation of most SymPy classes.
|
3 |
+
"""
|
4 |
+
|
5 |
+
from __future__ import annotations
|
6 |
+
from typing import Any
|
7 |
+
|
8 |
+
from sympy.core import S, Rational, Pow, Basic, Mul, Number
|
9 |
+
from sympy.core.mul import _keep_coeff
|
10 |
+
from sympy.core.relational import Relational
|
11 |
+
from sympy.core.sorting import default_sort_key
|
12 |
+
from sympy.core.sympify import SympifyError
|
13 |
+
from sympy.utilities.iterables import sift
|
14 |
+
from .precedence import precedence, PRECEDENCE
|
15 |
+
from .printer import Printer, print_function
|
16 |
+
|
17 |
+
from mpmath.libmp import prec_to_dps, to_str as mlib_to_str
|
18 |
+
|
19 |
+
|
20 |
+
class StrPrinter(Printer):
|
21 |
+
printmethod = "_sympystr"
|
22 |
+
_default_settings: dict[str, Any] = {
|
23 |
+
"order": None,
|
24 |
+
"full_prec": "auto",
|
25 |
+
"sympy_integers": False,
|
26 |
+
"abbrev": False,
|
27 |
+
"perm_cyclic": True,
|
28 |
+
"min": None,
|
29 |
+
"max": None,
|
30 |
+
}
|
31 |
+
|
32 |
+
_relationals: dict[str, str] = {}
|
33 |
+
|
34 |
+
def parenthesize(self, item, level, strict=False):
|
35 |
+
if (precedence(item) < level) or ((not strict) and precedence(item) <= level):
|
36 |
+
return "(%s)" % self._print(item)
|
37 |
+
else:
|
38 |
+
return self._print(item)
|
39 |
+
|
40 |
+
def stringify(self, args, sep, level=0):
|
41 |
+
return sep.join([self.parenthesize(item, level) for item in args])
|
42 |
+
|
43 |
+
def emptyPrinter(self, expr):
|
44 |
+
if isinstance(expr, str):
|
45 |
+
return expr
|
46 |
+
elif isinstance(expr, Basic):
|
47 |
+
return repr(expr)
|
48 |
+
else:
|
49 |
+
return str(expr)
|
50 |
+
|
51 |
+
def _print_Add(self, expr, order=None):
|
52 |
+
terms = self._as_ordered_terms(expr, order=order)
|
53 |
+
|
54 |
+
prec = precedence(expr)
|
55 |
+
l = []
|
56 |
+
for term in terms:
|
57 |
+
t = self._print(term)
|
58 |
+
if t.startswith('-') and not term.is_Add:
|
59 |
+
sign = "-"
|
60 |
+
t = t[1:]
|
61 |
+
else:
|
62 |
+
sign = "+"
|
63 |
+
if precedence(term) < prec or term.is_Add:
|
64 |
+
l.extend([sign, "(%s)" % t])
|
65 |
+
else:
|
66 |
+
l.extend([sign, t])
|
67 |
+
sign = l.pop(0)
|
68 |
+
if sign == '+':
|
69 |
+
sign = ""
|
70 |
+
return sign + ' '.join(l)
|
71 |
+
|
72 |
+
def _print_BooleanTrue(self, expr):
|
73 |
+
return "True"
|
74 |
+
|
75 |
+
def _print_BooleanFalse(self, expr):
|
76 |
+
return "False"
|
77 |
+
|
78 |
+
def _print_Not(self, expr):
|
79 |
+
return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"]))
|
80 |
+
|
81 |
+
def _print_And(self, expr):
|
82 |
+
args = list(expr.args)
|
83 |
+
for j, i in enumerate(args):
|
84 |
+
if isinstance(i, Relational) and (
|
85 |
+
i.canonical.rhs is S.NegativeInfinity):
|
86 |
+
args.insert(0, args.pop(j))
|
87 |
+
return self.stringify(args, " & ", PRECEDENCE["BitwiseAnd"])
|
88 |
+
|
89 |
+
def _print_Or(self, expr):
|
90 |
+
return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"])
|
91 |
+
|
92 |
+
def _print_Xor(self, expr):
|
93 |
+
return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"])
|
94 |
+
|
95 |
+
def _print_AppliedPredicate(self, expr):
|
96 |
+
return '%s(%s)' % (
|
97 |
+
self._print(expr.function), self.stringify(expr.arguments, ", "))
|
98 |
+
|
99 |
+
def _print_Basic(self, expr):
|
100 |
+
l = [self._print(o) for o in expr.args]
|
101 |
+
return expr.__class__.__name__ + "(%s)" % ", ".join(l)
|
102 |
+
|
103 |
+
def _print_BlockMatrix(self, B):
|
104 |
+
if B.blocks.shape == (1, 1):
|
105 |
+
self._print(B.blocks[0, 0])
|
106 |
+
return self._print(B.blocks)
|
107 |
+
|
108 |
+
def _print_Catalan(self, expr):
|
109 |
+
return 'Catalan'
|
110 |
+
|
111 |
+
def _print_ComplexInfinity(self, expr):
|
112 |
+
return 'zoo'
|
113 |
+
|
114 |
+
def _print_ConditionSet(self, s):
|
115 |
+
args = tuple([self._print(i) for i in (s.sym, s.condition)])
|
116 |
+
if s.base_set is S.UniversalSet:
|
117 |
+
return 'ConditionSet(%s, %s)' % args
|
118 |
+
args += (self._print(s.base_set),)
|
119 |
+
return 'ConditionSet(%s, %s, %s)' % args
|
120 |
+
|
121 |
+
def _print_Derivative(self, expr):
|
122 |
+
dexpr = expr.expr
|
123 |
+
dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count]
|
124 |
+
return 'Derivative(%s)' % ", ".join((self._print(arg) for arg in [dexpr] + dvars))
|
125 |
+
|
126 |
+
def _print_dict(self, d):
|
127 |
+
keys = sorted(d.keys(), key=default_sort_key)
|
128 |
+
items = []
|
129 |
+
|
130 |
+
for key in keys:
|
131 |
+
item = "%s: %s" % (self._print(key), self._print(d[key]))
|
132 |
+
items.append(item)
|
133 |
+
|
134 |
+
return "{%s}" % ", ".join(items)
|
135 |
+
|
136 |
+
def _print_Dict(self, expr):
|
137 |
+
return self._print_dict(expr)
|
138 |
+
|
139 |
+
def _print_RandomDomain(self, d):
|
140 |
+
if hasattr(d, 'as_boolean'):
|
141 |
+
return 'Domain: ' + self._print(d.as_boolean())
|
142 |
+
elif hasattr(d, 'set'):
|
143 |
+
return ('Domain: ' + self._print(d.symbols) + ' in ' +
|
144 |
+
self._print(d.set))
|
145 |
+
else:
|
146 |
+
return 'Domain on ' + self._print(d.symbols)
|
147 |
+
|
148 |
+
def _print_Dummy(self, expr):
|
149 |
+
return '_' + expr.name
|
150 |
+
|
151 |
+
def _print_EulerGamma(self, expr):
|
152 |
+
return 'EulerGamma'
|
153 |
+
|
154 |
+
def _print_Exp1(self, expr):
|
155 |
+
return 'E'
|
156 |
+
|
157 |
+
def _print_ExprCondPair(self, expr):
|
158 |
+
return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond))
|
159 |
+
|
160 |
+
def _print_Function(self, expr):
|
161 |
+
return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ")
|
162 |
+
|
163 |
+
def _print_GoldenRatio(self, expr):
|
164 |
+
return 'GoldenRatio'
|
165 |
+
|
166 |
+
def _print_Heaviside(self, expr):
|
167 |
+
# Same as _print_Function but uses pargs to suppress default 1/2 for
|
168 |
+
# 2nd args
|
169 |
+
return expr.func.__name__ + "(%s)" % self.stringify(expr.pargs, ", ")
|
170 |
+
|
171 |
+
def _print_TribonacciConstant(self, expr):
|
172 |
+
return 'TribonacciConstant'
|
173 |
+
|
174 |
+
def _print_ImaginaryUnit(self, expr):
|
175 |
+
return 'I'
|
176 |
+
|
177 |
+
def _print_Infinity(self, expr):
|
178 |
+
return 'oo'
|
179 |
+
|
180 |
+
def _print_Integral(self, expr):
|
181 |
+
def _xab_tostr(xab):
|
182 |
+
if len(xab) == 1:
|
183 |
+
return self._print(xab[0])
|
184 |
+
else:
|
185 |
+
return self._print((xab[0],) + tuple(xab[1:]))
|
186 |
+
L = ', '.join([_xab_tostr(l) for l in expr.limits])
|
187 |
+
return 'Integral(%s, %s)' % (self._print(expr.function), L)
|
188 |
+
|
189 |
+
def _print_Interval(self, i):
|
190 |
+
fin = 'Interval{m}({a}, {b})'
|
191 |
+
a, b, l, r = i.args
|
192 |
+
if a.is_infinite and b.is_infinite:
|
193 |
+
m = ''
|
194 |
+
elif a.is_infinite and not r:
|
195 |
+
m = ''
|
196 |
+
elif b.is_infinite and not l:
|
197 |
+
m = ''
|
198 |
+
elif not l and not r:
|
199 |
+
m = ''
|
200 |
+
elif l and r:
|
201 |
+
m = '.open'
|
202 |
+
elif l:
|
203 |
+
m = '.Lopen'
|
204 |
+
else:
|
205 |
+
m = '.Ropen'
|
206 |
+
return fin.format(**{'a': a, 'b': b, 'm': m})
|
207 |
+
|
208 |
+
def _print_AccumulationBounds(self, i):
|
209 |
+
return "AccumBounds(%s, %s)" % (self._print(i.min),
|
210 |
+
self._print(i.max))
|
211 |
+
|
212 |
+
def _print_Inverse(self, I):
|
213 |
+
return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"])
|
214 |
+
|
215 |
+
def _print_Lambda(self, obj):
|
216 |
+
expr = obj.expr
|
217 |
+
sig = obj.signature
|
218 |
+
if len(sig) == 1 and sig[0].is_symbol:
|
219 |
+
sig = sig[0]
|
220 |
+
return "Lambda(%s, %s)" % (self._print(sig), self._print(expr))
|
221 |
+
|
222 |
+
def _print_LatticeOp(self, expr):
|
223 |
+
args = sorted(expr.args, key=default_sort_key)
|
224 |
+
return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args)
|
225 |
+
|
226 |
+
def _print_Limit(self, expr):
|
227 |
+
e, z, z0, dir = expr.args
|
228 |
+
return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print, (e, z, z0, dir)))
|
229 |
+
|
230 |
+
|
231 |
+
def _print_list(self, expr):
|
232 |
+
return "[%s]" % self.stringify(expr, ", ")
|
233 |
+
|
234 |
+
def _print_List(self, expr):
|
235 |
+
return self._print_list(expr)
|
236 |
+
|
237 |
+
def _print_MatrixBase(self, expr):
|
238 |
+
return expr._format_str(self)
|
239 |
+
|
240 |
+
def _print_MatrixElement(self, expr):
|
241 |
+
return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
|
242 |
+
+ '[%s, %s]' % (self._print(expr.i), self._print(expr.j))
|
243 |
+
|
244 |
+
def _print_MatrixSlice(self, expr):
|
245 |
+
def strslice(x, dim):
|
246 |
+
x = list(x)
|
247 |
+
if x[2] == 1:
|
248 |
+
del x[2]
|
249 |
+
if x[0] == 0:
|
250 |
+
x[0] = ''
|
251 |
+
if x[1] == dim:
|
252 |
+
x[1] = ''
|
253 |
+
return ':'.join((self._print(arg) for arg in x))
|
254 |
+
return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' +
|
255 |
+
strslice(expr.rowslice, expr.parent.rows) + ', ' +
|
256 |
+
strslice(expr.colslice, expr.parent.cols) + ']')
|
257 |
+
|
258 |
+
def _print_DeferredVector(self, expr):
|
259 |
+
return expr.name
|
260 |
+
|
261 |
+
def _print_Mul(self, expr):
|
262 |
+
|
263 |
+
prec = precedence(expr)
|
264 |
+
|
265 |
+
# Check for unevaluated Mul. In this case we need to make sure the
|
266 |
+
# identities are visible, multiple Rational factors are not combined
|
267 |
+
# etc so we display in a straight-forward form that fully preserves all
|
268 |
+
# args and their order.
|
269 |
+
args = expr.args
|
270 |
+
if args[0] is S.One or any(
|
271 |
+
isinstance(a, Number) or
|
272 |
+
a.is_Pow and all(ai.is_Integer for ai in a.args)
|
273 |
+
for a in args[1:]):
|
274 |
+
d, n = sift(args, lambda x:
|
275 |
+
isinstance(x, Pow) and bool(x.exp.as_coeff_Mul()[0] < 0),
|
276 |
+
binary=True)
|
277 |
+
for i, di in enumerate(d):
|
278 |
+
if di.exp.is_Number:
|
279 |
+
e = -di.exp
|
280 |
+
else:
|
281 |
+
dargs = list(di.exp.args)
|
282 |
+
dargs[0] = -dargs[0]
|
283 |
+
e = Mul._from_args(dargs)
|
284 |
+
d[i] = Pow(di.base, e, evaluate=False) if e - 1 else di.base
|
285 |
+
|
286 |
+
pre = []
|
287 |
+
# don't parenthesize first factor if negative
|
288 |
+
if n and not n[0].is_Add and n[0].could_extract_minus_sign():
|
289 |
+
pre = [self._print(n.pop(0))]
|
290 |
+
|
291 |
+
nfactors = pre + [self.parenthesize(a, prec, strict=False)
|
292 |
+
for a in n]
|
293 |
+
if not nfactors:
|
294 |
+
nfactors = ['1']
|
295 |
+
|
296 |
+
# don't parenthesize first of denominator unless singleton
|
297 |
+
if len(d) > 1 and d[0].could_extract_minus_sign():
|
298 |
+
pre = [self._print(d.pop(0))]
|
299 |
+
else:
|
300 |
+
pre = []
|
301 |
+
dfactors = pre + [self.parenthesize(a, prec, strict=False)
|
302 |
+
for a in d]
|
303 |
+
|
304 |
+
n = '*'.join(nfactors)
|
305 |
+
d = '*'.join(dfactors)
|
306 |
+
if len(dfactors) > 1:
|
307 |
+
return '%s/(%s)' % (n, d)
|
308 |
+
elif dfactors:
|
309 |
+
return '%s/%s' % (n, d)
|
310 |
+
return n
|
311 |
+
|
312 |
+
c, e = expr.as_coeff_Mul()
|
313 |
+
if c < 0:
|
314 |
+
expr = _keep_coeff(-c, e)
|
315 |
+
sign = "-"
|
316 |
+
else:
|
317 |
+
sign = ""
|
318 |
+
|
319 |
+
a = [] # items in the numerator
|
320 |
+
b = [] # items that are in the denominator (if any)
|
321 |
+
|
322 |
+
pow_paren = [] # Will collect all pow with more than one base element and exp = -1
|
323 |
+
|
324 |
+
if self.order not in ('old', 'none'):
|
325 |
+
args = expr.as_ordered_factors()
|
326 |
+
else:
|
327 |
+
# use make_args in case expr was something like -x -> x
|
328 |
+
args = Mul.make_args(expr)
|
329 |
+
|
330 |
+
# Gather args for numerator/denominator
|
331 |
+
def apow(i):
|
332 |
+
b, e = i.as_base_exp()
|
333 |
+
eargs = list(Mul.make_args(e))
|
334 |
+
if eargs[0] is S.NegativeOne:
|
335 |
+
eargs = eargs[1:]
|
336 |
+
else:
|
337 |
+
eargs[0] = -eargs[0]
|
338 |
+
e = Mul._from_args(eargs)
|
339 |
+
if isinstance(i, Pow):
|
340 |
+
return i.func(b, e, evaluate=False)
|
341 |
+
return i.func(e, evaluate=False)
|
342 |
+
for item in args:
|
343 |
+
if (item.is_commutative and
|
344 |
+
isinstance(item, Pow) and
|
345 |
+
bool(item.exp.as_coeff_Mul()[0] < 0)):
|
346 |
+
if item.exp is not S.NegativeOne:
|
347 |
+
b.append(apow(item))
|
348 |
+
else:
|
349 |
+
if (len(item.args[0].args) != 1 and
|
350 |
+
isinstance(item.base, (Mul, Pow))):
|
351 |
+
# To avoid situations like #14160
|
352 |
+
pow_paren.append(item)
|
353 |
+
b.append(item.base)
|
354 |
+
elif item.is_Rational and item is not S.Infinity:
|
355 |
+
if item.p != 1:
|
356 |
+
a.append(Rational(item.p))
|
357 |
+
if item.q != 1:
|
358 |
+
b.append(Rational(item.q))
|
359 |
+
else:
|
360 |
+
a.append(item)
|
361 |
+
|
362 |
+
a = a or [S.One]
|
363 |
+
|
364 |
+
a_str = [self.parenthesize(x, prec, strict=False) for x in a]
|
365 |
+
b_str = [self.parenthesize(x, prec, strict=False) for x in b]
|
366 |
+
|
367 |
+
# To parenthesize Pow with exp = -1 and having more than one Symbol
|
368 |
+
for item in pow_paren:
|
369 |
+
if item.base in b:
|
370 |
+
b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
|
371 |
+
|
372 |
+
if not b:
|
373 |
+
return sign + '*'.join(a_str)
|
374 |
+
elif len(b) == 1:
|
375 |
+
return sign + '*'.join(a_str) + "/" + b_str[0]
|
376 |
+
else:
|
377 |
+
return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
|
378 |
+
|
379 |
+
def _print_MatMul(self, expr):
|
380 |
+
c, m = expr.as_coeff_mmul()
|
381 |
+
|
382 |
+
sign = ""
|
383 |
+
if c.is_number:
|
384 |
+
re, im = c.as_real_imag()
|
385 |
+
if im.is_zero and re.is_negative:
|
386 |
+
expr = _keep_coeff(-c, m)
|
387 |
+
sign = "-"
|
388 |
+
elif re.is_zero and im.is_negative:
|
389 |
+
expr = _keep_coeff(-c, m)
|
390 |
+
sign = "-"
|
391 |
+
|
392 |
+
return sign + '*'.join(
|
393 |
+
[self.parenthesize(arg, precedence(expr)) for arg in expr.args]
|
394 |
+
)
|
395 |
+
|
396 |
+
def _print_ElementwiseApplyFunction(self, expr):
|
397 |
+
return "{}.({})".format(
|
398 |
+
expr.function,
|
399 |
+
self._print(expr.expr),
|
400 |
+
)
|
401 |
+
|
402 |
+
def _print_NaN(self, expr):
|
403 |
+
return 'nan'
|
404 |
+
|
405 |
+
def _print_NegativeInfinity(self, expr):
|
406 |
+
return '-oo'
|
407 |
+
|
408 |
+
def _print_Order(self, expr):
|
409 |
+
if not expr.variables or all(p is S.Zero for p in expr.point):
|
410 |
+
if len(expr.variables) <= 1:
|
411 |
+
return 'O(%s)' % self._print(expr.expr)
|
412 |
+
else:
|
413 |
+
return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0)
|
414 |
+
else:
|
415 |
+
return 'O(%s)' % self.stringify(expr.args, ', ', 0)
|
416 |
+
|
417 |
+
def _print_Ordinal(self, expr):
|
418 |
+
return expr.__str__()
|
419 |
+
|
420 |
+
def _print_Cycle(self, expr):
|
421 |
+
return expr.__str__()
|
422 |
+
|
423 |
+
def _print_Permutation(self, expr):
|
424 |
+
from sympy.combinatorics.permutations import Permutation, Cycle
|
425 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
426 |
+
|
427 |
+
perm_cyclic = Permutation.print_cyclic
|
428 |
+
if perm_cyclic is not None:
|
429 |
+
sympy_deprecation_warning(
|
430 |
+
f"""
|
431 |
+
Setting Permutation.print_cyclic is deprecated. Instead use
|
432 |
+
init_printing(perm_cyclic={perm_cyclic}).
|
433 |
+
""",
|
434 |
+
deprecated_since_version="1.6",
|
435 |
+
active_deprecations_target="deprecated-permutation-print_cyclic",
|
436 |
+
stacklevel=7,
|
437 |
+
)
|
438 |
+
else:
|
439 |
+
perm_cyclic = self._settings.get("perm_cyclic", True)
|
440 |
+
|
441 |
+
if perm_cyclic:
|
442 |
+
if not expr.size:
|
443 |
+
return '()'
|
444 |
+
# before taking Cycle notation, see if the last element is
|
445 |
+
# a singleton and move it to the head of the string
|
446 |
+
s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):]
|
447 |
+
last = s.rfind('(')
|
448 |
+
if not last == 0 and ',' not in s[last:]:
|
449 |
+
s = s[last:] + s[:last]
|
450 |
+
s = s.replace(',', '')
|
451 |
+
return s
|
452 |
+
else:
|
453 |
+
s = expr.support()
|
454 |
+
if not s:
|
455 |
+
if expr.size < 5:
|
456 |
+
return 'Permutation(%s)' % self._print(expr.array_form)
|
457 |
+
return 'Permutation([], size=%s)' % self._print(expr.size)
|
458 |
+
trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size)
|
459 |
+
use = full = self._print(expr.array_form)
|
460 |
+
if len(trim) < len(full):
|
461 |
+
use = trim
|
462 |
+
return 'Permutation(%s)' % use
|
463 |
+
|
464 |
+
def _print_Subs(self, obj):
|
465 |
+
expr, old, new = obj.args
|
466 |
+
if len(obj.point) == 1:
|
467 |
+
old = old[0]
|
468 |
+
new = new[0]
|
469 |
+
return "Subs(%s, %s, %s)" % (
|
470 |
+
self._print(expr), self._print(old), self._print(new))
|
471 |
+
|
472 |
+
def _print_TensorIndex(self, expr):
|
473 |
+
return expr._print()
|
474 |
+
|
475 |
+
def _print_TensorHead(self, expr):
|
476 |
+
return expr._print()
|
477 |
+
|
478 |
+
def _print_Tensor(self, expr):
|
479 |
+
return expr._print()
|
480 |
+
|
481 |
+
def _print_TensMul(self, expr):
|
482 |
+
# prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)"
|
483 |
+
sign, args = expr._get_args_for_traditional_printer()
|
484 |
+
return sign + "*".join(
|
485 |
+
[self.parenthesize(arg, precedence(expr)) for arg in args]
|
486 |
+
)
|
487 |
+
|
488 |
+
def _print_TensAdd(self, expr):
|
489 |
+
return expr._print()
|
490 |
+
|
491 |
+
def _print_ArraySymbol(self, expr):
|
492 |
+
return self._print(expr.name)
|
493 |
+
|
494 |
+
def _print_ArrayElement(self, expr):
|
495 |
+
return "%s[%s]" % (
|
496 |
+
self.parenthesize(expr.name, PRECEDENCE["Func"], True), ", ".join([self._print(i) for i in expr.indices]))
|
497 |
+
|
498 |
+
def _print_PermutationGroup(self, expr):
|
499 |
+
p = [' %s' % self._print(a) for a in expr.args]
|
500 |
+
return 'PermutationGroup([\n%s])' % ',\n'.join(p)
|
501 |
+
|
502 |
+
def _print_Pi(self, expr):
|
503 |
+
return 'pi'
|
504 |
+
|
505 |
+
def _print_PolyRing(self, ring):
|
506 |
+
return "Polynomial ring in %s over %s with %s order" % \
|
507 |
+
(", ".join((self._print(rs) for rs in ring.symbols)),
|
508 |
+
self._print(ring.domain), self._print(ring.order))
|
509 |
+
|
510 |
+
def _print_FracField(self, field):
|
511 |
+
return "Rational function field in %s over %s with %s order" % \
|
512 |
+
(", ".join((self._print(fs) for fs in field.symbols)),
|
513 |
+
self._print(field.domain), self._print(field.order))
|
514 |
+
|
515 |
+
def _print_FreeGroupElement(self, elm):
|
516 |
+
return elm.__str__()
|
517 |
+
|
518 |
+
def _print_GaussianElement(self, poly):
|
519 |
+
return "(%s + %s*I)" % (poly.x, poly.y)
|
520 |
+
|
521 |
+
def _print_PolyElement(self, poly):
|
522 |
+
return poly.str(self, PRECEDENCE, "%s**%s", "*")
|
523 |
+
|
524 |
+
def _print_FracElement(self, frac):
|
525 |
+
if frac.denom == 1:
|
526 |
+
return self._print(frac.numer)
|
527 |
+
else:
|
528 |
+
numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True)
|
529 |
+
denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True)
|
530 |
+
return numer + "/" + denom
|
531 |
+
|
532 |
+
def _print_Poly(self, expr):
|
533 |
+
ATOM_PREC = PRECEDENCE["Atom"] - 1
|
534 |
+
terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ]
|
535 |
+
|
536 |
+
for monom, coeff in expr.terms():
|
537 |
+
s_monom = []
|
538 |
+
|
539 |
+
for i, e in enumerate(monom):
|
540 |
+
if e > 0:
|
541 |
+
if e == 1:
|
542 |
+
s_monom.append(gens[i])
|
543 |
+
else:
|
544 |
+
s_monom.append(gens[i] + "**%d" % e)
|
545 |
+
|
546 |
+
s_monom = "*".join(s_monom)
|
547 |
+
|
548 |
+
if coeff.is_Add:
|
549 |
+
if s_monom:
|
550 |
+
s_coeff = "(" + self._print(coeff) + ")"
|
551 |
+
else:
|
552 |
+
s_coeff = self._print(coeff)
|
553 |
+
else:
|
554 |
+
if s_monom:
|
555 |
+
if coeff is S.One:
|
556 |
+
terms.extend(['+', s_monom])
|
557 |
+
continue
|
558 |
+
|
559 |
+
if coeff is S.NegativeOne:
|
560 |
+
terms.extend(['-', s_monom])
|
561 |
+
continue
|
562 |
+
|
563 |
+
s_coeff = self._print(coeff)
|
564 |
+
|
565 |
+
if not s_monom:
|
566 |
+
s_term = s_coeff
|
567 |
+
else:
|
568 |
+
s_term = s_coeff + "*" + s_monom
|
569 |
+
|
570 |
+
if s_term.startswith('-'):
|
571 |
+
terms.extend(['-', s_term[1:]])
|
572 |
+
else:
|
573 |
+
terms.extend(['+', s_term])
|
574 |
+
|
575 |
+
if terms[0] in ('-', '+'):
|
576 |
+
modifier = terms.pop(0)
|
577 |
+
|
578 |
+
if modifier == '-':
|
579 |
+
terms[0] = '-' + terms[0]
|
580 |
+
|
581 |
+
format = expr.__class__.__name__ + "(%s, %s"
|
582 |
+
|
583 |
+
from sympy.polys.polyerrors import PolynomialError
|
584 |
+
|
585 |
+
try:
|
586 |
+
format += ", modulus=%s" % expr.get_modulus()
|
587 |
+
except PolynomialError:
|
588 |
+
format += ", domain='%s'" % expr.get_domain()
|
589 |
+
|
590 |
+
format += ")"
|
591 |
+
|
592 |
+
for index, item in enumerate(gens):
|
593 |
+
if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"):
|
594 |
+
gens[index] = item[1:len(item) - 1]
|
595 |
+
|
596 |
+
return format % (' '.join(terms), ', '.join(gens))
|
597 |
+
|
598 |
+
def _print_UniversalSet(self, p):
|
599 |
+
return 'UniversalSet'
|
600 |
+
|
601 |
+
def _print_AlgebraicNumber(self, expr):
|
602 |
+
if expr.is_aliased:
|
603 |
+
return self._print(expr.as_poly().as_expr())
|
604 |
+
else:
|
605 |
+
return self._print(expr.as_expr())
|
606 |
+
|
607 |
+
def _print_Pow(self, expr, rational=False):
|
608 |
+
"""Printing helper function for ``Pow``
|
609 |
+
|
610 |
+
Parameters
|
611 |
+
==========
|
612 |
+
|
613 |
+
rational : bool, optional
|
614 |
+
If ``True``, it will not attempt printing ``sqrt(x)`` or
|
615 |
+
``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)``
|
616 |
+
instead.
|
617 |
+
|
618 |
+
See examples for additional details
|
619 |
+
|
620 |
+
Examples
|
621 |
+
========
|
622 |
+
|
623 |
+
>>> from sympy import sqrt, StrPrinter
|
624 |
+
>>> from sympy.abc import x
|
625 |
+
|
626 |
+
How ``rational`` keyword works with ``sqrt``:
|
627 |
+
|
628 |
+
>>> printer = StrPrinter()
|
629 |
+
>>> printer._print_Pow(sqrt(x), rational=True)
|
630 |
+
'x**(1/2)'
|
631 |
+
>>> printer._print_Pow(sqrt(x), rational=False)
|
632 |
+
'sqrt(x)'
|
633 |
+
>>> printer._print_Pow(1/sqrt(x), rational=True)
|
634 |
+
'x**(-1/2)'
|
635 |
+
>>> printer._print_Pow(1/sqrt(x), rational=False)
|
636 |
+
'1/sqrt(x)'
|
637 |
+
|
638 |
+
Notes
|
639 |
+
=====
|
640 |
+
|
641 |
+
``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy,
|
642 |
+
so there is no need of defining a separate printer for ``sqrt``.
|
643 |
+
Instead, it should be handled here as well.
|
644 |
+
"""
|
645 |
+
PREC = precedence(expr)
|
646 |
+
|
647 |
+
if expr.exp is S.Half and not rational:
|
648 |
+
return "sqrt(%s)" % self._print(expr.base)
|
649 |
+
|
650 |
+
if expr.is_commutative:
|
651 |
+
if -expr.exp is S.Half and not rational:
|
652 |
+
# Note: Don't test "expr.exp == -S.Half" here, because that will
|
653 |
+
# match -0.5, which we don't want.
|
654 |
+
return "%s/sqrt(%s)" % tuple((self._print(arg) for arg in (S.One, expr.base)))
|
655 |
+
if expr.exp is -S.One:
|
656 |
+
# Similarly to the S.Half case, don't test with "==" here.
|
657 |
+
return '%s/%s' % (self._print(S.One),
|
658 |
+
self.parenthesize(expr.base, PREC, strict=False))
|
659 |
+
|
660 |
+
e = self.parenthesize(expr.exp, PREC, strict=False)
|
661 |
+
if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1:
|
662 |
+
# the parenthesized exp should be '(Rational(a, b))' so strip parens,
|
663 |
+
# but just check to be sure.
|
664 |
+
if e.startswith('(Rational'):
|
665 |
+
return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1])
|
666 |
+
return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e)
|
667 |
+
|
668 |
+
def _print_UnevaluatedExpr(self, expr):
|
669 |
+
return self._print(expr.args[0])
|
670 |
+
|
671 |
+
def _print_MatPow(self, expr):
|
672 |
+
PREC = precedence(expr)
|
673 |
+
return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False),
|
674 |
+
self.parenthesize(expr.exp, PREC, strict=False))
|
675 |
+
|
676 |
+
def _print_Integer(self, expr):
|
677 |
+
if self._settings.get("sympy_integers", False):
|
678 |
+
return "S(%s)" % (expr)
|
679 |
+
return str(expr.p)
|
680 |
+
|
681 |
+
def _print_Integers(self, expr):
|
682 |
+
return 'Integers'
|
683 |
+
|
684 |
+
def _print_Naturals(self, expr):
|
685 |
+
return 'Naturals'
|
686 |
+
|
687 |
+
def _print_Naturals0(self, expr):
|
688 |
+
return 'Naturals0'
|
689 |
+
|
690 |
+
def _print_Rationals(self, expr):
|
691 |
+
return 'Rationals'
|
692 |
+
|
693 |
+
def _print_Reals(self, expr):
|
694 |
+
return 'Reals'
|
695 |
+
|
696 |
+
def _print_Complexes(self, expr):
|
697 |
+
return 'Complexes'
|
698 |
+
|
699 |
+
def _print_EmptySet(self, expr):
|
700 |
+
return 'EmptySet'
|
701 |
+
|
702 |
+
def _print_EmptySequence(self, expr):
|
703 |
+
return 'EmptySequence'
|
704 |
+
|
705 |
+
def _print_int(self, expr):
|
706 |
+
return str(expr)
|
707 |
+
|
708 |
+
def _print_mpz(self, expr):
|
709 |
+
return str(expr)
|
710 |
+
|
711 |
+
def _print_Rational(self, expr):
|
712 |
+
if expr.q == 1:
|
713 |
+
return str(expr.p)
|
714 |
+
else:
|
715 |
+
if self._settings.get("sympy_integers", False):
|
716 |
+
return "S(%s)/%s" % (expr.p, expr.q)
|
717 |
+
return "%s/%s" % (expr.p, expr.q)
|
718 |
+
|
719 |
+
def _print_PythonRational(self, expr):
|
720 |
+
if expr.q == 1:
|
721 |
+
return str(expr.p)
|
722 |
+
else:
|
723 |
+
return "%d/%d" % (expr.p, expr.q)
|
724 |
+
|
725 |
+
def _print_Fraction(self, expr):
|
726 |
+
if expr.denominator == 1:
|
727 |
+
return str(expr.numerator)
|
728 |
+
else:
|
729 |
+
return "%s/%s" % (expr.numerator, expr.denominator)
|
730 |
+
|
731 |
+
def _print_mpq(self, expr):
|
732 |
+
if expr.denominator == 1:
|
733 |
+
return str(expr.numerator)
|
734 |
+
else:
|
735 |
+
return "%s/%s" % (expr.numerator, expr.denominator)
|
736 |
+
|
737 |
+
def _print_Float(self, expr):
|
738 |
+
prec = expr._prec
|
739 |
+
if prec < 5:
|
740 |
+
dps = 0
|
741 |
+
else:
|
742 |
+
dps = prec_to_dps(expr._prec)
|
743 |
+
if self._settings["full_prec"] is True:
|
744 |
+
strip = False
|
745 |
+
elif self._settings["full_prec"] is False:
|
746 |
+
strip = True
|
747 |
+
elif self._settings["full_prec"] == "auto":
|
748 |
+
strip = self._print_level > 1
|
749 |
+
low = self._settings["min"] if "min" in self._settings else None
|
750 |
+
high = self._settings["max"] if "max" in self._settings else None
|
751 |
+
rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high)
|
752 |
+
if rv.startswith('-.0'):
|
753 |
+
rv = '-0.' + rv[3:]
|
754 |
+
elif rv.startswith('.0'):
|
755 |
+
rv = '0.' + rv[2:]
|
756 |
+
if rv.startswith('+'):
|
757 |
+
# e.g., +inf -> inf
|
758 |
+
rv = rv[1:]
|
759 |
+
return rv
|
760 |
+
|
761 |
+
def _print_Relational(self, expr):
|
762 |
+
|
763 |
+
charmap = {
|
764 |
+
"==": "Eq",
|
765 |
+
"!=": "Ne",
|
766 |
+
":=": "Assignment",
|
767 |
+
'+=': "AddAugmentedAssignment",
|
768 |
+
"-=": "SubAugmentedAssignment",
|
769 |
+
"*=": "MulAugmentedAssignment",
|
770 |
+
"/=": "DivAugmentedAssignment",
|
771 |
+
"%=": "ModAugmentedAssignment",
|
772 |
+
}
|
773 |
+
|
774 |
+
if expr.rel_op in charmap:
|
775 |
+
return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs),
|
776 |
+
self._print(expr.rhs))
|
777 |
+
|
778 |
+
return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)),
|
779 |
+
self._relationals.get(expr.rel_op) or expr.rel_op,
|
780 |
+
self.parenthesize(expr.rhs, precedence(expr)))
|
781 |
+
|
782 |
+
def _print_ComplexRootOf(self, expr):
|
783 |
+
return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'),
|
784 |
+
expr.index)
|
785 |
+
|
786 |
+
def _print_RootSum(self, expr):
|
787 |
+
args = [self._print_Add(expr.expr, order='lex')]
|
788 |
+
|
789 |
+
if expr.fun is not S.IdentityFunction:
|
790 |
+
args.append(self._print(expr.fun))
|
791 |
+
|
792 |
+
return "RootSum(%s)" % ", ".join(args)
|
793 |
+
|
794 |
+
def _print_GroebnerBasis(self, basis):
|
795 |
+
cls = basis.__class__.__name__
|
796 |
+
|
797 |
+
exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs]
|
798 |
+
exprs = "[%s]" % ", ".join(exprs)
|
799 |
+
|
800 |
+
gens = [ self._print(gen) for gen in basis.gens ]
|
801 |
+
domain = "domain='%s'" % self._print(basis.domain)
|
802 |
+
order = "order='%s'" % self._print(basis.order)
|
803 |
+
|
804 |
+
args = [exprs] + gens + [domain, order]
|
805 |
+
|
806 |
+
return "%s(%s)" % (cls, ", ".join(args))
|
807 |
+
|
808 |
+
def _print_set(self, s):
|
809 |
+
items = sorted(s, key=default_sort_key)
|
810 |
+
|
811 |
+
args = ', '.join(self._print(item) for item in items)
|
812 |
+
if not args:
|
813 |
+
return "set()"
|
814 |
+
return '{%s}' % args
|
815 |
+
|
816 |
+
def _print_FiniteSet(self, s):
|
817 |
+
from sympy.sets.sets import FiniteSet
|
818 |
+
items = sorted(s, key=default_sort_key)
|
819 |
+
|
820 |
+
args = ', '.join(self._print(item) for item in items)
|
821 |
+
if any(item.has(FiniteSet) for item in items):
|
822 |
+
return 'FiniteSet({})'.format(args)
|
823 |
+
return '{{{}}}'.format(args)
|
824 |
+
|
825 |
+
def _print_Partition(self, s):
|
826 |
+
items = sorted(s, key=default_sort_key)
|
827 |
+
|
828 |
+
args = ', '.join(self._print(arg) for arg in items)
|
829 |
+
return 'Partition({})'.format(args)
|
830 |
+
|
831 |
+
def _print_frozenset(self, s):
|
832 |
+
if not s:
|
833 |
+
return "frozenset()"
|
834 |
+
return "frozenset(%s)" % self._print_set(s)
|
835 |
+
|
836 |
+
def _print_Sum(self, expr):
|
837 |
+
def _xab_tostr(xab):
|
838 |
+
if len(xab) == 1:
|
839 |
+
return self._print(xab[0])
|
840 |
+
else:
|
841 |
+
return self._print((xab[0],) + tuple(xab[1:]))
|
842 |
+
L = ', '.join([_xab_tostr(l) for l in expr.limits])
|
843 |
+
return 'Sum(%s, %s)' % (self._print(expr.function), L)
|
844 |
+
|
845 |
+
def _print_Symbol(self, expr):
|
846 |
+
return expr.name
|
847 |
+
_print_MatrixSymbol = _print_Symbol
|
848 |
+
_print_RandomSymbol = _print_Symbol
|
849 |
+
|
850 |
+
def _print_Identity(self, expr):
|
851 |
+
return "I"
|
852 |
+
|
853 |
+
def _print_ZeroMatrix(self, expr):
|
854 |
+
return "0"
|
855 |
+
|
856 |
+
def _print_OneMatrix(self, expr):
|
857 |
+
return "1"
|
858 |
+
|
859 |
+
def _print_Predicate(self, expr):
|
860 |
+
return "Q.%s" % expr.name
|
861 |
+
|
862 |
+
def _print_str(self, expr):
|
863 |
+
return str(expr)
|
864 |
+
|
865 |
+
def _print_tuple(self, expr):
|
866 |
+
if len(expr) == 1:
|
867 |
+
return "(%s,)" % self._print(expr[0])
|
868 |
+
else:
|
869 |
+
return "(%s)" % self.stringify(expr, ", ")
|
870 |
+
|
871 |
+
def _print_Tuple(self, expr):
|
872 |
+
return self._print_tuple(expr)
|
873 |
+
|
874 |
+
def _print_Transpose(self, T):
|
875 |
+
return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"])
|
876 |
+
|
877 |
+
def _print_Uniform(self, expr):
|
878 |
+
return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b))
|
879 |
+
|
880 |
+
def _print_Quantity(self, expr):
|
881 |
+
if self._settings.get("abbrev", False):
|
882 |
+
return "%s" % expr.abbrev
|
883 |
+
return "%s" % expr.name
|
884 |
+
|
885 |
+
def _print_Quaternion(self, expr):
|
886 |
+
s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args]
|
887 |
+
a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")]
|
888 |
+
return " + ".join(a)
|
889 |
+
|
890 |
+
def _print_Dimension(self, expr):
|
891 |
+
return str(expr)
|
892 |
+
|
893 |
+
def _print_Wild(self, expr):
|
894 |
+
return expr.name + '_'
|
895 |
+
|
896 |
+
def _print_WildFunction(self, expr):
|
897 |
+
return expr.name + '_'
|
898 |
+
|
899 |
+
def _print_WildDot(self, expr):
|
900 |
+
return expr.name
|
901 |
+
|
902 |
+
def _print_WildPlus(self, expr):
|
903 |
+
return expr.name
|
904 |
+
|
905 |
+
def _print_WildStar(self, expr):
|
906 |
+
return expr.name
|
907 |
+
|
908 |
+
def _print_Zero(self, expr):
|
909 |
+
if self._settings.get("sympy_integers", False):
|
910 |
+
return "S(0)"
|
911 |
+
return "0"
|
912 |
+
|
913 |
+
def _print_DMP(self, p):
|
914 |
+
try:
|
915 |
+
if p.ring is not None:
|
916 |
+
# TODO incorporate order
|
917 |
+
return self._print(p.ring.to_sympy(p))
|
918 |
+
except SympifyError:
|
919 |
+
pass
|
920 |
+
|
921 |
+
cls = p.__class__.__name__
|
922 |
+
rep = self._print(p.rep)
|
923 |
+
dom = self._print(p.dom)
|
924 |
+
ring = self._print(p.ring)
|
925 |
+
|
926 |
+
return "%s(%s, %s, %s)" % (cls, rep, dom, ring)
|
927 |
+
|
928 |
+
def _print_DMF(self, expr):
|
929 |
+
return self._print_DMP(expr)
|
930 |
+
|
931 |
+
def _print_Object(self, obj):
|
932 |
+
return 'Object("%s")' % obj.name
|
933 |
+
|
934 |
+
def _print_IdentityMorphism(self, morphism):
|
935 |
+
return 'IdentityMorphism(%s)' % morphism.domain
|
936 |
+
|
937 |
+
def _print_NamedMorphism(self, morphism):
|
938 |
+
return 'NamedMorphism(%s, %s, "%s")' % \
|
939 |
+
(morphism.domain, morphism.codomain, morphism.name)
|
940 |
+
|
941 |
+
def _print_Category(self, category):
|
942 |
+
return 'Category("%s")' % category.name
|
943 |
+
|
944 |
+
def _print_Manifold(self, manifold):
|
945 |
+
return manifold.name.name
|
946 |
+
|
947 |
+
def _print_Patch(self, patch):
|
948 |
+
return patch.name.name
|
949 |
+
|
950 |
+
def _print_CoordSystem(self, coords):
|
951 |
+
return coords.name.name
|
952 |
+
|
953 |
+
def _print_BaseScalarField(self, field):
|
954 |
+
return field._coord_sys.symbols[field._index].name
|
955 |
+
|
956 |
+
def _print_BaseVectorField(self, field):
|
957 |
+
return 'e_%s' % field._coord_sys.symbols[field._index].name
|
958 |
+
|
959 |
+
def _print_Differential(self, diff):
|
960 |
+
field = diff._form_field
|
961 |
+
if hasattr(field, '_coord_sys'):
|
962 |
+
return 'd%s' % field._coord_sys.symbols[field._index].name
|
963 |
+
else:
|
964 |
+
return 'd(%s)' % self._print(field)
|
965 |
+
|
966 |
+
def _print_Tr(self, expr):
|
967 |
+
#TODO : Handle indices
|
968 |
+
return "%s(%s)" % ("Tr", self._print(expr.args[0]))
|
969 |
+
|
970 |
+
def _print_Str(self, s):
|
971 |
+
return self._print(s.name)
|
972 |
+
|
973 |
+
def _print_AppliedBinaryRelation(self, expr):
|
974 |
+
rel = expr.function
|
975 |
+
return '%s(%s, %s)' % (self._print(rel),
|
976 |
+
self._print(expr.lhs),
|
977 |
+
self._print(expr.rhs))
|
978 |
+
|
979 |
+
|
980 |
+
@print_function(StrPrinter)
|
981 |
+
def sstr(expr, **settings):
|
982 |
+
"""Returns the expression as a string.
|
983 |
+
|
984 |
+
For large expressions where speed is a concern, use the setting
|
985 |
+
order='none'. If abbrev=True setting is used then units are printed in
|
986 |
+
abbreviated form.
|
987 |
+
|
988 |
+
Examples
|
989 |
+
========
|
990 |
+
|
991 |
+
>>> from sympy import symbols, Eq, sstr
|
992 |
+
>>> a, b = symbols('a b')
|
993 |
+
>>> sstr(Eq(a + b, 0))
|
994 |
+
'Eq(a + b, 0)'
|
995 |
+
"""
|
996 |
+
|
997 |
+
p = StrPrinter(settings)
|
998 |
+
s = p.doprint(expr)
|
999 |
+
|
1000 |
+
return s
|
1001 |
+
|
1002 |
+
|
1003 |
+
class StrReprPrinter(StrPrinter):
|
1004 |
+
"""(internal) -- see sstrrepr"""
|
1005 |
+
|
1006 |
+
def _print_str(self, s):
|
1007 |
+
return repr(s)
|
1008 |
+
|
1009 |
+
def _print_Str(self, s):
|
1010 |
+
# Str does not to be printed same as str here
|
1011 |
+
return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
|
1012 |
+
|
1013 |
+
|
1014 |
+
@print_function(StrReprPrinter)
|
1015 |
+
def sstrrepr(expr, **settings):
|
1016 |
+
"""return expr in mixed str/repr form
|
1017 |
+
|
1018 |
+
i.e. strings are returned in repr form with quotes, and everything else
|
1019 |
+
is returned in str form.
|
1020 |
+
|
1021 |
+
This function could be useful for hooking into sys.displayhook
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.containers import Tuple
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.core.symbol import Symbol
|
4 |
+
from sympy.core.sympify import SympifyError
|
5 |
+
|
6 |
+
from types import FunctionType
|
7 |
+
|
8 |
+
|
9 |
+
class TableForm:
|
10 |
+
r"""
|
11 |
+
Create a nice table representation of data.
|
12 |
+
|
13 |
+
Examples
|
14 |
+
========
|
15 |
+
|
16 |
+
>>> from sympy import TableForm
|
17 |
+
>>> t = TableForm([[5, 7], [4, 2], [10, 3]])
|
18 |
+
>>> print(t)
|
19 |
+
5 7
|
20 |
+
4 2
|
21 |
+
10 3
|
22 |
+
|
23 |
+
You can use the SymPy's printing system to produce tables in any
|
24 |
+
format (ascii, latex, html, ...).
|
25 |
+
|
26 |
+
>>> print(t.as_latex())
|
27 |
+
\begin{tabular}{l l}
|
28 |
+
$5$ & $7$ \\
|
29 |
+
$4$ & $2$ \\
|
30 |
+
$10$ & $3$ \\
|
31 |
+
\end{tabular}
|
32 |
+
|
33 |
+
"""
|
34 |
+
|
35 |
+
def __init__(self, data, **kwarg):
|
36 |
+
"""
|
37 |
+
Creates a TableForm.
|
38 |
+
|
39 |
+
Parameters:
|
40 |
+
|
41 |
+
data ...
|
42 |
+
2D data to be put into the table; data can be
|
43 |
+
given as a Matrix
|
44 |
+
|
45 |
+
headings ...
|
46 |
+
gives the labels for rows and columns:
|
47 |
+
|
48 |
+
Can be a single argument that applies to both
|
49 |
+
dimensions:
|
50 |
+
|
51 |
+
- None ... no labels
|
52 |
+
- "automatic" ... labels are 1, 2, 3, ...
|
53 |
+
|
54 |
+
Can be a list of labels for rows and columns:
|
55 |
+
The labels for each dimension can be given
|
56 |
+
as None, "automatic", or [l1, l2, ...] e.g.
|
57 |
+
["automatic", None] will number the rows
|
58 |
+
|
59 |
+
[default: None]
|
60 |
+
|
61 |
+
alignments ...
|
62 |
+
alignment of the columns with:
|
63 |
+
|
64 |
+
- "left" or "<"
|
65 |
+
- "center" or "^"
|
66 |
+
- "right" or ">"
|
67 |
+
|
68 |
+
When given as a single value, the value is used for
|
69 |
+
all columns. The row headings (if given) will be
|
70 |
+
right justified unless an explicit alignment is
|
71 |
+
given for it and all other columns.
|
72 |
+
|
73 |
+
[default: "left"]
|
74 |
+
|
75 |
+
formats ...
|
76 |
+
a list of format strings or functions that accept
|
77 |
+
3 arguments (entry, row number, col number) and
|
78 |
+
return a string for the table entry. (If a function
|
79 |
+
returns None then the _print method will be used.)
|
80 |
+
|
81 |
+
wipe_zeros ...
|
82 |
+
Do not show zeros in the table.
|
83 |
+
|
84 |
+
[default: True]
|
85 |
+
|
86 |
+
pad ...
|
87 |
+
the string to use to indicate a missing value (e.g.
|
88 |
+
elements that are None or those that are missing
|
89 |
+
from the end of a row (i.e. any row that is shorter
|
90 |
+
than the rest is assumed to have missing values).
|
91 |
+
When None, nothing will be shown for values that
|
92 |
+
are missing from the end of a row; values that are
|
93 |
+
None, however, will be shown.
|
94 |
+
|
95 |
+
[default: None]
|
96 |
+
|
97 |
+
Examples
|
98 |
+
========
|
99 |
+
|
100 |
+
>>> from sympy import TableForm, Symbol
|
101 |
+
>>> TableForm([[5, 7], [4, 2], [10, 3]])
|
102 |
+
5 7
|
103 |
+
4 2
|
104 |
+
10 3
|
105 |
+
>>> TableForm([list('.'*i) for i in range(1, 4)], headings='automatic')
|
106 |
+
| 1 2 3
|
107 |
+
---------
|
108 |
+
1 | .
|
109 |
+
2 | . .
|
110 |
+
3 | . . .
|
111 |
+
>>> TableForm([[Symbol('.'*(j if not i%2 else 1)) for i in range(3)]
|
112 |
+
... for j in range(4)], alignments='rcl')
|
113 |
+
.
|
114 |
+
. . .
|
115 |
+
.. . ..
|
116 |
+
... . ...
|
117 |
+
"""
|
118 |
+
from sympy.matrices.dense import Matrix
|
119 |
+
|
120 |
+
# We only support 2D data. Check the consistency:
|
121 |
+
if isinstance(data, Matrix):
|
122 |
+
data = data.tolist()
|
123 |
+
_h = len(data)
|
124 |
+
|
125 |
+
# fill out any short lines
|
126 |
+
pad = kwarg.get('pad', None)
|
127 |
+
ok_None = False
|
128 |
+
if pad is None:
|
129 |
+
pad = " "
|
130 |
+
ok_None = True
|
131 |
+
pad = Symbol(pad)
|
132 |
+
_w = max(len(line) for line in data)
|
133 |
+
for i, line in enumerate(data):
|
134 |
+
if len(line) != _w:
|
135 |
+
line.extend([pad]*(_w - len(line)))
|
136 |
+
for j, lj in enumerate(line):
|
137 |
+
if lj is None:
|
138 |
+
if not ok_None:
|
139 |
+
lj = pad
|
140 |
+
else:
|
141 |
+
try:
|
142 |
+
lj = S(lj)
|
143 |
+
except SympifyError:
|
144 |
+
lj = Symbol(str(lj))
|
145 |
+
line[j] = lj
|
146 |
+
data[i] = line
|
147 |
+
_lines = Tuple(*[Tuple(*d) for d in data])
|
148 |
+
|
149 |
+
headings = kwarg.get("headings", [None, None])
|
150 |
+
if headings == "automatic":
|
151 |
+
_headings = [range(1, _h + 1), range(1, _w + 1)]
|
152 |
+
else:
|
153 |
+
h1, h2 = headings
|
154 |
+
if h1 == "automatic":
|
155 |
+
h1 = range(1, _h + 1)
|
156 |
+
if h2 == "automatic":
|
157 |
+
h2 = range(1, _w + 1)
|
158 |
+
_headings = [h1, h2]
|
159 |
+
|
160 |
+
allow = ('l', 'r', 'c')
|
161 |
+
alignments = kwarg.get("alignments", "l")
|
162 |
+
|
163 |
+
def _std_align(a):
|
164 |
+
a = a.strip().lower()
|
165 |
+
if len(a) > 1:
|
166 |
+
return {'left': 'l', 'right': 'r', 'center': 'c'}.get(a, a)
|
167 |
+
else:
|
168 |
+
return {'<': 'l', '>': 'r', '^': 'c'}.get(a, a)
|
169 |
+
std_align = _std_align(alignments)
|
170 |
+
if std_align in allow:
|
171 |
+
_alignments = [std_align]*_w
|
172 |
+
else:
|
173 |
+
_alignments = []
|
174 |
+
for a in alignments:
|
175 |
+
std_align = _std_align(a)
|
176 |
+
_alignments.append(std_align)
|
177 |
+
if std_align not in ('l', 'r', 'c'):
|
178 |
+
raise ValueError('alignment "%s" unrecognized' %
|
179 |
+
alignments)
|
180 |
+
if _headings[0] and len(_alignments) == _w + 1:
|
181 |
+
_head_align = _alignments[0]
|
182 |
+
_alignments = _alignments[1:]
|
183 |
+
else:
|
184 |
+
_head_align = 'r'
|
185 |
+
if len(_alignments) != _w:
|
186 |
+
raise ValueError(
|
187 |
+
'wrong number of alignments: expected %s but got %s' %
|
188 |
+
(_w, len(_alignments)))
|
189 |
+
|
190 |
+
_column_formats = kwarg.get("formats", [None]*_w)
|
191 |
+
|
192 |
+
_wipe_zeros = kwarg.get("wipe_zeros", True)
|
193 |
+
|
194 |
+
self._w = _w
|
195 |
+
self._h = _h
|
196 |
+
self._lines = _lines
|
197 |
+
self._headings = _headings
|
198 |
+
self._head_align = _head_align
|
199 |
+
self._alignments = _alignments
|
200 |
+
self._column_formats = _column_formats
|
201 |
+
self._wipe_zeros = _wipe_zeros
|
202 |
+
|
203 |
+
def __repr__(self):
|
204 |
+
from .str import sstr
|
205 |
+
return sstr(self, order=None)
|
206 |
+
|
207 |
+
def __str__(self):
|
208 |
+
from .str import sstr
|
209 |
+
return sstr(self, order=None)
|
210 |
+
|
211 |
+
def as_matrix(self):
|
212 |
+
"""Returns the data of the table in Matrix form.
|
213 |
+
|
214 |
+
Examples
|
215 |
+
========
|
216 |
+
|
217 |
+
>>> from sympy import TableForm
|
218 |
+
>>> t = TableForm([[5, 7], [4, 2], [10, 3]], headings='automatic')
|
219 |
+
>>> t
|
220 |
+
| 1 2
|
221 |
+
--------
|
222 |
+
1 | 5 7
|
223 |
+
2 | 4 2
|
224 |
+
3 | 10 3
|
225 |
+
>>> t.as_matrix()
|
226 |
+
Matrix([
|
227 |
+
[ 5, 7],
|
228 |
+
[ 4, 2],
|
229 |
+
[10, 3]])
|
230 |
+
"""
|
231 |
+
from sympy.matrices.dense import Matrix
|
232 |
+
return Matrix(self._lines)
|
233 |
+
|
234 |
+
def as_str(self):
|
235 |
+
# XXX obsolete ?
|
236 |
+
return str(self)
|
237 |
+
|
238 |
+
def as_latex(self):
|
239 |
+
from .latex import latex
|
240 |
+
return latex(self)
|
241 |
+
|
242 |
+
def _sympystr(self, p):
|
243 |
+
"""
|
244 |
+
Returns the string representation of 'self'.
|
245 |
+
|
246 |
+
Examples
|
247 |
+
========
|
248 |
+
|
249 |
+
>>> from sympy import TableForm
|
250 |
+
>>> t = TableForm([[5, 7], [4, 2], [10, 3]])
|
251 |
+
>>> s = t.as_str()
|
252 |
+
|
253 |
+
"""
|
254 |
+
column_widths = [0] * self._w
|
255 |
+
lines = []
|
256 |
+
for line in self._lines:
|
257 |
+
new_line = []
|
258 |
+
for i in range(self._w):
|
259 |
+
# Format the item somehow if needed:
|
260 |
+
s = str(line[i])
|
261 |
+
if self._wipe_zeros and (s == "0"):
|
262 |
+
s = " "
|
263 |
+
w = len(s)
|
264 |
+
if w > column_widths[i]:
|
265 |
+
column_widths[i] = w
|
266 |
+
new_line.append(s)
|
267 |
+
lines.append(new_line)
|
268 |
+
|
269 |
+
# Check heading:
|
270 |
+
if self._headings[0]:
|
271 |
+
self._headings[0] = [str(x) for x in self._headings[0]]
|
272 |
+
_head_width = max([len(x) for x in self._headings[0]])
|
273 |
+
|
274 |
+
if self._headings[1]:
|
275 |
+
new_line = []
|
276 |
+
for i in range(self._w):
|
277 |
+
# Format the item somehow if needed:
|
278 |
+
s = str(self._headings[1][i])
|
279 |
+
w = len(s)
|
280 |
+
if w > column_widths[i]:
|
281 |
+
column_widths[i] = w
|
282 |
+
new_line.append(s)
|
283 |
+
self._headings[1] = new_line
|
284 |
+
|
285 |
+
format_str = []
|
286 |
+
|
287 |
+
def _align(align, w):
|
288 |
+
return '%%%s%ss' % (
|
289 |
+
("-" if align == "l" else ""),
|
290 |
+
str(w))
|
291 |
+
format_str = [_align(align, w) for align, w in
|
292 |
+
zip(self._alignments, column_widths)]
|
293 |
+
if self._headings[0]:
|
294 |
+
format_str.insert(0, _align(self._head_align, _head_width))
|
295 |
+
format_str.insert(1, '|')
|
296 |
+
format_str = ' '.join(format_str) + '\n'
|
297 |
+
|
298 |
+
s = []
|
299 |
+
if self._headings[1]:
|
300 |
+
d = self._headings[1]
|
301 |
+
if self._headings[0]:
|
302 |
+
d = [""] + d
|
303 |
+
first_line = format_str % tuple(d)
|
304 |
+
s.append(first_line)
|
305 |
+
s.append("-" * (len(first_line) - 1) + "\n")
|
306 |
+
for i, line in enumerate(lines):
|
307 |
+
d = [l if self._alignments[j] != 'c' else
|
308 |
+
l.center(column_widths[j]) for j, l in enumerate(line)]
|
309 |
+
if self._headings[0]:
|
310 |
+
l = self._headings[0][i]
|
311 |
+
l = (l if self._head_align != 'c' else
|
312 |
+
l.center(_head_width))
|
313 |
+
d = [l] + d
|
314 |
+
s.append(format_str % tuple(d))
|
315 |
+
return ''.join(s)[:-1] # don't include trailing newline
|
316 |
+
|
317 |
+
def _latex(self, printer):
|
318 |
+
"""
|
319 |
+
Returns the string representation of 'self'.
|
320 |
+
"""
|
321 |
+
# Check heading:
|
322 |
+
if self._headings[1]:
|
323 |
+
new_line = []
|
324 |
+
for i in range(self._w):
|
325 |
+
# Format the item somehow if needed:
|
326 |
+
new_line.append(str(self._headings[1][i]))
|
327 |
+
self._headings[1] = new_line
|
328 |
+
|
329 |
+
alignments = []
|
330 |
+
if self._headings[0]:
|
331 |
+
self._headings[0] = [str(x) for x in self._headings[0]]
|
332 |
+
alignments = [self._head_align]
|
333 |
+
alignments.extend(self._alignments)
|
334 |
+
|
335 |
+
s = r"\begin{tabular}{" + " ".join(alignments) + "}\n"
|
336 |
+
|
337 |
+
if self._headings[1]:
|
338 |
+
d = self._headings[1]
|
339 |
+
if self._headings[0]:
|
340 |
+
d = [""] + d
|
341 |
+
first_line = " & ".join(d) + r" \\" + "\n"
|
342 |
+
s += first_line
|
343 |
+
s += r"\hline" + "\n"
|
344 |
+
for i, line in enumerate(self._lines):
|
345 |
+
d = []
|
346 |
+
for j, x in enumerate(line):
|
347 |
+
if self._wipe_zeros and (x in (0, "0")):
|
348 |
+
d.append(" ")
|
349 |
+
continue
|
350 |
+
f = self._column_formats[j]
|
351 |
+
if f:
|
352 |
+
if isinstance(f, FunctionType):
|
353 |
+
v = f(x, i, j)
|
354 |
+
if v is None:
|
355 |
+
v = printer._print(x)
|
356 |
+
else:
|
357 |
+
v = f % x
|
358 |
+
d.append(v)
|
359 |
+
else:
|
360 |
+
v = printer._print(x)
|
361 |
+
d.append("$%s$" % v)
|
362 |
+
if self._headings[0]:
|
363 |
+
d = [self._headings[0][i]] + d
|
364 |
+
s += " & ".join(d) + r" \\" + "\n"
|
365 |
+
s += r"\end{tabular}"
|
366 |
+
return s
|
venv/lib/python3.10/site-packages/sympy/printing/tensorflow.py
ADDED
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.external.importtools import version_tuple
|
2 |
+
from collections.abc import Iterable
|
3 |
+
|
4 |
+
from sympy.core.mul import Mul
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.codegen.cfunctions import Sqrt
|
7 |
+
from sympy.external import import_module
|
8 |
+
from sympy.printing.precedence import PRECEDENCE
|
9 |
+
from sympy.printing.pycode import AbstractPythonCodePrinter, ArrayPrinter
|
10 |
+
import sympy
|
11 |
+
|
12 |
+
tensorflow = import_module('tensorflow')
|
13 |
+
|
14 |
+
class TensorflowPrinter(ArrayPrinter, AbstractPythonCodePrinter):
|
15 |
+
"""
|
16 |
+
Tensorflow printer which handles vectorized piecewise functions,
|
17 |
+
logical operators, max/min, and relational operators.
|
18 |
+
"""
|
19 |
+
printmethod = "_tensorflowcode"
|
20 |
+
|
21 |
+
mapping = {
|
22 |
+
sympy.Abs: "tensorflow.math.abs",
|
23 |
+
sympy.sign: "tensorflow.math.sign",
|
24 |
+
|
25 |
+
# XXX May raise error for ints.
|
26 |
+
sympy.ceiling: "tensorflow.math.ceil",
|
27 |
+
sympy.floor: "tensorflow.math.floor",
|
28 |
+
sympy.log: "tensorflow.math.log",
|
29 |
+
sympy.exp: "tensorflow.math.exp",
|
30 |
+
Sqrt: "tensorflow.math.sqrt",
|
31 |
+
sympy.cos: "tensorflow.math.cos",
|
32 |
+
sympy.acos: "tensorflow.math.acos",
|
33 |
+
sympy.sin: "tensorflow.math.sin",
|
34 |
+
sympy.asin: "tensorflow.math.asin",
|
35 |
+
sympy.tan: "tensorflow.math.tan",
|
36 |
+
sympy.atan: "tensorflow.math.atan",
|
37 |
+
sympy.atan2: "tensorflow.math.atan2",
|
38 |
+
# XXX Also may give NaN for complex results.
|
39 |
+
sympy.cosh: "tensorflow.math.cosh",
|
40 |
+
sympy.acosh: "tensorflow.math.acosh",
|
41 |
+
sympy.sinh: "tensorflow.math.sinh",
|
42 |
+
sympy.asinh: "tensorflow.math.asinh",
|
43 |
+
sympy.tanh: "tensorflow.math.tanh",
|
44 |
+
sympy.atanh: "tensorflow.math.atanh",
|
45 |
+
|
46 |
+
sympy.re: "tensorflow.math.real",
|
47 |
+
sympy.im: "tensorflow.math.imag",
|
48 |
+
sympy.arg: "tensorflow.math.angle",
|
49 |
+
|
50 |
+
# XXX May raise error for ints and complexes
|
51 |
+
sympy.erf: "tensorflow.math.erf",
|
52 |
+
sympy.loggamma: "tensorflow.math.lgamma",
|
53 |
+
|
54 |
+
sympy.Eq: "tensorflow.math.equal",
|
55 |
+
sympy.Ne: "tensorflow.math.not_equal",
|
56 |
+
sympy.StrictGreaterThan: "tensorflow.math.greater",
|
57 |
+
sympy.StrictLessThan: "tensorflow.math.less",
|
58 |
+
sympy.LessThan: "tensorflow.math.less_equal",
|
59 |
+
sympy.GreaterThan: "tensorflow.math.greater_equal",
|
60 |
+
|
61 |
+
sympy.And: "tensorflow.math.logical_and",
|
62 |
+
sympy.Or: "tensorflow.math.logical_or",
|
63 |
+
sympy.Not: "tensorflow.math.logical_not",
|
64 |
+
sympy.Max: "tensorflow.math.maximum",
|
65 |
+
sympy.Min: "tensorflow.math.minimum",
|
66 |
+
|
67 |
+
# Matrices
|
68 |
+
sympy.MatAdd: "tensorflow.math.add",
|
69 |
+
sympy.HadamardProduct: "tensorflow.math.multiply",
|
70 |
+
sympy.Trace: "tensorflow.linalg.trace",
|
71 |
+
|
72 |
+
# XXX May raise error for integer matrices.
|
73 |
+
sympy.Determinant : "tensorflow.linalg.det",
|
74 |
+
}
|
75 |
+
|
76 |
+
_default_settings = dict(
|
77 |
+
AbstractPythonCodePrinter._default_settings,
|
78 |
+
tensorflow_version=None
|
79 |
+
)
|
80 |
+
|
81 |
+
def __init__(self, settings=None):
|
82 |
+
super().__init__(settings)
|
83 |
+
|
84 |
+
version = self._settings['tensorflow_version']
|
85 |
+
if version is None and tensorflow:
|
86 |
+
version = tensorflow.__version__
|
87 |
+
self.tensorflow_version = version
|
88 |
+
|
89 |
+
def _print_Function(self, expr):
|
90 |
+
op = self.mapping.get(type(expr), None)
|
91 |
+
if op is None:
|
92 |
+
return super()._print_Basic(expr)
|
93 |
+
children = [self._print(arg) for arg in expr.args]
|
94 |
+
if len(children) == 1:
|
95 |
+
return "%s(%s)" % (
|
96 |
+
self._module_format(op),
|
97 |
+
children[0]
|
98 |
+
)
|
99 |
+
else:
|
100 |
+
return self._expand_fold_binary_op(op, children)
|
101 |
+
|
102 |
+
_print_Expr = _print_Function
|
103 |
+
_print_Application = _print_Function
|
104 |
+
_print_MatrixExpr = _print_Function
|
105 |
+
# TODO: a better class structure would avoid this mess:
|
106 |
+
_print_Relational = _print_Function
|
107 |
+
_print_Not = _print_Function
|
108 |
+
_print_And = _print_Function
|
109 |
+
_print_Or = _print_Function
|
110 |
+
_print_HadamardProduct = _print_Function
|
111 |
+
_print_Trace = _print_Function
|
112 |
+
_print_Determinant = _print_Function
|
113 |
+
|
114 |
+
def _print_Inverse(self, expr):
|
115 |
+
op = self._module_format('tensorflow.linalg.inv')
|
116 |
+
return "{}({})".format(op, self._print(expr.arg))
|
117 |
+
|
118 |
+
def _print_Transpose(self, expr):
|
119 |
+
version = self.tensorflow_version
|
120 |
+
if version and version_tuple(version) < version_tuple('1.14'):
|
121 |
+
op = self._module_format('tensorflow.matrix_transpose')
|
122 |
+
else:
|
123 |
+
op = self._module_format('tensorflow.linalg.matrix_transpose')
|
124 |
+
return "{}({})".format(op, self._print(expr.arg))
|
125 |
+
|
126 |
+
def _print_Derivative(self, expr):
|
127 |
+
variables = expr.variables
|
128 |
+
if any(isinstance(i, Iterable) for i in variables):
|
129 |
+
raise NotImplementedError("derivation by multiple variables is not supported")
|
130 |
+
def unfold(expr, args):
|
131 |
+
if not args:
|
132 |
+
return self._print(expr)
|
133 |
+
return "%s(%s, %s)[0]" % (
|
134 |
+
self._module_format("tensorflow.gradients"),
|
135 |
+
unfold(expr, args[:-1]),
|
136 |
+
self._print(args[-1]),
|
137 |
+
)
|
138 |
+
return unfold(expr.expr, variables)
|
139 |
+
|
140 |
+
def _print_Piecewise(self, expr):
|
141 |
+
version = self.tensorflow_version
|
142 |
+
if version and version_tuple(version) < version_tuple('1.0'):
|
143 |
+
tensorflow_piecewise = "tensorflow.select"
|
144 |
+
else:
|
145 |
+
tensorflow_piecewise = "tensorflow.where"
|
146 |
+
|
147 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
148 |
+
e, cond = expr.args[0].args
|
149 |
+
if len(expr.args) == 1:
|
150 |
+
return '{}({}, {}, {})'.format(
|
151 |
+
self._module_format(tensorflow_piecewise),
|
152 |
+
self._print(cond),
|
153 |
+
self._print(e),
|
154 |
+
0)
|
155 |
+
|
156 |
+
return '{}({}, {}, {})'.format(
|
157 |
+
self._module_format(tensorflow_piecewise),
|
158 |
+
self._print(cond),
|
159 |
+
self._print(e),
|
160 |
+
self._print(Piecewise(*expr.args[1:])))
|
161 |
+
|
162 |
+
def _print_Pow(self, expr):
|
163 |
+
# XXX May raise error for
|
164 |
+
# int**float or int**complex or float**complex
|
165 |
+
base, exp = expr.args
|
166 |
+
if expr.exp == S.Half:
|
167 |
+
return "{}({})".format(
|
168 |
+
self._module_format("tensorflow.math.sqrt"), self._print(base))
|
169 |
+
return "{}({}, {})".format(
|
170 |
+
self._module_format("tensorflow.math.pow"),
|
171 |
+
self._print(base), self._print(exp))
|
172 |
+
|
173 |
+
def _print_MatrixBase(self, expr):
|
174 |
+
tensorflow_f = "tensorflow.Variable" if expr.free_symbols else "tensorflow.constant"
|
175 |
+
data = "["+", ".join(["["+", ".join([self._print(j) for j in i])+"]" for i in expr.tolist()])+"]"
|
176 |
+
return "%s(%s)" % (
|
177 |
+
self._module_format(tensorflow_f),
|
178 |
+
data,
|
179 |
+
)
|
180 |
+
|
181 |
+
def _print_MatMul(self, expr):
|
182 |
+
from sympy.matrices.expressions import MatrixExpr
|
183 |
+
mat_args = [arg for arg in expr.args if isinstance(arg, MatrixExpr)]
|
184 |
+
args = [arg for arg in expr.args if arg not in mat_args]
|
185 |
+
if args:
|
186 |
+
return "%s*%s" % (
|
187 |
+
self.parenthesize(Mul.fromiter(args), PRECEDENCE["Mul"]),
|
188 |
+
self._expand_fold_binary_op(
|
189 |
+
"tensorflow.linalg.matmul", mat_args)
|
190 |
+
)
|
191 |
+
else:
|
192 |
+
return self._expand_fold_binary_op(
|
193 |
+
"tensorflow.linalg.matmul", mat_args)
|
194 |
+
|
195 |
+
def _print_MatPow(self, expr):
|
196 |
+
return self._expand_fold_binary_op(
|
197 |
+
"tensorflow.linalg.matmul", [expr.base]*expr.exp)
|
198 |
+
|
199 |
+
def _print_CodeBlock(self, expr):
|
200 |
+
# TODO: is this necessary?
|
201 |
+
ret = []
|
202 |
+
for subexpr in expr.args:
|
203 |
+
ret.append(self._print(subexpr))
|
204 |
+
return "\n".join(ret)
|
205 |
+
|
206 |
+
_module = "tensorflow"
|
207 |
+
_einsum = "linalg.einsum"
|
208 |
+
_add = "math.add"
|
209 |
+
_transpose = "transpose"
|
210 |
+
_ones = "ones"
|
211 |
+
_zeros = "zeros"
|
212 |
+
|
213 |
+
|
214 |
+
def tensorflow_code(expr, **settings):
|
215 |
+
printer = TensorflowPrinter(settings)
|
216 |
+
return printer.doprint(expr)
|
venv/lib/python3.10/site-packages/sympy/printing/theanocode.py
ADDED
@@ -0,0 +1,565 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
.. deprecated:: 1.8
|
3 |
+
|
4 |
+
``sympy.printing.theanocode`` is deprecated. Theano has been renamed to
|
5 |
+
Aesara. Use ``sympy.printing.aesaracode`` instead. See
|
6 |
+
:ref:`theanocode-deprecated` for more information.
|
7 |
+
|
8 |
+
"""
|
9 |
+
from __future__ import annotations
|
10 |
+
from typing import Any
|
11 |
+
|
12 |
+
from sympy.external import import_module
|
13 |
+
from sympy.printing.printer import Printer
|
14 |
+
from sympy.utilities.iterables import is_sequence
|
15 |
+
import sympy
|
16 |
+
from functools import partial
|
17 |
+
|
18 |
+
from sympy.utilities.decorator import doctest_depends_on
|
19 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
20 |
+
|
21 |
+
theano = import_module('theano')
|
22 |
+
|
23 |
+
if theano:
|
24 |
+
ts = theano.scalar
|
25 |
+
tt = theano.tensor
|
26 |
+
from theano.sandbox import linalg as tlinalg
|
27 |
+
|
28 |
+
mapping = {
|
29 |
+
sympy.Add: tt.add,
|
30 |
+
sympy.Mul: tt.mul,
|
31 |
+
sympy.Abs: tt.abs_,
|
32 |
+
sympy.sign: tt.sgn,
|
33 |
+
sympy.ceiling: tt.ceil,
|
34 |
+
sympy.floor: tt.floor,
|
35 |
+
sympy.log: tt.log,
|
36 |
+
sympy.exp: tt.exp,
|
37 |
+
sympy.sqrt: tt.sqrt,
|
38 |
+
sympy.cos: tt.cos,
|
39 |
+
sympy.acos: tt.arccos,
|
40 |
+
sympy.sin: tt.sin,
|
41 |
+
sympy.asin: tt.arcsin,
|
42 |
+
sympy.tan: tt.tan,
|
43 |
+
sympy.atan: tt.arctan,
|
44 |
+
sympy.atan2: tt.arctan2,
|
45 |
+
sympy.cosh: tt.cosh,
|
46 |
+
sympy.acosh: tt.arccosh,
|
47 |
+
sympy.sinh: tt.sinh,
|
48 |
+
sympy.asinh: tt.arcsinh,
|
49 |
+
sympy.tanh: tt.tanh,
|
50 |
+
sympy.atanh: tt.arctanh,
|
51 |
+
sympy.re: tt.real,
|
52 |
+
sympy.im: tt.imag,
|
53 |
+
sympy.arg: tt.angle,
|
54 |
+
sympy.erf: tt.erf,
|
55 |
+
sympy.gamma: tt.gamma,
|
56 |
+
sympy.loggamma: tt.gammaln,
|
57 |
+
sympy.Pow: tt.pow,
|
58 |
+
sympy.Eq: tt.eq,
|
59 |
+
sympy.StrictGreaterThan: tt.gt,
|
60 |
+
sympy.StrictLessThan: tt.lt,
|
61 |
+
sympy.LessThan: tt.le,
|
62 |
+
sympy.GreaterThan: tt.ge,
|
63 |
+
sympy.And: tt.and_,
|
64 |
+
sympy.Or: tt.or_,
|
65 |
+
sympy.Max: tt.maximum, # SymPy accept >2 inputs, Theano only 2
|
66 |
+
sympy.Min: tt.minimum, # SymPy accept >2 inputs, Theano only 2
|
67 |
+
sympy.conjugate: tt.conj,
|
68 |
+
sympy.core.numbers.ImaginaryUnit: lambda:tt.complex(0,1),
|
69 |
+
# Matrices
|
70 |
+
sympy.MatAdd: tt.Elemwise(ts.add),
|
71 |
+
sympy.HadamardProduct: tt.Elemwise(ts.mul),
|
72 |
+
sympy.Trace: tlinalg.trace,
|
73 |
+
sympy.Determinant : tlinalg.det,
|
74 |
+
sympy.Inverse: tlinalg.matrix_inverse,
|
75 |
+
sympy.Transpose: tt.DimShuffle((False, False), [1, 0]),
|
76 |
+
}
|
77 |
+
|
78 |
+
|
79 |
+
class TheanoPrinter(Printer):
|
80 |
+
""" Code printer which creates Theano symbolic expression graphs.
|
81 |
+
|
82 |
+
Parameters
|
83 |
+
==========
|
84 |
+
|
85 |
+
cache : dict
|
86 |
+
Cache dictionary to use. If None (default) will use
|
87 |
+
the global cache. To create a printer which does not depend on or alter
|
88 |
+
global state pass an empty dictionary. Note: the dictionary is not
|
89 |
+
copied on initialization of the printer and will be updated in-place,
|
90 |
+
so using the same dict object when creating multiple printers or making
|
91 |
+
multiple calls to :func:`.theano_code` or :func:`.theano_function` means
|
92 |
+
the cache is shared between all these applications.
|
93 |
+
|
94 |
+
Attributes
|
95 |
+
==========
|
96 |
+
|
97 |
+
cache : dict
|
98 |
+
A cache of Theano variables which have been created for SymPy
|
99 |
+
symbol-like objects (e.g. :class:`sympy.core.symbol.Symbol` or
|
100 |
+
:class:`sympy.matrices.expressions.MatrixSymbol`). This is used to
|
101 |
+
ensure that all references to a given symbol in an expression (or
|
102 |
+
multiple expressions) are printed as the same Theano variable, which is
|
103 |
+
created only once. Symbols are differentiated only by name and type. The
|
104 |
+
format of the cache's contents should be considered opaque to the user.
|
105 |
+
"""
|
106 |
+
printmethod = "_theano"
|
107 |
+
|
108 |
+
def __init__(self, *args, **kwargs):
|
109 |
+
self.cache = kwargs.pop('cache', {})
|
110 |
+
super().__init__(*args, **kwargs)
|
111 |
+
|
112 |
+
def _get_key(self, s, name=None, dtype=None, broadcastable=None):
|
113 |
+
""" Get the cache key for a SymPy object.
|
114 |
+
|
115 |
+
Parameters
|
116 |
+
==========
|
117 |
+
|
118 |
+
s : sympy.core.basic.Basic
|
119 |
+
SymPy object to get key for.
|
120 |
+
|
121 |
+
name : str
|
122 |
+
Name of object, if it does not have a ``name`` attribute.
|
123 |
+
"""
|
124 |
+
|
125 |
+
if name is None:
|
126 |
+
name = s.name
|
127 |
+
|
128 |
+
return (name, type(s), s.args, dtype, broadcastable)
|
129 |
+
|
130 |
+
def _get_or_create(self, s, name=None, dtype=None, broadcastable=None):
|
131 |
+
"""
|
132 |
+
Get the Theano variable for a SymPy symbol from the cache, or create it
|
133 |
+
if it does not exist.
|
134 |
+
"""
|
135 |
+
|
136 |
+
# Defaults
|
137 |
+
if name is None:
|
138 |
+
name = s.name
|
139 |
+
if dtype is None:
|
140 |
+
dtype = 'floatX'
|
141 |
+
if broadcastable is None:
|
142 |
+
broadcastable = ()
|
143 |
+
|
144 |
+
key = self._get_key(s, name, dtype=dtype, broadcastable=broadcastable)
|
145 |
+
|
146 |
+
if key in self.cache:
|
147 |
+
return self.cache[key]
|
148 |
+
|
149 |
+
value = tt.tensor(name=name, dtype=dtype, broadcastable=broadcastable)
|
150 |
+
self.cache[key] = value
|
151 |
+
return value
|
152 |
+
|
153 |
+
def _print_Symbol(self, s, **kwargs):
|
154 |
+
dtype = kwargs.get('dtypes', {}).get(s)
|
155 |
+
bc = kwargs.get('broadcastables', {}).get(s)
|
156 |
+
return self._get_or_create(s, dtype=dtype, broadcastable=bc)
|
157 |
+
|
158 |
+
def _print_AppliedUndef(self, s, **kwargs):
|
159 |
+
name = str(type(s)) + '_' + str(s.args[0])
|
160 |
+
dtype = kwargs.get('dtypes', {}).get(s)
|
161 |
+
bc = kwargs.get('broadcastables', {}).get(s)
|
162 |
+
return self._get_or_create(s, name=name, dtype=dtype, broadcastable=bc)
|
163 |
+
|
164 |
+
def _print_Basic(self, expr, **kwargs):
|
165 |
+
op = mapping[type(expr)]
|
166 |
+
children = [self._print(arg, **kwargs) for arg in expr.args]
|
167 |
+
return op(*children)
|
168 |
+
|
169 |
+
def _print_Number(self, n, **kwargs):
|
170 |
+
# Integers already taken care of below, interpret as float
|
171 |
+
return float(n.evalf())
|
172 |
+
|
173 |
+
def _print_MatrixSymbol(self, X, **kwargs):
|
174 |
+
dtype = kwargs.get('dtypes', {}).get(X)
|
175 |
+
return self._get_or_create(X, dtype=dtype, broadcastable=(None, None))
|
176 |
+
|
177 |
+
def _print_DenseMatrix(self, X, **kwargs):
|
178 |
+
if not hasattr(tt, 'stacklists'):
|
179 |
+
raise NotImplementedError(
|
180 |
+
"Matrix translation not yet supported in this version of Theano")
|
181 |
+
|
182 |
+
return tt.stacklists([
|
183 |
+
[self._print(arg, **kwargs) for arg in L]
|
184 |
+
for L in X.tolist()
|
185 |
+
])
|
186 |
+
|
187 |
+
_print_ImmutableMatrix = _print_ImmutableDenseMatrix = _print_DenseMatrix
|
188 |
+
|
189 |
+
def _print_MatMul(self, expr, **kwargs):
|
190 |
+
children = [self._print(arg, **kwargs) for arg in expr.args]
|
191 |
+
result = children[0]
|
192 |
+
for child in children[1:]:
|
193 |
+
result = tt.dot(result, child)
|
194 |
+
return result
|
195 |
+
|
196 |
+
def _print_MatPow(self, expr, **kwargs):
|
197 |
+
children = [self._print(arg, **kwargs) for arg in expr.args]
|
198 |
+
result = 1
|
199 |
+
if isinstance(children[1], int) and children[1] > 0:
|
200 |
+
for i in range(children[1]):
|
201 |
+
result = tt.dot(result, children[0])
|
202 |
+
else:
|
203 |
+
raise NotImplementedError('''Only non-negative integer
|
204 |
+
powers of matrices can be handled by Theano at the moment''')
|
205 |
+
return result
|
206 |
+
|
207 |
+
def _print_MatrixSlice(self, expr, **kwargs):
|
208 |
+
parent = self._print(expr.parent, **kwargs)
|
209 |
+
rowslice = self._print(slice(*expr.rowslice), **kwargs)
|
210 |
+
colslice = self._print(slice(*expr.colslice), **kwargs)
|
211 |
+
return parent[rowslice, colslice]
|
212 |
+
|
213 |
+
def _print_BlockMatrix(self, expr, **kwargs):
|
214 |
+
nrows, ncols = expr.blocks.shape
|
215 |
+
blocks = [[self._print(expr.blocks[r, c], **kwargs)
|
216 |
+
for c in range(ncols)]
|
217 |
+
for r in range(nrows)]
|
218 |
+
return tt.join(0, *[tt.join(1, *row) for row in blocks])
|
219 |
+
|
220 |
+
|
221 |
+
def _print_slice(self, expr, **kwargs):
|
222 |
+
return slice(*[self._print(i, **kwargs)
|
223 |
+
if isinstance(i, sympy.Basic) else i
|
224 |
+
for i in (expr.start, expr.stop, expr.step)])
|
225 |
+
|
226 |
+
def _print_Pi(self, expr, **kwargs):
|
227 |
+
return 3.141592653589793
|
228 |
+
|
229 |
+
def _print_Exp1(self, expr, **kwargs):
|
230 |
+
return ts.exp(1)
|
231 |
+
|
232 |
+
def _print_Piecewise(self, expr, **kwargs):
|
233 |
+
import numpy as np
|
234 |
+
e, cond = expr.args[0].args # First condition and corresponding value
|
235 |
+
|
236 |
+
# Print conditional expression and value for first condition
|
237 |
+
p_cond = self._print(cond, **kwargs)
|
238 |
+
p_e = self._print(e, **kwargs)
|
239 |
+
|
240 |
+
# One condition only
|
241 |
+
if len(expr.args) == 1:
|
242 |
+
# Return value if condition else NaN
|
243 |
+
return tt.switch(p_cond, p_e, np.nan)
|
244 |
+
|
245 |
+
# Return value_1 if condition_1 else evaluate remaining conditions
|
246 |
+
p_remaining = self._print(sympy.Piecewise(*expr.args[1:]), **kwargs)
|
247 |
+
return tt.switch(p_cond, p_e, p_remaining)
|
248 |
+
|
249 |
+
def _print_Rational(self, expr, **kwargs):
|
250 |
+
return tt.true_div(self._print(expr.p, **kwargs),
|
251 |
+
self._print(expr.q, **kwargs))
|
252 |
+
|
253 |
+
def _print_Integer(self, expr, **kwargs):
|
254 |
+
return expr.p
|
255 |
+
|
256 |
+
def _print_factorial(self, expr, **kwargs):
|
257 |
+
return self._print(sympy.gamma(expr.args[0] + 1), **kwargs)
|
258 |
+
|
259 |
+
def _print_Derivative(self, deriv, **kwargs):
|
260 |
+
rv = self._print(deriv.expr, **kwargs)
|
261 |
+
for var in deriv.variables:
|
262 |
+
var = self._print(var, **kwargs)
|
263 |
+
rv = tt.Rop(rv, var, tt.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 Theano graph variable.
|
271 |
+
|
272 |
+
The ``dtypes`` and ``broadcastables`` arguments are used to specify the
|
273 |
+
data type, dimension, and broadcasting behavior of the Theano 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 |
+
``theano.tensor.Tensor``.
|
277 |
+
|
278 |
+
See the corresponding `documentation page`__ for more information on
|
279 |
+
broadcasting in Theano.
|
280 |
+
|
281 |
+
.. __: http://deeplearning.net/software/theano/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 Theano datatypes to use when creating
|
291 |
+
new Theano variables for those symbols. Corresponds to the ``dtype``
|
292 |
+
argument to ``theano.tensor.Tensor``. 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 ``theano.tensor.Tensor`` to use when creating Theano
|
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 |
+
theano.gof.graph.Variable
|
305 |
+
A variable corresponding to the expression's value in a Theano
|
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 theano_code(expr, cache=None, **kwargs):
|
321 |
+
"""
|
322 |
+
Convert a SymPy expression into a Theano graph variable.
|
323 |
+
|
324 |
+
.. deprecated:: 1.8
|
325 |
+
|
326 |
+
``sympy.printing.theanocode`` is deprecated. Theano has been renamed to
|
327 |
+
Aesara. Use ``sympy.printing.aesaracode`` instead. See
|
328 |
+
:ref:`theanocode-deprecated` for more information.
|
329 |
+
|
330 |
+
Parameters
|
331 |
+
==========
|
332 |
+
|
333 |
+
expr : sympy.core.expr.Expr
|
334 |
+
SymPy expression object to convert.
|
335 |
+
|
336 |
+
cache : dict
|
337 |
+
Cached Theano variables (see :class:`TheanoPrinter.cache
|
338 |
+
<TheanoPrinter>`). Defaults to the module-level global cache.
|
339 |
+
|
340 |
+
dtypes : dict
|
341 |
+
Passed to :meth:`.TheanoPrinter.doprint`.
|
342 |
+
|
343 |
+
broadcastables : dict
|
344 |
+
Passed to :meth:`.TheanoPrinter.doprint`.
|
345 |
+
|
346 |
+
Returns
|
347 |
+
=======
|
348 |
+
|
349 |
+
theano.gof.graph.Variable
|
350 |
+
A variable corresponding to the expression's value in a Theano symbolic
|
351 |
+
expression graph.
|
352 |
+
|
353 |
+
"""
|
354 |
+
sympy_deprecation_warning(
|
355 |
+
"""
|
356 |
+
sympy.printing.theanocode is deprecated. Theano has been renamed to
|
357 |
+
Aesara. Use sympy.printing.aesaracode instead.""",
|
358 |
+
deprecated_since_version="1.8",
|
359 |
+
active_deprecations_target='theanocode-deprecated')
|
360 |
+
|
361 |
+
if not theano:
|
362 |
+
raise ImportError("theano is required for theano_code")
|
363 |
+
|
364 |
+
if cache is None:
|
365 |
+
cache = global_cache
|
366 |
+
|
367 |
+
return TheanoPrinter(cache=cache, settings={}).doprint(expr, **kwargs)
|
368 |
+
|
369 |
+
|
370 |
+
def dim_handling(inputs, dim=None, dims=None, broadcastables=None):
|
371 |
+
r"""
|
372 |
+
Get value of ``broadcastables`` argument to :func:`.theano_code` from
|
373 |
+
keyword arguments to :func:`.theano_function`.
|
374 |
+
|
375 |
+
Included for backwards compatibility.
|
376 |
+
|
377 |
+
Parameters
|
378 |
+
==========
|
379 |
+
|
380 |
+
inputs
|
381 |
+
Sequence of input symbols.
|
382 |
+
|
383 |
+
dim : int
|
384 |
+
Common number of dimensions for all inputs. Overrides other arguments
|
385 |
+
if given.
|
386 |
+
|
387 |
+
dims : dict
|
388 |
+
Mapping from input symbols to number of dimensions. Overrides
|
389 |
+
``broadcastables`` argument if given.
|
390 |
+
|
391 |
+
broadcastables : dict
|
392 |
+
Explicit value of ``broadcastables`` argument to
|
393 |
+
:meth:`.TheanoPrinter.doprint`. If not None function will return this value unchanged.
|
394 |
+
|
395 |
+
Returns
|
396 |
+
=======
|
397 |
+
dict
|
398 |
+
Dictionary mapping elements of ``inputs`` to their "broadcastable"
|
399 |
+
values (tuple of ``bool``\ s).
|
400 |
+
"""
|
401 |
+
if dim is not None:
|
402 |
+
return {s: (False,) * dim for s in inputs}
|
403 |
+
|
404 |
+
if dims is not None:
|
405 |
+
maxdim = max(dims.values())
|
406 |
+
return {
|
407 |
+
s: (False,) * d + (True,) * (maxdim - d)
|
408 |
+
for s, d in dims.items()
|
409 |
+
}
|
410 |
+
|
411 |
+
if broadcastables is not None:
|
412 |
+
return broadcastables
|
413 |
+
|
414 |
+
return {}
|
415 |
+
|
416 |
+
|
417 |
+
@doctest_depends_on(modules=('theano',))
|
418 |
+
def theano_function(inputs, outputs, scalar=False, *,
|
419 |
+
dim=None, dims=None, broadcastables=None, **kwargs):
|
420 |
+
"""
|
421 |
+
Create a Theano function from SymPy expressions.
|
422 |
+
|
423 |
+
.. deprecated:: 1.8
|
424 |
+
|
425 |
+
``sympy.printing.theanocode`` is deprecated. Theano has been renamed to
|
426 |
+
Aesara. Use ``sympy.printing.aesaracode`` instead. See
|
427 |
+
:ref:`theanocode-deprecated` for more information.
|
428 |
+
|
429 |
+
The inputs and outputs are converted to Theano variables using
|
430 |
+
:func:`.theano_code` and then passed to ``theano.function``.
|
431 |
+
|
432 |
+
Parameters
|
433 |
+
==========
|
434 |
+
|
435 |
+
inputs
|
436 |
+
Sequence of symbols which constitute the inputs of the function.
|
437 |
+
|
438 |
+
outputs
|
439 |
+
Sequence of expressions which constitute the outputs(s) of the
|
440 |
+
function. The free symbols of each expression must be a subset of
|
441 |
+
``inputs``.
|
442 |
+
|
443 |
+
scalar : bool
|
444 |
+
Convert 0-dimensional arrays in output to scalars. This will return a
|
445 |
+
Python wrapper function around the Theano function object.
|
446 |
+
|
447 |
+
cache : dict
|
448 |
+
Cached Theano variables (see :class:`TheanoPrinter.cache
|
449 |
+
<TheanoPrinter>`). Defaults to the module-level global cache.
|
450 |
+
|
451 |
+
dtypes : dict
|
452 |
+
Passed to :meth:`.TheanoPrinter.doprint`.
|
453 |
+
|
454 |
+
broadcastables : dict
|
455 |
+
Passed to :meth:`.TheanoPrinter.doprint`.
|
456 |
+
|
457 |
+
dims : dict
|
458 |
+
Alternative to ``broadcastables`` argument. Mapping from elements of
|
459 |
+
``inputs`` to integers indicating the dimension of their associated
|
460 |
+
arrays/tensors. Overrides ``broadcastables`` argument if given.
|
461 |
+
|
462 |
+
dim : int
|
463 |
+
Another alternative to the ``broadcastables`` argument. Common number of
|
464 |
+
dimensions to use for all arrays/tensors.
|
465 |
+
``theano_function([x, y], [...], dim=2)`` is equivalent to using
|
466 |
+
``broadcastables={x: (False, False), y: (False, False)}``.
|
467 |
+
|
468 |
+
Returns
|
469 |
+
=======
|
470 |
+
callable
|
471 |
+
A callable object which takes values of ``inputs`` as positional
|
472 |
+
arguments and returns an output array for each of the expressions
|
473 |
+
in ``outputs``. If ``outputs`` is a single expression the function will
|
474 |
+
return a Numpy array, if it is a list of multiple expressions the
|
475 |
+
function will return a list of arrays. See description of the ``squeeze``
|
476 |
+
argument above for the behavior when a single output is passed in a list.
|
477 |
+
The returned object will either be an instance of
|
478 |
+
``theano.compile.function_module.Function`` or a Python wrapper
|
479 |
+
function around one. In both cases, the returned value will have a
|
480 |
+
``theano_function`` attribute which points to the return value of
|
481 |
+
``theano.function``.
|
482 |
+
|
483 |
+
Examples
|
484 |
+
========
|
485 |
+
|
486 |
+
>>> from sympy.abc import x, y, z
|
487 |
+
>>> from sympy.printing.theanocode import theano_function
|
488 |
+
|
489 |
+
A simple function with one input and one output:
|
490 |
+
|
491 |
+
>>> f1 = theano_function([x], [x**2 - 1], scalar=True)
|
492 |
+
>>> f1(3)
|
493 |
+
8.0
|
494 |
+
|
495 |
+
A function with multiple inputs and one output:
|
496 |
+
|
497 |
+
>>> f2 = theano_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True)
|
498 |
+
>>> f2(3, 4, 2)
|
499 |
+
5.0
|
500 |
+
|
501 |
+
A function with multiple inputs and multiple outputs:
|
502 |
+
|
503 |
+
>>> f3 = theano_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True)
|
504 |
+
>>> f3(2, 3)
|
505 |
+
[13.0, -5.0]
|
506 |
+
|
507 |
+
See also
|
508 |
+
========
|
509 |
+
|
510 |
+
dim_handling
|
511 |
+
|
512 |
+
"""
|
513 |
+
sympy_deprecation_warning(
|
514 |
+
"""
|
515 |
+
sympy.printing.theanocode is deprecated. Theano has been renamed to Aesara. Use sympy.printing.aesaracode instead""",
|
516 |
+
deprecated_since_version="1.8",
|
517 |
+
active_deprecations_target='theanocode-deprecated')
|
518 |
+
|
519 |
+
if not theano:
|
520 |
+
raise ImportError("theano is required for theano_function")
|
521 |
+
|
522 |
+
# Pop off non-theano keyword args
|
523 |
+
cache = kwargs.pop('cache', {})
|
524 |
+
dtypes = kwargs.pop('dtypes', {})
|
525 |
+
|
526 |
+
broadcastables = dim_handling(
|
527 |
+
inputs, dim=dim, dims=dims, broadcastables=broadcastables,
|
528 |
+
)
|
529 |
+
|
530 |
+
# Print inputs/outputs
|
531 |
+
code = partial(theano_code, cache=cache, dtypes=dtypes,
|
532 |
+
broadcastables=broadcastables)
|
533 |
+
tinputs = list(map(code, inputs))
|
534 |
+
toutputs = list(map(code, outputs))
|
535 |
+
|
536 |
+
#fix constant expressions as variables
|
537 |
+
toutputs = [output if isinstance(output, theano.Variable) else tt.as_tensor_variable(output) for output in toutputs]
|
538 |
+
|
539 |
+
if len(toutputs) == 1:
|
540 |
+
toutputs = toutputs[0]
|
541 |
+
|
542 |
+
# Compile theano func
|
543 |
+
func = theano.function(tinputs, toutputs, **kwargs)
|
544 |
+
|
545 |
+
is_0d = [len(o.variable.broadcastable) == 0 for o in func.outputs]
|
546 |
+
|
547 |
+
# No wrapper required
|
548 |
+
if not scalar or not any(is_0d):
|
549 |
+
func.theano_function = func
|
550 |
+
return func
|
551 |
+
|
552 |
+
# Create wrapper to convert 0-dimensional outputs to scalars
|
553 |
+
def wrapper(*args):
|
554 |
+
out = func(*args)
|
555 |
+
# out can be array(1.0) or [array(1.0), array(2.0)]
|
556 |
+
|
557 |
+
if is_sequence(out):
|
558 |
+
return [o[()] if is_0d[i] else o for i, o in enumerate(out)]
|
559 |
+
else:
|
560 |
+
return out[()]
|
561 |
+
|
562 |
+
wrapper.__wrapped__ = func
|
563 |
+
wrapper.__doc__ = func.__doc__
|
564 |
+
wrapper.theano_function = func
|
565 |
+
return wrapper
|
venv/lib/python3.10/site-packages/sympy/printing/tree.py
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
def pprint_nodes(subtrees):
|
2 |
+
"""
|
3 |
+
Prettyprints systems of nodes.
|
4 |
+
|
5 |
+
Examples
|
6 |
+
========
|
7 |
+
|
8 |
+
>>> from sympy.printing.tree import pprint_nodes
|
9 |
+
>>> print(pprint_nodes(["a", "b1\\nb2", "c"]))
|
10 |
+
+-a
|
11 |
+
+-b1
|
12 |
+
| b2
|
13 |
+
+-c
|
14 |
+
|
15 |
+
"""
|
16 |
+
def indent(s, type=1):
|
17 |
+
x = s.split("\n")
|
18 |
+
r = "+-%s\n" % x[0]
|
19 |
+
for a in x[1:]:
|
20 |
+
if a == "":
|
21 |
+
continue
|
22 |
+
if type == 1:
|
23 |
+
r += "| %s\n" % a
|
24 |
+
else:
|
25 |
+
r += " %s\n" % a
|
26 |
+
return r
|
27 |
+
if not subtrees:
|
28 |
+
return ""
|
29 |
+
f = ""
|
30 |
+
for a in subtrees[:-1]:
|
31 |
+
f += indent(a)
|
32 |
+
f += indent(subtrees[-1], 2)
|
33 |
+
return f
|
34 |
+
|
35 |
+
|
36 |
+
def print_node(node, assumptions=True):
|
37 |
+
"""
|
38 |
+
Returns information about the "node".
|
39 |
+
|
40 |
+
This includes class name, string representation and assumptions.
|
41 |
+
|
42 |
+
Parameters
|
43 |
+
==========
|
44 |
+
|
45 |
+
assumptions : bool, optional
|
46 |
+
See the ``assumptions`` keyword in ``tree``
|
47 |
+
"""
|
48 |
+
s = "%s: %s\n" % (node.__class__.__name__, str(node))
|
49 |
+
|
50 |
+
if assumptions:
|
51 |
+
d = node._assumptions
|
52 |
+
else:
|
53 |
+
d = None
|
54 |
+
|
55 |
+
if d:
|
56 |
+
for a in sorted(d):
|
57 |
+
v = d[a]
|
58 |
+
if v is None:
|
59 |
+
continue
|
60 |
+
s += "%s: %s\n" % (a, v)
|
61 |
+
|
62 |
+
return s
|
63 |
+
|
64 |
+
|
65 |
+
def tree(node, assumptions=True):
|
66 |
+
"""
|
67 |
+
Returns a tree representation of "node" as a string.
|
68 |
+
|
69 |
+
It uses print_node() together with pprint_nodes() on node.args recursively.
|
70 |
+
|
71 |
+
Parameters
|
72 |
+
==========
|
73 |
+
|
74 |
+
asssumptions : bool, optional
|
75 |
+
The flag to decide whether to print out all the assumption data
|
76 |
+
(such as ``is_integer`, ``is_real``) associated with the
|
77 |
+
expression or not.
|
78 |
+
|
79 |
+
Enabling the flag makes the result verbose, and the printed
|
80 |
+
result may not be determinisitic because of the randomness used
|
81 |
+
in backtracing the assumptions.
|
82 |
+
|
83 |
+
See Also
|
84 |
+
========
|
85 |
+
|
86 |
+
print_tree
|
87 |
+
|
88 |
+
"""
|
89 |
+
subtrees = []
|
90 |
+
for arg in node.args:
|
91 |
+
subtrees.append(tree(arg, assumptions=assumptions))
|
92 |
+
s = print_node(node, assumptions=assumptions) + pprint_nodes(subtrees)
|
93 |
+
return s
|
94 |
+
|
95 |
+
|
96 |
+
def print_tree(node, assumptions=True):
|
97 |
+
"""
|
98 |
+
Prints a tree representation of "node".
|
99 |
+
|
100 |
+
Parameters
|
101 |
+
==========
|
102 |
+
|
103 |
+
asssumptions : bool, optional
|
104 |
+
The flag to decide whether to print out all the assumption data
|
105 |
+
(such as ``is_integer`, ``is_real``) associated with the
|
106 |
+
expression or not.
|
107 |
+
|
108 |
+
Enabling the flag makes the result verbose, and the printed
|
109 |
+
result may not be determinisitic because of the randomness used
|
110 |
+
in backtracing the assumptions.
|
111 |
+
|
112 |
+
Examples
|
113 |
+
========
|
114 |
+
|
115 |
+
>>> from sympy.printing import print_tree
|
116 |
+
>>> from sympy import Symbol
|
117 |
+
>>> x = Symbol('x', odd=True)
|
118 |
+
>>> y = Symbol('y', even=True)
|
119 |
+
|
120 |
+
Printing with full assumptions information:
|
121 |
+
|
122 |
+
>>> print_tree(y**x)
|
123 |
+
Pow: y**x
|
124 |
+
+-Symbol: y
|
125 |
+
| algebraic: True
|
126 |
+
| commutative: True
|
127 |
+
| complex: True
|
128 |
+
| even: True
|
129 |
+
| extended_real: True
|
130 |
+
| finite: True
|
131 |
+
| hermitian: True
|
132 |
+
| imaginary: False
|
133 |
+
| infinite: False
|
134 |
+
| integer: True
|
135 |
+
| irrational: False
|
136 |
+
| noninteger: False
|
137 |
+
| odd: False
|
138 |
+
| rational: True
|
139 |
+
| real: True
|
140 |
+
| transcendental: False
|
141 |
+
+-Symbol: x
|
142 |
+
algebraic: True
|
143 |
+
commutative: True
|
144 |
+
complex: True
|
145 |
+
even: False
|
146 |
+
extended_nonzero: True
|
147 |
+
extended_real: True
|
148 |
+
finite: True
|
149 |
+
hermitian: True
|
150 |
+
imaginary: False
|
151 |
+
infinite: False
|
152 |
+
integer: True
|
153 |
+
irrational: False
|
154 |
+
noninteger: False
|
155 |
+
nonzero: True
|
156 |
+
odd: True
|
157 |
+
rational: True
|
158 |
+
real: True
|
159 |
+
transcendental: False
|
160 |
+
zero: False
|
161 |
+
|
162 |
+
Hiding the assumptions:
|
163 |
+
|
164 |
+
>>> print_tree(y**x, assumptions=False)
|
165 |
+
Pow: y**x
|
166 |
+
+-Symbol: y
|
167 |
+
+-Symbol: x
|
168 |
+
|
169 |
+
See Also
|
170 |
+
========
|
171 |
+
|
172 |
+
tree
|
173 |
+
|
174 |
+
"""
|
175 |
+
print(tree(node, assumptions=assumptions))
|
venv/lib/python3.10/site-packages/sympy/vector/__init__.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.vector.coordsysrect import CoordSys3D
|
2 |
+
from sympy.vector.vector import (Vector, VectorAdd, VectorMul,
|
3 |
+
BaseVector, VectorZero, Cross, Dot, cross, dot)
|
4 |
+
from sympy.vector.dyadic import (Dyadic, DyadicAdd, DyadicMul,
|
5 |
+
BaseDyadic, DyadicZero)
|
6 |
+
from sympy.vector.scalar import BaseScalar
|
7 |
+
from sympy.vector.deloperator import Del
|
8 |
+
from sympy.vector.functions import (express, matrix_to_vector,
|
9 |
+
laplacian, is_conservative,
|
10 |
+
is_solenoidal, scalar_potential,
|
11 |
+
directional_derivative,
|
12 |
+
scalar_potential_difference)
|
13 |
+
from sympy.vector.point import Point
|
14 |
+
from sympy.vector.orienters import (AxisOrienter, BodyOrienter,
|
15 |
+
SpaceOrienter, QuaternionOrienter)
|
16 |
+
from sympy.vector.operators import Gradient, Divergence, Curl, Laplacian, gradient, curl, divergence
|
17 |
+
from sympy.vector.implicitregion import ImplicitRegion
|
18 |
+
from sympy.vector.parametricregion import (ParametricRegion, parametric_region_list)
|
19 |
+
from sympy.vector.integrals import (ParametricIntegral, vector_integrate)
|
20 |
+
|
21 |
+
__all__ = [
|
22 |
+
'Vector', 'VectorAdd', 'VectorMul', 'BaseVector', 'VectorZero', 'Cross',
|
23 |
+
'Dot', 'cross', 'dot',
|
24 |
+
|
25 |
+
'Dyadic', 'DyadicAdd', 'DyadicMul', 'BaseDyadic', 'DyadicZero',
|
26 |
+
|
27 |
+
'BaseScalar',
|
28 |
+
|
29 |
+
'Del',
|
30 |
+
|
31 |
+
'CoordSys3D',
|
32 |
+
|
33 |
+
'express', 'matrix_to_vector', 'laplacian', 'is_conservative',
|
34 |
+
'is_solenoidal', 'scalar_potential', 'directional_derivative',
|
35 |
+
'scalar_potential_difference',
|
36 |
+
|
37 |
+
'Point',
|
38 |
+
|
39 |
+
'AxisOrienter', 'BodyOrienter', 'SpaceOrienter', 'QuaternionOrienter',
|
40 |
+
|
41 |
+
'Gradient', 'Divergence', 'Curl', 'Laplacian', 'gradient', 'curl',
|
42 |
+
'divergence',
|
43 |
+
|
44 |
+
'ParametricRegion', 'parametric_region_list', 'ImplicitRegion',
|
45 |
+
|
46 |
+
'ParametricIntegral', 'vector_integrate',
|
47 |
+
]
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.76 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/basisdependent.cpython-310.pyc
ADDED
Binary file (12.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/coordsysrect.cpython-310.pyc
ADDED
Binary file (31.4 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/deloperator.cpython-310.pyc
ADDED
Binary file (3.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/dyadic.cpython-310.pyc
ADDED
Binary file (8.98 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/functions.cpython-310.pyc
ADDED
Binary file (13.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/implicitregion.cpython-310.pyc
ADDED
Binary file (13 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/integrals.cpython-310.pyc
ADDED
Binary file (6.07 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/operators.cpython-310.pyc
ADDED
Binary file (9.76 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/orienters.cpython-310.pyc
ADDED
Binary file (12.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/parametricregion.cpython-310.pyc
ADDED
Binary file (6.39 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/point.cpython-310.pyc
ADDED
Binary file (4.12 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/scalar.cpython-310.pyc
ADDED
Binary file (2.36 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/vector/__pycache__/vector.cpython-310.pyc
ADDED
Binary file (18.1 kB). View file
|
|